text:
Q: React Context test component that contains both Context.Provider and Context.Consumer I am attempting to test a component that contains both the provider and consumer of React Context. See App.tsx below.
The provider is in a wrapper class that also handles state.
How do I mock the ConfigurationContextProvider wrapper class so that it can properly provide the loadedStatus value to the consumer for testing the various renders of App.tsx?
App.tsx:
    public render(): React.ReactNode {
    return (
      <ConfigurationContextProvider>
        <ConfigurationContext.Consumer>
          { ({
            loadedStatus,
          }): ReactElement => {
            switch( loadedStatus ){
              case ConfigStatus.GoodConfiguration:
                return ( this.renderApp());
              case ConfigStatus.NotLoaded:
                return ( this.renderUnloadedApp() );
              case ConfigStatus.BadConfiguration:
                return ( this.renderBadConfiguration() );
            }
          }}
        </ConfigurationContext.Consumer>
      </ConfigurationContextProvider>
    )}

ContextProvider.tsx:
    export const ConfigurationContext = React.createContext<ConfigurationState | undefined>(undefined);

    export enum ConfigStatus {
      NotLoaded,
      BadConfiguration,
      GoodConfiguration
    }

    export interface ConfigurationState{
      loadedStatus: ConfigStatus;
      baseUrl: URL;
    }

    export class ConfigurationContextProvider extends Component< {}, ConfigurationState> {

      constructor( props: {} ){
        super(props);
        this.state = {
          loadedStatus: ConfigStatus.NotLoaded,
          baseUrl: null
        }
      }

      async componentDidMount(): Promise<void> {
        await this.loadConfiguration();
      }

      setConfiguration(configuration: Response): void {
        const URL_KEY = 'BASE_URL';
        const URL_VALUE = configuration[URL_KEY];
        if (!Object.prototype.hasOwnProperty.call(configuration, URL_KEY))
        {
          this.setState({ loadedStatus: ConfigStatus.BadConfiguration });
          console.error(`Missing field in configs: ${ URL_KEY }`);
        }
        else {
          try{
            this.setState({
              loadedStatus: ConfigStatus.GoodConfiguration,
              baseUrl: new URL(URL_VALUE),
            });
          }
          catch {
            this.setState({ loadedStatus: ConfigStatus.BadConfiguration });
            console.error(`Bad URL in environment configs - ${ URL_KEY } : ${ URL_VALUE }`);
          }
        }
      }

      loadConfiguration(): Promise<void> {
        const configPromise: Promise<Response> = fetch('./env.json');
        return configPromise.then( (response) => response.json())
          .then( (config: Response) => this.setConfiguration(config));
      }

      render(): React.ReactNode {
        return (
          <ConfigurationContext.Provider value = { {
            ...this.state,
          } }>
            {this.props.children}
          </ConfigurationContext.Provider>
        )
      }
    }

A: Found easiest way was to spyOn loadConfig function of the ConfigurationContextProvider and set the responses as needed to setConfig. This way could test various outcomes and have full Context/State updating as needed.
jest.spyOn(
  ConfigurationContextProvider.prototype, 'loadConfiguration').mockImplementation(
    function(this: ConfigurationContextProvider) {
      this.setConfiguration( { BASE_URL: 'http://localhost:8080' });
      return Promise.resolve();
    }
);


text:
Q: Detecting palindromes So I'm working on a program that identifies palindromes (words that are the same forwards and backwards). To accomplish this I place the contents of a string into a queue and a stack one character at a time. I then have a for loop compare the entries of the stack with that of the queue to see if they match up. If each character matches than we have a palindrome. Any characters not matching results in the match flag going false and breaking the loop. The problem is that my for loop won't run. The program skips over it completely. In fact it tells me that my "match" variable is unused. Any help would be appreciated. Thanks for reading my post.
**
I apologize for my vagueness. Stack and Queue are classes of my own design. They take a String input, divide the String into characters (char type), creating a node for each character and connecting them. Stack is last in first out, Queue is first in first out. blank 1 and blank 2 are empty nodes that act as start markers within each.
public void palVerify(String s)
{
    boolean match=true;

    //creates stack
    Stack backward=new Stack(blank1);
    backward.push(s);

    //creates queue
    Queue forward=new Queue(blank2);
    forward.enqueue(s);

    // THIS LOOP WONT RUN

    for (int i=0; i < s.length(); i++)
    {
        if (backward.readTop()==forward.readFront())
        {

            backward.pop();
            forward.dequeue();
        }
        else
        {
            match=false;
            break;
        }

    }

    if (match=true)
        System.out.println("This word is a Palindrome");
    else
        System.out.println("This word is not a Palindrome");

}

A: You're never evaluating match in your code, only assigning to it. That's why you're getting the unused variable warning.
You likely want to evaluate match in the if statement on the bottom - replace with if(match=true) (which is assigning true to match variable) with if (match) (which evaluates the variable and branches based on its value).
On your for loop - it probably is running (you can add a System.out.println("Here"); to the beginning of it to prove it.  However, you're comparing Strings using == - String comparison should use the equals method.
I'm not sure what blank1 and blank2 are; I assume they're member or static variables declared outside your method.  I don't think your logic to do the detection of the palindrome (comparing backward.readTop and forward.readFront does what you think it does, unless you're using your own custom versions of Stack and Queue)

A: public class JustForShow {

    public boolean isPalindrome(String text){
        if(text == null || text.isEmpty())
            return false;

        char []arr = text.toCharArray();
        for (int i = 0,y = (arr.length - 1); i<y; i++,y--) {
            if(arr[i] != arr[y]){
                return false;
            }
        }
        return true;
    }

    public static void main(String[] args) {
        String palind = "ABCDDCBA";
        JustForShow jfs = new JustForShow();
        System.out.println(jfs.isPalindrome(palind));
    }
}

A: Here is a working solution :
public static void main(String[] args) {
    Scanner input = new Scanner(System.in);

    System.out.print("Enter a three-digit integer: ");
    int number = input.nextInt();

    if (number / 100 == number % 10)
       System.out.println(number + " is a palindrome");
    else
       System.out.println(number + " is not a palindrome");
 }

redpajama_set_name: RedPajamaStackExchange


text:
Q: Cannot get correct privileges using Samba on NFS mounted partition I have read/scanned for Samba/NFS problems and answers on the forum, which were quite interesting, many thanks for those :) Setting up NFS can be quite a pain in the ... but getting a warning before the problems arise is really a nice thing to have.
My problem:
I installed two PC's with Ubuntu/Kubuntu, both as server, but need some help getting things right. Ubuntu is working fine, on both machines (called P and N), and I installed Samba on machine P to make an easy interface with all the Windows machines in the office, and installed NFS client on the same machine P. The other machine N is setup with NFS server.
Everything is working fine, Windows shows the Samba user home directory, logs in fine on machine P, and the NFS mount is also visible, and when I use a linux shell to login on a linux account, I can see the NFS mounted directory, and I am able to write to it (create new files).
What is working:
  A Samba user can read files on the NFS mount, and can even rename files on it.
What is not working:
  A Samba user cannot create a new file.
I synchronized the GUID/UID on both machines as to not fall into the NFS users pitfall, so that cannot be the problem. At this moment I don't have that many users installed, so it's easy to keep track.
It might well be that my problem is version related: Machine P runs 12.04 Ubuntu, machine N runs 12.10 (Kubuntu). And I am using PuTTY to get a shell

A: You'll have to browse the internet for more details (as I am just passing by), but the issue is due to file locking--specifically opportunistic locking not playing well with NFS. You can tell Samba that the Linux kernel (or really NFS in this case) doesn't support opportunistic locking by adding the following to the smb.conf file:
kernel oplocks = no

There are drawbacks to this approach, but it's the quickest and easiest resolution I know of.
It's been a year since you asked the question, so I hope you haven't STILL been waiting for an answer but I hope that this ends up helping someone else!
Cheers,
polymathcoder


text:
Q: Select an element in DOM which is not a sibling, but goes after Let us suppose I have the following DOM

Now I would like to select the div with elementToSelect class but only if div with parent class has inside it an element with childNotSibling class. Is it possible to acomplish this using css?

A: This JSFiddle should do the trick:  https://jsfiddle.net/tremor/f4cghd5x/
Using JQuery here is the Javascript portion of the code.
// find all the occurrences of .childNotSibling
$("body").find(".childNotSibling").each(function(index, element) {
  // if .childNotSibling's parent has class "parent"
  if ($(this).parent().hasClass("parent")) {
    // and if the parent's next sibling has "elementToSelect"
    if ($(this).parent().next().hasClass("elementToSelect")) {
      // do something with that element
      $(this).parent().next().css("background-color", "red");
    }
  }
});


text:
Q: How to remove bluriness of fonts and 'lock in' effect when combining transform: scale with transition: transform? When combining transform:scale with transition:scale, the animation has two problems, and the problems are similar in Firefox and Chrome.
1) The font/border is extremely blurry during the transition
2) About 0.3s after the transition, the browser 'locks-in' the new scale. It is hard to explain but you will clearly see from the example.

123123

123123

123123

I've tried adding backface-visibility: hidden but this has no effect in Firefox and makes the end of the transition permanently blurred.
Also tried using transform-origin: 100% 0, but no avail.
Take a look at the Codepen:
https://codepen.io/vibonaaci/pen/LKqrPX
Any ideas? If you use the effect on some more stylized elements, the issue really hurts the eyes.


text:
Q: If $\tau ^{(n)}\downarrow \tau $ then $\{X_{\tau ^{(n)}}\}_{n\in \mathbb{N}}$ is uniformly integrable Reading in the book of Bhattacharya and Waymire of probability theory I find the following assertion:

Let $\{X_t\}_{t\in [0,T]}$ a right-continuous martingale adapted to a filtration $\{\mathcal F_t\}_{t\in [0,T]}$, for $T>0$ finite, and $\tau $ an stopping time. Let $P_n:=\{k2^{-n}T:k\in\{0,\ldots ,2^n\}\}$ and define $\tau ^{(n)}:=\min\{s\in P_n: s-\tau\geqslant 0 \}$, then $\{X_{\tau ^{(n)}}\}_{n\in \mathbb{N}}$ is uniformly integrable.

