text:
Q: Как правильно использовать if-else для радиокнопки? Есть фрейм, в котором создаю радиокнопки:
rbg = new ButtonGroup();

addDirectRadioButton("Подразделения", "SELECT * FROM DEPT");
addDirectRadioButton("Сотрудники", "SELECT * FROM EMP");
addDirectRadioButton("Разрядная сетка", "SELECT * FROM SALGRADE");

addButton = new JButton("Ввод");
addButton.setToolTipText("Ввести новые данные в таблицу");
addButton.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {}
});

public final void addDirectRadioButton(String name, final String query) {
    boolean selected = query.equals(DEFAULT_QUERY);
    JRadioButton button = new JRadioButton(name, selected);
    rbg.add(button);
    directPanel.add(button);

    ActionListener listener = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent event) {
            dbtm.executeUpdate(query);
        }
    };
    button.addActionListener(listener);
}

И есть кнопка, в которую нужно поместить if-else. В зависимости от того, какая кнопка выбрана, должен открываться один из трех фреймов, к примеру: AddDeptFrame, AddEmpFrame и AddSalgradeFrame. Как правильно построить if-else для моей кнопки?

A: if-else в обработчике нажатия на кнопку - не очень хороший подход, т.к. если появятся новые варианты, код придется менять как на участке создания радиокнопок, так и в обработчике, и можно допустить ошибку. Удобнее сделать универсальный обработчик, и поместить разные варианты действий в коллекцию.
Код пользуется тем, что ButtonGroup может возвращать модель выбранной радиокнопки.
import java.awt.BorderLayout;
import java.util.HashMap;
import java.util.function.Supplier;

import javax.swing.ButtonGroup;
import javax.swing.ButtonModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;

public class RadioFrames extends JFrame {

    // таблица соответствия моделей кнопок фабрикам, создающим нужные фреймы
    HashMap<ButtonModel, Supplier<JFrame>> radioToFrames = new HashMap<>();
    ButtonGroup rbg = new ButtonGroup();
    JPanel directPanel = new JPanel();

    public RadioFrames() {
        JPanel content = new JPanel( new BorderLayout() );

        content.add( directPanel, BorderLayout.CENTER );

        // используются method reference из java 8
        addDirectRadioButton("Подразделения", AddDeptFrame::new, true );
        addDirectRadioButton("Сотрудники", AddEmpFrame::new, false );
        addDirectRadioButton("Разрядная сетка", AddSalgradeFrame::new, false );

        JButton addButton = new JButton( "Ввод" );

        addButton.addActionListener( event -> {
            // rbg.getSelection() возвращает нам модель выбранной кнопки
            //   или null, если ничего не выбрано.
            // radioToFrames.get( null ) - допустимый вызов, и просто вернет
            //   null, т.к. в таблице нет такого ключа
            Supplier<JFrame> frameSupplier = radioToFrames.get( rbg.getSelection() );
            // если в таблице есть фабрика для такой модели,
            //   создаем и показываем новый фрейм
            if ( frameSupplier != null ) {
                frameSupplier.get().setVisible( true );
            }
        });

        content.add( addButton, BorderLayout.SOUTH );

        setContentPane( content );
    }

    public void addDirectRadioButton( String name, Supplier<JFrame> frameSupplier, boolean selected ) {
        JRadioButton button = new JRadioButton( name, selected );
        rbg.add(button);
        directPanel.add(button);

        // добавляем в карту пару (модель -> фабрика)
        radioToFrames.put( button.getModel(), frameSupplier );
    }

    public static void makeUI() {
        RadioFrames mainFrame = new RadioFrames();
        mainFrame.setDefaultCloseOperation( WindowConstants.EXIT_ON_CLOSE );
        mainFrame.pack();
        mainFrame.setVisible( true );
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater( RadioFrames::makeUI );
    }
}

class SizedFrame extends JFrame { public SizedFrame( String title ) { super( title ); setSize( 320, 200); } };
class AddDeptFrame extends SizedFrame { public AddDeptFrame() {super("DeptFrame"); } };
class AddEmpFrame extends SizedFrame { public AddEmpFrame() {super("EmpFrame"); } };
class AddSalgradeFrame extends SizedFrame { public AddSalgradeFrame() {super("SalgradeFrame"); } };

Если все-таки надо сделать условный оператор (очень разная обработка условий, которую нельзя/не хочется закинуть в несколько классов-обработчиков), можно воспользоваться свойством ButtonModel actionCommand.
При создании кнопки установить свойство button.setActionCommand("command-text"), а при обработке нажатия делать String command = rbg.getSelection().getActionCommand() и дальше в зависимости от результата что-то делать.


