text:
Q: generating TTT game tree in lua I am attempting to write a tic-tac-toe game in lua, and plan on using the minimax algorithm to  decide non-human moves. The first step in this involves generating a tree of all possible board states from a single input state. I am trying to recursively do this, but cannot seem to figure out how. (I think) I understand conceptually how this should be done, but am having trouble implementing it in lua.
I am trying to structure my tree in the following manner. Each node is a list with two fields.
{ config = {}, children = {} }

Config is a list of integers (0,1,2) that represent empty, X, and O and defines a TTT board state. Children is a list nodes which are all possible board states one move away from the current node.
Here is my function that I currently have to build the game tree
function tree_builder(board, player)
    supertemp = {}

    for i in ipairs(board.config) do

        --iterate through the current board state.
        --for each empty location create a new node
        --representing a possible board state

        if board.config[i] == 0 then
            temp = {config = {}, children = {}}

            for j in ipairs(board.config) do
                temp.config[j] = board.config[j]
            end

        temp.config[i] = player
        temp.children = tree_builder(temp, opposite(player))
        supertemp[i] = temp
        end

    end
    return supertemp
end

The function is called in the following manner:
start_board = {config = {1,0,0,0}, children = {} }
start_board.children = tree_builder(start_board, 1)

When I comment out the recursive element of the function (the line "temp.children = builder(temp, opposite(player))") and only generate the first level of children. the output is correct. When called via code that is conceptually identical to (I am using love2D so formatting is different):
for i in pairs(start_board.children) do
    print (start_board.children[i].config)

The three children are:
1,1,0,0
1,0,1,0
1,0,0,1

However, once I add the recursive element, the following is output for the same three children
1,1,2,1
1,1,2,1
1,1,2,1

I have been searching online for help and most of what I have found is conceptual in nature or involves implementation in different languages. I believe I have implemented the recursive element wrongly, but cannot wrap my head around the reasons why.

A: Don't understand what opposite(player) means in temp.children = tree_builder(temp, opposite(player)).
Notice that a recursion need an end condition.
This is my solution under your structure:
local COL = 3
local ROW = 3

local function printBoard( b )
    local output = ""
    local i = 1
    for _,v in ipairs(b.config) do
        output = output .. v .. ( (i % COL == 0) and '\n' or ',' )
        i = i + 1
    end
    print( output )
end

local function shallowCopy( t )
  local t2 = {}
  for k,v in pairs(t) do
    t2[k] = v
  end
  return t2
end

local MAX_STEP = COL * ROW

local ING = 0
local P1 = 1
local P2 = 2
local TIE = 3

local STATUS = { [P1] = "P1 Win", [P2] = "P2 Win", [TIE] = "Tied" }

local start_board = { config = {P1,0,0,0,0,0,0,0,0}, children = {} }

local function checkIfOver( board, step )
    local config = board.config
    local over = false
    --check rows
    for i=0,ROW-1 do
        over = true
        for j=1,COL do
            if 0 == config[i*COL+1] or config[i*COL+j] ~= config[i*COL+1] then
                over = false
            end
        end
        if over then
            return config[i*COL+1]
        end
    end
    --check cols
    for i=1,COL do
        over = true
        for j=0,ROW-1 do
            if 0 == config[i] or config[i] ~= config[i+COL*j] then
                over = false
            end
        end
        if over then
            return config[i]
        end
    end
    --check diagonals
    if config[1] ~= 0 and config[1] == config[5] and config[5] == config[9] then
        return config[1]
    end
    if config[3] ~=0 and config[3] == config[5] and config[5] == config[7] then
        return config[3]
    end
    if step >= MAX_STEP then
        return TIE
    else
        return ING
    end
end

local function treeBuilder( board, step )
    --check the game is over
    local over = checkIfOver( board, step )
    if  over ~= ING then
        printBoard( board )
        print( STATUS[over], '\n---------\n' )
        return
    end
    local child
    local childCfg
    for i,v in ipairs(board.config) do
        if 0 == v then
            child = { config = {}, children = {} }
            childCfg = shallowCopy( board.config )
            childCfg[i] = (step % 2 == 0) and P1 or P2
            child.config = childCfg
            table.insert( board.children, child )
            treeBuilder( child, step + 1 )
        end
    end
end

treeBuilder( start_board, 1 )


text:
Q: Run service after device was restarted I want that one of my services runs even if user has restarted device. I've tried this code but didn't succeed. What should I do? Help me please.
Thank you!
MyService2.class:
public class MyService2 extends Service {
    private MyReceiver mR = null;
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override

    public int onStartCommand(Intent intent, int flags, int startId) {
        mR = new MyReceiver();
        IntentFilter intentFilter = new IntentFilter(Intent.ACTION_BOOT_COMPLETED);
        registerReceiver(mR, intentFilter);
    }
}

MyReceiver.class
public class MyReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)){
            context.startService(new Intent(context, MyService.class));
            context.startService(new Intent(context,MyService2.class));
        }
    }
}

A: You are Registering your BroadcastReciver in your Service , Which your trying to start using your BroadcastReciver which is not registered.
So try registering your broadcast Reciever in your manifest file like this
<receiver android:name="your broadcast class">
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
    </intent-filter

A: First no need to register your receiver in service. Add your broadcast receiver in Manifest.
Like :
<receiver android:name="your broadcast class">
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
        </intent-filter>

Remember to add permission also :
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

When device is rebooted your receiver will automatically get executed by system as it is declared in manifest. In your receiver just start your service.
public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
    if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)){
        //add a log or toast to confirm the receive
        context.startService(new Intent(context, MyService2.class));
    }
}

}
AND
public class MyService2 extends Service {
private MyReceiver mR = null;
@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override

public int onStartCommand(Intent intent, int flags, int startId) {
    // do what ever you wanted to do...
}

}

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I calculate how many push-ups will be done in a year, if I start with 1 a day, the first week, 2/day the second, etc? My son is doing 1 pushup each night before bed, 7 days a week. Then he is adding an additional pushup for the second week (total of 14). Then 3/night the 3rd week, and so on. Can you show me a method of determining how many he will do in a year, if he keeps this up? Thanks.

A: $365=7 \cdot 52 + 1$. So if we assume that this is NOT a leap year, and your son starts doing pushups on the first day of the year, the number of pushups done = $7(1+2+\dots + 52) + 53$ = $\dfrac{7 \cdot 52 \cdot 53}{2} + 53=9699$.
If it is a leap year, the number of pushups = $\dfrac{7 \cdot 52 \cdot 53}{2} + 2 \cdot 53=9752$.

A: Your comment indicated that you didn't see how Ayush's answer worked, so here's an explanation.
To make things simple, we'll just look at the number of pushups performed by the end of week 52. In week 1, he'll have done 7, in week 2, at 2 per day, he'll do 14, and so on. The total number of pushups done by the end of week 52 will then be
\begin{align}
P &= 7 + 14 + 21 + \dots + 7\times 50 + 7\times 51 + 7\times 52\\
&= 7 + 14 + 21 + \dots + 350 + 357 + 364
\end{align}
Now add $P$ to itself, written in reverse:
\begin{array}{ccccccccccccc}
P &= 7 &+ &14 &+ &21 &+ &\dots &+ &350 &+ &357 &+ &364\\
P &= 364 &+ &357 &+ &350 &+ &\dots &+ &21 &+ &14 &+ &7
\end{array}
The sum of the first two terms is $(7 + 364) = 371$. That's also the sum of the second two terms, $(14+357)$, since we added and subtracted 7 to the two terms. By the same reasoning, the sum of each of the 52 pairs will also be 371, so when we add all 52 of the pairs we'll have
$$
2P = 371 + 371 + 371 + \dots + 371 + 371 + 371 = 52\times 371
$$
and so $P = (52 \times 371)/2 = 9646$.
This holds in general, too, if you're adding a bunch of terms where each of the adjacent pairs have the same difference (7, in this example, known as an arithmetic sequence): the sum will be
$$
\frac{(\text{number of terms})\times(\text{first term} + \text{last term})}{2}
$$


text:
Q: hiding of template parameter of member template from temp.local :

In the definition of a member of a class template that appears outside
  of the class template definition, the name of a member of the class
  template hides the name of a template-parameter of any enclosing class
  templates (but not a template-parameter of the member if the member is
  a class or function template).
  [ Example:
template<class T> struct A {
  struct B { /* ... */ };
  typedef void C;
  void f();
  template<class U> void g(U);
};

template<class B> void A<B>::f() {
  B b;              // A's B, not the template parameter
}

template<class B> template<class C> void A<B>::g(C) {
  B b;              // A's B, not the template parameter
  C c;              // the template parameter C, not A's C
}

— end example ]

the problem is that, each compiler, that i have tried ( g++, vc, icc, clang ), treats C in A<B>::g(C) as A's member name and doesn't compile that example.
Is this a common bug.?