I cannot see why $\{X_{\tau ^{(n)}}\}_{n\in \mathbb{N}}$ is uniformly integrable, the "proof" in the book state that
$$
\begin{align*}
\operatorname{E}(\mathbf{1}_{[|X_{\tau ^{(n)}}|> \lambda ]}|X_{\tau ^{(n)}}|)&=\sum_{k=0}^{2^n-1}\operatorname{E}(\mathbf{1}_{[\tau ^{(n)}=(k+1)2^{-n}T]\cap [|X_{\tau ^{(n)}}|>\lambda ]}|X_{(k+1)2^{-n}T}|)\\
&\leqslant \sum_{k=0}^{2^n-1}\operatorname{E}(\mathbf{1}_{[\tau ^{(n)}=(k+1)2^{-n}T]\cap [|X_{\tau ^{(n)}}|>\lambda ]}|X_{T}|)\\
&=\operatorname{E}(\mathbf{1}_{[|X_{\tau ^{(n)}}|>\lambda ]}|X_{T}|)\to \operatorname{E}(\mathbf{1}_{[|X_{\tau}|>\lambda ]}|X_{T}|)\tag1
\end{align*}
$$
However, from the above I dont see any reason about why $\{X_{\tau ^{(n)}}\}_{n\in \mathbb{N}}$ must be uniformly integrable. To be uniformly integrable it must be the case that
$$
\lim_{\lambda \to +\infty }\sup_{n\in \mathbb{N}}\operatorname{E}(\mathbf{1}_{[|X_{\tau ^{(n)}}|> \lambda ]}|X_{\tau ^{(n)}}|)=0\tag2
$$
The problem is that the convergence $\mathbf{1}_{[|X_{\tau ^{(n)}}|>\lambda ]}\to \mathbf{1}_{[|X_{\tau}|>\lambda ]}$ a.s. is not monotone in any sense, as far as I can see, so its neither the convergence
$$
\operatorname{E}(\mathbf{1}_{[|X_{\tau ^{(n)}}|>\lambda ]}|X_{T}|)\to \operatorname{E}(\mathbf{1}_{[|X_{\tau}|>\lambda ]}|X_{T}|)\tag3
$$
So I cannot assert (2) from (1). Can someone enlighten me? Thank you.


text:
Q: IPrincipal should be ClaimsPrincipal but is WindowsPrincipal I've got a controller with 3 action methods on it, two of which are regular OData calls and a third which is a function. Using Azure AD and ADAL to secure the WebAPI.
CustomAuthAttribute (IsAppAuthorizing Simply checks a web.config entry)
public class OpsmApiAuthorizeAttribute : AuthorizeAttribute
{
    /// <summary>
    /// Returns whether or not the user has authenticated with ADFS and whehter ornot we are configured to do authorization
    /// </summary>
    /// <param name="actionContext"></param>
    /// <returns></returns>
    protected override bool IsAuthorized(System.Web.Http.Controllers.HttpActionContext actionContext)
    {
        if (HttpContext.Current.IsAppAuthorizing())
            return base.IsAuthorized(actionContext);

        return true;
    }
}

Startup.Auth.cs
    public void ConfigureAuth(IAppBuilder app)
    {
        app.UseWindowsAzureActiveDirectoryBearerAuthentication(
            new WindowsAzureActiveDirectoryBearerAuthenticationOptions
            {
                Tenant = ConfigurationManager.AppSettings["ida:Tenant"],
                TokenValidationParameters = new TokenValidationParameters
            {
                ValidAudience = ConfigurationManager.AppSettings["ida:Audience"],
            },
                MetadataAddress = ConfigurationManager.AppSettings["ida:MetadataEndpoint"],
            });
    }

Controller (ByUser is the OData function that does not get proper IPrincple information, other two methods work fine)
[OpsmApiAuthorizeAttribute]
public class ProjectsController : BaseController
{
    /// <summary>
    /// Get a Project Detail for a given project id
    /// </summary>
    /// <returns>json</returns>
    [EnableQuery]
    public IQueryable<OPSM.DataAccess.Database.OpsM.PRJ> Get([FromODataUri] string key)
    {
       ...
    }
    /// <summary>
    /// Get all Projects
    /// </summary>
    /// <returns>json</returns>
    [EnableQuery]
    public IQueryable<OPSM.DataAccess.Database.OpsM.PRJ> Get()
    {
        ...
    }

    [HttpGet]
    //[CacheOutput(ServerTimeSpan = 60 * 60)]
    public IHttpActionResult ByUser([FromODataUri]string userId)
    {
       ...
    }
}


text:
Q: getting the number of nodes in a binary search tree So I'm working on a method that gets the number of nodes in a binary search tree, when I have 3 nodes, it gives me 3, but if I do 5 it gives me 4, what do I need to change?
int BinaryTree::size(int count, Node *leaf) const
{
    if(leaf != NULL)//if we are not at a leaf
    {
        size(count + 1, leaf->getLeft());//recurisvly call the function and increment the count
        size(count + 1, leaf->getRight());
    }
    else
    {
        return count;//return the count
    }

}

A: int BinaryTree::size(Node *leaf) const
{
    if(leaf == NULL) { //This node doesn't exist. Therefore there are no nodes in this 'subtree'
        return 0;
    } else { //Add the size of the left and right trees, then add 1 (which is the current node)
        return size(leaf->getLeft()) + size(leaf->getRight()) + 1;
    }
}

While this is a different approach, I find that is it easier to read through than what you had.

A: Other people have already chimed in with a correct algorithm.  I'm just going to explain why your algorithm doesn't work.
The logic behind your algorithm seems to be: keep a running count value.  If the leaf is null then it has no children so return the count, if the leaf is not null then recurse down the children.
This is backwards though.  Because you're going to need to pass your int by reference, not value, and then not increment if it's null, increment if it's not null, and recurse.
So your original idea would work with some modifications, but Nick Mitchinson and arrows have a better way.  This is your algorithm fixed so it works:
int BinaryTree::size(Node *leaf, int& count=0) const
{
    if(leaf != NULL)//if we are not at a leaf
    {
        count++;
        size(leaf->getLeft(), count);//recurisvly call the function and increment the count
        size(leaf->getRight(), count);
    }

    return count;//return the count
}

But again, there are better ways to write this.  And the other answers show them.

A: int BinaryTree::size(Node *n) const
{
    if(!n)
        return 0;
    else
        return size(n->getLeft()) + 1 + size(n->getRight());
}


