text:
Q: Why do molecules absorb "exact" frequencies when given a "continuous" beam of light? This question is in the context of performing simple rotational spectroscopy on molecules, but could be extended for more general cases.
In rotational (microwave or IR) spectroscopy of molecules, the energy levels are discrete and given by
$$E_J=BJ(J+1)$$
where $B$ is the rotational constant, and $J$ is the angular momentum quantum number for the molecule.
Given the selection rule is $\Delta J=\pm 1$, one can show that we get allowed transitions between levels, with energy spacings at
$$\Delta E=2B,\; 4B,\; 6B,\; ...$$
and so on, which correspond to peaks in the spectrum.
My confusion is that due to the discrete nature of this formalism, the molecule needs to absorb a photon of energy exactly $2nB$, where $n$ is a positive integer.  However if we feed in a continuous spectrum of light, mathematically speaking one gets rather worried when we are required to select a discrete value!  Yet we see peaks, so light is definitely being absorbed!
My thoughts so far on explanations include the fact that the peaks aren't infinitely thin - i.e. they have some thickness to them.  Is this from inherent quantum mechanical uncertainty in energy of the photons that need to be absorbed (maybe from the Heisenberg relation for $\Delta E$ and $\Delta t$)?  Are there Doppler broadening effects occurring?  I don't quite understand why these "errors" or "uncertainties" would be present if the molecule has the above "exact" spacings however.

A:
My thoughts so far on explanations include the fact that the peaks aren't infinitely thin - i.e. they have some thickness to them.  Is this from inherent quantum mechanical uncertainty in energy of the photons that need to be absorbed (maybe from the Heisenberg relation for $\Delta E$ and $\Delta t$)?

Yes.

Are there Doppler broadening effects occurring?

Potentially, also yes.

Spectral lines are never exact delta-function spikes of zero width $-$ they always have a nonzero spectral bandwidth.
The sources of this bandwidth are generally divided into two different classes:

*

*Inhomogeneous broadening occurs when you have an ensemble of molecules absorbing at different frequencies, such as the Doppler effects you mentioned (so, there will be a thermal distribution of velocities, and each will produce a different Doppler shift), as well as e.g. different Zeeman shifts from inhomogeneities in the magnetic field, and so on.

*On the other hand, even if all the molecules are in identical conditions, there are also homogeneous-broadening effects. The main culprit here is, as you point out, the $\Delta E$-$\Delta t$ uncertainty relationship, where $\Delta t$ is given by the radiative decay lifetime of the excited state: frequencies any closer together than $1/\Delta t$ require times at least as long as $\Delta t$ to distinguish, and in that time any initial absorption has time to decay by re-emission and start absorbing again.

A: Indeed the absorption line is not infinitely thin. If it were, the absorption would take infinitely long!
There are several sources of line broadening. Lines are broadened by the effect of lifetime. The transition takes a finite time and therefore a finite number of wavelengths. This results in broadening. Also the molecule feels effects from its environment. In a gas it will collide, which this will affect the resonance and the lifetime, and doppler broadening due to thermal or other motion. If the molecule is in a solid it may experience variation in its environment. In a liquid it may experience motional narrowing.
See https://en.wikipedia.org/wiki/Spectral_line_shape


text:
Q: Seeking bitmap font id for installation in Ubuntu 20.04 I had been using a specific bitmap font (see image in following link) since Ubuntu 10.04, enabled via this technique, which worked until 18.04. The font would show up in gnome-terminal settings as "Fixed".
My desired bitmap font
I have now upgraded to 20.04, and the font is no longer available. I have verified that the technique in this answer works to restore bitmap fonts on 20.04; however, I am seeking identification of the specific font I had been using so far. What bdf file corresponds to it?

A: Found it; turns out it is 9x15.bdf. I just downloaded them all and checked them one by one. Documenting steps here in case anyone else has an OCD itch to scratch:

*

*wget with wildcards, from here
$ wget -r -nd -np -A '*.bdf' https://opensource.apple.com/source/X11fonts/X11fonts-14/font-misc-misc/font-misc-misc-1.1.2

*Script to check each bdf (wait for keypress from here):
$ for font in *.bdf; do echo $font; gnome-font-viewer $font & read -n1 -s -r -p $'Press key to continue...\n' key; done
Find the font you want; then install via the technique in the previously-linked answer.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Undefined Reference but Library Linked I'm currently trying to add the RaspiCam library found here:
https://sourceforge.net/projects/raspicam/?source=typ_redirect
To the Apriltags library found here:
http://people.csail.mit.edu/kaess/apriltags/
I unzipped the RaspiCam library and built it separately, then just copied and pasted it into the AprilTags folder. My AprilTags folder looks like this now:
AprilTags build cmake CMakeLists.txt example LICENSE Makefile pod-build raspicam-0.1.6 README.txt src systems.txt tags

Inside the raspicam-0.1.6 folder is this:
build Changelog CMakeLists.txt CMakeLists.txt.user cmake_uninstall.cmake.in dependencies README src utils

I add the library from raspicam to the top of my code in AprilTags as:
#include <raspicam/raspicam_cv.h>

and it detects it when I build. I know this because I purposefully wrote the library wrong, ex. raspicam_cvv.h, and it gave me an error because there is no library like that. So it definitely links. However, when I try to use the library in code with for example:
raspicam::RaspiCam_Cv Camera;

It gives this error:
CMakeFiles/apriltags_demo.dir/apriltags_demo.cpp.o: In function `main':
apriltags_demo.cpp:(.text.startup+0x2d4): undefined reference to `raspicam::RaspiCam_Cv::RaspiCam_Cv()'
apriltags_demo.cpp:(.text.startup+0x324): undefined reference to `raspicam::RaspiCam_Cv::~RaspiCam_Cv()'
apriltags_demo.cpp:(.text.startup+0x384): undefined reference to `raspicam::RaspiCam_Cv::~RaspiCam_Cv()'
collect2: error: ld returned 1 exit status
example/CMakeFiles/apriltags_demo.dir/build.make:139: recipe for target 'bin/apriltags_demo' failed
make[3]: *** [bin/apriltags_demo] Error 1
CMakeFiles/Makefile2:193: recipe for target 'example/CMakeFiles/apriltags_demo.dir/all' failed
make[2]: *** [example/CMakeFiles/apriltags_demo.dir/all] Error 2
Makefile:127: recipe for target 'all' failed
make[1]: *** [all] Error 2
Makefile:27: recipe for target 'all' failed
make: *** [all] Error 2

as an undefined reference. I did some research online and found a similar query here: library is linked but reference is undefined where the solution is to change the order in which you link. However, because both projects are built using CMake, I don't know how you would change the order of linking.

A: NOTE - I would make this a comment if I could, need more rep:

*

*Have you tried "" over <> for your include? <> is for predefined directories while "" follows a relative path

*This may seem like an excess check, but did you make sure you have both the .lib and corresponding .h file for the library in the same directory? Lot of people have the .lib but are missing the .h for the lib
I come across this problem when I forget to do either of these two, whether in cmake or in visual c++ through vstudio


text:
Q: MahApps.Metro: WindowCommands ItemsSource binding I am trying to bind a collection of items to the windowcommands of metrowindow. Below is the xaml snippet.
<metro:MetroWindow.WindowCommands>
        <metro:WindowCommands ItemsSource="{Binding WindowCommands}">
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <Button Content="{Binding DisplayName}"
                            Command="{Binding Callback}"/>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </metro:WindowCommands>
    </metro:MetroWindow.WindowCommands>

But it does not display the DisplayName property, but the type name of the bounded datatype. How can I achive the intended behaviour?

A: Works if you add the template as a resource to the MetroWindow. For this to work you will need to create a WindowCommandViewModel that has Label and Callback properties.
<metro:MetroWindow.Resources>
    <DataTemplate DataType="{x:Type viewModels:WindowCommandViewModel}">
        <Button Content="{Binding DisplayName}"
                Command="{Binding Callback}"/>
    </DataTemplate>
</metro:MetroWindow.Resources>


text:
Q: Why am I receiving a "no ordering relation defined for complex numbers" error? See this question for some background. My main problem on that question was solved, and it was suggested that I ask another one for a second problem I'm having:
print cubic(1, 2, 3, 4)  # Correct solution: about -1.65
...
    if x > 0:
TypeError: no ordering relation is defined for complex numbers
print cubic(1, -3, -3, -1)  # Correct solution: about 3.8473
    if x > 0:
TypeError: no ordering relation is defined for complex numbers

Cubic equations with one real root and two complex roots are receiving an error, even though I am using the cmath module and have defined the cube root function to handle complex numbers. Why is this?

A: It is not clear from your example code what x is, but it seems it must be a complex number.  Sometimes, when using complex numerical methods, an approximate solution will come up as a complex number even though the exact solution is supposed to be real.
Complex numbers have no natural ordering, so an inequality x > 0 makes no sense if x is complex.  That's what the type error is about.

A: Python's error messages are pretty good, as these things go: unlike some languages I could mention, they don't feel like random collections of letters.  So when Python complains of the comparison
if x > 0:

that
TypeError: no ordering relation is defined for complex numbers

you should take it at its word: you're trying to compare a complex number x to see whether or not it's greater than zero, and Python doesn't know how to order complex numbers.  Is 2j > 0?  Is -2j > 0?  Etc.  In the face of ambiguity, refuse the temptation to guess.
Now, in your particular case, you've already branched on whether or not x.imag != 0, so you know that x.imag == 0 when you're testing x and you can simply take the real part, IIUC:
>>> x = 3+0j
>>> type(x)
<type 'complex'>
>>> x > 0
Traceback (most recent call last):
  File "<ipython-input-9-36cf1355a74b>", line 1, in <module>
    x > 0
TypeError: no ordering relation is defined for complex numbers

>>> x.real > 0
True


text:
Q: Visual Basic, Check if a sheet exists in another workbook I'm really new to Visual Basic and I don't know any python either, I'm trying to write code that is able to check if a worksheet exists in a workbook...
Sub sheetexist()
    If Len(Dir(("C:\My Data\Performance Spreadsheets\[ABCD - Performance.xls]Jun 14"))) Then
        MsgBox "Sheet exist"
    Else
        MsgBox "Sheet does not exist"
    End If
End Sub

ABCD does have the sheet for Jun 14 however the code only returns "Sheet does not exist", is there another way to check for worksheets in other workbooks?

A: I think you're mis-using the Dir function.
The easiest way to check if a sheet exists is with error-handling.
Function SheetExists(wbPath as String, shName as String)
    Dim wb as Workbook
    Dim val

    'Assumes the workbook is NOT open
    Set wb = Workbooks.Open(wbPath)
    On Error Resume Next
    val = wb.Worksheets(shName).Range("A1").Value
    SheetExists = (Err = 0)

    'Close the workbook
    wb.Close

End Function

