text:
Q: Waiting on a service that itself relies on nested promises/observables I am trying to use the Ionic Native QR Scanner in an application. As I will need the scanner in multiple modules, I thought it would be a good idea to build a simple service that can open the scanner and return the result.
To start with, I'm using the sample code available on the link above:
// inside qrScannerService...
public scanQR(): Promise<void> {
    return this.qrScanner.prepare()
        .then((status: QRScannerStatus) => {
            if (status.authorized) {
                let scanSub = this.qrScanner.scan().subscribe((qrResult: string) => {

                    this.qrScanner.hide();
                    scanSub.unsubscribe();
                    // this is what I want, ultimately.
                    return qrResult;
                });
                this.qrScanner.show();
            } else if (status.denied) {
                console.log("denied");
            } else {
                // permission was denied, but not permanently.
            }
        })
        .catch((e: any) => console.log('Error is', e));
}

So that's the service. In my module, I use the scanner service like so:
private doQRScan() {
    this.qrScannerService.scanQR().then(result => {
        console.log(result);
    });
}

So I have a promise chain doQRScan()->scanQR()->prepare()->scan() and I need to wait on all three promises/observables, or I need to restructure the service method, but I'm fairly new to Angular and so far the answer eludes me.
As it stands, prepare() returns its promise and doQRScan() is satisfied, so the actual QR scan is never returned.
Any ideas?

A: You need to return a new promise in your scanQR function . I haven't tested it, but something like this should work for you:
public scanQR() {
return new Promise((resolve, reject) => {
    this.qrScanner.prepare()
        .then((status: QRScannerStatus) => {
            if (status.authorized) {
                let scanSub = this.qrScanner.scan().subscribe((qrResult: string) => {

                    this.qrScanner.hide();
                    scanSub.unsubscribe();
                    // this is what I want, ultimately.
                    // return qrResult;
                    resolve(qrResult) //-------> resolving your top level promise
                });
                this.qrScanner.show();
            } else if (status.denied) {
                console.log("denied");
                reject("denied!")
            } else {
                // permission was denied, but not permanently.
                reject("denied!")
            }
        })
        .catch((e: any) =>
            console.log('Error is', e)
            reject(e)
        );
})

}


text:
Q: How to handle multiple .env files on Vercel? In my private git repository, I have 3 env files for every environment
.env.local

.env.development

.env.production

My production branch is main and the preview environment (staging or pre-production) branch is development. When I push changes to the development branch, Vercel is reading the .env.production file instead of the .env.development
How can I make Vercel read a specific env file for a specific environment? In the NextJS documentation says we can have those multiple env files

A: you can specify the path for what you are calling.
https://www.npmjs.com/package/dotenv#path
example:
require('dotenv').config({ path: `.env.${process.env.NODE_ENV}` })

redpajama_set_name: RedPajamaStackExchange


text:
Q: Async_Sinatra blocks only when requesting from browser's tabs I'm giving async Sinatra a try and having a problem.
When using the following simple code:
require 'sinatra'
require 'sinatra/async'

Sinatra.register Sinatra::Async

aget '/delay/?' do
  logger.info "Connected"
  EM.add_timer(5) { body {"delayed for 5 seconds" } }
end

It runs fine when I concurrently request /delay/ with ab, taking 5 secs for all requests.
It does block however when I request /delay/ from within 2 Chrome tabs (or Firefox), and it executes sequentially, causing the 2nd request to take 10 secs.
The funny thing is that requesting it from multiple Safari tabs, again executes fine (in parallel).
Any idea, what might be causing this behavior?
Gem Versions:
gem 'sinatra', "~> 1.3.2"
gem "eventmachine", "1.0.0.beta.4.1"
gem 'thin', "~> 1.3.1"
gem "async_sinatra", "~> 1.0.0"

A: UPDATE: It seems that the browser cache is what's causing this for both Firefox and Chrome. There can be only 1 active cache write for any URL. Adding a query param will actually fix this.
Source: Multiple Ajax requests for same URL


text:
Q: DependencyResolver doesn't Resolve dependencies. Why? I'm using Unity as my IoC in a project.
UnityConfig is setup like this...
public static class UnityConfig
{
    private static readonly IUnityContainer container = new UnityContainer();

    public static void ConfigureIoCContainer()
    {
        My.Composition.Builder.Compose(container);

        DependencyResolver.SetResolver(new UnityDependencyResolver(container));
    }

    /// <summary>
    /// Gets the configured Unity container.
    /// </summary>
    public static IUnityContainer GetConfiguredContainer()
    {
        return container;
    }
}

My.Composition.Builder.Compose() does this ...
    public static void Compose(IUnityContainer container)
    {
        var types = new List<Type>();

        types.AddRange(Services.Interface.Builder.GetTypes(container));
        types.AddRange(Services.Builder.GetTypes(container));
        // ... lots more assemblies referenced here

        var distinctTypes = types.Distinct();

        container.RegisterTypes(distinctTypes, WithMappings.FromMatchingInterface, WithName.Default, WithLifetime.PerResolve);
    }

Now, in the 2 assemblies referenced above, this I return 3 types; IConfigUow, ISecurityUow and IResourceUow from the first and ConfigUow, SecurityUow and ResourceUow from the second.
If I put a breakpoint at the line after My.Composition.Builder.Compose(container) in UnityConfig is called and have a look at the list of registered types I can see all that I should...
{Microsoft.Practices.Unity.ContainerRegistration}
    LifetimeManager: {Microsoft.Practices.Unity.PerResolveLifetimeManager}
    LifetimeManagerType: {Name = "PerResolveLifetimeManager" FullName = "Microsoft.Practices.Unity.PerResolveLifetimeManager"}
    MappedToType: {Name = "ConfigUow" FullName = "My.Services.Security.ConfigUow"}
    Name: null
    RegisteredType: {Name = "IConfigUow" FullName = "My.Services.Interface.Security.IConfigUow"}

{Microsoft.Practices.Unity.ContainerRegistration}
    LifetimeManager: {Microsoft.Practices.Unity.PerResolveLifetimeManager}
    LifetimeManagerType: {Name = "PerResolveLifetimeManager" FullName = "Microsoft.Practices.Unity.PerResolveLifetimeManager"}
    MappedToType: {Name = "SecurityUow" FullName = "My.Services.Security.SecurityUow"}
    Name: null
    RegisteredType: {Name = "ISecurityUow" FullName = "My.Services.Interface.Security.ISecurityUow"}

{Microsoft.Practices.Unity.ContainerRegistration}
    LifetimeManager: {Microsoft.Practices.Unity.PerResolveLifetimeManager}
    LifetimeManagerType: {Name = "PerResolveLifetimeManager" FullName = "Microsoft.Practices.Unity.PerResolveLifetimeManager"}
    MappedToType: {Name = "ResourceUow" FullName = "My.Services.Localization.ResourceUow"}
    Name: null
    RegisteredType: {Name = "IResourceUow" FullName = "My.Services.Interface.Localization.IResourceUow"}

However, if I let the next line execute to set the DependencyResolver and call
DependencyResolver.Current.GetService<IConfigUow>();

a value of null is returned. Calling
DependencyResolver.Current.GetService<ISecurityUow>();

works and returns an instance of SecurityUow. Attempting to resolve IResourceUow also fails.
For the life of me I can't see what I'm doing wrong. Anyone have any ideas?
UPDATE
OK, so by calling container.Resolve(IConfigUow) I got an exception that was being masked by the DependencyResolver.
The error suggested that I was missing a type mapping. The constructor for ConfigUow looks like this...
    public ConfigUow(ICrudRepo<AM.Configuration> crudRepo = null) : base(crudRepo)
    {
        CrudRepo = crudRepo ?? DependencyResolver.Current.GetService<IConfigRepo>();
        Ctx = CrudRepo.GetContext();
    }

I was unaware that I needed to explicitly call RegisterType() for types that use generics.
So, all I needed to do was register the appropriate type like this...
container.RegisterType(typeof (ICrudRepo<>), typeof (CrudRepo<>));

And it all worked.
For future readers, these pages proved helpful...

*

*Registering Generic Parameters and Types (MSDN)

*Using Unity, how do you register type mappings for generics? (StackOverflow)

A: The answer was that the DependencyResolver was masking the fact that the IoC container was throwing an exception.
Having discovered that it wasn't too hard to fix the problem. Readers are invited to look at the UPDATE to the original question to see what it was I had to fix and how I did it.


text:
Q: What is the closure of the class of context-free languages under intersection? Let $\mathsf{CF}$ be the class of context-free languages. As is well known, $\mathsf{CF}$ is not closed under intersections; the classical counterexample is the intersection of $\{a^mb^mc^n\mid m,n\in\mathbb N\}$ with $\{a^mb^nc^n\mid m,n\in\mathbb N\}$. Can one explicitly describe the closure of $\mathsf{CF}$ under (finite) intersections?
Note that $\mathsf{CF}$ is a subclass of $\mathsf{CS}$, the context-sensitive languages, and that $\mathsf{CS}$ is closed under intersection, so the closure is contained in $\mathsf{CS}$. Then the question boils down to, is every context-sensitive language a finite intersection of context-free languages, or is there a "nice" intermediate class that is closed under intersections?
I find it surprising that the answer to this natural question appears hard to find in the literature.

A: Let $L = \{wcw \mid w \in \{a,b\}^*\}$. It is shown in [1] that the complement of $L$ is context-free and thus $L$ is context-sensitive. However $L$ cannot be expressed as a finite intersection of context-free languages.
It follows that the class $\cap\mathsf{CF}$ of finite intersections of context-free languages is strictly included in the class $\mathsf{CS}$ of context-sensitive languages.
[1] D. Wotschke,
The Boolean closures of the deterministic and nondeterministic context-free languages. Dritte Jahrestagung der Gesellschaft für Informatik (Hamburg, 1973), pp. 113--121. Lecture Notes in Comput. Sci., Vol. 1, Springer, Berlin, 1973.


text:
Q: Qt and parsing JSON data in C++ I have a QJsonObject in my code and It looks something like what is posted below (once converted to a string in python), (with a lot more entries of the same form). Suppose I want to group all of the name attributes in an array. In python I would convert my Json String to a dictionary and then populate this list as follows. How can I do this in c++ with qt?
1.
CountryNameList = []
For i in range len(CountryDictionary[1]):
      CountryNameList.append CountryDictionary[1][i]["name"]

// Below is what the JSON file looks like:
[
    {
        "per_page": "50",
        "total": 264,
        "page": 1,
        "pages": 6
    },
    [
        {
            "longitude": "-70.0167",
            "name": "Aruba",
            "region": {
                "id": "LCN",
                "value": "Latin America & Caribbean (all income levels)"
            },
            "adminregion": {
                "id": "",
                "value": ""
            },
            "iso2Code": "AW",
            "capitalCity": "Oranjestad",
            "latitude": "12.5167",
            "incomeLevel": {
                "id": "NOC",
                "value": "High income: nonOECD"
            },
            "id": "ABW",
            "lendingType": {
                "id": "LNX",
                "value": "Not classified"
            }
        },
        {
            "longitude": "69.1761",
            "name": "Afghanistan",
            "region": {
                "id": "SAS",
                "value": "South Asia"
            },
            "adminregion": {
                "id": "SAS",
                "value": "South Asia"
            },
            "iso2Code": "AF",
            "capitalCity": "Kabul",
            "latitude": "34.5228",
            "incomeLevel": {
                "id": "LIC",
                "value": "Low income"
            },
            "id": "AFG",
            "lendingType": {
                "id": "IDX",
                "value": "IDA"
            }
        },
  ] ]

A: Sample how to read and parse your json:
#include <QtCore>

int main() {
    QFile input_file("input.json");

    if (!input_file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qDebug() << "Can't open file";
        return 1;
    }

    QJsonParseError parse_error;

    //read and parse from file
    QJsonDocument doc = QJsonDocument::fromJson(input_file.readAll(),
                                               &parse_error);

    //check parsing errors
    if (parse_error.error != QJsonParseError::NoError) {
        qDebug() << "Parsing error:" << parse_error.errorString();
        return 1;
    }

    //this is top level arraya
    QJsonArray arr_doc = doc.array();

    //this is array of country objects
    QJsonArray arr_countries = arr_doc[1].toArray();

    //list to save result
    QList<QString> country_name_list;

    //c++11 style for cycle. Iterate over countries.
    for (const auto& country: arr_countries) {
        //getting name of country and convert to string, append to result
        country_name_list.append(country.toObject()["name"].toString());
    }

    qDebug() << country_name_list;

    return 0;
}

Don't forget add to .pro file:
CONFIG += c++11

And remove comma from your json:
     }
        },
  ] ]