text:
Q: how to convert Dictionary to Dictionary using Colllection.ToDictionary() I am using Dapper to fetch a 2 column resultset into a dictionary.
I noticed that intellisense shows me a .ToDictionary() when I hover over the resultset but I cannot get it to work since dapper uses dynamic properties/expandoObject
Dictionary<string, string > rowsFromTableDict = new Dictionary<string, string>();
using (var connection = new SqlConnection(ConnectionString))
{
   connection.Open();
   var results =  connection.Query
                  ("SELECT col1 AS StudentID, col2 AS Studentname
                    FROM Student order by StudentID");
    if (results != null)
    {
    //how to eliminate below foreach using results.ToDictionary()
    //Note that this is results<dynamic, dynamic>
         foreach (var row in results)
         {
              rowsFromTableDict.Add(row.StudentID, row.StudentName);
         }
         return rowsFromTableDict;
     }
}

thank you

A: Try:
results.ToDictionary(row => (string)row.StudentID, row => (string)row.StudentName);

Once you have a dynamic object, every thing you do with it and the corresponding properties and methods are of the dynamic type.  You need to define an explicit cast to get it back into a type that is not dynamic.

A: if (results != null)
{
    return results.ToDictionary(x => x.StudentID, x => x.StudentName);
}


text:
Q: why do corona sdk's scene hide event not fired? and why timers are still printing stuff into the console even though i remove the scene? this is how I start the timers
local composer = require( "composer" )
local scene = composer.newScene()

timersArray = {}

function scene:create( event )

  function performTimedEvents(timeString)

  local function onTimer( event )
      local params = event.source.params
      if(arg == 5) then
        timer.cancel( event.source )
        return
      end
  end

  for i=1,10 do
      --print("performWithDelay "..sliceStars(timeString)[i])
      timersArray[i] = timer.performWithDelay( 1000*sliceStars(timeString)[i], onTimer )
      timersArray[i].params = { n = i }
  end

  end

  performTimedEvents(pagesTimers[currentPage])
end

this is how I cancel the timers (before leaving the scene) but they are still there when I leave the scene, the timers are still printing stuff into the console... notice this specific line timer.cancel(timersArray[j])
function flushTimers()
  pageSequence(5)
  print("QQQtimersArray")
  print_r(timersArray)
  for j=1,#timersArray do
    print("didCancelTimer "..j)
    timer.cancel(timersArray[j])
    --timer.pause(timersArray[j])
    timersArray[j] = nil
  end
  timersArray = {}
  print_r(timersArray)
  print("didReturn");
end

also why scene:hide is not being fired, it used to work at old times when we had storyboard with exit, but this hide callback is not getting called, please help :(
function scene:hide( event )

print("YYY_hide_!!!")

local sceneGroup = self.view
local phase = event.phase

if ( phase == "will" ) then
    print("YYY_hide_will")
    -- Called when the scene is on screen (but is about to go off screen)
    -- Insert code here to "pause" the scene
    -- Example: stop timers, stop animation, stop audio, etc.
elseif ( phase == "did" ) then
    print("YYY_hide_did")
    -- Called immediately after scene goes off screen
end
end

function scene:destroy( event )

local sceneGroup = self.view

-- Called prior to the removal of scene's view
-- Insert code here to clean up the scene
-- Example: remove display objects, save state, etc.

--myAudioPlayer = nil
--audio.stop()
--audio.rewind(1)
flushTimers()
--timersArray = nil

print("YYY_destroy_did")
end

scene:addEventListener( "create", scene )
scene:addEventListener( "show", scene )
scene:addEventListener( "hide", scene )
scene:addEventListener( "destroy", scene )

by the way, this is how I remove the current scene
      composer.removeScene("currentScene")
      composer.gotoScene("nextScene",effectOptions)

A: You should cancel your timers when the phase is did inside your scene:hide() event.
function scene:hide( event )

    print("YYY_hide_!!!")

    local sceneGroup = self.view
    local phase = event.phase

    if ( phase == "will" ) then
        print("YYY_hide_will")
        -- Called when the scene is on screen (but is about to go off screen)
        -- Insert code here to "pause" the scene
        -- Example: stop timers, stop animation, stop audio, etc.
    elseif ( phase == "did" ) then
        print("YYY_hide_did")
        -- Called immediately after scene goes off screen
        flushTimers()
        composer.removeScene("sceneName")
    end
end


text:
Q: fs.js module in nodejs requiring itself? I'm currently learning nodeJS and running version v6.10.2, I was taking a look at the fs.js module source code located in the graceful-js folder and noticed this code in it:
'use strict'

var fs = require('fs')

module.exports = clone(fs)

function clone (obj) {
  if (obj === null || typeof obj !== 'object')
    return obj

  if (obj instanceof Object)
    var copy = { __proto__: obj.__proto__ }
  else
    var copy = Object.create(null)

  Object.getOwnPropertyNames(obj).forEach(function (key) {
    Object.defineProperty(copy, key, Object.getOwnPropertyDescriptor(obj, key))
  })

  return copy
}

How can a module require itself does it have to do with the clone keyword? I couldn't find any other module named fs.js either.

A: You're looking at part of the code for the graceful-fs package which is a wrapper around the builtin fs module in NodeJS. So this code is not requiring itself - the require statement imports the builtin fs module and the rest of the code clones it so that other parts of the graceful-fs package can override some of the default fs functionality without affecting the original module.


text:
Q: How to make TXMLDocument (with the MSXML Implementation) always include the encoding attribute? I have legacy code (I didn't write it) that always included the encoding attribute, but recompiling it to D2010, TXMLDocument doesn't include the encoding anymore. Because the XML data have accented characters both on tags and data, TXMLDocument.LoadFromFile simply throws EDOMParseErros saying that an invalid character is found on the file. Relevant code:
   Doc := TXMLDocument.Create(nil);
   try
     Doc.Active := True;
     Doc.Encoding := XMLEncoding;
     RootNode := Doc.CreateElement('Test', '');
     Doc.DocumentElement := RootNode;
     <snip>
     //Result := Doc.XMl.Text;
     Doc.SaveToXML(Result);    // Both lines gives the same result

On older versions of Delphi, the following line is generated:
<?xml version="1.0" encoding="ISO-8859-1"?>

On D2010, this is generated:
<?xml version="1.0"?>

If I change manually the line, all works like always worked in the last years.
UPDATE: XMLEncoding is a constant and is defined as follow
  XMLEncoding = 'ISO-8859-1';

A: You'll want to see IXMLDocument.CreateProcessingStruction. I use OmniXML, but it's syntax is similar and should get you started:
var
  FDoc: IXMLDocument;
  PI:  IXMLProcessingInstruction;
begin
  FDoc := OmniXML.CreateXMLDoc();
  PI := FDoc.CreateProcessingInstruction('xml', 'version="1.0" encoding="UTF-8"');
  FDoc.AppendChild(PI);
end;

A: var
  XMLStream: TStringStream;
begin
   Doc := TXMLDocument.Create(nil);
   try
     Doc.Active := True;
     Doc.Encoding := XMLEncoding;
     RootNode := Doc.CreateElement('Test', '');
     Doc.DocumentElement := RootNode;
     <snip>
     XMLStream := TStringStream.Create;
     Doc.SaveToStream(XMLStream);
     Result := XmlStream.DataString;
     XMLStream.Free;

Since Ken's answer and the link to MSXML article, I decided to investigate the XML property and SaveToXML method. Both use the XML property of the MSXMLDOM implementation - which in the article is said that do not bring the encoding when directly read ( in the "Creating New XML Documents with MSXML" section right after the use of CreateProcessInstruction method).
UPDATE:
I found that accented characters are getting truncated in the resulting XML. When the processor of that XML started to throw strange errors, we saw that the chars are being converted to the numeric char constant ( #13 is the numeric char constant for carriage return). So, I used a TStringStream to get it FINALLY right.


text:
Q: Is there any serious MySQL naming styleguide? As you can saw in Table name show a syntax error in MySQL question you can define some particular tablename (attn-cse-a[3-1][mpms][10-8-2013]).
A comment suggest to use only alphanumeric chars as good tablename, but this is really a wise choice? What about of "-" and "_"?
Is there any serious styleguide to MySQL naming of tables, columns, index, etc.?
I say MySQL because of big differences between DB syntax rules of SQL servers, but of course can be a generic SQL naming styleguide!

A: The MySQL Reference Manual has a pretty good description of what is allowed:
http://dev.mysql.com/doc/refman/5.5/en/identifiers.html
Personally I use a subset of the allowable characters for unquoted identifiers, which the manual describes as follows:

*

*Permitted characters in unquoted identifiers:

*

*ASCII: [0-9,a-z,A-Z$_] (basic Latin letters, digits 0-9, dollar,    underscore)

*Extended: U+0080 .. U+FFFF

Restricting that list further, I would not use any of the following in table/column names or other identifiers:

*

*dollar sign ($)

*extended characters

*reserved words
So basically that leaves you with alphanumeric characters and underscores, but avoid reserved words.


text:
Q: How to debug izpack installer? I'm creating an IzPack installer and want to know how can I debug the installer or some actions using the most automatic tools, it includes generating a debug log with the installer actions and commands executed.

A: As explained in official documentation there exists some:
-DTRACE=true - allows you to check current state of conditions and variables values (in GUI mode)
-DSTACKTRACE=true - will output complete stacktrace of the exception that caused the installer failure
-DDEBUG=true - debug mode, most informative but kind of hard to read sometimes


text:
Q: How do you quickly descend a vertical surface while cleaning it? I watched a few high-level runs of some levels, and the players were able to seemingly cling to a wall, then run/fall down the wall very quickly while still cleaning the entire surface. I've found that if I just land on the wall, then falling takes quite a bit of time. If I dash downards, then I pass right by the surface without cleaning it. So I can either descend quickly or clean the surface.
How do I do both?
For example, shortly after 47 seconds in this video, the guy is able to slide quickly down the wall somehow. I'm not sure how he's managing to do this.

A: The trick in that video is pretty subtle. When they approach the wall, they do a downward dash in midair(ctrl+down) to give themselves a boost in downwards momentum. Then they hit the wall at the right spot to minimize the amount of sliding they need to do to clear the wall. This way, they increase the amount of downward momentum they have entering the slide, and decrease their download momentum only a small amount while holding on to the wall. As soon as the wall is clear, they hit back to let go of the wall, and repeat the trick with the other side.


text:
Q: Input text Field inside `` tag I am creating a dropdown with AngularJS.
here is the code..
<div class="col-md-9">
  <input type="text" placeholder="Enter Module" list="names"
         ng-model="data.Name" />
  <select id="names" class="form-control" ng-model="data.Name"
          ng-change="SetCategory(data.Name)" name="name">
    <option value='' disabled selected>------------- select an option ----------</option>
    <option ng-repeat="e in BrData | filter:data.Name "
            value="{{e.Name}}">{{e.Price}}</option>
  </select>
</div>

NOTE: List is Dynamic and i am using AngularJS to get data.
I need To create a searchbar inside select tag.
But Input tag can't nested in select tag.What should I do?

A: You can use typeahead from UI Bootstrap: https://angular-ui.github.io/bootstrap/#!#typeahead
Or if you need more advanced features along with search like multi-select, select all, deselect all, disable options, keyboard controls and much more try this: http://dotansimha.github.io/angularjs-dropdown-multiselect/docs/#/main

A: The way I see it, there are three options here.
Option One - Input outside the dropdown
Get the input outside the dropdown, and filter the values based on that value from the outside. I know that this is not your intended functionality exactly, but it would save you some trouble.
Option Two - Use some kind of third party dropdown library
As Mohd mentioned https://angular-ui.github.io/bootstrap/#!typeahead is a good fit and UI select too
Option three - Create something of your own
It need not even be using <select> tag. This is by far the most difficult, but also the most customizable and suitable for individual needs. The select tag will not be used as it does not support input inside of it, so some high end css will need to be used, as well as some backwards compatibility multiple browser testing that the already made libraries have already done.

A: Dealing with the <select> nightmare
From the Docs:

<select> Element Technical summary1

Permitted content: Zero or more <option> or <optgroup> elements.
Tag omission: None, both the starting and ending tag are mandatory.
Permitted parents: any element that accepts phrasing content

The short answer is that <input> elements can not be placed inside <select> elements.
<datalist> Element2
The datalist element is intended to provide a better mechanism for this concept.

<input type="text" name="example" list="exampleList">
<datalist id="exampleList">
  <option value="A">
  <option value="B">
</datalist>

For more information, see

*

*HTML combo box with option to type an entry

*MDN Learn HTML Forms - Dealing with the select nightmare

A: Use select2 as a dynamic option instead of HTML select option:
here  is link for select using js:
https://select2.org/tagging


text:
Q: Unit testing of method returning enum I am trying to create a test case of a method. Inside which another method is getting called which is returning an enum type.
How to expect and return for this method which is returning enum.
public class xyz {

    public request pqrs(Rest rest) {
        Confirm cnf= new Confirm();
        cnf.getAct().toString();
    }
}

public class Confirm {

    public Hgs getAct() {
        return act
    }
}

public enum Hgs{

}

How to expect and return for getAct()?

A: Returning an enum is like returning any other object. In your case, using EasyMock, it will look like:
Confirm confirm = mock(Confirm.class);
expect(confirm.getAct()).thenReturn(Hgs.VALUE);
replay(confirm);

However, the problem you will then have is that Confirm is create in the method, not injected. So using the mock is currently impossible. Two solutions there. The good one depends on your actual use-case.

*

*Inject Confirm

*Create it through some method that you can mock


text:
Q: How do I return an auth token to the google assistant using a website? I want to implement an Actions for Google app that links to user account in a Firebase project and query's their data. I have a website that is set up using Firebase UI that logs them in and redirects them to a dummy page that basically just says "You have been logged in." I cannot see any documentation anywhere that shows how to return this auth token to google so the assistant can use it to query things on their account. Does anybody know how to accomplish this? I am using this documentation https://developers.google.com/actions/identity/google-sign-in-oauth?creation=no. This is the specific text I am not understanding.
"Your service creates an access token and returns it to Google by redirecting the user's browser back to Google with the access token attached to the request."

A: This basically means that, instead of returning a new page, you issue an HTTP redirect to a URL that they have sent you as part of the request. You will need to add some parameters to this URL that include the auth info, and this is how Google will get the information - via the redirect handled by the user's browser.
They provide some details further down in step 4 on that page, which reads

Send an HTTP response that redirects the user's browser to the URL
  specified by the redirect_uri parameter. Include all of the following
  parameters in the URL fragment:
access_token: the access token you just generated
token_type: the string bearer
state: the unmodified state value from the original request
The following is an example of the resulting URL:
  https://oauth-redirect.googleusercontent.com/r/YOUR_PROJECT_ID#access_token=ACCESS_TOKEN&token_type=bearer&state=STATE_STRING


text:
Q: Query Amazon DynamoDB for specific result I am using the DynamoDB SDK v2 . I can scan the database however I am struggling to query it for a specific results. I don't know if I have the DB setup wrong or I am doing the query wrong.
When I use
- (void)getTableRow:(NSString *)rangeKey {
          AWSDynamoDBObjectMapper *dynamoDBObjectMapper = [AWSDynamoDBObjectMapper defaultDynamoDBObjectMapper];
            [[dynamoDBObjectMapper load:[SonicUserTableRow class]
                                hashKey:@"UserId"
                               rangeKey:rangeKey] continueWithExecutor:[BFExecutor mainThreadExecutor] withBlock:^id(BFTask *task) {
                if (!task.error) {

                   SonicUserTableRow *tableRow = task.result;

                   NSLog (@"Table Row %@", tableRow);

            } else {
               //Catch Error

            }
            return nil;
        }];
}

I am calling it using [self getTableRow:@" ENTER UNIQUE USER ID "];
However I am getting the error
The provided key element does not match the schema

How can I fix this?
Note I am using the new Amazon SDK v2.
My Database

HASH & RANGE KEYS

SonicUserTableRow .m
+ (NSString *)dynamoDBTableName {
    return @"SonicUsers";
}

+ (NSString *)hashKeyAttribute {
    return @"UserId";
}

+ (NSString *)rangeKeyAttribute {
    return @"Username";
}

SonicUserTableRow .h
@interface SonicUserTableRow : AWSDynamoDBModel <AWSDynamoDBModeling>

@property (nonatomic, strong) NSString *UserId;
@property (nonatomic, strong) NSString *Username;
@property (nonatomic, strong) NSString *profileImage;
@property (nonatomic, strong) NSString *active;
@property (nonatomic, strong) NSString *email;
@property (nonatomic, strong) NSString *flags;
@property (nonatomic, strong) NSString *attuned;

I have UserId value UserIdString:  us-east-1:4ae0a93a-59a6-45fd-80c8-ff6b99f1d152 in the database so am trying to call for example: [self getTableRow:@"us-east-1:4ae0a93a-59a6-45fd-80c8-ff6b99f1d152"];

A: If DropId is a hash key of your table, you can use - load:hashKey:rangeKey: to load a single item.


text:
Q: What's the pattern to request for all records using RESTful app? I would like to know what's the best approach for my RESTful app when requesting all records.
For example, I limit my responses to 10 if no $top value is provided to avoid overload. However, how can I format my request? Which is better, $top=allrows or $top=all? Is there any pattern I should check for?
If $top value is not provided I only return up to 10 rows.
GET /products?$top=

I just want to avoid this:
GET /products/all

A: There's no official pattern and any choice would depend on the size of your data.
Whatever you do, always put a maximum limit to the number of items you'll return regardless of parameters the client provides in the request.
Also, create a default count to return when no information is provided by parameters.
If you don't have tons of items to return, you count set your default count to be max limit and that be enough to always return all and you could just make the url without any details on specific counts return all.
GET /products   (no count/provided)

If you have hundreds or thousands and you have a default count of say 100, maybe use something a explicit count to extend that limit (up to the max of course--if asking for count > max, return a 400 bad request with message indicating count can't be higher than max)
 GET /products?count=1000000

However, this could be horrible for your server(s) and/or the client if you keep pushing the max limit higher and higher.
Typically, if you've a lot of records, you chunk it up and use a count and offset to pull it down in byte-sized chunks.  Also add meta data to the response object letting the requester know the current position, total records, and offset supplied
A little pseudo-code:
$count = 1000
$offset = 0
While count*offset < total records:
    GET /products?count=$count&offset=$offset
    $offset = $offset + $count

Assuming one of the requests looks like:
 GET /products?count=1000&offset=1000

Then in the response body you'd expect something like:
{
   "result": [
         {
           "id": "123",
           "name": "some product",
           "link": "/product/123"
         },

         ... many more products ...

         {
           "id": "465",
           "name": "another product",
           "link": "/product/465"
          }

    ],
    "meta": {
         "count": 1000,
         "offset": 1000,
         "total_count": 3000,
         "next_link": "/products?count=1000&offset=2000",
         "prev_link": "/products?count=1000&offset=0",

     },

     "status": 200
}

If you really want gold star you can make your resources adhere to HATEOS ( https://en.wikipedia.org/wiki/HATEOAS ) and include links to the individual resources in the list and maybe in the meta have links to the next and prior chunks of the list if you're walking a large list of items.  I've put some example links in the json sample above.

A: I would do it like that:
For all products GET /products
For certain product GET /products/{id}
For all products with filtering or sorting,
use GET /products but let the client send you Filter object in request body.
There it can specify if he wants certain page in pagination, or filter some records etc.
Filter Object could look like:
{"pageNumber":1,"pageSize":12,"freeText":"","conditions":[],"sortings":{}}
In your service map it to inner service filter and return the requested records.


text:
Q: Where do you get fur? A lot of people have been telling me to sell fur to get quick money.
I have been looking everywhere to get fur..... but couldn't find any.
Where do you get it?

A: Fur is called Pelt in game.
You get pelt by hunting and skinning animals in the Frontier. Different animals can be found in the hunting ground of the Frontier, each one giving a few different parts when skinned, that can be sold to merchants for money.
There are different way to hunt animals, either you can place loop snare and wait for an animal to be trapped, you can track them and kill them however you want (note that killing with your hands or bow provides you better quality fur), or you can be attacked by a pack of animals, you should then skin them after killing them.
As you advance in the game eventually you'll be able to buy pelts of several different animals in your homestead.


text:
Q: printf style formatting without outputting What I'm trying to do is make a new char* using a syntax similar to printf:
char* myNewString = XXXXprintf("My string says %s", myFirstString);

Is this doable without printing to an output stream?

A: You're looking for the sprintf or snprintf function.
Note that sprintf doesn't return a pointer to a newly allocated string; you have to allocate the string yourself, and make sure it's big enough:
char target[100];
sprintf(target, "My string says %s", myFirstString);

Unless you can be certain that the target is big enough, you should use snprintf, which limits the number of bytes copied to the target string.
snprintf returns the number of characters that would have been written to the target string. You can call snprintf with a null target and zero size to find out how many big a buffer is needed, then allocate the buffer and call it again to write to the target (NOTE: My original code sample had an off-by-one error.)
#include <stdio.h>
#include <stdlib.h>

int main(void) {
    const char *myFirstString = "hello, world";
    char *target;
    size_t size = snprintf(NULL, 0, "My string says %s", myFirstString);
    target = malloc(size+1); /* +1 for terminating '\0' */
    if (target == NULL) {
        fprintf(stderr, "Allocation failed\n");
        exit(EXIT_FAILURE);
    }
    size = snprintf(target, size+1, "My string says %s", myFirstString);
    printf("target = \"%s\"\n", target);
    return 0;
}

Note that snprintf was added to C by the 1999 ISO standard. Microsoft's compiler doesn't appear to support it; it does provide a function it calls _snprintf which probably does the same thing.
There's also a GNU extension called asprintf which does allocate the string for you:
char *target;
asprintf(&target, "My string says %s", myFirstString);

If you use this, you'll have to use free() later to deallocate the string.  And since this is a GNU extension, it will make your code less portable.

A: Sure, this is what sprintf is for: printf style formatting into a provided char*.
This documentation covers sprintf and related printf functions. Be sure to consider using snprintf instead: proper usage will make it a bit safer than sprintf by limiting the number of bytes actually copied to the supplied buffer.
The usage is a little different from your example: you supply a buffer which is modified by the sprintf. The function doesn't return the result, like other printf functions, return an int: the number of characters printed.
char myNewString[MAX_LEN];
snprintf(myNewString, MAX_LEN, "My string says %s", myFirstString);

A: The function you're looking for is sprintf.
http://www.manpages.info/linux/sprintf.3.html

A: If you don't mind GNUisms, asprintf may be the closest thing to what you're after: it automatically allocates a buffer for you (but you do have to remember to free it afterwards).
char *target;
int ret = asprintf(&target, "My string says %s", myFirstString);
// if ret < 0, the contents of target are undefined

A: I recommend snprintf, it is safer than sprintf.

A: sprintf should do that for you.
The only difference from printf is that the first parameter is a char* in which to store the string, i.e.
sprintf(myNewString, "My string says %s", myFirstString);


text:
Q: How to convert nested comma separated column inside a pandas data frame to specific format in Python I have data frame (df) as shown below
Input
Df

ID  linkedShipments
12      [{'SID': 'GBDXY551', 'Code': 'GBDXY55', 'Num': '2021121'}, {'SID': 'GBDXY551', 'Code': 'GBDXY55', 'Num': '20211215'}]
32      [{'SID': 'CHSGI422', 'Code': 'CHSGI421', 'Num': '4024421'}, {'SID': 'GBDXY551', 'Code': 'GBDXY55', 'Num': '20211222'}]

Expected Output
ID  SID         Code     Num
12  GBDXY551    GBDXY55  2021121
12  GBDXY551    GBDXY55  20211215
32  CHSGI422    CHSGI421 4024421
32  GBDXY551    GBDXY55  20211222

How can this be done in pandas?

A: The easiest way is:

*

*json.loads each row of linkedShipments

*traversal all element in linkedShipments

*combine ID and each element of linkedShipments as row dict

*append to new data

And the python code is below
import pandas as pd
import json

#The simulation of data
data = {"ID": [12, 24],
    "linkedShipments": ["[{'SID': 'GBDXY551', 'Code': 'GBDXY55', 'Num': '2021121'}, {'SID': 'GBDXY551', 'Code': 'GBDXY55', 'Num': '20211215'}]",
    "[{'SID': 'CHSGI422', 'Code': 'CHSGI421', 'Num': '4024421'}, {'SID': 'GBDXY551', 'Code': 'GBDXY55', 'Num': '20211222'}]"]
   }
#load as dataframe
df = pd.DataFrame(data)

new_data = {} #define new data
#treverse all rows in current data
for index, row in df.iterrows():
    #json only accept double quotes, so convert singal quotes to double quotes
    shipment_dict_list = json.loads(row['linkedShipments'].replace("\'", "\""))
    for shipment_dict in shipment_dict_list:
        new_data.setdefault("ID",[]).append(row['ID'])
        for key in shipment_dict:
            new_data.setdefault(key,[]).append(shipment_dict[key])
print(pd.DataFrame(new_data))

Here is the result:
   ID       SID      Code       Num
0  12  GBDXY551   GBDXY55   2021121
1  12  GBDXY551   GBDXY55  20211215
2  24  CHSGI422  CHSGI421   4024421
3  24  GBDXY551   GBDXY55  20211222


text:
Q: Is there a command to print the steps a function is using in Python? I'm working on doolittle decomposition. My function is fine(no errors), but i'm not receiving the right results. I'm sure everything is fine in the function with the exception of 2-4 variables that I might be misplacing. So my doubt here is if there is a function or a command to print all the calculations this function is using, step by step, so I can understand what is going wrong.
I'm using Python 3.6.2, Geany, Windows 10.
Here's the code:
def doolittle(A):
n = len(A)
b = 0
c = 0
L = [[0.0] * n for s in range(n)]
U = [[0.0] * n for s in range(n)]
for k in range(n):
    L[k][k] = 1.0
    for j in range(n):
        b += L[k][j] * U[j][k]
        U[k][j] = A[k][j] - b
    for i in range(k+1,n):
        c += L[k][i] * U[i][k]
        L[k][j] = (A[k][j] - c)/U[k][k]
return(L,U)

A = [[1, -3, 2], [-2,8,-1], [4, -6, 5]]
print(doolittle(A))

A: import ipdb
ipdb.set_trace()

Try using this where u want to enter the function.


text:
Q: My next and prev button for the list isn't working The problem: I am not able to get the value of the HTML list from javascript. Each time user click next button, the program will count how many times the user clicks the next button. In javascript, I called the HTML list and iterate it. inside for loop, I called user click on next button number and add 1, The result of the sum will go inside the array and display that array line data. I don't know because of some reason I can't able to get data. Let me know if you get confused
Here is the HTML code

 Google

Facebook

 Google

    <textarea id="File_Name" name="File_Name"></textarea>

    <button id="clickme" onclick="Next()"> Next </button>
    <button onclick="Prev()"> Prev </button>

Here is the JavaScript code

here is the CSS code

A: You are declaring count to 0 at the beginning of the function. So every time the button is clicked count equals 0 and then one is added. (It will always be 1) You need to pull the count var outside of the function. This will also be useful for your Prev function. I bet that your Next and prev functions will be similar enough to make only one function. Call your function with true or false to add or subtract the count.

A: Just Add this

in your head tag before the external script tag
beacuse you are using ajax you need jquery


text:
Q: Edit message contents in OneSignal notification Android I am trying to change the current 'Test Message' String in a OneSignal push notification. I simply want to use a variable defined in my code, but cannot figure out how to do it.
try {
    OneSignal.postNotification(new JSONObject("{'contents': ['en': 'Test Message'], 'include_player_ids': ['" + selectedUser.getOneSignalId() + "']}"),
    new OneSignal.PostNotificationResponseHandler() {
        @Override
        public void onSuccess(JSONObject response) {
            Log.i("OneSignalExample", "postNotification Success: " + response.toString());
        }

        @Override
        public void onFailure(JSONObject response) {
            Log.e("OneSignalExample", "postNotification Failure: " + response.toString());
        }
    });
} catch (JSONException f) {
    e.printStackTrace();
}

I was able to achieve something similar in sending the notification to a selected user. Now I just want to change the text of the actual message.

A:
Use this

String yourVaribale = " what ever you want to send"

OneSignal.postNotification(new JSONObject("{'contents': ['en': " +  yourVariable + "], 'include_player_ids': ['" + selectedUser.getOneSignalId() + "']}"),
                                                            new OneSignal.PostNotificationResponseHandler() {
                                                                @Override
                                                                public void onSuccess(JSONObject response) {
                                                                    Log.i("OneSignalExample", "postNotification Success: " + response.toString());
                                                                }

                                                                @Override
                                                                public void onFailure(JSONObject response) {
                                                                    Log.e("OneSignalExample", "postNotification Failure: " + response.toString());
                                                                }
                                                            });
                                                } catch (JSONException f) {
                                                    e.printStackTrace();
                                                }

or you can try this way

String strJsonBody = "{"
                                                       +   "     \"app_id\": \"ef42157d-64e7-4ce2-9ab7-15db224f441b\","
                                                       +   "     \"included_segments\": [\"All\"],"
                                                       +   "     \"data\": {\"foo\": \"bar\"},"
                                                       +   "     \"contents\": {\"en\": \""+ description +"\"},"
                                                       +   "     \"headings\": {\"en\": \""+ title +"\"},"
                                                       +   "     \"big_picture\":\""+ imageurl +"\""

                                   + "}";

for second method follow this link

A: The solution below worked for me. The full name of the current user is concatenated to the string message " wants you to follow them." and is then sent to the selectedUser with the specific OneSignalID.
    OneSignal.postNotification(new JSONObject("{'contents': {'en': \""+ currentUser.getFullName() +" wants you to follow them." +"\"}, 'include_player_ids': ['" + selectedUser.getOneSignalId() + "']}"),
                new OneSignal.PostNotificationResponseHandler() {
                    @Override
                    public void onSuccess(JSONObject response) {
                        Log.i("OneSignalExample", "postNotification Success: " + response.toString());
                    }

                    @Override
                    public void onFailure(JSONObject response) {
                        Log.e("OneSignalExample", "postNotification Failure: " + response.toString());
                    }
                });


text:
Q: Calculate random variables from grouped dataframe I have a data frame called stats. I'd like to group by month_name and item and generate a random variable drawn from a normal distribution in a new column called rv.
This is the code I tried but it repeats the generation of 1 random variable in the rv column:
stats %>%
  group_by(month_name, item) %>%
  mutate(rv = rnorm(1, mean = mean, sd = sd))

The goal is to eventually replicate the rv output 10,000 times. How can I modify my code to generate the random variable for every row once and 10,000 times?
This is my data:
structure(list(month_name = structure(c(1L, 1L, 1L, 1L, 1L, 2L,
2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L, 4L, 5L, 5L,
5L, 5L, 5L, 6L, 6L, 6L, 6L, 6L, 7L, 7L, 7L, 7L, 7L, 8L, 8L, 8L,
8L, 8L, 9L, 9L, 9L, 9L, 9L, 10L, 10L, 10L, 10L, 10L, 11L, 11L,
11L, 11L, 11L, 12L, 12L, 12L, 12L, 12L), .Label = c("January",
"February", "March", "April", "May", "June", "July", "August",
"September", "October", "November", "December"), class = c("ordered",
"factor")), item = structure(c(1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L,
4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L,
5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L,
1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L,
2L, 3L, 4L, 5L), .Label = c("a", "b", "e", "d", "c"), class = "factor"),
    min = c(39853.3676768762, 11963.7336771844, 28475.0829411315,
    36241.9007031999, 35743.7750504859, 16092.552892924, 12528.9369640133,
    28363.8516762228, 29557.1911907891, 20577.9268503088, 26012.6643332399,
    43743.1386573406, 33757.0104608081, 24012.3644652027, 29987.8232384625,
    26663.1671529956, 50724.1357441692, 33156.7203254077, 36604.0975795671,
    32448.5497811945, 47818.2983698804, 25173.5205474241, 29648.7882981325,
    39034.0329768052, 15083.5548610647, 41560.8896893507, 40563.2944650284,
    48794.4526055819, 35895.1783353774, 30085.4271923688, 39675.7305889162,
    33628.9557047603, 36950.5993766457, 30593.5091646214, 28957.5398056329,
    37080.7178800747, 45454.3924797489, 28755.6280571895, 34733.1340290652,
    37227.9361452194, 21493.809533368, 33292.9944106622, 28137.6372068055,
    25582.8046285949, 23073.0637573296, 28846.9082264882, 19454.182866794,
    33869.2858697563, 19016.7538627489, 30647.6876387916, 35123.8965500988,
    34146.2780735908, 40593.6508043686, 26908.3734089905, 47178.2458120079,
    24665.5899193578, 22701.4906439165, 50735.1331088719, 36108.7624278488,
    21415.5715318508), lower = c(54524.7101912146, 26928.6804993352,
    25119.8847919585, 45942.5372327181, 52100.762800828, 23399.2712234262,
    14178.7907654734, 71366.6268933559, 49209.2124037853, 54643.7588467776,
    48369.7944054794, 29515.3335011807, 41577.635577101, 25357.3837384686,
    43253.4733925982, 43401.4748829102, 37741.3586860236, 52294.4029786582,
    58136.6122795486, 43617.5523486807, 46648.1777348884, 47822.6060157009,
    37122.0182632065, 65447.4620274838, 29544.1919272749, 54822.3562275875,
    64814.4174753617, 65538.2587526896, 39975.4034746898, 59117.6049731313,
    49024.4324422717, 25273.7368374795, 56946.7596272533, 50660.5745923196,
    37221.8185672126, 30508.2772838287, 47172.6674212663, 52956.1465111511,
    45488.8349086128, 52660.1832157037, 37406.8854102724, 25601.012749268,
    41414.610113642, 41145.7009104373, 26879.9690641376, 69323.7347440924,
    59453.3099916568, 19260.9187209561, 14090.2250971317, 41778.9038974128,
    35013.9160392596, 39672.0871995261, 57517.2881078087, 52765.3573599843,
    57267.2271717807, 54869.720268229, 58525.9231470629, 44610.285805162,
    47317.3995094377, 17599.590085043), mean = c(58549.8098049081,
    56374.4327553941, 39864.1715264267, 85333.1530921059, 64454.2358008729,
    63343.4098283811, 69838.6859070403, 41935.3881398536, 40239.4399412696,
    70073.2291007902, 57535.295477502, 76197.4454180647, 60836.2074195693,
    64601.7379215889, 51599.3556004457, 49092.0124309883, 47319.767991988,
    63121.0872241636, 43048.0322965586, 77405.4987695189, 64320.8901918307,
    53059.7915920758, 63712.4934804165, 37248.933469329, 48285.12302248,
    60352.1030623367, 67648.010113929, 52282.8579266665, 63868.4373429784,
    71370.1455147326, 59275.2217698193, 74524.7831867724, 62464.1935824186,
    50255.8945012446, 31094.1686136834, 75833.6439248775, 32190.7391406323,
    77010.5148506178, 69635.0888164364, 65885.8987213858, 54022.7135642953,
    35801.3865465657, 60637.9983665307, 90783.7721781328, 57264.0603250172,
    59977.2976696403, 71712.656969139, 76705.4011709067, 89462.5059367925,
    76714.0458753254, 56859.5782454854, 66820.0053236744, 58243.7435076688,
    52843.8704599132, 77247.3384533588, 55515.7748808548, 75004.3165800858,
    88370.1869726297, 68628.9281194796, 53895.0496305422), median = c(42352.1610450345,
    57330.3183802072, 55273.2047201131, 82351.3852530883, 46370.4898234873,
    52386.0432388715, 47943.0683307536, 53897.781347776, 67858.0064600009,
    73013.024717384, 83116.7356352266, 44401.5903576421, 69025.6068023045,
    81625.3403276092, 43344.4404418446, 49701.9746204065, 44889.5603216509,
    86449.7649043697, 52150.9769065634, 58675.8138647348, 55665.7047792249,
    44566.4888204713, 50517.7492643733, 73778.9515308994, 60652.1631558926,
    87345.0069311662, 68268.9807235179, 41356.3226356087, 41585.1763113502,
    75144.8373297139, 81967.7788670882, 66041.6207332688, 55103.8870449834,
    77301.4195253735, 54130.4774678618, 65176.7990367632, 46834.9652749994,
    65134.3889325556, 76621.5018669346, 89066.7483257445, 79344.8597627239,
    50867.4889878177, 51326.3717332736, 74843.6262595514, 66235.6184875188,
    98300.5112442494, 51378.9240605971, 61277.8214283028, 48915.1245226839,
    52765.9194941648, 47028.8412992194, 74841.2039136489, 70896.5761749783,
    67414.0877191645, 60655.1682545525, 42707.2850070942, 51244.6187187212,
    70889.9732948709, 82834.1260629236, 56029.4540887989), upper = c(96808.9361470916,
    72722.9262056796, 89079.513341868, 84709.1878768955, 87694.368834914,
    87860.8548839792, 80996.3827453218, 84247.9259137302, 95585.6388675179,
    57338.746606262, 88681.3926853573, 87957.989278465, 87360.6574510974,
    92664.4254709955, 73493.0826366849, 84230.5990186054, 81442.2517006442,
    87801.9592453634, 107883.319372054, 101919.939543795, 78090.4252899963,
    70239.1417329303, 100675.767786787, 99806.9236049608, 71452.5071326737,
    73879.3479602876, 106131.22309752, 125238.035074805, 76731.6350473027,
    105563.285669622, 98604.105083167, 88657.8428176833, 81133.2031578456,
    92495.2957986084, 104836.803460225, 102419.6178137, 86160.3548401189,
    87287.9179449312, 72987.3973022452, 73185.0732579627, 90916.179982239,
    111282.33982277, 142168.512194455, 100479.774695548, 118375.00968986,
    116099.107730658, 105747.461541425, 106715.198136428, 128585.197217447,
    87996.5319472346, 67831.1501517932, 109713.080164634, 78535.3157822644,
    128602.704986898, 82213.8086826659, 118591.773718681, 66518.2467960131,
    91250.5061727746, 117072.914540123, 114524.034290364), max = c(137612.711045413,
    142519.370905613, 137456.124250483, 149209.014602568, 158745.717583772,
    144886.189765236, 168837.723206789, 148308.890270968, 158590.65413993,
    152288.303209753, 154042.306686713, 143922.848061827, 147477.579594905,
    147438.066965268, 141502.628117831, 150285.096748915, 148713.594899874,
    156656.255445038, 151517.357942321, 146177.731181398, 130056.291991729,
    150991.849546995, 150476.190905448, 140149.802748207, 162573.574139209,
    124218.878401843, 140313.610415297, 156852.359228369, 147676.550419975,
    139922.178103581, 131822.195549853, 143008.968758112, 142237.425864494,
    148756.818388612, 123905.560034301, 157126.60664862, 132868.19652461,
    137884.902850549, 142164.212835827, 144616.429331364, 154277.663061656,
    156870.781144851, 170948.478868233, 154970.297432983, 144661.430142095,
    151193.528913062, 136056.623739965, 132695.069145067, 144366.408646971,
    154456.483407293, 143518.023088591, 145811.265404348, 139900.024678788,
    127547.709882734, 149995.24047052, 145400.958382574, 159524.480570906,
    118905.663549293, 161631.72583606, 147524.546274058), sd = c(9989.37951375166,
    9906.50689980405, 9903.6852849217, 10008.3321579478, 10075.4653993515,
    10063.7122293343, 10053.0016932606, 9826.1129055558, 9855.88655389009,
    10028.7176055065, 10070.3833732403, 9941.07465801432, 10094.2667749602,
    9910.53181242413, 10104.5889493016, 9851.70104229335, 9972.91821342281,
    10080.4485086333, 10044.5102818099, 10037.3707232711, 10025.1107006076,
    10022.3659427419, 9941.51637265177, 9873.12826319285, 10027.9036424549,
    10033.6518983864, 9970.47127759776, 9937.3319252128, 10013.3439414305,
    10030.3125017708, 10168.5115559098, 10213.3568382367, 9990.24289183087,
    9968.82189362707, 10048.7504375345, 10015.8411633632, 10037.6851291425,
    9925.92765463682, 9835.81447415085, 9782.6505066721, 10033.5360418173,
    9991.76186224687, 9924.86818104305, 9970.41809893224, 9980.55197551292,
    9886.97032019385, 9925.73912143071, 9971.01687402101, 9858.19281102242,
    9969.19466304141, 9955.12658457894, 10139.5950943687, 9967.09479735319,
    10168.1650679826, 10023.9501235604, 9821.41776472295, 10064.1149573067,
    10134.8532916488, 9943.57024828908, 9833.93164357077)), row.names = c(NA,
-60L), groups = structure(list(month_name = structure(1:12, .Label = c("January",
"February", "March", "April", "May", "June", "July", "August",
"September", "October", "November", "December"), class = c("ordered",
"factor")), .rows = structure(list(1:5, 6:10, 11:15, 16:20, 21:25,
    26:30, 31:35, 36:40, 41:45, 46:50, 51:55, 56:60), ptype = integer(0), class = c("vctrs_list_of",
"vctrs_vctr", "list"))), row.names = c(NA, 12L), class = c("tbl_df",
"tbl", "data.frame"), .drop = TRUE), class = c("grouped_df",
"tbl_df", "tbl", "data.frame"))

A: you can try data.table:
library(data.table) # load data.table

setDT(stats) # convert stats to data.table
stats[, rv := rnorm(.N, mean = mean, sd = sd), by = .(month_name, item)]

In your example there's only one record of each combination month_name and item, but I can imagine your real data has more.

*

*The := is an assignment operator. You'll assign the result of rnorm into a new column called rv.

*The by =  part serves for grouping, see ?data.table.

EDIT TO ADD:
If you want 10,000 random variables, then:
stats[, new_rv := .(list(rnorm(1e4, mean, sd))), by = .(month_name, item)]

You already know the := and the by = parts, so let's dive into the expression in the middle:

*

*The .(list()) bit will assign the resulting list (vector of 10,000 random numbers, in our case) to the variable (because we are using the assignment operator :=).

*The very interesting thing is that with this .(list()) "combo" you can store complex things in a variable (column) of a data.table. I use it often to store things such as forecasts, plots or linear models, etc. by group: it is very useful!

Now, if you want to operate on your new variable, please keep in mind that it is a list, so you need to subset it accordingly:
If you want to check that the standard deviation of new_rv of row 1 is close to what you expect, the following code will throw an error:
stats[1, sd(new_rv)]
> Error in var(if (is.vector(x) || is.factor(x)) x else as.double(x), na.rm = na.rm) :
> is.atomic(x) is not TRUE

It is complaining that you are attempting to calculate sd() on a list. The correct code is:
stats[1, sd(new_rv[[1]])]
[1] 9926.439

The [[1]]] part is correctly subsetting the first element of the list.


text:
Q: Nonlinear ODE's So I've in second-year, taking a course on differential equations. We've learned about integrating factors, different classifications, substitutions, etc. I think I have a hold on lots of this stuff so far but this one problem is stuck in my teeth and it's driving me crazy. It looks simple enough but Maple spits out a big ugly logarithmic equation with an arctan term, and I don't know where to begin:
$x^2\,dx + (xy + x^2)\,dy = 0$

A: $$
\frac{dy}{dx} = -\frac{x^{2}}{xy+x^{2}} = -\frac{1}{\frac{y}{x} + 1}.
$$
using the transform $z = y/x$ yields
$$
x\frac{dz}{dx} + z = - \frac{1}{z+1}.
$$
This is separable and therefore can be solved.
To complete the problem
$$
\int \frac{(z+1)}{z(z+1)+1}dz = -\int \frac{1}{x} = -\mathrm{ln}(x) + C
$$
now we shall concentrate on the lhs
$$
\frac{(z+1)}{z(z+1)+1} = \frac{4}{3}\frac{(z+1)}{\left(\frac{z+\frac{1}{2}}{\sqrt{3/4}}\right)^{2}+1}.
$$
Using a change of variable $u = \frac{z+\frac{1}{2}}{\sqrt{\frac{3}{4}}}$ leads to
$$
\frac{4}{3}\frac{\frac{\sqrt{3}}{2}u+\frac{1}{2}}{u^{2}+1}= \frac{2}{\sqrt{3}}\frac{u+\frac{1}{\sqrt{3}}}{u^{2}+1}
$$
after all that re-arranging we can sub back into the integral.
$$
\int \frac{2}{\sqrt{3}}\frac{u+\frac{1}{\sqrt{3}}}{u^{2}+1}\sqrt{\frac{3}{4}}du = -\mathrm{ln}(x) + C
$$
we can split the integral on the lhs as
$$
\int \frac{u}{u^{2}+1} du + \frac{1}{\sqrt{3}}\int \frac{1}{u^{2}+1}du
$$
The terms above evaluates to terms in the brackets below
$$
\left[\frac{1}{2}\mathrm{ln}\left(u^{2}+1\right)+\frac{1}{\sqrt{3}}\mathrm{arctan}(u) \right] = -\mathrm{ln}(x) + C
$$
$$
u = \frac{1}{x}\frac{2y+x}{\sqrt{3}}
$$
transforming back
$$
\left[\frac{1}{2}\mathrm{ln}\left(\left(\frac{1}{x}\frac{2y+x}{\sqrt{3}}\right)^{2}+1\right)+\frac{1}{\sqrt{3}}\mathrm{arctan}\left(\frac{1}{x}\frac{2y+x}{\sqrt{3}}\right) \right] = -\mathrm{ln}(x) + C
$$
which if we expand the log argument yields
$$
\left(\frac{1}{x}\frac{2y+x}{\sqrt{3}}\right)^{2}+1 = \frac{4y^{2} + 4xy + x^{2} + 3x^{2}}{3x^{2}} = \frac{4}{3}\frac{y^{2} + xy + y^{2}}{x^{2}}
$$
which if we take the logarithm of
$$
\mathrm{ln}\left(\frac{4}{3}\right) + \mathrm{ln}\left(\frac{y^{2} + xy + y^{2}}{x^{2}}\right)
$$
we can sub back into the solution equation and take the constant logarithm into the constant C, we finally reach
$$
\frac{1}{2}\mathrm{ln}\left(\frac{y^{2} + xy + y^{2}}{x^{2}}\right)+\frac{1}{\sqrt{3}}\mathrm{arctan}\left(\frac{1}{x}\frac{2y+x}{\sqrt{3}}\right)  = -\mathrm{ln}(x) + C
$$
was this close to what you got?


text:
Q: Take conditions from spinner and retrieve and list data in listview from database on basis of that conditions I want to retrieve data from the database so that only those data should be listview which will work on the true condition.
I have added two spinners in the XML file. One spinner contains the default values stored in java file for getting options of blood group and second contains city names.
I want that if a user selects BloodGroup as O+ve from spinner and City as Gurgaon and clicks on search button then the details of the person will be shown in the listview that follows both spinner queries.

A: The following is a working example of how you can apply the SelectedItem from two spinners and then by clicking a Search button display only rows that contain both items are then listed (if any).
The examples are based upon the scenario you provide. That is there is a specific list of Cities and BloodGroups that can be selected via the Spinners. The records table includes columns for both plus two columns _id and name. The test database is populated with 100 random names, cities and bloodgroups.
The layout activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Blood Bank" />

    <Spinner
        android:id="@+id/select_bloodgroup"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
    </Spinner>
    <Spinner
        android:id="@+id/select_city"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
    </Spinner>
    <Button
        android:id="@+id/search"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Search"/>
    <ListView
        android:id="@+id/records_list"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
    </ListView>
</LinearLayout>

The DatabaseHelper DBHelper.java
public class DBHelper extends SQLiteOpenHelper {

    public static final String DBNAME = "bloodbank";
    public static final int DBVERSION = 1;
    public static final String TB_RECORDS = "records";
    public static final String COl_RECORDS_ID = BaseColumns._ID;
    public static final String COL_RECORDS_NAME = "_name";
    public static final String COL_RECORDS_BLOODGROUP = "_blood_group";
    public static final String COL_RECORDS_CITY = "_city";

    SQLiteDatabase mDB;

    public DBHelper(Context context) {
        super(context,DBNAME, null, DBVERSION);
        mDB = this.getWritableDatabase();

    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String crtrecords = "CREATE TABLE IF NOT EXISTS " +
                TB_RECORDS + "(" +
                COl_RECORDS_ID + " INTEGER PRIMARY KEY," +
                COL_RECORDS_NAME + " TEXT," +
                COL_RECORDS_CITY + " TEXT, " +
                COL_RECORDS_BLOODGROUP + " TEXT" +
                ")";
        db.execSQL(crtrecords);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int i, int i1) {

    }

    public long addRecord(String name, String city, String bloodgroup) {
        ContentValues cv = new ContentValues();
        cv.put(COL_RECORDS_NAME,name);
        cv.put(COL_RECORDS_CITY,city);
        cv.put(COL_RECORDS_BLOODGROUP,bloodgroup);
        return mDB.insert(TB_RECORDS,null,cv);
    }

    public Cursor getrecords(String city, String bloodgroup) {
        ArrayList<String> baseargs = new ArrayList<>();
        String whereclause = null;
        if (city != null && city.length() > 0) {
            whereclause = COL_RECORDS_CITY + "=?";
            baseargs.add(city);
        }
        if (bloodgroup != null && bloodgroup.length() > 0) {
            if (whereclause != null && whereclause.length() > 0) {
                whereclause = whereclause + " AND ";
            } else whereclause = "";
            whereclause = whereclause + COL_RECORDS_BLOODGROUP + "=?";
            baseargs.add(bloodgroup);
        }
        String[] whereargs = null;
        if (baseargs.size() > 0) {
            whereargs = new String[baseargs.size()];
            for (int i =0; i < baseargs.size();i++) {
                whereargs[i] = baseargs.get(i);
            }
        }
        return mDB.query(TB_RECORDS,null,whereclause,whereargs,null,null,COL_RECORDS_NAME);
    }
}

The invoking activity MainActivity.java :-
public class MainActivity extends AppCompatActivity {

    //Specific Blood groups
    public static final String[] BLOODGROUPS = new String[]{
            "A+","A-","B+","B-","0+","0-","AB+","AB-"
    };

    //Specific Cities
    public static final String[] CITIES = new String[]{
            "London","Paris","New York","Montreal","Gurgaon"
    };

    // Some names for auto generation of test data
    static final String[] peoples_names = new String[]{
            "Fred","Mary","Bert","Anne","James","Susan","Tom","Theresa",
            "Cherles","Corrine","David","Diana","Edward","Esmerelda",
            "George","Gorgina","Harrold","Heather"

    };

    TextView mTitle;
    Spinner mBloodGroups, mCities;
    Button mSearch;
    DBHelper mDBHlpr;
    ArrayAdapter<String> mCitiesAdapter, mBloodGroupsAdapater;
    ListView mRecordsList;
    SimpleCursorAdapter mSCA;
    String mCurrentCities = "", mCurrentBloodGroups = "";
    Cursor mCsr;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mTitle = this.findViewById(R.id.title);
        mBloodGroups = this.findViewById(R.id.select_bloodgroup);
        mCities = this.findViewById(R.id.select_city);
        mSearch = this.findViewById(R.id.search);
        mRecordsList = this.findViewById(R.id.records_list);
        mCurrentCities = "";
        mCurrentBloodGroups = "";

        // Add some test data
        mDBHlpr = new DBHelper(this);
        if (DatabaseUtils.queryNumEntries(mDBHlpr.getWritableDatabase(),DBHelper.TB_RECORDS) < 1) {
            Random rnd = new Random();
            rnd.setSeed(System.currentTimeMillis());
            for (int i = 0; i < 100; i++) {
                mDBHlpr.addRecord(
                        peoples_names[rnd.nextInt(peoples_names.length)],
                        CITIES[rnd.nextInt(CITIES.length)],
                        BLOODGROUPS[rnd.nextInt(BLOODGROUPS.length)]
                );
            }
        }

        //Setup City Spinner
        mCitiesAdapter = new ArrayAdapter<>(this,android.R.layout.simple_dropdown_item_1line,CITIES);
        mCities.setAdapter(mCitiesAdapter);
        //Setup Bloodgroups Spinner
        mBloodGroupsAdapater = new ArrayAdapter<>(this,android.R.layout.simple_dropdown_item_1line,BLOODGROUPS);
        mBloodGroups.setAdapter(mBloodGroupsAdapater);
        // Add Search Buitton Click Listener
        mSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mCurrentCities = mCities.getSelectedItem().toString();
                mCurrentBloodGroups = mBloodGroups.getSelectedItem().toString();
                refreshList();
            }
        });
        // Initial List (All)
        refreshList();

    }

    //Setup or refresh the ListView
    private void refreshList() {
        // Grab the data
        mCsr = mDBHlpr.getrecords(mCurrentCities,mCurrentBloodGroups);
        // If first time then setup the Cursor Adapter
        if (mSCA == null) {
            mSCA = new SimpleCursorAdapter(this,
                    android.R.layout.simple_list_item_2,
                    mCsr,
                    new String[]{DBHelper.COL_RECORDS_NAME,DBHelper.COL_RECORDS_CITY},
                    new int[]{android.R.id.text1, android.R.id.text2},
                    0
            );
            mRecordsList.setAdapter(mSCA);
        }
        // If not first time then swap the cursor
        else {
            mSCA.swapCursor(mCsr);
        }
    }
}