text:
Q: Someone joined SE in order to stalk me, but hasn't broken any site rules Naming no names...
I recently discovered that another user on one of the Stack Exchanges I frequent is a person I used to know in real life, who is still trying to chase after me despite my making it very clear that I don't want their company. This person has joined SE only in order to stalk me. So far they've posted one answer (to a question I'd also answered) and one question (which I believe was set in order to entrap me - the topic is a joke the two of us used to share IRL back when I used to spend time with this person), and participated in chat speaking almost exclusively to me.
When I joined SE, I tried hard to ensure my anonymity, mainly because I feared this person might try to stalk me. I no longer feel quite comfortable using SE, knowing that this user is following me around and watching what I do. But as far as I know, they haven't broken any SE rules.
Is there anything that can be done by SE administration? Are people allowed to join SE purely to stalk other people? Or do I just have to deal with it?

A: Almost everything that happens on Stack Exchange -- main sites, meta sites, most chat rooms -- is public.  That means anybody can see it and interact with it.  If you're not comfortable with that, then no, there's really nothing that SE can do to protect you from another user who isn't misbehaving.  You both have the same rights to use the site.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Create Soap Service under .net core 3.1 with existing WSDL file I got very interesting issue to create soap service with existing wsdl.
Reason for that is we tried to create a testing service and all we got is a wsdl file.
What I did is

*

*use the dotnet-svcutil server.wsdl to generate cs file

*create new .net core service project

*create new class to implement the interface in above cs file

*services.AddSingleton<RWSv7Services, ServerRWSv7Services>();

*app.UseSoapEndpoint("/Services", new BasicHttpBinding(), SoapSerializer.XmlSerializer); /here I'm using SoapCore package/

During testing the soap service method can be called, but I notice the Authentication in response message is not populated meanwhile the data in body message looks fine.
checked the real wsdl and my wsdl, they are different.
Correct one
<wsdl:operation name="listDocumentsInternal">
<soap:operation style="document" soapAction="/RetailWebServicesV7/InterfaceServices/RetailWebServicesV7Service.serviceagent/listDocumentsInternal"/>
<wsdl:input>
<soap:body use="literal" parts="listDocumentsReq"/>
<soap:header use="literal" message="tns:soapHeader" part="operationSystem"/>
<soap:header use="literal" message="tns:soapHeader" part="vendorDetails"/>
<soap:header use="literal" message="tns:soapHeader" part="authentication"/>
</wsdl:input>
<wsdl:output>
<soap:body use="literal" parts="listDocumentsRespInternal"/>
<soap:header use="literal" message="tns:soapHeader" part="authentication"/>
</wsdl:output>
<wsdl:fault name="fault1">
<soap:fault use="literal" name="fault1"/>
</wsdl:fault>
</wsdl:operation>

mine
<wsdl:operation name="listDocumentsInternal">
<soap:operation soapAction="/RetailWebServicesV7/InterfaceServices/RetailWebServicesV7Service.serviceagent/listDocumentsInternal" style="document"/>
<wsdl:input>
<soap:body use="literal"/>
</wsdl:input>
<wsdl:output>
<soap:body use="literal"/>
</wsdl:output>
</wsdl:operation>

Is anything missing?? In my mind they should be exactly same.
Thank you very much in advance.

A: endpoints.UseSoapEndpoint<RWSv7Services, CustomNamespaceMessage>("/Services", new BasicHttpBinding(), SoapSerializer.XmlSerializer);

public class CustomNamespaceMessage : CustomMessage
    {
        public CustomNamespaceMessage() { }
        public CustomNamespaceMessage(Message message) : base(message) { }

        public override MessageHeaders Headers
        {
            get
            {
                var index = base.Headers.FindHeader("Authentication", "my correct namespace");
                if (index >= 0)
                {
                    var xml = new XmlDocument();
                    xml.LoadXml(base.Headers[index].ToString());
                    var obj = new Authentication { };
                    var authNode = xml.ChildNodes.Cast<XmlNode>().FirstOrDefault(x => x.Name.Equals("Authentication", System.StringComparison.OrdinalIgnoreCase));
                    foreach(XmlNode node in authNode.ChildNodes)
                    {
                        if (node.Name.Equals("B2BAccount", System.StringComparison.OrdinalIgnoreCase))
                            obj.B2BAccount = node.InnerText;
                        if (node.Name.Equals("Password", System.StringComparison.OrdinalIgnoreCase))
                            obj.Password = node.InnerText;
                        if (node.Name.Equals("SecurityToken", System.StringComparison.OrdinalIgnoreCase))
                            obj.SecurityToken = node.InnerText;
                    }
                    var header = new CustomHeader(obj);
                    base.Headers.RemoveAt(index);
                    base.Headers.Add(header);

                }
                return base.Headers;
            }
        }
    }

public class CustomHeader : MessageHeader
    {
        private const string CUSTOM_HEADER_NAME = "Authentication";
        private const string CUSTOM_HEADER_NAMESPACE = "my correct namespace";

        private Authentication _customData;

        public Authentication CustomData
        {
            get
            {
                return _customData;
            }
        }

        public CustomHeader()
        {
        }

        public CustomHeader(Authentication customData)
        {
            _customData = customData;
        }

        public override string Name
        {
            get { return (CUSTOM_HEADER_NAME); }
        }

        public override string Namespace
        {
            get { return (CUSTOM_HEADER_NAMESPACE); }
        }

        protected override void OnWriteHeaderContents(
            System.Xml.XmlDictionaryWriter writer, MessageVersion messageVersion)
        {
            writer.WriteElementString("B2BAccount", CUSTOM_HEADER_NAMESPACE, _customData.B2BAccount);
            writer.WriteElementString("Password", CUSTOM_HEADER_NAMESPACE, _customData.Password);
            writer.WriteElementString("SecurityToken", CUSTOM_HEADER_NAMESPACE, _customData.SecurityToken);
        }
}


text:
Q: Updating a DIV with HTML using jQuery on click Annoying issue I've got here with a site, which I need to fix!
Basically, I've got a series of ingredients which can be dragged onto a mixing bowl, they then appear on the blackboard, the ingredient fades out and the URL is updated.
That all works great!
The problem i've got, is that we offer another way of the user to add ingredients to their mixing bowl, by simply clicking an "add to bowl" button.
You can see it in action here.
This method will update the "ingredients" array ok, but it won't update the blackboard, update the URL or fade away the jar on the shelf.
To see this working, just click a jar on the shelf and you'll see what I mean!
So, in the code, the snippet in question is this:
$(".ingredients_add").click(function () {

     // hide the ingredient box
     //$("#ingredients_box").toggleClass("hidden");
     $("#ingredients_box").toggleClass("visible");

     if( ingredients.length <= 4 ){

        // get the topping name
         var htmlString = $("#ingredients_box > .ingredients_name_label").text();
         $('.choc2_flavour').text(htmlString);

         //Add item to the array
         ingredients.push( htmlString );

         // test alert to check array is populating
         //alert(ingredients);

         // fade out jar --------- we need this to fade out the ingredient jar that has been added. Out of scope??
         ui.draggable.fadeOut(500);

         //Output the ingredients array -------- this isn't firing and updating the blackboard
         drawIngredients();

     } else {
         //Maybe show an alert here? The ingredient will revert automagically...

        alert("You've already added the maximum number of ingredients!");

        //ui.draggable({ revert: 'invalid' });
     }
 });

It doesn't seem to want to fire the drawIngredients function. Which looks like this:
//Function to redraw the ingredients list
function drawIngredients(){
    //alert("I'm going to draw me a list!");//#DEBUG

    //alert(ingredients);//#DEBUG

    //Clear down the ingredients div and querystring
    $('#ingredient_list').html('');
    ingString = "";

    //Get the URL
    var _href = $("a.to_step_4").attr("href");

    //Split the URL
    var _hrefs = _href.split("&");

    //alert(_href);//#DEBUG
    //alert(_hrefs);//#DEBUG

    //Add each ingredient into the div
    ingredients.forEach( drawIngredient );

    //Set the flavour part of the querystring;
    _hrefs[2] = "flavour="+ingString;

    //alert(_hrefs[2]);//#DEBUG

    var _href = _hrefs[0]+"&"+_hrefs[1]+"&"+_hrefs[2];

    $("a.to_step_4").attr("href", _href);
 }

 function drawIngredient( elem, index ){
    $('#ingredient_list').append('
'+elem+'
');
    ingString += elem+"|";
 }

Neither does it fade away the jar (maybe due to it being out of scope?).
Can anyone help?
Simon

A: The variable ui is a parameter in the drop handler, so it is out of scope at the point where you are calling it.  That is preventing the drawIngredients() function from being called.
If you need to fade out the jar, you're going to need to use some other mechanism of getting the current selected jar - storing it for later use by the dialog.
Perhaps the best way is to store a data-ingredient attribute on the jar, e.g.:

...

And then later use:
 $('li[data-ingredient="' + ingredient + '"]').fadeOut(500);
 drawIngredients();

That way, you can look at the data-ingredient on the parent
 when you invoke the dialog and save it for later use by the ingredient add routine.


text:
Q: How to concatenate vectors to create a array in loop? I have a loop for that generate a new vector (100,) in each iteration.  So the code loop likes
for i in range (10):
   for j in range (4):
     #Create a new vector (100,)
     #Concatenate 4 vector together to make (400,) #400=4*10
#Append the concatenation vectors (400,) in vertical to make (10,400) array

My expected is that generates a matrix size of (10,400) that concatenate vectors in these loops
Currently, my solution is
   matrix_= np.empty([10,400])
    for i in range (10):
       vector_horz=[]
       for j in range (4):
         #Create a new vector (100,)
         vector_rnd=#Random make a vector/list with size of (100,1)
         #Concatenate 4 vector together to make (400,) #400=4*10
         vector_horz.append(vector_rnd)
    #Append the concatenation vectors (400,) in vertical to make (10,400) array
       matrix_(:,i)=vector_horz

However, it said that my size of matrix and vector_horz cannot assign. Could you give me another solution?

A: Option 1
(Recommended) First generate your data and create an array at the end:
data = []
for i in range(10):
    for j in range(4):
        temp_list = ... # random vector of 100 elements
        data.extend(temp_list)

arr = np.reshape(data, (10, 400))

Option 2
Alternatively, initialise an empty array with np.empty and assign one slice at a time:
arr = np.empty((10, 400))
for i in range(10):
    for j in range(4):
        temp_list = ...
        arr[i, j * 100 : (j + 1) * 100] = temp_list


text:
Q: pocketsphinx ERROR: Could not build wheels for pocketsphinx, which is required to install pyproject.toml-based projects I am having trouble downloading this python module called pocketsphinx,
I've tried everything by downloading it manually, using git and more (I am on windows), I updated pip, and I even tried downloading visual studio with the python environment as the error insisted, i updated my python, I even tried updating my laptop, but I still can't get it to work. but I'm not giving up, although I am very frustrated.
`
FULL ERROR:
-- Trying "NMake Makefiles (Visual Studio 15 2017 x64 v141)" generator - failure
--------------------------------------------------------------------------------
  ********************************************************************************
  scikit-build could not get a working generator for your system. Aborting build.

  Building windows wheels for Python 3.11 requires Microsoft Visual Studio 2022.
  Get it with "Visual Studio 2017":

    https://visualstudio.microsoft.com/vs/

  Or with "Visual Studio 2019":

      https://visualstudio.microsoft.com/vs/

  Or with "Visual Studio 2022":

      https://visualstudio.microsoft.com/vs/

  ********************************************************************************
  [end of output]

note: This error originates from a subprocess, and is likely not a problem with pip.
ERROR: Failed building wheel for pocketsphinx
Failed to build pocketsphinx
ERROR: Could not build wheels for pocketsphinx, which is required to install pyproject.toml-based projects
`
Updating my python, updating PIP, Updating my laptop, Installing it manually, and using GIT, ive even tried some solutions on youtube (none of them worked)

A: Ok, i just found the problem. turns out python 3.11 is completely unsupported. meaning you will have to downgrade to 3.10 to use this module


text:
Q: Cannot resolve symbol callbackManager facebook sdk 4.0's lib I am working on register my app with facebook login API. Now i get error on callbackManager function. It says cannot resolve symbol callbackManager. Can someone please help me in this regards.
This is my xml.
 <?xml version="1.0" encoding="utf-8"?>
 <android.support.constraint.ConstraintLayout
 xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:app="http://schemas.android.com/apk/res-auto"
 xmlns:tools="http://schemas.android.com/tools"
 android:id="@+id/activity_main"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:background="#5b9bd5"
 tools:context="com.example.ratingapp.ratingapp.MainActivity">

    <ImageButton
    android:id="@+id/regiterbutton"
    android:layout_width="191dp"
    android:layout_height="56dp"
    android:background="@drawable/registerbutton"

    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    app:layout_constraintTop_toTopOf="@+id/activity_main"
    app:layout_constraintRight_toRightOf="@+id/loginbutton"
    app:layout_constraintBottom_toBottomOf="@+id/activity_main"
    app:layout_constraintVertical_bias="0.83" />

    <ImageButton
    android:id="@+id/loginbutton"
    android:layout_width="191dp"
    android:layout_height="0dp"
    android:background="@drawable/loginbutton"
    android:layout_above="@+id/regiterbutton"
    app:layout_constraintLeft_toLeftOf="@+id/activity_main"
    tools:layout_constraintLeft_creator="1"
    app:layout_constraintRight_toRightOf="@+id/activity_main"
    tools:layout_constraintRight_creator="1"
    app:layout_constraintBottom_toTopOf="@+id/regiterbutton"
    android:layout_marginBottom="32dp" />
   </android.support.constraint.ConstraintLayout>

This is my MainActivity.java
package com.example.ratingapp.ratingapp;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.Toast;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.accountkit.LoginResult;
import com.facebook.login.LoginManager;

import java.util.Arrays;

public class MainActivity extends AppCompatActivity {

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    FacebookSdk.sdkInitialize(this.getApplicationContext());
    setContentView(R.layout.activity_main);
    callbackManager = CallbackManager.Factory.create();

    LoginManager.getInstance().registerCallback(callbackManager,
            new FacebookCallback<LoginResult>() {
                @Override
                public void onSuccess(LoginResult loginResult) {
                    Log.d("Success", "Login");

                }

                @Override
                public void onCancel() {
                Toast.makeText(MainActivity.this, "Login Cancel",
   Toast.LENGTH_LONG).show();
                }

                @Override
                public void onError(FacebookException exception) {
                    Toast.makeText(MainActivity.this,
    exception.getMessage(), Toast.LENGTH_LONG).show();
                }
            });

    setContentView(R.layout.activity_main);

    ImageButton registrationbutton = (ImageButton)
    findViewById(R.id.regiterbutton);

    registrationbutton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            LoginManager.getInstance().logInWithReadPermissions(this,
     Arrays.asList("public_profile", "user_friends"));
        }
    });

   }

 @Override
 protected void onActivityResult(int requestCode, int resultCode, Intent
 data) {
    super.onActivityResult(requestCode, resultCode, data);

    callbackManager.onActivityResult(requestCode, resultCode, data);
    }
 }

A: you are not defining the callBackManager just define it globally like this
public class MainActivity extends AppCompatActivity {
private CallbackManager fbCallback; //define CallbackManager
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(this.getApplicationContext());
setContentView(R.layout.activity_main);
callbackManager = CallbackManager.Factory.create();


text:
Q: Expression: String Subscript Out of Range I am getting an error saying that my string subscript is out of range (the error message is the title) whenever I run my code. I expect it to be from using "counter" to calculate total cities and average population. How do I go about fixing this? I have tried other methods to calculate it but none have worked.
void cities( istream& in, ostream& out )
{
    ifstream ("cities.txt");
    string country, city, city2, state, lat, longi;
    int pop;
    int currentPop = 0;
    int smallestPop = 0;
    int largestPop = 0;
    int counter = 0;
    int sum = 0;
    int i = 0;
    int average = 0;
    string largestCity;
    string smallestCity;
    string population;

    readLineOfData(in, country, city, city2, state, pop, lat, longi);
    while(!in.fail())
    {
        counter++;
        output( out, country, city, city2, state, pop, lat, longi );

        readLineOfData(in, country, city, city2, state, pop, lat, longi);

        population[counter] = pop;

        if (pop < smallestPop || smallestPop == 0)
        {
            smallestPop = pop;
            smallestCity = city2;
        }

        if (pop > largestPop || largestPop == 0)
        {
            largestPop = pop;
            largestCity = city2;
        }

        for (int i = 0; i<counter; i++)
        {
            sum += population[i];
            average = sum/counter;
        }
    }

        out << "Smallest City: " << smallestCity << endl;
        out << "Population: " << smallestPop << endl;
        out << endl;
        out << "Largest City: " << largestCity << endl;
        out << "Largest Population: " << largestPop << endl;
        out << endl;
        out << "Total Cities: " << i << endl;
        out << "Average Population: " << average << endl;
    return;
}

void readLineOfData( istream& in, string &country,  string &city, string &city2,
    string &state, int &pop, string &lat, string &longi)
{
    getline( in, country, ',');
    getline( in, city, ',');
    getline( in, city2, ',');
    getline( in, state, ',');
    in >> pop;
    in.ignore( 200, ',' );
    getline( in, lat, ',');
    getline( in, longi, '\n' );

}

void output( ostream& out, string country, string city, string city2,
    string state, int pop, string lat, string longi )
{
}

A: The declaration
string population;

means that population is a sequence of character codes, but you're treating it as a sequence of numbers:
population[counter] = pop;

also at this point its size is 0, so indexing will just err out or give undefined behavior.
instead, declare population as a std::vector, and use
population.push_back( pop );


text:
Q: schedule api request and save to dataframe I try to scrape data from an api. I want to schedule this task so it requests the api every half an hour and saves appends the result to a dataframe. However the api response is a nested dictionary so i have to do some parsing. I read that I should lists instead of dataframes to append the data in the function. My Code so far looks like this:
import pandas as pd
import requests
from pandas.io.json import json_normalize
import schedule
import time

resp = requests.get(url).json()
df=[]
def fetch_here():
        global df
        r2=json_normalize(resp,record_path=["RWS","RW"])
        r=json_normalize(resp["RWS"],record_path=["RW","FIS","FI"])
        r1=json_normalize(resp["RWS"],record_path=["RW","FIS","FI","CF"])
        workFrame = pd.concat([r, r1], axis=1, sort=False)
        workFrame = workFrame.drop(['SHP',"CF","SSS.SS"], 1)
        time=r2["PBT"]
        workFrame["Time"]=time
        workFrame=workFrame.fillna(method="ffill")
        df=df.append(workFrame)

#Time
schedule.every(30).minutes.do(fetch_here)

while True:
    schedule.run_pending()
    time.sleep(1)

However I get the error: UnboundLocalError: local variable 'df' referenced before assignment.
I guess it would be better to store the parsing result as a list and then append?
But I don't know how to normalize the json to a list.
Hope someone can help. Thanks.


text:
Q: why no the collisions on the main function overloading?
Possible Duplicate:
Can we overload the main method in Java?

When I tryed to compile and run following code, it's working and I see "A" on the console.
Why?
In my mind (String... args) it is the same (String arg, String[] args).
public class AFewMainExample {
    public static void main(String... args) {
        System.out.print("A");
    }

