text:
Q: Transfer data from activity to fragment how can I transfer data when onTimeSet at MainActivity triggered to DataFragment and refresh it?
The proccess triggered when setTodayBtn clicked.
Main Activity:
public class MainActivity extends AppCompatActivity implements TimePickerDialog.OnTimeSetListener {

    public static MySQLiteHelper db;
    private ViewPagerAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ViewPager viewPager = findViewById(R.id.pager);
        adapter = new ViewPagerAdapter(getSupportFragmentManager());
        adapter.addFragment(new DataFragment(), "Data");
        adapter.addFragment(new SummaryFragment(), "Summary");
        adapter.addFragment(new VacationFragment(), "Missing");
        viewPager.setAdapter(adapter);

        viewPager.addOnPageChangeListener(new
        ViewPager.OnPageChangeListener() {
            int currentPosition = 0;

            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {

                FragmentLifecycle fragmentToHide = (FragmentLifecycle) adapter.getItem(currentPosition);
                fragmentToHide.onPauseFragment();

                FragmentLifecycle fragmentToShow = (FragmentLifecycle) adapter.getItem(position);
                fragmentToShow.onResumeFragment();

                currentPosition = position;
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        TabLayout tabLayout = findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(viewPager);
    }

    @Override
    public void onTimeSet(TimePicker timePicker, int i, int i1) {

        //Transfer i data to DataFragment
        //Refresh DataFragment

    }
}

Data Fragment:
public class DataFragment extends Fragment implements FragmentLifecycle{

    private Button setTodayBtn;

    public DataFragment() {

    }

    public static DataFragment newInstance(String param1, String param2) {
        DataFragment fragment = new DataFragment();
        return fragment;
    }

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

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

         View RootView = inflater.inflate(R.layout.fragment_data, container, false);
        setTodayBtn = RootView.findViewById(R.id.button_set_today);

        setTodayBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                DialogFragment newFragment = new TimePickerFragment();
                newFragment.show(getActivity().getFragmentManager(), "timePicker");

            }
        });

        return RootView;
    }

    private void refreshData() {

    }

    @Override
    public void onAttachFragment(Fragment childFragment) {
        super.onAttachFragment(childFragment);

    }

    @Override
    public void onDetach() {
        super.onDetach();
    }

    @Override
    public void onPauseFragment() {

    }

    @Override
    public void onResumeFragment() {

        refreshData();

    }

    public interface OnFragmentInteractionListener {
        void onFragmentInteraction(Uri uri);
    }

}

TimePickerFragment:
public class TimePickerFragment extends DialogFragment {

    private TimePickerDialog.OnTimeSetListener mListener;
    private Context context;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.context = context;

        try {
            mListener = (TimePickerDialog.OnTimeSetListener) context;
        } catch (ClassCastException e) {
            throw new ClassCastException(context.toString() + " must implement OnTimeSetListener");
        }
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        final Calendar c = Calendar.getInstance();
        int hour = c.get(Calendar.HOUR_OF_DAY);
        int minute = c.get(Calendar.MINUTE);

        return new TimePickerDialog(context, mListener, hour, minute, DateFormat.is24HourFormat(context));
    }

}

A: public class MainActivity extends AppCompatActivity implements TimePickerDialog.OnTimeSetListener {

    //...
    private DataFragment dataFragment;
    private ViewPagerAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ViewPager viewPager = findViewById(R.id.pager);
        adapter = new ViewPagerAdapter(getSupportFragmentManager());
        dataFragment = new DataFragment();
        adapter.addFragment(dataFragment, "Data");
        adapter.addFragment(new SummaryFragment(), "Summary");
        adapter.addFragment(new VacationFragment(), "Missing");
        viewPager.setAdapter(adapter);
    }
    //....
    @Override
    public void onTimeSet(TimePicker timePicker, int i, int i1) {
        dataFragment.setData(i);
        adapter.notifyDataSetChanged();
    }
}

You may also need to return POSITION_NONE from getItemPosition() inside your PagerAdapter


text:
Q: Handle "Not found" in community Is it possible handle "Not found" in community. For example when go to some not existing url community should redirect to some page responsible for handling 404 error.

A: You can use javascript in "Head Markup" to this
In Community setting click on the Edit Head Markup button and add the markup
Adding javascript to community pages

redpajama_set_name: RedPajamaStackExchange


text:
Q: Play2: How to overwrite config values within an unit test? I've the following test code where I want to test if given configuration parameters are used when creating an object within the tested code. To accomplish this, I try to override the config parameter in the beginning, capture the object and assert if the fields are set correctly.
Unfortunately, the config parameters from application.conf will not be overwritten with my test values. What is wrong? How can I overwrite the config parameter for the test?
application.conf:
email.default_from_address="my@company.com"
email.default_from_name="MyCompany"

Test:
  @Test
  public void testReadFromConfig() throws IOException, MandrillApiError {
    final Map<String, String> testConfig = new HashMap<>();
    final String fromName = "UnitTest From";
    final String fromEmail = "from@unittest.com";
    testConfig.put("email.default_from_name", fromName);
    testConfig.put("email.default_from_address", fromEmail);
    testConfig.putAll(inMemoryDatabase());

    running(fakeApplication(testConfig), () -> {
      MandrillEmailService emailService = new MandrillEmailService(
          mockedMandrillApi);
      EmailMessage testMessage = createTestMessageHelper(
          EmailMessage.CONTENT_TYPE.TEXT_HTML);
      emailService.send(testMessage);
    });

    ArgumentCaptor<MandrillMessage> captorForMandrillMsg =
        ArgumentCaptor.forClass(MandrillMessage.class);
    verify(mockedMessagesApi).send(captorForMandrillMsg.capture(), eq(false));

    MandrillMessage capturedMandrillMsg = captorForMandrillMsg.getValue();
    assertEquals(fromName, capturedMandrillMsg.getFromName());
    assertEquals(fromEmail, capturedMandrillMsg.getFromEmail());
  }

Error:
failed: expected:<[UnitTest From]> but was:<[MyCompany]>

A: I have found overwriting config in Play test framework extremely difficult. It must be Play bug. If you are not familiar with GlobalSettings class here is a resource. Try overwriting one of onLoadConfig methods as follows:
@Override
public Configuration onLoadConfig(Configuration config, File path, ClassLoader classloader) {
    if(Play.isTest()){
         // load test configuration and overwrite properties programmatically.
    }
}

A: My failure. The code mentioned above works. The problem was that I've read the configuration in a static block...
public class MandrillEmailService implements EmailService {

  private final static String FROM_ADDRESS;
  private final static String FROM_NAME;
  private final MandrillApi mandrillApi;

  static {
    FROM_ADDRESS = Play.application().configuration()
            .getString("email.default_from_address");
    FROM_NAME = Play.application().configuration()
            .getString("email.default_from_name");
  }

...


text:
Q: how to select a record from multiple tables I'd be glad if someone could show me how I can select a record from 12 tables.
The main issue is that I have a table for each subject for storing marks obtained by students.
Each subject table has the following columns: StudentId, RegId, AcademicYear, Term, Form, ClassScore, ExamScore, Total, Grade.
The studentDetails.Students table which contains students demographic record has StudentId  column as its primary key.

A: An example using a union query:
SELECT au_lname FROM authors
UNION ALL
SELECT lname FROM Employee
ORDER BY au_lname

A: There are a couple of different ways that you can return the data.
You can use a JOIN between the students table and all of the subjects tables:
select *  -- replace this with the columns you want to return
from Students s
left join subject1 s1
    on s.studentid = s1.studentid
left join subject2 s2
    on s.studentid = s2.studentid
left join subject3 s3
    on s.studentid = s3.studentid
left join subject4 s4
    on s.studentid = s4.studentid;

See SQL Fiddle with demo
Or you can use something like the following which joins the students table with a subquery that uses a UNION ALL between each subject table:
select s.StudentId, S.StudentName, S.Photo,
   sb.StudentId, sb.RegId, sb.AcademicYear,
   sb.Term, sb.Form, sb.ClassScore, sb.ExamScore, sb.Total, sb.Grade
from students s
inner join
(
    select s1.StudentId, s1.RegId, s1.AcademicYear,
          s1.Term, s1.Form, s1.ClassScore, s1.ExamScore, s1.Total, s1.Grade,
          'Subject1' as src
    from subject1 s1
    union all
    select s2.StudentId, s2.RegId, s2.AcademicYear,
          s2.Term, s2.Form, s2.ClassScore, s2.ExamScore, s2.Total, s2.Grade,
          'Subject2' as src
    from subject2 s2
    union all
    select s3.StudentId, s3.RegId, s3.AcademicYear,
          s3.Term, s3.Form, s3.ClassScore, s3.ExamScore, s3.Total, s3.Grade,
          'Subject3' as src
    from subject3 s3
) sb
    on s.studentid = sb.studentid

See SQL Fiddle with Demo
If you have another table that you want to join, then you will use:
select s.StudentId, S.StudentName, S.Photo,
   sb.StudentId, sb.RegId, sb.AcademicYear,
   sb.Term, sb.Form, sb.ClassScore, sb.ExamScore, sb.Total, sb.Grade,
   r.programofstudy
from students s
inner join
(
    select s1.StudentId, s1.RegId, s1.AcademicYear,
          s1.Term, s1.Form, s1.ClassScore, s1.ExamScore, s1.Total, s1.Grade,
          'Subject1' as src
    from subject1 s1
    union all
    select s2.StudentId, s2.RegId, s2.AcademicYear,
          s2.Term, s2.Form, s2.ClassScore, s2.ExamScore, s2.Total, s2.Grade,
          'Subject2' as src
    from subject2 s2
    union all
    select s3.StudentId, s3.RegId, s3.AcademicYear,
          s3.Term, s3.Form, s3.ClassScore, s3.ExamScore, s3.Total, s3.Grade,
          'Subject3' as src
    from subject3 s3
) sb
    on s.studentid = sb.studentid
left join Registration r
    on s.studentid = r.studentid
    and sb.regid = r.regid


text:
Q: Minor question about optimally increasing last item of a list What is the best way to increase the last item of a list by one? I've come up with ++list[[Length[list]]], is there something more efficient?

A: In my timings with a=Range[100000]
++a[[-1]]

a[[-1]] += 1

a[[-1]] = a[[-1]] + 1

and
++a[[100000]]

a[[100000]] += 1

a[[100000]] = a[[100000]] + 1

all evaluate in the same time.


text:
Q: issues getting .NET service installed I've been having on and off issues trying to get a service installed.
The problem is it installs fine on some machines, and others I either get that the service couldn't install
because of incorrect permissions, or that the service could be started, and these are all administrator account. I'm installing it using Advanced Installer.
What are some reasons that I could be having these issues? I should note the administrator account is a domain admin

A: I usually use the installutil.exe included with the .net framework version you are working with.  Installing with the utility will give you a log and tell you why the install may have failed.  In addition you will get prompted for a username and password if it is required during the installation process.  The formal Microsoft docs are here.
Enjoy!


text:
Q: ¿Cómo obtener los valores de frecuencia cardíaca de Google Fit History? Necesito obtener todas las mediciones del ritmo cardíaco, y no el mínimo, el máximo y el promedio, que es lo que he podido conseguir.
Este es el código que uso para leer de mi clase de Java.
private void readDataFitnessHistory()
{
    // Setting a start and end date using a range of 1 week before this moment.
    Calendar cal = Calendar.getInstance();
    Date now = new Date();
    cal.setTime(now);
    long endTime = cal.getTimeInMillis();

    cal.add(Calendar.WEEK_OF_YEAR, -1);
    long startTime = cal.getTimeInMillis();

    java.text.DateFormat dateFormat = getDateInstance();
    Log.d(TAG, "Range Start: " + dateFormat.format(startTime));
    Log.d(TAG, "Range End: " + dateFormat.format(endTime));

    DataReadRequest readRequest = new DataReadRequest.Builder()
            // The data request can specify multiple data types to return, effectively
            // combining multiple data queries into one call.
            // In this example, it's very unlikely that the request is for several hundred
            // datapoints each consisting of a few steps and a timestamp.  The more likely
            // scenario is wanting to see how many steps were walked per day, for 7 days.
            .aggregate(DataType.TYPE_HEART_RATE_BPM, DataType.AGGREGATE_HEART_RATE_SUMMARY)
            // Analogous to a "Group By" in SQL, defines how data should be aggregated.
            // bucketByTime allows for a time span, whereas bucketBySession would allow
            // bucketing by "sessions", which would need to be defined in code.
            .bucketByTime(1, TimeUnit.DAYS)
            .enableServerQueries()
            .setTimeRange(startTime, endTime, TimeUnit.MILLISECONDS)
            .build();

    // Invoke the History API to fetch the data with the query and await the result of
    // the read request.
    DataReadResult dataReadResult =
            Fitness.HistoryApi.readData(mApiClient, readRequest).await(1, TimeUnit.MINUTES);
    DataSet dataSet = dataReadResult.getDataSet(DataType.TYPE_HEART_RATE_BPM);
    showDataSet(dataSet);
    displayBpmDataForToday();

}

Gracias!
La respuesta:
History:    Type: com.google.heart_rate.summary
History:    Start: 22 sept. 2017 10:40:06
D/DBGPRUEBA History:    End: 22 sept. 2017 10:40:06
D/DBGPRUEBA History:    Field: average Value: 71.13179
D/DBGPRUEBA History:    Field: max Value: 86.0
D/DBGPRUEBA History:    Field: min Value: 55.0

A: Hola respondo a mi propia pregunta.
Para poder obtener todos los datapoints de las lecturas realizadas con la Api de Google Fit el objeto DataResult a construir sería el siguiente:
final DataReadRequest readRequest = new DataReadRequest.Builder()
   .read(DataType.TYPE_STEP_COUNT_DELTA)
   .read(DataType.TYPE_HEART_RATE_BPM)
   .enableServerQueries()
   .setTimeRange(startTime, endTime, TimeUnit.MILLISECONDS)
   .build();

Devolvería todos los datapoints entre el rango especificado.


text:
Q: Jquery get element attribute and insert it to an input text I need help for this issue.
I have a list of file and in each one a checkbox input. So i need to check one of that checkboxes and when click on "Insert" button, get the attribute value and insert it to that text input.
I appreciate your help.
here is my html code link:
http://jsfiddle.net/Qd3n5/4/