Result
Initially the following is displayed (as the data is random generated it may differ although there will be 100 item listed) :-

After Selecting City Gurgaon :- (note results will likely differ due to random data) :-

After Selecting Bloodgroup A- :- (again results will likely differ) :-

*

*Note this example works, the intention is that you learn from the supplied code and do YOUR research, if you have subsequent questions then you should ask them as separate and distinct questions on Stack Overflow.


text:
Q: looping through emails created by database recordset I wish to send an email to one address and cc to other addresses drawn from a table.
// get all cc email id's for this users site
$results3h = mysql_query("SELECT user_id FROM company_ccemails WHERE site_id = '$site_id' ");
echo mysql_error();
while($row = mysql_fetch_array($results3h))
    {
        $cc_id = $row['user_id'] ;

        //get email addresses for each id

       $results3i = mysql_query("SELECT username FROM user WHERE id = '$cc_id' ");
       echo mysql_error();

       while($row = mysql_fetch_array($results3i))
           {
              $ccemails = $row['username'] . "," ;
           }
           mysql_free_result($results3i);
}
mysql_free_result($results3h);
//send emails to

    $to = "support@mydomain.com ; ";
$subject = "$email_subject";
$message = "$email_message";
$headers = "CC: " .$ccemails. "\r\n";
$headers .= "From: " . strip_tags($myusername) . "\r\n";
$headers .= "Reply-To: ". strip_tags($myusername) . "\r\n";
$headers .= "BCC: " .$myusername. "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
mail($to, $subject, $message, $headers);