A: While the link you gave appears to be a draft and explicitly states it is not a part of any standard (http://eel.is/c++draft/), this particular clause in the draft appears to be identical to ISO C++ 14.6.1, paragraph 7.
So it does indeed seem to be either a common compiler bug or a clause that conflicts with and lost out to other clauses. I verified the example doesn't compile on MacOS Clang v802.0.42). Since you say all the major compilers emit errors here, I would suspect this clause is not reasonable to implement due to conflicts with some other clause(s).
EDIT: I also found a discussion within the standards community here related to this topic. The depth with which it gets discussed here suggests to me that this rule is contentious and may even be changed.


text:
Q: Sending XML input to WSDL using SoapClient I have this WSDL: https://secure.softwarekey.com/solo/webservices/XmlCustomerService.asmx?WSDL
I am trying to use SoapClient to send a request to the CustomerSearch method.
The code I'm using is as follows:
$url = 'https://secure.softwarekey.com/solo/webservices/XmlCustomerService.asmx?WSDL';
$client = new SoapClient($url);

$CustomerSearch = array(
    'AuthorID' => $authorID,
    'UserID' => $userID,
    'UserPassword' => $userPassword,
    'Email' => $customerEmail
);

$xml = array('CustomerSearch' => $CustomerSearch);

$result = $client->CustomerSearch(array('xml' => $xml));

When I run the code, I get the following PHP exception:
Fatal error: Uncaught SoapFault exception: [Client] SOAP-ERROR: Encoding: object has no 'any' property

I have also tried this for the XML:
$xml = "
<?xml version=\"1.0\" encoding=\"utf-8\"?>
<CustomerSearch>
    <AuthorID>$authorID</AuthorID>
    <UserID>$userID</UserID>
    <UserPassword>$userPassword</UserPassword>
    <Email>$customerEmail</Email>
</CustomerSearch>
";

Which gives me the following results (from a print_r):
object(stdClass)#4 (1) { ["CustomerSearchResult"]=> object(stdClass)#5 (1) { ["any"]=> string(108) "-2Invalid Xml Document" } }

The documentation says that the input XML should look something like this:
<CustomerSearch>
<AuthorID></AuthorID>
<UserID></UserID>
<UserPassword></UserPassword>
<SearchField></SearchField>
<SearchField></SearchField>
<!-- ...additional SearchField elements -->
</CustomerSearch>

I'm fairly new to Soap and I've tried messing around (passing in raw, typed out XML), and can't seem to get this to work.  Any insight on what I may be doing wrong would be greatly appreciated.

A: I think you need to look more into the documentation (with regards to the any parameter). But your request should be something like this:
$url = 'https://secure.softwarekey.com/solo/webservices/XmlCustomerService.asmx?WSDL';
$client = new SoapClient($url);

$xmlr = new SimpleXMLElement("<CustomerSearch></CustomerSearch>");
$xmlr->addChild('AuthorID', $authorID);
$xmlr->addChild('UserID', $userID);
$xmlr->addChild('UserPassword', $userPassword);
$xmlr->addChild('Email', $customerEmail);

$params = new stdClass();
$params->xml = $xmlr->asXML();

$result = $client->CustomerSearchS($params);

EDIT: This is how I've done it in similar project. It may not be best practice. SoapVar might be the better way to do it (SoapVoar example with ANY_XML).

A: try passing $client->CustomerSearch($CustomerSearch); or pass a string


text:
Q: How do you set a specific part of the output of a CMD batch command as a variable? or alternatively, just echo it? I'm writing a simple little batch file that gets the password of a saved Wi-Fi network, but I want to grab the Key Content, then paste it on its own. Here's the current code:
@echo off
set /p name=Enter Wi-Fi Name:
cls
echo %name%
netsh wlan show profile name="%name%" key=clear
cmd /k

This gives me a long list of data, but the line I'm looking for is the "Key Content" line. What I essentially want to do is grab the "Key Content" line, clear all the lines, then echo the "Key Content" line. Is this possible without any plugins on Windows 11?
I'm new to the site and coding as a whole, by the way, so what may seem like something completely obvious to you is something I have a 95 percent chance not to know. Thank you!

A: Here's a batch-file snippet, based upon you having received and properly validated the end users input:
@For /F "Tokens=1,* Delims=:" %%H In ('
 %SystemRoot%\System32\netsh.exe WLAN Show Profiles Name^="%name%" Key^=Clear
 2^>NUL ^| %SystemRoot%\System32\findstr.exe /RIC:"^[ ][ ]*Key Content[ ][ ]*: "
') Do @(Set "}=%%I" & SetLocal EnableDelayedExpansion
    For %%J In ("!}:~1!") Do @EndLocal & Echo(%%J)

You should always perform robust validation of any end users input, especially when using the Set /P command, which can accept nothing or absolutely anything, (including malicious content). If the target systems are Windows 8 / Server 2012 or above, then I wouldn't waste time asking the end user to self-determine the wireless profile name, and then type it correctly at a prompt. I'd just output all of the profile names, along side their returned keys.
The following examples are untested, and assume that your 'passwords' do not include double-quote characters. They should provide the output in a CSV-like format, ("ProfileName","Password"):
@For /F Tokens^=6^ Delims^=^" %%G In ('%SystemRoot%\System32\wbem\WMIC.exe
 /NameSpace:\\Root\StandardCimv2 Path MSFT_NetConnectionProfile Get Name
 /Format:MOF 2^>NUL') Do @For /F "Tokens=1,* Delims=:" %%H In ('
 %SystemRoot%\System32\netsh.exe WLAN Show Profiles Name^="%%G" Key^=Clear
 2^>NUL ^| %SystemRoot%\System32\findstr.exe /RIC:"^[ ][ ]*Key Content[ ][ ]*: "
') Do @(Set "}=%%I" & SetLocal EnableDelayedExpansion
    For %%J In ("!}:~1!") Do @EndLocal & Echo("%%G",%%J)
@Pause

As you appear to have used the cmd tag, despite your question being about a batch-file, you could probably do similarly, directly in the Command Prompt, (cmd.exe) too:
For /F Tokens^=6^ Delims^=^" %G In ('%SystemRoot%\System32\wbem\WMIC.exe /NameSpace:\\Root\StandardCimv2 Path MSFT_NetConnectionProfile Get Name /Format:MOF 2^>NUL') Do @For /F "Tokens=1,* Delims=:" %H In ('"%SystemRoot%\System32\netsh.exe WLAN Show Profiles Name="%G" Key=Clear 2>NUL | %SystemRoot%\System32\findstr.exe /RIC:"^[ ][ ]*Key Content[ ][ ]*: ""') Do @Set "}=%I" & For /F Delims^=^ EOL^= %J In ('%SystemRoot%\System32\cmd.exe /V /D /C "Echo "%G","!}:~1!""') Do @(Set /P ="%J") 0<NUL & Echo(


text:
Q: I added new RAM modules to my system, now I get unexpected shutdowns, why? Some days ago I increased my laptop's Memory to 16GB, Now  I'm facing unexpected shutdown, how I can check the reason my laptop is holding Ubuntu 13.10
Linux inspiron-3521 3.11.0-15-generic #23-Ubuntu SMP Mon Dec 9 18:17:04 UTC 2013 x86_64 x86_64 x86_64 GNU/Linux

A: Suggest you revert to your original memory configuration and run with that for a week. If the problem does not return, then change to the 16GB configuration. If the problem then returns, your memory is defective.

A: You can use a program like MemTest86+ to test your memory. I always run the test overnight whenever i do an installation/upgrade of memory. This will let you know if you got some bad RAM.
Here is a link to the MemTest+ website: http://www.memtest.org/
If you get any errors at all then you know you have something wrong with your RAM. You can then pull the new sticks you installed for the upgrade and run the test again to make sure that you are not getting the errors from the old memory.

A: An easier way to test memory is to hold [shift] on startup. Then in the menu, choose "Test memory"
The test is quite long.


text:
Q: Difference between N[CDF[NormalDistribution[m,s],x]] and CDF[NormalDistribution[m,s],x]? I'm new to Mathematica and I am struggling with the following problem:
If I evaluate the expression N[CDF[NormalDistribution[m,s],x]] for m=12, s=25 and x=10, i get 0.468119 (=the value I would expect), however, if I evaluate the expression CDF[NormalDistribution[m,s],x] for the same x,m,s, i get 0.324195.
I checked the documentation for Mathematica and I cannot spot the difference except that N[..] returns the numerical value of the expression inside the brackets.
Any ideas? Perhaps its soo simple but i don't see it..
Thank you


text:
Q: how keep ActiveTabIndex after reloading the page / doing postback? I'm trying to make an UI where, after uploading an image, the page must do a reload/postback without a TabContainer(ajaxcontroltoolkit) changing its ActiveTabIndex, but the default postback of the button(asp:button) causes me troubles when i try to realod the page via browser manually, it tries to re-do the last method used by the button if i don't use the next code (to reload the page):

Administrar.aspx.cs:

ScriptManager.RegisterStartupScript(this, this.GetType(), "key", "ShowMessage()", true);

JavaScript related function:

function ShowMessage()
{
    alert('Exito al cargar imagen.');
    window.location.href = 'Administrar.aspx';
}

BUT!, if i use this code when the page is reloading i loss the ActiveTabIndex.
All i want to do is, to keep an ActiveTabIndex when uploading an image to the database without having troubles with the browser manual reload, can you please tell me what i'm doing wrong or what can i do? i'm stuck on this for days.
here's the code for a better understanding:
FrontEnd:
<asp:TabContainer ID="TabContainer1" CssClass="cssTab" runat="server">

            <asp:TabPanel runat="server" ID="TabPanel1" HeaderText="INFORMACIÓN">
                        <ContentTemplate>

...

...

                        </ContentTemplate>
                    </asp:TabPanel>

            <asp:TabPanel runat="server" ID="TabPanel2" HeaderText="IMÁGENES">
                        <ContentTemplate>

Agregar Imagenes

                                Relación:
                                <asp:DropDownList CssClass="elementControl2" DataValueField="idInformacion" DataTextField="RelGal" ID="ddlRelacionGaleria" runat="server"></asp:DropDownList>

                                Imagen:
                                    <asp:RequiredFieldValidator ValidationGroup="grpImg" ID="RequiredFieldValidator12" runat="server" ErrorMessage="*Imagen Invalida." ControlToValidate="FilUplIMG" ForeColor="#CC3300"></asp:RequiredFieldValidator>

                                <asp:FileUpload ID="FilUplIMG" runat="server" CssClass="elementControl2" />

                                <asp:Button runat="server" ID="btnAgrImg" OnClick="btnAgrImg_Click" CssClass="btnAgregarPropiedad" Text="AGREGAR" />

                                <asp:UpdatePanel runat="server" UpdateMode="Conditional">
                                    <ContentTemplate>
                                       <asp:GridView runat="server" ID="gvImg" CssClass="gvImg2">...</asp:GridView>
                                       <asp:Label ID="lblPage2" CssClass="lblPage" runat="server" ForeColor="Blue"></asp:Label>
                                    </ContentTemplate>
                                </asp:UpdatePanel>

                        </ContentTemplate>
                    </asp:TabPanel>
 </asp:TabContainer>

BackEnd(Just the button for adding):
public void btnAgrImg_Click(object sender, EventArgs e)
{
    if (FilUplIMG.PostedFile != null)
    {
        string FileName = Path.GetFileName(FilUplIMG.PostedFile.FileName);

        MySqlConnection con = new MySqlConnection(strConnString);

        string strQuery = "insert into inmobiliarialrz.galeria (fkrelation, Relation, FileName, FilePath) values (@fkrelation, @Relation, @FileName, @FilePath)";

        MySqlCommand cmd = new MySqlCommand(strQuery);
        if (File.Exists(Server.MapPath("~/ImagenesPROP/") + FileName))
        {
            string script = "alert(\"Ya existe esta imagen.\");";
            ScriptManager.RegisterStartupScript(this, GetType(), "ServerControlScript", script, true);
        }
        else
        {
            //save files in the disk
            FilUplIMG.SaveAs(Server.MapPath("~/ImagenesPROP/" + FileName));

            cmd.Connection = con;
            cmd.Parameters.AddWithValue("@fkrelation", ddlRelacionGaleria.SelectedValue);
            cmd.Parameters.AddWithValue("@Relation", ddlRelacionGaleria.SelectedItem.Text);
            cmd.Parameters.AddWithValue("@FileName", FileName);
            cmd.Parameters.AddWithValue("@FilePath", "~/ImagenesPROP/" + FileName);
            cmd.CommandType = CommandType.Text;
            try
            {
                con.Open();
                cmd.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                lblFail.Visible = true;
                lblFail.Text = ex.Message;
            }
            finally
            {
                con.Close();
                con.Dispose();
            }
            this.MostrarImagen2();//this is a method to show data in a gridview.
            lblFail.Text = "";
            ScriptManager.RegisterStartupScript(this, this.GetType(), "key", "ShowMessage()", true);
            TabContainer1.ActiveTabIndex = 1;//here i'm trying a desperate move.
        }
    }
}


text:
Q: Should I link badly asked questions to Raymond? I recently encountered a vague question on Stack Overflow which asked for instructions on a very basic operation in C++. I added an answer linking to a Google results page, which contained very easy tutorials as top hits, as well as linking a few of these hits directly.
The asker commented that he "tried these links but not of much help..!!" and I answered that "we can't really help you if you don't tell us what you tried and what went wrong".
At that point I felt compelled to link to The Old New Thing:

You may also want to have a look
  at Raymond Chen's blog. He's regularly
  providing interesting reads.

Is this acceptable? Or does it sound too rude? I want to give clear advice as to the uselessness of his question as it is without sounding too mean.

A: If it's a total newbie, I'd recommend either taking the time to point out (briefly but not rudely) what info is missing, or quietly leave the question alone.
The blog links may contain valuable info on how to ask better questions, but I doubt they will be of real help in most situations. I'd reserve those for people who chronically ask bad questions and show no improvement.

A: A newbie absolutely loves people who guide them. Help them, if providing a link to Raymond or whatever is necessary do that. Do not rick roll or abuse them.

A: Link them to
https://stackoverflow.com/questions/ask-advice
Note that this is a mandatory clickthrough page for new users who ask questions.


text:
Q: DX - List of Bundle/Prefix types? With the DX CLI you can't deploy certain individual files - ex. aura and lightning components. You have to use syntax like
sfdx force:source:deploy -m AuraDefinitionBundle:<aura bundle name>,ApexClass:<some class name> and so on.
Is there any definitive list of all possible types of 'prefixes' like AuraDefinitionBundle: in SFDC docs? I've not yet come across one on https://developer.salesforce.com/docs/atlas.en-us.sfdx_cli_reference.meta/sfdx_cli_reference/cli_reference.htm
Thanks!

A: You can use any of the types in the Metadata Types documentation. There is mostly a 1:1 relationship to those metadata types for the force:source:retrieve command. Settings are kind of an exception (e.g. Address Settings would be retrieved using Settings:Address), but I think that's the only one.
Edit: Updated Link. The types are located in the left nav menu.


text:
Q: Navigate from one fragment to another fragment on click of a button This is the code II implemented by googling and reading another stack overflow answers. but any answer is not working for me.
Following code this error - "No view found for id 0x7f09009e
Please help me to implement this
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);