Call the function like this from a worksheet cell:
=SheetExists("C:\My Data\Performance Spreadsheets\ABCD - Performance.xls", "Jun 14")

Or from VBA like:
Debug.Print SheetExists("C:\My Data\Performance Spreadsheets\ABCD - Performance.xls", "Jun 14")

Without opening the workbook, you could use the code here.
This will raise an error if any part of the formula can't evaluate (e.g., if you pass the name of a non-existent sheet, a bad file path, etc., Error 2023:
Private Function GetInfoFromClosedFile(ByVal wbPath As String, _
    wbName As String, wsName As String, cellRef As String) As Variant
Dim arg As String
    GetInfoFromClosedFile = ""
    If Right(wbPath, 1) <> "\" Then wbPath = wbPath & "\"
    If Dir(wbPath & "\" & wbName) = "" Then Exit Function
    arg = "'" & wbPath & "[" & wbName & "]" & _
        wsName & "'!" & Range(cellRef).Address(True, True, xlR1C1)
    On Error Resume Next
    GetInfoFromClosedFile = ExecuteExcel4Macro(arg)
End Function

Call it:
Sub Test()
Dim path As String
Dim filename As String
Dim sheetName As String
Dim cellAddress As String

path = "c:\users\you\desktop"

filename = "file.xlsx"

sheetName = "Jun 14"

cellAddress = "A1"

Dim v As Variant  'MUST BE VARIANT SO IT CAN CONTAIN AN ERROR VALUE

v = GetInfoFromClosedFile(path, filename, sheetName, cellAddress)
If IsError(v) Then MsgBox "Sheet or filename doesn't exist!"

End Sub


text:
Q: Get HTML element text without children How would I receive only the direct text, not including children and children's text?
For example in this case I would like to receive "Lorem":

  Lorem

    Ipsum

A: Once you get a reference to the div, from your jQuery I'm assuming it has the class title

var div = document.getElementsByClassName('title')[0]; //get the reference to the parent div
var name = div.firstChild.nodeValue;

alert(name)

  hi

    asd

If you want to complicate it

var div = document.getElementsByClassName('title')[0]; //get the reference to the parent div
var array = [].map.call(div.childNodes, function(child) {
  return child.nodeType == 3 && child.nodeValue.trim() ? child.nodeValue.trim() : undefined;
})
var name = array.join();

alert(name)

  hi

    asd

  this also

A: You can write this way:
alert($(".title").clone().children().remove().end().text())

Snippet:

$(function(){
  alert($(".title").clone().children().remove().end().text());
});

  hi

    asd

or write your own function as shown in this SO post in the jquery and can reuse it wherever needed.
jQuery.fn.justtext = function() {

    return $(this).clone()
            .children()
            .remove()
            .end()
            .text();

};

alert($('#mydiv').justtext());

A: Below code works...
$('div').filter(function(){
    console.log( $.trim($(this).clone().context.firstChild.data) );
});

A: If you want to get hi only try this :
var element = $("div:first").text();


text:
Q: Update selectbox options and save to database I've to select boxes:
<select name="select1" id="select1" multiple="multiple">
<option value="8">Civics</option>
<option value="9">English</option>
<option value="10">Economics</option>
</select>

<select id="select2" size="4" multiple="multiple" name="select2[]">
<option value="1">Maths</option>
<option value="2">Physics</option>
<option value="3">Chemistry</option>
<option value="4">Biology</option>
<option value="5">History</option>
<option value="7">Social Studies</option>
<option value="11">Geography</option>
</select>

The data for both the boxes is fetched from the db on page load.
The idea is to either add/delete options from the select2 and save it to a table in the db. I delete the existing data in the table before updating it.
The issue I'm facing is while saving the data, only the new options which are added to the select2 are getting saved and if I remove any options, I'm getting an index out of bounds error. How do I make sure that the values which are already there in the select2 on page load are read as well?
The php code is as follows:
<?php
if(isset($_POST['save']))
{
    $qry = 'delete * from table_sel2';
    $exec = mysqli_query($conn,$qry);

    foreach ($_POST['select2'] as $sel_val)
    {
        echo $sel_val;
        $sql = "insert into table_sel2 (select2,status_id) values (".$sel_val.",1)";
        $result = mysqli_query($conn,$sql);
    }
    $message = "Done!";
}
?>

Jquery code to move data between the selectboxes:
$('#add').click(
            function(e)
            {
                $('#select1 > option:selected').appendTo('#select2');

            });

            $('#remove').click(
            function(e)
            {
                $('#select2 > option:selected').appendTo('#select1');

            });

A: Select all options from select2 upon form submission like this -
    submit_bttn.click(function () {
      $('#select2 option').each(function () {
          $(this).attr('selected', true);
      });
    });


text:
Q: How can I bind non-ascii keys with a utf-8-encoded .vimrc? The problem
I have a Scandinavian keyboard, and I want to bind my Æ, Ø and Å keys. For example, I use Ø as leader:
" ok, works:
let mapleader = "ø"

When the .vimrc is encoded in latin1, this works like a charm. However, I want to use :set enc=utf8 in my .vimrc, and then the mappings stop working:
" whoops, doesn't work:
let mapleader = "ø"
set encoding=utf-8

I presume this is because the .vimrc is written as utf-8, and that Vim is unable to parse or map the multi-byte characters.
What I want is to be able to use my non-ascii keymappings while still defaulting to utf-8 for all files other than .vimrc. (Storing .vimrc as latin1 would be an acceptable solution, but I haven't figured out a way to do it.)
Approaches that don't work
I have tried all kinds of things, and none of the following work:

*

*Modelines that set encoding and/or fileencoding for .vimrc.

*Mapping the keys to "\u00f8" and similar values instead.

*Putting non-valid utf-8 sequences in .vimrc to force defaulting to latin1.

*Various autocommands to set encoding and/or fileencoding for .vimrc.

*Opening Vim with --cmd "set encoding=latin1", because I edit my .vimrc too frequently for that to be feasible.

How can I use both set encoding=utf-8 and map my non-ascii keys?

A: The problem is caused by the ultisnips plugin. Disabling ultisnips will resolve the issue.


text:
Q: Fixed height input field on focus 'centers' the input I have an input field where I add a fixed height. However, when I focus on said height, the height turns back to the original one...What I mean by that is that when I focus it, the 'area' where I write is in the center of the input field, while I want it at the bottom of the input field.
The reason why I want that is because I want a label inside the input field, so I increase the height of the input field, and stack the label behind the input field and have a transparent background on the input field. Here's the code and the demo on jsfiddle:

input {
  position: absolute;
  -webkit-appearance: none;
  -moz-appearance: none;
  appearance: none;
  border-radius: 0;
  width: 100%;
  height: 7vh;
  z-index: 10;
  color: black;
  background-color: transparent;
}
.test-label {
  position: absolute;
  left: 2%;
  margin: 0;
  top: 5%;
  color: #778692;
}
.form-field {
  height: 7vh;
  position: relative;
  padding: 0;
}

Input

  <input type="text" />

How would I go to solve this?

A: I would probably add some padding to the top and include the
box-sizing: border-box;

So that your padding doesn't effect the size of the box.
The issue you will have, is your text's height is not dependant on the height of the view, whereas your input field is. So you will find inconsistent results on different height screens.
Here's an example JS fiddle:
http://jsfiddle.net/6uLnreu5/3/
Hope this helps

A: Use padding-top instead of fixed height. input {padding-top: 20px;}

A: you should define a font-size on your .test-label, and the set padding-top on the input equal to the font-size+x px where 0<=x<=somevalue as per your need of gapping between the label and text write area. Check out the fiddle - http://jsfiddle.net/6uLnreu5/7/
Additionally, you have to set box-sizing: border-box on the input so that its height does not increase beyond 10vh


text:
Q: Accessing sub-object property with a plain string Let's say I have the following object:
var a = {
    x: {
        y: 'Good job!'
    }
    z: 'Nice try...'
}

and the following strings:
var key1 = "z";
var key2 = "x.y";

Is there a way to access the value of y by using the key2 variable?
console.log(a[key1]) will work because it will get evaled to a['z'], but a[key2] won't because it will get evaled to a['x.y'] which is not valid.


text:
Q: How to search data in Spring JPA Restful Service I want to do a spring data search.. And below is a list of available product names.
"payload": [
    {
        "id": 1,
        "productName": "SHRIMPS COCKTAIL"
    },
    {
        "id": 2,
        "productName": "MELON FRAPE"
    },
    {
        "id": 3,
        "productName": "HORS D'OEUVRE VARIE"
    },
    {
        "id": 4,
        "productName": "CREAM OF VEGETABLES SOUP"
    },
    {
        "id": 5,
        "productName": "RAVIOLI AU JUS"
    },
    {
        "id": 6,
        "productName": "OMELETTE ESPAGNOLE"
    },
    {
        "id": 7,
        "productName": "CHICKEN A LA KING"
    },
    {
        "id": 8,
        "productName": "ROAST BEEF PRINTAINIERE"
    },
    {
        "id": 9,
        "productName": "PASRSLEY POTATOES"
    },
    {
        "id": 10,
        "productName": "SAUTED POTATOES"
    }
]

}
When I search using Postman with code like this, the results are successful
{
"session":{
    "userId":"WebAdmin ACS",
    "timestamp":"2019-07-10 13:00:00"
},
"payload":{
    "pageNumber":0,
    "limit":5,
    "productName":"MELON FRAPE"
}

Respone 200 OK like this
{
"status": {
    "statusCode": "000",
    "statusDesc": "Success"
},
"pageData": {
    "totalData": 1,
    "totalPaging": 1
},
"payload": [
    {
        "id": 2,
        "productName": "MELON FRAPE"
    }
]

But when I search with the keyword melon, the results are not there
{
"session":{
    "userId":"WebAdmin ACS",
    "timestamp":"2019-07-10 13:00:00"
},
"payload":{
    "pageNumber":0,
    "limit":5,
    "productName":"MELON"
}

}
Response :
{
"status": {
    "statusCode": "001",
    "statusDesc": "Data Not Found"
}

What I want is when entering keywords such as m, me, melon then the same results will come out not having to include the full name. My code like this
@RequestMapping(value = "/findproducthk", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
public Response<List<Product>> findProductHouseKeeping(@RequestBody Request<FindProductHouseKeeping> request, HttpServletRequest httpServletRequest) throws JsonProcessingException, NoSuchAlgorithmException {
    Response<List<Product>> rvalue = new Response<>();

    Status status = new Status();
    String user = request.getSession().getUserId();
    log.info("Headers : " + HttpUtil.getHeadersInfo(httpServletRequest).toString());
    log.info("Incoming request from " + httpServletRequest.getRemoteAddr() + ":" + httpServletRequest.getRemotePort() + "\n"
            + "    Method    : " + httpServletRequest.getMethod() + "\n"
            + "    TLS       : " + httpServletRequest.isSecure() + "\n"
            + "    Path      : " + httpServletRequest.getRequestURI() + "\n"
            + "    Body      : " + mapper.writeValueAsString(request));

    FindProductHouseKeeping findProduct = request.getPayload();
    Pageable paging = PageRequest.of(findProduct.getPageNumber(), findProduct.getLimit(), Sort.by("productName").ascending());
    Page<Product> data = null;
     if (request.getPayload().getProductName() == null) {
        data = productRepository.findById(findProduct.getId(), paging);
    } else {
        data = productRepository.findByProductNameIgnoreCase(findProduct.getProductName().toLowerCase(), paging);
    }
    if (data.isEmpty()) {
        status.setStatusCode("001");
        status.setStatusDesc("Data Not Found");
    } else {
        status.setStatusCode("000");
        status.setStatusDesc("Success");

        PagingResponse xPage = new PagingResponse();
        xPage.setTotalData(data.getTotalElements());
        xPage.setTotalPaging(data.getTotalPages());

        rvalue.setPayload(data.getContent());
        rvalue.setPageData(xPage);
    }

    log.info("Resp : " + status.toString());
    rvalue.setStatus(status);
    return rvalue;
}

============================================================================================
    public class FindProductHouseKeeping {
private int id;
private String productName;
private int pageNumber;
private int limit;

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public String getProductName() {
    return productName;
}

public void setProductName(String productName) {
    this.productName = productName;
}

public int getPageNumber() {
    return pageNumber;
}

public void setPageNumber(int pageNumber) {
    this.pageNumber = pageNumber;
}

public int getLimit() {
    return limit;
}

public void setLimit(int limit) {
    this.limit = limit;
}

Here is repository
public interface ProductRepository extends JpaRepository<Product, Integer> {
Page<Product> findByProductNameIgnoreCase(String productName, Pageable paging);
Page<Product> findById(Integer id, Pageable paging);

A: If I understand correctly you are searching "MELON" which is just part of data in database "MELON FRAPE".
In order to fix this problem, you have to implement Query which will include Like or Containing. There is few options:

*

*Use supported JPA keyword inside method name:

Page<Product> findByProductNameContainingIgnoreCase(String productName, Pageable paging);

*Create method (you can call it whatever you want) and use @Query annotations which can include native or JPA query.

More information: docs.


text:
Q: Simple Present in Indefinite Past timeI My grammar book says Simple Present can be used with some certain verbs in Indefinite Past
For example,
"I forget what he said"
Is there any difference between
"I forgot what he said" and "I forget what he said"
Because Simple past can also express "Uncertain  Past" in this case

A: In spoken English, "I forget" is most commonly used as a very informal way of saying "I forgot". This is very common in casual conversation:

A: Do we have homework this week?
B: I don't know, I forget what the teacher said.

You could use "I forget (x)" to indicate that you always or habitually forget something, but then you would want to use the present tense in the inner clause, and probably use some modifier, like always:

John is such an unmemorable speaker. I always forget what he says.

"I forget what he said" could mean that you habitually forget one thing that he said at a particular time in the past: e.g.

I always forget what John said on that one August night. He gave me some advice, but I can never remember it.


text:
Q: Android assign to textview I want to assign data from database to textview or variable. But i get an error when assigning a value to textview or variable. When i Log to display the data it is OK.
Error:
    Only the original thread that created a view hierarchy can touch its views.
Here is the code:
try {
            String sql = "SELECT Cname FROM demo";
            Statement stmt = con.createStatement();
            ResultSet rs = stmt.executeQuery(sql);

            while (rs.next()) {
                  TextView txtValue = (TextView)findViewById(R.id.textView3);
            txtValue.setText(rs.getString("Cname"));

            }

A: As the error implies you need to set the text on the main thread.
You can post a message via the TextView, so it runs on the UI thread:
final ResultSet rs = stmt.executeQuery(sql);
...
final TextView txtValue = (TextView) findViewById(R.id.textView3);
txtValue.post(new Runnable() {
    @Override
    public void run() {
        txtValue.setText(rs.getString("Cname"));
    }
});


text:
Q: How to open the "My Files/File Manager" in Android Programmatically (using Intent) in Android 12 - Snow Cone? How to open My Files/File Manager folder in Android Programmatically (using intent) in Android 12 - Snow Cone?
I am using the below code snippet which opens up the File Manager in Android 11(Red Velvet Cake),  I want the My Files folder to get open programmatically in Android 12(Snow Cone), please let me know if there are any specific intent parameters I need to pass to get the File Manager open in Android 12.
        Intent chooserIntent;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            chooserIntent = new Intent(Intent.ACTION_PICK,
            MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            chooserIntent.setType("*/*");
        }else {
            chooserIntent = new Intent(Intent.ACTION_GET_CONTENT);
            chooserIntent.setType("*/*");
            chooserIntent.addCategory(Intent.CATEGORY_OPENABLE);
        }

Thanks :)


text:
Q: Using the Files.move creates a new "file" file type rather than moving the file to a directory I am trying to make a program that extracts multiple MP4 files from there individual folders and places them in a folder that is already created (code has been changed slightly so that it doesn't mess up any more of the MP4s, rather dummy text files).
I have managed to get so far as to list all folders/files in the specified folder however am having trouble moving them to a directory.
static File dir = new File("G:\\New Folder");
static Path source;
static Path target = Paths.get("G:\\gohere");

static void showFiles(File files[]) {
    for (File file : files) { // Loops through each file in the specified directory in "dir" variable.

        if (file.isDirectory()) { // If the file is a directory.

            File[] subDir = file.listFiles(); // Store each file in a File list.

            for (File subFiles : subDir) { // Loops through the files in the sub-directory.
                if (subFiles.getName().endsWith(".mp4")) { // if the file is of type MP4
                    source = subFiles.toPath(); // Set source to be the abs path to the file.
                    System.out.println(source);
                    try {
                        Files.move(source, target);
                        System.out.println("File Moved");
                    } catch (IOException e) {
                        e.getMessage();
                    }
                }
            }
        } else {
            source = file.toPath(); // abs path to file
            try {
                Files.move(source, target);
                System.out.println("File moved - " + file.getName());
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}

public static void main(String[] args) {
    showFiles(dir.listFiles());
}

The problem is when I go to move the file from the source folder to the target, it removes or converts the target.

A: Files.move isn't like the command line. You're programming. You have to spell things out. You're literally asking Files.move to make it so that target (here, G:\GoHere) will henceforth be the location for the file you are moving. If you intended: No, the target is G:\GoHere\TheSameFileName then you have to program this.
Separately, your code is a mess. Stop using java.io.File and java.nio.Path together. Pick a side (and pick the java.nio side, it's an newer API for a good reason), and do not mix and match.
For example:
Path fromDir = Paths.get("G:\\FromHere");
Path targetDir = Paths.get(G:\\ToHere");
try (DirectoryStream ds = Files.newDirectoryStream(fromDir)) {
  for (Path child : ds) {
    if (Files.isRegularFile(child)) {
      Path targetFile = targetDir.resolve(child.getFileName());
      Files.move(child, targetFile);
    }
  }
}

resolve gives you a Path object that is what you need here: The actual file in the target dir.


text:
Q: Rotar Cubo 3d Java Buenas, esta es mi primera pregunta y no se si esto va acá pero intentare de ser lo mas claro posible, tengo lo siguiente :
    private final int B_WIDTH = 850;
    private final int B_HEIGHT = 850;
    private final int DELAY = 25;
    private Thread animator;
    private Punto[] p = new Punto[8];
    private int x = 50, y=150;
    float YP[] = new float[2];
    float XP[] = new float[2];

    private int[][] matrizRotacion = new int[3][3];
        public Line(){
            initLine();
        }

        private void initLine(){
            setPreferredSize(new Dimension(B_WIDTH, B_HEIGHT));
            setDoubleBuffered(true);

            p[0] = new Punto(x,x,y);
            p[1] = new Punto(y,x,y);
            p[2] = new Punto(y,x,x);
            p[3] = new Punto(x,x,x);
            p[4] = new Punto(x,y,x);
            p[5] = new Punto(y,y,x);
            p[6] = new Punto(y,y,y);
            p[7] = new Punto(x,y,y);
        }

        @Override
        public void addNotify() {
            super.addNotify();

            animator = new Thread(this);
            animator.start();
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.translate(200, 10);
            pintar(g);

        }

        public void pintar(Graphics g){
            g.drawLine(p[0].XP, p[0].YP, p[1].XP, p[1].YP);
            g.drawLine(p[1].XP, p[1].YP, p[2].XP, p[2].YP);
            g.drawLine(p[2].XP, p[2].YP, p[3].XP, p[3].YP);
            g.drawLine(p[3].XP, p[3].YP, p[0].XP, p[0].YP);

            g.drawLine(p[6].XP, p[6].YP, p[5].XP, p[5].YP);
            g.drawLine(p[5].XP, p[5].YP, p[4].XP, p[4].YP);
            g.drawLine(p[4].XP, p[4].YP, p[7].XP, p[7].YP);
            g.drawLine(p[7].XP, p[7].YP, p[6].XP, p[6].YP);

            g.drawLine(p[6].XP, p[6].YP, p[1].XP, p[1].YP);
            g.drawLine(p[0].XP, p[0].YP, p[7].XP, p[7].YP);
            g.drawLine(p[3].XP, p[3].YP, p[4].XP, p[4].YP);
            g.drawLine(p[2].XP, p[2].YP, p[5].XP, p[5].YP);
            Toolkit.getDefaultToolkit().sync();
        }

        private void cycle() {
         // x +=1;
         // y += 1;
            for (int i = 0; i < 100; i++) {
                initLine();
            }

        }

        @Override
        public void run() {
        long beforeTime, timeDiff, sleep;

        beforeTime = System.currentTimeMillis();

        while (true) {

            cycle();

            repaint();

            timeDiff = System.currentTimeMillis() - beforeTime;
            sleep = DELAY - timeDiff;

            if (sleep < 0) {
                sleep = 2;
            }

            try {
                Thread.sleep(sleep);
            } catch (InterruptedException e) {
                System.out.println("Interrupted: " + e.getMessage());
            }

            beforeTime = System.currentTimeMillis();
        }
    }
}

También tengo una clase Punto y una clase que dibuja el panel donde esta eso:
public class Punto {
        double x,y,z;
        int XP;
        int YP;
        public Punto(int x, int y, int z) {
            this.x = x;
            this.y = y;
            this.z = z;

            get2DX();
            get2DY();

        }

        private int get2DX() {
            XP = (int) (x+z*(Math.cos(90)));
            return XP;
        }

        private int get2DY() {
            YP = (int) (y+z*(Math.sin(90)));
            return YP;
        }
    }

Esto dibuja un cubo 3d, pero quiero hacer que este cubo rote con algún eje y sinceramente no entiendo como hacer lo de la matriz de rotación
|cos, -sen 0|   |x|
|sen   cos 0| * |y|        algo asi..
|0    0    1|   |z|
así que mi pregunta es si alguien me puede explicar o mostrar un ejemplo de como puedo hacer esto? o si lo que tengo esta bien (se que hay métodos para hacer esto mismo fácil pero el punto es entender como funciona).
gracias.


text:
Q: How do I get the value of the selected items in the multiselect bootstrap? I have already visited several similar topics, but the answers are always $('element').val(), but this only returns an array with the text and not the value. Note that I want it to return something like: [1, 2, 3] and not [email1@email.com, email2@email.com, email3@email.com]

function create_multiselect(element){
    element.multiselect({
      enableFiltering: true,
      includeSelectAllOption: true,
      enableCaseInsensitiveFiltering: true,
      buttonWidth: '100%',
      maxHeight: 450,
  });
}
function getvalue(element){
  console.log(element.val());
}

$("#btn").on("click", function(){
  getvalue($("#activity_from"));
});

create_multiselect($('#activity_from'));
<!-- jQuery -->
      <script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
      <!-- Bootstrap -->
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
      <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
        <!-- multiselect -->
      <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.15/css/bootstrap-multiselect.css" integrity="sha512-EvvoSMXERW4Pe9LjDN9XDzHd66p8Z49gcrB7LCUplh0GcEHiV816gXGwIhir6PJiwl0ew8GFM2QaIg2TW02B9A==" crossorigin="anonymous" />
      <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.15/js/bootstrap-multiselect.min.js" integrity="sha512-aFvi2oPv3NjnjQv1Y/hmKD7RNMendo4CZ2DwQqMWzoURKxcqAoktj0nNG4LU8m23+Ws9X5uVDD4OXLqpUVXD5Q==" crossorigin="anonymous"></script>

<div class="form-group">
    <select id="activity_from" name="multiselect[]" multiple="multiple" class="form-control activity_multiselect">
          <option valeu="1">email1@emal.com</option>
          <option valeu="2">email2@emal.com</option>
          <option valeu="3">email3@emal.com</option>
          </select>
</div>

<button type="button" id="btn"> GET VALUE </button>


text:
Q: Is there a way to disable OCR mode in Tika without uninstalling tesseract I am using tika-app jar for my project and is there a way to disable tesseract OCR in tika. There are two things which has to be kept as such:
1.tesseract cannot be uninstalled
2.tika.xml can't be edited, as tika-app.jar is used off the shelf
Is there a way to set the configuration in the java code by setting the context or parser property to disable OCR?
I tried the below code but still OCR extracts the text from image files while parsing.
            PDFParserConfig pdfConfig = new PDFParserConfig();
            pdfConfig.setOcrStrategy(OCR_STRATEGY.NO_OCR);
            context.set(PDFParserConfig.class, pdfConfig);```

A: <?xml version="1.0" encoding="UTF-8"?>
<properties>
    <parsers>
        <parser class="org.apache.tika.parser.DefaultParser">
       <parser-exclude class="org.apache.tika.parser.ocr.TesseractOCRParser"/>
        </parser>
    </parsers>
</properties>

A: I prefer to do this with java as its only difference with the default config would be OCR removed; I'm not certain if the XML config does the same:
TikaConfig defaultConfig = TikaConfig.getDefaultConfig();
CompositeParser compositeParser = (CompositeParser) defaultConfig.getParser();
Map<MediaType, Parser> parsers = compositeParser.getParsers();
parsers.values().removeIf(parser -> parser instanceof TesseractOCRParser);
compositeParser.setParsers(parsers);
Tika TIKA = new Tika(defaultConfig);


text:
Q: template instantiation with constexpr function failure I have template class C that has a non-type but reference template parameter to a type P:
class P {
public:
  int x;
  int y;
};

template <const P &x>
class C {
public:
  const int &f() { return x.x; }
};

I declared a global variable of type P:
P p = {33,44};

I also declared a function that returns a reference to p:
constexpr const P &h() { return p; }

And then tried to use these in the following :
C<p> o;    // line 1
C<h()> oo; // line 2

Of course I have no problem with the first instantiation but the second. My compiler complains:
error: non-type template argument does not refer to any declaration

Why is so ? I was unable to find an argument against it in the norm. I am not sure that it is exactly the same problem as in Calling constexpr in default template argument, where the discussion was about point of instantiation of nested instanciation. Here it is more a type problem, but which one ? My function h() returns a reference to a well defined variable of the well defined type (const P &). I expected that some inlining would take place a give the right result but it is not the case. Could you tell me why ?
Declaring the function as inline doesn't change anything to the problem.
Experiments were done with Apple LLVM version 6.0 (clang-600.0.56) (based on LLVM 3.5svn. I also tried with g++-mp-4.8 (MacPorts gcc48 4.8.3_2) 4.8.3 and the error was reported as:
'h()' is not a valid template argument for type 'const P&' because it is not an object with external linkage

It looks like my call to h() (which is a constexpr so compile-time computable) is not seen as such...

I forgot to say that the problem is the same if we try with another reference like this:
const P &pp = p;

and then
C<pp> oo;

this time the first compiler says:
non-type template argument of reference type 'const P &' is not an object

and the second:
error: could not convert template argument 'pp' to 'const P &'

pp is not an object? pp is not of type const P&? Well I can use it as is it one... I know it is a reference but indistinguishable from a native reference, or ?

A: In the case of
C<h()> oo;

§14.3.2/4 kicks in:

[Note: Temporaries, unnamed lvalues, and named lvalues with no linkage are not acceptable template-
  arguments when the corresponding template-parameter has reference type.

(emphasis mine)

A: It looks like this restriction was subject to the following proposal Allow constant evaluation for all non-type template arguments, still trying to determine the status of this proposal. It says:

The syntactic restrictions for pointers, references, and pointers to
  members are awkward and prevent reasonable refactorings. For instance:
template<int *p> struct A {};
int n;
A<&n> a; // ok

constexpr int *p() { return &n; }
A<p()> b; // error

and further says:

The historical reason for the restriction was most likely that C++
  previously did not have a sufficiently strong specification for
  constant expressions of pointer, reference, or pointer-to-member type.
  However, that is no longer the case. The status quo is that an
  implementation is required to evaluate such a template argument, but
  must then discard the result if it turns out to not be null.
In addition to the above, the restriction to entities with linkage is
  an artifact of exported templates, and could have been removed when
  the linkage restrictions on template type parameters were removed.

and it would remove this section of the note with this restriction:

unnamed lvalues, and named lvalues with no linkage

the whole note reads:

Temporaries, unnamed lvalues, and named lvalues with no linkage are
  not acceptable template-arguments when the corresponding
  template-parameter has reference type.

Update
The revised version of this proposal N4268 was adopted into the working draft at Urbana and we can see the changes in the latest working draft N4296. The new note reads:

A temporary object is not an acceptable template-argument when the
  corresponding template-parameter has reference type

The normative section is 14.3.2 (temp.arg.nontype) paragraph 1 which with this proposal would say:

For a non-type template-parameter of reference or pointer type, the
  value of the constant expression shall not refer to (or for a pointer
  type, shall not be the address of):

*

*a subobject (1.8),

*a temporary object (12.2),

*a string literal (2.14.5),

*the result of a typeid expression (5.2.8), or

*a predefined func variable (8.4.1).

and we can find this new wording in the latest draft standard N4296.
It looks like this change has actually been implemented in clang HEAD see your code working live, using the -std=c++1z flag. This implies the change should be part of C++17, assuming no subsequent changes reverses or alters it.


text:
Q: Jquery insert hidden field from dropdown is throwing error when trying to submit to access db via asp I have an asp form that will be completing two actions. The first is to submit the data to the database, the second is to email the data to the person selected in the form.
I have a drop down menu that shows employee names and passes a value of the employee email address.
I'm currently using this Jquery code to pass the employee name to a hidden field and want to use that hidden field to submit to the database.
$(document).ready( function (){

$("#to").change( function(){

  var selectedValue = $("#to option:selected").val();

  var selectedText = $("#to option:selected").text();

       $("#hiddenText").val( selectedText );

       alert("Hidden field text is: " + $("#hiddenText").val());

 });

 });

This appears to work, the alert show the correct value. When I try to submit the form and insert to the database, I get this error:
Microsoft OLE DB Provider for ODBC Drivers error '80040e57'
[Microsoft][ODBC Microsoft Access Driver]Invalid string or buffer length
/intranet/EmployeeInfo/Heroes1/heroesPost.asp, line 30
Below is the insert code:
    <%
If (CStr(Request("MM_insert")) = "heroes") Then
  If (Not MM_abortEdit) Then
' execute the insert
Dim MM_editCmd

Set MM_editCmd = Server.CreateObject ("ADODB.Command")
MM_editCmd.ActiveConnection = MM_PhoneDir_STRING
MM_editCmd.CommandText = "INSERT INTO REACH ([To], Dept, prideSelect, flagpoleSelect, [comment], [from]) VALUES (?, ?, ?, ?, ?, ?)"
MM_editCmd.Prepared = true
MM_editCmd.Parameters.Append MM_editCmd.CreateParameter("param1", 203, 1, 1073741823, Request.Form("hiddenText")) ' adLongVarWChar
MM_editCmd.Parameters.Append MM_editCmd.CreateParameter("param2", 202, 1, 50, Request.Form("dept")) ' adVarWChar
MM_editCmd.Parameters.Append MM_editCmd.CreateParameter("param3", 202, 1, 50, Request.Form("prideSelect")) ' adVarWChar
MM_editCmd.Parameters.Append MM_editCmd.CreateParameter("param4", 202, 1, 255, Request.Form("flagpoleSelect")) ' adVarWChar
MM_editCmd.Parameters.Append MM_editCmd.CreateParameter("param5", 203, 1, 1073741823, Request.Form("comment")) ' adLongVarWChar
MM_editCmd.Parameters.Append MM_editCmd.CreateParameter("param6", 202, 1, 100, Request.Form("from")) ' adVarWChar
MM_editCmd.Execute
MM_editCmd.ActiveConnection.Close

' append the query string to the redirect URL
Dim MM_editRedirectUrl
MM_editRedirectUrl = "HeroesThanks.asp"
If (Request.QueryString <> "") Then
  If (InStr(1, MM_editRedirectUrl, "?", vbTextCompare) = 0) Then
    MM_editRedirectUrl = MM_editRedirectUrl & "?" & Request.QueryString
  Else
    MM_editRedirectUrl = MM_editRedirectUrl & "&" & Request.QueryString
  End If
End If
Response.Redirect(MM_editRedirectUrl)
  End If
 End If
%>

If I "ignore" the hidden field and just submit the value from the drop down, the form submits without error and the information is added to the database.
Any ideas on what I need to change to get this to work correctly?

A: It is likely that the data you are trying to insert is being truncated, if the string 250 long and your database field only accepts 50 chars then you will get this error.
More info ... check out Why do I get 80040E57 / 80040E07 errors?


text:
Q: many custom dialog with radioButton i have simple app using dialog for divided,subtraction,and etc with looping condition by operator
my error
02-08 17:29:23.271: W/KeyCharacterMap(744): No keyboard for id 0
02-08 17:29:23.271: W/KeyCharacterMap(744): Using default keymap: /system/usr/keychars/qwerty.kcm.bin
02-08 17:29:24.011: D/dalvikvm(744): GC_EXTERNAL_ALLOC freed 72K, 52% free 2611K/5379K, external 914K/1038K, paused 59ms
02-08 17:29:26.101: W/KeyCharacterMap(744): No keyboard for id 0
02-08 17:29:26.101: W/KeyCharacterMap(744): Using default keymap: /system/usr/keychars/qwerty.kcm.bin
02-08 17:29:30.311: D/AndroidRuntime(744): Shutting down VM
02-08 17:29:30.311: W/dalvikvm(744): threadid=1: thread exiting with uncaught exception (group=0x40015560)
02-08 17:29:30.321: E/AndroidRuntime(744): FATAL EXCEPTION: main
02-08 17:29:30.321: E/AndroidRuntime(744): java.lang.NullPointerException
02-08 17:29:30.321: E/AndroidRuntime(744):  at com.example.dialog_looping.MainActivity$1$1$1.onClick(MainActivity.java:72)
02-08 17:29:30.321: E/AndroidRuntime(744):  at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:159)
02-08 17:29:30.321: E/AndroidRuntime(744):  at android.os.Handler.dispatchMessage(Handler.java:99)
02-08 17:29:30.321: E/AndroidRuntime(744):  at android.os.Looper.loop(Looper.java:123)
02-08 17:29:30.321: E/AndroidRuntime(744):  at android.app.ActivityThread.main(ActivityThread.java:3683)
02-08 17:29:30.321: E/AndroidRuntime(744):  at java.lang.reflect.Method.invokeNative(Native Method)
02-08 17:29:30.321: E/AndroidRuntime(744):  at java.lang.reflect.Method.invoke(Method.java:507)
02-08 17:29:30.321: E/AndroidRuntime(744):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
02-08 17:29:30.321: E/AndroidRuntime(744):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
02-08 17:29:30.321: E/AndroidRuntime(744):  at dalvik.system.NativeStart.main(Native Method)
02-08 17:34:30.490: I/Process(744): Sending signal. PID: 744 SIG: 9

this is my full code use dialog looping for subtraction,divided and etc....
public class MainActivity extends Activity {
    int result=0,i;
    int [] arr;
    int indexArray = 0;
    String Oprtr;
    RadioGroup operator_mode;
    RadioButton rb;
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        final LayoutInflater inflater = this.getLayoutInflater();
        final View v=inflater.inflate(R.layout.dialoginput, null);

        operator_mode=(RadioGroup)findViewById(R.id.operator);

        //operator_mode.setOnClickListener(l)(null);

        new AlertDialog.Builder(MainActivity.this)
            .setIcon(R.drawable.ic_launcher)
            .setTitle("Total Operator")
            .setView(v)
            .setPositiveButton("Ok", new DialogInterface.OnClickListener() {

                 public void onClick(final DialogInterface dialog, int whichButton) {
                      EditText op = (EditText)v.findViewById(R.id.operator);
                      arr=new int [Integer.valueOf(op.getText().toString())+1];
                      for (i = 0;i<arr.length;i++){

                            LayoutInflater inflater = MainActivity.this.getLayoutInflater();
                            final View v2=inflater.inflate(R.layout.input, null) ;

                            new AlertDialog.Builder(MainActivity.this)
                                .setIcon(R.drawable.ic_launcher)
                                .setTitle("number:")
                                .setView(v2)
                                .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dlg, int sumthin) {

                                        EditText number = (EditText)v2.findViewById(R.id.number);
                                        arr[indexArray]= Integer.valueOf(number.getText().toString());
                                        //Log.v ("aa",Integer.toString(arr[indexArray]));

                                        LayoutInflater inflater = MainActivity.this.getLayoutInflater();
                                        final View v3=inflater.inflate(R.layout.operator, null) ;

                                        new AlertDialog.Builder(MainActivity.this)
                                        .setIcon(R.drawable.ic_launcher)
                                        .setTitle("select Operator:")
                                        .setView(v3)
                                        .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                                            public void onClick(DialogInterface dlg, int sumthin) {
                                                sumthin = operator_mode.getCheckedRadioButtonId();
                                                rb = (RadioButton) findViewById(sumthin);
                                                switch(sumthin){
                                                case R.id.plus:
                                                    Oprtr = "+";
                                                    Log.v ("aa",Oprtr);
                                                    /*
                                                    if (indexArray==0){
                                                        result = arr[indexArray];
                                                        if (result<0){
                                                            new AlertDialog.Builder(MainActivity.this)
                                                                .setTitle("Error")
                                                                .setMessage("result can't negative value")
                                                                .setNeutralButton("Close", new DialogInterface.OnClickListener() {
                                                                    public void onClick(DialogInterface dlg, int sumthin) {
                                                                        finish();
                                                                    }
                                                                })
                                                                .show();
                                                            } else if (result>9999999){
                                                                new AlertDialog.Builder(MainActivity.this)
                                                                .setTitle("Error")
                                                                .setMessage("result can't > 9999999")
                                                                .setNeutralButton("Close", new DialogInterface.OnClickListener() {
                                                                    public void onClick(DialogInterface dlg, int sumthin) {
                                                                        finish();
                                                                    }
                                                                })
                                                                .show();
                                                            }else {
                                                                new AlertDialog.Builder(MainActivity.this)
                                                                .setTitle("result")
                                                                .setMessage(Integer.toString(result))
                                                                .setNeutralButton("Close", new DialogInterface.OnClickListener() {
                                                                    public void onClick(DialogInterface dlg, int sumthin) {
                                                                    }
                                                                })
                                                                .show();
                                                            }
                                                    } else {
                                                            result = result + arr[indexArray];
                                                            if (result<0){
                                                            new AlertDialog.Builder(MainActivity.this)
                                                                .setTitle("Error")
                                                                .setMessage("result can't negative value")
                                                                .setNeutralButton("Close", new DialogInterface.OnClickListener() {
                                                                    public void onClick(DialogInterface dlg, int sumthin) {
                                                                        finish();
                                                                    }
                                                                })
                                                                .show();
                                                            } else if (result>9999999){
                                                                new AlertDialog.Builder(MainActivity.this)
                                                                .setTitle("Error")
                                                                .setMessage("result can't > 9999999")
                                                                .setNeutralButton("Close", new DialogInterface.OnClickListener() {
                                                                    public void onClick(DialogInterface dlg, int sumthin) {
                                                                        finish();
                                                                    }
                                                                })
                                                                .show();
                                                            }else {
                                                                new AlertDialog.Builder(MainActivity.this)
                                                                .setTitle("result")
                                                                .setMessage(Integer.toString(result))
                                                                .setNeutralButton("Close", new DialogInterface.OnClickListener() {
                                                                    public void onClick(DialogInterface dlg, int sumthin) {
                                                                    }
                                                                })
                                                                .show();
                                                            }
                                                    }
                                                    indexArray++;
                                                    */
                                                    break;
                                                case R.id.minus:
                                                    //str="Meeting Mode";
                                                    break;
                                                case R.id.substract:
                                                    //str="Silent Mode";
                                                    break;
                                                case R.id.divide:
                                                    //str="Offline Mode";
                                                    break;
                                            }
                                            }
                                        })
                                        .show();
                                    }
                                })
                                .show();
                        }
                 }
            })

            .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
              public void onClick(DialogInterface dialog, int whichButton) {
                 finish();
              }
            })
            .show();
    }
}

where the error with my code?
please help me.thanks

A: Your RadioGroup is null, I believe. You need to set your view with
setContentView(R.layout.your_view)
Then if you need to inflate a view use:
operator_mode=(RadioGroup)v.findViewById(R.id.operator);
instead of
operator_mode=(RadioGroup)findViewById(R.id.operator);
Edit
You can use your inflater but you would have to do something like:
Window window = getWindow();

    window.setContentView(v);`

But you are still calling setContentView()


text:
Q: Output for a nested function in r The code below is one way to model "Snakes and ladders" game:
    ladder.df <- data.frame(start=c(1,4,9,21,28,36,51,71,80), end=c(38,14,31,42,84,44,67,91,100))
snake.df <- data.frame(start=c(98,95,93,87,64,62,56,49,47,16), end=c(78,75,73,24,60,19,53,11,26,6))

game<-function(nop){
positions<-c()
curpos <- 0 # Current location
nroll <- 0 # Number of rolls
snakes <- 0 # Number of snakes encountered
ladders <- 0 # Number of ladders encountered
players<-c(1:nop)
ladders2<-c()
snakes2<-c()

for(i in 1:nop){
while(curpos < 100) {
  roll <- sample(6,1)
  curpos <- curpos + roll
  nroll <- nroll + 1
  positions<-append(positions,curpos)

  # Need to check if we landed on a ladder or slide and move forward or back
  if (any(ladder.df$s %in% curpos)) {
    curpos <- ladder.df$e[ladder.df$s %in% curpos]
    ladders <- ladders + 1
  }
  if (any(snake.df$s %in% curpos)) {
    curpos <- snake.df$e[slide.df$s %in% curpos]
    snakes <- snakes + 1
  }
}
data<-data.frame("Player:"=players[i],"Ladders"=ladders,"Snakes"=snakes,"Number of rolls"=nroll)
print(data)
}
}

The code runs fine, however, the output I want ( that is, no. of ladders, snakes and number of throws for each player) duplicates the results of the last player, since neither snakes, ladders or no. of throws dependent on i. Question is- how do I fix this? I tried various approaches (like assigning all the 'snakes' values to the vector and call a certain value from a vector, corresponding to the value i) but it will not budge. Thanks for all the support in advance!


text:
Q: Is there any way to programatically get the activity name in Android? I have 100+ activities in my Android Studio project. I need to find and replace them with their activity name. For example, my 100+ activities have the same code  as this
String activityName = "Example.this";

And now I need to search for and replace the Example part with their activity name.
For ActivityOne I need to achieve this
String activityName = "ActvitiyOne.this";

For ActivityTwo I need this
String activityName = "ActvitiyTwo.this";

I can replace all of them with one word by using Ctrl + Shift + R.
But is there any way to achieve the above or do I need to do it manually?

A: You can replace them all with ClassUtils.getSimpleName(this) or getClass().getSimpleName()
String activityName = ClassUtils.getSimpleName(this);
 or
String activityName = getClass().getSimpleName();


text:
Q: network errror when trying to connect to docker instance (windows 7/docker toolbox) I am trying to use docker for the first time on windows 7. I've gone through several guides and everything seemed to be going well, however I cannot actually connect to the docker container once I run it.
I am trying to connect to http://192.168.99.100:32769/ however I keep getting the following error;

Network Error (tcp_error)
A communication error occurred: "Operation timed out"
The Web Server may be down, too busy, or experiencing other problems preventing it from responding to requests. You may wish to try again at a later time.

Below is a screen grab with some information.

Here is a screen grab of the kitematic window;

I've tried running docker-machine env default and also the command it says to afterwards, on both cmd/powershell but neither works.
I've tried removing and recreating the docker machine. As well as reinstalling docker completely.
I can't seem to find any information as to why I'm getting this error.
Exact windows version is Windows 7 Professional.
Hope someone can help out? If you need any more information please say!


text:
Q: Probability that $5$ numbers chosen randomly in the interval $[0, 1]$ all lie in the middle half of the interval. My attempt: Have $5$ random variables uniform on the interval $[0, 1]$, with cdf $F(x) = x$.
The middle half of the interval is $[\frac{1}{4}, \frac{3}{4}]$. The probability that one of the random variables lies in this interval is
$$ p = F\Big(\frac{3}{4}\Big) - F\Big(\frac{1}{4}\Big) = \frac{3}{4} - \frac{1}{4} = \frac{1}{2} .$$
The probability that all five random variables lie in this interval is then
$$ p^5 = \Big(\frac{1}{2}\Big)^5 = \frac{1}{32} .$$
There was no solution for this exercise in my textbook and I couldn't find the answer anywhere online. Hoping somebody can verify if this is the correct answer.

A: Your solution looks entirely correct to me. Strictly speaking, the phrase

$5$ numbers chosen randomly in the interval $[0,1]$

is a little vague, because it doesn't say if the picks are independent, but you can safely assume that, and then the probability of each event is $\frac12$, so the probability of them all is $\frac{1}{32}$. Well done!

A: Don't even need the ' F(x)' stuff since the interval u want them to be in has length 1/2 and the other two intervals [0,1/4) and (3/4,1] combined are length 1/2 so the probability will be (1/2)^n for n bring the numbers of picked .this case is n=5 .


text:
Q: Adjust alpha of UIColor I set a UIColor using rgb to a background of a UILabel. I'm trying to adjust the alpha only. How can I modify the alpha of an existing rgb UIColor?
Edit
Basically I have UILabels that have a set UIColor (using rgb), and I won't know what color the UILabels are. At a certain point, I will have to change the labels alpha`. How can I just change the labels color alpha?

A: why not using label.alpha = 0.5 ? to adjust your label's alpha?
update: if you want to adjust alpha from a old color, here is an example:
UIColor uicolor = [UIColor greenColor];
CGColorRef color = [uicolor CGColor];

int numComponents = CGColorGetNumberOfComponents(color);

UIColor newColor;
if (numComponents == 4)
{
    const CGFloat *components = CGColorGetComponents(color);
    CGFloat red = components[0];
    CGFloat green = components[1];
    CGFloat blue = components[2];
    newColor = [UIColor colorWithRed: red green: green blue: blue alpha: YOURNEWALPHA];

}

A: The shortest possible code (Swift 5):
view.backgroundColor = .black.withAlphaComponent(0.75)

A: colorWithAlphaComponent: did the trick.
So what I had to do was:
self.mylabel.backgroundColor = [self.myLabel.backgroundColor colorWithAlphaComponent:0.3];

A: If you have custom colors defined, you can do this as well:
view.backgroundColor = [[MyClass someColor] colorWithAlphaComponent:0.25];

A: Swift 3+
yourUIView.backgroundColor = UIColor.white.withAlphaComponent(0.75)

Swift 2
yourUIView.backgroundColor = UIColor.whiteColor().colorWithAlphaComponent(0.75)

A: Version Swift (5.4)
UIColor.blue.withAlphaComponent(0.5)

A: Please set alpha in below code -
[UIColor colorWithRed:200.0/255.0 green:191.0/255.0 blue:231.0 /255.0 alpha:1.0]


text:
Q: Make Visual Studio use a Windows 10 Mobile emulator installed on the other machine Is there a way to configure Visual Studio 2015 to use
the Windows 10 Mobile emulator installed on a remote Hyper-V server for debugging & testing UWP apps instead of having VS spin up the emulator VMs locally?
The server is a dedicated Hyper-V machine which has plenty of RAM and CPU power to run multiple emulator instances simultaneously. The machines are connected by a 1 Gbps Ethernet, and the PC's Hyper-V Manager is already set up to interact with the remote VMs on the server (i.e. create/start/shutdown/save etc.)

A: Unfortunately, this is not possible today.


text:
Q: How to handle cross browser and device compatibility for MediaRecorder and Audio control My web app needs to support recording of audio using a web interface and then subsequent playback of the same audio files.
My prelim analysis shows that chrome supports "audio/webm" and safari supports "audio/mp4" for recording audio using the MediaRecorder. This would have been fine but HTML5 AUDIO component on these browsers has the same format limitation and this is causing a device/OS fragmentation.
I am using AWS as my application's backend.
Is there a way to get around this browser segmentation.


text:
Q: How to remove extra quotes in pymysql This code uses pymysql, however when i try to insert the variable title into the sql query it comes out with 'title' for example when i set title to = test the database created is 'test' is there a way to create the table without the extra quotes
   import pymysql
    connection = pymysql.connect(
        host='localhost',
        user='root',
        password='',
        db='comments',
    )
    c= connection.cursor()
    sql ='''CREATE TABLE IF NOT EXISTS `%s` (
      `comment_id` int(11) NOT NULL,
      `parent_comment_id` int(11) NOT NULL,
      `comment` varchar(200) NOT NULL,
      `comment_sender_name` varchar(40) NOT NULL,
      `date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8; '''
    c.execute(sql, (title))

A: In my case I just rewrite the escape method in class 'pymysql.connections.Connection', which obviously adds "'" arround your string.
I don't know whether it is a bad idea, but there seems no better ways, if anyone knows, just let me know.
Here's my code:
from pymysql.connections import Connection, converters

class MyConnect(Connection):
    def escape(self, obj, mapping=None):
        """Escape whatever value you pass to it.

        Non-standard, for internal use; do not use this in your applications.
        """
        if isinstance(obj, str):
            return self.escape_string(obj)  # by default, it is :return "'" + self.escape_string(obj) + "'"
        if isinstance(obj, (bytes, bytearray)):
            ret = self._quote_bytes(obj)
            if self._binary_prefix:
                ret = "_binary" + ret
            return ret
        return converters.escape_item(obj, self.charset, mapping=mapping)

config = {'host':'', 'user':'', ...}
conn = MyConnect(**config)
cur = conn.cursor()


text:
Q: How to get value from UItableView for textField? I have tableView on my viewController, and one textField. TableView present list of names. When I click on cell with the name, I want to get that name like textfield text.
Anybody have idea how can I do that?

A: The method didSelectRow at from tableView will give you the indexPath clicked. You are probably loading those names based on an array, you can then do array[indexPath.row]

A: Add this code to your class.
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    yourTextfield.text = namesArray[indexPath.row]
}

A: func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
     let name = names[indexPath.row]
     yourTextfieldName.text = namesArray[indexPath.row]
}

A: When user tap of tableView cell its detected in  didSelectRowAt from this you can get selected cell index to find name in the array.
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
      let name = names[indexPath.row]  // Get selected name from array names
      print(name)
     textField.text = name // Assign   textField text to selected name
}


text:
Q: Copy only strings between two string patterns Testing some regex code.  It should look something like this, I think.
r'\stable_name:\s+([a-z _1-9]+)\n    (.*?)\sid: validate'

results = re.findall(r'\stable_name:\s+([a-z _1-9]+)\n    (.*?)\sid: validate',lines,flags=re.DOTALL)

But I'm getting no results back.  All I get is this error: AttributeError: 'tuple' object has no attribute 'replace'

A: So, for the example:
lines = """table_name: snl_realestate_pricing_eap_pricechanges
some text here...
id: validate

table_name: snl_realestate_pricing_eap_return_5y
some text here...
id: validate

table_name: snl_realestate_pricing_eap_rates_10yrnote
some text here...
id: validate"""

The regex gives me:
results = re.findall(r'table_name:\s+([a-z _1-9\n]+\sid: validate',lines,flags=re.DOTALL)
>>> results
[('snl_realestate_pricing_eap_pricechanges', 'some text here...'), ('snl_realestate_pricing_eap_return_5y', 'some text here...')]

This produces tuples, which you're (I assume) trying to do something like results[0].replace(), which fails with your error
Changing the regex gives me:
results = re.findall(r'table_name:\s+(.*?)\sid: validate',lines,flags=re.DOTALL)
>>> results
['snl_realestate_pricing_eap_pricechanges\nsome text here...', 'snl_realestate_pricing_eap_return_5y\nsome text here...', 'snl_realestate_pricing_eap_rates_10yrnote\nsome text here...']

If you want to break this up you can map a split, or you can use it intact if you're doing something else.
>>> list(map(lambda x: x.split("\n"), results))
[['snl_realestate_pricing_eap_pricechanges', 'some text here...'], ['snl_realestate_pricing_eap_return_5y', 'some text here...'], ['snl_realestate_pricing_eap_rates_10yrnote', 'some text here...']]

If you want to get rid of a certain number of lines you could so something like this:
new_results = list()
for res in map(lambda x: x.split("\n"), results)
    try:
        new_results.append([res[0]] + res[8:])
    except IndexError:
        continue

This should keep the first line and anything from line 9 and above. It would probably be tough to do what you want with a pure regular expression, so processing after you get the chunks you want as lists of strings is the way that I'd go.

A: results = re.findall(r'table_name:\s+([a-z _0-9]+)\n(.*?)\sid: validate',lines,flags=re.DOTALL)


text:
Q: Magento Configurable Product Attributes hey guys, having an issue with magento which i just cant seem to find a solution to.
i have tried many ways of getting a configurable products attributes (simple products) and listing them, now i have them listing from 2 ways but the way im working with is below
$confAttributes = @$_product->getTypeInstance(true)->getConfigurableAttributesAsArray($_product);

    $sizes = array();

    foreach($confAttributes AS $atts){
        //print '';//'
'.print_r($atts).'
';
        if($atts['label'] == 'Size'){

            foreach($atts['values'] AS $val){

                $sizes[] = $val['store_label'];

            }

        }

    }

my only problem with this now is i need to only pull back the size attributes which are in stock - looked through mage files to find solution but just cant see anything - the result i need is done in config product php file but i cant access it from in the code where i need to list the size attribute.
any help would be great, thanks!

A: Solution:
You can get easily all configurable(product) details page information on any other PHTML file by using following code:
e.g.: in my case i'm getting details on catalog/product/list.phtml.

        <?php
        $temp = new Mage_Catalog_Block_Product_View_Type_Configurable();
        $temp->setData('product', $_product);
        $_attributes = Mage::helper('core')->decorateArray($temp->getAllowAttributes());
        ?>
        <?php if ($_product->isSaleable() && count($_attributes)):?>
            <?php foreach($_attributes as $_attribute): ?>
            <?php
                $prices = $_attribute->getPrices();
                foreach($prices as $price) {
                    echo $price['pricing_value'] . "
";
                }
            ?>
            <?php endforeach; ?>

        <?php endif;?>

Thanks,

A: found the solution, i had to use the above what i had already coded and use assosicated products for the size and then check the stock levels and put them into an array and check the stock when building my attribute list - works great - anyone else have a better solution please share :D thanks


text:
Q: PHP upload problems I'm am completely stumped. I'm trying to upload a simple photo via HTTPS. I've done this countless times, but this one time it's not working.
Here's the situation. I'm using a very simple yet robust file upload script, simple input=file, etc. and submit button to upload using POST, from there PHP takes over and does the rest. Once over on the php side I went through some problem solving/debugging and noticed that the file name was a bunch of goop... uploads/1.��8D��J��Q��9. certainly not the file i choose.
I'm not sure if this is a problem with the SSL, HTML5, or PHP. All other data passed through ends up very readable in the DB.
I've noticed something new in the file upload box of c:\fakepath, i've used HTML5 for the past several months and haven't seen this, looked it up and saw it's an HTML5 security feature. dont know if that's causing the problem or not?
Ok so I've verified with a friend (incase I was going crazy) that the HTML and PHP is fine.
I have even broken it down and went super simple with still no luck...
$uploaddir = 'uploads/';

$uploadfile = $uploaddir . basename($_FILES['photo']['name']);
$filename = $_FILES['photo']['name'];
if (move_uploaded_file($_FILES['photo']['tmp_name'], $uploadfile)) {
    echo "Alls good.";
}

Also on the HTML page I am using the jquery plugin "niceforms" I have turned this off to rule it out, and still does not work.
Thank you.

A: I am wondering whether you declared your from like the one below:
<form enctype="multipart/form-data" action="uploader.php" method="POST">
   <input type="hidden" name="MAX_FILE_SIZE" value="100000" />
   Choose a file to upload: <input name="uploadedfile" type="file" /><br />
   <input type="submit" value="Upload File" />
</form>

You should declare the enctype if you upload something.

A: It's always the simple things isn't it? I think you may be overlooking the relative upload dir path that you are moving the file to. I wouldn't use a relative path here.
$uploaddir = 'uploads/';

Instead, try using the full file system path to the upload directory. This is usually the document root concatenated with your 'uploads' directory.
$_SERVER['DOCUMENT_ROOT'] or dirname(__FILE__)

...should help define the path.
$uploaddir = $_SERVER['DOCUMENT_ROOT'].'/uploads/';


text:
Q: How do i disable vertical scrolling but enable horizontal scrolling in collectionview swift 4? when I disable scrolling. It disabled for both horizontal and vertical.
how do I disable scroll for only vertical only?
settings for collectionview

A: It's not possible to scroll collectionView in both directions. Either it will scroll horizontally or vertically.
User scrollDirection to specify your desired scroll direction.
if let flowLayout = collectionView.collectionViewLayout as?  UICollectionViewFlowLayout {
    flowLayout.scrollDirection = .horizontal
    flowLayout.scrollDirection = .vertical
}


text:
Q: Flowpaper Zine, How to show pdf in single-page mode instead of two-page mode, by default? When I open a document in Zine PHP server side, it opens in two-page mode.
I have to click on menu bar in order to switch to single-page mode.
Is there anyway to open the PDF document in single-page mode by default.

A: Set the following parameter to force single page mode:
InitViewMode : 'Portrait',


text:
Q: How to find $\#\{1\le x\le 5^k:5^k|(x^4-1)\}$? Find $\#\{1\le x\le 5^k:5^k|(x^4-1)\}$. I am not so sure how it is done, nor am I completely sure if it is about any specific $k$ or all of them together. What I did arrive at, not being really sure, is:
If $k=0$, the answer is $1$, I guess, so suppose $k>1$.
I need to have $x^4\equiv 1 \pmod{5^k}$ satisfied. I know it is for $x\equiv 1 \pmod{5^k}$. Since $5^k=5^{k-1}\cdot 4+5^{k-1}=4\cdot5^{k-1}+4\cdot5^{k-2}+5^{k-3}=4(5^{k-1}+...+5^2+5)+5\equiv 1 \pmod4$, then by a theorem taught in class, $x\equiv -1$ is a primitive root modulo $5^k$. That is, $x=5^k-1\in \{1\le x\le 5^k:5^k|(x^4-1)\}$. So $\#\{1\le x\le 5^k:5^k|(x^4-1)\}\ge 2$. I am stuck at the moment. I don't know how to find more $x$ solutions such that $x^4\equiv 1 \pmod{5^k}$. How have my argues been so far? I could really use your guiding.

A: $G=\left(\mathbb{Z}_{/(5^k\mathbb{Z})}\right)^*$ is a cyclic group having order $o(G)=4\cdot 5^{k-1}$ and we are just looking for the number of $g\in G$ such that $o(g)$ is $1$,$2$ or $4$. Assuming that $G=\langle h \rangle$, such elements are $h^{o(G)},h^{o(G)/2},h^{o(G)/4}$ and $h^{3 o(G)/4}$, so their number is:
$$ \varphi(1)+\varphi(2)+\varphi(4) = \sum_{d\mid 4}\varphi(d) = 4$$
no matter what $k$ is.

A: First note that if $x$ works for $k+1$ then $x$ (reduced modulo $5^k$) also works for $k$, so every solution for $k+1$ comes from a solution for $k$.
Now suppose we have a solution for $k$, that is, $a^4-1\equiv0\bmod{5^k}$. Let $b=a+5^kt$; then there is exactly one value of $t$ in $\{\,0,1,2,3,4\,\}$ such that $b$ is a solution for $k+1$. We see this as follows.
$b^4-1=a^4+4a^35^kt+5^{2k}c-1$ for some $c$, so dividing $b^4-1\equiv0\bmod{5^{k+1}}$ through by $5^k$ we get $${a^4-1\over5^k}+4a^3t\equiv0\bmod5$$ Since $a\not\equiv0\bmod5$, this equation has a unique solution $t$, and we are done.
All I have done here is I have gone through the standard proof of Hensel's Lemma for this particular congruence.


text:
Q: Sending PDF from jsPDF to controller via ajax Guys how can I send the jsPDF file to the controller while also  including  the  model.  I  believe I  have  to change the ajax data: piece, This however is  eluding me.  Any help would  be appreciated.
Model:
public class PartialReportModel
{
    public List<ShiftReportDetail> ReportDetails { get; set; }
    public ShiftReport Report { get; set; }
    public byte[] testingImg { get; set; }
    public IFormFile pdf { get; set; }
    public List<UserListsForSignatures> ListOfNames { get; set; }
    public List<ProductCodes> ProductsList { get; set; }
    public List<EquipList> Equipment { get; set; }
    public List<CodeTable> CodeList { get; set; }
}

Controller:
    [HttpPost]
    public async Task<IActionResult> EditReport(PartialReportModel model,IFormFile Test)
    {
        // do something else here with pdf and model
        return Json(1);
    }

JS:
$(document).on("click", "#SubmitReportEdits", function () {
var pdf;
html2canvas(document.querySelector("#mod1")).then(canvas => {
    var imgData = canvas.toDataURL(
        'image/png');
    var doc = new jsPDF('p', 'mm', 'a4', true);
    var width = doc.internal.pageSize.width;
    var height = doc.internal.pageSize.height;
    doc.addImage(imgData, 'PNG', 10, 10, width - 20, height - 10);
    pdf = doc.output('blob');
    //doc.save('test.pdf');
});
// ajax the thing
$.ajax({
    type: "POST",
    url: $("#EditReportForm").attr("action"),
    data: $("#EditReportForm").serialize() + "&Test="+pdf,
    success: function () {
        // close the modal
        // reload the table
        $('#ReviewReport').modal('toggle');
        $('#NotificationDiv').append( // change
            "

        " + "Report has been edited. Thank you." +
            "<button type='button' class='close' data-dismiss='alert' aria-
        label='Close'>" + "×" + "</button>" + "

"
        );
     }
  });
});

Currently I can see my model stuff but the pdf side is null.

A: Because we all have deadlines :/,  I am going to use this method to work this for now  until a  better answer comes along.
First is to convert the file to a base64 string, Then set that to a  value inside the form. Have  a hidden  input to receive the value. This case string pdf.  Then pass it along the ajax.  We now see the value in the controller side. Also have to use jpeg as PNG was too large a file and was getting 413 server errors. Code_debt++
model:
public string pdf { get; set; }

HTML5:
<input asp-for="pdf" hidden/>

Javascript:
$(document).on("click", "#SubmitReportEdits", function () {
html2canvas(document.querySelector("#mod1")).then(canvas => {
    var imgData = canvas.toDataURL(
        'image/jpeg');
    var doc = new jsPDF('p', 'mm', 'a4', true);
    var width = doc.internal.pageSize.width;
    var height = doc.internal.pageSize.height;
    doc.addImage(imgData, 'jpeg', 10, 10, width - 20, height - 10);
    var pdf = doc.output('datauristring').slice(28); // wipe first28chars
    //saving the base64
    $('#pdf').val((pdf));
    // ajax the  thing
    $.ajax({
        type: "POST",
        url: $("#EditReportForm").attr("action"),
        data: $("#EditReportForm").serialize(),
        success: function () {
            // close the modal
            // reload the table
            $('#ReviewReport').modal('toggle');
            $('#NotificationDiv').append( // change
                "
 " + "Report has been edited. Thank you." +
                "<button type='button' class='close' data-dismiss='alert' aria-label='Close'>" + "×" + "</button>" + "
"
            );
        }
    });
  });
 });

Controller Side:


text:
Q: Unable to use GET method in console application I have created a web API in which CRUD operations are performed. Now I wanted to test it on real time basis, so I decided to make a console application by following this tutorial. The tutorial provides the code in which while running the application the code its self created a product and get, update and delete it. But I want to use user input. I am successful in creating product(s). But while getting it i am facing an issue, see my code
Class
class Product
{

    [Key]
    public string Id { get; set; }

    [Required]
    public string Name { get; set; }

    [Required]
    public decimal Price { get; set; }

    [Required]
    public string Category { get; set; }
}

Console
static HttpClient client = new HttpClient();

    static void ShowProduct(Product product)
    {
        Console.WriteLine($"Name: {product.Name}\tPrice: {product.Price}\tCategory: {product.Category}");
    }

    static async Task<Uri> CreateProductAsync(Product product)
    {
        HttpResponseMessage response = await client.PostAsJsonAsync("api/product/", product);
        response.EnsureSuccessStatusCode();

        // return URI of the created resource.
        return response.Headers.Location;
    }

    static async Task<Product> GetProductAsync(string path)
    {
        Product product = null;
        HttpResponseMessage response = await client.GetAsync(path);
        if (response.IsSuccessStatusCode)
        {
            product = await response.Content.ReadAsAsync<Product>();
        }
        return product;
    }

static async Task RunAsync()
    {
        int a;
        decimal price = 0;
        string name = null, category = null;
        char option;

        client.BaseAddress = new Uri("http://localhost:7361/");
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        try
        {
            label:
            Console.Write("1. Create a product\n");
            Console.Write("2. View products\n");
            Console.Write("3. Update a product\n");
            Console.Write("4. Delete a product\n");
            Console.Write("5. Exit\n");

            Console.WriteLine("\nEnter your choice: ");
            a = Convert.ToInt32(Console.ReadLine());

            switch(a)
            {
                case 1:

                    Console.WriteLine("Enter name of the product: ");
                    name = Convert.ToString(Console.ReadLine());

                    Console.WriteLine("\nEnter price of the product: ");
                    price = Convert.ToDecimal(Console.ReadLine());
                    Console.WriteLine("\nEnter category of the product: ");
                    category = Convert.ToString(Console.ReadLine());

                    // Create a new product
                    Product product = new Product { Name = name, Price = price, Category = category };

                    var url = await CreateProductAsync(product);
                    Console.WriteLine($"Created at {url}");

                    Console.WriteLine("Want to create more product(s)? (y/n): ");
                    option = Convert.ToChar(Console.ReadLine());

                    if(option == 'y' || option == 'Y')
                    {
                        Console.Clear();
                        goto case 1;
                    }
                    else if(option == 'n' || option == 'N')
                    {
                        Console.Clear();
                        goto label;
                    }

                    break;

                case 2:

                    // Get the product

                    product = await GetProductAsync(url.PathAndQuery);
                    ShowProduct(product);

                    break;

                   //case 3:...
                   //case 4:...

                case 5:

                    Environment.Exit(0);

                    break;
            }
}

In case 2 at product = await GetProductAsync(url.PathAndQuery);, I am unable to use url variable as it says Use of unassigned local variable 'url'.
Also I can't declare var outside it because it will be not initialized to anyone.
I have tried to change the type from var to string but still unable to perform the task.
Any help would be highly appreciated

A: Share your tips on how to bribe the compiler to allow use of unassigned variable ;)
You're trying to use variable url within case 2: although that variable doesn't exist within the scope of this case. It seems you have declared url within case 1: and technically this variable can't be access past the break statement closing case 1.
Go back a step and have a quick read on variable scope within switch statement in c#
A quick fix is to delcare Uri url just before the switch(), so it's accessible inside all of the cases in the switch. Just make sure you either give it an initial value or add a default: statement and initialize it there before using it further down in the code.


text:
Q: Dyanmic Endorsement Policy I am actually new to Hyperldeger fabric framework. I am working on research project where I want to select specific Endorsers from my end. Can we really do that ?
As far as I know, the Endorsement policy will be always in the syntax of "AND(Org1MSP.peer,Org2MSP.peer)". But I want to select the individual peers of the organization and currently it seems impossible. Is there any other workaround ?
Please put some light on this.

A: From your client, you can choose to select whatever endorser peers you prefer for each transaction through Transaction.setEndorserPeers(peers). But it is a client decision, not a network restriction. Another client could choose any other endorser selection strategy (as long as it fulfills the endorsement policies of the chaincode). At endorsement policy level, you cannot require specific peers.


text:
Q: links.append() does not show all the image links as a list I need to scrape 29 images of this hotel. With the code below, the output is each link separately every time I run the cell. Even though I used links.append(), I need to re-run the cell in order to get another image.
r = rq.get("https://uk.hotels.com/ho177101/?q-check-out=2020-04-18&FPQ=3&q-check-in=2020-04-17&WOE=6&WOD=5&q-room-0-children=0&pa=1&tab=description&JHR=2&q-room-0-adults=2&YGF=2&MGT=1&ZSX=0&SYE=3#:WO")

soup = BeautifulSoup(r.text, "html.parser")

links = []

x = soup.select('img[src^="https://exp.cdn-hotels.com/hotels/1000000/560000/558400/558353"]')

for img in x:
    links.append(img['src'])

#os.mkdir("hotel_photos")

for l in links:
    print(l)

Thank you in advance!

A: Try this:
links = []

x = soup.select('a[href^="https://exp.cdn-hotels.com/hotels/1000000/560000/558400/558353"]')

for img in x:
    links.append(img['href'])

But, this will only work for that specific link, if you need a code that would scrape any link you provide, because this "https://exp.cdn-hotels.com/hotels/1000000/560000/558400/558353" changes depending on the hotel, so this would be a better approach:
x = soup.select("li[id^='thumb-']")
for i in x:
    links.append((next(i.children, None)["href"]))

for l in links:
    print(l)

PS: If you need after that to download the pictures, make sure to replace "&w=82&h=82" with "&w=773&h=530" to match the picture displayed.


text:
Q: How to return new table when join multi table in ASP.NET MVC public List<Book> getListBooks(int top)
    {
        var result = (from book in db.Books
                      join author in db.Authors on book.AuthorID equals author.ID
                      join publisher in db.Publishers on book.PublisherID equals publisher.ID
                      join category in db.BookCategories on book.CategoryID equals category.ID
                      join catalog in db.BookCatalogs on category.catalogID equals catalog.ID
                      where book.Status == true
                      select new
                      {
                          ID = book.ID,
                          Name = book.Name,
                          Alias = book.Alias,
                          Price = book.Price,
                          Quanlity = book.Quality,
                          ViewCount = book.ViewCount,
                          Status = book.Status,
                          Image = book.Image,
                          MoreImages = book.MoreImages,
                          PublicationDate = book.PublicationDate,
                          BookCover = book.BookCover,
                          Catalog = catalog.Name,
                          Category = category.Name,
                          Publisher = publisher.Name,
                      });
        return result.ToList();
    }

Severity  Code    Description Project File    Line    Suppression State
  Error   CS0029  Cannot implicitly convert type 'System.Collections.Generic.List<>' to 'System.Collections.Generic.List'  Model

A: You can't convert anonymous type directly to List<T>, you have to specify the Class/Type instead.
Set select new to select new Book for conversion.
public List<Book> getListBooks(int top)
{
    var result = (from book in db.Books
                  join author in db.Authors on book.AuthorID equals author.ID
                  join publisher in db.Publishers on book.PublisherID equals publisher.ID
                  join category in db.BookCategories on book.CategoryID equals category.ID
                  join catalog in db.BookCatalogs on category.catalogID equals catalog.ID
                  where book.Status == true
                  select new Book
                  {
                      ID = book.ID,
                      Name = book.Name,
                      Alias = book.Alias,
                      Price = book.Price,
                      Quanlity = book.Quality,
                      ViewCount = book.ViewCount,
                      Status = book.Status,
                      Image = book.Image,
                      MoreImages = book.MoreImages,
                      PublicationDate = book.PublicationDate,
                      BookCover = book.BookCover,
                      Catalog = catalog.Name,
                      Category = category.Name,
                      Publisher = publisher.Name,
                  });
    return result.ToList();
}

Also, you can do like this as well.
public List<Book> getListBooks(int top)
{
    var result = (from book in db.Books
                  join author in db.Authors on book.AuthorID equals author.ID
                  join publisher in db.Publishers on book.PublisherID equals publisher.ID
                  join category in db.BookCategories on book.CategoryID equals category.ID
                  join catalog in db.BookCatalogs on category.catalogID equals catalog.ID
                  where book.Status == true
                  select new
                  {
                      ID = book.ID,
                      Name = book.Name,
                      Alias = book.Alias,
                      Price = book.Price,
                      Quanlity = book.Quality,
                      ViewCount = book.ViewCount,
                      Status = book.Status,
                      Image = book.Image,
                      MoreImages = book.MoreImages,
                      PublicationDate = book.PublicationDate,
                      BookCover = book.BookCover,
                      Catalog = catalog.Name,
                      Category = category.Name,
                      Publisher = publisher.Name,
                    }).AsEnumerable().Select(x => new Book
                    {
                      ID,
                      Name,
                      Alias,
                      Price,
                      Quanlity,
                      ViewCount,
                      Status,
                      Image,
                      MoreImages,
                      PublicationDate,
                      BookCover,
                      Catalog,
                      Category,
                      Publisher,
                    }).ToList();
return result.ToList();
}


text:
Q: Why can't I get the gotour with go get? So I decided I wanted to learn go, and so I started the tour. In stage 3 of that tour they recommend to use go to checkout a copy of the tour and run it locally, so I installed go for mac via the recommended installer package.
I then had the go command available, so I ran go get code.google.com/p/go-tour/gotour as it suggests in the tour.
It says "and then run the resultant gotour executable" in the tour. No executable was to be found.
The output from go get was this:
package code.google.com/p/go-tour/gotour: Get https://code.google.com/p/go-tour/source/checkout?repo=: EOF

I know EOF means end of file but I'm not sure as to whether that was an error message or not.
I have hg installed:
$ hg --version
Mercurial Distributed SCM (version 2.3.1)

And I set my $GOPATH (and the file doesn't appear there):
echo $GOPATH
/Users/alex/.golib

Running go env returns this:
GOROOT="/usr/local/go"
GOBIN=""
GOARCH="386"
GOCHAR="8"
GOOS="darwin"
GOEXE=""
GOHOSTARCH="386"
GOHOSTOS="darwin"
GOTOOLDIR="/usr/local/go/pkg/tool/darwin_386"
GOGCCFLAGS="-g -O2 -fPIC -m32 -pthread -fno-common"
CGO_ENABLED="1"

If it helps, I'm using fish as my shell.
What am I doing wrong?

A: a go get (contrary to go get -u) will get, compile and install the go module you want in $GOPATH.
The executable gotour will be in $GOPATH/bin.
So make sure you have your $GOPATH/bin in your path.
When executed, you should see:
2012/09/15 10:43:57 Serving content from $GOPATH/src/code.google.com/p/go-tour
2012/09/15 10:43:57 Open your web browser and visit http://127.0.0.1:3999/

Note (personal preference): I would use a more visible path than /Users/alex/.golib: /Users/alex/go
GOPATH isn't just to get some libs, but to develop all your go projects.