when sending this email only the 'to' and 1 'cc' is sent although there are 3 'cc' email address. if I move the send code under $ccemails = $row... then an email is sent to each 'cc' separately along with support@mydomain.com. this results in support@ getting lots of emails.
how do I change the code to get the cc emails in one string and send as one email so support only receives one copy?
I'm relatively new to PHP coding (usually ASP) and am sure this is straight forward but is confusing me at the moment
thanks for any help

A: With $ccemails = $row['username'] . "," ; you are assigning the value of $row['username'] to your $ccemails variable. This means you override it everytime in the loop.
You have to concat the string with .=
Try this below:
$ccemails = ""; // define this here, because otherwise you will get a notice
while ( $row = mysql_fetch_array( $results3h ) ) {
    /**
     * Your code
     */
    while ( $row = mysql_fetch_array( $results3i ) ) {
        $ccemails .= $row['username'] . ",";
    }
    /**
     * Your code
     */
}


text:
Q: How can I take varying chunks out of a Kotlin Sequence? If I have a Kotlin sequence, every invocation of take(n) restarts the sequence.
val items = generateSequence(0) {
    if (it > 9) null else it + 1
}

@Test fun `take doesn't remember position`() {
    assertEquals(listOf(0, 1), items.take(2).toList())
    assertEquals(listOf(0, 1, 2), items.take(3).toList())
}