//////more code here //////

OnClickListener listner = new OnClickListener() {

            @Override
            public void onClick(View v) {
                Fragment fragment=null;
                if(v==rootView.findViewById(R.id.Button)){
                    fragment = new SortListFragment();
                }
                FragmentManager manager =getFragmentManager();
                FragmentTransaction transaction = manager.beginTransaction();
                transaction.replace(R.id.fragment_sort, fragment);
                transaction.commit();

            }
        };

         ImageButton btn = (ImageButton)rootView.findViewById(R.id.button);
         btn.setOnClickListener(listner);

        return rootView;
    }

A: ButtonOnClickInterface interface;
public void onCreateView(//parameters){
   View view=//inflate the view;
   Button button =(Button)view.findViewById(R.id.buttonId);
   button.setOnClickListener(new View.OnclickListener{
       @Override
       public void onClick(View v){
           try{
              interface.onClick();
           }catch(Throwable e){
              //may be null
           }
       }
   });
}

@Override
public void onAttach(Context c){
   super.onAttach(c);
   try{
      interface=(ButtonOnClickInterface)c;
   }catch(Throwable e){
      //not implemented
   }
}

And your interface
interface ButtonOnClickInteface{
   void onClick();
}

Implement this interface in your activity.

A: Add this line above on click listner:
rootview = inflater.inflate(R.layout.<your layout xml>, container,
                    false);

A: I think you forgot to provide layout file in which you have put buttons and all.
So please provide below line in your code after "super.OnCreateView()"
  rootView = inflater.inflate(R.layout.your_layout_file, container, false);

And then check it is working or not, hope this will work


text:
Q: React/Redux, useEffect/useSelector, stale closures and event listeners I have a React/Redux class component which I'm converting to a functional component.
Previously, it had a componentDidMount callback which added an event listener for a custom event dispatched from elsewhere in the app. This is being replaced by useEffect. The event listener, on triggering, calls a method elsewhere in this component.
This method performs actions which depend on the values retrieved from a selector. Initially I was passing useEffect an empty array of dependencies so it would only add the event listener on mount. However, obviously this results in a stale closure around the selector values. A working solution is to pass it the selector as a dependency – however, this results in the listener being removed/re-added every time the value of the selector changes, which isn't great.
I'm trying to think of a solution which only adds the event listener the one time while allowing the called method to access the current value of the selector.
Example code:
const currentValue = useSelector(state => getValue(state));

useEffect(() => {
  document.addEventListener('my.custom.event', handleEvent);

  return(() => document.removeEventListener('my.custom.event', handleEvent));
}, []);

const handleEvent = () => {
  console.log(currentValue)
}

As is, this creates a stale closure around currentValue so that on event trigger, the value logged isn't necessarily the most recent.
Changing [] to [currentValue] in useEffect results in the expected behavior, but removes/re-adds the event listener on every change of currentValue.
Since this isn't a state value of the component, there's no option to use a callback like console.log(currentValue => console.log(currentValue)) to access the most recent value. I also played around with using useRef to hold onto the value, but I believe I'd need some way to update the ref value every time the selector's value changes, which isn't much of a solution.
In the actual component, the value of currentValue is modified in Redux by other components so changing it into a state value isn't really workable either.
I'm wondering:

*

*whether there's a solution to refreshing the value of the selector in the called method;

*whether the only solution is to remove/re-add the listener on dependency change, or;

*whether it's best to just leave this component as a class component and bypass this issue entirely (componentDidMount doesn't suffer from the stale closure issue.)

A: The useRef method is usually the solution for this problem, but you'll need another useEffect to update the ref with the currentValue:
const currentValue = useSelector(state => getValue(state));
const valueRef = useRef();

useEffect(() => { valueRef.current = currentValue; }, [currentValue]);

useEffect(() => {
  const handleEvent = () => {
    console.log(valueRef.current)
  }

  document.addEventListener('my.custom.event', handleEvent);

  return(() => document.removeEventListener('my.custom.event', handleEvent));
}, []);

However, you can also extract the entire function out of the useEffect, and use it in a hook, so you can easily create a custom hook for event handling:
const useEventHandler = (eventName, eventHandler, eventTarget = document) => {
  const eventHandlerRef = useRef();

  useEffect(() => {
    eventHandlerRef.current = eventHandler;
  });

  useEffect(() => {
    const handleEvent = (...args) => eventHandlerRef?.current(...args);

    eventTarget.addEventListener(eventName, handleEvent);

    return (() => eventTarget.removeEventListener(eventName, handleEvent));
  }, []);
}

Using the hook:
const currentValue = useSelector(state => getValue(state));

useEventHandler('my.custom.event', () => console.log(currentValue))

A:
however, this results in the listener being removed/re-added every time the value of the selector changes, which isn't great.

Why is it a problem? Does it affect performance of your app in any measurable way? From an immutability point of view, if the value change, then the event listener does something different, so it makes sense to simply replace the event listener by a different one.
If the value changes many times a second (for instance at every frame or every mousemove), then it does create a small performance hit, in which case Ori Drori's solution might be a good one, but it makes the code harder to understand and the performance gain is pretty small.
But if the value only changes a few times a second or less often, I would not worry at all about adding and removing the event listener.


text:
Q: Can PostgreSQL join to a stored procedure? In SQL Server and Oracle, joining to (or selecting from) stored procedures that return a resultset is not supported.
Is it possible in PostgreSQL?
If so, a followup question is:  is it possible, perhaps via foreign data wrappers, to join to a stored procedure within an MS SQL Server database??

A: PostgreSQL can join to a stored procedure (function). Tables and rows to get us started.
create schema test;
create table test.test_a (
  id integer primary key
);

insert into test.test_a values
(1), (2);

create table test.test_b (
  id integer references test.test_a,
  n integer not null,
  primary key (id, n)
);

insert into test.test_b values
(1, 1), (1, 2), (1, 3), (2, 1), (2, 2);

A simple function.
create or replace function test.return_test_b ()
  returns table (
            id integer,
            n integer
          ) as
$$
    select * from test.test_b
$$ language sql;

Now you can join directly.
select A.id, B.n from test.test_a A
inner join test.return_test_b() B on A.id = B.id;

id  n
--
1   1
1   2
1   3
2   1
2   2


text:
Q: Displaying text next to an icon using styled components in React new to React and using styled components, but I'm building a header component that essentially has two black bars - the top bar (StyledApplicationBanner) which contains the logo and then (StyledBackBar) which contains the back arrow (an SVG) - my current code has everything where I want it in terms of positioning but I'm not sure how to make my
``back
 text align alongside the arrow? Can anyone suggest a starting point for making this happen?
import styled from "styled-components";
import icon from "./myicons-icon-light.png";
import arrow from "./arrow-left.svg";

const StyledApplicationBanner = styled.header`
  background: black;
  height: 64px;
  width: 100%;
  border-bottom: 1px solid rgb(151, 153, 155);
`;

const StyledBackBar = styled.div`
background: black;
height: 48px;
width: 100%;
color: white;

p {
  color: white;
  font-size: 12px;
  font-weight: bold;
  letter-spacing: 1px;
  line-height: 16px;
  text-transform: uppercase;
}
`;

const Icon = styled.img`
  height: 22px;
  width: 116px;
  margin-top: 21px;
  margin-left: 96px;
`;

const Arrow = styled.img`
  height: 32px;
  width: 32px;
  margin-top: 8px;
  margin-left: 88px;
`
  return (

  );
};

export default ApplicationHeader;

A: Use display: flex with align-items: center :
const StyledBackArrow = styled.div`
  display: flex;
  flex-direction: row;
  align-items: center;
`;

...

...

div {
  display: flex;
  flex-direction: row;
  align-items: center;
}

img {
  margin-right: 10px;
}

  Back


text:
Q: Adding Google Chrome to UNIX $PATH I recently got entangled by the UNIX file system and was playing around with terminal. I noticed that however I changed my $PATH variable, running "Google Chrome", the executable for opening up the Chrome Window, gives me error message of

-bash: Google Chrome: command not found