text:
Q: Prometheus configuration for Spring MVC 5 In my company's web application we are using Spring 5, but the application is written in Spring MVC and we are not gonna change it anytime soon. I need to connect the application to Prometheus but I could not find any webpage explaining using Prometheus in Spring MVC. All examples are for Spring Boot, unfortunately.
Can you tell me how to integrate our application to Prometheus?
Best regards,

A: There's an sample project of Spring (not boot) with prometheus
Enable prometheus using AOP

Add this annotation to any Spring Configuration class to enable  * the use of the PrometheusTimeMethod annotation


text:
Q: SQL FUNCTION - one alias in SELECT AND WHERE I want to insert to NewTable some id(found by calledMethod) from table 'inserted' when this id actually it's not in this table(NewTable)
Actually i'm using this method (calledMethod)twice. How to reduce this using for example alias?
CREATE TRIGGER TriggerName
    ON Table
    AFTER INSERT
AS
BEGIN
    INSERT INTO NewTable
    (
        FirstId
        SecondId
    )
    SELECT
        I.ID
        CalledMethod(I.Name)
    FROM INSERTED I
    WHERE CalledMethod(I.Name)
    NOT IN (SELECT SecondId FROM NewTable)
END
GO

The second problem occures when I want insert two rows at the same time.
Insert Into Table
(
Name
)
Values
('ro'),('ro-RO')

In this situation, the method returns the same index and both will be added. How to resolve this problem.
In this situation, the method returns the same index
This is example of calledMethod
CREATE FUNCTION CalledMethod
(
     @internalName nvarchar(50)
)
RETURNS int
AS

  BEGIN
     return  case
         when @internalName Like 'ro%'  then 6
         when @internalName Like 'sk%'  then 7
         when @internalName Like 'bg%'  then 9
          end
  END

A: I believe this is what you need:
CREATE TRIGGER TriggerName
    ON Table
    AFTER INSERT
AS
BEGIN
    INSERT INTO NewTable
    (
        FirstId
        SecondId
    )
    SELECT
        min(I.ID),
        x.called
    FROM INSERTED I
    CROSS APPLY
    (SELECT CalledMethod(I.Name) called) x
    WHERE
      x.called NOT IN (SELECT SecondId FROM NewTable)
    GROUP BY x.called
END


text:
Q: extracting an element using Xpath

need to extract "#purchase=9780345527721" from this element using Xpath

*

*this is what i have done till now :
$nodelist_nook = trim($xpath_nook->query("//a[@class='buy-as-gift-link']")->item(0)->nodeValue);

A: Use:
//a[@id='yui_3_4_1_1_1329966665861_8510']/@href