Is there an easy way of write say, another(n) such that
@Test fun `another does remember position`() {
    assertEquals(listOf(0, 1), items.another(2).toList())
    assertEquals(listOf(2, 3, 4), items.another(3).toList())
}

I suppose that I have to have something that isn't the Sequence to keep the state, so maybe what I'm actually asking for is a nice definition of fun Iterator<T>.another(count: Int): List<T>

A: What about this:
    @Test
    fun `another does remember position`() {
        val items: Sequence<Int> = generateSequence(0) {
            if (it > 9) null else it + 1
        }

        val (first, rest) = items.another(2)
        assertEquals(listOf(0, 1), first.toList())
        assertEquals(listOf(2, 3, 4), rest.another(3).first.toList())
    }

    fun <T> Sequence<T>.another(n: Int): Pair<Sequence<T>, Sequence<T>> {
        return this.take(n) to this.drop(n)
    }

A: Sequence does not remember its position, but its iterator does remember:
val iterator : Iterator<Int> = items.iterator()

Now all you need is something like take(n) but for Iterator<T>:
public fun <T> Iterator<T>.another(n: Int): List<T> {
    require(n >= 0) { "Requested element count $n is less than zero." }
    if (n == 0) return emptyList()
    var count = 0
    val list = ArrayList<T>(n)
    for (item in this) {
        list.add(item)
        if (++count == n)
            break
    }
    return list
}