Here's the context:
Google is installed on my /Applications/Google Chrome.app/Contents/MacOS as an executable called "Google Chrome" (I know that because when I type

/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome

a new Chrome window pops out with an error message saying

[12838:35843:0822/170630.283203:ERROR:browser_gpu_channel_host_factory.cc(103)] Failed to launch GPU process.

so I'm pretty sure this is the executable for running the program)
Then I did a little digging on $PATH variable which is supposed to maintain the searching path of where to find the executables everytime I type a "command" (or exe doesnt matter). Therefore, I went to ~ and find the file called .bash_profile where $PATH is edited and stored and append this to the file:

PATH="/Applications/Google\ Chrome.app/Contents/MacOS:${PATH}"
    export PATH

Then I source ~/.bash_profile and echo $PATH to that indeed the directory containing Chrome executable is inserted as part of $PATH as follow:
>  echo $PATH

/Applications/Google\ Chrome.app/Contents/MacOS:/Library/Frameworks/Python.framework/Versions/3.6/bin: ...

Then when I type Google\ Chrome, the system responds with "command not found". I went further more to do whereis Google\ Chrome and which Google\ Chrome, yet I got no response that forces me to believe Google Chrome is not the among the executing path.
Here's question, what did I do wrong when trying to edit $PATH to make Chrome easier to access? Is it because the way I understand $PATH is wrong? Or is it because I miss some tiny details? As far I know, I should have Chrome running as other applications like python and cassandra with the same $PATH edit but I didn't. Please share your precious insights with me on the topic. Your time and effort is very much appreciated :)

A: What you did wrong was putting the backslash into the variable as a literal; this has the shell trying to find a directory with a backslash in its name. (Because the backslash is present in the output of echo, we know that it actually ended up in the final variable, rather than being recognized as an effectively meaningless sequence and discarded).
Inside quotes, the space is already known to be literal, so there's no point to an additional backslash;
PATH="/Applications/Google Chrome.app/Contents/MacOS:$PATH"

...will suffice. (There's no need to explicitly export: Updating any shell variable named identically to a preexisting environment variable will automatically alter the latter).

By the way -- if you want to define a shell function so you can call chrome http://example.com/, that might look like:
chrome() { '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome' "$@"; }

Unlike aliases, functions can be exported (export -f chrome) to make them available to other instances of bash; they're also able to perform logic (such as inspecting their arguments and having different behaviors based on what they're passed).


text:
Q: rotating a text label
Possible Duplicate:
Objective C: How can you rotate text for UIButton and UILabel?

I am trying to rotate a IOS textlabel 180 degrees.
When I try rotating the label with:
[timeField layer].transform = CATransform3DMakeRotation(M_PI, 1.0, 0.0, 0.0);

All the separate characters are rotated individually, so the resulting text is mirrored.
How can I rotate the whole label, without the mirrored order of the characters?
When I do an animation, the rotation is OK.

A: You have to rotate the label with the property transform, something like:
timeField.transform = CGAffineTransformMakeRotation (3.14/2);

Hope this helps


text:
Q: Get POST body and return it to the browser I have implemented a proxy using sockets in Java.
Now I'm experiencing a problem with POST method, I mean, I'm able to capture the POST request, but I don't know how I have to proceed to capture the content (the body, not the headers) of this POST request, once done I would like to return the content to the browser (I need to implement this because when for example I try to login using my username and password it does nothing).
I capture the request using this code:
while ((buffer = in.readLine()) != null){
    System.out.println(buffer);
    headers[i] = buffer;
    i++;

    if(buffer.startsWith("GET")){
        String[] splitText = buffer.split(" ");
        url = splitText[1];
        post = false;
    }
    if(buffer.startsWith("POST")){
        String[] splitText = buffer.split(" ");
        url = splitText[1];
        post = true;
    }
    if(buffer.startsWith("Host:")){
        String[] splitText = buffer.split(" ");
        host = splitText[1];
    }

    if(buffer.isEmpty()){
        break;
    }
}

And I'm trying to return the body of the POST request using this code (obviously it's not working, only works for GET request):
URL u = new URL(url.toString());
HttpURLConnection connection = (HttpURLConnection) u.openConnection();

if(post){
    connection.setDoOutput(true);
    connection.setRequestMethod("POST");
}

byte[] buf = new byte[8196];
int bytesRead;
InputStream stream;
stream = connection.getInputStream();

while((bytesRead = stream.read(buf)) > 0){
    out.write(buf, 0, bytesRead);
    out.flush();
}

Any help would be much appreciated.
Thanks.
Edit, complete code:
public void run() {

        try {

            BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
            BufferedOutputStream out = new BufferedOutputStream(clientSocket.getOutputStream());

            String host = null;
            String url = null;
            int i=0;
            String [] headers = new String [100];
            String buffer;
            boolean post = false;

            while ((buffer = in.readLine()) != null) {
                System.out.println(buffer);
                headers[i]=buffer;
                i++;
                if(buffer.startsWith("GET"))
                {
                    String[] splitText = buffer.split(" ");
                    url = splitText[1];
                    post = false;
                    }
                if(buffer.startsWith("POST"))
                {
                    String[] splitText = buffer.split(" ");
                    url = splitText[1];
                    post = true;
                    }
                if(buffer.startsWith("PUT"))
                {
                    String[] splitText = buffer.split(" ");
                    url = splitText[1];
                    post = true;
                    }
                if(buffer.startsWith("Host:"))
                {
                    String[] splitText = buffer.split(" ");
                    host = splitText[1];
                    }

                if (buffer.isEmpty()) break;
                }

            if (!checkURL(host) && !checkWORD(url)){

                    URL u = new URL(url.toString());
                    HttpURLConnection connection = (HttpURLConnection) u.openConnection();
                    if (post){
                        connection.setDoOutput(true);
                        connection.setRequestMethod("POST");

                    }

                    for (int x=1;x<i-1;x++){
                    if (!headers[x].contains("Accept-Encoding:")){
                        connection.setRequestProperty(headers[x].substring(0, headers[x].indexOf(":")).toString() , headers[x].replace(headers[x].substring(0, headers[x].indexOf(":") +2), "").toString());
                    }
                    }

                    boolean redirect = false;

                    int status = ((HttpURLConnection) connection).getResponseCode();
                    if (status != HttpURLConnection.HTTP_OK) {
                        if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM || status == HttpURLConnection.HTTP_SEE_OTHER)
                        redirect = true;
                    }

                    if (redirect) {

                        String Url = connection.getHeaderField("Location");
                        URL urlloc = new URL(Url.toString());
                        connection = (HttpURLConnection) urlloc.openConnection();

                        if (checkWORD(Url)){

                            PrintWriter outt = new PrintWriter(clientSocket.getOutputStream());

                            outt.write("HTTP/1.0 200 OK\r\n");
                            outt.write("Date: Fri, 31 Dec 1999 23:59:59 GMT\r\n");
                            outt.write("Server: Apache/0.8.4\r\n");
                            outt.write("Content-Type: text/html\r\n");
                            outt.write("Content-Length: 57\r\n");
                            outt.write("Expires: Sat, 01 Jan 2000 00:59:59 GMT\r\n");
                            outt.write("Last-modified: Fri, 09 Aug 1996 14:21:40 GMT\r\n");
                            outt.write("\r\n");

                            outt.flush();
                            outt.close();

                        }

                        for (int x=1;x<i-1;x++){

                            if (!headers[x].contains("Accept-Encoding:")){
                                connection.setRequestProperty(headers[x].substring(0, headers[x].indexOf(":")).toString() , headers[x].replace(headers[x].substring(0, headers[x].indexOf(":") +2), "").toString());
                            }
                            }
                    }

                        byte[] buf = new byte[8196];
                        int bytesRead;
                        InputStream stream;
                        stream = connection.getInputStream();
                        while ((bytesRead = stream.read(buf)) > 0) {
                            out.write(buf, 0, bytesRead);
                            out.flush();
                        }

                        }else{

                            PrintWriter outt = new PrintWriter(clientSocket.getOutputStream());

                            outt.write("HTTP/1.0 200 OK\r\n");
                            outt.write("Date: Fri, 31 Dec 1999 23:59:59 GMT\r\n");
                            outt.write("Server: Apache/0.8.4\r\n");
                            outt.write("Content-Type: text/html\r\n");
                            outt.write("Content-Length: 57\r\n");
                            outt.write("Expires: Sat, 01 Jan 2000 00:59:59 GMT\r\n");
                            outt.write("Last-modified: Fri, 09 Aug 1996 14:21:40 GMT\r\n");
                            outt.write("\r\n");

                            outt.flush();
                            outt.close();
                            }

            out.close();
            in.close();
            clientSocket.close();

        } catch (Exception e) {
            e.printStackTrace();

        }
    }


text:
Q: How would I store my search results into a table using a foreach loop in powershell? Import-Module <JAMS>

$JAMSHistories = Get-JAMSHistory -Server TESTDUMMY2 -StartDate "01/20/2020" -EndDate "01/24/2020"

$historyTable = @()

foreach($JAMSHistory in $JAMSHistories)
{
    $row = New-Object -TypeName PSObject

    Write-Host $JAMSHistory.FinalSeverity
    if($JAMSHistory.FinalSeverity -match 'Success')
    {
        $row | Add-Member -NotePropertyName JobSeveritySuccess ($JAMSHistory.FinalSeverity)
    }
    else {
        if ($JAMSHistory.FinalSeverity -match 'Error') {
            $row | Add-Member -NotePropertyName JobSeverityError ($JAMSHistory.FinalSeverity) }
    } $historyTable += $row
}

$historyTable

A: You can do the following, which will output an array of objects ($historyTable) with a properties called JobSeveritySuccess and JobSeverityError.
$JAMSHistories = Get-JAMSHistory -Server TESTDUMMY2 -StartDate "01/20/2020" -EndDate "01/24/2020"

$historyTable = foreach ($JAMSHistory in $JAMSHistories) {

    $row = "" | Select JobSeveritySuccess,JobSeverityError
    if ($JAMSHistory.FinalSeverity -match 'Success') {
        $row.JobSeveritySuccess = $JAMSHistory.FinalSeverity
    }
    elseif ($JAMSHistory.FinalSeverity -match 'Error') {
        $row.JobSeverityError = $JAMSHistory.FinalSeverity
    }
    $row
}
# Output
$historyTable
# Output in Table Format
$historyTable | Format-Table

The problem with this approach is that every object will have JobSeveritySuccess and JobSeverityError properties, and they may be empty. The only time both properties will have data is if $JAMSHistory.FinalSeverity contains Error and Success for the same object. There is probably a better way to do your design if provided more requirements.

When doing this type of exercise, there are always some gotchas. Consider creating a new PSObject or PSCustomObject for loop iteration. Then output that object at the end of the loop code. When collecting the foreach loop output, just set a variable equal to the foreach loop. There's rarely a need to use += to build an array of foreach loop output. There could be some exceptions to this, but most of the time they are good things to consider.


text:
Q: Regular expression to match year? I'm new to regular expressions in excel vba, been looking at a few questions about it on stack overflow, found a great one at the following link "How to use Regular Expressions (Regex) in Microsoft Excel both in-cell and loops"
There was some very useful code here that I thought I might try to learn and adapt for my purposes, I'm trying to match a 4 digit string representing a year from a cell on a spreadsheet ie. "2016 was a good year" would yield "2016".
I used some slightly altered code from that question posted there and it manages to recognize that a string contains a year, however I'm not sure how to separate and extract the string from the rest of the cell contents, ie. getting 2016 on it's own in an adjacent cell, any changes I should make?
Private Sub splitUpRegexPattern()
Dim regEx As New RegExp
Dim strPattern As String
Dim strInput As String
Dim strReplace As String
Dim Myrange As Range