 samle-image.gif

        <input type="checkbox" name="delete" value="1" class="toggle">

 favicon.ico

        <input type="checkbox" name="delete" value="1" class="toggle">

 freedown.jpg

        <input type="checkbox" name="delete" value="1" class="toggle">

    <button type="button" id="Inser_btn" class="btn btn-primary Inser_btn">
 Insert

    </button>

    <input type="text" name="banners_image_local" value="some-text.png" size="51" maxlength="64">

A: You can try this :
$(function(){
    $('#Inser_btn').click(function(){
        var title='';
        $('input[name="delete"]:checked').each(function(){
            title+=$(this).closest('.size-text').prev().find('a').attr('title');
        });
        $('input[name="banners_image_local"]').val(title);
    });
});

Demo

A: Use this piece of Code
$("#Inser_btn").click(function(){
var val = $(".toggle:checked").parent().siblings().eq(0).find("p a").text();
$(".test input").val(val);

});
JSFIDDLE

A: By doing so:
$(document).ready(function(){
  $('#Inser_btn').click(function(){
      $('.download_list').each(function(){
          var checked = $(this).find('.toggle');
          if(checked.is(':checked')){
            $('input[name="banners_image_local"]').val($(this).find('a').html());
            return false;
          }
      });
  });
});

Here is a demo Fiddle

A: here is your code , have updated your JSFiddle
used jQuery for doing this click here
$(function(){
$("button").on('click', function(){
    var checked = $("input[type='checkbox']:checked");
    if(checked.length >0)
    {
        var value = checked.val();
        $("input[name='banners_image_local']").val(value);
    }

});

});

A: I am not sure whether this code works for you. Give it a try. (untested code)
$('#Inser_btn').on('click', function () {
   $('input[name="banners_image_local"]').val('');
   var ckText = $('input[name="delete"]:checked').val();
   var textBox = $('input[name="banners_image_local"]').val();
   textBox = textBox + " " + ckText;
   $('input[name="banners_image_local"]').val(textBox);
});

A: If you want to get the checked checkboxes value in the input field this should do with jQuery:
$("#Inser_btn").click(function(){
    $("#banners_image_local").val("");
    $('input[name="delete"]:checked').each(function() {
        $("#banners_image_local").val($("#banners_image_local").val() + ($(this).attr('value')));
   });
});

Also set the input text to id="banners_image_local"
Best.

A: Try this:
$('#Inser_btn').click(function () {
    $('input[name=banners_image_local]').val($('.toggle:checked').parent().prev().find('.File_Name').attr('title'));
});

Working Fiddle
Having a class name to input text would be better.


text:
Q: Как делить строку Задача: считываю файл и у меня там сплошной текст из цифр, пример:
1008905760101181870310118170851008875955100886887710088903191008885

И это малая часть, мне нужно, чтобы каждые 10 символов сохранялись в массиве или коллекции. Как это сделать?
Чтобы в конечном итоге выглядело вот так для одной из ячейки массива:
1008905760

A: String toParse = "1234567890123456789012345678901234567890123";
if(!toParse.isEmpty()) {
    int length = (int) Math.ceil(toParse.length() / 10);
    String[] result = new String[length];
    for(int i = 0; i < length - 1; i++) {
        result[i] = toParse.substring(i * 10, (i + 1) * 10);
    }
    result[length - 1] = toParse.substring(length * 10, toParse.length());
    for(String i : result){
        System.out.println(i);
    }
}

Вывод следующий:

1234567890
  1234567890
  1234567890
  123

A: package com.example.split;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

public class FileSpliterator {

    private static final int SPLIT_DIGITS_AMOUNT = 10;

    public static List<Integer> getNumbers(String filePath) throws IOException {
        try (Reader reader = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), StandardCharsets.US_ASCII))) {
            List<Integer> list = new ArrayList<>();
            StringBuilder sb = new StringBuilder(SPLIT_DIGITS_AMOUNT);

            int i = 1;
            while (true) {
                int ch = reader.read();
                if (ch == -1) {
                    if (sb.length() > 0) {
                        list.add(Integer.valueOf(sb.toString()));
                    }
                    break;
                }

                sb.append((char) ch);
                if (i % SPLIT_DIGITS_AMOUNT == 0) {
                    list.add(Integer.valueOf(sb.toString()));
                    sb.setLength(0);
                }

                i++;
            }
            return list;
        }
    }
}


text:
Q: FXML file in Netbeans keeps reverting changes to original copy? I'm working on a JavaFX application, and my FXML file keeps reverting back to its original changes whenever I build the file with dependencies in NetBeans.
Building with dependencies is the only way I can "save" changes with Maven, and whenever the build is complete, Notepad++ will inform me that the files have been changed and ask if I want to reload them (to which I click "NO"). If I have the FXML files open IN notepad++, then the changes are saved for that particular build, and if I run the project, everything works fine. The problem lies if I close my FXML files, and attempt to build the dependencies. Then, my changes are overwritten with the original code I had (I pulled the project from GitHub), and to get my changes back, I have to go to a commit I made. Is there some setting I missed when importing the Maven project into NetBeans? I am completely new to Maven and JavaFX (not programming or Java), so if I missed something trivial, please forgive me. Thanks!


text:
Q: Embedding a binary file inside a class library Is it possible to embed a custom binary file inside a C# class library and then at runtime read it with a binary reader?
I'm guessing it might be possible through resources.
Many thanks

A: Yes it is easy:
Add the file to your project and set the "Build action" to "Embedded resource".
In your program do
foreach (string name in Assembly.GetExecutingAssembly().GetManifestResourceNames())
{
  if (name.EndsWith("<name>", StringComparison.InvariantCultureIgnoreCase))
  {
    using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(name))
    {
      // ...
    }
    break;
  }
}

Finding the right resource is a little bit complicating because there is stuff in front of the file name (namespaces etc. set a breakpoint to the if(...) to see the real resource name).

A: You can do this by adding the file to the Resources through the project properties.  Visual studio will then give you a handy class to access your file using the following code
byte[] theFile = myNamespace.Properties.Resources.theBinaryFile;

Where the resource name is theBinaryFile.


text:
Q: Getting attachment file size in outlook VBA I receive emails and would like to save size of attachment in Excel sheet.
I can save size of email but I can't get size of attachment.
I looked up attachment.Size Property in MSDN, but it doesn't work. Could you please take a loop my for loop? I've attached my code below. I appreciate it if anyone would help.
Sub GetFromOutlook()

Dim OutlookApp As Outlook.Application
Dim OutlookNamespace As Namespace
Dim OutlookMail As Variant

Dim Folder As MAPIFolder

Dim olItems As Outlook.Items
Dim myItems As Outlook.Items
Dim olShareName As Outlook.Recipient

Dim dStart As Date
Dim dEnd As Date

Dim i As Integer

Dim sFilter As String
Dim sFilterLower As String
Dim sFilterUpper As String
Dim sFilterSender As String

'========================================================
'access to shared mailbox to get items
'========================================================

Set OutlookApp = New Outlook.Application
Set OutlookNamespace = OutlookApp.GetNamespace("MAPI")
Set olShareName = OutlookNamespace.CreateRecipient("teammailbox@example.ca")
Set Folder = Session.GetSharedDefaultFolder(olShareName, olFolderInbox).Folders("Subfolder1").Folders("Subfolder2")
Set olItems = Folder.Items

dStart = Range("From_Date").Value
dEnd = Range("To_Date").Value

'========================================================
'Conditions for restrict to get items specificed date
'========================================================

sFilterLower = "[ReceivedTime] >  '" & Format(dStart, "ddddd h:nn AMPM") & "'"
sFilterUpper = "[ReceivedTime] <  '" & Format(dEnd, "ddddd h:nn AMPM") & "'"
sFilterSender = "[SenderName] = ""jon.doe@example.com"""

'========================================================
'Restrict emails followed by above conditions
'========================================================

Set myItems = olItems.Restrict(sFilterLower)
Set myItems = myItems.Restrict(sFilterUpper)
Set myItems = myItems.Restrict(sFilterSender)

'========================================================
'items(emails) display in worksheets
'========================================================

i = 1

For Each myItem In myItems

     MsgBox myItem.Attachments.Size

     Range("eMail_subject").Offset(i, 0).Value = myItem.Subject
     Range("eMail_date").Offset(i, 0).Value = Format(myItem.ReceivedTime, "h:nn")
     Range("eMail_size").Offset(i, 0).Value = myItem.Size

     i = i + 1

Next myItem

Set Folder = Nothing
Set OutlookNamespace = Nothing
Set OutlookApp = Nothing

End Sub

Sub sbClearCellsOnlyData()
    Rows("5:" & Rows.Count).ClearContents
End Sub

A: The VBEditor has a great built-in tool for debugging. If you press Ctrl+F9, while selecting the myItem text with your mouse cursor you would be able to see it. It is called "Local Window" (or in German - "überwachungsausdrücke")
Long stroy short, give it a try like this in the code:
MsgBox myItem.Attachments.Item(1).Size

Instead of:
MsgBox myItem.Attachments.Size

Before doing this, it is a good idea to see whether the attachment exists:
If myItem.Attachments.Count > 0 Then

A: Attachment.Size property is not the size of the file blob - it is the size of the attachment record in the message store, which includes the attachment data, file name, and various other MAPI properties.
If you only want the file data, you can either use Extended MAPI (C++ or Delphi) to open the blob (PR_ATTACH_DATA_BIN) as IStream and call IStream::Stat. If you are limited to using the Outlook Object Model only, the only workaround is saving the attachment as file (Attachment.SaveAsFile) and then retrieving the file size.