This XPath expression selects all href attributes of all a elements that have an id attribute with string value "yui_3_4_1_1_1329966665861_8510".
In case you want to get not the attribute node (we hope that no two elements exist with the same value for id) but just its string value, this can be obtained as result of evaluating the following XPath expression:
string(//a[@id='yui_3_4_1_1_1329966665861_8510']/@href)


text:
Q: Can any other javascript client library, apart from socjjs, be used with spring websocket Spring websocket implements SockJs protocol at server and sockjs client can be used to interact with it. Is there any other equivalant library which can be used? We need to send query string with the sockjs comet URL but it seems it is not supported
http://sockjs-tornado.readthedocs.org/en/latest/faq.html
https://twitter.com/majek04/status/376371451005128704

So, more precisely, is there an alternative to sockjs client which supports query string and the goodness of sockjs client -fallback options?
I have raised a question about support for query string in sockjs:
http://stackoverflow.com/questions/31118456/can-i-add-request-parameter-to-sockjs-constructor-so-that-it-can-be-send-to-serv

A: As the answer of your other question states, yes, this is supported in SocksJS 1.0.0.
And SockJS 1.0.0 will be the default version in Spring Framework 4.2.0.RELEASE, see SPR-12422.


text:
Q: Java VTT parser/validator Are there any open source VTT parser/validators libraries available for java?
We found several for Node and Python

*

*https://www.npmjs.com/package/webvtt

*https://github.com/kickstarter/caption_crunch

*https://www.npmjs.com/package/webvtt


text:
Q: Hats order guide (Spoilers) Last year, it seemed to me that hats were ordered (in the leaderboard) by the effort it took to get them (the rarity of the hat).
I managed to guess the order last year.
How are hats displayed in the leaderboard this year? If it is still by difficulty, can someone list the order below?
E.g.: The R-E-S-P-E-C-T is always before The Stallman but The Stallman is always before the 3 hats.

A: SPOILERS BELOW
Feel free to edit.

*

*Oh the Horror

*Mr. Binx

*Eureka

*Before It Was Cool

*The Milliner

*The Question

*I See Your Point

*I'm not listening

*Marauder

*Robocop

*Full House

*IG-88

*Sock Puppet

*Make It Rain

*Archaeologist

*Ghost of Winterbash Past

*Bounty Hunter

*Conspiracy Theorist

*R-E-S-P-E-C-T

*Winter Is Coming

*Peanut Gallery

*Chatty Chatty

*The Stallman

*Boater

*Upboated

*Reanimated

*Mr Peanut Monopoly McDuck

*Defender of the Realm

*Florence Nightingale

*Johnny Three-hats

*Link to the Past

*Hello, World!

*Do the Swim

*UpDo

*Chuck Yeager

*Frosty the Snowman

*Passed Judgement

*Hi Ho Silver

*With Great Power

*L'chaim

*Old Hat
This is a first draft of my guesses.
I haven't placed:

*

*

*

*"First!"

*

*Ho Ho Ho

*Lonesome Cowboy

*

*
Because I don't see a pattern yet.
Also please note that some of the highest hats are placed there randomly but on top because I haven't seen a hat that comes before them yet.


text:
Q: ASPXAUTH cookie not being set by WebSecurity.Login I'm working on an MVC4/EF5 project.  I've released a live copy which is working fine online, but on my development copy logging on is no longer working.  WebSecurity.Login is returning true and I've traced it through my custom membership provider's ValidateUser function, which is also returning true, but when I then check Controller.User.Identity.Name, it is an empty string!?
This was definitely not happening before.  I have made several changes to my model, including the user class which my custom membership provider uses.  I've also changed the transforms on the web.config for publishing, changed the database initialiser and set automatic migrations on, but I can't see how any of this stuff could be affecting it.  I could work back through all my changes and revert until it works, but I'd really rather avoid that if I can.  Hoping someone else can shed some light on it before I have to go that far?
EDIT: The ASPXAUTH cookie is not being set - I assume that this is the cause of the problem.  Not sure why that should be though

A: Managed to pin it down - looks like the User.Identity.Name property hadn't updated after Login and I have some logic that automatically logs out invalid users


text:
Q: Unsuccessfully POST requests to an API I am using the python requests module to send a post request to the BestBuy API to add a product to the cart. But the request is loading until it times out.
My code:
import requests
payload={"items":[{"skuId":"5712666"}]}
headers = {'user-agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like
Gecko) Chrome/74.0.3729.169 Safari/537.36'}
requests.post('https://www.bestbuy.com/cart/api/v1/addToCart', data=payload, headers=headers)

You can find the request-response on the BestBuy site when you press add to cart.
I think it may be the access-control-allow-origin: https://www.bestbuy.com which blocks my request, but I am not 100% sure, I am kind of new. Any workarounds?


text:
Q: Ввести 3 вещественных числа. Вывести на экран разность максимального и минимального чисел из введенных Написал вот такой вот код, но все работает не так, как надо, в чем может быть проблема? Буду рад если кто-то именно объяснят в чем дело.
function asd(a, b, c){

    if(a>b && a>c){
        if(b<c){
            var sum = a - b;
        }else if(b>c){
            var sum = a - c;
        }
    }else if(b>a && b>c){
        if(a<c){
            var sum = b - a;
        }else if(a>c){
            var sum = b - c;
        }
    }else if(c>a && c>b){
        if(a<b){
            var sum = c - a;
        }else if(a>b){
            var sum = c - b;
        }
    }
    alert(sum);
}

A: На первый взгляд ваша функция возвращает нужный результат (максимальное число минус минимальное). Не совсем понимаю, что вы подразуменваете под словами - "работает не так как надо".
На мой взгляд слишком много вложенности проверок, а так же вы всё время внутри каждой проверки пересоздаёте переменную sum. Её для удобства можно вынести за передлы проверок, а внутри перезаписывать, вместо создания каждый раз заново.
Я бы порекомендовала воспользоваться нативными методами, вот таким образом:
    function asd(a, b, c) {
    let max = Math.max(a, b, c);
    let min = Math.min(a, b, c);
    return sum = (max - min);
    }

A: Можно доработать метод и действовать следующими способами:

*

*Получить массив из arguments, отсортировать его и вычесть из последнего элемента первый.

*Сразу передавать на вход массив из чисел, отсортировать его и вычесть из последнего элемента первый.
Данный подход позволяет в будущем увеличить количество вводимых чисел при необходимости.

function asd(a, b, c) {
  const args = [...arguments].sort((a, b) => a - b);
  return args[args.length - 1] - args[0];
}

console.log(asd(3, 2, 1));
console.log(asd(3, 2, 1, 78, 3, 434, 2));

function asdFromArray(arr) {
  const args = arr.sort((a, b) => a - b);
  return args[args.length - 1] - args[0];
}

console.log(asdFromArray([3, 2, 1]));
console.log(asdFromArray([3, 2, 1, 78, 3, 434, 2]));
console.log(asdFromArray([-10, 2, 1]));
console.log(asdFromArray([-10, -2]));


text:
Q: Hazelcast EntryProcessor not working for CompactSerialization I am trying to use EntryProcessor with CompactSerialization with Hazelcast 5.2 version but getting below error:
Hazelcast.Protocol.RemoteException: 'com.hazelcast.internal.serialization.impl.compact.DeserializedGenericRecord cannot be cast to com.hazelcast.map.EntryProcessor'
Can you please help and guide me what am I missing here? Is there anything need to configure from hazelcast.config side?
My .NET Client side:
public class MyTest
{
    public int ID { get; set; }
    public bool IsGroupLevel { get; set; }
    public int ItemFormContext { get; set; }
    public MyTest() { }
    public MyTest(int id, bool isGroupLevel, int itemFormContext)
    {
        this.ID = id;
        this.IsGroupLevel = isGroupLevel;
        this.ItemFormContext = itemFormContext;
    }
}
public class MyTestSerializer : ICompactSerializer\<MyTest\>
{
    public string TypeName => "MyTest";

    public MyTest Read(ICompactReader reader)
    {
        var ID = reader.ReadInt32("ID");
        var IsGroupLevel = reader.ReadBoolean("IsGroupLevel");
        var ItemFormContext = reader.ReadInt32("ItemFormContext");
        return new MyTest(ID, IsGroupLevel, ItemFormContext);
    }

    public void Write(ICompactWriter writer, MyTest value)
    {
        writer.WriteInt32("ID", value.ID);
        writer.WriteBoolean("IsGroupLevel", value.IsGroupLevel);
        writer.WriteInt32("ItemFormContext", value.ItemFormContext);
    }
}

public class UpdateEntryProcessor : MyTestSerializer, IEntryProcessor<MyTest>
{
    private MyTest value;
    public UpdateEntryProcessor(MyTest value = null)
    {
        this.value = value;
    }
}

public class Program
{
    //Creating client
    var options = new HazelcastOptionsBuilder()
    .With(args)
    .WithDefault("hazelcast.networking.addresses.0", "\<ip address\>")   //Read Hazelcast server address from config file
    .WithDefault("hazelcast.clustername", "local")
    .WithDefault("hazelcast.socket.receive.buffer.size", "128")
    .WithDefault("hazelcast.socket.client.receive.buffer.size", "128")
    .WithDefault("hazelcast.socket.send.buffer.size", "128")
    .Build();
    options.Networking.ReconnectMode = Hazelcast.Networking.ReconnectMode.ReconnectSync;
    options.Serialization.Compact.AddSerializer(new MyTestSerializer());

    IHazelcastClient client = HazelcastClientFactory.StartNewClientAsync(options).GetAwaiter().GetResult();

    var vpmap = client.GetMapAsync\<int, MyTest\>("vpMap").GetAwaiter().GetResult();
    vpmap.SetAsync(1, new MyTest(1, false, 100)).GetAwaiter().GetResult();

    var r1 = vpmap.GetAsync(1).GetAwaiter().GetResult();

    //update using entry processor
    vpmap.ExecuteAsync(new UpdateEntryProcessor(r1), r1.ID).GetAwaiter().GetResult();
}

Can you please help and guide me what am I missing here? Is there anything need to configure from hazelcast.config side?


text:
Q: How to get values from a Column in pandas if another column in same dataframe matches a condition?      Tax_Amount Rate    SGST    CGST    IGST    TDS Tax_Term

0   5697.0  9.0 NaN NaN NaN NaN CGST
1   954.0   9.0 NaN NaN NaN NaN TDS
2   1305.0  9.0 NaN NaN NaN NaN CGST
3   2724.0  9.0 NaN NaN NaN NaN SGST
4   18000.0 9.0 NaN NaN NaN NaN IGST

i Have a Dataframe as above, I want to have the Tax_Amount in all respective column if it matches the Colum Tax_Term.
Expected Output:-
    Tax_Amount  Rate    SGST    CGST    IGST    TDS Tax_Term
0   5697.0  9.0 NaN 5697.0  NaN NaN CGST
1   954.0   9.0 NaN 954.0   NaN 954.0   TDS
2   1305.0  9.0 NaN 1305.0  NaN NaN CGST
3   2724.0  9.0 2724.0  NaN NaN NaN SGST
4   18000.0 9.0 NaN NaN 18000.0 NaN IGST

I tried doing the same with below code however i didn't get the desired result.
final_df['SGST'] = final_df.query('Tax_Term == SGST')['Tax_Amount']
final_df['CGST'] = final_df.query('Tax_Term == CGST')['Tax_Amount']
final_df['IGST'] = final_df.query('Tax_Term == IGST')['Tax_Amount']
final_df['TDS'] = final_df.query('Tax_Term == TDS')['Tax_Amount']

any help will be appretiated.
Thanks.

A: If there are few values in the Tax_Term column, you can simply use a series of assignments using .loc:
final_df.loc[final_df['Tax_Term'] == 'CGST','CGST'] =final_df['Tax_Ammount']
final_df.loc[final_df['Tax_Term'] == 'TDS', 'TDS'] = final_df['Tax_Ammount']
final_df.loc[final_df['Tax_Term'] == 'SGST', 'SGST'] = final_df['Tax_Ammount']
final_df.loc[final_df['Tax_Term'] == 'IGST', 'IGST'] = final_df['Tax_Ammount']

Or, you can create a loop that iterates over unique values in Tax_term:
for term in final_df.Tax_Term.unique():
    final_df.loc[final_df['Tax_Term'] == term,
                 term] = final_df['Tax_Ammount']


text:
Q: Spoken Word Programming Language / System I recently came upon something called Rpoku which is a spoken computer language. I also found some research called Voice Code which takes a different approach. There's a demo video here..
Does this look promising, or is just a toy? Is it or will it be possible to create applications some day without typing at a keyboard?

A: I've been thinking about this one a lot; and I think it would take a paradigm shift (not to mention advances in AI on the scale of Star Trek) to allow programmers to be as productive orally as they are when writing.
For instance, in this simple code example, I'm actually saying a lot more than I'm typing:
List<Employee> ListOfEmployees = new List<Employee>();

foreach (Employee emp in ListOfEmployees) {
Console.WriteLine(emp.Name);
}

In that code block, I'm saying the following:

Create a generic list of employee
  objects, initalize the employee object
  to its default.  After that, I want to
  iterate through the employee objects
  one at a time, and write each one's
  name out to the console.

(I intentionally left out the code to assign the names to the employees -- for simplicity).
It was much faster for me to type out that code than it was to say what I wanted to do, and even if it weren't, there would have to be terms defined for the computer to translate my words into actual code.  Not to mention that this is a very high-level language -- imagine what Perl (or C) would look like if spoken?

A: I, for one, think that it's a horrible idea.  For spoken language to make sense and be easier it actually has to be somewhat free-form.  In the end all it'll result in is trying to figure out what is grammatically acceptable for the "compiler" to actually do what I want, and in the it'll be just as "technical" as languages are today, except more of a wolf in sheep's clothing.
Maybe I'd give it a shot if I wanted to drive myself to suicide :D

A: Probably not. Or at least not yet. The next step would be literate programming and DSL.
May be, but maybe not. We don't want to write more just to let the stakeholder actually understand the software intention. Are we?
Anyway, here's an interesting video about all this.
http://www.infoq.com/presentations/domain-specific-languages

A: Debugging would be annoying at best.
I think you might think more in terms of using a spoken language to drive a program.  If you had a set of high-level functions and data, you could easily say (to steal an example) "Print a list of employee names", as long as Print, List and Employee Names were already defined.


text:
Q: Pandas dataframe ranked by multiple columns (combination key) Is there a pythonic way of sorting the dataframe described below by a combo key - first by ORD_DT_KEY then by ORD_TM_KEY and then by ORD_KEY; and store the rank in another column ORD_RANK?
Code below does not work since it creates 3 separate ranks and throws an error when I try to assign it to single column.
import pandas as pd

#Read orders data stored in a pipe delimeted file
df_raw_orders = pd.read_table("Dummy_order_data.txt", delimiter="|")

print df_raw_orders.head()

df_sorted_orders = df_raw_orders
cols = ['ORD_DT_KEY','ORD_TM_KEY','ORD_KEY']
df_sorted_orders['ORD_RANK'] = df_sorted_orders[cols].rank(method='dense')

Input data, Dummy_order_data.txt, is as below:
ORD_KEY|ORD_DT_KEY|ORD_TM_KEY|QTY|SKU_KEY
10001|1|0|1|1
10001|1|0|1|2
10001|1|0|1|3
10002|2|0|1|1
10002|2|0|1|3
10003|3|0|1|4
10004|4|0|1|4
10004|4|0|1|5
10005|5|0|1|1
10006|6|0|1|1
10006|6|0|1|4
10007|7|0|1|3
10007|7|0|1|4
10008|8|0|1|5
10009|9|0|1|1
10009|9|0|1|4
10009|9|0|1|5
10010|10|0|2|1
10010|10|0|2|2
10010|10|0|2|3
10011|11|0|1|1
10011|11|0|1|3
10012|12|0|1|4
10012|12|0|1|5
10013|13|0|1|1
10014|14|0|2|1
10014|14|0|2|4

Required output:
ORD_KEY ORD_DT_KEY  ORD_TM_KEY  SKU_KEY QTY ORD_RANK
10001   1   0   1   1   1
10001   1   0   2   1   1
10001   1   0   3   1   1
10002   2   0   1   1   2
10002   2   0   3   1   2
10003   3   0   4   1   3
10004   4   0   4   1   4
10004   4   0   5   1   4
10005   5   0   1   1   5
10006   6   0   1   1   6
10006   6   0   4   1   6
10007   7   0   3   1   7
10007   7   0   4   1   7
10008   8   0   5   1   8
10009   9   0   1   1   9
10009   9   0   4   1   9
10009   9   0   5   1   9
10010   10  0   1   2   10
10010   10  0   2   2   10
10010   10  0   3   2   10
10011   11  0   1   1   11
10011   11  0   3   1   11
10012   12  0   4   1   12
10012   12  0   5   1   12
10013   13  0   1   1   13
10014   14  0   1   2   14
10014   14  0   4   2   14

A: Cause in your left there return 3 columns so you have to assign those back two 3 columns rather than one
for x in cols:
    df[x + 'rank'] = df[x].rank(method='dense')


text:
Q: Django views.py CreateView I'm currently doing my second Django project and I want to know something about views.py
in my first project I had classes that had the field:
model = 'name model'
or
form_class = 'name form'
some of them had both
and now in my second project I have class that has:
form_class = forms.UserCreateForm
How should I know which one should I use - from forms or from models and why this time Django won't let me do:
  form_class = UserCreateForm
and needs this 'forms.'

A: I think you have to take back the bases of Django.
What's the best way to start learning django?
You have to learn what is the difference between a model, a view, a form and a template.

A: You can import the form itself.
from django.contrib.auth.forms import UserCreationForm

class MyCreateView(CreateView):
   form_class = UserCreationForm

Or you can import the forms module, in which case you need to use forms.UserCreationForm.
from django.contrib.auth import forms

class MyCreateView(CreateView):
   form_class = forms.UserCreationForm

Personally, I think the first is clearer. It is very common to do from django import forms, which would clash with the second import. You could avoid this clash by importing it as auth_forms:
from django.contrib.auth import forms as auth_forms

class MyCreateView(CreateView):
   form_class = auth_forms.UserCreationForm


text:
Q: C Language Standard Collections Where Are They? I have committed to learning C now, I'm good with Python/PHP/Bash but I've decided I'm limited by not being fluent in C.  However I cannot imagine working in a language without lists and hashes, maybe I'm just jumping a gun, but surely there are 'standard' collection libraries.  I do not see any in the GNU standard lib though, any suggestions?

A: There is no standard, but there is a superb alternative that is far simpler than glib: Dave Hanson's C Interfaces and Implementations.  It includes several efficient collection abstractions and a number of other useful modules.  The software is free, and the book is worth buying.

A: Maybe you should try looking into glib. While it's not a standard in the same sense as STL for C++ it's a proven library and is used in a lot of applications.
http://library.gnome.org/devel/glib/2.22/

A: There is no "standard" set of collection classes for C. Many people simply roll their own as needed.
But of course, there are some libraries filling this gap. For example, glib offers linked lists, hashtables and various kinds of trees.

A: C is lower level than you're used to.  There are no standard collections in C outside of the array.

A: Depending on your system, you may find what you're looking for in sys/queue.h, which includes "implementations of singly-linked lists, doubly-linked lists, simple queues, and tail queues".

A: The cdcontainers interface is similar to C ++ STL
https://github.com/maksimandrianov/cdcontainers
#define CDC_USE_SHORT_NAMES  // for short names (functions and structs without prefix cdc_*)
#include <cdcontainers/vector.h>
#include <cdcontainers/casts.h>
#include <stdio.h>

int main(int argc, char** argv)
{
    vector_t *v;
    size_t i;

    if (vector_ctor(&v, NULL) != CDC_STATUS_OK)
        /* error handling */;

    if (vector_push_back(v, CDC_INT_TO_PTR(7)) != CDC_STATUS_OK)
        /* error handling */;

    if (vector_push_back(v, CDC_INT_TO_PTR(8)) != CDC_STATUS_OK)
        /* error handling */;

    for (i = 0; i < vector_size(v); ++i)
        printf("%i ", CDC_PTR_TO_INT(vector_get(v, i)));

    printf("\n");

    vector_dtor(v);

    return 0;
}

A: There aren't really standard collections in C.  Being a very low-level language (compared to C++ and more "modern" languages)
C++ adds these via the Standard Template Library.  Most of the "collections" such as hashing and lists are based on object oriented or generic programming techniques unavailable (other than via convention) in C.

A: There are no "standard" (as in part of the ISO C standard) container libraries, at least not as of C99.  I've seen several third-party attempts; all had some degree of lossage or another.
C has a very primitive and meager toolkit; I've compared programming in C to building a house with nothing but a handsaw and a claw hammer.


text:
Q: How can I overwrite an existing map in Automapper This is driving me nuts... I have been trying to pass a variable to a custom resolver, but it seems impossible to do.
I am currently using the following approach, but the value that is passed to the Custom Resolvers constructor is always an empty string "" even though I specifically register a new mapping to overwrite the existing one (See controller)
Custom Resolver
public class DueDateResolver :  ValueResolver<Task, string>
{

    public string DateFormat = "MMM dd, @ h:mm tt";

    public DueDateResolver(string dateFormat)
    {
        // If no date format is passed use the default
        if (!String.IsNullOrEmpty(dateFormat))
        {
            DateFormat = dateFormat;
        }
    }
}

Controller
// <summary>
    /// Ajax Method for filtering tasks by Date Range
    /// </summary>
    /// <param name="dateFilter">The date filter label ["Day", "Week", "Month", "All", "Last 30 Days"]</param>
    /// <returns>List of task objects</returns>
    [HttpGet]
    public JsonResult GetTasksByDateRange(DateFilters dateFilter)
    {
        RegisterMaps.RegisterTaskViewModel(dateFilter.ToString());

        List<Task> tasks = taskService.GetFilteredTasksByDate(dateFilter, "chobojunk@gmail.com");
        List<TaskTableViewModel> viewModelList = Mapper.Map<List<Task>, List<TaskTableViewModel>>(tasks);

        return Json(viewModelList, JsonRequestBehavior.AllowGet);
    }

Mappings
The Register() method is done at the global.asa level. The other method above is called in my controller.
/// <summary>
    /// Special case where I need to pass in a parameter
    /// </summary>
    public static void RegisterTaskViewModel(string dateFilter)
    {
        Mapper.CreateMap<Task, TaskTableViewModel>().ForMember(dest => dest.DueDate,
                                                     opt => opt.ResolveUsing<DueDateResolver>().ConstructedBy(() => new DueDateResolver(dateFilter)));
    }

    public static void Register()
    {
        Mapper.CreateMap<Task, TaskTableViewModel>().ForMember(dest => dest.DueDate,
                                                  opt => opt.ResolveUsing<DueDateResolver>().ConstructedBy(() => new DueDateResolver("")));
}

A: I would create the mapping once then leave it alone.  Create a context object with your resolver parameter, use DI/IoC to inject it into the resolver, and update it from the controller before executing the mapper.


text:
Q: SVN frequently says file is locked by me in another working copy I have an SVN repository (hosted on Dreamhost) with needs-lock set on binary files. It sometimes happen that, while committing files locked and modified by me, the commit fails with the error:
Error: Commit failed (details follow):
Error: File '/my/file.bin' is locked in
Error:  another working copy

If I try to get the lock on that file (without stealing it) it says:
Error: Path '/my/file.bin' is already locked by user
Error:  'my_username' in filesystem '/home/user1/svn/repo1/db'

Cleanup doesn't help, so the only way to solve this is to steal the lock, and then the commit succeedes.
This is not a critical issue, but it is really annoying, especially when it happens in the middle of a long commit.
I am inclined to think that this is caused by a bug of the client or the server, since I am sure that I'm not using other working copies, and the issue happens fairly frequently (3 times in the last two days) to me and my colleagues using the repository.
We are using TortoiseSVN 1.8.4, while the Dreamhost svn server is 1.6.12.
Thanks for any help.
UPDATE: I noticed that the error happens if I do an update of my working copy before committing (which gives no error and of course does not modify the locked files). By checking the status of the file, before the update tortoise says it is locked by me (checking only locally), while after the update checking locally it gives "????" as locking state, and by checking the server it then says it is locked by me. After the update the file is made read-only (because of the needs-lock), even if it is still marked as modified. So the sequence of actions is: lock file.bin -> modify file.bin -> update the whole working copy -> commit -> commit failed error. After the update the working copy seems to forget the state of the lock, and when it asks the server it believes it is locked on another working copy.

A: On Windows, I fixed the problem by the following steps:
1. Launch Repository Browser by clicking "Repo-browser" in the menu.
2. Locate the locked file.
3. Right click your mouse on the locked file.
4. Click "break lock".

A: Cleanup will not help. That's used for working copy locks, whereas you're running into an issue with files being locked in the repository itself as a means of implementing a mutex between users. See The Three Meanings of "Lock"
You probably have a client that's locking the file(s) for you in a different working copy without your knowledge (either locally or in a WC on your server), or perhaps you've got a WebDAV share that you've mounted and are opening the file(s) there which is causing a lock to be created.

A: I also encountered the same problem and found that out of three machines, in one of the machine I have locked the file and due to which I also facing the problem. What I did is release the lock from that machine and proceed further.
OR
Steal the lock first and then start working as this is the best option provided by SVN.

A: If using a JetBrains IDE:
right click on the file you want to unlock, go to Subversion and click lock
then select checkbox steal existing lock and apply with OK
right click on that file again, go to Subversion and click unlock
If using command line:
lock the file with --force
svn lock --force path/to/file.ext

and unlock it again
svn unlock path/to/file.ext

A: Found this: https://groups.google.com/forum/#!topic/subversion_users/wZikmNEubz4
It seems this problem manifests when using an svn 1.8 client and a server prior to 1.6.17:
when updating the root folder of a working copy, my locks get broken (regardless of the needs-lock flag).
I downgraded to a 1.7.14 client and the problem does not occur.


text:
Q: I can't see my application on google play I have just published my application ( 1 hour ago ) . And I can't find it anywhere I have tried the manual link https://play.google.com/store/apps/details?id=com.combucalc but i get nothing.
Any ideeas? Where can I mail them ?

A: It takes a little bit of time. It used to be a lot faster (instant), but lately it takes about 2-3 hours. Give it a while, it will show up.

A: Normally it will take a few hours until the app is available. For my last app it took 9 hours until it was online. It was very long, indeed... Your app will be online soon.

A: You'll need to wait a few more hours in all likelihood. The process used to be faster. About a year ago I remember publishing an app and it showing in under an hour. A couple months ago I published another app and it took about 5 hours to show up.
It's also worth noting that if your app title has any punctuation marks in it (most likely a comma), you may want to try searching for the app title in quotation marks. For example, a friend recently published Run, Tweet, Run. It took over a week for a search with the query Run, Tweet, Run to come back successful. However, if you explicitly searched with quotes around the title, as in "Run, Tweet, Run" you'd get a hit.
Good luck. It'll be up in no time. And remember, Google has the fastest publishing process of all major app stores: Apple takes about a week, Amazon takes 2-4 days, Microsoft takes 3+ days. So a few hours really isn't that bad.


text:
Q: Magento - E-mail is blank after updating template We are changing our e-mail templates in Magento. And after changing them, for some reason, the entire e-mail is blank. The only thing we changed is the order of the items and the HTML itself.
We did NOT change any other file, only this one.
Anybody any idea what is going wrong?
PS: we are running Magento 1.4.0.1, upgrading is not an option atm.
Thanks in Advance.
OLD FILE:

Beste {{var order.getCustomerName()}},

                    Bedankt voor uw bestelling bij Company. Gedurende uw bestelling wordt u op de hoogte gehouden van de laatste ontwikkeling van uw status.
                        U kunt de status van uw bestelling controleren door  in te loggen op uw account.

Uw bestelling #{{var order.increment_id}} (geplaatst op {{var order.getCreatedAtFormated('long')}})

                            Factuurgegevens:

                            Betaalmethode:

                                {{var order.getBillingAddress().format('html')}}

                                {{var payment_html}}

                    {{depend order.getIsNotVirtual()}}

                            Verzendinformatie:

                            Verzendmethode:

                                {{var order.getShippingAddress().format('html')}}

                                {{var order.getShippingDescription()}}

                    {{/depend}}
                    {{layout handle="sales_email_order_items" order=$order}}

                    {{var items_html}}

                    {{var order.getEmailCustomerNote()}}

Wij hopen dat er naar tevredenheid word behandeld en zien u graag in de toekomst terug bij een volgende bestelling bij Company.

Heeft u nog vragen? Stuur dan een e-mail naar bestelinfo@url.nl

Met vriendelijke groet,

NEW FILE:

    Companyname

    Street 28

    1234 AB City

    030-1234567
    info@url.nl
    www.url.nl

    Beste {{var order.getCustomerName()}},

    Bedankt voor uw bestelling bij Company. Gedurende uw bestelling wordt u op de hoogte gehouden van de laatste ontwikkeling van de status van uw bestelling. U kunt de status van uw bestelling altijd zelf in de gaten houden door  in te loggen op uw account.

        Uw bestelling #{{var order.increment_id}}
        (geplaatst op {{var order.getCreatedAtFormated('long')}})

        {{layout handle="sales_email_order_items" order=$order}}

        {{var items_html}}

    {{var order.getEmailCustomerNote()}}

        Factuuradres:

        Verzendadres:

        Betaalwijze:

        {{var order.getBillingAddress().format('html')}}

        {{var order.getShippingAddress().format('html')}}

        {{var payment_html}}

    {{depend order.getIsNotVirtual()}}

        Verzendwijze:

        {{var order.getShippingDescription()}}

    {{/depend}}

    Wij hopen dat er naar tevredenheid word behandeld en zien u graag in de toekomst terug bij een volgende bestelling bij Company.

    Heeft u vragen? Neem gerust contact met ons op:

      · Website: via het contactformulier. mail ons

      · Telefoon: 010-752351 (van maandag t/m vrijdag tussen 8.30 en 17.00 uur)

A: Chtck file encoding. Must be UTF-8


text:
Q: Cannot run another ajax while long polling? I'm trying to make a simple chat app on web, using long polling & php.
Mainly I have 2 ajax functions on the client,
1. update : to update the chat messages.
2. send : to send message the user enters.
The update function do a long polling, which is to wait until for 10 seconds or until new message is available.
The send function writes to a database.
My problem is, while the update function is running (long polling), the send function cannot run. And only after the update function has finished running, then the send function runs. Is this an expected behaviour or there is something wrong with my code?
If u want to see the web u can access it here : http://tedhost.awardspace.us
And if u're lazy to sign up u can use username dummy0 and password 123456
Here is the code..Sorry if my code is messy..
The ajax code : http://tedhost.awardspace.us/ajax.js
update_chat.php
<?php
session_start();
$filename = "wew.xt";
$user = $_SESSION["user"];
$last = $_SESSION["lmsgtime"];

if (file_exists($filename)) {
    $lama = 0;
    $mulai = time();
    do {
        $fin = fopen($filename, "r");
        $current = 0;
        fscanf($fin, "%d", $current);
        fclose($fin);
        usleep(10000);
        $akhir = time();
    } while($current <= $last && $akhir - $mulai <= 10);
}
include "con.php";
mysql_select_db($dbname, $con);
$sql = "SELECT * FROM chats WHERE time > '$last' ORDER BY time ASC";
$res = mysql_query($sql);
/*
$lama = 0;
while (mysql_num_rows($res) <= 0 && $lama <= 10000000) {
    $res = mysql_query($sql);
    usleep(500);
    $lama += 500;
}
*/
if (!$res)
    die("error");
$out = "";
while($row = mysql_fetch_array($res)) {
    $out = $out . "
";
    $out = $out . date("(h:i:s) ", $row["time"]);
    $out = $out . $row["user"];
    $out = $out . ": " . stripslashes($row["data"]);
    $out = $out . "
";
    $last = $row["time"];
}
$_SESSION["lmsgtime"] = $last;
echo $out;
?>

send.php
<?php
$time = time();
session_start();
include "con.php";
$data = mysql_real_escape_string($_GET["msg"]);
$user = mysql_real_escape_string($_SESSION["user"]);
mysql_select_db($dbname, $con);
$sql = "INSERT INTO chats VALUES ('$time', '$user', '$data')";
$res = mysql_query($sql);
if (!$res)
    die("err");
else
    echo "ok";
$lho = fopen("wew.xt", "w");
fprintf($lho, "%d\n", $time);
fclose($lho);
?>

A: If you're using the default session handler then only one script can have the session open at a time, as only one thing can write to a session file at a time otherwise corruption may occur.
It is possible that you can get around this problem by calling session_write_close as soon as possible in your scripts.  In the case of scripts that only read session data you should be able to call it straight after session_start.  In the case of scripts that make changes to the session, you'll have to call it immediately after the last change to the session you make.
While using session_write_close means that any subsequent changes you make to $_SESSION won't be saved, the $_SESSION array will still be accessible and contain the values last loaded from the session.
http://www.php.net/session_write_close has the relevant information.


text:
Q: How do I write a LINQ Expression Tree that filters on a method of a property? So I have a collection of objects with properties on it:
ParentObject parentObj
{
    string SomeProperty1
    string SomeProperty2
}

Before querying on these properties, they need to be made ToLower() and Trim(). I understand that I can do:
Expression.Call(pe, typeof(string).GetMethod("Trim", Type.EmptyTypes)); // Or ToLower

And
Expression.Property(pe, typeof(string).GetProperty("SomeProperty1"));

But how do I combine them?
I need something to the equivalent of
from query in parentObjCollection
where query.SomeProperty1.Trim() == "asdf"
select query

Any thoughts?

A: Expression.Property returns an expression itself, you can use that as the first parameter of the call (full example):
var parent = new ParentObject{ SomeProperty1 = "    test" };
var pe = Expression.Constant(parent);
var property = Expression.Property(pe, typeof(ParentObject).GetProperty("SomeProperty1"));
var call = Expression.Call(property, typeof(string).GetMethod("Trim", Type.EmptyTypes));

var result = Expression.Lambda(call).Compile().DynamicInvoke();

Console.WriteLine(result); // -> "test"

Note that I had to modify your Expression.Property call.


text:
Q: Die that never rolls the same number consecutively Suppose we have a "magic" die $[1-6]$ that never rolls the same number consecutively.
That means you will never find the same number repeated in a row.
Now let's suppose that we roll this die $1000$ times.
How can I find the PDF, expected number of times and variance of getting a specific value?

A: Getting a precise answer is possible, but not very enlightening (it would be very complicated, with a thousand terms to compute), so I'll focus on two approximate results: the law of large numbers, and the central limit theorem. With $1000$ throws on such a simple system, they are bound to be quite accurate.
To begin with, let's say that we throw a standard die a large number $N$ of times.
The standard die
Let $(X_n)_{n \geq 0}$ be the successive results of the die, which take their values in $\{1, \ldots, 6\}$. Then the $X_n$ are independent, and identically distributed (each has a probability of $1/6$ to yield any given number).
Let $f : \{1, \ldots, 6\} \to \mathbb{R}$ an observable. Then the sequence $(f(X_n))_{n \geq 0}$ is also a sequence of independent and identically distributed random variables. Put $S_N f := \sum_{k=0}^{N-1} f(X_k)$. For instance, if we take:

*

*$f(x) = 1_{x=4}$: then $S_N f$ is the number of times we get the number $4$ in the first $N$ throws.

*$f(x) = x$: then $S_N f$ is the sum of the first $N$ throws.
Since the expectation is linear,
$$\mathbb{E} (S_N f) = \mathbb{E} \left(\sum_{k=0}^{N-1} f(X_k)\right) = \sum_{k=0}^{N-1} \mathbb{E} \left(f(X_k)\right) = N\mathbb{E} \left(f(X_0)\right).$$
But that only deals with the average value of $S_N f$. Since $f$ is bounded, and thus integrable, the (weak) law of large numbers asserts that, in distribution,
$$\lim_{N \to + \infty} \frac{S_N f}{N} =\mathbb{E} \left(f(X_0)\right).$$
This gives you a first order result. This is not completely satisfactory; for instance, if $\mathbb{E} \left(f(X_0)\right) = 0$, this law tells us that the sum grows sub-linearly. We may want something more precise, which gives us a non degenerate limit distribution. Since $f$ is bounded, it is square-integrable, and we may apply the central limit theorem:
$$\lim_{N \to + \infty} \frac{S_N f-N\mathbb{E} \left(f(X_0)\right)}{\sqrt{N}} = \sigma(f) \mathcal{N},$$
where the convergence is in distribution, $\mathcal{N}$ is a standard centered Gaussian, $\overline{f} = f-\mathbb{E} (f)$, and:
$$\sigma(f)^2 = \mathbb{E} (\overline{f}^2) = \frac{1}{6} \sum_{k=1}^6 \overline{f}(k)^2,$$
For instance, if $f(x) = 1_{x=4}$, we get:
$$\lim_{N \to + \infty} \frac{S_N f}{N} = \frac{1}{6},$$
so roughly $1/6$th of the throws yield a $4$, and:
$$\lim_{N \to + \infty} \frac{S_N f-N/6}{\sqrt{N}} = \frac{\sqrt{5}}{6} \mathcal{N},$$
which tells us for instance that the number of $4$, with probability $0.95$, will be in the interval $[N/6-\sqrt{5N}/3, N/6+\sqrt{5N}/3]$. For $N = 1000$ throws, this is the interval $[143,190]$.
The magical die
I'll now show how these results apply to the magical die. However, I won't prove what I assert, because it tends to be quite high level (I do this in a graduate course, typically).
I'll assume that the die is fair: for the first throw, the $6$ possible outcomes are equally likely,
and for each throw past the first, the $5$ possible outcomes are also equally likely. The first remark is that, for any given throw,
$$\mathbb{P} (X_n = 1) = \ldots = \mathbb{P} (X_n = 6) = \frac{1}{6}.$$
This is because, if you relabel the faces of the die, it doesn't change the law of the sequence of throws, so at each throw, all the outcomes are equally likely.
The sequence $(X_n)_{n \geq 0}$ is then a stationary Markov chain: for all $n$, the throw $X_{n+1}$ depends only on $X_n$. I may encode it into the following matrix:
$$P:= \left(\begin{matrix}
 0  & 1/5 & 1/5 & 1/5 & 1/5 & 1/5 \\
1/5 &  0  & 1/5 & 1/5 & 1/5 & 1/5 \\
1/5 & 1/5 &  0  & 1/5 & 1/5 & 1/5 \\
1/5 & 1/5 & 1/5 &  0  & 1/5 & 1/5 \\
1/5 & 1/5 & 1/5 & 1/5 &  0  & 1/5 \\
1/5 & 1/5 & 1/5 & 1/5 & 1/5 &  0
\end{matrix}\right)$$
The coefficient $P_{ij}$ is the probability that, given that the die is currently on $i$, the next throw yields $j$. So $P_{ii} = 0$ for all $i$, and $P_{ij} = 1/5$ otherwise.
This Markov chain is finite-state (there are six possible states), transitive (starting from any state $i$, I can get to any state $j$ in two steps), and aperiodic (given any two states $i$ and $j$,
I can go from $i$ to $j$ in $n$ steps, for all $n \geq 2$ - in other words, if you give me two possible outcomes of the die, I can see these possible outcomes $n$ throws apart, as long as $n \geq 2).
Let $f : \{1, \ldots, 6\} \to \mathbb{R}$ be an observation. Then the sequence $(f(X_n))_{n \geq 0}$ is still identically distributed (since the $X_n$ are identically distributed), but these random variables
are no longer independent. Knowing $f(X_n)$ tends to constrain severely $f(X_{n+1})$: if $f$ is injective, then $f(X_{n+1}) \neq f(X_n)$. However, what will save us is that the dependence decays very fast:
knowing $f(X_n)$ gives a lot of information on $f(X_{n+1})$, but very little on, say, $f(X_{n+10})$. And this influence decay exponentially fast. In other words, if the first throw is $1$,
you can say reliably that the second throw won't be $1$, but there is not much you can say on the tenth or twentieth throw.
Given an observable $f$, note that we still have:
$$\mathbb{E} (S_N f) = \mathbb{E} \left(\sum_{k=0}^{N-1} f(X_k)\right) = N\mathbb{E} \left(f(X_0)\right),$$
because this argument only uses the stationarity of the process. We also still have a law of large numbers, in distribution,
$$\lim_{N \to + \infty} \frac{S_N f}{N} =\mathbb{E} \left(f(X_0)\right).$$
So the law of large number is still as simple, and is a consequence of Birkhoff's theorem
and the transitivity of the Markov chain. Now, we also have a central limit theorem, but it is more complicated. Indeed,
$$\lim_{N \to + \infty} \frac{S_N f-N\mathbb{E} \left(f(X_0)\right)}{\sqrt{N}} = \sigma_{GK} (f) \mathcal{N},$$
where the convergence is in distribution, $\mathcal{N}$ is a standard centered Gaussian, $\overline{f} = f-\mathbb{E} (f)$ and:
$$\sigma_{GK} (f)^2 = \mathbb{E} (\overline{f}^2) + 2 \sum_{n=1}^{+ \infty} \mathbb{E} (\overline{f} (X_0) \overline{f}(X_n)).$$
the main change is the formula for the variance, which is given by Green-Kubo's formula.
Now, how do we compute this thing? An observable $f$ is essentially the same thing as an element of $\mathbb{R}^6$; for instance, $1_{x=4} = (0, 0, 0, 0, 1, 0)$. Now, one can prove that, for any functions $f$ and $g$,
$$\mathbb{E} (f (X_0) g(X_n)) = \mathbb{E} (f (X_0) (P^n) g (X_0)) = \frac{1}{6} \sum_{k=1}^6 f(k) (P^n) g (k),$$
and thanksfully, $P^n$ is easy to compute. If we write $A := P+I/5$ the $6 \times 6$ matrix whose coefficients are all $1/5$, then $A^k = (6/5)^{k-1} A$ for $k \geq 1$, so that:
$$P^n = \left( A-\frac{I}{5} \right)^n
= \sum_{k=0}^n \binom{n}{k} A^k \left( - \frac{1}{5} \right)^{n-k}
= \frac{5}{6} \sum_{k=0}^n \binom{n}{k} \left(\frac{6}{5} \right)^k \left( - \frac{1}{5} \right)^{n-k} A - \frac{5}{6}\left( - \frac{1}{5} \right)^n A+ \left( - \frac{1}{5} \right)^n I
= A - \frac{5}{6}\left( - \frac{1}{5} \right)^n A+ \left( - \frac{1}{5} \right)^n I.$$
In addition, if $\mathbb{E} (f (X_0)) = 0$, then $Af = 0$. This is the case for $\overline{f}$. Hence,
$$P^n \overline{f} = \left( - \frac{1}{5} \right)^n \overline {f},$$
so that:
$$\sigma_{GK} (f)^2
= \mathbb{E} (\overline{f}^2) + 2 \sum_{n=1}^{+ \infty} \mathbb{E} (\overline{f} (X_0) (P^n \overline{f})(X_0))
= \mathbb{E} (\overline{f}^2) + 2 \sum_{n=1}^{+ \infty} \left( - \frac{1}{5} \right)^n \mathbb{E} (\overline{f}^2)
= \left( 1+2 \sum_{n=1}^{+ \infty} \left( - \frac{1}{5} \right)^n\right) \mathbb{E} (\overline{f}^2)
=  \frac{2}{3} \sigma (f)^2.$$
For instance, if $f(x) = 1_{x=4}$, we get:
$$\lim_{N \to + \infty} \frac{S_N f}{N} = \frac{1}{6},$$
so roughly $1/6$th of the throws yield a $4$, and:
$$\lim_{N \to + \infty} \frac{S_N f-N/6}{\sqrt{N}} = \frac{\sqrt{10}}{6 \sqrt{3}} \mathcal{N},$$
which tells us for instance that the number of $4$, with probability $0.95$, will be in the interval $[N/6-\sqrt{10N}/(3\sqrt{3}), N/6+\sqrt{10N}/(3\sqrt{3})]$. For $N = 1000$ throws, this is the interval $[147,186]$.
What happens is that, if $f(X_n)$ is large, then since $X_{n+1} \neq X_n$, $f(X_{n+1})$ tends to be smaller. Large increments are immediately followed by smaller increments,
and small increments are immediatly followed by larger increments. This phenomenon tends to reduce the spread of $S_N f$, which explains that the results are slighly more concentrated with the magical die than with a standard die.

A: let $P_{k,n}$ be the probability to get $k$ times the result "1" in $n$ throws, and let $$P_{k,n} = p_{k,n} + q_{k,n}$$ where $p,q$ are the corresponding probabilities where you add the constraint that you finish with a 1 (for $p$) or anything but 1 (for $q$).
It is easy to get the equations (for $n \ge 1$) :
 $$5p_{k,n} = q_{k-1,n-1}$$ and $$5q_{k,n} = 5p_{k,n-1} + 4 q_{k,n-1}$$
from which you get that for $n \ge 2$, $$5q_{k,n} = q_{k-1,n-2} + 4q_{k,n-1}$$
Obviously, the $(p_{k,n})$ family satisfies the same linear equation, and since $P$ is the sum of $p$ and $q$, we have for $n \ge2$, that $$5P_{k,n} = P_{k-1,n-2} + 4P_{k,n-1}$$
Together with the data that $P_{0,0} = 1, P_{0,1} = \frac 16, P_{1,1} = \frac 56$ this is enough to determine all those numbers.
Let $f(x,y)$ be the formal power series $$f(x,y)=\sum P_{k,n} x^k y^n$$ From the recurrence on $P$ we immediately have that in $(5-4y-xy^2)f(x,y)$, every coefficient vanish except the coefficients of $x^0y^0, x^0y^1, x^1y^1$, and so that $f(x,y)$ is the power series of the rational fraction $$\frac {30+y+5xy}{6(5-4y-xyy)}$$
We can check that doing the partial evaluation $x=1$ we get $$f(1,y) = \frac {30+6y}{6(5-4y-yy)} = \frac{6(5+y)}{6(5+y)(1-y)} = \frac 1 {1-y} = 1 + y + y^2 + \dots$$so for each $n$, all the probabilities $P_{k,n}$ sum to $1$.

If $E_n$ is the expectation of the number of occurences of 1 in $n$ throws then $$E_n = \sum k P_{k,n}$$so that $$\sum E_n y^n = \frac {df}{dx} (1,y)$$
We compute
$$\frac{ df}{dx} = \frac  {(5y)(5-4y-xyy)-(-yy)(30+y+5xy)}{6(5-4y-xyy)^2}
 = \frac {y(5+y)^2}{6(5-4y-xyy)^2}$$
Then evaluating this at $x=1$ we get $$\sum E_ny^n = \frac {y(5+y)^2}{6(5+y)^2(1-y)^2} = \frac y {6(1-y)^2} = \sum \frac n6 y^n$$
Thus $E_n = n/6$ which is as we expected.

To compute the variance we need to compute the expectancy of the square of the number of occurences,
that is, $F_n = \sum k^2 P_{k,n}$.
Then $$\sum F_n y^n = \frac {d^2f}{dx^2}(1,y) + \frac {df}{dx}(1,y) =
\frac{2y^3(5+y)^2}{6(5+y)^3(1-y)^3} + \frac y{6(1-y)^2} = \frac{2y^3+y(5+y)(1-y)}{6(5+y)(1-y)^3} = \frac{5y-4y^2+y^3}{6(5+y)(1-y)^3}$$
$$\sum E_n^2 y^n = \sum \frac 1{36} n^2y^n = \frac {y(1+y)}{36(1-y)^3}$$
Computing their difference gives the variance :
$$\sum V_n y^n = \frac {30y-24y^2+6y^3-y(1+y)(5+y)} {36(5+y)(1-y)^3}
 = \frac {5y(5-6y+y^2)}{36(5+y)(1-y)^3}
 = \frac {5y(5-y)}{36(5+y)(1-y)^2} \sim_{y=1} \frac {20}{216(1-y)^2}$$
Doing the partial fraction decomposition gives a formula $$V_n = \frac {50}{1296} + \frac{20}{216}n - \frac {50}{1296}(-1/5)^n$$

I expect that after renormalization, your random variable (number of 1s obtained in $n$ throws) converges in law to a gaussian variable as $n \to \infty$.

A: [Assuming the dice is otherwise fair - that is, if you just rolled $x$, the next roll is discrete uniform on $\{1,2,3,4,5,6\}-x$]
Say the rolls are ordered $X_1,X_2,\cdots$ and $x_i\in\{1,2,3,4,5,6\}$ for all $i$. Then the joint pdf is:
$$\mathbb{P}(X_1=x_1, X_2=x_2,\cdots,X_n=x_n)=\frac{1}{6}\left(\frac{1}{5}\right)^{n-1}\prod_{i=1}^{n-1}\mathbb{I}_{\displaystyle\{x_i\neq x_{i+1}\}}$$
and each individual roll has the uniform distribution, i.e.
$$\mathbb{P}(X_n=x_n)=\frac{1}{6}$$
This preserved uniformity is easily proven by induction and conditioning, i.e. working through the relation $\mathbb{P}(X_n)=\mathbb{P}(X_n\vert X_{n-1})\mathbb{P}(X_{n-1})$.

A: Here is some information based upon the Goulden-Jackson Cluster Method.

We consider the set of words $\in \mathcal{V}^{\star}$ of length $n\geq 0$ built from an alphabet $$\mathcal{V}=\{1,2,3,4,5,6\}$$ and the set $B=\{11,22,33,44,55,66\}$ of bad words, which are not allowed to be part of the words we are looking for. We derive a function $f(s)$ with the coefficient of $s^n$ being  the number of wanted words of length $n$.

According to the paper (p.7) the generating function $f(s)$  is
\begin{align*}
f(s)=\frac{1}{1-ds-\text{weight}(\mathcal{C})}\tag{1}
\end{align*}
with $d=|\mathcal{V}|=6$, the size of the alphabet and with the weight-numerator $\mathcal{C}$ with
\begin{align*}
\text{weight}(\mathcal{C})=\text{weight}(\mathcal{C}[11])+\cdots+\text{weight}(\mathcal{C}[66])
\end{align*}

We calculate according to the paper
  \begin{align*}
\text{weight}(\mathcal{C}[11])&=-s^2-\text{weight}(\mathcal{C}[11])s\\
&\cdots\\
\text{weight}(\mathcal{C}[66])&=-s^2-\text{weight}(\mathcal{C}[66])s\\
\end{align*}
  and get
  \begin{align*}
\text{weight}(\mathcal{C}[11])=\cdots=\text{weight}(\mathcal{C}[66])=-\frac{s^2}{1+s}
\end{align*}
It follows
  \begin{align*}
f(s)&=\frac{1}{1-ds-\text{weight}(\mathcal{C})}\\
&=\frac{1}{1-6s+\frac{6s^2}{1+s}}\\
&=\frac{1+s}{1-5s}\\
&=(1+s)\sum_{n\geq 0}5^ns^n\\
&=1+6\sum_{n\geq 1}5^{n-1}s^n\\
&=1+6s+30s^2+150s^3+750s^4+3750s^5+\mathcal{O}(s^6)\tag{2}
\end{align*}
We conclude, the number of sequences of length $n\geq 1$ from $\{1,2,\ldots,6\}$ with no consecutive numbers is $6\cdot 5^{n-1}$.
Since the number of all sequences of length $n$ is $6^n$, the probability for each valid sequence of length $n\geq 1$ is assuming a fair die
  \begin{align*}
\mathbb{P}(\text{valid sequence of length } n)=
\left(\frac{5}{6}\right)^{n-1}\qquad\qquad n\geq  1
\end{align*}

$$ $$

[2016-05-10] Generating function $f(s,u)$ keeping track of a specific digit
With a slight generalisation we can mark all occurrences of a specific digit let's say $6$. We use the variable $u$ to count occurrences of $6$ and derive a generating function $f(s,u)$
  \begin{align*}
f(s,u)=\sum_{n=0}^{\infty}a_{n,k}u^ks^n
\end{align*}
  with $a_{n,k}$ the number of admissible sequences, i.e. containing no bad words from $B$ of length $n$ with exactly $k$ $6$s.

We start similarly as above but additionally mark each occurrence of $6$ with $u$.
\begin{align*}
\text{weight}(\mathcal{C}[11])&=-s^2-\text{weight}(\mathcal{C}[11])s\\
&\cdots\\
\text{weight}(\mathcal{C}[66])&=-\color{blue}{u^2}s^2-\text{weight}(\mathcal{C}[66])\color{blue}{u}s\\
\end{align*}
and get
\begin{align*}
\text{weight}(\mathcal{C}[11])&=\cdots=\text{weight}(\mathcal{C}[55])=-\frac{s^2}{1+s}\\
\text{weight}(\mathcal{C}[66])&=-\frac{\color{blue}{u^2}s^2}{1+\color{blue}{u}s}
\end{align*}

It follows
  \begin{align*}
f(s,u)&=\frac{1}{1-((d-1)+\color{blue}{u})s-\text{weight}(\mathcal{C},\color{blue}{u})}\\
&=\frac{1}{1-(5+\color{blue}{u})s+\frac{5s^2}{1+s}+\frac{\color{blue}{u^2}s^2}{1+\color{blue}{u}s}}\\
&=\frac{(1+s)(1+us)}{1-4s-5us^2}\tag{3}\\
&=1+(5+u)s+10(2+u)s^2+5(16+13u+u^2)s^3\\
&\qquad+10(32+36u+7u^2)s^4+5(256+368u+121u^2+5u^3)s^5+\mathcal{O}(s^6)\tag{4}
\end{align*}

If we take a look e.g. at the coefficient of $s^4$ of the series expansions  (2) and (4) we see the number of admissible sequences of length $4$  is $750$ with
\begin{align*}
&10\left.(32+36u+7u^2)\right|_{u=1}\\
&\qquad=\left.(320+360u+70u^2)\right|_{u=1}\\
&\qquad=750
\end{align*}
The coefficient $70$ is the number of admissible sequences of length $4$ containing exactly two $6s$ and similar interpretations hold for the other summands.

Let $a_{k,n}$ denote the number of admissible sequences of length $n$ containing exactly $k$ $6$s. We use the coefficient of operator $[s^n]$ to denote the coefficient of $s^n$ in a series. We obtain from (3)
  \begin{align*}
a_{k,n}=[u^ks^n]f(s,u)=[u^ks^n]\frac{1+(1+u)s+us^2}{1-4s-5us^2}\\
\end{align*}
Since
  \begin{align*}
[u^ks^n]&\frac{1}{1-4s-5us^2}\\
&=[u^ks^n]\sum_{l=0}^\infty s^l(4+5us)^l\\
&=\sum_{l=0}^n[u^ks^{n-l}]\sum_{j=0}^l\binom{l}{j}(5us)^j4^{l-j}\\
&=\sum_{l=0}^n[u^k]\binom{l}{n-l}(5u)^{n-l}4^{2l-n}\\
&=\binom{n-k}{k}5^k4^{n-2k}
\end{align*}
we obtain
  \begin{align*}
a_{k,n}&=[u^ks^n]\frac{1+(1+u)s+us^2}{1-4s-5us^2}\\
&=[u^ks^n]\left(1+s+us+us^2\right)\frac{1}{1-4s-5us^2}\\
&=\left([u^ks^n]+[u^ks^{n-1}]+[u^{k-1}s^{n-1}]+[u^{k-1}s^{n-2}]\right)\frac{1}{1-4s-5us^2}\\
&=\binom{n-k}{k}5^k4^{n-2k}+\binom{n-k-1}{k}5^k4^{n-1-2k}\\
&\qquad+\binom{n-k}{k-1}5^{k-1}4^{n-2k+1}+\binom{n-k-1}{k-1}5^{k-1}4^{n-2k}\\
&=5^k4^{n-2k}\left(\binom{n-k}{k}+\frac{1}{4}\binom{n-k-1}{k}
+\frac{4}{5}\binom{n-k}{k-1}+\frac{1}{5}\binom{n-k-1}{k-1}\right)\\
&=5^k4^{n-2k}\left(\frac{5}{4}\binom{n-k-1}{k}
+2\binom{n-k-1}{k-1}+\frac{4}{5}\binom{n-k-1}{k-2}\right)\tag{5}
\end{align*}

A small check of (5) gives e.g.
\begin{align*}
a_{5,2}&=5^2\cdot2^2\left(\frac{5}{4}\binom{2}{2}+2\binom{2}{1}+\frac{4}{5}\binom{2}{0}\right)\\
&=100\left(\frac{5}{4}+4+\frac{4}{5}\right)\\
&=125+400+80\\
&=605
\end{align*}
in    accordance with the coefficient   of $u^2s^5$ in (4).

We conclude: The number $a_{1000,k}$ of admissible sequences of length $1000$ containing exactly $k$ $6$s is
  \begin{align*}
5^k4^{1000-2k}
\left(\frac{5}{4}\binom{999-k}{k}+2\binom{999-k}{k-1}+\frac{4}{5}\binom{999-k}{k-2}\right)
\end{align*}

in accordance with a result of @joriki.

A: An impressive array of heavy machinery has been brought to bear on this question. Here's a slightly more pedestrian solution.
The $6\cdot5^{999}$ admissible sequences of rolls are equiprobable, so we need to count how many of them contain $k$ occurrences of a given number, say, $6$.
Let $a_{jn}$ be the number of admissible sequences of length $n$ with exactly $j$ $6$s that begin and end with a non-$6$. Fix a non-$6$ at the beginning, glue a non-$6$ to the right of each of the $j$ $6$s and choose $j$ slots for the resulting glued blocks out of $n-j-1$ objects ($j$ glued blocks and $n-2j-1$ unglued non-$6$s). There are $5^{j+1}4^{n-2j-1}$ options for the non-$6$s, so that makes
$$
a_{jn}=\frac54\cdot4^n\left(\frac5{16}\right)^j\binom{n-j-1}j
$$
sequences.
A sequence with $k$ $6$s can begin and end with non-$6$s, for a contribution of $a_{k,1000}$, begin with a $6$ and end with a non-$6$ or vice versa, for a contribution of $2a_{k-1,999}$, or begin and end with a $6$, for a contribution of $a_{k-2,998}$, for a total of
$$
a_{k,1000}+2a_{k-1,999}+a_{k-2,998}=4^{1000}\left(\frac5{16}\right)^k\left(\frac54\binom{999-k}k+2\binom{999-k}{k-1}+\frac45\binom{999-k}{k-2}\right)\;.
$$
Dividing by the total number of admissible sequences yields the probability of rolling $k$ $6$s:
$$
\frac56\left(\frac45\right)^{1000}\left(\frac5{16}\right)^k\left(\frac54\binom{999-k}k+2\binom{999-k}{k-1}+\frac45\binom{999-k}{k-2}\right)\;.
$$
We could use this to calculate the expectation and variance, but this is more easily done using the linearity of expectation.
By symmetry, the expected number of $6$s rolled is $\frac{1000}6=\frac{500}3=166.\overline6$.
With $X_i$ denoting the indicator variable for the $i$-th roll being a $6$, the variance is
\begin{align}
\operatorname{Var}\left(\sum_iX_i\right)
&=
\mathbb E\left(\left(\sum_iX_i\right)^2\right)-\mathbb E\left(\sum_iX_i\right)^2
\\
&=
1000\left(\frac16-\frac1{36}\right)+2\sum_{i\lt j}\left(\textsf{Pr}(X_i=1\land X_j=1)-\textsf{Pr}(X_i=1)\textsf{Pr}(X_j=1)\right)
\\
&=
1000\left(\frac16-\frac1{36}\right)+2\sum_{i\lt j}\textsf{Pr}(X_i=1)\left(\textsf{Pr}(X_j=1\mid X_i=1)-\textsf{Pr}(X_j=1)\right)\;.
\end{align}
The conditional probability $p_{j-i}=\textsf{Pr}(X_j=1\mid X_i=1)$ depends only on $j-i$; it satisfies $p_{k+1}=\frac15(1-p_k)$ and has initial value $p_1=0$, with solution $p_k=\frac{1-\left(-\frac15\right)^{k-1}}6$. Thus
\begin{align}
\operatorname{Var}\left(\sum_iX_i\right)
&=
1000\left(\frac16-\frac1{36}\right)-\frac1{18}\sum_{k=1}^{999}(1000-k)\left(-\frac15\right)^{k-1}
\\
&=
1000\left(\frac16-\frac1{36}\right)-\frac1{18}\cdot\frac{25}{36}\left(\frac65\cdot1000-1+\left(-\frac15\right)^{1000}\right)
\\
&=\frac{60025-5^{-998}}{648}
\\
&\approx\frac{60025}{648}
\\
&\approx92.63\;,
\end{align}
in agreement with mercio's result.

A: I just did a simple simulation for $1,000$ valid rolls $10,000$ times (to get a good average) and got the following average (absolute value) difference from the expected results of a fair die (which is $166.667$ of each of the $6$ numbers)
$1$: $~~7.7098$
$2$: $~~7.6851$
$3$: $~~7.7798$
$4$: $~~7.5926$
$5$: $~~7.6609$
$6$: $~~7.5286$
Interestingly, if I do the same simulation but for a fair die, I get:
$1$: $~~9.3069$
$2$: $~~9.4111$
$3$: $~~9.4203$
$4$: $~~9.4153$
$5$: $~~9.4366$
$6$: $~~9.3795$
I do not know why this is.


text:
Q: Is Console.log() and process.stdout.write different? if console.log is just process.stdout.write with a line-break at the end, then Why do I get nothing printed when I use process.stdout.write but I get answer in console.log() for the following code.
var waittime = 3000;
var currenttime = 0;
var waitint = 10;

function percentage(p) {
    process.stdout.clearLine();
    process.stdout.cursorTo(0);
    process.stdout.write(`waiting ... ${p}%`);
}

var interval = setInterval(function() {
    currenttime += waitint;
    percent = Math.floor((currenttime / waittime) * 100);
    percentage(percent);
}, waitint);

setTimeout(function() {
    clearInterval(interval);
    percentage(100);
    process.stdout.write("\nGowtham");
}, waittime);

process.stdout.write("\nIt's not getting displayed");
//console.log("It's getting displayed here!");

What's wrong?
There is a difference I guess. Correct me if I'm wrong.

A: Please take some time to analyse step by step what process.stdout.* methods are called in your code.
First thing that's called is the last line:
process.stdout.write("\nIt's not getting displayed");

This prints out your message.
Right after that, Node executes the setInterval callback, which contains the percentage() call. There, the first call is:
process.stdout.clearLine();

So your output is printed and immediately removed. console.log() appends a newline character to the output, so the process.stdout.clearLine(); affects an empty line after your message.
If you want your code to work, add a newline to your output string:
process.stdout.write("\nNow it's getting displayed, duh!\n");


text:
Q: Is there any way to access an outer scope's variable once the present scope has defined one of the same name? It would seem not:
function o(){
  var v = 1;
  function i(){
    var v = 2;
    // any way at all, now, to access the 1 value?
  }
}

But is there?

A: No, within i the v symbol completely shadows the v in o, and there's no other way to get at it. With that code, there's no way for i to get at o's v.
Of course, if you used different names for the variables, that problem goes away. :-)