Set Myrange = ActiveSheet.Range("D2:D244")

For Each c In Myrange

    strPattern = "([0-9]{4})" 'looks for (4 consecutive numbers)

    If strPattern <> "" Then
        strInput = c.Value
        strReplace = "$1"

        With regEx
            .Global = True
            .MultiLine = True
            .IgnoreCase = False
            .Pattern = strPattern
        End With

        If regEx.Test(strInput) Then
            c.Offset(0, 5) = regEx.Replace(strInput, "$1") 'puts the string in an adjacent cell
        Else
            c.Offset(0, 5) = "(Not matched)"
        End If
    End If
Next
End Sub

A: You could significantly improve your code as below:

*

*Use variant arrays rather than a range

*Move the RegExp out of the loop (you are setting it the same way for each cell)

*Your RegExp parameters can be reduced for what you want (minor).
Private Sub splitUpRegexPattern()

    Dim regEx As Object
    Dim strPattern As String
    Dim strInput As String
    Dim X
    Dim Y
    Dim lngCnt As Long

    Set regEx = CreateObject("vbscript.regexp")
    X = ActiveSheet.Range("D2:D244").Value2
    Y = X

    strPattern = "\b[0-9]{4}\b" 'looks for (4 consecutive numbers)

    With regEx
        .MultiLine = True
        .Pattern = strPattern

        For lngCnt = 1 To UBound(X)

            If .Test(X(lngCnt, 1)) Then
                Y(lngCnt, 1) = .Execute(X(lngCnt, 1))(0)
            Else
                Y(lngCnt, 1) = "(Not matched)"
            End If
        Next

        Range("D2:D244").Offset(0, 5).Value2 = Y
    End With
End Sub

A: user1016274, thanks, your comment really helped, had to do some searching on it, but I found the answer
using regEx.Execute(strInput) I managed to return the string matched:
Private Sub splitUpRegexPattern()
    Dim regEx As New RegExp
    Dim strPattern As String
    Dim strInput As String
    Dim strReplace As String
    Dim Myrange As Range

    Set Myrange = ActiveSheet.Range("D2:D244")

    For Each c In Myrange

        strPattern = "([0-9]{4})" 'looks for (4 consecutive numbers)

        If strPattern <> "" Then
              strInput = c.Value
              strReplace = "$1"

            With regEx
                .Global = True
                .MultiLine = True
                .IgnoreCase = False
                .Pattern = strPattern
            End With

            If regEx.Test(strInput) Then
                c.Offset(0, 5) = regEx.Execute(strInput).Item(0).SubMatches.Item(0) 'this was the part I changed
            Else
                c.Offset(0, 5) = "(Not matched)"
            End If
        End If
    Next
 End Sub


text:
Q: React setter warning: Functions are not valid as a React Child This is my first React project, so thank you in advance for bearing with me if this is a basic question. I have a two range inputs and I am trying to perform a calculation and update content when those range inputs are moved. Here's my file:
index.tsx
import * as React from 'react'

export default function Index() {

  let hours = React.useState(2)
  const setHours = (newHours) => {
    hours = newHours;
    setPrice(hours, price);
  }

  let miles = React.useState(18)
  const setMiles = (newMiles) => {
    miles = newMiles;
    setPrice(hours, price);
  }

  let price = React.useState(0)
  const setPrice = (hours, miles) => {
    price = hours * 6.00 + miles * 0.32
  }
  setPrice(hours, miles);

  return (

Estimated fee of ${price} for a {hours} hour, {miles} mile trip.

       <input onChange={(e) => setHours(e.target.value)} value={hours} type="range" min="1" max="24" />
        <input onChange={(e) => setMiles(e.target.value)} value={miles} type="range" min="1" max="200" />

  );
}

This unfortunately throws a warning "Functions are not valid as a React child."

A: that's not how you should use the useState hook in case you want the value you should use the following:
const [hours, setHours] = useState()
then you can use hours as you used it in the example above now you're giving a useState() hook as the value of your input and that would definitely cause the error you have.
please follow this link to see more about useState hook

A:   const [hours, setHours] = React.useState(2)
  const [miles, setMiles] = React.useState(18)
  const [price, setPrice] = React.useState(0)

  const handleHours = (newHours) => {
    setHours(newHours)
    handlePrice()
  }

  const handleMiles = (newMiles) => {
    setMiles(newMiles)
    handlePrice()
  }

  const handlePrice = () => {
    let newPrice = hours * 6.00 + miles * 0.32;
    setPrice(newPrice)
  }


text:
Q: A proxy server that can add javascript I'm looking for a simple way to add a javascript to html via proxy server.
I actually found exactly what I wanted here:
https://github.com/axiak/filternet
But it just doesn't work. It uses a deprecated part of a library, and I have no idea how to fix it, as I know nothing about node.js
Does anyone know any other solution that can get the same goal?
Thanks
Yair

A: I've found on my own computer, that charles knows how to do that exact this. It's a great tool, you should use right now!!!
http://www.charlesproxy.com/


text:
Q: Identify if someone has paid in an excel spreadsheet and create text to say they have I'm a sports club treasurer, god knows why.
Each month I download the monthly statement from the bank and then have to check by hand to see that each member has paid their monthly due.
Is there a way I can create a formula for each user that would search Column B for the name 'John Smith' and if it's present, under Column C, create the text 'John Smith has paid' or something?
I've tried playing with the find and search functions but no joy so far.
Any help greatly appreciated!

A: I solved this using a combination of IF() and COUNTIF():

For the sake of this question the values in A, C, D and E are not important, however it does assume that your NAME is identical to that which you receive from the bank.
The formula is:
=IF(COUNTIF(B:B,"*"&J2&"*")>0,"PAID","NOT PAID")

A: EDIT: Fixed bug in formula

Here's a solution using the standard INDEX(…,MATCH()) technique:

Enter the following formula in I3 and ctrl-enter/copy-paste/fill-down the column:
=IF(IFERROR(INDEX(D:D,MATCH(H3&"*",B:B,0)),0)>0,"Paid","Not paid")

If this formula finds a transaction that matches the member, it checks to see if the Credit column contains a value to determine if the due has been paid.  This could easily be adapted to determine if the full amount has been paid or only a part payment has been received.
Explanation:
If the third argument of MATCH() is a 0 (exact match), then the find string can use wildcards. * means zero or more characters, so MATCH("JOHN SMITH SMITH*",…,0) means match the first string starting with the phrase JOHN SMITH SMITH.


text:
Q: How to do something when user touches canvas? Assistance to check bounds Hi I drew a bitmap on the canvas and I wanted to do something when the user touches it.
Bitmap backbutton = BitmapFactory.decodeResource(getResources(),
            R.drawable.backbutton);
    Paint paint = new Paint();

canvas.drawBitmap(backbutton, canvasWidth - 100, 0, paint);

I have tried the following to solve the problem but it isnt working. How do I check for inbounds properly?
public void onTouch(View view, MotionEvent event) {
    if(backbutton.contains((int) (event.getX()), (int)(event.getY()), (int)(event.getX()+100),(int) (event.getY()+30))) {
        Toast.makeText(view.getContext(), "this works", Toast.LENGTH_LONG).show();

    }

}

But I seem to be doing something wrong with the contains(). Can someone help me out here please?

A: First get the rect of the bitmap on the canvas. then in the onTouchEvent, check the touched x, y is contained in the rect before.
Added Example:
public class MyView extends View {
Rect bitmapRect;
public MyView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
}

public MyView(Context context, AttributeSet attrs) {
    super(context, attrs);
}

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);    //To change body of overridden methods use File | Settings | File Templates.

    Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.ic_launcher);

    Rect source = new Rect(0,0,bitmap.getWidth(), bitmap.getHeight());
    bitmapRect = new Rect(0,0, bitmap.getWidth(), bitmap.getHeight());

    canvas.drawBitmap(bitmap, source, bitmapRect, new Paint());

}

@Override
public boolean onTouchEvent(MotionEvent event) {
    int x = (int)event.getX();
    int y =   (int)event.getY();
    if(null != bitmapRect && bitmapRect.contains(x,y)){
        Toast.makeText(view.getContext(), "this works", Toast.LENGTH_LONG).show();
    }

    return super.onTouchEvent(event);    //To change body of overridden methods use File | Settings | File Templates.
}

}


text:
Q: Cannot fetch URL using an ajax call, but can via Postman Not sure why I can't I fetch the url "https://api.spotify.com/v1/artists/1rQX6kg84TqcwGtZHYIdn4/album" using $.get, but when I paste the exact same url into postman, it worked.
JSFiddle
$.get(
    "https://api.spotify.com/v1/artists/1rQX6kg84TqcwGtZHYIdn4/album",
    function (data, status) {
        alert("Data: " + data + "\nStatus: " + status);
    }
);

A: Do you have any spotity API tokens in your postman environment/globals/saved request? I'm guessing that the API requires an API token to be send (usually in the header), which is happening in Postman, but you aren't doing that in your ajax call.
Postman has a generate code feature that will generate code snippets for a particular request, and JQuery ajax is one of the supported targets. Why don't you try generating a snippet from Postman and see if there is a difference?


text:
Q: Incorrect Cookie Values, while reading it. I have a webforms app that uses cookies to store some temp data so that i can read it further on to do some other functions.
here is the code for setting/writing a cookie.
  Response.Cookies["Region"].Value = Convert.ToString(DropDownList1.SelectedItem);
                    Response.Cookies["Region"].Expires = DateTime.Now.AddDays(100);

                    HttpCookie dxs = new HttpCookie("Region");//cookie name
                    dxs.Values["Region"] = Convert.ToString(DropDownList1.SelectedItem);
                    dxs.Expires = DateTime.Now.AddDays(100);

                    Response.Cookies.Add(dxs);
                    Response.Cookies["Region"].Expires = DateTime.Now.AddDays(100);
                    Response.Redirect("~/HomePage.aspx");

here i how i read the cookie
if (Request.Cookies["Region"] != null)//read cookie
            {
                HttpCookie aCookie = Request.Cookies["Region"];
                ab = Server.HtmlEncode(aCookie.Value);
            }
            else
            {
                return;
            }

Now, here lies my problem, while reading, the cookie it gives values like Region=xyz or Region=abc; attached image.

What am i doing wrong?
Any and all help is appreciated..

A: dxs.Values - Gets a collection of key/value pairs that are contained within a single cookie.

You are giving the name of this cookies as Region.