A: I got hint from @Vityata and my below code is fixed and it works now.
For Each myItem In myItems

     Range("eMail_subject").Offset(i, 0).Value = myItem.Subject
     Range("eMail_date").Offset(i, 0).Value = Format(myItem.ReceivedTime, "h:nn")

     If myItem.Attachments.Count > 0 Then
     Range("eMail_size").Offset(i, 0).Value = myItem.Attachments.Item(1).Size / 1024  'convert to 3 digits (KB)

     Else
     Range("eMail_size").Offset(i, 0).Value = "No attached file"

     End If

  i = i + 1

Next myItem


text:
Q: How to select Multiple items in pickList(Primefaces)? I am trying to make a pickList. And I want multiple items to get selected on a click of single item. How can I achieve that?

A: I´m taking this from the primefaces website
in your view, I guess  you will have something like this
    <h:form>

     <p:selectBooleanCheckbox value="#{selectBooleanView.value1}" label="parent">
        <p:ajax update="cb1 cb2" listener="#{selectBooleanView.yourLogic}" />
      </p:selectBooleanCheckbox>
         <p:selectBooleanCheckbox id="cb1" value="#{selectBooleanView.value2}" label="son1"/>
         <p:selectBooleanCheckbox id="cb2" value="#{selectBooleanView.value3}" label="son2"/>

    </h:form>

See in the previuos code the ajax tag call the managed bean and update some items based in the ID
Your managed bean  SelectBooleanView.java
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.context.FacesContext;

@ManagedBean
public class SelectBooleanView {

private boolean value1;
private boolean value2;
private boolean value3;

public boolean isValue1() {
    return value1;
}

public void setValue1(boolean value1) {
    this.value1 = value1;
}

public boolean isValue2() {
    return value2;
}

public void setValue2(boolean value2) {
    this.value2 = value2;
}
public boolean isValue3() {
    return value3;
}

public void setValue3(boolean value3) {
    this.value3 = value3;
}

public void yourLogic() {
   this.value3= value1;
   this.value2=value1;
}
}

A: You can either use the server side ajax transfer event or client side 'onTransfer' call back attribute.
<p:ajax event="transfer" listener="#{foo.addOtherItemsToTranferList}" />
-OR-
<p:pickList ... onTransfer="foo.bar()">


text:
Q: Visual Studio Code: Changing language syntax highlighting within a document with multiple languages I have files with snippets in multiple different languages. I would like to change the syntax highlighting for a different blocks of code with, for example, comment blocks. Example would be:
SQL Procedure:

#sh sql

-- Establish procedure:
DELIMITER //
DROP PROCEDURE IF EXISTS -- ...
-- Basically, SQL syntax highlighting here until #endsh.

#endsh

Required PHP code for processing and verifying:

#sh php

<?php
// Some PHP code ...
?>

#endsh

I've split the code blocks for markdown syntax hightlighting. I've used #sh as an example from the built-in #region and #endregion that are in vscode, just as an example to get the point across.
I have looked for this for a while and couldn't find an answer, or an extension that would allow this. Basically, is this possible currently with some method, or is it possible with an extension that might not exist yet? If no such extension exists, where would be a good place to start to create this myself?
Thanks a lot.


text:
Q: Looking for general method for GridBagLayout component creation I'm designing a GUI with 20 or so components: 10 labels, 4 text fields, 4 buttons, and 2 text areas. Using GridBagLayout seemed a great idea. But with all the instance variables required to do it by the book for each component (i.e., not reuse), a general method for adding components seemed a must. I really thought this could work:
(Note: HORIZ is abbreviation for GridBagConstraints.HORIZONTAL;
      CENTER is abbreviation for GridBagConstraints.CENTER.)
public static void addComponent(Container f,      Component c,
                                  int     x,        int   y,
                                  int     w,        int   h,
                                  int     ipadx,    int   ipady,
                                  float   wtx,      float wty,
                                  int fill, int anchor, Insets insets){

  GridBagConstraints gbc = new GridBagConstraints();

  gbc.gridx = x;    gbc.gridy = y;
  gbc.gridwidth = w;    gbc.gridheight = h;
  gbc.fill = fill;
  gbc.ipadx = ipadx;    gbc.ipady = ipady;
  gbc.insets = insets;  gbc.anchor = anchor;
  gbc.weightx = wtx;    gbc.weighty = wty;

  f.add(c,gbc);
}

I called it like so:
    Insets insets = new Insets(0,0,0,0);
    JFrame frame = new JFrame();
    label = new JLabel("Blablablah");
    addComponent(frame, label, 0,0, 1,1, 0,0, 0.5f,0, HORIZ, CENTER, insets);

But I got message "cannot add to layout: constraint must be a string (or null)" at f.add(c.gbc).
I think I understand the error: frame doesn't have GridBagConstraints prior to the call to addComponent and gbc in the first line of the method doesn't belong to parameter f (or anything else?).
So I modified the method signature slightly, omitting Container:
public static void addComponent(                  Component c,
                                  int     x,        int   y,
... (rest unchanged)

And I modified the problem line like so:
frame.add(c, gbc);

So I'm using a global variable, frame, when I'd rather pass it as an argument.
Two questions:
(1) Is there a way to minimally modify my code to enable passing frame to addComponent?
(2) Is there any reason to want to do so? I guess this amounts to asking, what would YOU do?

P.S. Here's calls to the modified addComponent, hastily thrown together to get some semblance of the first few lines of what I want. The spacing reeks at the moment--I need to monkey with insets, ipads, fills--but it's actually usable. (New name for frame is GUI.)
private static void createAndShowGUI() {
  GUI = new JFrame();
  GUI.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  gbl = new GridBagLayout();
  GUI.setLayout(gbl);

  addComponent(lblRootNode, 0,0, 1,1, 0,0, 0.5f,0, HORIZONTAL, CENTER, new Insets(0,0,0,0));
  addComponent(txtRootNode, 1,0, 5,1, 60,0, 0.5f,0, HORIZONTAL, CENTER, new Insets(0,0,0,0));
  addComponent(btnBrowse,   6,0, 1,1, 0,0, 0.5f,0, HORIZONTAL, CENTER, new Insets(0,0,0,0));
  addComponent(lblFilenamePat, 0,1, 2,1, 0,0, 0.5f,0, HORIZONTAL, EAST, new Insets(0,0,0,0));
  addComponent(txtFilenamePat, 2,1, 4,1, 0,0, 0.5f,0, HORIZONTAL, LINE_END, new Insets(0,0,0,0));
  addComponent(lblDates, 0,2, 2,1, 0,0, 0.5f,0, HORIZONTAL, CENTER, new Insets(0,0,0,0));
  addComponent(lblSizes, 2,2, 2,1,   0,0, 0.5f,0, HORIZONTAL, CENTER, new Insets(0,0,0,0));

...

A: I use GridBagLyout quite a lot, but like many others before me, I quickly found out it can be quite verbose.  There are many examples on the web of how users wrote utility methods and/or classes to help them generate GBL code.  I'll show you what I do.
1) First, I created 2 enums that are wrappers for the anchor and fill GridBagConstraints fields. I prefer the type checking of enums vs. ints, and it also allows me to write more concise code (as you'll see later). And yes, I still use the older "directional" values for Anchor. I could never quite get used to the preferred values of PAGE_START and the like.  Use whatever you prefer.
Anchor.java:

package gbl;

import java.awt.*;

/**
 * Convenience enum that aliases out all possible values for the
 * GridBagConstraints anchor property.
 */
public enum Anchor
{
  NORTH(GridBagConstraints.NORTH),
  SOUTH(GridBagConstraints.SOUTH),
  EAST(GridBagConstraints.EAST),
  WEST(GridBagConstraints.WEST),
  NORTHEAST(GridBagConstraints.NORTHEAST),
  NORTHWEST(GridBagConstraints.NORTHWEST),
  SOUTHEAST(GridBagConstraints.SOUTHEAST),
  SOUTHWEST(GridBagConstraints.SOUTHWEST),
  CENTER(GridBagConstraints.CENTER);

  private int constraint;

  private Anchor(int gbConstraint)
  {
    constraint = gbConstraint;
  }

  public int getConstraint()
  {
    return constraint;
  }
}

Fill.java:

package gbl;

import java.awt.*;

/**
 * Convenience enum that aliases out all possible values for the
 * GridBagConstraints fill property.
 */
public enum Fill
{
  NONE(GridBagConstraints.NONE),
  HORIZONTAL(GridBagConstraints.HORIZONTAL),
  VERTICAL(GridBagConstraints.VERTICAL),
  BOTH(GridBagConstraints.BOTH);

  private int constraint;

  private Fill(int gbConstraint)
  {
    constraint = gbConstraint;
  }

  public int getConstraint()
  {
    return constraint;
  }
}

2) Then, I created a subclass of GridBagConstraints that allowed me "chain" the properties only as I need them, while utilizing common defaults:
GBConstraints.java:

package gbl;

import java.awt.*;

/**
 * Convenience class to simplify the creation of a GridBagConstraints object.
 */
public class GBConstraints extends GridBagConstraints
{
  public GBConstraints(int gridX, int gridY)
  {
    super();

    this.gridx = gridX;
    this.gridy = gridY;

    this.gridwidth = 1;
    this.gridheight = 1;
    this.weightx = 0;
    this.weighty = 0;
    this.anchor = NORTHWEST;              // old default was CENTER
    this.fill = NONE;
    this.insets = new Insets(1,2,1,2);    // old default was (0,0,0,0)
    this.ipadx = 1;                       // old default was 0
    this.ipady = 1;                       // old default was 0
  }

  public GBConstraints anchor(Anchor anchor)
  {
    this.anchor = anchor.getConstraint();
    return this;
  }

  public GBConstraints fill(Fill fill)
  {
    this.fill = fill.getConstraint();

    /*
     * As a convenience, set the weights appropriately since these values are
     * almost always used in tandem with the given Fill. The caller can always
     * call the weight(...) method later if these defaults aren't desired.
     */
    switch (fill)
    {
      case HORIZONTAL:
        this.weightx = 1;
        this.weighty = 0;
        break;
      case VERTICAL:
        this.weightx = 0;
        this.weighty = 1;
        break;
      case BOTH:
        this.weightx = 1;
        this.weighty = 1;
        break;
      default:
        this.weightx = 0;
        this.weighty = 0;
        break;
    }

    return this;
  }

  public GBConstraints insets(int length)
  {
    return insets(length, length, length, length);
  }

  public GBConstraints insets(int top, int left, int bottom, int right)
  {
    this.insets = new Insets(top, left, bottom, right);
    return this;
  }

  public GBConstraints ipad(int ipadX, int ipadY)
  {
    this.ipadx = ipadX;
    this.ipady = ipadY;
    return this;
  }

  public GBConstraints span(int gridWidth, int gridHeight)
  {
    this.gridwidth = gridWidth;
    this.gridheight = gridHeight;
    return this;
  }

  public GBConstraints spanX(int gridWidth)
  {
    this.gridwidth = gridWidth;
    return this;
  }

  public GBConstraints spanY(int gridHeight)
  {
    this.gridheight = gridHeight;
    return this;
  }

  public GBConstraints weight(double weightX, double weightY)
  {
    this.weightx = weightX;
    this.weighty = weightY;
    return this;
  }

  public GBConstraints weightX(double weightX)
  {
    this.weightx = weightX;
    return this;
  }

  public GBConstraints weightY(double weightY)
  {
    this.weighty = weightY;
    return this;
  }
}

3) Putting it all together, here's a demo that shows how to use the above classes. This greatly simplifies using GridBagLayout, IMHO.  Side note: I normally stay away from static imports, but I like it in this situation.
Demo:

package gbl;

import static gbl.Anchor.*;
import static gbl.Fill.*;

import java.awt.*;
import javax.swing.*;