A: To answer the last part of your question:

I suppose that I have to have something that isn't the Sequence to keep the state, so maybe what I'm actually asking for is a nice definition of fun Iterator.another(count: Int): List

One such implementation would be:
fun <T> Iterator<T>.another(count: Int): List<T> {
    val collectingList = mutableListOf<T>()
    while (hasNext() && collectingList.size < count) {
        collectingList.add(next())
    }
    return collectingList.toList()
}

This passes your test if you use the iterator produced by the sequence:
@Test
fun `another does remember position`() {
    val items = generateSequence(0) {
        if (it > 9) null else it + 1
    }.iterator() //Use the iterator of this sequence.
    assertEquals(listOf(0, 1), items.another(2))
    assertEquals(listOf(2, 3, 4), items.another(3))
}

To me what you've described is an iterator, since it's something that allows you to go over a collection or sequence etc. but also remember its last position.
NB the implementation above wasn't written to take into consideration what should happen for non-positive counts passed in, and if the count is larger than what's left to iterate over you'll be returned a list which has smaller size than n. I suppose you could consider this an exercise for yourself :-)

A: Sequence does not remember its position, but its iterator does remember:
val iterator : Iterator<Int> = items.iterator()

Unfortunately there is no take(n) for an iterator, so to use the one from stdlib you need to wrap iter into an Iterable:
val iterable : Iterable<Int> = items.iterator().asIterable()

fun <T> Iterator<T>.asIterable() : Iterable<T> = object : Iterable<T> {
    private val iter = this@asIterable
    override fun iterator() = iter
}