And in side this cookie, you are storing a collection of one item - key=Region and value=Goa.
if you want to create a cookie with name as Region, and value as Goa, you can try like -
HttpCookie dxs = new HttpCookie("Region", Convert.ToString(DropDownList1.SelectedItem));

and add this cookie to your Resopnse cookies collection -
Response.Cookies.Add(dxs);


text:
Q: Does Keeping a Cookie "Whitelist" Slow Down Chrome? I use Chrome so that, by default, I block all cookies, but then "whitelist" sites I use often, either fully accepting its cookies or by selecting the "clear on exit" option.
As a result, I have created two impossibly long lists. Checking on Chrome's Settings > Privacy & security > Site settings > Cookies and site data, the items contained on the lists "Sites that can always use cookies" and "Always clear cookies when windows are closed" run in the hundreds.
My question is:Does this slow down Chrome more than allowing all cookies to be saved?
It seems obvious to me that, without blocking cookies as I currently do, and unless cookies are cleared often, there will be very rapidly a significantly large amount of cookies stored. Is, however, anything inherently slower in maintaining such large whitelists?

A: Slower, yes, but by how much? This is for you to say.
If you have not noticed any major slow-down, then it may only be on the order of
milliseconds, so not worth worrying about.

A: If you open developer tools and go to the Network tab it will show you all web requests including how many cookies in each request, the size of the request and the total time for the request. At the bottom of the Network tab it will also show the webpage total for kB transferred, MB in resources and time to load the page.
There is a specific filter "Has blocked cookies" which may be useful somehow as well.
I would think scenario B, with cookies being blocked and specific websites whitelisted would be more of a negative impact on webpage performance. While storing data is commonly used to track users for ads and such it is also used to remember data for better usability.
For example, you are on a website and logging in takes you to the login page. It would be nice for the login page to take you back to the page you were previously on.
The type/version of browser may be stored in a cookie to let the website know to use web features like lazy loading. Storing this information would make the webpage load faster since it would defer loading images until they were in your view vs loading everything at once.
Blocking cookies would seem to make web pages work harder and have worse performance than the milliseconds storing/accessing a cookie would take. The webpage is still going to try to use the API to work with cookies and whatever Javascript or backend framework to do this will load either way.


text:
Q: How should i find latitude and longitude of my location? I want to get latitude and longitude of my location and after, i convert there to Location. but i dont know How should i get latitude and longitude of my location?
Location.java:
public class Location extends MapActivity {

MapView map;
MapController controller;
GeoPoint mygeo;
GeoPoint searchgeo;

@Override
public void onCreate(Bundle onSavedInstance){
    super.onCreate(onSavedInstance);
    setContentView(R.layout.location);

    map=(MapView)findViewById(R.id.mapView);
    LinearLayout zoomLayout=(LinearLayout)findViewById(R.id.zoom);
    View zoomView=map.getZoomControls();
    zoomLayout.addView(zoomView,new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT,Gravity.BOTTOM+Gravity.CENTER_HORIZONTAL));

    map.displayZoomControls(true);
    //
    controller=map.getController();
    map.setSatellite(true);

    initMyLocation();

}
private void initMyLocation(){
    final MyLocationOverlay overlay=new MyLocationOverlay(this,map);
    overlay.enableMyLocation();
    overlay.enableCompass();
    overlay.runOnFirstFix(new Runnable(){
        public void run(){
            controller.setZoom(8);
            controller.animateTo(overlay.getMyLocation());
        }
    });
    map.getOverlays().add(overlay);

}

@Override
public boolean isRouteDisplayed(){
    return false;
}
 }

Thanks
Cheers

A: Check this out. It shows exactly how to obtain your current location, and getting its lat and long
GPS not update location after close and reopen app on android
please note you have to include the necessary permissions in the manifest for this to work
as seen here https://stackoverflow.com/a/3380641/975959

A: Use Location Listener to get your current location (Latitude and Longitude).
This to call Location Listener
    LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
    LocationListener mlocListener = new MyLocationListener();
    mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);

You can get your latitude and longitude in this class
    public class MyLocationListener implements LocationListener

    {

    @Override
    public void onLocationChanged(Location loc)
    {
     double longitude =  loc.getLongitude();
     double latitude = loc.getLatitude();
    }
    @Override
    public void onProviderDisabled(String provider)
    {
       Toast.makeText( getApplicationContext(),"Enable GPS",Toast.LENGTH_SHORT ).show();
       Intent enablegps = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
       startActivity(enablegps);
    }

    @Override
    public void onProviderEnabled(String provider)
    {
    Toast.makeText( getApplicationContext(), "Gps Enabled", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras)
    {} }

Hope it helps.

A: Especially In your case do this in  initMyLocation()
double latitude = (overlay.getMyLocation().getLatitudeE6())/ 1e6;

double longitude = (overlay.getMyLocation().getLongitudeE6())/ 1e6;

A: Please follow the step below :
Step 1 : Create main.xml like below with a button. when you press it should Toast you current Location.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<Button
 android:id="@+id/retrieve_location_button"
 android:text="Retrieve Location"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 />
</LinearLayout>

step 2 : Create an Activity like below :
package com.xxx.yyy.zzz;
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class LbsGeocodingActivity extends Activity {

        private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1; // in Meters
        private static final long MINIMUM_TIME_BETWEEN_UPDATES = 1000; // in Milliseconds

        protected LocationManager locationManager;

        protected Button retrieveLocationButton;

        @Override
        public void onCreate(Bundle savedInstanceState) {

            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);

            retrieveLocationButton = (Button) findViewById(R.id.retrieve_location_button);

            locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

            locationManager.requestLocationUpdates(
                    LocationManager.GPS_PROVIDER,
                    MINIMUM_TIME_BETWEEN_UPDATES,
                    MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
                    new MyLocationListener()
            );

        retrieveLocationButton.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    showCurrentLocation();
                }
        });

        }

        protected void showCurrentLocation() {

            Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

            if (location != null) {
                String message = String.format(
                        "Current Location \n Longitude: %1$s \n Latitude: %2$s",
                        location.getLongitude(), location.getLatitude()
                );
                Toast.makeText(LbsGeocodingActivity.this, message,
                        Toast.LENGTH_LONG).show();
            }

        }

        private class MyLocationListener implements LocationListener {

            public void onLocationChanged(Location location) {
                String message = String.format(
                        "New Location \n Longitude: %1$s \n Latitude: %2$s",
                        location.getLongitude(), location.getLatitude()
                );
                Toast.makeText(LbsGeocodingActivity.this, message, Toast.LENGTH_LONG).show();
            }

            public void onStatusChanged(String s, int i, Bundle b) {
                Toast.makeText(LbsGeocodingActivity.this, "Provider status changed",
                        Toast.LENGTH_LONG).show();
            }

            public void onProviderDisabled(String s) {
                Toast.makeText(LbsGeocodingActivity.this,
                        "Provider disabled by the user. GPS turned off",
                        Toast.LENGTH_LONG).show();
            }

            public void onProviderEnabled(String s) {
                Toast.makeText(LbsGeocodingActivity.this,
                        "Provider enabled by the user. GPS turned on",
                        Toast.LENGTH_LONG).show();
            }

        }

    }

Step 3 : Create AndroidManifest.xml with following three permissions :
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

When you run this app you will find a button on the screen of android device. When you press this button then you will see Toast message with latitude and longitude of your current gps location.


text:
Q: SQLite: Must a Cursor be closed when the DB is closed? I have an open database an read out some data. After my read operations are done I close the database but not the cursor.
Do I need to close the Cursor too?
I assume it will be done by the close of the db, but is that true?
What may happen if I don't close the Cursor?

SQLiteDatabase db = ...;
Cursor c = database.rawQuery("SELECT * FROM foo");
//read some values using the Cursor

c.close(); //<- is this required?
db.close();

A: The documentation says:

When finished iterating through results, call close() on the cursor to release its resources.

If you do not close the cursor, you might get an exception later.

A: If you close a database, the corresponding cursor will also be closed as far as I know.
An example of an exception that was thrown when I tried to traverse through a cursor (via cursor.moveToNext()) after having closed it's corresponding SQLite database is as follows:

java.lang.IllegalStateException: Cannot perform this operation because
  the connection pool has been closed.


text:
Q: Django CharField limitations how can I specify a blacklist for a CharField. However I want the blacklist to be effective in the Django admin panel aswell...otherwise I would just validate it in the view.
By blacklist I mean values that can't be used. I also set unique for the value but I would like to disable a few strings aswell.
Thanks,
Max

A: Since we're a few years later, you should write a custom blacklist validator:
from django.db import models
from django.core.exceptions import ValidationError

def validate_blacklist(value):
    if value in ['a', 'b', 'c']:
        raise ValidationError(
            "'a', 'b' and 'c' are prohibited!",
            params={'value': value},
        )

class MyModel(models.Model):
    even_field = models.CharField(max_length=200, validators=[validate_even])

See: Django Validators for full documentation.

A: I would override the model's save() method and the to be inserted value against a blacklist before calling the parent class' save() method.
Something like that (simplified):
class BlackListModel(models.Model):
   blacklist = ['a', 'b', 'c']

   # your model fields definitions...

   def save(self, *args, **kwargs):
        if self.blacklist_field in self.blacklist:
            raise Exception("Attempting to save a blacklisted value!")
        return super(BlackListModel, self).save(*args, **kwargs)

That way it works in all of your applications.

A: This is not possible out of the box. You would have to write a custom form field or otherwise add custom admin handling to do admin-level validation. To do it at the database level, I suspect you would need to set up some kind of trigger and stored procedure, but that's not my area so I'll leave that to others.


text:
Q: PHAssetCollection for "Camera Roll" and "My Photo Stream" is empty im trying to present a list of all the albums titles in my iphone and when i press a title i want it to present all the photos of that specific album in a collection view.I am using the "PhotosUI" framework and i use this code to get the album titles:
-(void)getLibrariesList
{
    NSArray *collectionsFetchResults;
    albumNames = [[NSMutableArray alloc] init];

    PHFetchResult *smartAlbums = [PHAssetCollection       fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum
                                                                                subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
    PHFetchResult *syncedAlbums = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum
                                                                           subtype:PHAssetCollectionSubtypeAlbumSyncedAlbum options:nil];
    PHFetchResult *userCollections = [PHCollectionList fetchTopLevelUserCollectionsWithOptions:nil];

    PHFetchOptions *userAlbumsOptions = [PHFetchOptions new];
    userAlbumsOptions.predicate = [NSPredicate predicateWithFormat:@"estimatedAssetCount > 0"];

    // Add each PHFetchResult to the array
    collectionsFetchResults = @[smartAlbums, userCollections, syncedAlbums];

    for (int i = 0; i < collectionsFetchResults.count; i ++) {

        PHFetchResult *fetchResult = collectionsFetchResults[i];

        for (int x = 0; x < fetchResult.count; x ++) {

            PHCollection *collection = fetchResult[x];

            albumNames[x] = collection.localizedTitle;

        }
    }
    //update the tableview
    [self.libraryTableView reloadData];
}