If instead of o you had code at global scope, you could access v as a property of the global object, because when you declare a variable globally, it becomes a property of the global object. For instance, this would work in loose mode:
var v = 1;
function i() {
    var v = 2;
    console.log("v == " + v);
    console.log("this.v == " + this.v);
}
i(); // Calling it like this makes `this` within the call the global object

Which would show
v == 2;
this.v == 1
That wouldn't work in strict mode, though, because this would be undefined within i.
On browsers, the global object has a property, window, it uses to refer to itself, so you wouldn't have to rely on this as with the above:
// Browsers only
var v = 1;
function i() {
    var v = 2;
    console.log("v == " + v);
    console.log("window.v == " + window.v);
}
i();

That works in either strict or loose mode, but only in browsers.
But global scope is a special case. For the code you quoted, no, there's no way to get there.


text:
Q: ValueError: x and y must have same first dimension, but have shapes (420,) and (19,) estava realizando este codigo y al querer correrlo me sale el error de: ValueError: x and y must have same first dimension, but have shapes (420,) and (19,), alguna sugerencia para corregirlo.
import matplotlib.pyplot as plt
import numpy as np
import math

velocidad_de_stall = 21.26
velocidad_maxima = 60
peso = 140

n_max = round((2.1+(24000/(peso+10000))),2)
print(n_max)
n_max_margen = 1.5*n_max
print(n_max_margen)
n_min = round(-.4*(n_max),2)
print(n_min)
n_min_margen = 1.5*n_min
print(n_min_margen)
velocidad_maxima_stall = 140*1.5