That makes itareble.take(n) remember its position, but unfortunately there is a of-by-one error because the standard .take(n) asks for one element too many:
public fun <T> Iterable<T>.take(n: Int): List<T> {
    require(n >= 0) { "Requested element count $n is less than zero." }
    if (n == 0) return emptyList()
    if (this is Collection<T>) {
        if (n >= size) return toList()
        if (n == 1) return listOf(first())
    }
    var count = 0
    val list = ArrayList<T>(n)
    for (item in this) {
        if (count++ == n)
            break
        list.add(item)
    }
    return list.optimizeReadOnlyList()
}

That can be fixed with a little tweak:
public fun <T> Iterable<T>.take2(n: Int): List<T> {
    require(n >= 0) { "Requested element count $n is less than zero." }
    if (n == 0) return emptyList()
    if (this is Collection<T>) {
        if (n >= size) return toList()
        if (n == 1) return listOf(first())
    }
    var count = 0
    val list = ArrayList<T>(n)
    for (item in this) {

        list.add(item)
        //count++
        if (++count == n)
            break
    }
    return list
}

Now both of you tests pass:
@Test fun `take does not remember position`() {
    assertEquals(listOf(0, 1), items.take2(2).toList())
    assertEquals(listOf(0, 1, 2), items.take2(3).toList())
}

@Test fun `another does remember position`() {
    assertEquals(listOf(0, 1), iter.take2(2).toList())
    assertEquals(listOf(2, 3, 4), iter.take2(3).toList())
}

A: You could create a function generateStatefulSequence which creates a sequence which keeps its state by using a second sequence's iterator to provide the values.
The iterator is captured in the closure of that function.
On each iteration the seed lambda ({ i.nextOrNull() }) of the returned sequence starts off with the next value provided by the iterator.
// helper
fun <T> Iterator<T>.nextOrNull() = if(hasNext()) { next() } else null

fun <T : Any> generateStatefulSequence(seed: T?, nextFunction: (T) -> T?): Sequence<T> {
    val i = generateSequence(seed) {
        nextFunction(it)
    }.iterator()

    return generateSequence(
        seedFunction = { i.nextOrNull() },
        nextFunction = { i.nextOrNull() }
    )
}

Usage:
val s = generateStatefulSequence(0) { if (it > 9) null else it + 1 }
println(s.take(2).toList())  // [0, 1]
println(s.take(3).toList())  // [2, 3, 4]
println(s.take(10).toList()) // [5, 6, 7, 8, 9, 10]

Try it out

A: Here is a nice definition of fun Iterator<T>.another(count: Int): List<T> as requested:
fun <T> Iterator<T>.another(count: Int): List<T> =
        if (count > 0 && hasNext()) listOf(next()) + this.another(count - 1)
        else emptyList()

A: As another workaround (similar to the suggestion by Willi Mentzel above) would be to create a asStateful() extension method that converts any sequence into a one that will remember the position, by wrapping it into an Iterable that always yields the same iterator.
class StatefulIterable<out T>(wrapped: Sequence<T>): Iterable<T> {
    private val iterator = wrapped.iterator()
    override fun iterator() = iterator
}

fun <T> Sequence<T>.asStateful(): Sequence<T> = StatefulIterable(this).asSequence()

Then you can do:
val items = generateSequence(0) {
    if (it > 9) null else it + 1
}.asStateful()

@Test fun `stateful sequence does remember position`() {
    assertEquals(listOf(0, 1), items.take(2).toList())
    assertEquals(listOf(2, 3, 4), items.take(3).toList())
}

Try it here: https://pl.kotl.in/Yine8p6wn


text:
Q: Suppress TeXworks PDF preview Is there any way to suppress the PDF preview appearing? I really don't like the internal PDF viewer and I prefer using Acrobat. (I know that on Windows, Acrobat makes the .pdf file read-only, but I'm on linux and it behaves better here). It is annoying pop-up that I have to kill or so whenever I compile.

A: Opening the PDF viewer part of TeXworks is configured on a per-tool basis in the Typesetting preferences. So for example to prevent the viewer opening after typesetting using pdfLaTeX, I would need to untick the box in the following dialog

(Screenshot on Windows, but the same principal applies on Linux)

A: In the "Typesetting" tab of the preferences, you can double click the tool you use, say "pdfLaTeX" and there you can disable "View PDF after running".
I'm afraid you have to do it for all tools.


text:
Q: Drawing partial circle arc in 2D I'm trying to draw a partial circle arc in Visual Basic. (Example: 75% of an outer arc.)
I tried to do this both by adding in the Visual Power Packs and by using the below code but I can't seem to figure out how to hide a portion of the arc without either covering everything within the circle or disabling the circle altogether.

(The goal being that as the countdown timer ticks down, a portion of the circle disappears as the clock is counting down. So at 0:15, there's half the circle and the like.)
Is there a way to draw a 2D circle arc that doesn't involve using any sort of graphics engine?


text:
Q: Kendo UI Tooltip on show, access target? The target is accessible by passing the argument e to the anonymous function for content.
gridToolTipz = $('#grid').kendoTooltip({
    filter: "td[role=gridcell]",
    content: function (e) {
            var target = e.target; // the element for which the tooltip is shown
            ...
    },
    show: function(e) {
            var target = e.target; // the element for which the tooltip is shown
            ...
    }
});

Is it possible to achieve the same thing on show? The above code doesn't work.

A: You can always access the target element by calling tooltip.target():
var toolTip = $('#grid').kendoTooltip({
    filter: "td[role=gridcell]",
    content: function (e) {
        var target = e.target; // the element for which the tooltip is currently shown
        return "Content is: " + target.text(); // use current element for content
    },
    show: function (e) {
        var target = this.target(); // the element for which the tooltip is currently  shown

        if (target) {
            console.log("now showing with content: ");
            console.log(target.text());
        }
    }
}).data("kendoTooltip");

See demo: http://jsfiddle.net/lhoeppner/mcpxj/


text:
Q: Why the shift to past perfective when the whole sentence is in the present? I was looking at Collins' definition of double-cross:

If someone you trust double-crosses you, they do something which harms you instead of doing something they had promised to do.

So we have double-crosses and harms in present simple, but then the last choice of tense and aspect is had promised in past perfective. Can someone explain to me why it cannot be present perfective? What is the point of reference in time for this past perfective?

A: One use of the past perfect, according to Cambridge dictionaries, is where you're talking about a changed state, something that was the case but is no longer the case. For instance where someone promised something, then broke that promise. This can happen even when you're using the present tense.
They give a couple of examples:

A: Are you going anywhere today?
B: I had planned to go to the beach but look at the rain!

They note that here "had is stressed; the meaning is 'I have now changed my mind'". It emphasises that B no longer wants to go to the beach, unlike "I planned to go to the beach but look at the rain!" In the latter case they might still go to the beach even though it's raining.

I'm very happy working as an engineer but I had wanted to be an actor when I was younger.

In the latter case the speaker is emphasising that they no longer want to be an actor, while "I'm very happy working as an engineer but I wanted to be an actor when I was younger." might suggest that they still want to be an actor even if they aren't one now.
It wouldn't be wrong to use the present perfect "...something they have promised to do", but "had promised" emphasised something that was done but is no longer the case: the promise is broken.

A:
they had promised to do. = [that] they had promised to do.

This is a subordinate, relative clause that modifies "something".
The tense of subordinate clauses are not (in general) affected by the tense of the main clause.
Why choose the past perfect?
The past perfect is used to describe context and background, i.e. events that finished prior to the main event. The main event is "double crossing you".
Your example is a correct use of the past perfect.
Compare
I had dug the garden, I had taken the dog for a walk (things that had finished before the main event and give context) and then the visitors arrived (The main event).


text: Q: Another proof that $A[x]\otimes M\cong M[x]$ Let $A$ be a ring and $M$ be an $A$-module. If $x$ is an indeterminate, I know that $A[x]\otimes_AM\cong M[x]$ ($A[x],M[x]$ are clearly $A$-modules). However my question is if one can prove this equality using the exact sequences, plus the facts that $M\otimes_A-$ is right-exact and that $A[x]\otimes _A-$ is exact.


text:
Q: OpenOffice converter don't work with apache Does anyone know why this works great with phpCLI but fails with apache?
$cmd = "soffice --headless --nofirststartwizard -convert-to pdf:writer_pdf_Export file.doc -outdir converted/";
exec($cmd, $dump, $ret);

A: I was struggling with this few more hours, but finally I've found solution here
http://geekswithblogs.net/robertphyatt/archive/2011/11/19/converting-.docx-to-pdf-or-.doc-to-pdf-or-.doc.aspx
I hope this can help someone else

A: Try use "export HOME=/tmp" before run OpenOffice.
Example:
  export HOME=/tmp
  soffice --headless --convert-to pdf --outdir /var/www/public/uploads/ /var/www/public/uploads/artcl.ppt


text:
Q: sql server insert into dynamic global named table from from xml I would like to insert data into temp global table with dynamic named:
SET @SQL = '
CREATE TABLE '+Cast(@TableName as VARCHAR(60))+'
(
    Adr VARCHAR(1000)
)';
execute (@SQL);

I'm able to retreive values which I need like:
SELECT Recipient.query('.').value('.','varchar(15)')
FROM   @not.nodes('Data/MgRec' ) xmlData(ref) CROSS APPLY
    ref.nodes('Recipient') AS Recipients(Recipient) ;

Which give me list with some values..
Now when I'd like to insert those values:
SET @SQL = 'INSERT INTO '+ Cast(@TableName as VARCHAR(60))+' (Adr)
 Select Recipient.query(''.'').value(''.'',''varchar(15)'')
FROM  '+ Cast(@not as VARCHAR(60))  +'.nodes(''Data/MgRec'' ) xmlData(ref) CROSS APPLY
    ref.nodes(''Recipient'') AS Recipients(Recipient)' ;
    execute (@SQL);
SET @SQL = 'select * from ' +Cast(@TableName as VARCHAR(60))
execute (@SQL);

And here I'm stucked , error:

Target string size is too small to represent the XML instance

Any advice, please?
Bellow @not xml:
<Data>
  <MgRec>
    <Recipient>10800234</Recipient>
    <Recipient>24900005</Recipient>
    <Recipient>24900004</Recipient>
    <Recipient>10201026</Recipient>
    <Recipient>66600019</Recipient>
    <Recipient>14042243</Recipient>
  </MgRec>
</Data>

A: Why not just properly parametrise your query?
DECLARE @SchemaName sysname = N'dbo',
        @TableName sysname = N'YourTable';

DECLARE @SQL nvarchar(MAX);
SET @SQL = '
CREATE TABLE ' + QUOTENAME(@SchemaName) + N'.' + QUOTENAME(@TableName)+ N'
(
    Adr VARCHAR(1000)
)
INSERT INTO ' + QUOTENAME(@SchemaName) + N'.' + QUOTENAME(@TableName)+ N' (Adr)
SELECT Recipient.value(''(./text())[1]'',''varchar(15)'')
FROM @not.nodes(''Data/MgRec'' ) xmlData(ref)
     CROSS APPLY ref.nodes(''Recipient'') AS Recipients(Recipient) ;';
EXEC sys.sp_executesql @SQL, N'@not xml', @not;

db<>fiddle