    public static void main(String args) {
        System.out.print("B");
    }

    public static void main(String[] args, String arg) {
        System.out.print("C");
    }

    public static void main(String arg, String[] args) {
        System.out.print("D");
    }
}

A: This is actually specified in the JLS, §12.1.4:

The method main must be declared public, static, and void. It must specify a formal parameter (§8.4.1) whose declared type is array of String. Therefore, either of the following declarations is acceptable:

*

*public static void main(String[] args)

*public static void main(String... args)

There is no difference between the varargs type and the standard array type other than the way in which the function is called, as is noted here. Consequently, the varargs version satisfies all the criteria detailed above and passes as a valid main method. Evidently, all of your other main overloads are not equivalent (otherwise there would be a compile-error).

A: the first signature is the only one that matches void main (String[] args)
difference fn(String... args) vs fn(String[] args)

A: Parameters (order (or) type (or) both) are different for each of the main method, which leaves only one main method with real main syntax, so no issues.
If you add following main method you will see compile time error, because now there are two methods with exact syntax.
public static void main(String[] args) {
    System.out.print("A");
}

Read this tutorial for more info on overloading.

A: The main problem was:
+ signature of main(String... args) is different for
    - main(String[] args, String arg)
    - main(String arg, String[] args)

+ main(String... args)
    - not equals for main(String[] args, String[] args2)
    - only for main(String[] args)

though I catch the compilation error on the following example:
public class MainOverloadingExample4 {

void go(String s){
    System.out.println("void go(String s)");
}
void go(String ... s){
    System.out.println("void go(String ... s)");
}
void go(String s, String ... arr){
    System.out.println("void go(String s, String ... arr){");
}
public static void main(String[] args) {
    new MainOverloadingExample4().go("where I am?", "why I am here?");
}
}

The method go(String[]) is ambiguous for the type MainOverloadingExample


text:
Q: Error converting odt to java with odftoolkit This is my first time with odftoolkit and I'm having an extrange error. I have an .odt template and when converting to pdf it looses data.
Example:

    **Title 1:**
Text 1.
    **Title 2:**
Text 2.

The thing is that cnverted PDF only have Text1 / text2 and nothin about the titles. Both are the same font but different heigth.
public static File convertir(File informe) throws Exception{
    logger.entry();
    File informePdf = null;
    String filePath = "";
    try{
        InputStream is = new FileInputStream(informe);
        filePath = informe.getAbsolutePath().replace(".ODT",".PDF");
        informePdf = new File(filePath);
        OutputStream os = new FileOutputStream(informePdf);
        ConversorPDF conversor = new ConversorPDF(is, os, false, true);
        conversor.convert();
        logger.trace("Convertido a PDF correctamente");
        return informePdf;
    }catch ( Exception e){
        logger.catching(e);
        throw e;
    }
}

Sorry for my english ;)


text:
Q: tikz figure from file Lets say i have a tikz figure in a file called tik_fig1.tex and tik_fig2.tex with \documentclass[tikz]{standalone}
Is it then possible to add these to a main.tex with \documentclass{article} by referencing the files, eg as
\documentclass{article}
\begin{document}

\begin{figure}
add(tik_fig1.tex)
\end{figure}

\begin{figure}
add(tik_fig2.tex)
\end{figure}

\end{document}

assuming all files are in the same directory.

A: You can \usepackage{standalone}.
% File-name: main.tex
\documentclass{article}
\usepackage{tikz}
\usepackage{standalone}

\begin{document}
\includestandalone{input}
\end{document}

% File-name: input.tex
\documentclass{standalone}

\begin{document}
\begin{tikzpicture}
  \draw (0,0) -- (1,1);
\end{tikzpicture}
\end{document}

Keep both of these files in the same directory of course. Note that you shall not add the .tex suffix to the argument of the \includestandalone command. Also you must load tikz in the main.tex file.


text:
Q: Экспорт товаров из 1С и импорт их в базу интернет-магазина на django Экспорт осуществляется в XML файлы. Получается приличная папочка мегабайт на 300 вместе с картинками. Я написал скрипт  в 500 строк кода, который однократно парсит все это в объекты python и грузит в базу. Объекты парсятся в словари, затем методом Model.objects.bulk_create(obj_list) без вызова save для каждого объекта. Парсятся сразу несколько моделей в порядке их зависимости друг от друга.
И все вроде работает. Но меня терзают смутные сомнения. Оптимальный ли это путь?
Ответственное лицо заявило, что будет делать мне выгрузку каждый день. В то же время, выгрузка такого объема явно избыточная. Изменений даже за день там в сотни раз меньше самой выгрузки. Меняются в основном остатки, то есть цифирь. Правильнее было бы отслеживать лишь эти изменения. Не так ли?
Какие существуют методы или решения экспорта-импорта из 1С для сайта на django?

A: Повесьте выгружаемые объекты на План обмена в 1С. При ежедневной выгрузке стучитесь в него и получаете только измененные объекты. После чего очищаете узел плана обмена, чтобы в следующий раз повторно их не тянуть


text:
Q: Script for take rate from website to write to .txt file I don't know how to take BTC rate from this website
https://api.coinmarketcap.com/v1/ticker/?limit=9  (7th row "price_usd")
to use it for some calculation and then write it to .txt file.
I already used it, calculated a screen it on my website by javascript, but I can't write it to txt file in my PC and I need it. I know that javascript doesn't offer to write it to .txt file, but do you have any idea how to do it with writing to txt file by different language?

A: Moe, you can use bash scripting on linux (if you are familiar). Here is the code. This should give you a direction to perform your calculations. Try running this from the command line. You can still simplify this code.
wget "https://api.coinmarketcap.com/v1/ticker/?limit=9" -O output

cat output | grep 'price_usd' | sed 's/"//g' | sed 's/,//g' | sed 's/price_usd//g' | sed 's/: //g' | awk '{print $1}' >
final.txt

cat final.txt


text:
Q: Does this proof make sense? $m \mid n$ if and only if $m \mid n^2$ Question and proof below. I'm a bit unsure if this proof make sense and want a second opinion. I could find a counter example I guess but I was trying to show that it is the case sometimes but not is not implied for all cases.
Either prove or find a counter-example to the statement $m \:|\: n$ if and only if $m \:|\: n^2$. (Here $n$ and $m$ are integers.)
Proof(Direct)
$m \:|\: n \Leftrightarrow n=km$
$m \:|\: n^2 \Leftrightarrow n^2=lm$
$n^2 = m^2 l^2 = m (m l^2)$
For any Prime $P$ : $P \:|\: ab \Rightarrow (P \:|\: a$ or $P \:|\: b)$
If $m$ is Prime $m \:|\: n^2 \Rightarrow m \:|\: n$
$\therefore \:m \:|\: n \not\Leftrightarrow m \:|\: n^2$ $\blacksquare$
EDIT:
Fixed the double k issue in the original (flawed) proof, alternate proof using counter-example
Proof(Cases)
Suppose $m \mid n$
Then $n = mk$ for some $k \in \mathbb{Z}$
$n^2 = (mk)^2 = m^2 k^2 = m(mk^2)$, so $m \mid n^2$
Suppose $m = 9$ and $n = 6$
Then $9 \mid 6^2 = 36$ but $9 \nmid 6$
$\therefore m \:|\: n \not\Leftrightarrow m \:|\: n^2$ $\blacksquare$
Thanks for the comments and help everyone!

A: You reused $k$ in the first and second lines of your proof, though these $k$'s are different (unless $n = 0$).
For the forward direction, suppose $m \mid n$. Then $n = mk$ for some $k \in \mathbb{Z}$. Then $n^2 = (mk)^2 = m^2 k^2 = m(mk^2)$, so $m \mid n^2$.
The converse is not true in general. Take $m = 9$ and $n = 6$. Then $9 \mid 6^2 = 36$ but $9 \not \mid 6$.
EDIT: I'm going to add a slight addendum, based on an comment that Thomas Andrews made. Specifically, this biconditional holds provided that $m$ is prime.
The forward direction holds by precisely the same argument. Suppose now that $m$ is prime and $m \mid n^2$. Then we have $n^2 = mk$ for some $k \in \mathbb{Z}$. Since $m$ is prime, $m \mid n^2$ immediately requires that $m \mid n$, which is the statement of Euclid's lemma.


text:
Q: ! Missing } inserted.} \end{thebibliography} I continuously get this error. Even though there is nothing missing or extra in line 132. I also checked for similar errors but could not find proper solution that could work for me.
Error:
! Missing } inserted.
<inserted text>
}
l.132 \end{thebibliography}
I've inserted something that you may have forgotten.
(See the <inserted text> above.)
With luck, this will get me unwedged. But if you
really didn't forget anything, try typing `2' now; then
my insertion and my current dilemma will both disappear.

Code snippet:
\begin{figure}[h]
\centering
\includegraphics[scale=0.5]{210}
\caption{{\small Schematic}}
\label{fig:210}                   % 132 line
\end{figure}


text:
Q: Primefaces datePicker range selection : allow to select only one date I would like to allow user to select only a date or a range of dates. It's for and SQL search.
One date selected: I search the items with this date
Two dates selected: I search the items between these two dates
I'm using PrimeFaces 8.0. I would like to have only one field to do that.
2 options tested with <p:datePicker>:

*

*selectionMode="multiple", great but i can't limit the number of date to maximum 2 dates. Not very user friendly too. Would be nice to be able to select only 2 dates, at the third date selected the 2 previous are unselected.

*selectionMode="range", perfect to select two date, but if you selected only one date, it's not submitted to a backing bean, totally ignored. How can I submit just one date?

A: This code will loop over all primefaces widgets on the page.
If the widget is a datePicker, and has only one date selected, it will add the same date as second date.
for (var widgetVar in PrimeFaces.widgets) {

    try {

    var widget = PrimeFaces.widgets[widgetVar];

    if(widget.jq && widget.jq[0].classList.contains('p-datepicker')){
        var datePicker = PF('' + widget.widgetVar);
        console.log('datePicker found');
        console.log(datePicker);
        console.log('Date : ');
        console.log(datePicker.getDate());

        if(datePicker.getDate() && datePicker.getDate().length == 2 && datePicker.getDate()[1] == null){
            datePicker.setDate(datePicker.getDate()[0]);
        }
    }

    } catch (error) {
       console.error(error);
    }

}