x = list(np.arange(0,velocidad_maxima_stall,0.5))
y = list(np.arange(n_min_margen,n_max_margen,0.5))
# x1 = velocidad_de_stall* np.sqrt(x)

plt.plot(x,y)
plt.grid()
plt.xlabel('Velocidad (m/s)')
plt.ylabel('Load Factor')
plt.title('V-n')
plt.show()

A: Hay dos problemas

*

*Tienes que pasarle a matplotlib arrays, no listas. Para ello simplemente queda la parte de tú código así:

x = np.arange(0,velocidad_maxima_stall,0.5))
y = np.arange(n_min_margen,n_max_margen,0.5))

*El vector x y el vector y tienen que tener el mismo tamaño. Tú vector x tiene 420 datos, mientras que el y tiene 19. Para representar un punto en un gráfico, siempre necesitas saber para cada punto cual es su valor en el eje de abscisas y cual es su valor en el eje de ordenadas.


text:
Q: How-to: Dockerfile layer(s) reuse / reference I want to create a few images where each dockerfile will include some common layers. Its all mixed and no consistent sequence for all of the images.
E.g. some will need to have java on them, and I want to define the below lines (taken from the official java 8 dockerfile) as a building block (layer) that will be referenced in other dockerfiles.
In some cases it could be more than one layer that I would want to reuse - making this requirement recursive in nature (building blocks constructed of building blocks).
RUN \
    echo oracle-java8-installer shared/accepted-oracle-license-v1-1 select true | debconf-set-selections && \
    add-apt-repository -y ppa:webupd8team/java && \
    apt-get update && \
    apt-get install -y oracle-java8-installer && \
    rm -rf /var/lib/apt/lists/* && \
    rm -rf /var/cache/oracle-jdk8-installer

Is that supported by Docker today? Is it a good practice to install e.g. Java separately as a layer that way ... or should I merge it with other installs (to keep the image minimal)? What are the best practices around such a scenario please?
=========== UPDATE ==============
Seems like the feature of referencing/including is not supported. But I am still not sure about the best practices ...
@Sri pointed out below to the best practices:
https://docs.docker.com/engine/userguide/eng-image/dockerfile_best-practices/#run
Where is it encouraged to use "RUN apt-get update && apt-get install -y" for all package installation.
But does it also mean that we are not encouraged to use different layers for different packages? like the below example:
RUN apt-get update && apt-get install -y package-foo
RUN apt-get update && apt-get install -y package-bar

A: Based on further reading:

*

*There is no INCLUDE like feature currently. https://github.com/docker/docker/issues/735

*Best practices encourage to use "RUN apt-get update && apt-get install -y" for all package installation. But it doesn't mean that you can not use that same technique to separate package installs (e.g. package-foo and package-bar) due to maintainability. It is a tradeoff with minimizing the number of layers. https://docs.docker.com/engine/userguide/eng-image/dockerfile_best-practices/#/minimize-the-number-of-layers (see also how the build cache operates, identifying it as different layers)
Thank you @Sri for some lead pointers.

A: Docker has the concept of base image. This can be provided in the Dockerfile as "FROM < base-image >". This should be the first line in the Dockerfile. The base image can contain all the commons and individual containers can deal with specific functionalities.


text:
Q: what might be causing this to fill this treeview multiple times? I found this code online. It works, but for some reason it loads the file directory twice.
namespace DockSample.Controls
{
    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Windows.Forms;
    using System.IO;
    using System.Drawing;
    using Microsoft.VisualBasic.FileIO;
    using DockSample;

    //TODO: Add options for filtering by robot
       public class SolutionExplorer : TreeView
        {

            public SolutionExplorer()
            {
                this.BeforeExpand += customBeforeExpand;
                this.Nodes.Clear();
                CreateTree(this);
            }

            private bool CreateTree(TreeView treeView)
            {

                bool returnValue = false;

                try
                {
                    // Create Desktop
                    TreeNode desktop = new TreeNode();
                  //  desktop.Text = "Desktop";
                  //  desktop.Tag = "Desktop";
                  //  desktop.Nodes.Add("");
                  //  treeView.Nodes.Add(desktop);
                    // Get driveInfo
                    foreach (DriveInfo drv in DriveInfo.GetDrives())
                    {

                        TreeNode fChild = new TreeNode();
                        if (drv.DriveType == DriveType.CDRom)
                        {
                            fChild.ImageIndex = 1;
                            fChild.SelectedImageIndex = 1;
                        }
                        else if (drv.DriveType == DriveType.Fixed)
                        {
                            fChild.ImageIndex = 0;
                            fChild.SelectedImageIndex = 0;
                        }
                        fChild.Text = drv.Name;
                        fChild.Nodes.Add("");
                        treeView.Nodes.Add(fChild);
                        returnValue = true;
                    }

                }
                catch
                {
                    returnValue = false;
                }
                return returnValue;

            }

            /* Method :EnumerateDirectory
            * Author : Chandana Subasinghe
            * Date : 10/03/2006
            * Discription : This is use to Enumerate directories and files
            *
            */
            public TreeNode EnumerateDirectory(TreeNode parentNode, List<string> thisFilter)
            {

                try
                {
                    DirectoryInfo rootDir;

                    // To fill Desktop
                    Char[] arr = { '\\' };
                    string[] nameList = parentNode.FullPath.Split(arr);
                    string path = "";

                    if (nameList.GetValue(0).ToString() == "Desktop")
                    {
                        path = SpecialDirectories.Desktop + "\\";

                        for (int i = 1; i < nameList.Length; i++)
                        {
                            path = path + nameList[i] + "\\";
                        }

                        rootDir = new DirectoryInfo(path);
                    }
                    // for other Directories
                    else
                    {

                        rootDir = new DirectoryInfo(parentNode.FullPath + "\\");
                    }

                    parentNode.Nodes[0].Remove();
                    foreach (DirectoryInfo dir in rootDir.GetDirectories())
                    {

                        TreeNode node = new TreeNode();
                        node.Text = dir.Name;
                        node.Nodes.Add("");
                        parentNode.Nodes.Add(node);
                    }
                    //Fill files
                    foreach (FileInfo file in rootDir.GetFiles())
                    {
                        if (isValidFilter(getExtention(file.Name)))
                        {
                            TreeNode node = new TreeNode();
                            node.Text = file.Name;
                            node.ImageIndex = 2;
                            node.SelectedImageIndex = 2;
                            parentNode.Nodes.Add(node);
                        }
                    }

                }

                catch
                {
                }

                return parentNode;
            }
            private bool isValidFilter(string ext)
            {
                bool result = false;
                foreach(string s in filter)
                {
                    if (ext == s)
                        result =  true;

                }

                return result;
            }
            private string getExtention(string filename)
            {
                return filename.Substring(filename.IndexOf("."));
            }
            private void customBeforeExpand(object sender, TreeViewCancelEventArgs e)
            {
                if (e.Node.Nodes[0].Text == "")
                {
                    TreeNode node = this.EnumerateDirectory(e.Node,filter);
                }
            }
            private List<string> filter = new List<string>();
            public List<string> Filter
            {
                get { return filter; }
                set { filter = value; }
            }
            private void InitializeComponent()
            {
                this.SuspendLayout();
                this.ResumeLayout(false);

            }
        }

}