and this code to get all the photos for the specific album by it's title:
-(void)showPhotosInCollectionViewForALbumWithName:(NSString*)albumName
{
    libraryAssets = [NSMutableArray array];

    __block PHAssetCollection *collection;

    // Find the album
    PHFetchOptions *fetchOptions = [[PHFetchOptions alloc] init];
    fetchOptions.predicate = [NSPredicate predicateWithFormat:@"title = %@", albumName];
    collection = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum
                                                          subtype:PHAssetCollectionSubtypeAny
                                                          options:fetchOptions].firstObject;

    PHFetchResult *collectionResult = [PHAsset fetchAssetsInAssetCollection:collection options:nil];

    [collectionResult enumerateObjectsUsingBlock:^(PHAsset *asset, NSUInteger idx, BOOL *stop) {

        [libraryAssets addObject:asset];
    }];
    [self.libraryPhotosCollectoionView reloadData];
}

for certain albums it's working, albums like "Instagram" and albums i have created with my phone but when i press the "Camera Roll" and "My Photo Stream" album it dosent show anything.
any ideas why this is happening or if there another way to fetch all of my device's photos?

A: I got an answer. I retrieve all Camera Roll Photos&Videos. Below is my code.
   PHFetchOptions *fetchOptions = [[PHFetchOptions alloc] init];
collection = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum
                                                      subtype:PHAssetCollectionSubtypeSmartAlbumUserLibrary
                                                      options:fetchOptions].firstObject;

collectionResult = [PHAsset fetchAssetsInAssetCollection:collection options:nil];
NSLog(@"Custom album images::%@",collectionResult);

[collectionResult enumerateObjectsUsingBlock:^(PHAsset *asset, NSUInteger idx, BOOL *stop)
{
    NSLog(@"Custom album::%@",asset);
    NSLog(@"Collection Result Count:%lu", (unsigned long)self.collectionResult.count);

    //add assets to an array for later use in the uicollectionviewcell
}];


text:
Q: How To Enable/Disable a Table Row in jQuery Is there a pre made function in jQuery wherein when you click a button it will enable a row. Then if you click it again, it will disable the row. I found about toggle() and toggleClass(). But it does work when it calls a function. The thought is somewhat like this but I know the syntax is wrong.
jQuery
function disableRows(){
$("#test1table tbody tr").each(function() {
    $(this).find('input:text').prop('disabled', true);
});

function enableRows(){
$("#test1table tbody tr").each(function() {
    $(this).find('input:text').prop('disabled', false);
});

$(document).ready(function() {
  $('.yearButt').click(function(){
      $(this).toggleClass(enableRows(), disableRows());
  });
});

A: Use toggle not toggleClass, toggle will call functions alternatively on each click event
$(document).ready(function() {
  $('.yearButt').toggle(
      function() { enableRows(); },
      function() { disableRows(); }
    );
  });
});

You can also optimize your enable disable code by removing loops and using proper selectors for desired element
$("#test1table").find("input,button,textarea,select").attr("disabled", "disabled");
or this

A: I think below code help you to understand the requirements:
Ref: Enable Disable Controls in a table row

$(document).on('change', '.chkView', function() {
    $(this).closest('tr').find('.chkEdit, .chkDelete').prop('disabled', !this.checked);
})

        <input type="checkbox" class="chkView"/>View
        <input type="checkbox" class="chkEdit" disabled/>Edit
        <input type="checkbox" class="chkDelete" disabled/>Delete

        <input type="checkbox" class="chkView"/>View
        <input type="checkbox" class="chkEdit" disabled/>Edit
        <input type="checkbox" class="chkDelete" disabled/>Delete

A: You can simplify your code:
$(document).ready(function() {
    $('.yearButt').click(function(){
        var enabled = parseInt($(this).data('enabled'));
        $("#test1table tbody tr input:text").prop('disabled', enabled );

        $(this).data('enabled', !enabled)
    });
});

A: First, you're looking for .toggle(), not .toggleClass() :)
Then...
This isn't doing what you expect:
$(this).toggle(enableRows(), disableRows());

This is invoking the two functions immediately and then toggling based on the results of those functions.  (Which are both undefined.)  Instead of executing the functions, you just want to reference the functions so that .toggle() will execute them according to its logic:
$(this).toggle(enableRows, disableRows);

Note: If your code snippet is complete, then you also forgot the closing } after each of those functions.  Simple typo.


text:
Q: Can anyone suggest good Guidelines for asp .net UI design? I am a c# developer.
Recently I had to design a web UI  in asp .net 2.0 .I had strange problems with aligning controls in Visual studio UI.
I have used Div, table tags to align asp .net controls(labels, textbox, grid etc).
But the problem was what I saw in design surface of visual studio was entirely different (most of the time) when I view the page in browser.
The gap between controls  and  alignments was never perfect .I have seen other developers also doing trial and error methods without a proper guidelines.
C# coding I am pretty good and I have lots of Microsoft articles and help materials to guide me.
But I haven't found proper articles and guidelines for UI design of asp .net pages.(may be its out there and i havent found yet?)
Can anyone through more light on this subject. Any good books ,suggestions  etc?
Thanks in advance
SNC

A: If you want granular control over your HTML/XHTML output then I would recommend switching to ASP.NET MVC.  The problems you've described are those typically encountered when using ASP.NET WebForms.   As Anton mentions, you do need to gain a good understanding of XHTML and CSS as well.

A: While I definitly +1 everyone suggesting that you get a better grasp of CSS and positioning in general and ditch the drag and drop method of building your controls, I figure you need something sooner rather than later.
For that, I give you Yahoo!'s CSS Grids (JQuery, MooTools and other libraries also have grid layout tools) which will help you to get your UI done quickly. In the mean time read up on CSS.
(X)HTML is compositional - not unlike XAML (which is actually modeled on HTML/CSS). When building WinForms you can drag and drop your controls onto the window willy-nilly, but not so with the web. One thing the drag and drop designer misses is that (X)HTML components have a hierarchy to them. The designer tries to overcome this by using position: absolute; which is a precarious crutch.
Your controls need to be composed with their positional relationships more or less intact already and that means you'll have to edit the code by hand to put things in the proper order.

A: It's not the UI design per se. What you need is solid understanding of how CSS and generally styles work on the web (in short: they do poorly). So what you need is a good CSS book. Plus, you'll have to dump WYSIWYG ASP.NET page editor.

A: I'm curious if you feel your HTML skills are on par.  Could you create this same page in HTML without visual studio and get the results you expect (using notepad)?
Regardless, start spending more time in the HTML markup and less time using the designer surface in Visual Studio.  The more you understand the output that ASP.NET creates the better a web developer you will become.
A trick I use quite often is knowing that you don't need to recompile to change aspx code.  Make your changes to the aspx file, save, and then refresh your browser.  Also, use firefox and get the webdeveloper plugin.  I use the outline block level elements quite often to understand where some of my html flow problems are occurring.
Read up on Web Design.  I'm a bit behind but I've always loved zengarden and zeldman.. I'm sure there's better out there now.


text:
Q: E: Package 'apache2' has no installation candidate on Ubuntu 17.10 Got error E: Package 'apache2' has no installation candidate while installing apache2 with sudo apt-get install apache2 on Ubuntu 17.10.
Here is the message displayed on terminal.
sudo apt-get install apache2
Reading package lists... Done
Building dependency tree
Reading state information... Done
Package apache2 is not available, but is referred to by another package.
This may mean that the package is missing, has been obsoleted, or
is only available from another source

E: Package 'apache2' has no installation candidate

Message after apt-cache policy apache2 command.
apache2:
  Installed: (none)
  Candidate: (none)
  Version table:

Message after egrep -v '^#|^ *$' /etc/apt/sources.list /etc/apt/sources.list.d/*.list command
/etc/apt/sources.list.d/linuxgndu-ubuntu-sqlitebrowser-artful.list:deb http://ppa.launchpad.net/linuxgndu/sqlitebrowser/ubuntu artful main
/etc/apt/sources.list.d/mongodb-org-3.6.list:deb [arch=amd64,arm64] https://repo.mongodb.org/apt/ubuntu xenial/mongodb-org/3.6 multiverse
/etc/apt/sources.list.d/slack.list:deb https://packagecloud.io/slacktechnologies/slack/debian/ jessie main
/etc/apt/sources.list.d/sublime-text.list:deb https://download.sublimetext.com/ apt/stable/
/etc/apt/sources.list.d/vscode.list:deb [arch=amd64] http://packages.microsoft.com/repos/vscode stable main
/etc/apt/sources.list.d/webupd8team-ubuntu-java-artful.list:deb http://ppa.launchpad.net/webupd8team/java/ubuntu artful main

How can I solve this issue?

A: The main problem is missed /etc/apt/sources.list.
You can recreate it with:
cat <<EOF | sudo tee /etc/apt/sources.list
deb http://archive.ubuntu.com/ubuntu $(lsb_release -cs) main restricted universe multiverse
deb http://archive.ubuntu.com/ubuntu $(lsb_release -cs)-updates main restricted universe multiverse
deb http://archive.ubuntu.com/ubuntu $(lsb_release -cs)-security main restricted universe multiverse
deb http://archive.ubuntu.com/ubuntu $(lsb_release -cs)-backports main universe restricted multiverse
EOF

Then run
sudo apt-get update
sudo apt-get dist-upgrade
sudo apt-get install apache2

A: Try sudo apt-get update and then sudo apt-get install apache2.
I recommend installing the complete LAMP Stack using tasksel
sudo apt-get install tasksel

sudo tasksel to launch it
Select LAMP server and install it.
Hope that helps.

A: This might be the fastest

*

*Run sudo software-properties-gtk

*Under 'Ubuntu Software' tab select/tick the first 4 options- main, universe, restricted, multiverse

*Click 'Close'

*Click 'Reload'

Now, try your install command again.


text:
Q: D3 : How to only load half the data EDIT: I've added what rows looks like at the end of the post.
I've been trying to only load in the first half of the data onto a line graph but I've been having problems.
I thought taking in 'rows' (which is everything returned) and halving it would work but it returns nothing to the screen. What am I missing if you guys can see?
I have to parse the fullData to make an entirely new object instead of just referencing rows, which means once I'd cut the data in half it would actually delete the data so I couldn't load it back in later.
d3.csv(data, function(d) {
  return {
    month: parseDate(d.month),
    price: Number(d.price.trim().slice(1))
  };
}).then(function(rows) {
  max = d3.max(rows, function(d) {
    return d.price;
  });
  minDate = d3.min(rows, function(d) {
    return d.month;
  });
  maxDate = d3.max(rows, function(d) {
    return d.month;
  });
  let fullData = JSON.parse(JSON.stringify(rows));

  let halfData = fullData.splice(0, Math.floor(fullData.length / 2)); //this doesn't load properly

  var y = d3
    .scaleLinear()
    .domain([0, max])
    .range([height, 0]);

  var x = d3
    .scaleTime()
    .domain([minDate, maxDate])
    .range([0, width]);

  var yAxis = d3.axisLeft(y);
  var xAxis = d3.axisBottom(x);

  var line = d3
    .line()
    .x(function(d) {
      return x(d.month);
    })
    .y(function(d) {
      return y(d.price);
    })
    .curve(d3.curveCardinal);

  var svg = d3
    .select(".chart")
    .append("svg")
    .attr("id", "svg")
    .attr("height", "100%")
    .attr("width", "100%");

  var chartGroup = svg
    .append("g")
    .attr("class", "chartGroup")
    .attr("transform", "translate(" + xNudge + "," + yNudge + ")");

  chartGroup
    .append("path")
    .attr("class", "line")
    .attr("d", function(d) {
      return line(halfData);
    });

  chartGroup
    .append("g")
    .attr("class", "axis x")
    .attr("transform", "translate(0," + height + ")")
    .call(xAxis);

  chartGroup
    .append("g")
    .attr("class", "axis y")
    .call(yAxis);
});

What rows returns:
    (96) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, columns: Array(2)]
0
:
{month: Wed Jan 01 2003 00:00:00 GMT+0000 (Greenwich Mean Time), price: 54}
1
:
{month: Sat Feb 01 2003 00:00:00 GMT+0000 (Greenwich Mean Time), price: 54}
2
:
{month: Sat Mar 01 2003 00:00:00 GMT+0000 (Greenwich Mean Time), price: 50}
3
:
{month: Tue Apr 01 2003 00:00:00 GMT+0100 (Irish Standard Time), price: 52}
4
:
{month: Thu May 01 2003 00:00:00 GMT+0100 (Irish Standard Time), price: 53}
5
:
{month: Sun Jun 01 2003 00:00:00 GMT+0100 (Irish Standard Time), price: 49}
6
:
{month: Tue Jul 01 2003 00:00:00 GMT+0100 (Irish Standard Time), price: 51}
7
:
{month: Fri Aug 01 2003 00:00:00 GMT+0100 (Irish Standard Time), price: 52}
8
:
{month: Mon Sep 01 2003 00:00:00 GMT+0100 (Irish Standard Time), price: 54}
9
:
{month: Wed Oct 01 2003 00:00:00 GMT+0100 (Irish Standard Time), price: 52}
10
:
{month: Sat Nov 01 2003 00:00:00 GMT+0000 (Greenwich Mean Time), price: 50}

A: I figured it out yesterday, this is how I did it!
if (completed === false) {
        rows.splice(Math.floor(rows.length / 2), rows.length);
      }

I have a global variable called completed that is set to false. While false it splits the data in half and only shows the first half of the data.


text:
Q: ReactJS + Websocket + Context = Max update depth exceeded I'm having a ReactJS "Warning: Maximum update depth exceeded" error occuring in my WebsocketContext component and I'm not sure why and hoping someone might be able to shed some light.  I'll share as much code as I can.
(I'm still a ReactJS apprentice so I completely acknowledge my approach(es) could be very wrong!)
My small SPA will have a Websocket connection to AWS, which receives Codepipeline Events to populate a ReactJS UI to display the current state of pipelines (we have a lot of them, 600+)
Following several Stackoverflow and internet examples, I created a WebsocketContext to handle the connectivity and message receiving, and then wrapped my main component(s) in App.js within that context so they had access to the messages and connection.
My main issue right now seems to be with how the ws.current.onmessage is behaving as, after the initial load of pipelines, approx 650, give it about 10 mins and any trickle through updates that call setMessage() cause this:
Warning: Maximum update depth exceeded. This can happen when a component calls setState inside useEffect, but useEffect either doesn't have a dependency array, or one of the dependencies changes on every render. 3 react_devtools_backend.js:4026:25
    overrideMethod react_devtools_backend.js:4026
    React 5
    onmessage WebsocketContext.js:57
    (Async: EventHandlerNonNull)
    connect WebsocketContext.js:56
    WebsocketProvider WebsocketContext.js:79
    React 12
    workLoop scheduler.development.js:266
    flushWork scheduler.development.js:239
    performWorkUntilDeadline scheduler.development.js:533
    (Async: EventHandlerNonNull)
    js scheduler.development.js:571
    js scheduler.development.js:633
    factory react refresh:6
    Webpack 24

Below is a stripped down version of the WebsocketContext.js
export function WebsocketProvider({children}) {
    const [message, setMessage] = useState(null);
    const [isReady, setIsReady] = useState(false);

    const ws = useRef(null);

    const connect = () => {
        ws.current = new WebSocket(PIPELINE_WEBSOCKET_URL)
        ws.current.onerror = (event) => {  }
        ws.current.onopen = () => {
            console.log(`[${getTimestamp()}] Opened connection to '${PIPELINE_WEBSOCKET_URL}'`);
            setIsReady(true);
        }

        ws.current.onclose = () => {
            setTimeout(function () {
                console.log(`[${getTimestamp()}] Closed connection to '${PIPELINE_WEBSOCKET_URL}'`);
                setIsReady(false);
                connect();
            }, WEBSOCKET_RECONNECT_DELAY);
        }

        ws.current.onmessage = (event) => {
            setMessage(JSON.parse(event.data)); // <-- Problem thrown from here!
        }

        const wsCurrent = ws.current;

        return () => {
            console.log(`[${getTimestamp()}] Closing connection to '${PIPELINE_WEBSOCKET_URL}'...`);
            wsCurrent.close();

        };
    }

    useEffect(() => {
        connect()
    }, [])

    const ret = [isReady, message, ws.current?.send.bind(ws.current)];

    return (
        <WebsocketContext.Provider value={ret}>
            {children}
        </WebsocketContext.Provider>
    )
}

export default WebsocketContext;

Here is a component within my App.js that implements this context:
export default function ParentPipelineDashboard() {
    const [groupedPipelineObjects, setGroupedPipelineObjects] = useState({});
    const [message, send] = useContext(WebsocketContext);

    useEffect(() => {
        if (message) {
            updatePipelineTypeObjects(message)
        }
    }, [message]);

    const updatePipelineTypeObjects = (data) => {
        try {
            const pipelineName = data.pipelineName;
            const pipelineGroup = data.pipelineGroupName;
            setGroupedPipelineObjects(prevState => {

                const groups = {...prevState};
                if (groups[pipelineGroup]) {
                    groups[pipelineGroup] = {
                        ...groups[pipelineGroup], [pipelineName]: data,
                    };
                } else {
                    groups[pipelineGroup] = {
                        [pipelineName]: data,
                    };
                }
                return groups;
            })
        } catch (error) {
            console.log(error))
        }
    }
}

That ParentPipelineDashboard creates a larger complete 'Object' of all my pipeline data in such a way that makes it easy to extract what I need and when I need it, stored in groupedPipelineObjects.
The groupedPipelineObjects object then feeds many child-components within the ParentPipelineDashboard component in order to create rows of data specific to each pipeline, progress bars for the pipelines, info buttons, details, etc.
So, looking at the chain (i think?):

*

*WebsocketContext receives AWS events and sets each one received to
message in its useState()

*The ParentPipelineDashboard component
makes use of the message variable in the context to create its own
complete Object

*That complete Object is used to feed
child-components.

Eventually it complains about the depth and points to the onmessage function in the context component.  But i don't understand why -- surely React can handle it being used that often and that many times?
Is there a correct/more efficient way to approach this?
Thanks!
I have already moved the Websocket into a context instead of sitting in the original component for reuse.  I tried to create a separate function that the onmessage would call instead of directly calling the setMessage().
I expect that it shouldn't complain about the max depth being exceeded


text:
Q: Перемещение персонажа JavaScript Пишу онлайн игру. Сейчас используется перемещение персонажа на клетку по которой пользователь кликнул. Хочу сделать перемещение клавиатурой.
Как я это вижу:
Пользователь зажимает кнопку ходьбы - на сервер идёт запрос о том что пользователь начал движение, всем клиентам отправляется информация о том что игрок начал движение и на стороне клиента он двигается в определённую сторону, когда кнопку отпускает на сервер идёт информация что пользователь остановился.
И вот здесь у меня проблема. Если у какого-нибудь клиента будет плохое интернет соединение, значит он может вовремя не получить информацию от сервера о том, что пользователь остановился и будет продолжать обрабатывать его перемещение до тех пор пока интернет не восстановится. Получается будет иметь неверную информацию о местоположении пользователя который сделал перемещение.
Что-нибудь сможете посоветовать?


text:
Q: Using previous JDK version which is not available via SDKMAN but from adoptopenjdk I have the following situation:
$ sdk java list
 AdoptOpenJDK  |     | 15.0.1.j9    | adpt    |            | 15.0.1.j9-adpt
               |     | 15.0.1.hs    | adpt    | installed  | 15.0.1.hs-adpt
               |     | 14.0.2.j9    | adpt    |            | 14.0.2.j9-adpt
               |     | 14.0.2.hs    | adpt    |            | 14.0.2.hs-adpt
               |     | 13.0.2.j9    | adpt    |            | 13.0.2.j9-adpt
               |     | 13.0.2.hs    | adpt    |            | 13.0.2.hs-adpt
               |     | 12.0.2.j9    | adpt    |            | 12.0.2.j9-adpt
               |     | 12.0.2.hs    | adpt    |            | 12.0.2.hs-adpt
               |     | 11.0.9.j9    | adpt    |            | 11.0.9.j9-adpt
               | >>> | 11.0.9.hs    | adpt    | installed  | 11.0.9.hs-adpt
...

But on adoptopenjdk the following version https://github.com/AdoptOpenJDK/openjdk11-binaries/releases/tag/jdk-11.0.8%2B10 is available and can be downloaded.
But when I try to install it via sdkman:
$ sdk java install
tools$ sdk install java 11.0.8.hs-adpt

Stop! java 11.0.8.hs-adpt is not available. Possible causes:
 * 11.0.8.hs-adpt is an invalid version
 * java binaries are incompatible with Darwin
 * java has not been released yet

Is there a way to handle that via sdkman or not?

A: sdkman doesn't recognize as candidates every existing version of the jdk.
However it allows to add local version as compensation.
Thus you'll just have to download the specific version you need, store it in any path you want, and then use a command to register the local version as installed in sdkman:
https://sdkman.io/usage#localversion


text:
Q: GKE nodes binding to a gateway I'm trying to route nodes managed by GKE to a gateway so each one of the nodes will eventually have the same IP. The reason is to allow, that static gateway IP only, to access my clients firewall.
I didn't find a solution on Google Kubernetes Engine, can anyone think of a way of doing that, with my GKE nodes?

A: You could use Cloud NAT in GCP to allow GKE outbound connections through a single external IP address, therefore you can whitelist that public IP address in your Firewall device. You can check the next link for how to configure Cloud NAT in GKE