public class GridBagDemo implements Runnable
{
  public static void main(String[] args)
  {
    SwingUtilities.invokeLater(new GridBagDemo());
  }

  public void run()
  {
    JLabel lblFirst  = new JLabel("First Name");
    JLabel lblLast   = new JLabel("Last Name");
    JLabel lblStreet = new JLabel("Street");
    JLabel lblCity   = new JLabel("City");
    JLabel lblState  = new JLabel("State");
    JLabel lblZip    = new JLabel("ZIP");
    JLabel lblNotes  = new JLabel("Notes");

    JTextField txfFirst  = new JTextField(15);
    JTextField txfLast   = new JTextField(20);
    JTextField txfStreet = new JTextField(40);
    JTextField txfCity   = new JTextField(15);
    JTextField txfState  = new JTextField(5);
    JTextField txfZip    = new JTextField(10);

    JTextArea txaNotes = new JTextArea(5, 50);
    JScrollPane scrNotes = new JScrollPane(txaNotes);
    scrNotes.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

    Component spacer1 = Box.createHorizontalStrut(5);
    Component spacer2 = Box.createHorizontalStrut(5);

    JPanel panel = new JPanel(new GridBagLayout());
    panel.add(spacer1,   new GBConstraints(0,0));
    panel.add(lblFirst,  new GBConstraints(0,1));
    panel.add(txfFirst,  new GBConstraints(1,1));
    panel.add(lblLast,   new GBConstraints(2,1));
    panel.add(txfLast,   new GBConstraints(3,1).spanX(3).fill(HORIZONTAL));
    panel.add(lblStreet, new GBConstraints(0,2));
    panel.add(txfStreet, new GBConstraints(1,2).spanX(5).fill(HORIZONTAL));
    panel.add(lblCity,   new GBConstraints(0,3));
    panel.add(txfCity,   new GBConstraints(1,3));
    panel.add(lblState,  new GBConstraints(2,3).anchor(EAST));
    panel.add(txfState,  new GBConstraints(3,3));
    panel.add(lblZip,    new GBConstraints(4,3));
    panel.add(txfZip,    new GBConstraints(5,3).fill(HORIZONTAL));
    panel.add(lblNotes,  new GBConstraints(0,4));
    panel.add(scrNotes,  new GBConstraints(1,4).spanX(5).fill(BOTH));
    panel.add(spacer2,   new GBConstraints(0,5));

    JFrame frame = new JFrame("Grid Bag Demo");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.add(new JScrollPane(panel), BorderLayout.CENTER);
    frame.pack();
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
  }
}

Again, this is just one of many ways you'll find online.  Hope this helps.

A: You said:

I called it like so:
Insets insets = new Insets(0,0,0,0);
JFrame frame = new JFrame();
label = new JLabel("Blablablah");
addComponent(frame, label, 0,0, 1,1, 0,0, 0.5f,0, HORIZ, CENTER, insets);

Did you actually omit frame.setLayout(new GridBagLayout())?
Because this is what causes the cannot add to layout: constraint must be a string (or null) error...
EDIT:
Possible duplicates:

*

*Java GridBagLayout and JPanel Error: cannot add to layout:
constraint must be a string (or
null)

*getting Exception : java.lang.IllegalArgumentException: cannot add
to layout: constraint must be a string (or
null)

A: Here's me using @Splungebob's enums and methods (and his "demo" as a model) to positively painlessly and quickly design and implement a very nice UI into an existing program of mine that had a terrible UI.
public class UI extends JFrame {
...
JPanel panel = new JPanel(new GridBagLayout());
panel.setBackground(Color.LIGHT_GRAY);
panel.add(lblCenterX,     new GBConstraints(0,0));
panel.add(lblCenterY,     new GBConstraints(0,1));
panel.add(lblRadius,      new GBConstraints(0,2).anchor(EAST));
panel.add(lblIterations,  new GBConstraints(0,3).anchor(EAST));
panel.add(spnCenterX,     new GBConstraints(1,0).fill(HORIZONTAL));
panel.add(spnCenterY,     new GBConstraints(1,1).ipad(90,10));
panel.add(spnRadius,      new GBConstraints(1,2));
panel.add(spnIterations,  new GBConstraints(1,3));
panel.add(btnPaint,       new GBConstraints(0,4).spanX(2).spanY(2).ipad(30,20).anchor(CENTER));
panel.add(btnDefaults,    new GBConstraints(0,6));
panel.add(btnExit,        new GBConstraints(1,6).anchor(EAST));
this.add(panel, BorderLayout.CENTER);
this.pack();
this.setLocationRelativeTo(null);
this.setVisible(true);

I post this only in hopes that someone needing as much help as I did about GBL finds it and then looks back up at Splunge's stuff. How cool is the line for btnPaint, where I make a HUGE button!

A: As I commented above, @ccjmme's help led me to add two lines and modify a signature to get a working version with no global variables. I am posting a version that is much better than that working verion. My subsequent comment explains why.
package test;
import java.awt.*;
import javax.swing.*;

public class Test{

  public static void addComponent(Component c, Container f,      GridBagConstraints gbc,
                                    int     x,        int   y,
                                    int     w,        int   h,
                                    int     ipadx,    int   ipady,
                                    float   wtx,      float wty,
                                    int fill, int anchor, Insets insets){
    if(fill   <= 0)     fill    = GridBagConstraints.NONE;
    if(anchor <= 0)     anchor  = GridBagConstraints.CENTER;
    if(insets == null)  insets  = new Insets(0,0,0,0);
    gbc.gridx = x;        gbc.gridy = y;
    gbc.gridwidth = w;    gbc.gridheight = h;
    gbc.fill = fill;
    gbc.ipadx = ipadx;    gbc.ipady = ipady;
    gbc.insets = insets;  gbc.anchor = anchor;
    gbc.weightx = wtx;    gbc.weighty = wty;

    f.add(c,gbc);
  }

  public static void addComponent(String s, Container f, GridBagConstraints gbc,
                                  int     x,        int   y,
                                  int     w,        int   h,
                                  int     ipadx,    int   ipady,
                                  float   wtx,      float wty,
                                  int fill, int anchor, Insets insets){
    addComponent(new JLabel(s),f,gbc,x,y,w,h,ipadx,ipady,wtx,wty,fill,anchor,insets);
  }

  public static void addComponent(Component c, Container f, GridBagConstraints gbc,
                                  int     x,        int   y){
    addComponent(c, f, gbc, x, y, 1,1, 0,0, 0.5f,0.5f,
                  GridBagConstraints.NONE, GridBagConstraints.CENTER,
                  new Insets(0,0,0,0));
  }

  public static void main(String[] args) {
    Insets insets = new Insets(0,0,0,0);
    JFrame frame = new JFrame();
    frame.setLayout(new GridBagLayout());
    JLabel label = new JLabel("Blablablah");
    JTextField text = new JTextField("text");
    JTextField next = new JTextField("a bit longer");
    GridBagConstraints gbc = new GridBagConstraints();

    addComponent("On the fly", frame, gbc, 0,0, 1,1, 0,0, 0.5f,0, 0, 0, insets);
    addComponent(label,        frame, gbc, 0,1);

    addComponent(next, frame, gbc, 1,1, 10,1, 0,0, 5.0f,0.5f, GridBagConstraints.EAST, 0, null);
    addComponent(text, frame, gbc, 1,0);
    frame.pack();
    frame.setVisible(true);
  }
}

Improvements:
(1) Two additional signatures for addComponent so that (i) a label can be created on the fly without declaring and initializing a variable (not good if code needs to refer to it, but mine rarely does) and (ii) any component can be added by just specifying (x,y) and accepting defaults.
(2) "Default 0" options to avoid having to type 'GridBagConstraints.CENTERand...NONE` if you'll usually want those fill and anchor values.


text:
Q: How can I find the maximum value of one variable, conditional on the level of another? I have a vector of hourly temperatures (DATA$TEMP) linked to dates (DATA$DATE) and thermometer position (DATA$PLACE).
I want identify the maximum temperature conditional on date and position. I can easily do this one date and position at a time, given I specify each date and position.  eg.
x <- max(DATA$TEMP[DATA$DATE =="20/12/15" & DATA$PLACE=="room"])

However I have many dates and positions and would like a function that can run through each date / position combination and return a vector of max temps linked to each.

A: Try this
library(dplyr)

x <- DATA %>%
   group_by(DATE, PLACE) %>%
   summarise(maximum= max(TEMP))

A: Here an answer using base:
 by(DATA$TEMP, list(DATA$DATE, DATA$PLACE), max)

On a more general note, this kind of problem falls under the split-apply-combine paradigm. If you google this, you will find that there are quite many ways of doing this in R. From several base functions, to plyr, dplyr, and data.table versions. See e.g. here.

A: Another option with data.table
library(data.table)
setDT(DATA)[, list(Max = max(TEMP)) , .(DATE, PLACE)]

Or with base R aggregate
aggregate(TEMP~DATE+PLACE, DATA, FUN= max)


text:
Q: what equation $\text{Ric}\le \frac{1}{2}Sg$ implies in three dimension Let $M$ be the three manifold with the following equation holds:
$$\text{Ric}\le \frac{1}{2}Sg$$
Which is an analog of the Einstein equation.What does this condition implies for three dimensional case?
I know if the equality holds,the manifold has constant sectional curvature,is there more information about this equation?


text:
Q: Encrypt file using certificate resulting in 'Expecting PUBLIC KEY' I've been given a certificate and told to encrypt a file using openssl.

*

*This certificate is a .cer file, so I need to create a .pem file first. I have tried doing this using macOS's Keychain Access, and also using openssl in the terminal. They result in the same file, which starts with -----BEGIN CERTIFICATE-----.

*I run the following command
openssl pkeyutl -encrypt -inkey certificate.pem -pubin -in key.xml -pkeyopt rsa_padding_mode:oaep -pkeyopt rsa_oaep_md:sha256 -pkeyopt rsa_mgf1_md:sha256 -out key.xml.enc

*I get the error

unable to load Public Key Error initializing context
  4799456876:error:0906D06C:PEM routines:PEM_read_bio:no start
  line:pem_lib.c:697:Expecting: PUBLIC KEY

Am I using the wrong tools or the wrong approach? Any help is appreciated :)


text:
Q: Scale (resize) large images (graphics) that exceed page margins Background
A large number of screen captures have been scaled 300% at 288dpi. They appear correctly when embedded in OpenOffice, but not LyX.
Problem
Images that do not extend beyond the margins (small images) appear perfectly. Images that are too big extend beyond the margins.
Attempt #1
\setkeys{Gin}{width=1.0\textwidth}

However, that code scales the smaller images to also fit the width, which is undesirable. (The smaller images become distorted.)
Attempt #2
Didn't attempt this, but it looks useful.
% Redefine includgraphics for avoiding images larger than the screen size
% If the size is not specified.
\let\py@Oldincludegraphics\includegraphics