A: The constructor of your control runs at both design time and run time.  So as soon as you drop the control on the form, it will fill the tree view.  Problem is, the nodes will be serialized to InitializeComponent().  Take a look at the Designer.cs file for your form, you'll find them back there.  When you run the form, the constructor runs again, doubling the list.
You need to prevent the constructor from adding the nodes at design time.  That's a bit difficult to do, you'd normally use the DesignMode property but it isn't set to true yet in the constructor.  Do it like this instead:
protected override void OnHandleCreated(EventArgs e) {
    base.OnHandleCreated(e);
    if (!DesignMode && treeView.Nodes.Count == 0) {
        CreateTree(this);
    }
}

Or do it explicitly by adding a public method that you call in the form's constructor or OnLoad method.  Which is rather wise, you might want to catch exceptions.  Always likely when you tinker with the file system.


text:
Q: How to convert and update the string values in my double linked list into uppercase letters?
*

*Say I have the following values in the double linked list: "Orange,
banana, PEAR".

*How can I successfully convert each of those strings    into:
"ORANGE, BANANA, PEAR".

The for loop I used to convert the lowercase char to uppercase char is supposed to run until it reaches the null char of the string in head->data, and then check if its a lowercase converting it to an upper case by substracting the char at that index by 32 to get the uppercase ASCII value of the lowercase char. A friend suggested to type cast it, but even then it won't fully execute it kept giving me same output. So I'm stuck as to what could be the issue. Any help is appreciated or suggestions.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

