text:
Q: How to fix a memory error when filtering a dataframe? I get a memory error while doing a simple filtering on a dataframe. Never had this issue before until windows 10 was reinstalled on my laptop.
I tried a workaround from Unable to allocate array with shape and data type, and changed the page file size. Besides I reinstalled my 32-bit python with 64-bit python.
My csv file is not super huge, around 600 MB, my RAM is 16 GB. My code:
df = pd.read_csv('file.csv')
quant = df['a'].quantile(0.995)
df = df[df['a']<quant]

In the end I get this error MemoryError: Unable to allocate 171. MiB for an array with shape (3, 7483698) and data type float64
What is the nature of this issue and how to fix it?

A: Using dask data frame can split your data frame into smaller pandas dataframe across your cpu cores. This will enable parallel computing before dask combine the result.
import dask.dataframe as dd
#Run dask.read_csv() which is quite similar to pandas.read_csv
df = dd.read_csv('file.csv')
#Use — .compute() — to initiate calculation
df = df[ df['a'] < dd['a'].quantile(0.995) ].compute()
#The output from using .compute() is a pandas dataframe
df

Source:

*

*https://docs.dask.org/en/latest/dataframe.html

A: So basically the answer is to properly uninstall Python 32-bit and install Python 64-bit.


text:
Q: How to store a base 2 number in a register? but my instructor is not responding. I have an extra credit question for a MIPS program as follows:
Extra credit covers binary to ASCII data type conversion. It is useful
to convert the 2's complement integer into an ASCII string so that it
can be displayed on the monitor. Derive a binary-to-ASCII conversion
routine, BinarytoASCII, for converting a 2's complement integer stored
in a0 register into an ASCII string stored in v0 register. The value
initially in a0 is restricted to be within the range -999 to +999. After
the algorithm completes execution, v0 contains the sign of the value
initially stored in a0. The following three bytes contain the three
ASCII codes corresponding to the three decimal digits representing its
magnitude. This algorithm always produces a string of four characters
independent of the sign and magnitude of the integer being converted.

Maybe I am not reading this problem correctly, but is it not impossible to store a binary value directly into a register in MIPS? It seems as though this is asking for a decimal to ASCII conversion. If I am wrong can you show how to place a base-2 number into register in MIPS? thank you

A: Numbers in registers are in binary.  This is why a 32-bit register can store signed values from -2^31 .. 2^31-1, using 2's complement encoding.  https://en.wikipedia.org/wiki/Two%27s_complement
If the native storage format in a register was decimal, bit-shifts left and right would multiply/divide by powers of 10, not powers of 2.

Encoding is separate from value.  Given a bit-pattern of 0b11111111111111111111110000011001 in a 32-bit register, you can describe / represent the encoded value as

*

*-999 decimal, interpreting it as signed 2's complement

*0xfffffc19 unsigned hex

*037777776031 octal

*0b11111111111111111111110000011001 binary

These are all the same number, just different ways of expressing either the mathematical value (as a negative decimal number), or the 2's complement bit-pattern (hex, octal and binary).
Usually hex is only used to describe the bit-pattern, so you wouldn't usually see a negative hex number like -0x3e7.

It's a common misunderstanding that numbers in registers or memory are "in hex".  Hex is a serialization format for binary numbers, allowing them to be stored as text in a human-readable format.  A number is only in hex if it's stored as a sequence of ASCII characters.
An ASCII string of decimal digits is another way to serialize numbers, and that's what you're being asked to do here.
Hex and decimal are commonly used in asm source code, but the assembler will assemble your numbers into 32-bit binary words.  (Or 16-bit immediates as part of the instruction stream, for something like addiu $t0, $t1, 0x1234)
You can talk about a binary number's value using hex, but it's actually stored as base 2 bits.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Error importing a custom class from a module in the current location I have a file called blogtag.py as follows
from .base import Base
from sqlalchemy import Column, Integer, String, schema, Sequence, Boolean
from sqlalchemy.orm import relationship
from .blogpost import Blogpost

class Tag(Base):
    """Tag model."""

    __tablename__ = 'tag'

    tag_id_seq = Sequence('tag_id_seq', metadata=Base.metadata)
    id = Column("id",Integer, tag_id_seq,server_default=tag_id_seq.next_value(), primary_key=True)
    name = Column('name', String)
    isactive = Column('isactive', Boolean)
    postList = relationship(Blogpost, secondary="posttag")

and another file in the same location , called blogpost.py which looks like this as follows
from .base import Base
import datetime
from sqlalchemy import Column, ForeignKey, Integer, String, Sequence, Boolean, Text, DateTime
from sqlalchemy.orm import relationship
from .image import Image
from .blogtag import Tag

class Blogpost(Base):
    """Post model."""

    __tablename__ = 'post'

    post_id_seq = Sequence('post_id_seq', metadata=Base.metadata)
    id = Column("id",Integer, post_id_seq,server_default=post_id_seq.next_value(), primary_key=True)
    title = Column('title', String)
    imageList = relationship(Image, backref="post")
    tagList = relationship(Tag, secondary="posttag")

Now , everytime I try to run my setup.py which imports both the files, I keep getting this error
 File "blogtag.py", line 4, in <module>
    from .blogpost import Blogpost
ImportError: cannot import name 'Blogpost'

Can you please let me know what might be happening here please ?
Thanks

A: This is a case of circular import. In general, circular imports are the sign of bad design.
in module blogpost.py
from .blogtag import Tag

You are importing Tag class which forces the python interpreter to first load blogtag module.
Then in blogtag.py
from .blogpost import Blogpost

which again tells interpreter to load Blogpost class first. But interpreter already have been to the blogpost module and Blogpost class is yet not loaded into memory. So interpreter says that there is no class Blogpost in blogpost.py
To solve this issue, the best solution is to remove mapping statements and create a mapping model for Tag and Blogpost
module blogtag.py
from .base import Base
from sqlalchemy import Column, Integer, String, schema, Sequence, Boolean
from sqlalchemy.orm import relationship

class Tag(Base):
    """Tag model."""

    __tablename__ = 'tag'

    tag_id_seq = Sequence('tag_id_seq', metadata=Base.metadata)
    id = Column("id",Integer, tag_id_seq,server_default=tag_id_seq.next_value(), primary_key=True)
    name = Column('name', String)
    isactive = Column('isactive', Boolean)

module blogpost.py
from .base import Base
import datetime
from sqlalchemy import Column, ForeignKey, Integer, String, Sequence, Boolean, Text, DateTime
from sqlalchemy.orm import relationship
from .image import Image

class Blogpost(Base):
    """Post model."""

    __tablename__ = 'post'

    post_id_seq = Sequence('post_id_seq', metadata=Base.metadata)
    id = Column("id",Integer, post_id_seq,server_default=post_id_seq.next_value(), primary_key=True)
    title = Column('title', String)
    imageList = relationship(Image, backref="post")

mapping module tag_blogpost_mapping.py
from sqlalchemy.orm import relationship

from .base import Base
from .blogtag import Tag
from .blogpost import Blogpost

class BlogpostTagMapping(Base):
    tag = relationship(Tag)
    blogpost = relationship(Blogpost)


text:
Q: Migrating NextJS static site to squarespace/cms I've just started working with NextJs and I'm currently in the process of migrating an existing static site over to squarespace for easier editing. I've managed to migrate static html/css/svg assets, but am unsure how to move js files across in the _next/static/chunks/ folder.
I've tried manually linking these files but keep getting minified js errors with no detailed information. Just wondering if there is a better/recommended way to move things across?


text:
Q: how to use "setFieldHint" in CRUD form? I want to add hint to the CRUD form but I receive error.
 $temp_crud->getElement('pin')->setFieldHint('the hint');

A: simply add this to your Model:
$this->addField('my_field')->hint('this hint will show on the form');

Alternatively you can do
if($temp_crud->form) {
    $temp_crud->form->getElement('pin')->setFieldHint('the hint');
}


text:
Q: Issue with form submission I used the following code....

    <% String loginstatus=request.getParameter("loginstatus");
       String option=request.getParameter("option");
        //out.println(option);
%>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>LOGIN PAGE</title>
    <link href="style/style.css" rel="stylesheet" type="text/css" />

        <%
           Connection con;

           Statement stmt;

       ResultSet rs;

            System.out.print("Oracle data base connectivity.......");

    try{

                Class.forName("oracle.jdbc.driver.OracleDriver");

                    con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","sfts","sfts");

                    stmt=con.createStatement();

                    System.out.println("Success");

                    session.setAttribute("connection", con);
                    session.setAttribute("statement", stmt);

                    System.out.println("Session keys are ready");
                }
                catch(Exception e)
                {

        System.out.println(e);
                }
            %>

SALES FORCE TRACKING SYSTEM

                <%if(loginstatus!=null && loginstatus.equals("mismatch")){
                    %>
INVALID USERNAME OR PASSWORD.
<%
                }%>
               <form name="loginform" onsubmit="return validate(uname,pwd)" action="loginpagevalidation.jsp">

SignIn Here

UserName	<input type="text" name="uname" />

Password	<input type="password" name="pwd"/>

	<input type="submit" name="submit" value="SIGNIN"/><input type="reset" onclick="managersigning.html" name="reset" value="RESET"/>

	 Click here to SingUp

                </form>

                <%if(option==null){%>
                    <input type="radio" name="pwdissue" onclick="pwd(this)" value="forget"/>Forget Password
                    <input type="radio" name="pwdissue" onclick="pwd(this)" value="ChangePassword"/>Reset Password
                    <%}else if(option!=null && option.equals("forgetpwd")){%>
                        <input type="radio" name="pwdissue" checked  value="forget"/>Forget Password
                        <input type="radio" name="pwdissue" onclick="pwd(this)" value="reset"/>Change Password
                        <form onclick="forgetpwdformvalidation()" action="">

Enter EmployeeID	<input type="text" name="eid">

Enter EmailID	<input type="text" name="mailid">

	<input type="submit" name="sendmail" value="Reset and send password to me">

                        </form>
                    <%}else if(option!=null && option.equals("resetpwd")){%>
                        <input type="radio" name="pwdissue" onclick="pwd(this)" value="forget"/>Forget Password
                        <input type="radio" name="pwdissue" checked value="reset"/>Change Password
                        <form onsubmit="return resetpwdvalidation()" action="">

Enter EmployeeID	<input type="text" name="eid">

Enter Old Password	<input type="text" name="oldpwd">

Enter New Password	<input type="text" name="newpwd">

	<input type="submit" name="sendmail" value="Change My Password">

                        </form>
                    <%}%>

Output screen for this is:

My problem is whenever i click on either of 'ForgetPassword' or 'ResetPassword' it's appropriate java script function should be called but instead it is directing to loginvalidation.jsp?
What is this problem...??

A: It looks like pwd() is the function you are calling?
<input type="radio" name="pwdissue" onclick="pwd(this)" value="forget"/>Forget Password
Which does redirect to loginpagevalidation.jsp
function pwd(pwdissue){
    var pwddecision=pwdissue.value;
    //alert(pwddecision);
    window.open('loginpagevalidation.jsp?option='+pwddecision,target="_self");
}

Am I missing something?