text:
Q: jquery attr(name,value) method's value parameter I'm reading Bibeault's jQuery in Action and I'm having troublel understanding the value parameter of the attr() method. The book says that the parameter can be a function whose parameters are index and previousValue. What is the purpose of these parameters? I don't understand the text's explanation.
Specifically I want to know:

*

*Are these parameters mandatory?

*What is an example of how these parameters are used?

*Can I use other parameters within the function?

A: It's actually pretty simple. The attr() function has three possible modes; the one you refer to takes a callback to get the value.
For example:
 $('.someClass').attr('rel', function(index, value)
 {
      // index refers to the elements index of the set; so of all elements with the
      //    css class 'someClass', the index will refer to that position in the list.
      //    If three elements match, the callback will be invoked 3 times, with 0, 1, 2
      //    as the index when each element, respectively, is invoked.

      // value refers to the current value of the attribute.

      // Return the value you want to set.
      return 'SomeRelValue';
 });

The parameters are not mandatory; if you simply omit them from the callback signature, you simply dont have access to that information. You cannot pass other parameters to this method. You might want to use this function when you will match a lot of elements, and want to insert some data based on their ordinal position of the selector element.
For example:
 $('.someElements').attr('rel', function(index, value)
 {
      return value + index;
 });

For each element matching the selector, you set the rel attribute to what it was plus the index of the selector. So element one, if it had a rel of 'sampleRel', is set to 'sampleRel1', element two with rel' sampleRel' becomes 'sampleRel2', etc etc

A: 1) No parameters are mandatory in javascript. You use whatever amount you want. These parameters are available for you in your function.
2) examples:
Let's say you have this html:

Now, run this snippet:
$('a').attr('title', function(index, previousValue){
    return previousValue + ' - An external link';
});

This will add the string " - An external link" to the end of every title.
Now, look at this:
$('a').attr('title', function(index, previousValue){
    return previousValue + ' - Link number ' + index;
});

This will result in the following html:

As you can see, you can see, these parameters are very handy.
3) Not sure what you mean by using other parameters. Please clarify.

It seems that you are not familiar with Javascript's scope lookup chain. You do not have to explicitly pass parameters to a function. If they're defined in a scope above it, the function will have access to it:
var num1 = 23;
var num2 = 54;

$('a').attr('title', function(){
    return num1 + num2;
});

A: attr is a way to access attributes on an element. the overload which allows a function will allow you to use the function return to set the value (the index param to the function would be the index into the selection, previousValue being the value it had until now).
I've never used this overload myself, but assume it would be nice if you're making attribute values based on some sort of function.
They are not mandatory, passing different number of parameters gives different functionality:
attr('name') - gets the value of name
attr('name','value') - sets the value of name
attr('name',function(i,v){return v+i;}); - sets the value of name to the previous value + the index in the collection.
example:
lets say we have five spans with the class hiccup and name 'yup'.
$('span.hiccup').attr('name',function(i,v){return v + i;});

will give each span a name 'yup1' - 'yup5'.
Additionally, you have access to this inside the function, which refers to the element itself. Given this, you could probably do some really interesting stuff.
As always, jQuery has awesome documentation of all of this:
http://api.jquery.com/attr

A: There's a good example in jQuery's documentation, which I'll shorten here:
Here's the relevant HTML:

Zero-th

First

Second

If you then run this javascript it'll apply unique id's to each div:
$("div").attr("id", function (arr) {
  return "div-id" + arr;
});

The $ function returns all of the div's so the arr argument allows you to specify the attribute value based on the index.
The function passed to attr also received a value specifying the old attribute value, but as this is javascript the function doesn't have to name that argument and it's still available in the arguments.


text:
Q: (PHP) MySQLi - Database entry missing I have a problem. Namely, I want a very simple form with select fields to be entered into a database. For this I use MYSQLi. Here you can see the code I use in HTML. But should be correct so far.
<form action="./php-functions/apply-server.php" method="post" class="form-group">

        Servertyp
        <select class="custom-select" name="applyservertype">
            <option value="1">Gameserver</option>
            <option value="2">vServer</option>
            <option value="" disabled selected>Bitte auswählen...</option>
        </select>

        Betriebssystem
        <select class="custom-select" name="serveroperatingsystem">
            <option value="u1604">Ubuntu 16.04</option>
            <option value="u1804">Ubuntu 18.04</option>
            <option value="u1810">Ubuntu 18.10</option>
            <option value="u1904">Ubuntu 19.04</option>
            <option value="u2004">Ubuntu 20.04</option>
            <option value="d10">Debian 10</option>
            <option value="d9">Debian 9</option>
            <option value="" disabled selected>Bitte auswählen...</option>
        </select>

        Systemeigenschaften
        <select class="custom-select" name="serversystem">
            <option value="1220">1 Kerne | 2GB RAM | 20GB Speicher</option>
            <option value="2440">2 Kerne | 4GB RAM | 40GB Speicher</option>
            <option value="3660">3 Kerne | 6GB RAM | 60GB Speicher</option>
            <option value="4880">4 Kerne | 8GB RAM | 80GB Speicher</option>
            <option value="" disabled selected>Bitte auswählen...</option>
        </select>

        Spiel
        <select class="custom-select" name="servergame">
            <option value="ark">ARK: Survival Evolved</option>
            <option value="gmod">Garry's Mod</option>
            <option value="mc">Minecraft Paper</option>
            <option value="rust">Rust</option>
            <option value="csgo">CS:GO</option>
            <option value="" disabled selected>Bitte auswählen...</option>
        </select>

        Systemeigenschaften
        <select class="custom-select" name="servergamesystem">
            <option value="4450">4 Kerne | 4GB RAM | 5GB Speicher</option>
            <option value="" disabled selected>Bitte auswählen...</option>
        </select>

        Beschreibung
        <textarea class="form-control" rows="5" min="50" max="1500" id="description" name="description" placeholder="• Wozu benötigst du den Server? (Konzept)
• Existiert bereits eine Community?
• Existiert bereits eine Website?
• ..." required></textarea>
        Bitte möglichst ausführlich, um eine schnelle und gezielte Abwicklung zu garantieren.
Mindestens 50 Zeichen, maximal 1500 Zeichen.

    <button type="submit" class="btn btn-secondary">Absenden </button>
</form>

Now follows my PHP code. Here I use the switch case, because I have two select cases and want to enter each differently into the database.
<?php
session_start();
if (!isset($_SESSION['loggedin'])) {
    $_SESSION['notification'] = "not-loggedin";
    header('Location: ../../index.php');
    exit;
}

$DATABASE_HOST = '#';
$DATABASE_USER = '#';
$DATABASE_PASS = '#';
$DATABASE_NAME = '#';
$con = mysqli_connect($DATABASE_HOST, $DATABASE_USER, $DATABASE_PASS, $DATABASE_NAME);
if (mysqli_connect_errno()) {
    exit('Fehler bei der Verbindung zu MySQL: ' . mysqli_connect_error());
}

$type = intval($_POST['applyservertype']);
$none = 'none';

switch ($type) {
    case 1:
        if ($stmt = $con->prepare('INSERT INTO serverapply (username, servertype, operatingsystem, game, system, serverdescription) VALUES (?, ?, ?, ?, ?, ?)')) {
            $stmt->bind_param('ssssss', $_SESSION['name'], $_POST['applyservertype'], $none, $_POST['servergame'], $_POST['servergamesystem'], $_POST['description']);
            $stmt->execute();
            $_SESSION['notification'] = "server-successful";
            header('Location: ' . $_SERVER['HTTP_REFERER']);
            exit;
        } else {
            $_SESSION['notification'] = "server-error";
            header('Location: ' . $_SERVER['HTTP_REFERER']);
            exit;
        }
        $stmt->close();
        break;
    case 2:
        if ($stmt = $con->prepare('INSERT INTO serverapply (username, servertype, operatingsystem, game, system, serverdescription) VALUES (?, ?, ?, ?, ?, ?)')) {
            $stmt->bind_param('ssssss', $_SESSION['name'], $_POST['applyservertype'], $_POST['serveroperatingsystem'], $none, $_POST['serversystem'], $_POST['description']);
            $stmt->execute();
            $_SESSION['notification'] = "server-successful";
            header('Location: ' . $_SERVER['HTTP_REFERER']);
            exit;
        } else {
            $_SESSION['notification'] = "server-error";
            header('Location: ' . $_SERVER['HTTP_REFERER']);
            exit;
        }
        break;
    default:
        $_SESSION['notification'] = "server-error";
        header('Location: ' . $_SERVER['HTTP_REFERER']);
        break;
}

Here is the picture of my database structure.
My database version
The PHP code is not executing properly for some reason I don't see. The form will be submitted and redirected to the page as if the submission was successful. After submitting, however, no database entry is created.

A: You are inserting an extra value ssssss. Just match the values with the attributes. The values are 7 and the attributes are 6.
bind_param should be like:
$stmt->bind_param($_SESSION['name'], $_POST['applyservertype'], $none, $_POST['servergame'], $_POST['servergamesystem'], $_POST['description']);


text:
Q: Reactive forms angular show error for pattern in angular I have reactive form like this
this.form = this.formBuilder.group({
      email: ['', [
        Validators.required,
        Validators.maxLength(120),
        Validators.pattern('^[^\\s@]+@[^\\s@]+\\.[^\\s@]{1,}$')
      ]],
    });

Now I need to display error for different error, like this

THIS EMAIL NOT VALID

But I got error
Cannot read property 'pattern' of null
Does anybody had similar problem with showing error for pattern?

A: You either fail or pass the validation. when you pass the validation form.controls.email.errors does not exist.
To overcome that: you need to replace errors with errors? as below:

THIS EMAIL NOT VALID

A: Please try this ::

THIS EMAIL NOT VALID


text:
Q: Cannot access e.target.id even though its there when i log e.target in react import { connect } from 'react-redux';
import { getClubs } from '../../actions/club';
import PropTypes from 'prop-types';

const ViewPlayers = ({ clubs, loading, getClubs }) => {
  useEffect(() => {
    getClubs();
  }, [getClubs]);

  const [form, editForm] = useState({
    club_id: ''
  });

  const selClub = e => {
    console.log(e.target); --> Has the id value set to the correct id
    console.log(e.target.id); --> outputs empty string
  };
  const submitData = e => {};
  return loading === true ? (

wait

  ) : (

View players

      <form onSubmit={e => submitData(e)}>

            Select Club

          <select
            className='form-control mb-3'
            name='club'
            value={form.club_id}
            onChange={e => selClub(e)}
          >
            {clubs.map(data => {
              return (
                <option key={data._id} id={data._id}>
                  {data.name}
                </option>
              );
            })}
          </select>

      </form>

  );
};

ViewPlayers.propTypes = {
  loading: PropTypes.bool.isRequired,
  clubs: PropTypes.array.isRequired,
  getClubs: PropTypes.func.isRequired
};

const mapStateToProps = state => ({
  clubs: state.club.data,
  loading: state.club.loading
});

export default connect(mapStateToProps, { getClubs })(ViewPlayers);