//My node structure
struct node
{
    char* data;
    struct node *prev;
    struct node *next;
};

//Declared two global variables
struct node* head = NULL;
struct node* tail = NULL;

// Function to insert at the front
// of the linked list
void insertAtEnd(char* data) {
    //Create a new node
    struct node *newNode = (struct node*)malloc(sizeof(struct node));
    newNode->data = data;

    //If list is empty
    if(head == NULL) {
        //Both head and tail will point to newNode
        head = tail = newNode;
        //head's previous will point to NULL
        head->prev = NULL;
        //tail's next will point to NULL, as it is the last node of the list
        tail->next = NULL;
    }
    else {
        //newNode will be added after tail such that tail's next will point to newNode
        tail->next = newNode;
        //newNode's previous will point to tail
        newNode->prev = tail;
        //newNode will become new tail
        tail = newNode;
        //As it is last node, tail's next will point to NULL
        tail->next = NULL;
    }
}

// The traverse list function
void traverse()
{
    // List is empty
    if (head == NULL) {
        printf("\nList is empty\n");
        return;
    }
    // Else print the Data
    struct node* temp;
    temp = head;
    while (temp != NULL) {
        printf("%s\n", temp->data);
        temp = temp->next;
    }
}

int main(int argc, char **argv){

insertAtEnd("Orange");
insertAtEnd("banana");
insertAtEnd("PEAR");

//converting each char in head->data into uppercase letter.
    for (int i = 0; head->data[i]!='\0'; i++) {
        printf("Entered outer loop\n");
        if((int)head->data[i] >= 97 && (int)head->data[i] <= 122) {
            head->data[i] = (char)(((int)head->data[i]) - 32);
            printf("Entered inner loop\n");
        }
    }

    traverse();

}