\newbox\image@box%
\newdimen\image@width%
\renewcommand\includegraphics[2][\@empty]{%
  \ifx#1\@empty%
    \setbox\image@box=\hbox{\py@Oldincludegraphics{#2}}%
    \image@width\wd\image@box%
    \ifdim \image@width>\linewidth%
      \setbox\image@box=\hbox{\py@Oldincludegraphics[width=\linewidth]{#2}}%
      \box\image@box%
    \else%
      \py@Oldincludegraphics{#2}%
    \fi%
  \else%
    \py@Oldincludegraphics[#1]{#2}%
  \fi%
}

Source: http://svn.python.org/projects/external/Sphinx-1.0.5/sphinx/texinputs/sphinx.sty
Attempt #3
% Resize figures that are too wide for the page
\let\oldincludegraphics\includegraphics
\renewcommand\includegraphics[2][]{%
  \makeatletter%
  \def\maxwidth{\ifdim\Ginnatwidth>\linewidth\linewidth%
  \else\Ginnatwidth\fi}%
  \makeatother%
  \oldincludegraphics[width=\maxwidth]{#2}%

Packages
Using graphicx.
Other package suggestions are welcome.
Question
Without adding LaTeX code to every image that exceeds the margins, what can be done to resize just those images that are too big?
Example
The following image is an example of many, many images that must be scaled back to fit the page width:

Related

*

*How to make images appear at their actual size?

*http://compgroups.net/comp.text.tex/A-modified-includegraphics

A: I don't use Lyx, but many people in my lab do, and come to me with all sorts of problems created by Lyx. All of the Lyx-created problems I've seen can only be fixed by editing the latex code manually. YMMV.
This should fix it (you'll need
\usepackage{ifthen}

\ifthenelse{\lengthtest{Gin > \textwidth}}
{\setkeys{Gin}{width=1.0\textwidth}}{\relax}

A: Using the adjustbox package with the export option which extends graphicx with several new keys you can now simply use the max width key which scales the image down to that width if it is larger but doesn't scale it at all if it is smaller the equal to it. There are also the related keys max height, max size (for both width and height) as well as min width, min height and min size.
In your case simply use the following code:
\includegraphics[max width=\linewidth]{<image file name>}

Note that you can't set max width etc. in a global way using \setkeys{Gin}{max width=...}. It is implemented in a different way as width. However, I'm planning to add a possibility for this as well.

A: *

*Define a macro that calculates whether the image is wider than \linewidth.

*If the image is too wide then assign a value of \linewidth to the macro.

*Otherwise, assign the value of the graphic input's natural width (\Gin@nat@width).

*Redefine \includegraphics to leverage the new macro definition.

\usepackage{graphicx}

% Determine if the image is too wide for the page.
\makeatletter
\def\ScaleIfNeeded{%
  \ifdim\Gin@nat@width>\linewidth
    \linewidth
  \else
    \Gin@nat@width
  \fi
}
\makeatother

% Resize figures that are too wide for the page.
\let\oldincludegraphics\includegraphics
\renewcommand\includegraphics[2][]{%
  \oldincludegraphics[width=\ScaleIfNeeded]{#2}
}

Source

A: Here is another solution, based on the original attempt #2 (from sphinx.sty). What I needed was to only resize images that were too big, in all the others that could fit I wanted to keep the original arguments to \includegraphics.
\makeatletter
\newbox\image@box%
\newdimen\image@width%
\newcommand\IncludeGraphics[2][\@empty]{%
  \setbox\image@box=\hbox{\includegraphics[#1]{#2}}%
  \image@width\wd\image@box%
  \ifdim \image@width>\linewidth%
    \setbox\image@box=\hbox{\includegraphics[width=\linewidth]{#2}}%
    \box\image@box%
  \else%
    \includegraphics[#1]{#2}%
  \fi%
}

I can now do:
\IncludeGraphics[scale=.7]{myimage}

And in case the myimage scaled down to 70% is still wider than current line it will be scaled down even more to fit the \linewidth otherwise it will stay scaled down to only 70%.
Please note, that this will create a new command \IncludeGraphics rather than modify the \includegraohics. If you want to use \includegraphics instead then you need to add
\let\oldincludegraphics\includegraphics

And change the \newcommand\IncludeGraphics to \renewcommand\includegraphics and inside the body call the \oldincludegraphics.


text:
Q: pandas read_sql used for CREATE in Postgres db giving TypeError for SQLite I am trying to use pandas to create functions and tables in postgres.
When I try this query:
conn = = psycopg2.connect(host='localhost', database='my_data',
                     port='5566', user='postgres', password='postgres')

create_example = '''
    create temporary table example(id int primary key, str text, val integer);
    insert into example values
    (1, 'a', 1),
    (2, 'a', 2),
    (3, 'b', 2);
'''
pd.read_sql(create_example,conn)

I get the following error TypeError: 'NoneType' object is not iterable

The connection/read_sql works for simple queries but I get the error when I try to CREATE a function or table. Why am I getting the error and why does the error seem to be in SQLite when the connection is to a postgres database? tia
UPDATE: Per the observation by @AdrianKlaver I imported sqlalchemy as follows.
from sqlalchemy import create_engine

def db_connect():
    db_connect_string = "postgresql+psycopg2://{user}:{passwd}@{server}:{port}/{db}" \
        .format(user="postgres", passwd="postgres",
    server="localhost", db="my_data", port="5566")
    return create_engine(db_connect_string)

alchemy_conn = db_connect()

So using this alchemy connection:
pd.read_sql(create_example,alchemy_conn.raw_connection())

>>TypeError: 'NoneType' object is not iterable

If I try to use the cursor function I get the error AttributeError: 'psycopg2.extensions.cursor' object has no attribute 'cursor'


text:
Q: Elastic server running out of space on VirtualBox? I'm running the frontend part of a project which uses an Elastic search server on a VirtualBox instance.
This is the error I'm getting:
[FORBIDDEN/12/index read-only / allow delete (api)];].
Checking if there is enough disk space with df -h showed the following output:
Filesystem      Size  Used Avail Use% Mounted on
udev            982M     0  982M   0% /dev
tmpfs           201M  6,3M  194M   4% /run
/dev/sda1        23G   17G  5,3G  76% /
tmpfs          1001M  1,4M  999M   1% /dev/shm
tmpfs           5,0M  4,0K  5,0M   1% /run/lock
tmpfs          1001M     0 1001M   0% /sys/fs/cgroup
D_DRIVE         379G  285G   95G  76% /media/sf_D_DRIVE
tmpfs           201M  8,0K  201M   1% /run/user/108
tmpfs           201M   36K  201M   1% /run/user/1000

Do I still need to add space to the VirtualBox instance? Trying to unlock indices with curl -XPUT -H "Content-Type: application/json" http://localhost:9200/_all/_settings -d '{"index.blocks.read_only_allow_delete": null}' returned curl: (7) Failed to connect to localhost port 9200: Connection refused. I'm not sure though if I specified the correct location and port.
How do I get the Elastic server to run?


text:
Q: Error 3265 - Field exists in recordset All,
I'm trying to populate an activexlist view, but am getting Error 3265.
The code to populate it is:
Do Until rs.EOF
        Set lstItem = ctlListView.ListItems.Add()
        lstItem.text = rs!EntityID
        lstItem.subitems(1) = Nz(rs!Class, "")
        lstItem.subitems(2) = Nz(rs!Bundle, "")
        lstItem.subitems(3) = Nz(rs!Reference, "")
        lstItem.subitems(4) = Nz(rs!DisplayReference, "")
        lstItem.subitems(5) = Nz(rs!CalculatedReference, "")
        lstItem.subitems(6) = Nz(Format(rs!EntityDate, "d mmm yyyy"), "")
        lstItem.subitems(7) = Nz(Format(rs!EntityTime, "hh:mm am/pm"), "")
            lstItem.subitems(8) = Nz(rs!Description, "")
[...]

And the recordset that's triggering the error is:
SELECT p_Primary_1.EntityID, p_Primary_1.Class, p_Primary_1.Reference, p_Primary_1.Bundle, p_Primary_1.EntityDate, p_Primary_1.EntityTime, p_Primary_1.Description, p_Primary_1.DisplayReference, p_Primary_1.CalculatedReference, p_Primary.EntityID
FROM p_Primary AS p_Primary_1 INNER JOIN (p_Primary INNER JOIN JunctionTable ON p_Primary.EntityID = JunctionTable.PK1) ON p_Primary_1.EntityID = JunctionTable.PK2
WHERE (((p_Primary.EntityID) = 46) AND ((JunctionTable.RelationshipType) = 'EXEX'));

I get the error on line
lstItem.text = rs!EntityID

I presume that is because "EntityID" exists twice in the recordset (p_Primary_1.EntityID and P_Primary.EntityID).
How do you avoid the error?  (e.g., is it possible to simply add the first object in the collection (which will always be "EntityID")?)

A: Responding to your questions in opposite order ...

is it possible to simply add the first object in the collection (which will always be "EntityID")?

Yes, you can reference a recordset field via its (zero-based) index.  So the first field is rs.Fields(0) or rs(0)
Incidentally you can use rs.Fields(0).Name to see the name Access is using for that field in the recordset.

How do you avoid the error?

If you use Fields(0), you would need to ensure it gets updated as needed when/if the SELECT is modified.
If you really need both EntityID fields in the query, alias one or both ...
SELECT p_Primary_1.EntityID AS EntityID1, p_Primary.EntityID AS EntityID0

Otherwise, just SELECT one of those 2 EntityID fields.


text:
Q: What is reason for compile errors from .h file of custom library class in Arduino IDE I am developing a program for a robot using Energia (a fork of Arduino). I decided to create a library composed of a single class to handle position and distance calculations.
When I try to use the class I am seeing compiler errors that I do not understand.
Here is my .h file:
#ifndef Position
#define Position
#include "Energia.h"
class Position
{
    public:
        Position(int PinEcho, int PinTrig);
        float getDistance(char* Distance);
        float getDistanceMoy(int Nombre,char* unite);
    private:
        int _pinEcho;
        int _pinTrig;

};
#endif

And the .cpp file contains:
#include "Energia.h" //Arduino.h if we are using Arduino
#include "Position.h"

Position::Position(int pinEcho,int pinTrig)
{
    pinMode(pinEcho, OUTPUT);
    pinMode(pinTrig, INPUT);
    digitalWrite(pinTrigger, LOW);
    int _pinEcho = pinEcho;
    int _pinTrig = pinTrig;
    const unsigned long MEASURE_TIMEOUT = 25000UL;
    const float SOUND_SPEED = 340 / 1000;
}

float Position::getDistance(char* mode){
    digitalWrite(pinTrigger, LOW);
    digitalWrite(pinTrigger, HIGH);
    delayMicroseconds(10);
    digitalWrite(pinTrigger, LOW);
    long mesure = pulseIn(pinEcho,HIGH,MEASURE_TIMEOUT);
    float distance = mesure / 2 * SOUND_SPEED;
    if(mode =="cm") distance = distance / 10;
    if(mode =="dm") distance = distance / 100;
    if(mode == "m") distance = distance / 1000;
    return distance;
}

float Position::getDistanceMoy(int maxi,char* mode){
    int i=0, j=0;
    int distMoy = 0;
    while(i != maxi ){
        digitalWrite(pinTrigger, LOW);
        digitalWrite(pinTrigger, HIGH);
        delayMicroseconds(10);
        digitalWrite(pinTrigger, LOW);
        long mesure = pulseIn(pinEcho,HIGH,MEASURE_TIMEOUT);
        float distance = mesure / 2 * SOUND_SPEED;
        if(distance != 0){
            distMoy += distance;
            j++;
        }
        i++;
    }
    distMoy = distMoy/j;
    if(mode =="cm") distMoy = distMoy / 10;
    if(mode =="dm") distMoy = distMoy / 100;
    if(mode == "m") distMoy = distMoy / 1000;
    return distMoy;
}

Then I import the library on Arduino with #include <Position.h> and then initialize it:
Position position(Variable1,Variable2);

But when I want to use it and Energia (or Arduino) I get these errors:
In file included from C:\Users\alex9\Documents\Energia\sketch_may10a\sketch_may10a.ino:1:0:
C:\Users\alex9\Documents\Energia\libraries\Position/Position.h:15:18: error: expected unqualified-id before 'int'
         Position(int PinEcho, int PinTrig);
                  ^
C:\Users\alex9\Documents\Energia\libraries\Position/Position.h:15:18: error: expected ')' before 'int'
C:\Users\alex9\Documents\Energia\libraries\Position/Position.h:13:1: error: an anonymous struct cannot have function members
 {
 ^
C:\Users\alex9\Documents\Energia\libraries\Position/Position.h:22:1: error: abstract declarator '<anonymous class>' used as declaration
 };
 ^
sketch_may10a:8: error: expected constructor, destructor, or type conversion before '(' token
 Position position(PinEcho,PinTrig);
                  ^
exit status 1 expected constructor, destructor, or type conversion before '(' token

I don't understand these error messages and don't know what I need to fix. Could someone help me?

A: In your .h file you have the following lines of text which are Preprocessor commands to:

*

*check to see if the Preprocessor macro "Position" is defined

*if it is not defined then define it as empty or no text

Once the Preprocessor does this macro definition for the macro "Position" then as the Preprocessor continues to do its source text processing, one of the things it does is everytime it finds the token "Position" it will replace that token with its defined value which in this case is the empty string.
#ifndef Position
#define Position

You must remember when using the Preprocessor that it is an additional processing step that has nothing to do with compilation. It is a text only processing step which is used to modify the source text before it is fed into the compiler which is a totally separate step.
You can check what is happening by running the Preprocessor by itself and looking at the resulting output file. How that is done will vary between compilers though typically it is a compiler switch.
The typical way to put Preprocessor guards in a .h file is to do something like this example. This Preprocessor macro for an include file guard is made up of the name of the include file followed by the letter "H" followed by the word "included" with the various parts connected with underscores:
#ifndef POSITION_H_INCLUDED
#define POSITION_H_INCLUDED

By using this macro name it is much less likely that you will have a clash between the macro name and some variable or class or struct name/label or other text token within the source file.
This naming convention does a couple of things for you.
First it uses all upper case which is the defacto standard for Preprocessor macro names.
Secondly it is pretty descriptive of the intent of this macro name.
Thirdly the probability of some other text token being the same is fairly remote so the likelihood of an error such as you are running into is small.
Naming Approaches for Large Bodies of Source Code
However with a large project, as in hundreds of thousands of lines of code with thousands of files, it is possible that the same name is used for different include files in different libraries. This same issue is why the namespace concept was invented with C++.
So a more complex name using some additional text added to the macro name would increase the probability of the macro name being unique. One approach would be to add the name of the library or the name of the manufacturer to the macro name.
#ifndef POSITION_H_INCLUDED_POSITION_LIB_MICHAUD
#define POSITION_H_INCLUDED_POSITION_LIB_MICHAUD

A simple approach is to add the date and time into the macro name as in:
#ifndef POSITION_H_INCLUDED_20180517_1021_00
#define POSITION_H_INCLUDED_20180517_1021_00

Some IDEs will do something similar for you as part of generating source code for classes and that sort of thing. Here is an example from an older Visual Studio C++ IDE that generated an MFC class include file. This is kind of overkill in that it appears the IDE generates a GUID, which is pretty unique, and uses that to create what is like 99.999999999% likely to be a unique Preprocessor macro name or identifier. Notice that as part of generating this macro name, the IDE used the name of the include file, the letter "H", and the word "included" along with the GUID.
#if !defined(AFX_OPOSCASHDRAWER_H__86921069_045D_4880_A41A_5A18F0E5FABD__INCLUDED_)
#define AFX_OPOSCASHDRAWER_H__86921069_045D_4880_A41A_5A18F0E5FABD__INCLUDED_

Also notice that the IDE generated Preprocessor directive is using the defined() operator. This allows you to use more complex logical operations with the #if directive of the Preprocessor.
See this Wikipedia article, C Preprocessor for more details about the Preprocessor. This material should apply to most C++ versions of the Preprocessor as well.

A: You should not name the Class the same way you name your define
A define is like an alias, so, your Class name is being set to the define value, in your case empty string.


text:
Q: MongoDb pool connection I have configured pool connection in my code, I have doubt that pool connection needs to handle by code After each operation is completed or else Mongo db driver handles pool connection by itself?
                int maxConnectionPoolSize = Convert.ToInt32(ConfigurationManager.AppSettings["MaxConnectionPoolSize"]);
                int maxConnectionIdleTime = Convert.ToInt32(ConfigurationManager.AppSettings["MaxConnectionIdleTime"]);

                var mongoClientSettings = MongoClientSettings.FromConnectionString(PlatformRuntimeSecrets.DataServiceSecrets.ConnectionString);

                if (minConnectionPoolSize > 0)
                    mongoClientSettings.MinConnectionPoolSize = minConnectionPoolSize;

                if (maxConnectionPoolSize > 0)
                    mongoClientSettings.MaxConnectionPoolSize = maxConnectionPoolSize;

                if (maxConnectionIdleTime > 0)
                    mongoClientSettings.MaxConnectionIdleTime = TimeSpan.FromMinutes(maxConnectionIdleTime);

                mongoClient = new MongoClient(mongoClientSettings);
                mongoDatabase = mongoClient.GetDatabase(PlatformRuntimeSecrets.DataServiceSecrets.Database);```


text:
Q: Object assignment is creating a reference in PHP I have a weird behavior when assigning an existant object to an array.
In the example below, I have a class that contains one property. I create a first array with 3 instances (let's call them 2-4-6) and then a second array with 2 other instances using one object of the first array (instance 4). While modifying the values of the objects in second array to create 2 new instances (ie instances 3-5), the instance 4 is also modified. In consequence, at the first array query I get the right values (2-4-6) but after creating the second array I get the modified value (2-5-6). I would expect that the assignment operator copied the object, but instead it creates a reference to the instance. In the example I can get rid of this issue by explicitly calling clone, but in a larger scale, this isn't work (wrong code optimization?). Any clue (or good practice) of how to avoid this issue?
Thanks!
<?php
    class TestBase
    {
        private int $m_test = 0;
        public function SetTest(int $v)
        {
            $this->m_test = $v;
        }
        public function GetTest() : int
        {
            return $this->m_test;
        }
    }

    function getNewList(TestBase $ref) : array
    {
        $newlist = [3 => new TestBase(), 5 => $ref];
        $newlist[3]->SetTest(3);
        $newlist[5]->SetTest(5);
        return $newlist;
    }

    $listOfTest = [2 => new TestBase(), 4 => new TestBase(), 6 => new TestBase()];
    $listOfTest[2]->SetTest(2);
    $listOfTest[4]->SetTest(4);
    $listOfTest[6]->SetTest(6);

    foreach ($listOfTest as $test)
    {
        echo $test->GetTest().'
';
    }
    // 2
    // 4
    // 6

    //$ref = clone $listOfTest[4];
    $ref = $listOfTest[4];
    $newList = getNewList($ref);

    foreach ($listOfTest as $test)
    {
        echo $test->GetTest().'
';
    }
    // 2
    // 5
    // 6
?>

A: The problem is in the way the PHP uses arrays. Array assignment by reference
only works if both the argument and the lvalue are references to arrays. If an object is passed in, it will be copied and a reference to it will be set in both places. The subsequent reassignment of the lvalue will not have any effect on the original array.
Referencing an existing array and then copying it using clone can work around this. The example below shows how this can be done, but you could also use a factory or some other means to create a new array that has references to all of the existing elements (by calling get_object_vars() on each).
<?php
    function getNewList(TestBase $ref) : array
    {
        $newlist = [3 => clone $ref, 5 => clone $ref];
        $newlist[3]->SetTest(3);
        $newlist[5]->SetTest(5);
        return $newlist;
    }

    //$ref = clone $listOfTest[4];
    $ref = &$listOfTest[4];

    var_dump($ref); // TestBase Object (1) (2) { ["m_test"]=> int(5) }

    //$newList = getNewList($ref);

    foreach ($listOfTest as &$test)
    {
        echo "before: ".$test->GetTest().'
'; // 2, 4, 6 in output here!

        var_dump($test); // TestBase Object (1) (2) { ["m_test"]=> int(4) }

        echo "after: ".$test->GetTest().'
';  // 2, 4, 6 in output here!

        var_dump($test); // TestBase Object (1) (2) { ["m_test"]=> int(4) }
    }
?>


text:
Q: BigQuery - How to unnest multiple arrays, and distribute values from one column? I have a table with multiple arrays, and one column that acts like a key:

The question is how to unnest this structure so that each row also gets the rowkey value?
For example:
domain, event, ... referrer should also have the same rowkey?
Tried basically using unnest on the whole table.
SELECT
  *
FROM
  UNNEST(`table.bigtable_analytics.frontend`)
LIMIT
  1000

But getting an issue regarding table names:
Unrecognized name: table.bigtable_analytics.frontend at [4:10]

A: It is not clear what exactly schema of your table, so below example (for BigQuery Standard SQL) just uses simplified schema to introduce the approach to get done what you asked: each row also gets the rowkey value
simplified dummy data is:
Row     rowkey  column.name column.value
1       key1    domain      aaa.com
                event       pageload
                hash        12345
2       key2    domain2     aaa2.com
                event2      pageload2
                hash2       123456789

#standardSQL
WITH `project.dataset.table` AS (
  SELECT 'key1' rowkey, [STRUCT<name STRING, value STRING>('domain', 'aaa.com'), STRUCT('event', 'pageload'), STRUCT('hash', '12345')] column UNION ALL
  SELECT 'key2', [STRUCT<name STRING, value STRING>('domain2', 'aaa2.com'), STRUCT('event2', 'pageload2'), STRUCT('hash2', '123456789')]
)
SELECT rowkey, x.*
FROM `project.dataset.table` t, t.column x

with result as
Row rowkey  name    value
1   key1    domain  aaa.com
2   key1    event   pageload
3   key1    hash    12345
4   key2    domain2 aaa2.com
5   key2    event2  pageload2
6   key2    hash2   123456789


text:
Q: How to unscramble my account? I got an error saying it was logged and suggested I post here.
Somehow, my login is all messed up.
First symptom was I could not login to new beta sustainability.stackexchange.com when I got home, having created account at work.  When I went there, it first would not be log in till I used beta link, then when I did, the Google login did nothing.  (Also facebook and yahoo buttons do nothing on sustainability site.)  So I created a openId account and that worked, but it made a new account at sustainability, so I deleted that account and associated my openId with my existing profile, then tried to login again, but again new account, deleted it again.
Then somehow I got the error that said it was logged and suggested posting on meta.
How can I get google login to work on sustainability?
How can I get openId to not create a new account on sustainability?

A:
When I went there, it first would not be log in till I used beta link

That part is by design. You have to use the link from the invitation email from every new device you want to log in from while the site is in private beta. So long as you use the same login credentials as usual, it should all just work. (I had no trouble using "log in with Stack Exchange" earlier today, though this is obviously anecdotal.)
Your profile on the Sustainability site says you were last seen 38 minutes ago, so I assume you got the login working eventually?
I only see one account with your email or login credentials and as far as I can tell it should all be working properly.
If you're still running into issues, it's probably best to drop us a line via https://sustainability.stackexchange.com/help.


text:
Q: Different Layouts for Horizontal and Vertical for an Android app? The optimum layout for controls might depend on the orientation.   If I have a set of checkboxes or radio buttons they might fit well if I stack them vertically when the user holds the phone in a vertical orientation.  But if the user flips to horizontal it might be better to arrange them into two shorter stacks side-by-side, instead of forcing the user to scroll.
Does Android have any UI guidelines that address whether it's acceptable to use different layouts for vertical and horizontal?     And if so, how would I implement it to use the same controls, i.e., the same ID's for both layouts?
Thanks in advance!

A: It is completely acceptable to use different layouts for horizontal and vertical.  This is why Android provides the layout and layout-land folders for defining these.
If it makes sense to you and will be easier for the user to navigate, then do it.
To implement this, you create an xml file with the same name in both the layout and layout-land folders.  You then specify the same android:id for each asset.  For instance a textview would contain the same id in both xml files:
<TextView android:text="@string/SomeText"
        android:id="@+id/TextView01"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
</TextView>

It's that simple.


text:
Q: Data objects not found in embedded vegan:cca. Scoping issue? I try to embed cca (and also capscale) from package vegan (version 2.5-7, R 4.1.2) in another function to test an analysis pipeline with some data transformation and then varying model formulas. The used data matrices (e.g. bio and env) can have different names and are normally not visible in the global work space. The error that I get is:
Error in eval(match.call()$data, environment(formula), enclos = .GlobalEnv) :
object 'env' not found

that looks like a scoping issue. Looking around, it seems that vegan had some problems with scoping in the past that are said to be fixed, so I wonder if I overlooked something. Any workaround is also welcome, e.g. environment manipulation.
library("vegan")

## create some example data
set.seed(123)
bio <- matrix(sample(0:10, 50, replace = TRUE), nrow = 10)
env <- data.frame(
  x = sample(1:10, 10),
  y = 1:10 + rnorm(10),
  z = rnorm(10)
)
cca(bio ~ x + y, data = env) # works

## enclose cca with some other stuff in a function
foo <- function(model, bio, env) {
  ## do preparatory data transformation
  fm <- cca(model, data = env)
  print(fm)
  ## do something else
}

model <- formula(bio ~ x + y) # works
foo(model, bio=bio, env=env)

## now rename data to test scoping
bio2 <- bio
env2 <- env
rm(bio, env)

foo(model, bio = bio2, env = env2) # error
# Error in eval(match.call()$data, environment(formula), enclos = .GlobalEnv) :
# object 'env' not found

A: Yes, looks to be a scoping issue. I think the key is to update the formula's environment inside the function:
foo <- function(model, bio, env) {
  # update model environment
  environment(model) = environment()
  ## do preparatory data transformation
  fm <- cca(model, data = env)
  print(fm)
  ## do something else
}


text:
Q: Plataformas que executam Tomcat Alguém sabe me informar quais plataformas (Windows, Linux, Mac, etc.) rodam o Tomcat 9.0?
Se possível, indiquem uma referência para tal informação.
Grato.

A: Boa noite amigo,as três plataformas suportam o tomcat em todas as versões.
Preparando o Tomcat em casa
Baixe o Tomcat 7 em http://tomcat.apache.org/ na página de downloads da versão que escolher, você precisa de uma "Binary Distribution". Mesmo no windows, dê preferência a versão .zip, para você entender melhor o processo de inicialização do servidor. A versão executável é apenas um wrapper para executar a JVM, já que o Tomcat é 100% Java.
O Tomcat foi por muito tempo considerado implementação padrão e referência das novas versões da API de servlets. Ele também é o servlet container padrão utilizado pelo JBoss. Ele continua em primeira posição no mercado, mas hoje tem esse lugar disputado pelo Jetty e pelo Grizzly (esse último é o servlet container que faz parte do servidor de aplicação da Oracle/Sun, o Glassfish).
Entre no diretório de instalação e execute o script startup.sh:
cd apache-tomcat/bin
./startup.sh
Entre no diretório de instalação do tomcat e rode o programa shutdown.sh:
cd apache-tomcat/bin
./shutdown.sh
Aprenderemos futuramente como iniciar o container de dentro do próprio Eclipse, por comodidade e para facilitar o uso do debug.
Tomcat no Windows
Para instalar o Tomcat no Windows basta executar o arquivo .exe que pode ser baixado no site do Tomcat (como falamos, dê preferência ao zip). Depois disso, você pode usar os scripts startup.bat e shutdown.bat, analogamente aos scripts do Linux.
Tô tomate vai funcionar em qualquer ambiente compatível com o Java Enterprise Edition, seja o Linux, Windows ou Mac OS.
Referência: https://www.caelum.com.br/apostila-java-web/o-que-e-java-ee/#3-6-preparando-o-tomcat-em-casa
   CAP 3.6
Se tiver o Java instalado na máquina a ele vai rodar,
Link pára download do tomcat.


text:
Q: On macOS Monterey 12.5, how can I allow Conda to collect package metadata from ? I am on a MacBook M1 Pro, macOS Monterey 12.5, using conda 4.13.0 in zsh(z-shell) to attempt package installations.
(My goal is to install tensorflow-deps from the apple channel of Anaconda, so I can use GPU-accelerated TensorFlow on my M1 Pro. As far as I understand, Conda is the only way to install apple's tensorflow-deps package.)
Problem
Whenever I try to install packages with Anaconda (conda) in the terminal, I get:
Collecting package metadata (current_repodata.json): failed
CondaHTTPError: HTTP 000 CONNECTION FAILED for url <https://repo.anaconda.com/pkgs/main/osx-64/current_repodata.json>

Note that I managed to successfully access this resource with this command:
curl https://repo.anaconda.com/pkgs/main/osx-64/current_repodata.json

So it seems like it's just the Conda tool that is failing.
The issue has been marked as stale in GitHub, and has not been solved.
Similar issues have been addressed before and solved, but since those solutions are not working, I am assuming that my issue is somehow different, and thus I am creating a new question to nuance the discussion.
Attempted solutions
I have tried everything from the discussion of the GitHub issue, and more.
I have to download and convert my root certificate, and then:
export REQUESTS_CA_BUNDLE=/path/to/root/certificate.pem

as outlined here, but that does not fix the issue.
I have tried replacing
~/opt/anaconda3/lib/python3.9/site-packages/certifi/cacert.pem

with the same generated cert, which did not work.
Doing conda update -n base -c defaults conda as suggested in the GitHub issue shows the same CondaHTTPError: HTTP 000 CONNECTION FAILED for url <https://repo.anaconda.com/pkgs/main/osx-arm64/repodata.json> error.
Some users report that using the -k/--insecure flag or configuring Conda to not verify ssl fixes this issue. This is not really a solution in the first place, and also it does not work for me.
Some Windows users report that copying come DLLs around fixes the issue, but I don't know what the equivalent of this would be on Mac, if there is one.


text:
Q: How do I get the JSONArray that's already in a JSONArray I can't seem too get the second layer in the JSON Array.
What I want is, to get all the names from the Categories, and then I want to sent the "forums id" trough a intent to an different Activity.
If it helps, I followed this tutorial and I'm getting my JSON array from here
Part of JSON Array
{
"categories": [{
    "name": "Facepunch",
    "forums": [{
        "id": 6,
        "name": "General Discussion",
        "viewing": 217
    }, {
        "id": 60,
        "name": "Fast Threads",
        "viewing": 188
    }, {
        "id": 64,
        "name": "Videos And Flash Movies and That Kind Of Crap",
        "viewing": 239
    }, {
        "id": 403,
        "name": "Mass Debate",
        "viewing": 9
    }, {
        "id": 396,
        "name": "Sensationalist Headlines",
        "viewing": 455
    }, {
        "id": 51,
        "name": "In The News Node",
        "viewing": 100
    }]
  }]
}

Part of my code
try {
    // Getting Array of Contacts
categories = json.getJSONArray(TAG_CATEGORIES);
forums = json.getJSONArray(TAG_FORUMS);

// looping through All categories
for(int i = 0; i < categories.length(); i++){
    JSONObject c = categories.getJSONObject(i);

    // Storing each json item in variable
    String CatName = c.getString(TAG_CATName);

    // Phone number is agin JSON Object
            JSONObject All_forums = forums.getJSONObject(i);
            String forum_id = All_forums.getString(TAG_FORUMS_ID);
            String forum_name = All_forums.getString(TAG_FORUMS_NAME);

        // creating new HashMap
        HashMap<String, String> map = new HashMap<String, String>();

        // adding each child node to HashMap key => value
    map.put(TAG_CATName, CatName);
    map.put(TAG_FORUMS, forum_name);

    // adding HashList to ArrayList
    contactList.add(map);
}
} catch (JSONException e) {
    e.printStackTrace();
}

A: To get the array of forums of one category you have to call
forums = c.getJSONArray(TAG_FORUMS);

inside your for-loop. Afterwards you can iterate over the forums to get their ids and names.
Code sample:
categories = json.getJSONArray(TAG_CATEGORIES);
for(int i = 0; i < categories.length(); i++) {
    JSONObject c = categories.getJSONObject(i);
    forums = c.getJSONArray(TAG_FORUMS);
    for(int j = 0; j < forums.length(); j++){
        JSONObject f = forums.getJSONObject(j);
        String forum_id = f.getString(TAG_FORUMS_ID);
        String forum_name = f.getString(TAG_FORUMS_NAME);
        …
    }
}

A: You have to get the second layer from the category JSONObject.
try {
// Getting Array of Contacts
categories = json.getJSONArray(TAG_CATEGORIES);

// looping through All categories
for(int i = 0; i < categories.length(); i++){
    JSONObject c = categories.getJSONObject(i);

    forums = c.getJSONArray(TAG_FORUMS);

    ...
}

A: You should use Gson parser. It very simply and basic usage than Android standart JSON parser. You parsing very basically.
Create class for json object items already in it to object or primitive types.

A: Try this:

    // Getting Array of Contacts

    categories = json.getJSONArray(TAG_CATEGORIES);

    forums = categories.getJSONArray(TAG_FORUMS);

    // looping through All categories

    for(int i = 0; i < forums.length(); i++){

        JSONObject c = forums.getJSONObject(i);

    // your code ....

}

A: Simple usage
public String getClasstoJson(Object o) throws Exception
{
    Gson gson = new Gson();
    gson.toJson(o);
    return gson.toString();
}

public Object getJsontoClass(Object o,String json) throws Exception
{

    Gson gson = new Gson();

    try {
        Object st = o.getClass().newInstance();
        st= gson.fromJson(json.toString(), st.getClass());
        return  st;

    }catch (IllegalAccessException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InstantiationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return null;
}


text:
Q: cascade persist results in null column value for a ManyToMany entity Owner:
@Entity
public class Strategy implements Serializable {

    @Id
    @GeneratedValue
    private Long id;

    @ManyToMany(fetch = FetchType.EAGER, cascade = {CascadeType.PERSIST})
    @JoinTable(name = "StrategyHost", joinColumns = {@JoinColumn(name = "strategyId")}, inverseJoinColumns = {@JoinColumn(name = "hostId")})
    private Set<Host> hostName;

}

Related entity:
@Entity
public class Host {
    @Id
    @GeneratedValue
    private Long id;

    @Column(unique = true)
    private String name;

    @ManyToMany(mappedBy = "hostName")
    private List<Strategy> strategies;

    public Host(String name) {
        this.name = name;
    }
}

Test:
@Test
@Transactional(propagation = Propagation.NOT_SUPPORTED)
public void testStrategyWithHosts() {
    Strategy s = new Strategy();

    Set<Host> hosts= new HashSet<>();
    hosts.add(Host.builder().name("aaa").build());
    hosts.add(Host.builder().name("bbb").build());
    s.setHostName(hosts);
    Strategy saved= strategyDao.save(s);
    Set<Host> hostName = saved.getHostName();
}

debug shows the persisted saved object having Host:

Where are name values? However, if I add merge in cascade type array, name are valued. Why insert (not update managed entities) operation for related entities must have merge cascade type? Although log shows nothing suspicious:

insert into strategy...
  insert into host...
  insert into host...
  update strategy ...
  insert into strategy_host ...
  insert into strategy_host ...


text:
Q: Error in second derivative using Lagrange quadratic interpolation Quadratic lagrange interpolation is given by $P(x)=\sum _{k=0}^2 l_k(x) f_k$ with error term $E(x)=\frac{(x-x_0)(x-x_1)(x-x_2) f^{'''}(\xi )}{3!}$.
To calculate, error for second derivative at point any point, first I calculated
$$E'(x)=f^{'''}(\xi)\frac{(x-x_0)(x-x_1)+(x-x_0)(x-x_2)+(x-x_2)(x-x_1)}{3!}+\frac{(x-x_0)(x-x_1)(x-x_2)}{3!}\frac{d}{dx}f^{'''}(\xi),$$ where $x_0<\xi<x_2$  then
$$E''(x)=f^{'''}(\xi)\frac{(2x-x_0-x_1)+(2x-x_0-x_2)+(2x-x_2-x_1)}{3!}+ \frac{(x-x_0)(x-x_1)+(x-x_0)(x-x_2)+(x-x_2)(x-x_1)}{3!}\frac{d}{dx}f^{'''}(\xi)+\frac{(x-x_0)(x-x_1)+(x-x_0)(x-x_2)+(x-x_2)(x-x_1)}{3!}\frac{d}{dx}f^{'''}(\xi)+  \frac{(x-x_0)(x-x_1)(x-x_2)}{3!}\frac{d^2}{dx^2}f^{'''}(\xi)$$
Therefore at $x=x_0$, $E^{''}(x_0)=  f^{'''}(\xi)\frac{(2x_0-x_1-x_2)}{3}+\frac{(x_0-x_1)(x_0-x_2)}{6}\frac{d}{dx}f^{'''}(\xi)+\frac{(x_0-x_1)(x_0-x_2)}{6}\frac{d}{dx}f^{'''}(\xi)$.
I need to show that this value is equal to
$E^{''}(x_0)=  f^{'''}(\xi)\frac{(2x_0-x_1-x_2)}{3}+\frac{(x_0-x_1)(x_0-x_2)}{24}[f^{iv}(\eta_1)+f^{iv}(\eta_2)]$.
Any help is appreciated.


text:
Q: In ASP.NET MVC and Entity Framework, how do I lock an account for 15 minutes default? How do I unlock it? How do I lock an account for 15 minutes default? How do I unlock it?
Using only ASP.NET MVC and Entity Framework


text:
Q: Webviews don't always store cookies? How to force this? I have an app that runs a Webview Activity, and my server's web framework handles user authentication (logins) by storing a session token in a cookie. I have my app running on 4 devices: An Android 2.2.1 (A), Android 2.3.6 (B), an Android 2.3.7 (C), and an Android 4.0.3 (D). For Androids (A), (B), and (D), the Webview stays logged in even after previous Activity Destorys, indicating that cookies are saved for the WebView automatically. However, for Android (C), cookies don't appear to be stored for the WebView, because I am asked to log in again after a previous Activity Destroy. If this happens in one of my devices, it can surely happen in other devices as well. I want to learn how I can force WebViews to always save cookies.
TL;DR How do I force WebViews to always store cookies? OR how do I handle WebView cookie storage/retrieval myself?


text:
Q: Como tirar o 0. do 'round' PHP Como faço para tirar esse 0. da conta abaixo..
$idMark = 6;
$rating[5] = 4;

$bar5estrelas = ($ratings[5] == 0) ? 0 : round(($ratings[5]/$idMark), 2);

Resultado: 0.67

Como o retiro o 0. deixando apenas 67 ?

A: Não sei se afirmar qual a melhor maneira de fazer pois eu não sei qual será o objetivo, já que o seu código me parece algo com porcentagem mas não consigo ter certeza do que realmente você quer fazer
Entretanto você pode tentar:
round(($ratings[5]/$idMark), 2) * 100;

Ou você pode tentar converter pra string e tirar o 0. com str_replace (acredito que o php já converta para string quando usamos funções com str_ por exemplo):
str_replace('0.', '', round(($ratings[5]/$idMark), 2));

Mas é como eu disse, não sei se é o melhor caminho, pois não sei qual o objetivo do código.
Se estiver trabalhando com porcentagem (o que não dá pra ter certeza devido a variável $ratings[5]) você poderia simplesmente fazer assim:
round(($ratings[5] / $idMark) * 100);


text:
Q: Remove overflow-x and overflow-y using jQuery I want to remove overflow-x and overflow-y using jQuery. I have tried several methods, but they don't seem to work:
Here is my code:
body #s4-workspace {
  left: 0;
  overflow-x: auto;
  overflow-y: scroll;
  position: relative;
}

other tags

Here are the methods I've tried:
1)
$('body #s4-workspace').css('overflow-x','');
$('body #s4-workspace').css('overflow-y','');

2)
$('body #s4-workspace').removeProp('overflow-x');
$('body #s4-workspace').removeProp('overflow-y');

If I output the overflow properties after either method, I see no change in their values.
See my demonstration below:

$(document).ready(function() {
  try {
    $('body #s4-workspace').css('overflow-x', '');
    $('body #s4-workspace').css('overflow-y', '');

    $('body #s4-workspace').removeProp('overflow-x');
    $('body #s4-workspace').removeProp('overflow-y');

    alert($('body #s4-workspace').css('overflow-x'));
  } catch (e) {
    alert(e);
  }
});
 body #s4-workspace {
   left: 0;
   overflow-x: auto;
   overflow-y: scroll;
   position: relative;
 }

other tags

View on JSFiddle
How can I remove overflow with jQuery?

A: You just need to set them to their default values - visible:
$('body #s4-workspace').css('overflow-x','visible');
$('body #s4-workspace').css('overflow-y','visible');

A: Explanation
According to jQuery's css() documentation:

Setting the value of a style property to an empty string ... does not ... remove a style that has been applied with a CSS rule in a stylesheet or  element.

I've demonstrated that issue below -- notice that there is no change in the overflow value:

$(function() {

  var $workspace = $('#s4-workspace'),
    $output = $('#outout');

  $('div#output').html("Old overflow value: " + $workspace.css('overflow-x') + "");

  $workspace.css('overflow-x', '');
  $('div#output').html($('div#output').html() + "Old overflow value: " + $workspace.css('overflow-x') + "");

});
#s4-workspace {
  overflow-x: auto;
}
#output span {
  display: block;
}

other tags

However, an empty string will reset overflow to its default value if it's been set by jQuery:

$(function() {

  var $workspace = $('#s4-workspace'),
    $output = $('#outout');

  $workspace.css('overflow-x', 'auto');
  $('div#output').html("Old overflow value: " + $workspace.css('overflow-x') + "");

  $workspace.css('overflow-x', '');
  $('div#output').html($('div#output').html() + "Old overflow value: " + $workspace.css('overflow-x') + "");

});
#output span {
  display: block;
}

other tags

Solution
The solution of setting the overflow value explicitly has been offered by ahoffner.
Another idea is to apply overflow via a CSS class. Then you can remove it with jQuery's removeClass() rather than manipulating the style directly:

$(function () {

    var $workspace = $('#s4-workspace'),
        $output = $('#output');

    $output.html("Old overflow value: " + $workspace.css('overflow-x') + "");
    $workspace.removeClass('horizontal_scroll');
    $output.html($output.html() + "New overflow value: " + $workspace.css('overflow-x') + "");

});
#s4-workspace {
     left: 0;
     position: relative;
 }
 .horizontal_scroll {
     overflow-x:auto;
 }
 #output span {
     display:block;
 }

other tags

Incidentally:

Warning: one notable exception is that, for IE 8 and below, removing a shorthand property such as border or background will remove that style entirely from the element, regardless of what is set in a stylesheet or  element.


text:
Q: Makefile with macro, does not generate any executable I wrote a Makefile(code below) for my program which contains hello.h, hello.cpp and main.cpp (this is a trivial testbench for hello.cpp).
However, after I type make in the terminal, it tells me

make: `hello.o' is up to date.

Can someone give any hints? Thank you!
#MACRO
CAT_HOME = $(MGC_HOME)
TARGET = my_tb
#OBJECT1 = hello.o
OBJECTS = hello.o main.o
#OBJECT2 = main.o
DEPENDS = hello.cpp main.cpp hello.h
INCLUDES = -I"$(CAT_HOME)/shared/include"
DEFINES =
CXX = /usr/bin/g++
CXXFLAGS = -g -O3 $(DEFINES) $(INCLUDES)

$(TARGETS) : $(OBJECTS)
    $(CXX) $(CXXFLAGS) -o $(TARGET) $(OBJECTS)

$(OBJECTS) : $(DEPENDS)

#phony target to remove all objects and executables
.PHONY: clean
clean:
    rm -f *.o

A: You define a TARGET variable but later try to use $(TARGETS). Theres an S in difference.
Also, it is inefficient to let every .o file depend on every .cpp file. You might as well just write a linear script that recompiles everything unconditionally. Since you're depending on make's built-in rule for creating a .o from the corresponding .cpp, you don't need to declare that dependency explicitly. So you can remove all of the .cpp files from DEPENDS without losing any relevant dependencies.


text:
Q: Extending UIImageView with categories throws error on self.dispatchQueue I try to extend the UIImageView with a new 'loadImageNamed:' method. Within this method i use a dispatchQueue but XCode throws an error, that the property 'dispatchQueue' is not found on Object of type 'UIImageView'.
Can somebody give me a hint?! Thanks!
#import "UIImageView+LazyPicLoad.h"

@implementation UIImageView (LazyPicLoad)

-(void)loadImageNamed:(NSString *)name {
dispatch_async(self.dispatchQueue, ^{
    NSData *imageData;
    if (name) {
        if ([UIScreen mainScreen].scale == 2.0)
            imageData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:[name stringByAppendingString:@"@2x"] ofType:@"png"]];
        else
            imageData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:name ofType:@"png"]];
    }

    CGImageRef decompressedImage = NULL;
    if (imageData) {
        CGDataProviderRef imageDataProvider = CGDataProviderCreateWithCFData((__bridge CFDataRef)imageData);
        CGImageRef image = CGImageCreateWithPNGDataProvider(imageDataProvider, NULL, NO, kCGRenderingIntentDefault);
        CGContextRef bitmapContext = CGBitmapContextCreate(NULL, CGImageGetWidth(image), CGImageGetHeight(image), CGImageGetBitsPerComponent(image), CGImageGetWidth(image) * 4, CGColorSpaceCreateDeviceRGB(), kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little);
        CGContextDrawImage(bitmapContext, CGRectMake(0, 0, CGImageGetWidth(image), CGImageGetHeight(image)), image);
        decompressedImage = CGBitmapContextCreateImage(bitmapContext);

        CGDataProviderRelease(imageDataProvider);
        CGImageRelease(image);
        CGContextRelease(bitmapContext);
    }

    dispatch_sync(dispatch_get_main_queue(), ^{
        if (decompressedImage)
            self.image = [UIImage imageWithCGImage:decompressedImage];
    });

    if (decompressedImage)
        CGImageRelease(decompressedImage);
});
}

@end

A: That's precisely the problem, there isn't a dispatchQueue property on UIImageView. If you want to send that block to background, you should be using this instead:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    // background code
});


text:
Q: How to disable NSButton focus outline When my application launches, it has one button. This button has ended up with a very ugly blue outline. How can I disable this? (Code or Interface Builder solution welcome.)

A: In interface builder click on the button and then in the right hand panel go to the Attributes inspector. At the bottom of the attributes panel there is a section called "View".
The first item in that section is "Focus Ring".
Change this value to 'None'.

A: It's 2016 and this is how you do it programmatically in Swift 2.2:
view.focusRingType = .none


text:
Q: Camel Routes - How to return the body response as xml First of all, I am new with Spring Boot.
I am not sure if it is possible, but I would like to return the xml response from the external url.
I have this code:
@GetMapping("/myPage")
public void myPage() {
    restConfiguration().host("localhost").port(8080);
    from("timer://runOnce?repeatCount=1&delay=0")
            .to("rest:get:/external-page")
            .to("stream:out");
}

myPage() is returning a XML (that's OK). So, now I would like to return the same XML when I do:
curl http://localhost/myPage

I am not sure if I have to use .to("stream:out"), but the curl is returning an empty result.
Can someone help me?
Thanks in advance.

A: I found the solution, this is how to get the response.
CamelContext context = new DefaultCamelContext();
    context.addRoutes(new RouteBuilder() {
        public void configure() {
            restConfiguration().host(sHost).port(iPort);
            from("direct:start")
                    .setHeader(Exchange.HTTP_METHOD,simple("GET"))
                    .to("rest:get:/external-page");
        }
    });

    context.start();

    ProducerTemplate template = context.createProducerTemplate();
    String headerValue = "application/xml";

    Map<String, Object> headers = new HashMap<String,Object>();
    headers.put("Content-Type", headerValue);

    Object result = template.requestBodyAndHeaders("direct:start", null, headers, String.class);
    Exchange exchange = new DefaultExchange(context);
    String response = ExchangeHelper.convertToType(exchange, String.class, result);
    context.stop();

    return response;