A: Your pwd function opens a 'loginpagevalidation.jsp' window; is that what you're saying you don't want to happen?
Those should be links, not radio buttons. And are you really doing that SQL work in the JSP? This shouldn't have passed anybody's code review for a variety of reasons :(
For future reference, it's good to include only the code actually related to the problem rather than a source dump of the entire page. I removed some of the unimportant HTML.

A: It is the javascript function pwd taht calls the url loginpagevalidation.jsp, so your function indeed gets executed, but also redirects immediately to the new url. Isn't that what you want?


text:
Q: Xcode: Calendar for Ipad or Iphone I have a technical question: In xcode there is only a data-picker and this element is not functional in my app because in my app the user must be fast to choose date time. I would to use another instrument for chose a date. Have you any suggestions?

A: You can probably use one of the Date pickers lots of web sites are using : some kind of calendar view where you touch at the day you want.
You may have to code your own component though.
Examples :
http://www.bitrepository.com/a-collection-of-free-javascript-date-pickers.html


text:
Q: Iptable order of rules with example I had question about IPtables.
Let's start with this example of my book:

What rules you would set for a mail server accepting connections for
  EMSTP (port 465) and IMAP (port 993) having a network interface eth1
  exposed to the Internet and another network interface eth2 exposed to
  the corporate network?

I tried to respond with this:
Iptable -A FORWARD  -p  EMSTP, IMAP -s all -i eth1 -m multiport 465,993  state –state  NEW, ESTABILISHED  -j ACCEPT
Iptable -A FORWARD  -p  EMSTP, IMAP -s all -i eth2 -m multiport 465,993  state –state  NEW, ESTABILISHED  -j ACCEPT

*

*I thought about FORWARD because isn't specified if traffic is INPUT
or OUTPUT... So I used the generic in/out (FORWARD if I can use in
this mode)

*The protocol is specified(so I think don't have problems    about)

*I Used two rules because I used different interface, but I    think
can do all in the same rules, just adding another -i inside the same rule.

*For the network, I think that one is (internet) and another one is
local network (I really don't know what mean for "corporate")

My question is if my response is good and if it is mandatory to use this type of format.
What change is I swap the order of the rules?
In this case ad example:
 Iptable -A FORWARD -j ACCEPT   -i eth1 -p EMSTP, IMAP -s all  -m multiport 465,993  state –state  NEW, ESTABILISHED

Just swapping the jump and the inteface (-j and -i)
Someone can help to understand?

A: First, some reminders:

*

*-p argument is to specificy protocols like TCP, UDP, ICMP ... not higher level protocol like IMAP.

*OUTPUT and INPUT chains are for the packets outgoing from the machine and incoming to the machine. If you want to filter packets that are forwarded (when your machine act as a gateway), you must use the FORWARD chain. To distinguish IN and OUT, use the input or output interfaces and the source and destination IPs

*ESTABILISHED --> typo !!! :)
Now, let's have a look to your problem:

What rules you would set for a mail server accepting connections for EMSTP (port 465) and IMAP (port 993) having a network interface eth1 exposed to the Internet and another network interface eth2 exposed to the corporate network?

The problem is too broad since it says that:

*

*The machine is a mail server.

*It has two interfaces

*It must accept connections for mail related protocols.

But it isn't said that the connections must be accepted for both networks (internet / corporate). Anyway, let's assume that it is the case.
iptables works with discriminants: -i is one to match packets incoming to THAT interfaces.
Since you want the traffic to be accepted on every interfaces, then simply remove -i.
As mentionned previously, -p is to specify the transport protocol. Mails work in TCP, so use ̀ -p tcp`.
So your first responses would work (minus typo and some syntax error, the idea is OK).
Your last won't cause it allows packets coming from internet (eth1) to pass throught your server and go to your corporate network.


text:
Q: How can we read files from storage container azure using python In aws, used to get the files from s3 like this
 s3 = boto3.client('s3')
 object = s3.get_object(Bucket='ringr-dev',Key=file_name)
 serializedObject = (object['Body'].read().decode('utf-8'))
 data = json.loads("[" + serializedObject.replace("}\n{", "},\n{") + "]")
 jsonStr = data[0]

In azure, trying to code but i am not able to read,
 from azure.storage.blob import BlobClient
 blob = BlobClient(account_url="https://abc.blob.core.windows.net",
              container_name="sourcemetadata",
              blob_name="1eea7b89-f114-4ca.json",
              credential="qBncEBNxfwkBw+7UcxFFDIWCLRISg11gLyYxnwOxd+jLoYl")
data = blob.download_blob()

Not able to read the data. Please guide!

A: Did you have a chance to read the official documentation?
from azure.storage.blob import BlobServiceClient
connection_string=''
blob_service_client = BlobServiceClient.from_connection_string(connection_string)
container_client = blob_service_client.get_container_client("<container name>")
blob_client = container_client.get_blob_client("<blob name>")
blob_client.download_blob().readall() # read blob content as string


text:
Q: C++ - Creating a temporary object with decltype or auto I have an object "a" and I want to copy it into an object "b" but modify it a bit without modifying "a". Then that would look like this:
class SomeClass{

public:
    int a;

public:
    SomeClass(int _a)       {a = _a;}
    SomeClass& doStuff()    {++a; return *this;}

};

const SomeClass a( 25);
const auto b = SomeClass( a).doStuff();

This works nice but lets say I don't now / don't want to write the type of "a", then I came up with this solution:
const auto b = std::remove_const<decltype( a)>::type( a).doStuff();

Am I doing this right? Is there a less ugly solution for this? (where I don't have to type "a" twice.) Using auto or something. Preferably not a macro.

A: How about
template<typename T>
T copy(const T& t) { return T(t); }

const auto b = copy(a).doStuff();

A: Elaborating VTT's comment:
class SomeClass;
class DoStuff
{
    friend class SomeClass;
    SomeClass const& c;
public:
    explicit DoStuff(SomeClass const& c)
        : c(c)
    { }
};

class SomeClass
{
    int a;
public:
    SomeClass(int a)
        : a(a)
    { }

    SomeClass(SomeClass const& other)
        : a(other.a)
    { }

    SomeClass(DoStuff d)
        : SomeClass(d.c)
    {
        doStuff();
    }
};

SomeClass const a(7);
SomeClass const b((DoStuff(a)));

Only unlucky drawback: we need additional parentheses to prevent from b being interpreted as function SomeClass const b (DoStuff a) { } with a as parameter name...
I personally would have preferred making DoStuff an inner class of SomeClass, but that would have forced you to repeat the class name again:
SomeClass const b (( SomeClass::DoStuff(d) ));

(Haha, now I got myself - one repetition of the class name I still have even without the inner class...)
OK, before anyone moans:
SomeClass const b { DoStuff(a) };

Lately mentioned? Well, guess, I personally absolutely do not appreciate this syntax and avoid it wherever possible - even with initialiser lists, I still place parentheses around: std::vector<int> v({7, 10, 12}); – but that's a different topic...

A: A better approach would be to make a distinguished wrapper type for SomeClass reference dedicated to doStuff operation and make constructor accepting this type. This approach eliminates possible overhead of creating a temporary SomeClass object and of passing an extra parameter into constructor. Though it does not make much difference if SomeClass is a rather simple.
class
t_DoingStuffSomeClassWrap final
{
    #pragma region Fields

    private: SomeClass const & m_inst;

    #pragma endregion

    private:
    t_DoingStuffSomeClassWrap(void) = delete;

    public:
    t_DoingStuffSomeClassWrap(t_DoingStuffSomeClassWrap const & that) noexcept
    :   m_inst{that.m_inst}
    {}

    public: explicit
    t_DoingStuffSomeClassWrap(SomeClass const & inst) noexcept
    :   m_inst{inst}
    {}

    private: t_DoingStuffSomeClassWrap &
    operator =(t_DoingStuffSomeClassWrap const & that) = delete;

    private: t_DoingStuffSomeClassWrap &
    operator =(t_DoingStuffSomeClassWrap && that) = delete;

    public: SomeClass const &
    Unwrap(void) const noexcept
    {
        return(m_inst);
    }
};

// inside of SomeClass definition:
public: explicit
SomeClass(t_DoingStuffSomeClassWrap const wrap)
:   a{wrap.Unwrap().a}
{
    doStuff();
}

//  actual use
const SomeClass b{t_DoingStuffSomeClassWrap{a}};


text:
Q: Display hour with 15 min interval in django template I need to print dropdown menu with time selection in django template like:
12:00 AM
12:15 AM
12:30 AM
(...)

All hours should be visible.
Is there any simple way to do it in Django template without coding it inside the view or manual typing?

A: I don't think this is possible only with the templating language unless you write a custom tag for this.
But this can be easily achieved with 3 lines of python in your view:
times = []
for i in range(0, 24*4):
  times.append((datetime.combine(date.today(), time()) + datetime.timedelta(minutes=15) * i).time().strftime("%I:%M %p"))

in your template:
{% for time in times %}
    <option>{{ time }}</option>
{% endfor %}


text:
Q: Can I use malloc when defining a structure? Is there any way to dynamically allocate memory for a structure in the definition of the structure, and if it can't be done, what is the best way to dynamically allocate memory for that structure ?
typedef struct user_t{
    char user_name[30];
    char email[50];
    int movieswatched;
    movie *movielist;
}user_t;

I want to allocate memory for movielist .

A: You can use a flexible array member:
typedef struct user_t{
    char user_name[30];
    char email[50];
    int movieswatched;
    movie movielist[];  // The flexible array member,
                        // must always be last and declared as an array without a size
}user_t;

A structure like this must be allocated dynamically (with e.g. malloc), for example as
user_t *my_user = malloc(sizeof *my_user + sizeof(movie) * 50);  // Allocate space for 50 movies

A: You can't do it in the definition of the structure (which wouldn't make much sense anyway as you don't yet know the number of movies and because different user_t variables might have different number of movies).
You need to do it at runtime, for example like this:
user_t v;
...
v.movielist = malloc(sizeof(movie) * numberofmovies);

A: You could define a 'factory' function.  That's a fancy name for a function that does both mallocs for you.  Something like :
user_t *user_factory( const int movies_watched )
{
    user_t *user = malloc(sizeof *my_user);  // should check for NULL

    user->movieswatched = movies_watched;
    user->movielist = malloc(sizeof(movie) * movies_watched);

    return user;
}

It's common to combine the mallocs, BTW, then you can use @someprogrammerdude's flexible array member approach (but still wrap it in the factory).  The other advantage of their way is that it's harder to have an accidental memory leak.
If you really want an automatic variable as you have in your example, then you can have a half-way house of init (and deinit) functions:
void init_user_t( user_t *user, const int movies_watched )
{
    user->movieswatched = movies_watched;
    user->movielist = malloc(sizeof(movie) * movies_watched);
}

void deinit_user_t( user_t *user )
{
    free( user->movielist );
    user->movielist = NULL;
    user->movieswatched = 0;
}

...

user_t my_user;
init_user_t( &my_user, 6 /*num_movies*/ );


text:
Q: Смс-сервисы для рассылки и получения сообщений Добрый день, друзья!
На моем сайте используется смс-рассылка с использованием сервиса sms.ru. Все работает замечательно, но начальник сказал, чтобы сделать совместимым со всеми возможными смс-сервисами. В связи с чем прошу привести полный перечень всех основных смс-сервисов, а также указать, в чем каждый отличается от остальных, требуются ли инсталляция классов, модулей или чего-то еще для работы смс отправки, а также указать, какие данные требуются для отправки сообщений (в одних случаях это api_id, в других логин и пароль, в третьих почтовый ящик или номер телефона и т.д).
В общем, задача такая, гугл особо не помог, нету полного списка всех сервисов хотя бы внутрироссийских и обзора их функциональностей и реквизитов.
P.S. И это все такие особенности в работе постоянны, и надо выполнять всего за 15 штук)), я, наверное, свалю с этой работы и найду, где хотя бы платят нормально, а требования будут такие же).
Спасибо за внимание.
A: Бегать за всем-всеми агрегаторами рассылок будет утомительно и бесполезно, поскольку кто-то закроется, кто-то откроется, кто-то протокол поменяет и т.д..
Более правильный путь - это работа напрямую с операторами сотовой связи, их как-то значительно меньше, чем агрегаторов рассылок. Т.е. стать самому себе агрегатором.
Для этого нужно заключить договор с кем-то из операторов и получить доступ к их шлюзу по протоколу SMPP, после чего поднять у себя сервис отправки смс и контроля за доставкой (из бесплатных популярен kannel) и приложить к нему веб-интерфейс управления, самописный или готовый.
A: Подключение одного SMS-сервиса займет один день! + отладка сутки. В итоге два дня и один сервис готов!
Список сервисов:
http://smsc.ru/ - он поддерживает шесть протоколов взаимодействия, выбирайте любой (наиболее удобный для Вас) протокол. Инфа тут.
http://smsaero.ru/ - очень простой, отправить сообщение можно элементарным GET-запросом. Инфа тут.
http://www.mobilmoney.ru/ - обмен по протоколам SMPP и XML.
http://www.epochta.ru/products/sms/sms-api.php - смс-сервис, по этой ссылке описано API.
http://www.sms4b.ru/programs/clearphp.php - можно скачать уже готовый php-скрипт, установить на сайте и юзать!
П.С. Это всего лишь малый список смс-сервисов. Но это самые популярные. Думаю, еще можно найти около 15 мелких - вот только особого смысла подключать их не вижу. Для отказоустойчивости системы достаточно 3-х смс-сервисов. Не думаю, что все три откажут в одно и тоже время!
A: Отвечу по привычке на свой же вопрос. Вот что мне удалось нарыть:
1) http://sms.ru
Простой и удобный сервис для отправки/получения смс. Использование кода минимально.
Установка токена выглядит проще некуда:
$token=file_get_contents("http://sms.ru/auth/get_token");

Отправка смс тоже очень простая, требует лишь наличие api ключа:
$this->config['urlSMSService'] = 'http://sms.ru/sms/send?api_id=e9c9392d-dff3-d104-d584-1e603434dc1b&to=7';
$send = file_get_contents($this->config['urlSMSService'].$data['email']."&text=".urlencode(iconv("utf-8", "windows-1251","Ваш временный код для восстановления аккаунта: ".$pass)));

В переменную $send можно получать коды ошибки, возможные при отправке.
2) http://www.smsfeedback.ru
Еще один сервис по отправке и получения смс. Объемы кода более внушительные, к примеру, функция отправки смс выглядит таким образом:
<?php

/*
* функция передачи сообщения
*/

function send($host, $port, $login, $password, $phone, $text, $sender = false, $wapurl = false )
{
    $fp = fsockopen($host, $port, $errno, $errstr);
    if (!$fp) {
        return "errno: $errno \nerrstr: $errstr\n";
    }
    fwrite($fp, "GET /messages/v2/send/" .
        "?phone=" . rawurlencode($phone) .
        "&text=" . rawurlencode($text) .
        ($sender ? "&sender=" . rawurlencode($sender) : "") .
        ($wapurl ? "&wapurl=" . rawurlencode($wapurl) : "") .
        "  HTTP/1.0\n");
    fwrite($fp, "Host: " . $host . "\r\n");
    if ($login != "") {
        fwrite($fp, "Authorization: Basic " .
            base64_encode($login. ":" . $password) . "\n");
    }
    fwrite($fp, "\n");
    $response = "";
    while(!feof($fp)) {
        $response .= fread($fp, 1);
    }
    fclose($fp);
    list($other, $responseBody) = explode("\r\n\r\n", $response, 2);
    return $responseBody;
}

/*
* использование функции передачи сообщения
*/

echo send("api.smsfeedback.ru", 80, "login", "password",
          "79031234567", "text here", "TEST-SMS");
?>

Необходимые данные для передачи: url-сервиса, порт, логин, пароль, номер телефона, ну и соответственно сам текст смс.
3) http://www.epochta.ru/products/sms/sms-api.php
Еще один сервис по рассылке смс, подробности я пока еще не узнавал. На практике не использовал. Подробное описание работы данного сервиса описаны тут.
4) http://ruseller.com/lessons.php?rub=37&id=940
Еще один хитрый способ отправки смс, через почту. Правда, код выглядит объемным и не очень красивым местами.
P.S. Если кто предложит еще смс-сервисы и способы отправки смс, напишите, так как я сделал явно не полный обзор возможных сервисов.


text:
Q: Should we remove event listener before destroying objects In Javascript, does the following create a memory leak
var button = document.createElement("input");
button.setAttribute("type","button");
button.addEventListener("click", myFunction);
button = null;

Do I have to remove the event listener first?
EDIT
Update to my question, I think that because I'm not actually adding this element to the DOM, then it's not a duplicate?


text:
Q: How can I get a certain segment with regex? I have a simple string
testteststete(segment1)tete(segment2)sttes323testte(segment3)eteste
I need to get (segment2). Each segment may be any text. I tried to use this regex
\(.+\). But i get this result

How i can get (segment2)?
PS: I want to get all of the segments in brackets

A: In C#, you can just match all the (...) substrings and then access the second one using Index 1:
var rx = @"\([^)]*\)";
var matches = Regex.Matches(str, rx).Cast<Match>().Select(p => p.Value).ToList();
var result = matches != null && matches.Count > 1 ? matches[1] : string.Empty;

See IDEONE demo
The regex matches

*

*\( - an opening (

*[^)]* - 0 or more characters other than )

*\) - a closing ).

A: I can't test it but this should probably work:
\([^\)]*\)

A: You can try to use this regex:
\(([^)]+)\)

REGEX DEMO

A: (?<=^[^()]*\([^)]*\)[^()]*\()[^)]*

You can simply use this.See Demo

A: var regex = new Regex(@"\(([^)]*)\)", RegexOptions.Compiled);
string secondMatch = regex.Matches(text).Cast<Match>()
    .Select(m => m.Value.Trim('(', ')'))
    .ElementAtOrDefault(1);


text:
Q: Python - Not Expecting Data by Unpacking Ethernet Frame Getting 0xc0a8 on Type Expecting 0x800 I have this Python function which unpacks ethernet frame:

def ethernet_frame(data):
        ipheader = struct.unpack('!6s6sH', data[0:14])
        dest_mac = binascii.hexlify(ipheader[0])
        src_mac = binascii.hexlify(ipheader[1])
        proto = ""

        protoType = ipheader[2]
        nextProto = hex(protoType)

        print(nextProto)
        if(nextProto == '0x800'):
            proto = 'IPV4'
        elif(nextProto == '0x86dd'):
            proto = 'IPV6'
        print(nextProto)

        return dest_mac, src_mac, proto, data[14:]

I was expecting to get 0x800 for IPV4 or 0x86dd for IPV6.
But after unpacking the frame I got 0xc0a8.
Can someone explain why I'm getting this unexpected data? and how to fix it to get correct data?

A: Sounds like you may be reading an IP header as an ethernet header. 0x0800 is the last two bytes of the ethernet header -- data[12:13]. The IP header pre-addresses is 12 bytes long, and the next two bytes (ip_header[12:13]) are the first two bytes of the IP source address. 0xc0a8 in decimal is (192, 168) -- which looks to me like the first two bytes of an internal IP address, 192.168.x.x.
(IIRC), the IP header is embedded directly after the ethernet header in the yellow data segment of your diagram, so if you tried to read a second ethernet header after the first one, for example, this could happen.
(by the way -- you don't need to convert protoType into a string to compare it to a hex value -- you can simply do if protoType == 0x0800 / elif protoType == 0x86dd).


text:
Q: How to bind enums to dropdown list? I used linq to get a set of Enums except one.This is my Linq
List<SyncRequestTypeEnum> lstDefaultSyncList = (List<SyncRequestTypeEnum>)(Enum
  .GetValues(typeof(SyncRequestTypeEnum))
  .Cast<SyncRequestTypeEnum>()
  .Except(new SyncRequestTypeEnum[] { SyncRequestTypeEnum.ProjectLevel })).ToList();

SyncRequestTypeEnum is my enum class which has 3 Enums.
 Here I am using (Enum.GetValues(typeof(SyncRequestTypeEnum)) so I am getting values. Now I am binding these values to dropdownlist as:
 ((DropDownList)control).DataSource = HtmlEncodeHelper.HtmlEncode(lstDefaultSyncList );
 ((DropDownList)control).DataBind();

This is not binding the actual enums. In UI it is displaying the values as System.Data.DataRowView. If I use GetNames instead of GetValues it is throwing a cast error
can someone help on this?


text:
Q: How to authenticate request with OpenID from JMeter as it throws 401 Un-Authorized error How to authenticate request with OpenID from JMeter as it throws 401 Un-Authorized error:
Response code: 401
Response message: Unauthorized
I am using BlazeMeter to record the request and the same JMX is using in JMeter.

A: I'm not personally familiar with OpenID, but I can say that in my experience, most 401 errors are due to not having setup authentication tokens properly in the script.
If you used the BlazeMeter Chrome Extension to create your script, this is probably the problem, because the recorder is unable to automatically script token-handling; that always requires manual intervention.
We've got a guide with a couple of demo videos of how to setup authentication tokens in your script -- you may find it helpful:
https://guide.blazemeter.com/hc/en-us/articles/207421705


text:
Q: Isomorphism on a Sylow-$p$-subgroup of a group $G$.
Problem: If $P$ is a Sylow-$p$-subgroup of a group $G$ and $f:G\rightarrow G$ is an isomorphism then $f(P)=P$.

I've tried to make a proof through the 2nd Sylow Theorems and through the fact that $f(P)$ is a $p$-subgoup of $G$ but I think that this there is a chance that this might not be the correct approach. Any kind of help is much appreciated!

A: That's certainly not true -- take any group with more than one Sylow $p$-subgroup. Sylow's second theorem says all the Sylow $p$-subgroups are conjugate, so in particular there's an inner automorphism moving one to any other.
Now if you know the Sylow $p$-subgroup is unique, then it is true. Indeed, $f(P)$ is a $p$-subgroup with the same cardinality as $P$, so must be $P$.

A: What is true is the following. Some terminology: an automorphism of $G$ is said to be fixed-point free, if it leaves only the identity $1$ fixed. If $f \in Aut(G)$ is fixed-point free, then $G=\{x^{-1}f(x): x \in G\}$: for $x^{-1}f(x)=y^{-1}f(y)$ is equivalent to $yx^{-1}=f(y)f(x)^{-1}=f(y)f(x^{-1})=f(yx^{-1})$, whence $yx^{-1}=1$, so $x=y$.
Theorem Let $f \in Aut(G)$ be fixed-point free, then there exists a $P \in Syl_p(G)$ such that $f(P)=P$. Moreover, there is only one such $P$.
Proof Note that $f(P)=P$ does not mean that $f$ fixes $P$ pointwise (otherwise $P$ would be trivial ...), but as a set!
Existence Since $f$ is an automorphism, $f(P) \in Syl_p(G)$. Hence by Sylow's Theorem a $y \in G$ exists with $f(P)=y^{-1}Py$. Choose $x \in G$ with $y=x^{-1}f(x)$. We claim that $f(xPx^{-1})=xPx^{-1}$: since both sets have the same cardinality, it suffices to show that $f(xPx^{-1}) \subseteq xPx^{-1}$. Take $s \in P$ and note that $f(x^{-1})=f(x)^{-1}=y^{-1}x^{-1}$. As $f(P)=y^{-1}Py$, $f(s)=y^{-1}ty$ for some $t \in P$. This amounts to: $f(xsx^{-1})=f(x) \cdot y^{-1}ty \cdot f(x)^{-1}=xy \cdot y^{-1}ty \cdot y^{-1}x^{-1}=xtx^{-1} \in xPx^{-1}$, as wanted.
Uniqueness To prove the uniqueness with respect to be invariant under $f$, assume $P \in Syl_p(G)$ being invariant under $f$. It is then is easy to see that its normalizer is also invariant under $f$, that is $f(N_G(P))=N_G(P)$. This induces an automorphism $f \mid _{N_G(P)}$, which of course is fixed-point free again, whence every element of $N_G(P)$ can be written as $n^{-1}f(n)$, with $n \in N_G(P)$.
Now assume there is another $Q \in Syl_p(G)$ with $f(Q)=Q$. Of course by Sylow's Theorem, $Q=uPu^{-1}$ for some $u \in G$. It follows that $uPu^{-1}=Q=f(Q)=f(uPu^{-1})=f(u)f(P)f(u^{-1})=f(u)Pf(u)^{-1}$, implying that $u^{-1}f(u) \in N_G(P)$. Hence $u^{-1}f(u)=n^{-1}f(n)$ for some $n \in N_G(P)$. But this implies $u=n$ and hence $Q=P$. $\square$

A: A subgroup $H\le G$ such that for any automorphism $a$ of $G$ we have $a(H)=H$ is called characteristic.
Sylow subgroups are in general not characteristic,  as we often have more than one,  which by a Sylow theorem are conjugate.   And conjugation by an element of the group is always an automorphism.
Examples of characteristic subgroups are the commutator subgroup,  the center,  the Frattini subgroup and the Fitting subgroup.
If you have only one subgroup of a certain order, then it's characteristic. For this reason,  all subgroups of cyclic groups are characteristic.
When the Sylow subgroup is unique, or normal,  it's characteristic.


text:
Q: Magento2: what is the difference between layout and page_layout? As I dig deeper in Magento 2, I noticed that there are layout and page_layout file? What are the differences between the two?

A: Well if i put this in simple words than
page_layout represents the full page, i mean you can declare your own full page without inheriting any master or root or other empty layout. (only use, if you want to completely customize your own full page.)
layout represents the part of the page (mostly the html content).  You can use this when you want your page to inherit the common contents from the root layout like header, footer etc etc.

A: Layout XML is a tool to build the pages of the Magento application in a modular and flexible manner. It enables us to describe the page layout and content placement.
Looking at XML root nodes, we differentiate two types of layouts:
1. layout: XML wrapped in <layout>
2. page: XML wrapped in <page>

Page layouts represent a full page in HTML, whereas layout layouts represent a part of a page.
The layout type is a subset of the page layout type. Both types of layout XML files are validated by the XSD schema found under the vendor/magento/framework/View/Layout/etc/ directory:
1. layout – layout_generic.xsd
2. page – page_configuration.xsd

Based on the application components that provide  and  elements, we can further section them as base and theme layouts.
The base layouts are provided by the modules, usually at the following locations:
1. <module_dir>/view/frontend/layout: page configuration and generic layout files
2. <module_dir>/view/frontend/page_layout: page layout files

The theme layouts are provided by the themes, usually at the following locations:
1. <theme_dir>/<Namespace>_<Module>/layout: page configuration and generic
layout files
2. <theme_dir>/<Namespace>_<Module>/page_layout: page layout files

Magento will load and merge all module and theme XML files on the appropriate page.
Once files are merged and XML instructions are processed, the result is rendered and sent
to the browser for display.

A: Page layout declares the wireframe of a page inside the  section, for example one-column layout or two-column layout.
Allowed layout instructions:
 <container>
 <referenceContainer>
 <move>
 <update>

Generic layouts define the contents and detailed structure inside the <body> section of the HTML page markup.
Conventionally generic layout files must be located as follows:
Module generic layouts: <module_dir>/view/frontend/layout
Theme generic layouts: <theme_dir>/<Namespace>_<Module>/layout

Follow this link for overview of layout overview: http://devdocs.magento.com/guides/v2.0/frontend-dev-guide/layouts/layout-overview.html
And some more detailed information about the layout file types: http://devdocs.magento.com/guides/v2.0/frontend-dev-guide/layouts/layout-types.html


text:
Q: Is there any way to increase a rubber-bands lifetime? Rubber-bands are simple, yet very useful. Old rubber bands(5 years?) get brittle? Why is that?

A: If a rubber band is usable for 5 years, it's a very good one.
There is not much you can do to prevent brittleness other than storing them in a dark and cool place. Light and oxygen are the most dangerous enemy of rubber.
The biggest influence on lifespan is the manufacturer, because they can choose
to use a persistent (expensive) type of rubber (eg Kalrez®, ask for prizes!)
Of course there are less extreme rubbers in prize.
Another way to extend life is to change the color; adding carbon black prolonges the life of rubber substantially (Protection from light) and by adding antioxidants.
The background of embrittlement of polybutadiene (polyisoprene) based
rubbers is crosslinking by radical chain reactions with oxygen.
Cheap urethane rubbers die from similar reactions, but those usually
become sticky, even liquid by this processes.


text:
Q: Vue how to draw picture and put next to another i want to draw image next to another in this same div.
Generaly drawing works fine, but i have problem with placing one picture next to another.
Every time i draw image it is placend in this same div.
My HTML is:
<div id="thumbnailImages">
    <canvas
        id="thumbnailImage"
    />
  </div>

And code:
 function thumbnail(video) {
  const canvasThumbnail = document.getElementById('thumbnailImage')
  const cth = canvasThumbnail.getContext('2d')

  const data = video.slice(8)
  imgToHTML(data, e => {
    const drawingThumbnail = new Image()
    drawingThumbnail.src = e.target.result
    drawingThumbnail.onload = function () {
      canvasThumbnail.width = 128
      canvasThumbnail.height = 128
      cth.drawImage(drawingThumbnail, 0, 0)
      document.getElementById('thumbnails').appendChild(canvasThumbnail)
    }
  })
}

I would like to have many 'canvas' in 'thumbnailImages' id.
Can you help me?

A: The issue is that you are reusing the same canvas over and over again. You need to create a new canvas to put next to it:
 function thumbnail(video) {
  const canvasThumbnail = document.createElement('canvas');
  const cth = canvasThumbnail.getContext('2d')

  const data = video.slice(8)
  imgToHTML(data, e => {
    const drawingThumbnail = new Image()
    drawingThumbnail.src = e.target.result
    drawingThumbnail.onload = function () {
      canvasThumbnail.width = 128
      canvasThumbnail.height = 128
      cth.drawImage(drawingThumbnail, 0, 0)
      document.getElementById('thumbnailImages').appendChild(canvasThumbnail)
    }
  })
}


text:
Q: how to initialize an output on verilog (sequential circuit) I'm new to Verilog coding and I have a college project to design a simple elevator system. The code worked perfectly fine on the FPGA but I cannot get the simulation to work. This is my code:
module move(
    output reg [1:0] current,
    input [1:0] target,
    input clk,
    input overloadin,
    output reg up,
    output reg down
    );

always@(posedge clk)
if (overloadin==1'b0)
begin
if (target[1:0]>current[1:0])
begin
current[1:0] <= current[1:0] + 1;
up = 1'b1;
down = 1'b0;

end
else if (target[1:0]<current[1:0])
begin
current[1:0] <= current[1:0] - 1;
down = 1'b1;
up = 1'b0;

end
else
begin
up = 1'b0;
down = 1'b0;

end
end
endmodule

'current' is declared as wire in the top module. I'm assuming I cannot simulate it because the value of 'current' was not initialized. How can I initialize the value of it without affecting the functionality of the always block?

A: You can use an 'initial' statement or add a reset signal.
initial
   current = 2'b00;

or
  input reset_n,
  ...
   always @(posedge clk or negedge reset_n)
   begin
      if (!reset_n)
         current <= 2'b00;
      else
      ...
   end

I personally prefer the latter but you can find several discussions on the use of initial vs reset in this and the ee forum.
I have not checked the rest of your code because to me it is unreadable due to the lack of indenting.

A: you are mixing blocking and non-blocking statements together is causing race condition during simulation. I have modified your code.
module move(
 output reg [1:0] current,
 input [1:0] target,
 input clk,
 input reset_n,             //Added an additional input
 input overloadin,
 output reg up,
 output reg down
);

always@(posedge clk or negedge reset_n)
begin
 if(!reset_n)               //Active low reset
 begin
   up      <= 1'd0;
   down    <= 1'd0;
   current <= 2'd0;
 end
else if(!overloadin)
begin
 if(target > current)
 begin
  up      <= 1'd1;
  down    <= 1'd0;
  current <= current + 2'd1;
 end
 else if(target < current)
 begin
  up      <= 1'd0;
  down    <= 1'd1;
  current <= current - 2'd1;
 end
else
 begin
  up      <= 1'd0;
  down    <= 1'd0;
 end
  end  end  endmodule


text:
Q: How to change element in array? Array is 2 dimensional 10x10 gameBoard
Code I made for array:
int gameBoardLength = gameBoard.length;
        System.out.print("  ");    //two spaces to align the text

        for (int i = 0; i < gameBoardLength; i++){   //gameboard.lenght = 10
            System.out.print(i + 1 + " ");
        }

Code for changing 1 or more random positions in array:
 private static char[][] placeShips(char[][] gameBoard, char water,char destroyer1, char ship, char destroyer2 ) {
        int x = 0;
        int y = 1;
        int gameBoardLenght = gameBoard.length;
        int placedDestroyers1 = 0;
        while (placedDestroyers1 < 4){
            int[] location = generateShipLocation(gameBoardLenght);
            char possibilityOfPlacement = gameBoard[location[x]][location[y]];
            if (possibilityOfPlacement == water){   // water is char '~' and at the begining array is filled up with that.
                gameBoard[location[x]][location[y]] = destroyer1;   //destroyer1  is a char (char destroyer1 = 'D'; )

            }placedDestroyers1++;
        } return gameBoard;
    }

What i need is to change 2/3/4 char in a row.
I'v already tried to change destroyer1 into Char [] of few elements, but that didn't made the job.
Edit:
I edited code like that:
private static char[][] placeShips(char[][] gameBoard, char water,char destroyer1, char ship, char destroyer2 ) {
        int x = 0;
        int y = 1;
        int gameBoardLenght = gameBoard.length;
        int placedDestroyers1 = 0;
        int[] location = generateShipLocation(gameBoardLenght); // that part is taking 1 random point from net method

        while (placedDestroyers1 < 4){
            char possibilityOfPlacement = gameBoard[location[x]][location[y]];
            if (possibilityOfPlacement == water){
                gameBoard[location[x]][location[y++]]  = destroyer1; //That part should placing first random point and next ones next to that one.
            }placedDestroyers1++;
        } return gameBoard;
    }

//Part below is making random point in location
private static int[] generateShipLocation(int gameBoardLenght) {

        int [] location = new int [5];
        for (int i = 0; i < location.length; i++){
            location[i] = new Random().nextInt(gameBoardLenght);
        } return location;
    }

And it is kinda working. Output is lining in line, but it is not in 1 line it's in parts.
The way i want them to be:
X X X O
O O O O
O O O O
But they going like that:
X O X O
O O O O
O O O O
Or that:
X O O X
O O O O
O O O O
SEMI SOLUTION:
 private static char[][] placingDestroyer1(char[][] gameBoard, char water,char destroyer1, char destroyer2) {

        int gameBoardLenght = gameBoard.length;
        int[] location = generateDestroyer1Location(gameBoardLenght);
        int placedDestroyers1 = 0;
        while (placedDestroyers1 < 4){
            char possibilityOfPlacement = gameBoard[location[0]][location[1]];
            if (possibilityOfPlacement == water && possibilityOfPlacement != destroyer1 && possibilityOfPlacement != destroyer2){
                gameBoard[location[0]][location[1]] = destroyer1;
            }
            placedDestroyers1++;
            location[1]++;  //thanks to Kemper Lee, I was able to track right solution. However that solution sometimes is out of lenght of array, so it is exiting with erro
        } return gameBoard;
    }

A: If I'm understanding your question, the best place to start would be to create some grids for visualization:
             10cols             EX 1              EX 2
           ~~~~~~~~~~        X~~~~~~~~~        ~~~~~~~~~~
           ~~~~~~~~~~        X~~~~~~~~~        ~~~~~~~~~~
           ~~~~~~~~~~        ~~~~~~~~~~        ~XXXX~~~~~
           ~~~~~~~~~~        ~~~~~~~~~~        ~~~~~~~~~~
    /*10*/ ~~~~~~~~~~        ~~~~~~~~~~        ~~~~~~X~~~
    rows   ~~~~~~~~~~        ~~~~~XXXX~        ~~~~~~X~~~
           ~~~~~~~~~~        ~~~X~~~~~~        ~~~~~~~~~~
           ~~~~~~~~~~        ~~~X~~~~~~        ~~~~~~~~~~
           ~~~~~~~~~~        ~~~X~~~~~~        ~XXX~~~~~~
           ~~~~~~~~~~        ~~~~~~~~~~        ~~~~~~~~~~

In Example 1 when index[0][0] is filled then either index[1][0] or index[0][1] has to filled in.
Likewise, in Example 2 when index[2][2] is filled then index[2][1], index[1][2], index[3][2], or index[2][3] need to be filled
NOTE -- this is NOT a complete solution


text:
Q: Programmatically Unhide Slides in PPT File I'm writing a little tool that converts slides in PPT Files to pngs, the problem I'm having is with hidden slides. How can I change a slide to be visible in java? Im currently using Apache POI for conversion to PNGs, although this doesn't work for clipart so I am tempted with exporting it to a PDF using unoconv first, then minipulating that. But doing it like this doesn't take in to account all the hidden slides. So how could I programmatically change the hidden slides to be visible?

A: This is kind of a hack and has been tested only with a PPT from Libre Office with POI 3.9 / POI-Scratchpad 3.8.
The spec ([MS-PPT].pdf / version 3.0 / page 201) says, that Bit 3 (fHidden) of Byte 18 specifies whether the corresponding slide is hidden and is not displayed during the slide show
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.lang.reflect.Field;

import org.apache.poi.hslf.model.Slide;
import org.apache.poi.hslf.record.Record;
import org.apache.poi.hslf.record.RecordTypes;
import org.apache.poi.hslf.record.UnknownRecordPlaceholder;
import org.apache.poi.hslf.usermodel.SlideShow;

public class UnhidePpt {
    public static void main(String[] args) throws Exception {
        FileInputStream fis = new FileInputStream("hiddenslide.ppt");
        SlideShow ppt = new SlideShow(fis);
        fis.close();

        Field f = UnknownRecordPlaceholder.class.getDeclaredField("_contents");
        f.setAccessible(true);

        for (Slide slide : ppt.getSlides()) {
            for (Record record : slide.getSlideRecord().getChildRecords()) {
                if (record instanceof UnknownRecordPlaceholder
                    && record.getRecordType() == RecordTypes.SSSlideInfoAtom.typeID) {
                    UnknownRecordPlaceholder urp = (UnknownRecordPlaceholder)record;

                    byte contents[] = (byte[])f.get(urp);
                    contents[18] &= (255-4);
                    f.set(urp, contents);
                }
            }
        }

        FileOutputStream fos = new FileOutputStream("unhidden.ppt");
        ppt.write(fos);
        fos.close();
    }
}


text:
Q: Golang Websocket detecting file message and writing it if more than 1 ws frame byte I need to save each new picture in one file, which is sent by several frames through websockets. Here is code of my file:
package main

import (
"fmt"
"golang.org/x/net/websocket"
"log"
"net/http"
"os"
"time"
)

var (
dirPath string
test    byte
lenFile int
)

func check(e error) {
if e != nil {
    panic(e)
}
}

func ChatServer(ws *websocket.Conn) {
defer ws.Close()
var test []byte
var payload []byte
for {
    err := websocket.Message.Receive(ws, &payload)
    if err != nil {
        log.Println(err)
    }

    fmt.Println("Payload: ", len(payload))

    test = append(test, payload...)
    fmt.Println("Test: ", len(test))

    fo, err := os.Create(fmt.Sprintf("./%d.png", time.Now().UnixNano()))
    check(err)
    _, err = fo.Write(test)
    check(err)
    fo.Close()
}
 log.Print("DONE")

}

func main() {
if len(os.Args) < 2 {
    log.Fatal("Usage: chatExample <dir>")
}

dirPath = os.Args[1]

fmt.Println("Starting... ")

http.Handle("/", http.FileServer(http.Dir(dirPath)))
http.Handle("/ws", websocket.Handler(ChatServer))

err := http.ListenAndServe(":3000", nil)

if err != nil {
    log.Fatal("ListenAndServe ", err)
}
}

And here is my results of downloading two files in order:

So I need save only two files (images) if I send two files, not three. Also I need to save two different files, I have to somehow detect new file from websocket connect.

A: The sender fragments one of the messages into two frames. Because the x/net/websocket API exposes frames instead of messages, the application writes three files.
It's not possible to detect message boundaries using the x/net/websocket package. Use the gorilla/websocket package instead.


text:
Q: Unable to find a matching configuration of project :react-native-gesture-handler: None of the consumable configurations have attributes i am getting the error Unable to find a matching configuration of project :react-native-gesture-handler: None of the consumable configurations have attributes.in react native.
"react-native-gesture-handler": "^1.1.0" added to project
i already included these to my react native project:
"dependencies": {
    "react": "16.6.3",
    "react-native": "0.58.6",
    "react-native-gesture-handler": "^1.1.0",
    "react-navigation": "^3.3.2"
  },
  "devDependencies": {
    "babel-core": "7.0.0-bridge.0",
    "babel-jest": "24.6.0",
    "jest": "24.6.0",
    "metro-react-native-babel-preset": "0.53.1",
    "react-test-renderer": "16.6.3"
  },
  "jest": {
    "preset": "react-native"
  }

unable to install app on avd. i want to run this project in android virtual device(avd).

A: If you're using Windows, change this in your settings.gradle
project(':react-native-gesture-handler').projectDir = new File(rootProject.projectDir, '..\node_modules\react-native-gesture-handler\android')

instead of:
project(':react-native-gesture-handler').projectDir = new File(rootProject.projectDir, '..\\node_modules\\react-native-gesture-handler\\android')

Ref:
https://github.com/kmagiera/react-native-gesture-handler/issues/436


text:
Q: File reading and testable code I have a piece of java code which reads strings from a file and creates a map out of the strings. As this code depends on a file, unit testing is clumsy. How does one design such pieces so that code can be unit tested?
One approach that I can think of is, instead of this piece taking a file as an argument it can take an input stream. In actual scenario, pass the file input stream, while unit testing pass an input stream created from a string. But, this looks like an over kill to me. Is there a better way?

A: It's a design error not to provide a function that reads from an InputStream if all you do with the file is read it. Therefore, modify the function to take an InputStream, and provide a wrapper that takes a File. Using a ByteArrayInputStream or a StringInputStream to test it is fine.

A: In such cases, I used to create the needed files for test cases, and use them in unit testing. I had a dedicated folder for these files (test data) and setup the test case(s) to take the file appropriate for the test case.

A: Look at it this way: no matter how you reorganize your code, the test data has to come from some file. I see 2 variants:

*

*Data is encoded in-place, in one of the .java unit test source code files. It works only for small test data sets. You would need to refactor your code to take input stream and have another wrapper that works with file, as you described.

*Test data file. You have to create a
project-wide convention where to keep your test
data files. Their location may be
relative to the jave project
location, or under a common test
data files root. In any case, it helps
to have a utility method that
returns a full test data file path given a "logical" file name.
It seems like in your case (just one test, a hundred words) the first solution may be enough. Yes, you would need to refactor the code a little. The second solution is more generic and personally I find it much more practical and applicable.
Some people would say this is not a unit test if it works with data files. Well, it's a matter of definition of "unit test", and is quite irrelevant. If you need to test your code, just find the best / most convenient way for your project.

A: I would suggest either using a dataset (in this case a file) which is dedicated for testing. Otherwise i would use mocking to simulate the access to the external resources.
In any case i would tend to extend the coverage of automatic tests as far as possible.


text:
Q: Drawing to selected canvas I have a page that begins with one canvas element. Using some colored buttons on the side I can add colored squares to this canvas.
Using jQuery, I have another click event that appends another canvas to the page. Tada, 2 canvas elements.
I also created a click event that adds a class of 'selected' to whichever canvas is clicked.
My struggle is, how can I draw only to the selected canvas?

A: In the mousedown event handler you can get the id of the clicked canvas like this:
function handleMouseDown(e){
  clickedId=e.target.id;
}

Then you can target the selected canvas based on its id.
A Demo:  http://jsfiddle.net/m1erickson/d46ZL/

A: You could also get the canvas element from the class name, as it seems you want to do, using jQuery as follows:
<!doctype html>

            <canvas width="600" height="400" style="border:1px solid #000000;"></canvas>

            <canvas class="selected" width="600" height="400" style="border:1px solid #000000;"></canvas>


text:
Q: How do I make TTS stop speaking IMMEDIATELY? I am using ISpVoice to speak an input string. Now, even though I use SPF_ASYNC and SPF_PURGEBEFORESPEAK tags in the Speak method, the tts doesn't stop whenever Pause is called instead it continues until the tts finishes a word.
Here's how I do it:
void speakSentence()
{
    pVoice->Pause();
    pVoice->Speak(L"This is a sentence.", SPF_ASYNC | SPF_PURGEBEFORESPEAK, NULL);
    pVoice->Resume();
}

Whenever I try to call this function at the middle of the word "sentence", the tts doesn't pause and instead continues to say the word until the end.
From microsoft documentation:

ISpVoice::Pause pauses the voice at the nearest alert boundary and closes the output device, allowing access to pending speak requests from other voices.

I tried changing the alert boundary by:
pVoice->SetAlertBoundary(SPEI_PHONEME);

and it doesn't work.
There is NVDA Screen Reader that solved this problem but I don't know how they did it.
Is there anyway to solve my problem?
EDIT:
Here's my full code. I am creating a small screen reader program that uses both UIAutomation and MSAA.
The program may somewhat unstable when comparing UI objects but most times it works.
screeenreader.h:
#ifndef _SCREENREADER_H_
#define _SCREENREADER_H_

#define WIN32_LEAN_AND_MEAN
#ifndef UNICODE
#define UNICODE
#endif

#include <windows.h>

#include <memory>

#include "speechsynthesis.h"
#include "uiautomator.h"

class ScreenReader
{
public:
    explicit ScreenReader(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR pScmdline, int iCmdShow);
    virtual ~ScreenReader();

    LRESULT CALLBACK MessageHandler(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam);
    int Exec();
private:
    void InitializeWindows();
    void InitRawInputDevices();
    bool IsMouseMove();
private:
    LPCWSTR m_applicationName;
    HINSTANCE m_hInstance;
    HINSTANCE m_hPrevInstance;
    PSTR m_pScmdline;
    int m_iCmdShow;

    HWND m_hWnd;

    SpeechSynthesis *m_pSpeech;
    UIAutomator *m_pAutomator;

    RAWINPUTDEVICE rid[2];

    LONG m_prevMouseX;
    LONG m_prevMouseY;

    BSTR currItem;
};

static ScreenReader *application;

static LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam);

#endif

screenreader.cpp: In this part I called ISpVoice at the messageloop section. At ScreenReader::MessageHandler() function at IsMouseMove condition.
#include "screenreader.h"

ScreenReader::ScreenReader(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR pScmdline, int iCmdShow)
{
    CoInitialize(NULL);
    m_pSpeech = new SpeechSynthesis;
    m_pAutomator = new UIAutomator;

    // Get current Cursor position.
    POINT pt;
    GetCursorPos(&pt);
    m_prevMouseX = pt.x;
    m_prevMouseY = pt.y;

    // Notify user the program is loading.
    m_pSpeech->Speak(L"Loading Rescan. Please wait.", SPF_DEFAULT, NULL);
    m_hInstance = hInstance;
    m_hPrevInstance = hPrevInstance;
    m_pScmdline = pScmdline;
    m_iCmdShow = iCmdShow;

    application = this;
    InitializeWindows();
    InitRawInputDevices();
}

ScreenReader::~ScreenReader()
{
    if (m_pSpeech != nullptr)
    {
        delete m_pSpeech;
        m_pSpeech = nullptr;
    }
    if (m_pAutomator != nullptr)
    {
        delete m_pAutomator;
        m_pAutomator = nullptr;
    }
    if (currItem != NULL)
    {
        SysFreeString(currItem);
        currItem = NULL;
    }
    CoUninitialize();
}

LRESULT CALLBACK ScreenReader::MessageHandler(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    switch (message)
    {
    case WM_INPUT:
    {
        UINT dwSize;
        GetRawInputData(
            (HRAWINPUT)lParam,
            RID_INPUT,
            NULL,
            &dwSize,
            sizeof(RAWINPUTHEADER)
        );
        std::unique_ptr<BYTE[]> lpb(new BYTE[dwSize]);
        if (!lpb)
            return 0;
        if (GetRawInputData(
            (HRAWINPUT)lParam,
            RID_INPUT,
            lpb.get(),
            &dwSize,
            sizeof(RAWINPUTHEADER)
        ) != dwSize)
            OutputDebugString(L"GetRawInputData does not return correct size!\n");

        RAWINPUT *raw = (RAWINPUT*)lpb.get();
        if (raw->header.dwType == RIM_TYPEKEYBOARD)
        {
            UINT mess = raw->data.keyboard.Message;
            UINT vKey = raw->data.keyboard.VKey;
            if (mess == WM_KEYDOWN)
            {
            }
        }
        else if (raw->header.dwType == RIM_TYPEMOUSE)
        {
            if (IsMouseMove())
            {
                BSTR item;
                HRESULT hr = m_pAutomator->GetUIAutomationItemNameAtMousePoint(&item);
                if (item == NULL)
                    return 0;
                if (currItem == NULL)
                    currItem = SysAllocString(item);
                if (wcscmp(currItem, item) != 0)
                {
                    m_pSpeech->Stop();
                    m_pSpeech->Speak(item);
                    if (currItem != NULL)
                        SysFreeString(currItem);
                    currItem = SysAllocString(item);
                }
                SysFreeString(item);
            }
        }
    }
        return 0;
    default:
        return DefWindowProc(hWnd, message, wParam, lParam);
    }
}

int ScreenReader::Exec()
{
    MSG msg;

    ShowWindow(m_hWnd, m_iCmdShow);

    // Tell the user that the program is ready.
    m_pSpeech->Speak(L"Rescan ready.", SPF_PURGEBEFORESPEAK);

    // The message loop
    while (GetMessage(&msg, NULL, 0, 0))
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }

    return msg.wParam;
}

void ScreenReader::InitializeWindows()
{
    // Create Window class.
    WNDCLASSEX wc;

    m_applicationName = L"Rescan Screen Reader";

    wc.cbSize = sizeof(WNDCLASSEX);
    wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
    wc.lpfnWndProc = WndProc;
    wc.cbClsExtra = 0;
    wc.cbWndExtra = 0;
    wc.hInstance = m_hInstance;
    wc.hIcon = LoadIcon(NULL, IDI_APPLICATION);
    wc.hCursor = LoadCursor(NULL, IDC_ARROW);
    wc.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1);
    wc.lpszMenuName = NULL;
    wc.lpszClassName = m_applicationName;
    wc.hIconSm = wc.hIcon;

    // Register the window class.
    RegisterClassEx(&wc);

    m_hWnd = CreateWindowEx(
        WS_EX_OVERLAPPEDWINDOW,
        m_applicationName,
        L"Rescan Screen Reader",
        WS_CAPTION | WS_MINIMIZEBOX | WS_OVERLAPPED | WS_SYSMENU,
        (GetSystemMetrics(SM_CXSCREEN) - 500) / 2,
        (GetSystemMetrics(SM_CYSCREEN) - 300) / 2,
        500,
        300,
        NULL,
        NULL,
        m_hInstance,
        NULL
    );
}

void ScreenReader::InitRawInputDevices()
{
    // Initialize Keyboard
    rid[0].usUsagePage = 0x01;
    rid[0].usUsage = 0x06;
    rid[0].dwFlags = RIDEV_INPUTSINK;
    rid[0].hwndTarget = m_hWnd;
    // Initialize Mouse
    rid[1].usUsagePage = 0x01;
    rid[1].usUsage = 0x02;
    rid[1].dwFlags = RIDEV_INPUTSINK;
    rid[1].hwndTarget = m_hWnd;

    // Register RIDs
    RegisterRawInputDevices(rid, 2, sizeof(RAWINPUTDEVICE));
}

bool ScreenReader::IsMouseMove()
{
    POINT pt;
    GetCursorPos(&pt);
    bool result = !(m_prevMouseX == pt.x && m_prevMouseY == pt.y);
    m_prevMouseX = pt.x;
    m_prevMouseY = pt.y;
    return result;
}

LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    switch (message)
    {
    case WM_QUIT:
        PostQuitMessage(0);
        return 0;
    case WM_DESTROY:
        PostQuitMessage(0);
        return 0;
    default:
        return application->MessageHandler(hWnd, message, wParam, lParam);
    }
}

I wrapped ISpVoice into the SpeechSynthesis class.
speechsynthesis.h:
#ifndef _SPEECHSYNTHESIS_H_
#define _SPEECHSYNTHESIS_H_

#pragma warning(disable :  4996)

#define SPCAT_VOICES_ONECORE L"HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Speech_OneCore\\Voices"

#include <sapi.h>
#include <sphelper.h>
#include <atlbase.h>

class SpeechSynthesis
{
public:
    SpeechSynthesis();
    ~SpeechSynthesis();

    HRESULT Speak(LPCWSTR pwcs, DWORD dwFlags = SPF_PURGEBEFORESPEAK | SPF_ASYNC | SPF_IS_NOT_XML, ULONG *pulStreamNumber = NULL);
    HRESULT Resume();
    HRESULT Pause();
    HRESULT Stop();

    ISpVoice* getVoice();

private:
    CComPtr<ISpObjectToken> cpVoiceToken;
    CComPtr<IEnumSpObjectTokens> cpEnum;
    ISpVoice* pVoice;
    ULONG count;
};

#endif

speechsynthesis.cpp:
#include "speechsynthesis.h"

SpeechSynthesis::SpeechSynthesis()
{
    HRESULT hr = CoCreateInstance(CLSID_SpVoice, NULL, CLSCTX_ALL, IID_ISpVoice, (void **)&pVoice);
    if (SUCCEEDED(hr))
        hr = SpEnumTokens(SPCAT_VOICES_ONECORE, NULL, NULL, &cpEnum);
    if (SUCCEEDED(hr))
        hr = cpEnum->GetCount(&count);
    if (SUCCEEDED(hr))
    {
        cpEnum->Item(1, &cpVoiceToken);
        pVoice->SetPriority(SPVPRIORITY::SPVPRI_ALERT);
        pVoice->SetAlertBoundary(SPEI_PHONEME);
        pVoice->SetOutput(NULL, TRUE);
        pVoice->SetVoice(cpVoiceToken);
    }
    if (FAILED(hr))
    {
        MessageBox(NULL, "A fatal error has occured", "Error Message", MB_ABORTRETRYIGNORE);
    }
}

SpeechSynthesis::~SpeechSynthesis()
{
    pVoice->Release();
}

HRESULT SpeechSynthesis::Speak(LPCWSTR pwcs, DWORD dwFlags, ULONG *pulStreamNumber)
{
    return pVoice->Speak(pwcs, dwFlags, pulStreamNumber);
}

HRESULT SpeechSynthesis::Resume()
{
    return pVoice->Resume();
}

HRESULT SpeechSynthesis::Pause()
{
    return pVoice->Pause();
}

HRESULT SpeechSynthesis::Stop()
{
    return Speak(NULL);
}

ISpVoice * SpeechSynthesis::getVoice()
{
    return pVoice;
}

uiautomator.h
#ifndef _UIAUTOMATOR_H_
#define _UIAUTOMATOR_H_

#include <windows.h>
#include <oleacc.h>
#include <uiautomation.h>

#pragma comment(lib, "oleacc.lib")

class UIAutomator
{
public:
    UIAutomator();
    ~UIAutomator();

    HRESULT GetItemNameAtMousePoint(BSTR *pStr);
    HRESULT GetUIAutomationItemNameAtMousePoint(BSTR *pStr);
private:
    HRESULT InitUIAutomation();

private:
    IUIAutomation *m_automation;
};

#endif

uiautomator.cpp
#include "uiautomator.h"

UIAutomator::UIAutomator()
{
    SetProcessDPIAware();
    HRESULT hr = InitUIAutomation();
}

UIAutomator::~UIAutomator()
{
}

HRESULT UIAutomator::GetItemNameAtMousePoint(BSTR * pStr)
{
    POINT pt;
    GetPhysicalCursorPos(&pt);
    VARIANT varItem;
    IAccessible *pAcc;
    HRESULT hr = AccessibleObjectFromPoint(pt, &pAcc, &varItem);
    if (SUCCEEDED(hr))
    {
        hr = pAcc->get_accName(varItem, pStr);
        VariantClear(&varItem);
        pAcc->Release();
    }
    return hr;
}

HRESULT UIAutomator::GetUIAutomationItemNameAtMousePoint(BSTR * pStr)
{
    CONTROLTYPEID id;
    POINT pt;
    IUIAutomationElement *elem;
    VARIANT val;
    GetCursorPos(&pt);
    HRESULT hr = m_automation->ElementFromPoint(pt, &elem);
    if (SUCCEEDED(hr))
    {
        hr = elem->get_CurrentControlType(&id);
        if (SUCCEEDED(hr))
        {
            if (id == UIA_PaneControlTypeId)
                GetItemNameAtMousePoint(pStr);
            else if (id == UIA_EditControlTypeId)
            {
                hr = elem->GetCurrentPropertyValue(UIA_ValueValuePropertyId, &val);
                if (SUCCEEDED(hr))
                {
                    *pStr = SysAllocString(val.bstrVal);
                    VariantClear(&val);
                }
            }
            else
            {
                hr = elem->get_CurrentName(pStr);
            }
        }
        elem->Release();
    }
    return hr;
}

HRESULT UIAutomator::InitUIAutomation()
{
    HRESULT hr = CoCreateInstance(__uuidof(CUIAutomation), NULL, CLSCTX_INPROC_SERVER,
        __uuidof(IUIAutomation), (void**)&m_automation);
    return hr;
}

main.cpp
#include "vld.h"
#include "screenreader.h"
#include <memory>

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR pScmdline, int iCmdShow)
{
    std::unique_ptr<ScreenReader> app(new ScreenReader(hInstance, hPrevInstance, pScmdline, iCmdShow));
    return app->Exec();
}

If you don't have time to compile here's the program.
If you launch it and hover the mouse on the program window there is a lag when highlighting minimize and close button. Also sometimes the tts doesn't stop immediately when you hover at another object.
Compare this one to NVDA Screen Reader. You will notice the big difference.

A: It works for me with or without setting SetAlertBoundary(SPEI_PHONEME).
The following is my test code, you can have a try.
HRESULT hr = ::CoInitialize(nullptr);
if (FAILED(hr))
{
    return EXIT_FAILURE;
}
std::wstring text;

text = L"This is a sentence.";

CComPtr<ISpVoice> cpVoice;
// Create a SAPI voice
hr = cpVoice.CoCreateInstance(CLSID_SpVoice);
//cpVoice->SetAlertBoundary(SPEI_PHONEME);
// set the output to the default audio device
if (SUCCEEDED(hr))
{
    hr = cpVoice->SetOutput(NULL, TRUE);
}
// Speak the text
if (SUCCEEDED(hr))
{
    hr = cpVoice->Speak(text.c_str(), SPF_ASYNC | SPF_PURGEBEFORESPEAK, NULL);
}

text = L"The third type, a logarithm of the unsigned fold change, is undoubtedly the most tractable.";

Sleep(600);

hr = cpVoice->Pause();
hr = cpVoice->Resume();
hr = cpVoice->Speak(text.c_str(), SPF_ASYNC | SPF_PURGEBEFORESPEAK, NULL);

Sleep(10000);

::CoUninitialize();
if (SUCCEEDED(hr))
{
    return EXIT_SUCCESS;
}
return EXIT_FAILURE;

A: I finally got it!
CComPtr<ISpAudio> audio;
CSpStreamFormat format;
format.AssignFormat(SPSF_11kHz8BitMono);

Initialize audio
SpCreateDefaultObjectFromCategoryId(SPCAT_AUDIOOUT, &audio);

Then, set its format and set it as output to pVoice.
audio->SetFormat(format.FormatId(), format.WaveFormatExPtr());
pVoice->SetOutput(audio, FALSE);

Now I have access to the audio stream!
Now to Immediately stop the audio, call:
audio->SetState(SPAS_STOP, 0);

Then speak again using:
audio->SetState(SPAS_RUN, 0);
pVoice->Speak(L"This is a sentence", SPF_ASYNC | SPF_PURGEBEFORESPEAK, NULL);


text:
Q: Excel horizontal chart with color bars and a marker I need to create a diagram with sections (yellow to red) and a marker at a % position. This is just an example.

A: Image for exampleI did the following and it works:

*

*Set all column width to 1.25

*Insert values 1 - 100 in A1-CV1 and change the font colour to white to hide them

*Create your scale by filling the cells colour in red, yellow and green in A2-CV2

*In C3 use the following code =IF($E$6=A1,"▲","") and drag this along to CV3.

*In Cell E6 put your value you want to show on the scale.

The triangle will go underneath the cell set.

A: I convinced myself I didn't know how to do this. And maybe even that it probably couldn't be done in an easy way.
However...

This is a stacked bar chart. The data:

The "Green" series has two bars, but the one on top, which has a value that you change in cell A3, is set to no fill, no border, labels inside-end with the label formatted as a callout that points towards the gridline of the bar underneath it.

What I couldn't figure out a good way to do was the make the callout vertically on top of the gridline without it becoming out of place when you change the value.
Disclaimer: The whole thing falls apart if you change the shape of the chart. :)


text:
Q: longest subsequence with alternate signs Given an array of +ve and -ve integers. Write an algorithm to find longest subsequence with alternate signs.
If 0 is there in array, it can be considered as both +ve and -Ve.
Exampls : Array : 5,-9,4,0,-1,5,-5,3,0,2
Longest subsequence : [0,-1,5,-5,3,0,2] size: 7
I wrote one function, it's working fine , but is there any other better way?
void f (int A[],int N){
    int fIndex = 0;
    int eIndex = 0;
    int maxCount =0;
    int curCount =0;
    int start =0;

    for(int i=1;i<N;++i){
        if(A[i] > 0 && A[i-1]>=0){
            if(i>=2 && A[i-2] < 0){
            fIndex = i;
            curCount =0;
            }
        }

        if(A[i] < 0 && A[i-1] <=0){
            if(i>=2 && A[i-2] > 0){
                fIndex = i;
                curCount =0;
            }
        }

        if((A[i] > 0 && A[i-1] <= 0) || (A[i] <0 && A[i-1]>=0)){
            curCount++;
            if(curCount > maxCount){
                maxCount = curCount;
            }
            start = fIndex;
            eIndex = i;
        }else if(A[i] == 0){
            if(A[i-1]> 0){
                A[i] = -1;
            }
            curCount++;
            if(curCount > maxCount){
                maxCount = curCount;
            }
            eIndex = i;
        }
    }
    return maxCount+1;
}

A: There are only two possibilities for alternation like -+-+... or +-+-.... so we can just use two counters and reset them when a number comes we don't like:
int max = 0;
int[] l = {0, 0};
for (int i = 0; i < N; i++) {
  if (a[i] == 0) {
    l[0]++;
    l[1]++;
    continue;
  }
  int s = ((i % 2 == 0 && a[i] < 0) || (i % 2 == 1 && a[i] > 0)) ? 0 : 1;
  l[1-s]++;
  if (l[s] > max)
      max = l[s];
  l[s] = 0;
}
return max >= l[0] && max >= l[1] ? max : (l[0] >= l[1] ? l[0] : l[1]);


text:
Q: Location of Outlook 2003 data After doing a backup, then a reinstall of a client's Windows XP computer I forgot to create a .pst of their mail from outlook 2003. I have all the data from the old installation but I don't know where Outlook 2003 stores its data.
Where abouts can I find this data?

A: c:\documents and settings\\Local Settings\Application Data\Microsoft\Outlook\
by default for PSTs

A: Outlook 2003 saves its data in so called "Personal Folder Files" .pst, which is an acryonym for "Personal Storage Table."
The .pst personal folder file is stored in a folder of your Windows profile. If you don't change the path manually, the standard path on a Windows XP installation is
C:\Documents and Settings\PROFILE_NAME\Local Settings\Application Data\Microsoft\Outlook\

One important advice: if the user had "auto archive" enabled, there could be another (or more) .pst in your backup: archive.pst. The file contains objects which were exported in order to keep the main .pst file from growing too large. Search for all *.pst files.

A: If the data hadn't been backed up, the default file for the Outlook account files won't be .PST, but .OST.  Only backups and archives will have the .PST file extension.


text:
Q: Track duration of voice calls I am trying to develop and app that tracks how many minutes are being used for phone calls.
I am trying to get Call events (call received, call ended, etc) in my app.
I tried to run the sample code of CoreTelephonyDemo, but I am not getting any call events.
I tried this code in applicationWillResignActive but I am not getting any call events.
Below is a sample of what I am working on.  Any help/suggestions would be greatly appreciated.
- (void)applicationWillResignActive:(UIApplication *)application
{
   CTCallCenter *callCenter1 = [[CTCallCenter alloc] init];
    callCenter1.callEventHandler=^(CTCall* call)
    {
        if (call.callState == CTCallStateDisconnected)
        {
            NSLog(@"Call has been disconnected");
        }
        else if (call.callState == CTCallStateConnected)
        {
            NSLog(@"Call has just been connected");
        }
        else if(call.callState == CTCallStateConnected)
        {
            NSLog(@"Call is incoming");
        }
        else
        {
            NSLog(@"None of the conditions");
        }
    };
}


text:
Q: LTTNG: using with a popular library I have a trivially simple question that I could not find the answer yet.
Say, I have a shared library X that is used by 100 simultaneously running applications A0, A1, ... A99. I had instrumented my library and with LTTNG using "X-Provider" as the provider name.  How can my user distinguish between X-Provider events that happen in A10 and A15?

A: With the lttng command-line utility, add the vpid context field to be recorded to your event records, for example:
$ lttng add-context -u -t vpid

This targets all the user space channels of the current recording session; you can of course select a specific recording session and/or channel (see lttng-add-context(1)).
You need to use this command before you start the tracers (lttng start).
All your event records will have a context field named vpid which is the virtual IDs of the processes which emitted them.
Now, you need to find a way to associate such VPIDs to instance IDs (A10, A15, etc.). You can do so with your own application-specific strategy, or you can simply record an initial event when starting the application which indicates the instance ID/name, for example:
tracepoint(x_provider, app_state, app_id);

Then, when reading the resulting trace(s), you can correlate the x_provider:app_state event record info with the records of your library-emitted events. For example, using the Babeltrace 2 Python bindings:
import bt2

vpid_app_ids = {}

for msg in bt2.TraceCollectionMessageIterator('/path/to/trace'):
    if type(msg) is not bt2._EventMessageConst:
        continue

    vpid = int(msg.event.common_context_field['vpid'])

    if msg.event.name == 'x_provider:app_state':
        app_id = int(msg.event.payload_field['app_id'])
        vpid_app_ids[vpid] = app_id
    else:
        app_id = vpid_app_ids[vpid]

        # Continue to process `msg.event` knowing the instance ID is
        # `app_id`...

I didn't test the example above, but you get the gist.


text:
Q: I can't save a category in Magento 2.3.5-p2 - Probably after migration from 1.9.2 I migrated a store from version 1.9.2 to 2.3.5-p2, I had some issues at first, as with any migration I did before, but I sorted everything out. The migration was made with the official Magento migration tool.
After a while of having the store online, I tried to enable / disable a category, or even only trying to save it without any change, and I'd always get this error:
Something went wrong while saving the category.
along with:
Argument 1 passed to Magento\Catalog\Model\Category\FileInfo::removeStorePath() must be of the type string, array given, called in /vendor/magento/module-catalog/Model/Category/FileInfo.php on line 167
No error report is generated, and I can´t seem to find an issue on the debug, system or exception logs.
Everything else has been working fine, so I don´t know what the problem could be. So any help would be awesome.

EDIT:
I've found a "temporal solution" (I think). On this question:
Magento 2.3.4 - Error: Call to a member function getAttributeCode()
On the file: vendor/magento/module-catalog/Observer/InvalidateCacheOnCategoryDesignChange.php on line 67 I commented this part of code:
if ($this->isCategoryAttributeChanged($designAttribute->getAttributeCode(), $category)) {
            $this->cacheTypeList->invalidate(
                [
                    \Magento\PageCache\Model\Cache\Type::TYPE_IDENTIFIER,
                    \Magento\Framework\App\Cache\Type\Layout::TYPE_IDENTIFIER
                ]
            );
            break;
        }

And now I can edit my categories again. But I doubt that this is the right solution for this.


text:
Q: no module named pyfiglet.fonts failed to execute script due to unhandled exception I have recently compiled a .py file to an application and the .py works fine but the application gives me this error no module named pyfiglet.fonts
failed to execute script '' due to unhandled exception
then closes immediately
The modules im using :
from colorama import Fore
from selenium import webdriver
from time import sleep
import pyfiglet
from colorama import Fore
from selenium import webdriver
from time import sleep

A: This may be due to missing package/ incorrect virtual env being used to run the program.
you can verify the package's installation by running pip freeze in the terminal if you are not using an IDE in the first place.


text:
Q: Python, how to POST statuses/update_with_media to Twitter? I am able to successfully post status updates (tweet) in Python with that:
import urllib
import oauth2 as oauth

token = oauth.Token(access_token,access_token_secret)
consumer = oauth.Consumer(consumer_key,consumer_secret)

client = oauth.Client(consumer,token)

data = {'status': 'hello world'}
request_uri = 'https://api.twitter.com/1/statuses/update.json'

resp, content = client.request(request_uri, 'POST', urllib.urlencode(data))

Now I would like to know what I need to change to be able to post a picture with update_with_media?

A: At last i got it working and wanted to let know for people who is struggling with this how i finally easily did it with the nice Twython library, it abstract the functions nicely:
from twython import Twython

twitter = Twython(
    twitter_token = 'consumer_key',
    twitter_secret = 'consumer_secret',
    oauth_token = 'access_token',
    oauth_token_secret = 'access_token_secret'
)

twitter.updateStatusWithMedia('/home/blah/projects/pathexample/static/example.png', status='hello!')

A: Something along these lines perhaps ?
data = {'status': 'hello world'
      , 'media': ['image.jpg']
      }
request_uri = 'https://upload.twitter.com/1/statuses/update_with_media.json'

resp, content = client.request(request_uri, 'POST', urllib.urlencode(data))

This was just quickly scraped together by checking out Working with statuses/update_with_media and POST statuses/update_with_media and may not be correct.


text:
Q: WPF: Changing the layout of Tabs in TabPanel Instead of at the top I wan't my tabs on the left side. I changed the template for the the TabControl so that the TabPanel would appear in first column and the second column would host the content.
Problem is I'm not sure how I change the TabPanel's layout so the tabs appear stacked vertically.
I know in normal ItemsControl objects its the ItemsPanel that I should change. How can I do this?

A: I think you are talking about showing your TabItem's header to the left vertically. Take a look at the TabStripPlacement property. You can set it to left to achieve what you want.
<TabControl TabStripPlacement="Left">
    ...
    ...
</TabControl>


text:
Q: Show that limit of integral equals supremum of its set Let $f$ be continuous on $[a,b]$, let $f(x)$ $\geq$ $0$ for $x$ $\in$ $[a,b]$ , and let $M_n := (\int_a^b f^n)^{1/n}$.
Show that $$\lim(M_n) = \sup \{ f(x) : x \in [a,b] \}$$

A: Set $M = \sup\{f(x): x\in[a,b]\}.$ Let $\varepsilon>0$ and define $S_\varepsilon =\{x\in[a,b]:f(x)\geqslant M-\varepsilon\}$. Then
\begin{align}
M_n&=\left(\int_{[a,b]} f(x)^n\ \mathsf dx\right)^{\frac1n}\\&\geqslant \left(\int_{S_\varepsilon} (M-\varepsilon)^n\ \mathsf dx\right)^{\frac1n}\\
&\geqslant (M-\varepsilon)\mu(S_\varepsilon)^{\frac1n}
\end{align}
where $\mu$ is Lebesgue measure, so that
$$\liminf_{n\to\infty} M_n\geqslant M. $$ For the reverse inequality, if $n>m$ then
\begin{align}
\int_{[a,b]} f(x)^n\ \mathsf dx &= \int_{[a,b]} f(x)^{n-m}f(x)^m\ \mathsf dx\\
&\leqslant\int_{[a,b]}M^{n-m} f(x)^m\ \mathsf dx\\
&=M^{n-m}\int_{[a,b]} f(x)^m\ \mathsf dx
\end{align}
and hence
$$M_n \leqslant\left(M^{n-m}\int_{[a,b]} f(x)^m\ \mathsf dx\right)^{\frac1n}\leqslant M^{\frac{n-m}m}\left(\int_{[a,b]} f(x)^m\ \mathsf dx\right)^{\frac1n},  $$
so that
$$\limsup_{n\to\infty} M_n\leqslant M. $$


text:
Q: PyTorch Networks within a Model I would like to define a network that comprises many templates.  Below under Network Definitions is a simplified example where the first network definition is used as a template in the second one.  This doesn't work - when I initialise my optimiser is says that the network parameters are empty!
How should I do this properly?  The network that I ultimately want is very complicated.
Main Function
if __name__ == "__main__":

myNet       = Network().cuda().train()
optimizer   = optim.SGD(myNet.parameters(), lr=0.01, momentum=0.9)

Network definitions:
class NetworkTemplate(nn.Module):

def __init__(self):
    super(NetworkTemplate, self).__init__()
    self.conv1 = nn.Conv2d(1, 3, kernel_size=1, bias=False)
    self.bn1 = nn.BatchNorm2d(3)

def forward(self, x):
    x = self.conv1(x)
    x = self.bn1(x)

    return x

class Network(nn.Module):

def __init__(self, nNets):
    super(Network, self).__init__()

    self.nets = []
    for curNet in range(nNets):
        self.nets.append(NetworkTemplate())

    def forward(self, x):

        for curNet in self.nets:
            x = curNet(x)

        return x

A: Just use torch.nn.Sequential? Like self.nets=torch.nn.Sequential(*self.nets) after you populated self.nets and then call return self.nets(x) in your forward function?
If you want to do something more complicated, you can put all networks into torch.nn.ModuleList, however you'll need to manually take care of calling them in your forward method in that case (but it can be more complicated than just sequential).


text:
Q: CSS: Show checkmark in top right of a td I am trying to show a checkmark in the top right corner of a td. I can't seem to get it there without expanding the whole tr. This is my table:

<input type="text">	 <-- in this td the icon should be placed.
     ...more rows...

I just tried using a class for the icon and making the tr relative and the td relative but it keeps expanding the td's height.
Any ideas?

A: You can use first-child selector and background-position attribute to show icon on right top of first td
tr:first-child td:first-child
{
    background-image:url('http://files.softicons.com/download/toolbar-icons/iconza-light-green-icons-by-turbomilk/png/32/check_mark.png');
    background-position:right top;
    background-repeat:no-repeat;
    padding-right:35px;
    padding-top:5px;
    padding-bottom:5px;
}

You can shorten this like
tr:first-child td:first-child
    {
        background:url('http://files.softicons.com/download/toolbar-icons/iconza-light-green-icons-by-turbomilk/png/32/check_mark.png') no-repeat right top red;
        padding:5px 35px 5px 0
    }

JS Fiddle Demo

A: Since you cannot use a position rule on table cells (prohibited by standards, only strictly enforced by Gecko) you have to use a workaround with another element inside, or use some other solution. Also you shouldn't be generating images for 'semantic' stuff like this, use classes, makes it both easier to generate, and easy to manipulate with JS.
HTML

    ...data 1...
multiline

    ...data 2...

    ...data 3...

CSS
td{
    background:#fcf4cf;
}
td.checked:before {
    content:url(http://www.kyoceradocumentsolutions.com.au/Style%20Library/en-us/Images1/TickMark.gif);
    float:right;
    padding-left:4px;
}

See this work on JSFiddle
This is compatible with all major browsers and semantically more correct than your current approach, with shorter CSS and HTML.


text:
Q: Can I save my R output (.jpeg) to an FTP server? (optional read) Greater Objective: PowerBI Web doesn't support a few R packages when published on the internet. It throws the below error ("Missing R Package"). Hence, I am working towards saving the output from R as an image (.jpeg) to a remote location (such as FTP) or cloud storage (secure and open source) and then import it to PowerBI. This workaround might resolve the package conflict (hoping).

Specific Objective*: The below code illustrates a trivial way of saving an R output(.jpeg) image locally. However, is there a way to save the image directly to the FTP server, provided I have the username/password etc? (unfortunately, I cannot share the server details)
library(outbreaks)
library(incidence)

cases = subset(nipah_malaysia, select = c("perak", "negeri_sembilan", "selangor",
                                           "singapore"))

i = as.incidence(cases, dates = nipah_malaysia$date, interval = 7L)
jpeg(file = "plot.jpeg")
plot(i)
dev.off()

I did come across this post on employing ftpUpload function from the "rcurl" package. However, to upload it to FTP, I might still need to save it locally which defeats my purpose in this use-case.
Any suggestions would be helpful.

A: If saving a temporary file (as you suggested in a comment) is an option, then you can do that with the following code:
library(outbreaks)
library(incidence)
library(RCurl)

cases = subset(nipah_malaysia, select = c("perak", "negeri_sembilan", "selangor",
                                           "singapore"))

i = as.incidence(cases, dates = nipah_malaysia$date, interval = 7L)
jpeg(file = filename <- tempfile())
plot(i)
dev.off()
ftpUpload(filename, "ftp://User:Password@FTPServer/destfile.jpeg")

A: If you're ok with having the output in PNG format (EDIT: I updated the code to show output to JPEG format) try the code below, with chunks borrowed from this answer that discusses how to save an image in memory:
EDIT: Updated to output to jpeg format
library(outbreaks)
library(incidence)

cases = subset(nipah_malaysia, select = c("perak", "negeri_sembilan", "selangor",
                                          "singapore"))

orig_i = as.incidence(cases, dates = nipah_malaysia$date, interval = 7L)
plot(orig_i)

#### This section adapted from
#### https://stackoverflow.com/questions/7171523/in-r-how-to-plot-into-a-memory-buffer-instead-of-a-fileinstead-of-a-file
#### loads image data to memory rather than a file

library(Cairo)
library(png)
library(ggplot2)

Cairo(file='/dev/null')

plot(orig_i) #your plot

# hidden stuff in Cairo
i = Cairo:::.image(dev.cur())
r = Cairo:::.ptr.to.raw(i$ref, 0, i$width * i$height * 4)

dev.off()

dim(r) = c(4, i$width, i$height) # RGBA planes
# have to swap the red & blue components for some reason
r[c(1,3),,] = r[c(3,1),,]

# now use the jpeg library to write the raw vector
library(jpeg)
p = writeJPEG(r, raw()) # raw JPEG bytes

#DEBUGGING - check that this actually works
#Note: Windows 10 has an error that might report this as a file system error
#In windows, drag and drop the file into an open chrome window to see the image
writeBin(p, con= "yourpathhere/check_output.jpg")

#adapted code from @tfehring's example for the updload
library(RCurl)
ftpUpload(p, "ftp://User:Password@FTPServer/destfile.jpg")


text:
Q: Elasticseach - force a field to index only, avoid store How do I force a field to be indexed only and not store the data. This option is available in Solr and not sure if it's possible in Elasticseach.

A: From document

By default, field values are indexed to make them searchable, but they
  are not stored. This means that the field can be queried, but the
  original field value cannot be retrieved.
  Usually this doesn't matter. The field value is already part of the
  _source field, which is stored by default. If you only want to retrieve the value of a single field or of a few fields, instead of
  the whole _source, then this can be achieved with source filtering

If you don't want field to be stored in _source too. You can exclude the field from source in mapping
Mapping:
{
  "mappings": {
    "properties": {
      "title":{
        "type":"text"
      },
      "description":{
        "type":
      }
    },
    "_source": {
      "excludes": [
        "description"
      ]
    }
  }
}

Query:
GET logs/_search
{
  "query": {
    "match": {
      "description": "b" --> field description is searchable(indexed)
    }
  }
}

Result:
"hits" : [
      {
        "_index" : "logs",
        "_type" : "_doc",
        "_id" : "-aC9V3EBkD38P4LIYrdY",
        "_score" : 0.2876821,
        "_source" : {
          "title" : "a" --> field "description" is not returned
        }
      }
    ]

Note:
Removing fields from source will cause below issue

*

*The update, update_by_query, and reindex APIs.

*On the fly highlighting.

*The ability to reindex from one Elasticsearch index to another, either to change mappings or analysis, or to upgrade an index to a new major version.

*The ability to debug queries or aggregations by viewing the original document used at index time.

*Potentially in the future, the ability to repair index corruption automatically.


text:
Q: Why does the read() function return an error? I used the read() function to read the contents from a file but got a -1 return value. The file is not empty, I think it might be the problem of data type, but I am not sure.
The contents of the file are like this:
1e00 000a 0600 0003 0100 0004 0300 0005
0800 0006 0900 0007 0b00 0003 0c00 0009
Thanks in advance.
#define swapFname "test.disk"

int main(int argc, char const *argv[])
{
    int diskfd;
    unsigned *buf;
    diskfd = open (swapFname, O_RDWR | O_CREAT, 0600);
    int location = (2-2) * 16 * 8 + 0*8; // 0
    int ret = lseek (diskfd, location, SEEK_SET);
    int retsize = read (diskfd, (char *)buf, 32);
    if (retsize < 0)
    { printf ("Error: Disk read returned incorrect size: %d\n", retsize);
        exit(-1);
    }
}

A: I was able to reproduce your issue locally.  Having done so, I modified the program to be more informative about the nature of the problem: instead of printing a hand-rolled yet minimally-expressive error message, I used the perror() function to print a message that explains the specific nature of the error:
    if (retsize < 0) {
        perror("read");
        exit(-1);
    }

Running the resulting program produced this message:

read: Bad address

This seems to be reporting on the problem that @MichaelBurr noted in his comment: you have declared buf as a pointer to unsigned, but you have not assigned it to point to anything.  As a result, it is a dangling pointer, and you should consider yourself lucky that the read function was able to recognize that, instead of (probably) clobbering random memory somewhere in your program's address space.  It seems likely that you instead want to declare buf as an array, maybe something like this:
    unsigned buf[16];

With that additional correction, the program no longer reported an error from read().  That means it probably didn't have an error in open(), either, or in lseek(), but you ought to be testing each of those results individually.

A: first I suggest to check you have open the file correctly, if the file have been opened check lseek if does not return -1, and later if you still wonder why you got -1 in read check errno in order to see the last error code.


text:
Q: OSGi implementation for C? Is there any OSGi implementation available for C? My search has only resulted in Apache Celix, but there is no release available for Celix yet.

A: This article OSGi and C++ talks about some projects in OSGi for C and C++.

A: Apache Celix is the only publicly known C implementation of the OSGi specs.
They are planning a 0.0.1 release and there are also early efforts going on for standardising a C/C++ OSGi API. Celix can certainly use early adopters to help it mature and gain more acceptance.


text:
Q: If $n=p_1^{k_1}p_2^{k_2}p_3^{k_3}\cdots p_r^{k_r}$ for $n>1$ then which of the following is true?
If an integer $n>1$ has prime factorization $n=p_1^{k_1}p_2^{k_2}p_3^{k_3}\cdots p_r^{k_r}$ which of the following are true?

*

*$\sum_{d|n}\mu(d)\tau(d)=1$

*$\sum_{d|n}\mu(d)\tau(d)=p_1p_2\cdots p_r$

*$\sum_{d|n}\frac{\mu(d)}{d}=\sum_{i=1}^{r}\left( 1-\frac{1}{p_i}\right)$

*$\sum_{d|n}\mu(d)d=\prod_{i=1}^{r}(1-p_i)$

using $\phi(n)=n\sum_{d|n}\frac{\mu(d)}{d}$ I can show that 3 is not true. But for the rest I don't have any idea. I think we have to use Mobius Inversion formula, but don't know how? Any help please. Thanks.

A: For a full explanation:
1 and 2: The only nonzero terms of $\sum_{d|n}\mu(d)\tau(d)$ come from $d$ being a product of distinct primes. There are $\binom rs$ divisors which are a product of $s$ distinct primes, and each of these contributes $(-1)^s2^s$. So $$\sum_{d|n}\mu(d)\tau(d)=\sum_{s=0}^r\binom rs(-2)^s=(1-2)^r=(-1)^r.$$
3: as you say, $\phi(n)=n\sum_{d|n}\frac{\mu(n)}d$ gives the RHS as the product of those terms, not the sum, so this is wrong.
4: Since $d\mu(d)$ is multiplicative, so is $\sum_{d|n}d\mu(d)$, and the RHS is also multiplicative, so it enough to check it is correct when $n=p^k$. In this case only the terms corresponding to $d=1$ and $d=p$ are nonzero, and this gives $f(p^k)=1-p$, as required.