Expected output(after attempting to convert each char to uppercase and calling traverse()):
ORANGE
BANANA
PEAR

Actual output:
Entered outer loop

Edit: joined all the code together for better reproduction and readability. My goal overall is to get to update the strings saved in the double linked list to become fully uppercase without using the uppercase function. Hence, that is why I ended up trying to use that for loop which supposedly uses the ASCII values in the table as reference to convert from lowercase to uppercase. However, when I run it for some reason it is not executing

A: You pass const char* to data so you can't convert it, you should write like this:
struct node* tmp = head;
while(tmp) {
    tmp->data = strdup(tmp->data);
    for (int i = 0; tmp->data[i]!='\0'; i++) {
        if(tmp->data[i] >= 97 && tmp->data[i] <= 122) {
            tmp->data[i] = tmp->data[i] - 32;
        }
    }
    tmp = tmp->next;
}
traverse();

And you no need to cast char to int, char can be used like an integer


text:
Q: filter out rolling mean results with limited data I am trying to calculate the rolling mean of a time series. I have no problems with the calculation, however, looking at the results, there are locations along the time series where the rolling mean occurs based on one or two values surrounded by a long series of missing values. I would like the rolling average to only occur when greater than 50% of the data within the width of the time frame for with the rolling average is performed. If less than 50% of the data is available, then the result for that index should be NaN.
I wrote some example code to hopefully demonstrate what I am trying to accomplish.
#Create example data
set.seed(12)
dat1=runif(20,min=0,max=10)
dat2=dat1
ind=which(dat2 %in% sample(dat2,5))
#in this case ind=c(4, 7, 8, 13, 16)
dat2[ind]=NA

dat3=dat1
ind2=which(dat3 %in% sample(dat3,12))
#in this case ind2=c(2, 5, 7, 8, 9, 10, 11, 12, 13, 14, 17, 18)
dat3[ind2]=NA

#create a time series
now <- Sys.time()
tseq <- seq(from = now, length.out = 20, by = "mins")

#data in zoo format
dat1=zoo(dat1,tseq)
dat2=zoo(dat2,tseq)
dat3=zoo(dat3,tseq)

#rolling mean using roll apply
dat1rollmean=rollapply(dat1,width=5,align='center',FUN=function(x) mean(x,na.rm=T))
dat2rollmean=rollapply(dat2,width=5,align='center',FUN=function(x) mean(x,na.rm=T))
dat3rollmean=rollapply(dat3,width=5,align='center',FUN=function(x) mean(x,na.rm=T))

#doesn't work
dat3newrollmean=rollmean(dat3,5)

#desired rolling mean result
dat2des=dat2rollmean
dat2des[4]=NaN

dat3des=dat3rollmean
dat3des[c(4:14)]=NaN

In this example, dat1 is a complete dataset for which my rollapply (width of 5) function works well, dat2 and dat3 have different levels of missing data. I would want my result in this case to replace any points in which the rollapply is performed on less than 2 points of data with NaN. That would be index 4 for dat2rollmean and indexes 4-14 for dat3rollmean. How would I write a function to find these instances of insufficient data and replace the resulting rolling mean result with NaN?

A: Use Mean defined below:
Mean <- function(x) if (sum(is.na(x)) < length(x) / 2) mean(x, na.rm = TRUE) else NaN

res1 <- rollapply(dat1, 5, Mean)
identical(res1, dat1rollmean)
## [1] TRUE

res2 <- rollapply(dat2, 5, Mean)
identical(res2, dat2des)
## [1] TRUE

res3 <- rollapply(dat3, 5, Mean)
identical(res3, dat3des)
## [1] TRUE


text:
Q: For which a the matrix is positive-definite We have $A=\begin{pmatrix}a&2\\ 2&a+1\end{pmatrix}$
And I want to know for which a the matrix is positive-definite.
So our requirement is $det(A)\ge0$
$(a*(a+1))-4\ge0$
$a^2+a-4\ge0$
I understand that in the points $\frac{-1+\sqrt{17}}{2},\frac{-1-\sqrt{17}}{2}$ the function are equal to zero.
Is it true to say that because the function is equal to zero in the points so $ ∀a>\frac{-1+\sqrt{17}}{2},\frac{-1-\sqrt{17}}{2}$
$a^2+a-4\ge0$?

A: You can prove a matrix is positive definite by checking if the determinant of all of its leading minors are greater then 0.
$$\begin{vmatrix} a\end{vmatrix}>0 \iff a>0 \space\space\space(1)$$
$$\begin{vmatrix}
a & 2 \\
2 & a+1
\end{vmatrix} = a^2+a-4$$
$$a^2+a-4>0 \iff a>\frac{-1+\sqrt{17}}{2} \space\space\space OR \space\space\space\space a<\frac{-1-\sqrt{17}}{2}\space\space\space\space\space(2)$$
From $(1)$ and $(2)$ we can get that A is positive definite for any $a>\frac{-1+\sqrt{17}}{2}$

A: The last step is to note that since $a^2+a-4=(a-(-1+\sqrt{17})/2)(a-(-1-\sqrt{17})/2)$, we have that it is positive precisely on $(-\infty,(-1-\sqrt{17})/2)\cup((-1+\sqrt{17})/2,\infty)$.


text:
Q: How to fix semaphore timeout error in my python program? Traceback (most recent call last):
  File "websockets\legacy\protocol.py", line 968, in transfer_data
  File "websockets\legacy\protocol.py", line 1038, in read_message
  File "websockets\legacy\protocol.py", line 1113, in read_data_frame
  File "websockets\legacy\protocol.py", line 1170, in read_frame
  File "websockets\legacy\framing.py", line 69, in read
  File "asyncio\streams.py", line 728, in readexactly
  File "asyncio\streams.py", line 522, in _wait_for_data
  File "asyncio\proactor_events.py", line 286, in _loop_reading
  File "asyncio\windows_events.py", line 841, in _poll
  File "asyncio\windows_events.py", line 489, in finish_recv
OSError: [WinError 121] The semaphore timeout has been reached

The error occures when the program runs for a longer time (around 90 minutes)
The callbackfunction gets called every 60 seconds around 500 times.
from polygon import websocket
from polygon.websocket.models import WebSocketMessage
from typing import List

c = websocket.WebSocketClient(
        api_key='***',
        feed='delayed.polygon.io',
        market='stocks',
        subscriptions=["A*"]

    )

def handle_msg(msgs: List[WebSocketMessage]):

    with open("C:/Users/user/Desktop/bot/stream.txt", "a") as file:
        for m in msgs:
            file.write(str(m) + "\n")

def main():
    c.run(handle_msg)

main()

I have never seen this kind of error and it somehow only happens when I run the code on a certain machine, but it still bothers me.


text:
Q: How to perform a dump from a Python script in Rethinkdb As described in https://www.rethinkdb.com/docs/backup/, when using the command line, it is possible to create a backup of a Rethinkdatabase using the command
rethinkdb dump
I'm interested in doing something similar from within a Python script, not from the command line. How can this be achieved?
As an example, consider the following code from the ten-minute introduction to RethinkDB:
import rethinkdb as r
r.connect("localhost", 28015).repl()
r.db("test").table_drop("authors").run()        # This line is included in case the script has already been run before
r.db("test").table_create("authors").run()

r.table("authors").insert([
    { "name": "William Adama", "tv_show": "Battlestar Galactica",
      "posts": [
        {"title": "Decommissioning speech", "content": "The Cylon War is long over..."},
        {"title": "We are at war", "content": "Moments ago, this ship received..."},
        {"title": "The new Earth", "content": "The discoveries of the past few days..."}
      ]
    },
    { "name": "Laura Roslin", "tv_show": "Battlestar Galactica",
      "posts": [
        {"title": "The oath of office", "content": "I, Laura Roslin, ..."},
        {"title": "They look like us", "content": "The Cylons have the ability..."}
      ]
    },
    { "name": "Jean-Luc Picard", "tv_show": "Star Trek TNG",
      "posts": [
        {"title": "Civil rights", "content": "There are some words I've known since..."}
      ]
    }
]).run()

cursor = r.table("authors").run()
for document in cursor:
    print(document)

Running this script produces the following standard output:
{u'tv_show': u'Battlestar Galactica', u'posts': [{u'content': u'The Cylon War is long over...', u'title': u'Decommissioning speech'}, {u'content': u'Moments ago, this ship received...', u'title': u'We are at war'}, {u'content': u'The discoveries of the past few days...', u'title': u'The new Earth'}], u'id': u'cc5f79c4-230b-4f6d-a642-db124c2ca9ad', u'name': u'William Adama'}
{u'tv_show': u'Star Trek TNG', u'posts': [{u'content': u"There are some words I've known since...", u'title': u'Civil rights'}], u'id': u'dd8b9963-34af-429d-8993-1c6be007367d', u'name': u'Jean-Luc Picard'}
{u'tv_show': u'Battlestar Galactica', u'posts': [{u'content': u'I, Laura Roslin, ...', u'title': u'The oath of office'}, {u'content': u'The Cylons have the ability...', u'title': u'They look like us'}], u'id': u'f3641355-282d-4fd6-ada6-1459246c054f', u'name': u'Laura Roslin'}

I'd like to write this data to a JSON file from within the Python script.


text:
Q: setting password for excel file when export from android app I am working on export feature from my application. I have to export my DB data as excel sheet.
I need to set password for my excel file.
I am using ApachePOI library to take db data and add to excel sheet.
The library also supports adding password. I have used the code to do it. But my export file is successful. but if I try to open it, it doesn't prompt me for the password.
Code:
 Biff8EncryptionKey.setCurrentUserPassword("password");
HSSFWorkbook hwb = new HSSFWorkbook();
HSSFSheet sheet = hwb.createSheet("new sheet");

HSSFRow row = sheet.createRow(count);
HSSFCell cell = row.createCell(0);
cell.setCellValue(nextLine[0]);

FileOutputStream fileOut = new FileOutputStream(outFilePath);
hwb.writeProtectWorkbook(Biff8EncryptionKey.getCurrentUserPassword(), "");
hwb.write(fileOut);

I don't know if I am doing something wrong in the password code section.
Kindly let me know how to enable password lock for the excel file. Any help on using the APachePOI library would be helpful for me.
Any one help me with some sample code for adding password protection to excel sheet.