Okay so i have set the id on option tag of the select statement to the id of the current club..
When i console.log(e.target) i can see the id value set for all the clubs in my data set.. But if i console.log(e.target.id) i get 'empty string' even though it is set on` the above console.log to the correct id???? if i do e.target.value i get the correct value also???
How is it not seeing the e,target.id???
Thanks in advance for any help

A: I don't know why you would even need to use the id attribute on option tags. You can specify an id for your select tag, at least it makes sense. For option tags what you want to do is specify their value attributes. Then you can access a selected value using e.target.value in your onChange handler.
<select
  className='form-control mb-3'
  name='club'
  value={form.club_id}
  onChange={e => selClub(e)}
>
  {clubs.map(data => {
    return (
      <option key={data._id} value={data._id}>
        {data.name}
      </option>
    );
  })}
</select>


text:
Q: SQL - How do you use a user defined function to constrain a value between 2 tables First here's the relevant code:
create table customer(
   customer_mail_address   varchar(255)   not null,
   subscription_start      date           not null,
   subscription_end        date,          check (subscription_end !< subcription start)
   constraint pk_customer primary key (customer_mail_address)
)

create table watchhistory(
   customer_mail_address   varchar(255)   not null,
   watch_date              date           not null,
   constraint pk_watchhistory primary key (movie_id, customer_mail_address, watch_date)
)

alter table watchhistory
    add constraint fk_watchhistory_ref_customer foreign key (customer_mail_address)
        references customer (customer_mail_address)
    on update cascade
    on delete no action
go

So i want to use a UDF to constrain the watch_date in watchhistory between the subscription_start and subscription_end in customer. I can't seem to figure it out.

A: Check constraints can't validate data against other tables, the docs say (emphasis mine):

[ CONSTRAINT constraint_name ]
{
  ...
  CHECK [ NOT FOR REPLICATION ] ( logical_expression )
}

logical_expression
Is a logical expression used in a CHECK constraint and returns TRUE or
  FALSE. logical_expression used with CHECK constraints cannot
  reference another table but can reference other columns in the same
  table for the same row. The expression cannot reference an alias data
  type.

That being said, you can create a scalar function that validates your date, and use the scalar function on the check condition instead:
CREATE FUNCTION dbo.ufnValidateWatchDate (
    @WatchDate DATE,
    @CustomerMailAddress VARCHAR(255))
RETURNS BIT
AS
BEGIN

    IF EXISTS (
        SELECT
            'supplied watch date is between subscription start and end'
        FROM
            customer AS C
        WHERE
            C.customer_mail_address = @CustomerMailAddress AND
            @WatchDate BETWEEN C.subscription_start AND C.subscription_end)
    BEGIN
        RETURN 1
    END

    RETURN 0

END

Now add your check constraint so it validates that the result of the function is 1:
ALTER TABLE watchhistory
    ADD CONSTRAINT CHK_watchhistory_ValidWatchDate
    CHECK (dbo.ufnValidateWatchDate(watch_date, customer_mail_address) = 1)

This is not a direct link to the other table, but a workaround you can do to validate the date. Keep in mind that if you update the customer dates after the watchdate insert, dates will be inconsistent. The only way to ensure full consistency in this case would be with a few triggers.


text:
Q: How to attach a attachment file to a list item using REST API in SharePoint 2013 I'd like to ask experts.
Dose anyone know how to attach a attachment file to a list item using REST API in SharePoint 2013 ?
I searched the bellow document. But there is no information about upload a file as list item's attachments.
http://msdn.microsoft.com/en-us/library/fp142386.aspx
Additional info:
I found the bellow article.
http://chuvash.eu/2013/02/20/rest-api-add-a-plain-text-file-as-an-attachment-to-a-list-item/
According to the article, it's enable to upload a attachment file to a list item using bellow Javascript code. I'd like to use C#. I'm trying now, but I still didn't success.
var content = "Hello, this text is inside the file created with REST API";
var digest = $("#__REQUESTDIGEST").val();
var composedUrl = "/_api/web/lists/GetByTitle('List1')/items(1)/AttachmentFiles/add(FileName='readme.txt')";
$.ajax({
    url: composedUrl,
    type: "POST",
    data: content,
    headers: {
        "X-RequestDigest": digest
    }
})

A: There are a several approaches how to consume SharePoint REST API using .NET,some of them are listed below:

*

*HttpClient - Provides a base class for sending HTTP requests and receiving HTTP responses from a resource identified by a URI. (.NET Framework 4.5)

*WebClient - provides common methods for sending data to and receiving data from a resource identified by a URI. (.NET Framework 1.1)

*HttpWebRequest - provides an HTTP-specific implementation of the WebRequest class, more low-level then the previous ones

All of them allows to perform CRUD operations in SharePoint Online/SharePoint 2013 using REST interface.
SPWebClient class demonstrates how to perform CRUD operations using WebClient.
How to add attachment file via SharePoint REST API
The following example demonstrates how to add attachment file to List in SharePoint Online:
var credentials = new SharePointOnlineCredentials(userName, securePassword);
AddAttachmentFile(webUrl, credentials, "Nokia Offices", 1, @"c:\upload\Nokia Head Office in Espoo.jpg");

public static void AddAttachmentFile(string webUrl,ICredentials credentials,string listTitle,int itemId,string filePath)
{
        using (var client = new SPWebClient(new Uri(webUrl),credentials))
        {
            var fileContent = System.IO.File.ReadAllBytes(filePath);
            var fileName = System.IO.Path.GetFileName(filePath);
            var endpointUrl = string.Format("{0}/_api/web/lists/GetByTitle('{1}')/items({2})/AttachmentFiles/add(FileName='{3}')", webUrl,listTitle,itemId,fileName);
            client.UploadFile(new Uri(endpointUrl), fileContent);
        }
}

Dependencies:

*

*Utilizes SPWebClient class which represents a wrapper for WebClient

*Json.NET library dependency

A: Try to use this:
var executor = new SP.RequestExecutor(appweburl);
var digest = $("#__REQUESTDIGEST").val();
var content = "Hello, this text is inside the file created with REST API";

executor.executeAsync(
{
url: appweburl +           "/_api/web/lists/getbytitle('List1')/items(1)/AttachmentFiles/add(FileName='readme.txt)",
method: "POST",
body: content,
headers: {
          "X-RequestDigest": digest
         },
success: function(data) {
         toastr.success('Document attached successfully.');
         },
error: function(err) {
         toastr.error('Oops! Document attached created fail.');
         }
}
);


text:
Q: Copy Cell With Line Breaks - Paste Values Into Separate Cells Is there a way in VBA to copy the contents of a cell that has multiple items in it (broken up by carriage returns), and pasting the contents into another Worksheet with each original cell value in their own cell / row?
The only way I know how to do this is double-clicking into the cell (or copying from the text box when highlighting the cell), and just pasting it into a single cell elsewhere. I wish I could do this manually, but i'm dealing with a bunch of data and doing this automatically would be wonderful.
Example:

A: Here's an example of splitting cell contents in A1 on Sheet 1, into a variable x splitting on a VBA line-feed (normally the result of ALT+ENTER in an Excel cell)
x = Split(Worksheets("Sheet 1").Range("A1").Value2, vbLf)

Then you can cycle through the elements of x using a counter i and put each element into column B, where i+1 can be the row. Sample working routine:
Sub e()
Dim x As Variant
Dim i As Long
x = Split(Worksheets("Sheet 1").Range("A1").Value2, vbLf)
For i = LBound(x) To UBound(x)
    Worksheets("Sheet 2").Range("A" & i + 1).Value2 = x(i)
Next i
End Sub

You could avoid looping by transposing the array directly into a Range e.g. below taking split contents of A1 and placing them in column B:
Sub e()
Dim x As Variant
x = Split(Range("A1").Value2, vbLf)
Range("B1:B" & UBound(x) + 1).Value2 = Application.WorksheetFunction.Transpose(x)
End Sub


text:
Q: How do I combine aes() and aes_string() options Let's say I have a plot like this
library(ggplot2)
ggplot(mtcars, aes(x=wt)) + ylab("") +
   geom_line(aes(y=mpg, color="one")) +
   geom_line(aes(y=qsec, color="two")) +
   scale_color_manual(name="Val", values=c(one="#105B63",two="#BD4932"))

where I am plotting two lines and specifying a color group for each. Now let's say I want to specify the variables names dynamically as character values which means I'll need to use aes_string(). If I try
v1<-"mpg"
v2<-"qsec"
ggplot(mtcars, aes(x=wt)) + ylab("") +
   geom_line(aes_string(y=v1, color="one")) +
   geom_line(aes_string(y=v2, color="two")) +
   scale_color_manual(name="Val", values=c(one="#105B63",two="#BD4932"))

I get the error
Error in eval(expr, envir, enclos) : object 'one' not found

because now aes_string() is trying to parse the color value when I just want a literal character value. And if I try
ggplot(mtcars, aes(x=wt)) + ylab("") +
   geom_line(aes_string(y=v1), aes(color="one")) +
   geom_line(aes_string(y=v2), aes(color="two")) +
   scale_color_manual(name="Val", values=c(one="#105B63",two="#BD4932"))

I get
Error: ggplot2 doesn't know how to deal with data of class uneval

presumably because the layer doesn't know how to handle two aesthetic directives.
How can I combine aes() and aes_string() aesthetics or how can I specify literal character values for aes_string()?

A: If you want to specify a character literal value in aes_string(), the easiest thing would be to use shQuote() to quote the value. For example
ggplot(mtcars, aes(x=wt)) + ylab("") +
   geom_line(aes_string(y=v1, color=shQuote("one"))) +
   geom_line(aes_string(y=v2, color=shQuote("two"))) +
   scale_color_manual(name="Val", values=c(one="#105B63",two="#BD4932"))

This works because aes_string() actually runs parse(text=) on each of the parameter values. The shQuote() function adds quotes around your character value so that when you parse the value, you get a character value back rather than a symbol/name. Compare these two calls
class(parse(text="a")[[1]])
# [1] "name"
class(parse(text=shQuote("a"))[[1]])
# [1] "character"

Alternatively, you might think of merging aes() directives. The aes() functions really just return a list with a class of uneval. We could define a function to combine/merge these list. For example we can define addition
`+.uneval` <- function(a,b) {
    `class<-`(modifyList(a,b), "uneval")
}

Now we can do
ggplot(mtcars, aes(x=wt)) + ylab("") +
   geom_line(aes_string(y=v1) + aes(color="one")) +
   geom_line(aes_string(y=v2) + aes(color="two")) +
   scale_color_manual(name="Val", values=c(one="#105B63",two="#BD4932"))

A: With ggplot2 V3.0.0 it became really simple :
v1<-"mpg"
v2<-"qsec"
ggplot(mtcars, aes(x=wt)) + ylab("") +
  geom_line(aes(y=!!sym(v1), color="one")) +
  geom_line(aes(y=!!sym(v2), color="two")) +
  scale_color_manual(name="Val", values=c(one="#105B63",two="#BD4932"))

A: As an alternative to @MrFlick's excellent answer, you can also use aes_q and turn your variables' content into names:
ggplot(mtcars, aes(x=wt)) + ylab("") +
  geom_line(aes_q(y=as.name(v1), color="one")) +
  geom_line(aes_q(y=as.name(v2), color="two")) +
  scale_color_manual(name="Val", values=c(one="#105B63",two="#BD4932"))


text: Q: Barcode Printer taking 8 seconds to print next job I am using TSC TA210 barcode printer. It accepts job prints, everything is ok but when i submit 10 jobs at a time then it takes 8 second to complete single job (taking total time 10jobs * 8 sec per job = 80 sec to complete 10 jobs)


text:
Q: How to wait until List>> finishes? It's my first time working with webClient and I am wondering how to wait until List<Mono<>> finishes. I have the following code:
List<Address> addresses = collectAllAddresses(someObject);
List<Mono<List<AnotherAddress>>> monoResponses =
        addresses.stream()
                .map(address -> webClientGateway.findAddresses(userData, address.getFullAddress()))
                .collect(Collectors.toList());

Mono.when(monoResponses).block();

log.info("mono responses");
monoResponses.stream()
        .flatMap(it -> Objects.requireNonNull(it.block()).stream()).forEach(it -> log.info("mono responses + {}", it));

and the following findAddresses method:
public Mono<List<AnotherAddress>> findAddresses(UserData userData, String fullAddress) {

    if (StringUtils.isEmpty(fullAddress)) {
        log.info("Address is empty that why we return Mono.just(Collections.emptyList()");
        return Mono.just(Collections.emptyList());
    }

    return webClient.get()
            .uri(path, uri -> uri.queryParam("query", fullAddress).queryParam("count", 1).build())
            .header("someHeader", someHeader)
            .retrieve()
            .bodyToMono(new ParameterizedTypeReference<List<AnotherAddress>>() {
            })
            .doOnError(e -> log.error("Error occurred!", e));
}

but every time I execute it I always get list of empty objects, I mean I get List but every object in that list is empty (every field of class AnotherAddress is null). What can be wrong?
UDP: more explanations:
I have two microservices. In one microservice (that return another address) there is RestController that sends anotherAddress. In another microservice I want to use WebClient (instead of using threadPool with many threads) to call the RestController from previous microservice. When I have previous implementation for function webClientGateway.findAddresses(userData, address.getFullAddress()) and it returns Mono<List> I tested it and immediately after calling function I call block on result and it works. But now I have following situation, I have many addresses (maybe 5 or 10) and I want send async request for every address and wait until latest finishes and after that I want to do another operation, but instead of getting fullfielded AnotherAddress instance, I am getting 5 empty AnotherAddress instances (every field is null)

A: Use a Flux instead of a Mono, e.g. something like (untested):
public Flux<AnotherAddress> findAddresses(UserData userData, String fullAddress) {

    if (StringUtils.isEmpty(fullAddress)) {
        log.info("Address is empty that why we return Mono.just(Collections.emptyList()");
        return Flux.empty();
    }

    return webClient.get()
            .uri(path, uri -> uri.queryParam("query", fullAddress).queryParam("count", 1).build())
            .header("someHeader", someHeader)
            .retrieve()
            .bodyToFlux(AnotherAddress.class)
            .doOnError(e -> log.error("Error occurred!", e));
}

If you don't need the AnotherAddress list grouped by address the you could use something like (untested):
Flux<AnotherAddress> anotherAddressFlux= Flux.fromIterable(addresses)
                .flatMap(address -> webClientGateway.findAddresses(userData, address.getFullAddress()));

If you want to block you can use:
List<AnotherAddress> anotherAddressList = anotherAddressFlux.collectList().block();


text:
Q: How to listen for document changes in Cloud Firestore using Flutter? I would like to have a listener method that checks for changes to a collection of documents if changes occur.
Something like:
import 'package:cloud_firestore/cloud_firestore.dart';

  Future<Null> checkFocChanges() async {
    Firestore.instance.runTransaction((Transaction tx) async {
      CollectionReference reference = Firestore.instance.collection('planets');
      reference.onSnapshot.listen((querySnapshot) {
        querySnapshot.docChanges.forEach((change) {
          // Do something with change
        });
      });
    });
  }

The error here is that onSnapshot isn't defined on CollectionReference.
Any ideas?

A: Reading through cloud_firestore's documentation you can see that a Stream from a Query can be obtained via snapshots().
For you to understand, I will transform your code just a tiny bit:
CollectionReference reference = Firestore.instance.collection('planets');
reference.snapshots().listen((querySnapshot) {
  querySnapshot.documentChanges.forEach((change) {
    // Do something with change
  });
});

You should also not run this in a transaction. The Flutter way of doing this is using a StreamBuilder, straight from the cloud_firestore Dart pub page:
StreamBuilder<QuerySnapshot>(
  stream: Firestore.instance.collection('books').snapshots(),
  builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
    if (!snapshot.hasData) return new Text('Loading...');
    return new ListView(
      children: snapshot.data.documents.map((DocumentSnapshot document) {
        return new ListTile(
          title: new Text(document['title']),
          subtitle: new Text(document['author']),
        );
      }).toList(),
    );
  },
);

If you want to know any more, you can take a look at the source, it is well documented, where it is not self-explanatory.
Also take note that I changed docChanges to documentChanges. You can see that in the query_snapshot file. If you are using an IDE like IntelliJ or Android Studio, it is also pretty easy to click through the files in it.

A: Using this you can listen changes inside a single document.
DocumentReference reference = FirebaseFirestore.instance.collection('collection').doc("document");
    reference.snapshots().listen((querySnapshot) {

      setState(() {
        field =querySnapshot.get("field");
      });
    });


text:
Q: Sitecore 7 Index treelist lucene I have Sitecore items with a treelist property referring to other items (with different a template).
My goal is to find item A that contains item B in the treelist property using the ContentSearch api (lucene).
I've added the treelist property to my index:
  <indexConfigurations>
    <defaultLuceneIndexConfiguration type="Sitecore.ContentSearch.LuceneProvider.LuceneIndexConfiguration, Sitecore.ContentSearch.LuceneProvider">
      <fieldMap             type="Sitecore.ContentSearch.FieldMap, Sitecore.ContentSearch">
        <fieldNames hint="raw:AddFieldByFieldName">
          <field patch:before="field[0]" fieldName="TreelistProperty" storageType="YES" indexType="UNTOKENIZED" vectorType="NO" boost="1f" type="System.String"
                 settingType="Sitecore.ContentSearch.LuceneProvider.LuceneSearchFieldConfiguration, Sitecore.ContentSearch.LuceneProvider">
            <analyzer type="Sitecore.ContentSearch.LuceneProvider.Analyzers.LowerCaseKeywordAnalyzer, Sitecore.ContentSearch.LuceneProvider" />
          </field>
        </fieldNames>
      </fieldMap>
    </defaultLuceneIndexConfiguration>
  </indexConfigurations>

I would expect that lucene stores the treelist property as a concatenation of guids.
Assuming this is correct and my index is populated my query looks like this:
master = Sitecore.ContentSearch.ContentSearchManager.GetIndex("sitecore_master_index");
using (var context = master.CreateSearchContext())
{
    var results = context.GetQueryable<SearchResultItem>()
                .Where(x => x["TreelistProperty"].Contains("{456-41414-my-guid-here-1516}"))
                .GetResults();
    var hits = results.Hits.ToArray();
}

This returns nothing. Where did it go wrong?

A: You should normalize your guid, like this:
var master = Sitecore.ContentSearch.ContentSearchManager.GetIndex("sitecore_master_index");
using (var context = master.CreateSearchContext())
{
    Sitecore.Data.ID myId = ID.Parse("{456-41414-my-guid-here-1516}");
    string normalizedID = Sitecore.ContentSearch.Utilities.IdHelper.NormalizeGuid(myId );
    var results = context.GetQueryable<SearchResultItem>()
                .Where(x => x["TreelistProperty"].Contains(normalizedID))
                .GetResults();
            var hits = results.Hits.ToArray();
}

A: I think there is a typo in your index configuration, can you try
indexType="UN_TOKENIZED"
You can also investigate what values are in your lucene indexes using luke
http://www.sitecore.net/en-gb/learn/blogs/technical-blogs/getting-to-know-sitecore/posts/2013/06/using-luke-to-understand-sitecore-7-search.aspx

A: I think the guid values are stored without the braces and dashes by default. Try converting to ToShortId() before the comparison.


text: Q: H2 Database - keep row number unchanged after updating row record So this is for H2 database. I have this issue that each time I update a record of row from a table, the updated row will automatically go to the end of the list. Is there a way to keep the row sequence unchanged even after updating? Thanks.


text:
Q: Get images from images folder within pygame I'm working on a game with pygame and I have the following directory for it:

As you can see, I have an images folder in the package.
Now I'm struggling, to get the image with the path "JumpnRun/images/player/jumper-1.png" from within the path "JumpnRun/Player/Player.py".
I tried to get that image using the following code:
self.image:pygame.Surface = pygame.image.load(str(Path("..") / "images" / "player" / "jumper-1.png")).convert_alpha()

But this doesn't seem to work and I get the error "FileNotFoundError: No such file or directory."
Any ideas on that?

A: So, to get the image with pygame.image.load function, you should do in this way: carImg = pygame.image.load('image.png').
To find out more, I recommand you to check out this link : https://pythonprogramming.net/displaying-images-pygame/
The code from the link worked for me!
I hope I helped you!

A: You should just be able to use pygame.image.load("./../../images/player/jumper-1.png") because the directory .. is reserved for parent directory.


text:
Q: Como detectar el valor de un span angular Tengo un dropdown con un par de opciones, quiero escuchar cuando el valor del span que tiene la opción seleccionada cambia a otra opción, es decir si la opción es A y se cambia a B, quiero escuchar ese cambio, estoy usando Angular

         A  //Listen this  change

opt A

opt B

A: Ya que estás trabajando con una lista y no con un <select> te recomendaria que usaras la acción click de Angular para capturar el evento y luego realizar la acción que necesites.

opt A

opt B


text:
Q: Unable to run gridview.databind(), eventargs error I have a listbox, that on selected change, runs a method to bind data to a gridview.  I get the error: Unable to cast object of type 'System.EventArgs' to type 'System.Web.UI.WebControls.GridViewRowEventArgs'.  I have other parts of my code that call another gridview.databind() from other controls, so I have no idea why it's throwing this error now?
Protected Sub lstEmployees_SelectedIndexChanged(ByVal sender As Object, ByVal e As     EventArgs) Handles lstEmployees.SelectedIndexChanged
    Dim x As Int16
    Dim startStr, endStr As String

    If txtAdminSelectedDate.Text <> "" Then
        dtWeeks = GetWeek(txtAdminSelectedDate.Text)
    End If

    If dtWeeks.Rows.Count > 0 Then
        x = dtWeeks.Rows(0).Item(0).ToString().IndexOf("-")
        endStr = dtWeeks.Rows(0).Item(0).ToString().Substring(x + 1, 11)
        startStr = dtWeeks.Rows(0).Item(1).ToString()
        dtWrkHours = GetHoursOfTheWeek(startStr, endStr, _user).Tables(0)
        gvAdmin.DataSource = dtWrkHours
        gvAdmin.DataBind()
        sStatus = String.Empty
        aStatus = String.Empty
        AdminTot = 0
        timeTot = 0
    End If

End Sub

A: I forgot I asked this questions, but deleting RowDatabound and re-creating it fixed it.  I knew it was something weird.

A: It's likely you have a bad method signature for your grid.  Make sure it looks something like this:
Note: Pay special attention to the args: ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs
Public Sub xyz_DataBind(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles xyz.RowDataBound
   ...
End Sub


text:
Q: Codeigniyer 3.0.4 Session class showing strange behavior Since I upgraded my code co CI 3.x, I'm having really bad issues with session handling. Has anyone here experienced those issues and is there any fix for this?
Here are few of them

*

*Session gets destroyed on one controller and its still available on another controller after page reloads

*Session is sometimes not available in most controllers and views

*Session class is initialized but when I try to destroy a session, it get session is not initialized error.
So far I've tried

*

*files and database drivers

*setting cookie names

*setting cookie domain

Here are my observations so far

*

*In case of files, session does not delete session files in /var/lib/php5 when we destroy session

*session cookie is auto-generated on every page refresh even if i delete it
See these logs
INFO - 2016-06-20 15:17:58 --> Config Class Initialized
INFO - 2016-06-20 15:17:58 --> Hooks Class Initialized
DEBUG - 2016-06-20 15:17:58 --> UTF-8 Support Enabled
INFO - 2016-06-20 15:17:58 --> Utf8 Class Initialized
INFO - 2016-06-20 15:17:58 --> URI Class Initialized
INFO - 2016-06-20 15:17:58 --> Database Driver Class Initialized
INFO - 2016-06-20 15:17:58 --> Router Class Initialized
INFO - 2016-06-20 15:17:58 --> Output Class Initialized
INFO - 2016-06-20 15:17:58 --> Security Class Initialized
DEBUG - 2016-06-20 15:17:58 --> Global POST, GET and COOKIE data sanitized
INFO - 2016-06-20 15:17:58 --> Input Class Initialized
INFO - 2016-06-20 15:17:58 --> Language Class Initialized
INFO - 2016-06-20 15:17:58 --> Loader Class Initialized
INFO - 2016-06-20 15:17:58 --> Helper loaded: url_helper
INFO - 2016-06-20 15:17:58 --> Helper loaded: cms_helper
INFO - 2016-06-20 15:17:58 --> Helper loaded: global_helper
INFO - 2016-06-20 15:17:58 --> Helper loaded: security_helper
INFO - 2016-06-20 15:17:58 --> Database Driver Class Initialized
**ERROR - 2016-06-20 15:17:58 --> Severity: Warning --> ini_set(): A session is active. You cannot change the session module's ini settings at this time /home/casper/Documents/webapps/fca/system/libraries/Session/Session.php 313
INFO - 2016-06-20 15:17:58 --> Session: Class initialized using 'files' driver.**
INFO - 2016-06-20 15:17:58 --> Model Class Initialized
INFO - 2016-06-20 15:17:58 --> Model Class Initialized
INFO - 2016-06-20 15:17:58 --> Model Class Initialized
INFO - 2016-06-20 15:17:58 --> Model Class Initialized
INFO - 2016-06-20 15:17:58 --> Model Class Initialized
INFO - 2016-06-20 15:17:58 --> Model Class Initialized
INFO - 2016-06-20 15:17:58 --> Model Class Initialized
INFO - 2016-06-20 15:17:58 --> Model Class Initialized
INFO - 2016-06-20 15:17:58 --> Model Class Initialized
INFO - 2016-06-20 15:17:58 --> Model Class Initialized
INFO - 2016-06-20 15:17:58 --> Model Class Initialized
INFO - 2016-06-20 15:17:58 --> Model Class Initialized
INFO - 2016-06-20 15:17:58 --> Model Class Initialized
INFO - 2016-06-20 15:17:58 --> Model Class Initialized
INFO - 2016-06-20 15:17:58 --> Model Class Initialized
INFO - 2016-06-20 15:17:58 --> Controller Class Initialized
INFO - 2016-06-20 15:17:58 --> Model Class Initialized
INFO - 2016-06-20 15:17:58 --> Model Class Initialized
INFO - 2016-06-20 15:17:58 --> Model Class Initialized
**ERROR - 2016-06-20 15:17:58 --> Severity: Warning --> session_destroy(): Trying to destroy uninitialized session /home/casper/Documents/webapps/fca/application/controllers/Register.php 536**
INFO - 2016-06-20 15:17:58 --> Final output sent to browser
DEBUG - 2016-06-20 15:17:58 --> Total execution time: 0.0282


text:
Q: ASP.Net white page of death after submit We have two ASP.NET (4.0) web applications running on IIS 8.5. Periodically, the users will try to log in and after submitting their credentials, the page will reload into a white screen.
The response size is 0 bytes and has a 200 status. The login page will reload and the HTML will be displayed, but when you submit the form the white page will be displayed. This is solved when the application pool is recycled.
I have checked the IIS logs and event viewer and there are no errors or warning related to this issue.
The code for the login.aspx page is below:
<%@ Page Title="" Language="C#" MasterPageFile="~/login.Master" AutoEventWireup="true" CodeBehind="login.aspx.cs" Inherits="Driver.login1" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">

</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">

        Invalid Credentials

        <asp:TextBox TextMode="SingleLine" ID="txtEmail" CssClass="form-control" placeholder="Box Number" runat="server"></asp:TextBox>

        <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" CssClass="has-error" ControlToValidate="txtEmail" ErrorMessage="Careem Id Required" Display="Dynamic"></asp:RequiredFieldValidator>

        <asp:TextBox ID="txtPassword" runat="server" CssClass="form-control" TextMode="Password" placeholder="Password"></asp:TextBox>

        <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" CssClass="has-error" ControlToValidate="txtPassword" ErrorMessage="Password Required" Display="Dynamic"></asp:RequiredFieldValidator>

                    <%--<asp:CheckBox ID="cbxRememberMe" runat="server" style="position: absolute; top: -20%; left: -20%; display: block; width: 140%; height: 140%; margin: 0px; padding: 0px; background: rgb(255, 255, 255); border: 0px; opacity: 0;" />--%>
                    <input id="Login1_RememberMe" runat="server" type="checkbox" name="Login1$RememberMe" style="position: absolute; top: -20%; left: -20%; display: block; width: 140%; height: 140%; margin: 0px; padding: 0px; background: rgb(255, 255, 255); border: 0px; opacity: 0;">

                Remember me

            <asp:Button ID="btnSubmit" Text="Sign In" runat="server" CssClass="btn btn-primary btn-block btn-flat" OnClick="btnSubmit_Click" />

</asp:Content>

And the code behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Driver
{
    public partial class login1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (Request.QueryString["action"] != null && Request.QueryString["action"] == "logout")
                {
                    HttpCookie loggedInCookie = new HttpCookie("LoggedIn");
                    loggedInCookie.Expires = DateTime.Now.AddDays(-1);
                    Response.Cookies.Add(loggedInCookie);
                }
                else if (Request.Cookies["LoggedIn"] != null && Request.Cookies["LoggedIn"].Value != null)
                {
                    Response.Redirect("default.aspx");
                }
            }
            if (Request.Cookies["LoggedIn"] != null && Request.Cookies["LoggedIn"].Value != null)
            {
                Response.Redirect("default.aspx");
            }
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            using (DriverEntities cnx = new DriverEntities())
            {
                string password = Global.EncryptPassword(txtPassword.Text);
                if (cnx.Drivers.Where(x => x.BoxNumber == txtEmail.Text && x.Password == password).Any())
                {
                    Driver driver = cnx.Drivers.FirstOrDefault(x => x.BoxNumber == txtEmail.Text && x.Password == password);
                    Car car = cnx.Cars.FirstOrDefault(x => x.Id == driver.CarId);
                    HttpCookie loggedInCookie = new HttpCookie("LoggedIn");
                    loggedInCookie.Value = driver.Id.ToString();
                    if (!Login1_RememberMe.Checked)
                        loggedInCookie.Expires = DateTime.Now.AddHours(8);
                    else
                        loggedInCookie.Expires = DateTime.Now.AddYears(1);
                    Response.Cookies.Add(loggedInCookie);
                    HttpCookie carCookie = new HttpCookie("MV_car");
                    carCookie.Value = car.Id.ToString();
                    Response.Cookies.Add(carCookie);
                    DateTime currentDate = DateTime.Now.AddDays(-1);
                    Response.Redirect("default.aspx");
                }
                else
                {
                    spnInvalidAccount.Visible = true;
                }
            }
        }
    }
}

Some Remarks:
- I haven't been able to recreate this issue locally. This is only happening in the production environment.
- We use the same login page for a dozen other applications and we haven't had the same issue with them.
- The page is not redirecting to the default.aspx page.
- Customerrors is turned off so if there was an application error we would be able to see the exception screen


text:
Q: Getting errors while using exoplayer in Android Project gradle
Am using exoplayer compile 'com.google.android.exoplayer:exoplayer:r1.5.15' in my project gradle.
While including this release am getting following error those i have mentioned in comment in my code am new in exoplayer
Here is my code
class HpLib_HlsHpLibRendererBuilder implements HpLib_RendererBuilder {
private static final int BUFFER_SEGMENT_SIZE = 64 * 1024;
private static final int MAIN_BUFFER_SEGMENTS = 254;
private static final int AUDIO_BUFFER_SEGMENTS = 54;
private static final int TEXT_BUFFER_SEGMENTS = 2;
private final Context context;
private final String userAgent;
private final String url;
private AsyncRendererBuilder currentAsyncBuilder;

public HpLib_HlsHpLibRendererBuilder(LiveChannels player, String userAgent, String video_url) {
    this.context = player;
    this.userAgent = userAgent;
    this.url = video_url;
}
@Override
public void buildRenderers(LiveChannels player) {
    currentAsyncBuilder = new AsyncRendererBuilder(context, userAgent, url, player);
    currentAsyncBuilder.init();
}

@Override
public void cancle() {
    if(currentAsyncBuilder != null)
    {
        currentAsyncBuilder.cancel();
        currentAsyncBuilder = null;
    }
}
@Override
public void cancel() {
    if (currentAsyncBuilder != null) {
        currentAsyncBuilder.cancel();
        currentAsyncBuilder = null;
    }
}

private static final class AsyncRendererBuilder implements ManifestFetcher.ManifestCallback<HlsPlaylist> { **//Class 'AsyncRendererBuilder' must either be declared abstract or implement abstract method 'onManifest(String, T)' in 'ManifestCallback**
    private final Context context;
    private final String userAgent;
    private final String url;
    private final LiveChannels player;
    private final ManifestFetcher<HlsPlaylist> playlistFetcher;
    private boolean canceled;
    public AsyncRendererBuilder(Context context, String userAgent, String url, LiveChannels player) {
        this.context = context;
        this.userAgent = userAgent;
        this.url = url;
        this.player = player;
        HlsPlaylistParser parser = new HlsPlaylistParser();
        playlistFetcher = new ManifestFetcher<>(url, new DefaultUriDataSource(context, userAgent),
                parser);
    }
    public void init() {
        playlistFetcher.singleLoad(player.getMainHandler().getLooper(), this);//Can not resolve method 'singleLoad(android.os.Looper, com.example.pash.drm.HpLib_HlsHpLibRendererBuilder.AsyncRendererBuilder)
    }
    public void cancel() {
        canceled = true;
    }
    @Override**//Method does not override method from its superclass**
    public void onSingleManifestError(IOException e) {
        if (canceled) {
            return;
        }

        player.onRenderersError(e);
    }
    @Override //Method does not override method from its superclass
    public void onSingleManifest(HlsPlaylist manifest) {
        if (canceled) {
            return;
        }
        Handler mainHandler = player.getMainHandler();
        LoadControl loadControl = new DefaultLoadControl(new DefaultAllocator(BUFFER_SEGMENT_SIZE));
        DefaultBandwidthMeter bandwidthMeter = new DefaultBandwidthMeter();
        PtsTimestampAdjusterProvider timestampAdjusterProvider = new PtsTimestampAdjusterProvider();

        boolean haveSubtitles = false;
        boolean haveAudios = false;
        if (manifest instanceof HlsMasterPlaylist) {
            HlsMasterPlaylist masterPlaylist = (HlsMasterPlaylist) manifest;
            haveSubtitles = !masterPlaylist.subtitles.isEmpty();

        }

        DataSource dataSource = new DefaultUriDataSource(context, bandwidthMeter, userAgent);
        HlsChunkSource chunkSource = new HlsChunkSource(true /* isMaster */, dataSource, manifest,
                DefaultHlsTrackSelector.newDefaultInstance(context), bandwidthMeter,
                timestampAdjusterProvider, HlsChunkSource.ADAPTIVE_MODE_SPLICE);    **//Can not resolve ADAPTIVE_MODE_SPLICE**
        HlsSampleSource sampleSource = new HlsSampleSource(chunkSource, loadControl,
                MAIN_BUFFER_SEGMENTS * BUFFER_SEGMENT_SIZE, mainHandler, player, LiveChannels.TYPE_VIDEO);
        MediaCodecVideoTrackRenderer videoRenderer = new MediaCodecVideoTrackRenderer(context, sampleSource,
                MediaCodecSelector.DEFAULT, MediaCodec.VIDEO_SCALING_MODE_SCALE_TO_FIT);**//MediaCodecVideoTrackRenderer  in MediaCodecVideoTrackRenderer cannot be applied to**
        MediaCodecAudioTrackRenderer audioRenderer = new MediaCodecAudioTrackRenderer(sampleSource,
                MediaCodecSelector.DEFAULT);

        TrackRenderer[] renderers = new TrackRenderer[2];
        renderers[0] = videoRenderer;
        renderers[1] = audioRenderer;
        //renderers[2] = textRenderer;
        player.onRenderers(renderers, bandwidthMeter);
    }
}}

Thank you in advance

A: Sorry for wasted you time I found some importing files are missed.
import com.google.android.exoplayer.util.Util;
import com.google.android.exoplayer.DefaultLoadControl;


text:
Q: Showing that there is no base-point preserving homotopy
I'm working on this problem and showed that X is contractible. In fact I showed that X has the origin (0,0) as its deformation retract. However, I'm stuck at the second part. It seems intuitively clear that there is no such homopoty, but can't find a contradiction. Could anyone help me?

A: yes the origin is a strong deformationretract of this one. But here comes the hint: you take the subspace topology (although not stated explicitely, but otherwise there would exist such a basepoint preserving homotopy), therefore you can't "move" all the infinite many points near $x_0$ to $I\times 0$ and tear them apart from $x_0$. This is precisely what we require for a continous function. Try to formalize this situation. (note again: every(!!) neighborhood of $(0,1)$ contains infinitely many points in $X - (0 \times I)$!)
Your proof should also contain that at some point, all points in $(x,I)$ for $x >0$ have to pass through $I \times 0$, which means that we are in the situation above.


text:
Q: Make an element float until a specified width I use float in order to make a login form be displayd on the right side of the page in a black bar. But when if a user resize the window and make it have a small width the form goes up of the background-image. I want it to stop floating and do not move when it has width 100px. My website is http://greek.netii.net. I use the following HTML code:
<form action='index.php?action=login' method='post'>

Email:<input id='logemail' type='text' name='email' />
        Password:<input id='logpass' type='password' name='pass' />
        <input class='button' type='submit' name='action' value='Login' />

Forgot Password?

</form>

And the following css code:
ul#loginbar {
    float:right;
    margin:25px 0px 0px 0px;
    list-style-type:none;
}

A: You can set minimum width and height using the following CSS properties:
min-width: 100px;
min-height: 150px;

to avoid components to be reduced too much.

A: you dont need to float it to the right as it will come inwards on resizing......use this
ul#loginbar
{
position: absolute;
top: 10px;
right: 10px;
margin:25px 0px 0px 0px;
list-style-type:none;

}

and also in the parent container of the form or the body add
position: relative;
min-width: 600px;


text:
Q: Serializer error with sqlachemy and marshmallow According to the official documentation I try to get all instances of the Vehicle class in json format
Session = sessionmaker(bind=engine)
session = Session()
from models import Vehicle
from marshmallow_sqlalchemy import ModelSchema

class VehicleShema(ModelSchema):
    class Meta:
        model = Vehicle

vehicles = session.query(Vehicle).all()

vehicle_schema = VehicleShema()

session.add(vehicles)
session.commit()

dump_data = vehicle_schema.dump(vehicles)

print(dump_data)

But get an error
    raise exc.UnmappedInstanceError(instance)
sqlalchemy.orm.exc.UnmappedInstanceError: Class 'builtins.list' is not mapped

I think the problem may be the definition of queriset vehicles = session.query(Vehicle).all() but but I don't find another way to do it.
Then I call only one instance vehicles = session.query(Vehicle).first() all works fine.
error traceback
Traceback (most recent call last):
  File "/home/y700/projects/viastart/sqlalchemy/orm/session.py", line 1955, in add
    state = attributes.instance_state(instance)
AttributeError: 'list' object has no attribute '_sa_instance_state'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "get_vehisle_by_id.py", line 11, in <module>
    session.add(vehicles)
  File "/home/y700/projects/viastart/sqlalchemy/orm/session.py", line 1957, in add
    raise exc.UnmappedInstanceError(instance)
sqlalchemy.orm.exc.UnmappedInstanceError: Class 'builtins.list' is not mapped

A: You aren't specifying whether you want to serialize the vechiles as a collection i.e., a list.
vehicle_schema = VehicleShema(many=True)

This should do the trick. Refer to the examples posted on marshmallow docs.

A: Per my comment use schema.dump(vehicles, many=True):
To expand you'll likely end up wanting to use some utility like the following:
def dumpData(load_object, schema, many=False):
    try:
        answer = schema.dump(load_object, many=many)
    except ValidationError as errors:
        raise InvalidDump(errors, status_code=400)
    return answer

class InvalidDump(Exception):
    """error for dumping data"""
    status_code = 400

    def __init__(self, message, status_code=None, payload=None):
        Exception.__init__(self)
        self.message = message
        if status_code is not None:
            self.status_code = status_code
        self.payload = payload

    def to_dict(self):
        """include marshmallow validation errors in response"""
        rv = dict(self.payload or ())
        rv['message'] = self.message.messages
        return rv

Then for each data dump you create a version with that marshmallow schema.
def dumpVehicle(load_object, many=False):
    return dumpData(load_object, schema=vehicle_schema_full, many=many)


text:
Q: Android - Video Activity I've set an app that plays videos from internal storage. You can choose videos from the list view but  I would like to add videos to the list view from the URL not internal source. The code looks like this right now:
 private void fillVideosList(){
        videosList.clear();
        addVideosFrom(String.valueOf(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES)));
        addVideosFrom(String.valueOf(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)));
        addVideosFrom(String.valueOf(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM)));

One more thing.
I have a problem with going back to the previous activity after exiting the video. After I exit video and push the back button it doesn't take me to the previous activity, it takes me to the video once again.
The code for video controller looks like that:
 public VideoController(Context context){
        super(context);
        this.context = context;
        FrameLayout.LayoutParams params = (FrameLayout.LayoutParams)this.getLayoutParams();
        DisplayMetrics metrics = getContext().getResources().getDisplayMetrics();
        float dp = 50f;
        float fpixels = metrics.density * dp;
        int pixels = (int) (fpixels + 0.5f);
        params.bottomMargin = pixels;
        //params.rightMargin = pixels;
        this.setLayoutParams(params);
    }

    @Override
    public void setAnchorView(View view){
        super.setAnchorView(view);
        ImageButton exitButton = new ImageButton(context);
        exitButton.setImageDrawable(getResources().getDrawable((R.drawable.exit)));
        exitButton.setBackgroundColor(Color.BLACK);
        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
                LayoutParams.WRAP_CONTENT);
        params.gravity = Gravity.RIGHT;
        addView(exitButton, params);
        exitButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context, VideoPlayer.class);
                intent.putExtra((VIDEO_ACTIVITY_INTENT), "showContinueWatching");
                context.startActivity(intent);

A: The reason is MediaController consumed KEYCODE_BACK event in below codes, if you want KEYCODE_BACK event send to Activity normally, all you have to do is override the dispatchKeyEvent method of MediaController, deal with like this:
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
    if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
        return false;
    }
    return super.dispatchKeyEvent(event);
}


text:
Q: How to use Picasso in an Adapter without using context in Fragment When I try to use context in my fragment I get the error:

constructor Adapter in class Adapter cannot be applied to given types;
  required:Context,List<ListItem>,OnItemClickListener

I have declared my context in my adapter as follows:
 private Context mContext;

then i initialized the context:
 public MyAdapter(Context context,List<ListItem> listItems, OnItemClickListener callback) {
    this.listItems = listItems;
    this.callback = callback;
    this.mContext = context;

}

And used mContext to get my imageurl in the onBindViewHolder using picasso
 @Override
        public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
            ListItem listItem = listItems.get(position);

     Picasso.with(mContext).load(listItem.getImageurl()).into(holder.imageUrl;

        }

But now I can't seem to get around using this context in my Fragment.
This is what I've tried: In my Fragment:
//an error occurs
 adapter = new MyAdapter(this,listItems);

so I tried this:
//still get an error
  adapter = new MyAdapter(getContext(),this);

I also tried getActivity but still get an error
adapter = new MyAdapter(getActivity());

where am I going wrong?
All I am really trying to do is display the image in my listfragment but I don't know how to use Picasso with using context, and MyAdapter does not require context to function properly. I've been using it without declaring context and the data displays properly. Onclick is also working and displaying strings from firebase, but now I need to display images from Firebase using Picasso into my listfragment. Everything else works fine except this line of code in my Fragment:
adapter = new MyAdapter(getActivity());

A: You try Get context from any View object in Holder.
Example:
mContext = holder.imageView.getContext()

A: Fragments are inflated inside an Activity.

*

*In Fragment, you either use the context of the Activity or the context of the whole application.

*Plus you have missed passing one more parameter in the Adapter, ie your click listener.

Define the adapter like this -
OnItemClickListener mOnItemClickListener = OnItemClickListener {
    void onItemClick(int position) {

    }
}

adapter = new MyAdapter(getActivity(), listItems, mOnItemClickListener);

or
adapter = new MyAdapter(getActivity().getApplicationContext(), listItems, mOnItemClickListener);

A: In your adapter initialization you pass 2 parameters, but your constructor requires 3 parameters.
so try to initialize using 3 params:
   adapter=new MyAdapter(getContext(), listItems, this);

getContext()= context of fragment.
lisItems= your list.
this=is your click interface listener (make sure you implemented the listener in your fragment).

A: Try this, I think you forgot last argument
OnItemClickListener listener = OnItemClickListener {
    void onItemClick(int position) {
        //some code
    }
}
adapter = new MyAdapter(this, listItems, listener);