text:
Q: J2EE war file redeployment changes not reflected I created the the file index.jsp as below
<form action="" method="POST">

    First Name: <input type="text" name="firstName" size="20">

    Surname: <input type="text" name="surname" size="20">

    <input type="submit" value="Submit">

</form>

I export it to .war and everything works fine. Then later I modified index.jsp, added in the form action to
<form action="GreetingServlet" method="POST">

    First Name: <input type="text" name="firstName" size="20">

    Surname: <input type="text" name="surname" size="20">

    <input type="submit" value="Submit">

</form>

I exported it again to .war, but the changes were not reflected. When I view source, the form action is still equal to blank. I have restarted apache as well. I view the log, it shows me that it has been redeployed.. but the changes were not reflected.
I have tried with different browsers, restart eclipse to see if the changes are saved, restart apache. Any advice? Thank you

A: What you are doing, the tools you are using, how you are using them, etc is totally unclear. It would be really helpful if you could give more details on your context and clarify what actions you are performing exactly. Currently, it's pretty hard to help you without guessing...
Just in case, my guess is that you actually didn't redeploy the WAR i.e. you didn't copy it to the webapps directory of Apache Tomcat (the fact that you are using Apache Tomcat is my second guess as Apache commonly refers to Apache HTTPD, the web server).

A: What does "export to WAR" mean to you?  I assume you mean create a new WAR and redeploy that to Tomcat.  Please confirm if this is true.
I'd also wonder if that action URL should be "/GreetingServlet".
Is GreetingServlet in a package?  Is it mapping in your web.xml file?  Can you invoke GreetingServlet by typing the URL into a browser?  If you can't contact it, I wouldn't expect your index.jsp to do so, either.
Is the index.jsp a <welcome-file> in your web.xml?
Leave Eclipse out of the picture for a moment.  Can you create a WAR file and deploy it to Tomcat successfully?
Which version of Tomcat are you running?  JDK?  Operating system?
It would help in the future if you would provide these kinds of details in your original question.  Help us help you.


text:
Q: Why does my implementation of strlcat gives a segmentation fault when the original does not? I am writing a re-implementation of strlcat as an exercise. I have perform several tests and they produce similar result. However on one particular case, my function gives an segmentation fault error while the original does not, could you explain to me why? I am not allowed to use any of the standard library function, that is why I have re-implemented strlen().
Here is the code I have written :
#include <stdio.h>
#include <string.h>

int ft_strlen(char *s)
{
    int i;

    i = 0;
    while (s[i] != '\0')
        i++;
    return (i);
}

unsigned int    ft_strlcat(char *dest, char *src, unsigned int size)
{
    size_t  i;
    int     d_len;
    int     s_len;

    i = 0;
    d_len = ft_strlen(dest);
    s_len = ft_strlen(src);
    if (!src || !*src)
        return (d_len);
    while ((src[i] && (i < (size - d_len - 1))))
    {
        dest[i + d_len] = src[i];
        i++;
    }
    dest[i + d_len] = '\0';
    return (d_len + s_len);
}

int main(void)
{
    char s1[5] = "Hello";
    char s2[] = " World!";

printf("ft_strcat :: %s :: %u :: sizeof %lu\n", s1, ft_strlcat(s1, s2, sizeof(s1)), sizeof(s1));
    // printf("strlcat :: %s :: %lu :: sizeof %lu\n", s1, strlcat(s1, s2, sizeof(s1)), sizeof(s1));
}

The output using strlcat is : strlcat :: Hello World! :: 12 :: sizeof 5. I am on macOS and I am using clang to compile if that can be of some help.

A: ft_strlcat() is not so bad, but it expects pointers to strings.  main() is troublesome: s1 lacks a null character: so s1 is not a string.
//char s1[5] = "Hello";
char s1[] = "Hello"; // Use a string

s1[] too small for the concatenated string "HelloWorld"
char s1[11 /* or more */] = "Hello"; // Use a string

"%lu" matches unsigned long.  size_t from sizeof matches "%zu".

Some ft_strlcat() issues:
unsigned, int vs. size_t
unsigned, int too narrow for long strings.  Use size_t  to handle all strings.
Test too late
if (!src || ...) is too late as prior ft_strlen(src); invokes UB when src == NULL.
const
ft_strlcat() should use a pointer to const to allow usage with const strings with src.
Advanced: restrict
Use restrict so the compiler can assume dest, src do not overlap and emit more efficient code - assuming they should not overlap.
Corner cases
It does not handle some pesky corner cases like when d_len >= size, but I will leave that detailed analysis for later.

Suggested signature
// unsigned int    ft_strlcat(char *dest, char *src, unsigned int size)
size_t ft_strlcat(char * restrict dest, const char * restrict src, size_t size)

Some untested code for your consideration:

*

*Tries to mimic strlcat().

*Returns sum of string lengths, but not more that size.

*Does not examine more than size characters to prevent reading out of bounds.

*Does not append a null character when not enough room.

*Does not check for dst, src as NULL.  Add if you like.

*Does not handle overlapping dest, src.  To do so is tricky unless library routines available.

*Use unsigned char * pointer to properly handle rare signed non-2's complement char.
size_t my_strlcat(char * restrict dst, const char * restrict src, size_t size) {
  const size_t size_org = size;

  // Walk dst
  unsigned char *d = (unsigned char*) dst;
  while (size > 0 && *d) {
    d++;
    size--;
  }
  if (size == 0) {
    return size_org;
  }

  // Copy src to dst
  const unsigned char *s = (const unsigned char*) src;
  while (size > 0 && *s) {
    *d++ = *s++;
    size--;
  }
  if (size == 0) {
    return size_org;
  }

  *d = '\0';
  return (size_t) (d - (unsigned char*) dst);
}

If the return value is less than size, success!

A: *

*s1 is not even long enough to accommodate the "Hello"

*Use the correct type for sizes.
size_t ft_strlcat(char *dest, const char *src, size_t len)
{
    char *savedDest = dest;
    if(dest && src && len)
    {
        while(*dest && len)
        {
            len--;
            dest++;
        }
        if(len)
        {
            while((*dest = *src) && len)
            {
                len--;
                dest++;
                *src++;
            }
        }
        if(!len) dest[-1] = 0;
    }
    return dest ? dest - savedDest : 0;
}

*Also your printf invokes undefined behaviour as order of function parameters evaluation is not determined. It should be:

int main(void)
{
    char s1[5] = "Hello";     //will only work for len <= sizeof(s1) as s1 is not null character terminated
    char s2[] = " World!";

    size_t result = ft_strlcat(s1, s2, sizeof(s1));
    printf("ft_strcat :: %s ::  %zu :: sizeof %zu\n", s1, result, sizeof(s1));
}

https://godbolt.org/z/8hhbKjsbx

redpajama_set_name: RedPajamaStackExchange


text:
Q: Android - Obtaining view for Activity title and attaching click listener I am trying something crazy here. I would like to attach a click listener to the title of my activity. For this I either need the title view's id or the view itself. Just to keep in mind, I am not defining a custom view for the title. All I do is set the title in the manifest for the appropriate Activity. I would now like to attach a click listener to the title.
How can this be achieved? Some direction or even a solution would be most appreciated. Thanks.

A: Place this on onCreate of your activity
final int abTitleId = getResources().getIdentifier("action_bar_title", "id", "android");
findViewById(abTitleId).setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
    //Do something
    }
});


text: Q: Managing Partners without the use of Communities I have recently implemented Salesforce to our company and we would need to manage some of our partners. Ie. Allow Partners to update leads that are assigned to them through Salesforce. The Partner Communities feature in Salesforce is above our budget so we cannot purchase this feature. Does anyone have any ideas on an alternative on how we can manage this requirement without using Partner Communities?


text:
Q: JavaFX When a predefined button is used in a for loop, it doesn't show up I have a ListView and it contains an unknown amount of BorderPanes. To make these BorderPanes i am using a constructor which makes an ArrayList of them. Each BorderPane contains a has a Label on the left and 2 buttons on the right. The dates are always unique but the buttons are always the same, and i need to use them outside the constructor for button.setOnAction.
The problem is, if the Button is defined outside the for loop inside the constructor, the button will simply not appear on the list, if it is created inside the for loop it does.
Code with program open

public ArrayList<BorderPane> makeDateListInfo(String fileName, Button buttonDateDelete, Button buttonDateEdit) {
        ArrayList<String> dateArray = getDateArray(fileName);
        ArrayList<BorderPane> outputList = new ArrayList<>();
        for(int i = 1; i < dateArray.size(); i++) {
            String[] arrOfText = dateArray.get(i).split("Date: ");
            arrOfText = arrOfText[1].split("\n\nWeight:");
            String date = arrOfText[0];
            arrOfText = arrOfText[1].split(" Kg|Kg");
            String weight = arrOfText[0];

            BorderPane dateBorderPane = new BorderPane();
            Label dateInfo = new Label("Date: " + date +  "    Weight: " + weight);

            Button dateDelete = new Button("Delete");
            Button dateEdit = new Button("Edit");
            HBox buttons = new HBox();
            buttons.getChildren().addAll(dateDelete, dateEdit);

            dateBorderPane.setLeft(dateInfo);
            dateBorderPane.setRight(buttons);
            outputList.add(dateBorderPane);
        }
        return outputList;
    }

Code and program with the changed code

Button buttonDateDelete, Button buttonDateEdit are defined in the exact same way as inside the for loop outside of it, i don't understand why it doesn't show up.
If they aren't defined outside i can't really interact with the button anymore and tell it what to do.


text:
Q: Lendo 2 vezes um array Bom tenho o seguinte array:
$teste = array(1,2,3,4);

Quando quero escrever ele na tela eu faço assim?
foreach ($teste as $c) {

    echo $c;

}

O resultado é: 1234
Preciso escrever o resultado 2 vezes e seguindo a ordem, assim: 11223344
Alguém sabe como fazer isso usando apenas um foreach?
OBS: O código que está dentro do foreach e grande e não quero que repetir ele, quero achar alguma maneira de fazer isso no foreach

A: Eu recomendaria você refatorar o seu código. Se ele é reutilizável, poderia muito bem estar definido em uma função. Nesse caso, bastaria fazer:
foreach ($teste as $c) {
    echo foo($c), foo($c);
}

Mas se quiser contornar isso, você pode percorrer o array através de um gerador:
function doubleForeach($arr) {
    foreach($arr as $item) {
        yield $item;
        yield $item;
    }
}

Assim, basta você fazer:
$teste = array(1,2,3,4);
$iterator = doubleForeach($teste);

foreach ($iterator as $c) {
    echo $c;
}

Veja funcionando no Repl.it

A: Como alternativa, podes controlar usando outra estrutura de repetição
foreach ($teste as $c) {
  for (int $i=0; $i<2; $i++){
    echo $c;
  }
}


text:
Q: Android Studio - For loop delay with Handler Thread I am trying to set a for loop with a delay using the handler thread. But when i set up the handler thread within the for loop i cannot use the index of the for loop as it says it must be called final, however that does not work either. Does anyone know how to fix this?

A: To Sleep Thread for while time you have to set for loop outside of postDelayed like below way. In that way you can acheive the Index of the loop.
final ImageButton[] all= {btn1, btn2, btn3, btn4};
Handler handler1 = new Handler();
for (int a = 1; a<= all.length ;a++) {
    handler1.postDelayed(new Runnable() {

         @Override
         public void run() {

             //Here..
         }
         }, 1000 * a);
    }
}

A: I think you can use CountDownTimer:
new CountDownTimer(30000, 1000) {

    public void onTick(long millisUntilFinished) {
        mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
       //here you can have your logic to set text to edittext
    }

    public void onFinish() {
        mTextField.setText("done!");
    }

}.start();

How to make a countdown Timer in android?
Or even like this:
public void animateTextView(float initialValue, float finalValue, final TextView  textview) {

    ValueAnimator valueAnimator = ValueAnimator.ofFloat(initialValue, finalValue);
    valueAnimator.setDuration(1500);

    valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
        @Override
        public void onAnimationUpdate(ValueAnimator valueAnimator) {

            textview.setText(valueAnimator.getAnimatedValue().toString());

        }
    });
    valueAnimator.start();

}


text:
Q: Controls at the bottom of UIScrollView not working The UIButton in the scrollView is visible, but not accessible. I am using Constraints.
My UI structure is this:
- UIView
   - scrollView: UIScrollView
     - contentView: UIView
       - UIButton
       - UIButton
       - UIButton
       - ....
       - UIButton
I've already tried to set the contentSize of the scrollView. And the height of the contentView. Next to that I've tried to uncheck the checkbox Adjust Scroll View Insets in the storyboard of that ViewController without any luck. I've also set the priority of the Align Center Y to 250, and the priority bottom space to 250 of the contentView.
func updateScrollViewSize() {
    var contentRect = CGRect.zero
    for view in contentView.subviews {
        contentRect = contentRect.union(view.frame)
    }

    contentRect.size = CGSize(width: scrollView.contentSize.width, height: contentRect.height + 50)
    scrollView.contentSize = contentRect.size
    contentView.frame.size = contentRect.size
    contentView.layoutIfNeeded()
}

The button I try to reach has a Y value of: 1030.0
The height of the contentView is: 871.0

A: Step-by-step:
Add a scroll view to your view, background color red, constrain it 20-pts on each side:

Add a UIView as your "content view" to the scroll view (green background to make it easy to see), constrain it 0-pts on each side, constrain equal width and equal height to the scroll view. Important: change the Priority of the Height constraint to 250!

Add a UILabel to the contentView, constrain it 30-pts from the top, centered horizontally:

Add another label to the contentView, constrain it 300-pts from the first label, centered horizontally:

Add a UIButton to the contentView, constrain it 30-pts from the bottom, centered horizontally:

Now add a vertical constraint from the bottom of the second label to the top of the button, and set it to 400-pts:

As you see, this pushes the button off-screen past the bottom of the scroll view.
Run the app. You will be able to scroll down to see the button, and you'll be able to tap it.
Absolutely no code needed!

A: If you use AutoLayout, you don't needed to install frames manually.
You can try install constraints properly and content size will be right in this case and you won't have to install content size manually.
If you achieve this, I guess everything will work correctly.
You can follow this or this guide


text:
Q: react native camera undefined use strict';
import React, { Component } from 'react';
import {
  AppRegistry,
  Dimensions,
  StyleSheet,
  Text,
  TouchableHighlight,
  View
} from 'react-native';
import Camera from 'react-native-camera';

class BadInstagramCloneApp extends Component {
  render() {
    return (
      <View style={styles.container}>
        <Camera
          ref={(cam) => {
            this.camera = cam;
          }}
          style={styles.preview}
          aspect={Camera.constants.Aspect.fill}>
          <Text style={styles.capture} onPress={this.takePicture.bind(this)}>[CAPTURE]</Text>
        </Camera>
      </View>
    );
  }
  takePicture() {
    this.camera.capture()
      .then((data) => console.log(data))
      .catch(err => console.error(err));
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1
  },
  preview: {
    flex: 1,
    justifyContent: 'flex-end',
    alignItems: 'center',
    height: Dimensions.get('window').height,
    width: Dimensions.get('window').width
  },
  capture: {
    flex: 0,
    backgroundColor: '#fff',
    borderRadius: 5,
    color: '#000',
    padding: 10,
    margin: 40
  }
});

AppRegistry.registerComponent('AwesomeProject', () => BadInstagramCloneApp);

I used the following steps to resolve the issue :
Delete the node_modules folder - rm -rf node_modules && npm install
Reset packager cache - rm -fr $TMPDIR/react-* or node_modules/react-native/packager/packager.sh --reset-cache
Clear watchman watches - watchman watch-del-all
Recreate the project from scratch
But i still get an error.

A: Make sure you have made the settings right, including running $ react-native link react-native-camera and others according the documentation.

A: You can try to use
var Camera = require('react-native-camera')

A: Replace the line:
import Camera from 'react-native-camera';

With this line:
import {RNCamera} from 'react-native-camera';

Change <Camera></Camera> tag to <RNCamera></RNCamera>.
Remove the aspect attribute from RNCamera tag.


text:
Q: INNER JOIN + IN condition does not work I have 2 tables: Question and Quiz.
Quiz is a collection of Questions.
Quiz table looks like this:
QuizdId  |  QuestionIds (NVARCHAR50)
  1    | 1,2,3,4,5
  2    | 6,7,8,9

The structure of Question table is not relevant. Its primary key is ID (integer)
For a given question Id, I want to select all the Question Data
This SQL does not work (gives syntax error)
SELECT qs.* FROM Questions AS qs
INNER JOIN Quiz AS qz on qs.ID IN (qz.QuestionIds)
WHERE qz.QuizId = 2;

SQL error: #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'qz.QuestionIds where qz.QuizId = 2
The below SQL does not give expected result. It gives only 1 question with ID 6. I guess the reason is that QuestionIds (in Quiz table) is nvarchar field and ID (in question table) is integer.
SELECT * FROM Questions WHERE ID IN (SELECT QuestionIds FROM Quiz WHERE QuizId = 2)

What shall I do ?
I want to extract this via SQL / Procedures / Routines.

A: You can use FIND_IN_SET() to join your two tables,
SELECT  qs.*
FROM    Questions qs
        INNER JOIN Quiz qz
            ON FIND_IN_SET(qs.ID, qz.QuestionIDs) > 0
WHERE   qz.QuizID = 2

but the way I could suggest is to normalize your table into 3-table design.
Question Table

*

*QuestionID (PK)

*QuestionText

*other columns...
Quiz Table

*

*QuizID (PK)

*other columns...
Quiz_Question Table

*

*QuestionID (FK) -- Primary Key with QuizID

*QuizID (FK)

..and if you were using the 3 table design, the query would look like this:
SELECT  qs.*
FROM    Questions qs
        INNER JOIN Quiz_Questions qq
            ON qq.QuestionID=qs.ID
WHERE   qq.QuizID = 2


text:
Q: Laravel PHPSpreadsheet download error Estoy trabajando con Laravel 9 y la librería "phpoffice/phpspreadsheet", lo que deseo hacer es generar un excel pero descargarselo al usuario sin guardarlo, no me interesa que se guarde en el sistema, sólo que el usuario lo pueda descrgar.
He leído por todos lados y he intentado con todas las respuestas pero ninguna me ha funcionado. No sé porque me arroja un error de JSON.
Aclaro por las dudas que estoy trabajando con Livewire aunque esto no tiene nada que ver, ya he probado de generar un archivo y que lo guarde y funciona a la perfección, pero lo que no puedo hacer andar es el download
Hasta llegue a pensar que puede ser que tenga algún problema ya que estoy utilizando debian 11, pero no creo
Les dejo el código y el error que me arroja
Muchas gracias por adelantado!
P/D: Ya probé con ob_end_clean(); pero no funcionó
La sección de los headers lo saqué de la documentación oficial
https://phpspreadsheet.readthedocs.io/en/latest/topics/recipes/#redirect-output-to-a-clients-web-browser
Bueno ahora sí les pongo el código
public function exportExcel2()
    {
        $users = $this->getUsers();
        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();
        $sheet->setCellValue('A1', 'LISTADO DE USUARIOS DEL SISTEMA DE GESTIÓN DE MORA');
        $writer = new Xlsx($spreadsheet);
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="myfile.xlsx"');
        header('Cache-Control: max-age=0');
        $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
        ob_end_clean();
        $writer->save('php://output');
    }

A: porque no intentas guardando el archivo en el storage temporalmente y lo descargas, así no tienes que agregar los headers, así he trabajado y no  ha presentado ningún problema.

$path = "tmp/{$file_name}.xlsx";

$writer = new Xlsx($spreadsheet);

$writer->save(storage_path("app/{$path}"));

return Storage::download($path, "file_to_download.xlsx");


text:
Q: A way to refresh the page without resetting/clearing the forms on it I'm working on a page with 9 inputs and js that performs logic on those inputs before submitting it.  It's getting really annoying having to enter the information into the forms every time I want to see my javascript changes.
Is there a way to refresh the page without clearing the form?
P.S. I'm working in IE9+, Chrome, Firefox, and Safari.
Thanks in advance!

A: Apparently, there are few tools (if any) that do this (at least that I was able to find).  I've found a way to do this by writing a script that hijacks the window event loop and stores all the input values in a stringified cookie.  When you refresh the page, you can use window.onload to automatically repopulate the inputs.
If you (understandably) don't want to write your own script to do this, I've written one you are welcome to use on github.


text:
Q: Implementing TestFX in the Eclipse I would like to write tests to my project in JavaFX and I've read that I have to use TestFX, so I want to implement the library to my eclipse. But I still can't resolve my problem (look at picture). I was looking for a solution but it was unsuccessful. I've imported all the necessary jar files to use TestFX...
Have you any idea where can be a reason?
When I move my mouse on the "red light bulb" there is information "The type com.google.common.base.Predicate cannot be resolved. It is indirectly referenced from required .class files"
Eclipse Picture

A: You have to add the Jar of the Guava library to your classpath.

A: You don't have to use TestFX, it's just a good third party library. There are many other options like JUnit.


text:
Q: How to access data pulled in ViewControllerA in another ViewControllerB? What should be the best possible way to get the data from ViewControllerA to ViewControllerB.
Here ViewContollerA has the data pulled from web by JSON parsing.
And ViewControllerB has the text view and labels that are to be filled by the data pulled in ViewControllerA
Any guide or reference would be greatly appreciated.

A: There are multiple ways to do this.

*

*pass data through segues

*notification center

*static object/service

*and more!

I found how-ios-view-controllers-communicate-with-each-other for you


text:
Q: Reinserting data after row deletion in cassandra using Pelops I am trying to re-insert data for same row-key after deleting the row  but they are not getting inserted. Neither any exception is thrown.
I am using Pelops RowDeletor to delete the row data (Note that the row-key is still shown with no columns) after deleting. If I truncate the table and reinsert columns gets inserted.
I have tried changing consistency levels from ANY to ONE to ALL. Any ideas as to whats the problem or should I go for Hector client?

A: This can be an issue with the tombstones (keys without columns) if your timestamp on your column is in the past.  Make sure this is not the case, and you should be able to insert.  Note that this is not an issue with Pelops but is related to Cassandra's conflict resolution.  If you have a tombstone that's newer than the insert, you will have this issue because Cassandra sees the delete as having happened after the insert.


text:
Q: use record from same model as foreignkey in django my model is as follows :
class Profile(model.Models):
    name = models.CharField(max_length = 20)
    full_name  = models.CharField(max_length = 20)
    husband_spouse = models.ForeignKey(Profile, on_delete=models.CASCADE)

on doing python manage.py makemigrations I get the following error : NameError: name 'Profile' is not defined
Question : How should I use another record of the same model as a foreignkey in my current model
TIA

A: This is because at that point Profile is not yet defined, you can use a string literal 'self' in that case:
class Profile(model.Models):
    name = models.CharField(max_length=20)
    full_name  = models.CharField(max_length=20)
    husband_spouse = models.ForeignKey(
        'self',
        on_delete=models.CASCADE
    )


text:
Q: Addition of angular momentum - normalization issue? If we have the raising and lowering operators for separate particles $J_1^\pm$ and $J_2^\pm$, we may define the total angular momentum operator $J$ and the corresponding raising and lowering operators as $J^\pm = J_1^\pm + J_1^\pm$. The intuition is difficult for me here since the left side lowers the z component of spin by one unit while the right side seems to do so by two units.
Now, say this acts on the two spin half particles in the state $\vert{\uparrow\uparrow}\rangle$. To preserve the norm, I need to have a factor of $\frac{1}{\sqrt 2}$ somewhere since I should get the state $\frac{1}{\sqrt 2} (\vert{\uparrow\downarrow}\rangle + \vert{\downarrow\uparrow}\rangle)$.
Yet the definition of any addition of angular momentum operator simple adds the two corresponding operators without normalization e.g. $J_z = J^1_z + J^2_z$. What gives?

A: $J_{\rm tot}^-$ only lowers the z component by 1 unit, not 2.
In $J_{tot} =J_1+J_2$ the $J_1$ acts only on the $j_1,m_1$ entries in $|J_1,m_1,j_2,m_2\rangle$ and the $J_2$ only on the $j_2,m_2$.
Thus
It's better   to write (as a mathematician would)
$$
J_{\rm tot}= J_1\otimes {\mathbb I}+ {\mathbb I}\otimes J_2
$$
and $$
|J_1,m_1,j_2,m_2\rangle= |j_1,m_1\rangle\otimes |j_2,m_2\rangle
$$
that makes what's going on more obvious. Each operator only acts on its own Hilbert space, and the total Hilbert space is the tensor product of the two spaces for the two separate spins. See  section 6.3.4 in https://courses.physics.illinois.edu/phys509/sp2018/bmaster.pdf
The "missing" $\sqrt 2$ is correct as $|\uparrow\uparrow\rangle$ is the $|j=1,m=1,\rangle$ state in  a spin-one multiplet where $J^-|j=1,m=1\rangle = \sqrt 2|j=1,m=0\rangle$.


text:
Q: How to get the names of the programs which are accessing a certain file/folder and blocking any other access to it?
Possible Duplicate:
Tool to determine what has locked a file

Sometime when I delete a file/folder, Windows 7 tells me that the file is accessed by other program and cannot be deleted. I close all the processes as much as I can but it is still blocked.
So, I wanna get a list of program that are accessing one file/folder. How can I do this in Windows 7?

A: Unlocker will do that.
It also lets you unlock the file with or without killing the locking process, and delete the file.
It's nicer than handle because it integrates into explorer.exe (adds an option to the right click menu).
(Note: deleting locked files can cause things to crash, if a program is in the process of using the file. On the other hand, sometimes programs hold file handles open well after they are actually done with the file (explorer.exe, I'm looking at you), so sometimes you can't really avoid using an unlocking utility.)

A: I use process explorer for this purpose all the tome. http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx

A: Use Handle.

Ever wondered which program has a
  particular file or directory open? Now
  you can find out. Handle is a utility
  that displays information about open
  handles for any process in the system.
  You can use it to see the programs that have a file open, or to see the
  object types and names of all the
  handles of a program.


text:
Q: How do I make an animation using HTML5 and CSS3? Are there free apps to do it? I'd like to put an animation in a web page using HTML5 and CSS3. Are there free apps that help to do that?

A: There are some really great tutorials out there. Have you tried Google yet?
I found this one particularly useful: http://css3.bradshawenterprises.com/
See also:
* http://coding.smashingmagazine.com/2011/09/14/the-guide-to-css-animation-principles-and-examples/
* https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Using_CSS_animations
* http://cferdinandi.github.io/spinners/


text:
Q: radio button checked and tabindex not working together As title says: its not working together
My Code:
<input type="radio" name="radio{{ tr.Id }}" value="y" tabindex="{{ tabindex }}">Correct
<input type="radio" name="radio{{ tr.Id }}" checked>Idk
<input type="radio" name="radio{{ tr.Id }}" value="n">Wrong

The tabindex is in this Code not working
when I remove checked tabindex="" is working
Im working with Twig and the Twig counter is correct ({{ tabindex}}) !!
Thanks in advance for every help :)
This Question might be a duplicate, but i just want to point out that checked and tabindex aren't working well together. Consider using a dropdown-menu as radio selection with tabindex and (in this case) selected


text:
Q: AWS SAM: How to create an S3 bucket with an already existing encryption key using SAM
I am a newbie to SAM (and CloudFormation) and I learned today that you can create a new bucket in adding something like this to the SAM yaml template:
Resources:
    my-great-new-bucket:
       Type:AWS::S3::Bucket

Does SAM offer a way to also add an already existing KMS encryption key to that newly created bucket (and to enable Bucket Key)?
With boto I would do exactly the following to achieve this:
 response = client.put_bucket_encryption(Bucket= bucketName, ServerSideEncryptionConfiguration={
        "Rules": [
            {
              "ApplyServerSideEncryptionByDefault": {
                "SSEAlgorithm": "aws:kms",
                "KMSMasterKeyID": myKeyArn
              },
              "BucketKeyEnabled": True
            }
          ]
        })

How can i transform this operation to the SAM template?

A: So S3::Bucket is not a SAM resource but a normal CloudFormation resource.
You can achieve this by changing KMS-KEY-ARN to the Key ID of your Key.
Resources:
  EncryptedS3Bucket:
    Type: 'AWS::S3::Bucket'
    Properties:
      BucketEncryption:
        ServerSideEncryptionConfiguration:
          - BucketKeyEnabled: true
            ServerSideEncryptionByDefault:
              SSEAlgorithm: 'aws:kms'
              KMSMasterKeyID: KMS-KEY-ARN


text:
Q: Use interfaces in JAX-WS web methods I need to use an interface as a parameter and as a return type in a JAX-WS web method. When starting my server I receive an IllegalAnnotationsException, which tells me that JAXB cannot handle interfaces.
I tried to annotate my class, method result and method parameters with @XmlRootElement and @XmlElement(type = ...) respectively, but this does not work.
How can I use an interface as an parameter and as a result type in a JAX-WS web method?

A: Take a look at @XmlJavaTypeAdapter. Maybe it will do the trick. More information available in here.


text:
Q: (Databricks Ad monetisation example) How do I find the latest match in a stream? In the blog post "Introducing Stream-Stream Joins in Apache Spark 2.3" joining clicks with impressions based on their adId is discussed:
# Define watermarks
impressionsWithWatermark = impressions \
  .selectExpr("adId AS impressionAdId", "impressionTime") \
  .withWatermark("impressionTime", "10 seconds ")   # max 10 seconds late

clicksWithWatermark = clicks \
  .selectExpr("adId AS clickAdId", "clickTime") \
  .withWatermark("clickTime", "20 seconds")        # max 20 seconds late

# Inner join with time range conditions
impressionsWithWatermark.join(
  clicksWithWatermark,
  expr("""
   clickAdId = impressionAdId AND
    clickTime >= impressionTime AND
    clickTime <= impressionTime + interval 1 minutes
    """
  )
)

I'd like to know if its possible to filter the resulting stream so that only the rows with latest clickTime are included in each "query interval".
The query interval is the interval given in the query join condition:
clickTime >= impressionTime AND
clickTime <= impressionTime + interval 1 minutes

So I might get the following sequence
{type:impression, impressionAdId:1, timestamp: 1}
{type:click, clickAdId:1, timestamp: 1}
{type:click, clickAdId:1, timestamp: 15}

And after t=60s or so spark emits the following row in the dataframe:
{impressionTimestamp: 1, clickTimestamp: 15: clickAddId: 1, impressionAdId: 1}

I only posted python code because that was what was in the article, answers with java or scala code are welcome too.


text:
Q: How do I disable map rotation entirely on my TF2 server? I have a private server. Before use, I just go in, exec a config, and change the level. Annoyingly, the server will sometimes switch to hydro or 2fort if we wait too long before starting a scrim.
I considered removing all maps but one (my desired default) from mapcycle.txt, but it seems like then, it would just switch to that one. I don't want to change mp_timelimit like "24/7 whatever map" servers, because it will get reset whenever I exec a match config anyway.
Can I just remove everything from mapcycle.txt and add something to my server.cfg to load up some particular map, say mge_training_v8_beta2, every time I restart? If so, what would I add? Does mapcycle.txt have to be populated?

A: There are lots of things you can do when running a server. I highly suggest you read up on https://wiki.teamfortress.com/wiki/Windows_dedicated_server and https://wiki.teamfortress.com/wiki/Dedicated_server_configuration
You can do a few things. First off, you can have more than one map cycle file. Second, you can have a config file per map. Just name a file mapname.cfg and put it in the cfg folder. Whenever your server changes to that map, it will run the cfg. This allows you to do things like change timelimit, switch the map cycle file to something else (like one that only has one map in it so it keeps changing to that map).
If you want to start your server with a specific map, add the +map mge_training_v8_beta2 command line option when running the server.
Use the mapcyclefile "my_mapcycle.txt" command to set the map cycle file to my_mapcycle.txt.


text:
Q: How to show Form1 from Form2 I want to close Form2 with a button(it belongs to Form2) also this button will show Form1.
private void button3_Click(object sender, EventArgs e)
    {
    Form1 form = new Form1();// It's wrong because we open a new object
    form.Show();
    this.Close();

    }

A: if you want to show Form 1 and close Form 2 you have to do:
IN FORM2:
    private void button3_Click(object sender, EventArgs e)
    {
        this.Close();
    }

IN FORM1:
    Form2 form2 = new Form 2(); //when you declare yur form 2
    form2.FormClosed += new FormClosedEventHandler(form2_FormClosed);

    void form2_FormClosed(object sender, FormClosedEventArgs e)
    {
        this.Visible = true;
    }


text:
Q: How to recursively retrieve folder with smartsheet API I'm working on a backup tool for smartsheet in python. I want to retrieve all the users file on my domain.
I don't know how to get the data but i don't know how to keep the Tree of folders like:
Folder A:
    - File A
    - Folder AB:
        *File AZ
        *File AE
        *Folder AC:
            File E

This above example is only subjective.
With Smartsheet when you retrieve the workspaces with :
ss.Home.list_all_contents()

here ss is smartsheet.Smartsheet(token)
You got that in return:
{
"folders": [
    {
        "id": 5709073300645764,
        "name": "folder 1",
        "permalink": "https://app.smartsheet.com/b/home?lx=Dsje3YKtpyZScrCX6Z1"
    }
],
"sheets": [
    {
        "id": 4583173393803140,
        "name": "sheet 1",
        "accessLevel": "OWNER",
        "permalink": "https://app.smartsheet.com/b/home?lx=Dsje3YKtpyZScrCX6Za",
        "createdAt": "2015-06-05T20:05:29Z",
        "modifiedAt": "2015-06-05T20:05:43Z"
    },
    {
        "id": 2331373580117892,
        "name": "Copy of sheet 1",
        "accessLevel": "OWNER",
        "permalink": "https://app.smartsheet.com/b/home?lx=Dsje3YKtpyZScrCX6Zb",
        "createdAt": "2015-06-05T20:05:29Z",
        "modifiedAt": "2015-06-05T20:05:43Z",
        "source": {
            "id": 4583173393803140,
            "type": "sheet"
        }
    }
],
"reports": [],
"templates": [],
"workspaces": [],
"sights": []
}

But nested folder looks like that:
{
    "id": 138433004889988,
    "folders": [
        {
            "id": 672830015727492,
            "folders": [
                {
                    "id": 3791044992100228,
                    "folders": [],
                    "reports": [],
                    "favorite": null,
                    "name": "3nested",
                    "templates": [],
                    "permalink": "",
                    "sheets": []
                }
            ],
            "reports": [],
            "favorite": null,
            "name": "2nested",
            "templates": [],
            "permalink": "",
            "sheets": [
                {
                    "accessLevel": "OWNER",
                    "userSettings": null,
                    "id": 2308634748184452,
                    "fromId": null,
                    "modifiedAt": "2017-08-26T07:30:23+00:00",
                    "attachments": [],
                    "resourceManagementEnabled": null,
                    "projectSettings": null,
                    "effectiveAttachmentOptions": [],
                    "favorite": null,
                    "showParentRowsForFilters": null,
                    "createdAt": "2017-08-07T08:17:20+00:00",
                    "version": null,
                    "rows": [],
                    "columns": [],
                    "readOnly": null,
                    "name": "file 2nested",
                    "permalink": "",
                    "owner": null,
                    "totalRowCount": null,
                    "ganttEnabled": null,
                    "source": null,
                    "dependenciesEnabled": null,
                    "ownerId": null,
                    "discussions": []
                }
            ]
        }
    ],
    "reports": [],
    "favorite": null,
    "name": "fnfd",
    "templates": [],
    "permalink": "",
    "sheets": [
        {
            "accessLevel": "OWNER",
            "userSettings": null,
            "id": 8542174187939716,
            "fromId": null,
            "modifiedAt": "2017-08-26T07:30:24+00:00",
            "attachments": [],
            "resourceManagementEnabled": null,
            "projectSettings": null,
            "effectiveAttachmentOptions": [],
            "favorite": null,
            "showParentRowsForFilters": null,
            "createdAt": "2017-08-03T18:16:29+00:00",
            "version": null,
            "rows": [],
            "columns": [],
            "readOnly": null,
            "name": "msp",
            "permalink": "",
            "owner": null,
            "totalRowCount": null,
            "ganttEnabled": null,
            "source": null,
            "dependenciesEnabled": null,
            "ownerId": null,
            "discussions": []
        }
    ]
}

the Tree of above json looks like that:
folder fnfd:
    - File msp.xlsx
    - Folder 2nested:
        -File file 2nested.xlsx
        -Folder 3nested

Question
How Can I retrieve recursively all those folder no matter the numbers of folder nested that you need to retrieve

A: You will need a standard recursive descent algorithm. For each call that returns a list of folders, you'll need to loop through the folder IDs and call ss_client.Folders.get_folder(folder_id) to retrieve the list of contained sheets and any child folders.


text:
Q: UISegmentedControl truncates segment titles I have a segmented control in my iPhone app that works great on ios6 but on ios7 the segment tiles are truncated (there is enough space for the text, but it truncates them anyway)
    self.segmentedControl.segmentedControlStyle = UISegmentedControlStyleBar;
self.segmentedControl.autoresizingMask = UIViewAutoresizingFlexibleWidth;
NSDictionary *defaultTextAttributes = [NSDictionary dictionaryWithObjectsAndKeys:defaultFont,
                                       UITextAttributeFont,
                                       defaultFontColor,
                                       UITextAttributeTextColor,
                                       nil];
[self.segmentedControl setTitleTextAttributes:defaultTextAttributes forState:UIControlStateNormal];

NSDictionary *selectedTextAttributes = [NSDictionary dictionaryWithObjectsAndKeys:selectedFont,
                                        UITextAttributeFont,
                                        selectedFontColor,
                                        UITextAttributeTextColor,
                                        nil];
[self.segmentedControl setTitleTextAttributes:selectedTextAttributes forState:UIControlStateHighlighted];

Any sugestions on how to fix this? Why would it work right on ios6 but truncate the titles on ios7...
This is the code that causes the problem...
      UIImage *unselectedBackgroundImage = [[UIImage imageNamed:@"product_details_segmentBckg"] resizableImageWithCapInsets:UIEdgeInsetsMake(1, 1, 1, 1)];
    /* Selected background */
    UIImage *selectedBackgroundImage = [[UIImage imageNamed:@"product_details_segmentBckg"] resizableImageWithCapInsets:UIEdgeInsetsMake(1, 1, 1, 1)];
    /* Image between two unselected segments */
    UIImage *bothUnselectedImage = [[UIImage imageNamed:@"product_details_segmentBckg"] resizableImageWithCapInsets:UIEdgeInsetsMake(1, 0, 1, 0)];
     /* Image between segment selected on the left and unselected on the right */
    UIImage *leftSelectedImage = [[UIImage imageNamed:@"product_details_segmentBckg"] resizableImageWithCapInsets:UIEdgeInsetsMake(1, 0, 1, 0)];
    /* Image between segment selected on the right and unselected on the right */
    UIImage *rightSelectedImage = [[UIImage imageNamed:@"product_details_segmentBckg"] resizableImageWithCapInsets:UIEdgeInsetsMake(1, 0, 1, 0)];

    if ([UIImage instancesRespondToSelector:@selector(imageWithRenderingMode:)]) {
#ifdef __IPHONE_7_0
        unselectedBackgroundImage = [unselectedBackgroundImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        selectedBackgroundImage = [selectedBackgroundImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        bothUnselectedImage = [bothUnselectedImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        leftSelectedImage = [leftSelectedImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        rightSelectedImage = [rightSelectedImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
#endif
    }

    [[UISegmentedControl appearance] setBackgroundImage:unselectedBackgroundImage
                                               forState:UIControlStateNormal
                                             barMetrics:UIBarMetricsDefault];

    [[UISegmentedControl appearance] setBackgroundImage:selectedBackgroundImage
                                               forState:UIControlStateSelected
                                             barMetrics:UIBarMetricsDefault];

    [[UISegmentedControl appearance] setDividerImage:bothUnselectedImage
                                 forLeftSegmentState:UIControlStateNormal
                                   rightSegmentState:UIControlStateNormal
                                          barMetrics:UIBarMetricsDefault];

    [[UISegmentedControl appearance] setDividerImage:leftSelectedImage
                                 forLeftSegmentState:UIControlStateSelected
                                   rightSegmentState:UIControlStateNormal
                                          barMetrics:UIBarMetricsDefault];

    [[UISegmentedControl appearance] setDividerImage:rightSelectedImage
                                 forLeftSegmentState:UIControlStateNormal
                                   rightSegmentState:UIControlStateSelected
                                          barMetrics:UIBarMetricsDefault];

If I comment this out the labels show up alright ... but I need the background images ....
So how do I keep ios6 compatibility while also having the customized segmented control on ios7

A: I solved this by setting the same title text attributes that I had for the normal state, for the selected state.
In iOS 6 this was enough:
NSMutableDictionary *attributes = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                   someUIFont, UITextAttributeFont,
                                   nil];

[self.segmentedControl setTitleTextAttributes:attributes forState:UIControlStateNormal];

Now I had to add this in order to make it work for iOS 7:
[self.segmentedControl setTitleTextAttributes:attributes forState:UIControlStateSelected];

A: after some research, here's my solution to the issue (Swift 3, iOS 10)
class CustomSegmentedControl: UISegmentedControl {

override func draw(_ rect: CGRect) {

    for segment in subviews {
        for subview in segment.subviews {
            if let segmentLabel = subview as? UILabel {
                segmentLabel.numberOfLines = 0
                segmentLabel.translatesAutoresizingMaskIntoConstraints = false
                segmentLabel.leadingAnchor.constraint(equalTo: segment.leadingAnchor).isActive = true
                segmentLabel.trailingAnchor.constraint(equalTo: segment.trailingAnchor).isActive = true
                segmentLabel.topAnchor.constraint(equalTo: segment.topAnchor).isActive = true
                segmentLabel.bottomAnchor.constraint(equalTo: segment.bottomAnchor).isActive = true
            }
        }
    }
}

override func didMoveToSuperview() {
    self.layer.cornerRadius = 5
    self.clipsToBounds = true
    self.backgroundColor = .white
    self.tintColor = UIColor.orange

    let font = UIFont(name: "Helvetica", size: 12.0)
    self.setTitleTextAttributes([NSFontAttributeName: font!], for: .normal)

    let fontBold = UIFont(name: "Helvetica-Bold", size: 12.0)
    self.setTitleTextAttributes([NSFontAttributeName: fontBold!], for: .selected)
}
}

A: I tried some solutions to avoid to recalculate all the segment sizes.
To fix my issue I put this code on the valueChange action of the segmented control:
for(int i=0;i<setControl.subviews.count; i++){
  NSString *title=[segControl titleForSegmentAtIndex:i];
  [segControl setTitle:title forSegmentAtIndex:i];
}

The problem happens with an App compiled for iOS6 (with Xcode 4.6.3) that runs on iOS7. The glitch is visible after the App is reactivated from suspension but not in all Views.

A: I was updating the title and it was getting truncated since the original title's length was less than the new title.
So, I added permanent non-breaking space \u{00a0} in the text of original title so match the length of the title before and after.


text:
Q: How to check if current time is equal to a particular number before I stop the video in html5 video I have written this code in HTML5 video to play around with the time functionality. If I set this line of code as
if(vid.currentTime > 5){
        vid.pause();
     }

the video will automatically pause, which is what i want. But if I set it as
if(vid.currentTime == 5){
        vid.pause();
     }

it refuses to pause and I want it to pause at different times in order to fire different actions. I don't know why. I have researched and tried to google similar situation but no luck. Any help will be appreciated. Here is the full code:
window.onload = init;

let vid;

function init() {

    vid = document.querySelector("#myPlayer");

    vid.ontimeupdate = displayTimeWhileVideoIsPlaying;
}

function playVideo() {
    vid.play();
}

function pauseVideo() {
    vid.pause();
}

function rewindVideo() {
    vid.currentTime = 0
}

function displayTimeWhileVideoIsPlaying(evt) {
    console.log(vid.currentTime);
    ccc = 5;
    if(vid.currentTime > 5){
        vid.pause();
     }

}

This is the link to my codepen for a working demo:
https://codepen.io/Okezie/pen/xWOLQd?editors=1011
The issue is presumably on line 28 of my code pen.

A: You could keep track of which pause points were hit , and not pause again.
var points = [
    { time: 5 , done: false},
      { time: 6 , done: false},
    { time: 8 , done: false},
    { time: 9 , done: false},
];

function displayTimeWhileVideoIsPlaying(evt) {

for(var point of points){
  console.log(vid.currentTime);
  if(vid.currentTime > point.time){
      if(!point.done){
        vid.pause();
        //vid.currentTime = point.time; //Optional, if you want to pause exact
        point.done = true;
      }
   }
}

The !point.done check guards against the 'inexactness' of the greater than check. It prevents the pause from taking effect at 5.3, 5.4, 5.8 etc. if the code previously paused at 5.
Checkout the updated pen : https://codepen.io/anon/pen/PRGOxW


text:
Q: Is it possible to define a euclidean structure on infinite dimensional vector space It is known that for every infinite dimensional vector space $V$, there exists a Hamel basis $B$, such that each $v\in V$ can be repsentated as $$v=\sum_{i=1}^{n(v)}a_ie_i$$ with $e_i \in B$. Now my question is, can we define a euclidean norm on V in the sense of $$\parallel v \parallel=\sqrt{\sum_{i=1}^{n(v)}\mid a_i\mid^2 } $$?

A: You've indeed described a norm, and it's also induced by a scalar product such that $\langle e_i,e_j\rangle=\delta_{ij}$ for all $i,j$ (such a scalar product is unique, given an algebraic basis). This norm is complete if and only if the dimension of the space is finite. This is proved by the fact that if $\{e_{i_1},e_{i_2},e_{i_3},\cdots\}$ is a countable subsequence of $B$, then the sequence of vectors $v_n=2^{-n}e_{i_n}$ satisfies $\sum_{j=1}^\infty \lVert v_j\rVert<\infty$, despite there being no vector $w$ such that $\lim_{n\to\infty}\left\lVert w-\sum_{j=1}^n v_j\right\rVert=0$.
In fact, let there be such $w$ and $w=\sum_{h=1}^m w_he_h+\sum_{j=1}^n w_{i_j}e_{i_j}$ - where $e_1,\cdots,e_m$ are not among the $\{e_{i_1},e_{i_2},\cdots\}$. Then, for all $r\ge n+1$ $$\left\lVert w-\sum_{j=1}^r v_j\right\rVert=\sqrt{\sum_{h=1}^m \lvert w_h\rvert^2+\sum_{j=1}^n \lvert w_{i_j}-2^{-j}\rvert^2+\sum_{j=n+1}^{r}2^{-2j}}\ge 2^{-(n+1)}$$
So the sequence of those quantities can't converge to $0$.


text:
Q: Change table row if a textbox has a certain value Hi I am new to javascript and Jquery i have a table with 5 rows, and an asp slider that selects a value from 1 to 5. i want the corresponding row in the table to be highlighted when moving the slider. is this possible with javascript or Jquery please?

A: Yes, although I do not know anything about .NET, I do know how to implement this in JavaScript.
HTML5 introduces a new input type called range. The input element has an event listener called change, which looks for changes in the input's value.
To make things simple, I created a generic table with five rows. When the change event is fired, the specific row will be highlighted and other rows will be back to normal.
I'm sure this can be improved, but at the moment, this was the only thing I could come up with
You should use a similar approach for your object.

var range = document.getElementById("my-range");
var result = document.getElementById("result");
var tableRows = document.querySelectorAll("tr");

range.addEventListener("change", function() {
    var rowIndex = +(range.value) - 1;
    var irrelevant = [];
    for (var i = 0; i <= 4; i++) {
        irrelevant.push(i);
    }
    irrelevant = irrelevant.filter(function(e) {
        return e != rowIndex;
    });
    tableRows[rowIndex].style.background = "gold";
    tableRows[irrelevant[0]].style.background = "white";
    tableRows[irrelevant[1]].style.background = "white";
    tableRows[irrelevant[2]].style.background = "white";
    tableRows[irrelevant[3]].style.backgroudn = "white";
});
<input id="my-range" type="range" min="1" max="5" />

    R1 C1
    R1 C2

    R2 C1
    R2 C2

    R3 C1
    R3 C2

    R4 C1
    R4 C2

    R5 C1
    R5 C2

A: You could do something like this. As in http://jsfiddle.net/venuchitta/uuLfwtrw/

$("#slider").slider(
{
            value:1,
            min: 1,
            max: 5,
            step: 1,
            slide: function( event, ui ) {
                $( "#slider-value" ).html( ui.value );
                 $('#data tr').removeClass('highlighted');
                 $('#data tr:eq('+(ui.value-1)+')').addClass('highlighted');
            }
}
);
h1 {
    font-family: Helvetica, Arial;
    font-weight: bold;
    font-size: 18px;
}

body, p{
    font-family: Helvetica, Arial;
}

tr.highlighted td {
    background: red;
}

HTML Slider Test

Your slider has a value of


text:
Q: one question about $\|V^HAV\|=\|A\|$ I have one question about matrix norm:
If $V$ is an nonsquare orthogonal matrix, $V\in C^{n\times m}$ and A is a square matrix, $A\in C^{n\times n}$.
Is it correct that
$\|V^HAV\|=\|A\|$.
If correct, please show the reason or proof.
Thank you

A: This is more or less true for square unitary matrices, but if $V$ is not square, then this isn't true.
You haven't specified what matrix norm you want to use.  As it happens, both the Frobenius norm ($\| A \|_{F}$), and the spectral or 2-norm ($\| A \|_{2}$) are invariant under unitary transformations.  For these norms, if $V$ is unitary, then $\| A \|=\| V^{H}A \|$ and $\| A \|= \| AV \|$.
To see this for the 2-norm, recall that
$\| A \|=\sqrt{\lambda_{\max}(A^{H}A)}$
Thus
$\| V^{H}A \|_{2}=\sqrt{\lambda_{\max}(A^{H}VV^{H}A)}=\sqrt{\lambda_{\max}(A^{H}A)}=\| A \|_{2} $.
For the second part, recall that eigenvalues are invariant under unitary similarity transformations.  Thus
$\| AV \|_{2}=\sqrt{\lambda_{\max}(V^{H}(A^{H}A) V)}=\sqrt{\lambda_{\max}(A^{H}A)}=\| A \|_{2}$.

A: This is not true. Take $$V=\begin{bmatrix} 1 \\ 0 \end{bmatrix}$$ and $A=I$ (identity matrix). By your terms, $V$ is a "non-square" orthogonal matrix (there is only one orthogonal vector though). But if it is a square, orthonormal matrix, this will hold true for both frobenius norm and induced 2-norm. For instance
$$||V^H AV||_2 = \max_{||x||_2=1}||V^HAVx||_2 = \max_{||y||_2=1}||V^HAy||_2=\max_{||y||_2=1}||Ay||_2$$ This holds true because, $||Vx||_2 = ||x||_2$ for all orthonormal matrices $V$ (try proving yourself). A similar argument hold for frobenius norms and you can prove it using the trick $||A||_F^2=trace\{A^HA\}$


text:
Q: How do I center an HTML5 video horizontally and vertically in a bare bones HTML document? Let's say I have a very simple HTML page with a single HTML5 video element. It's source code is:
<html>
    <head>
        <title>{TITLE}</title>
    </head>
    <body>
        <video height="{HEIGHT}" width="{WIDTH}" controls="">
            <source src="{SOURCE}" type="{TYPE}"/>
        </video>
    </body>
</html>

What can I do to center that video element both horizontally and vertically in the web browser? I'd prefer a CSS solution or at least a solution that uses as little in the way of hackish techniques as possible, but I'll take what I can get.

A: Couple of ways to achieve it (Added jQuery to help others as well):
Method 1: Add this class in your video
CSS:
.center {
    position: absolute;
    //Option 1
    top:50%; left: 50%;
    margin-left: -150px;
    margin-top: -75px;
    //Option 2 (Needs to check browser compatibility)
    top: calc(50%-75px);
    left: calc(50%-150px);
}

Method 2: Add some code for dynamic margins
CSS:
.center {
    position: absolute;
    top:  50%;
    left: 50%;
}

Code:
$('video').css({
    'margin-top': - $('video').height()/2,
    'margin-left': - $('video').width()/2
});

Method 3: Window size
Code:
$(window).on('load resize', function(){
    $('video').css({
        'position' : 'absolute',
        'top': $(window).height()/2 - $('video').height()/2,
        'left': $(window).width()/2 - $('video').width()/2
    });
});

Here is a link How to center an element horizontally and vertically for more detailed description.

A: Use following css will make your video element center vertically and horizontally.
video {
    left: 50%;
    position: absolute;
    top: 50%;
    transform: translate(-50%, -50%);
}

Working Fiddle

A: For background video i use this
HTML:
<video class="background" controls="">
    <source src="{SOURCE}" type="{TYPE}"/>
</video>

CSS:
   .background {
    position: fixed;
    right: 0px;
    bottom: 0px;
    min-width: 100%;
    min-height: 100%;
    width: auto;
    height: auto;
    z-index: -1;
   }

A: Include a simple css center class, like this for example:
    .center { margin: 0 auto; width: 400px; }

And then try this:
    <video class="center" height="{HEIGHT}" width="{WIDTH}" controls="">
       <source src="{SOURCE}" type="{TYPE}"/>
    </video>

A: Nothing very complex about this but here you go...
100% height on body and html gives you full screen vertical size.  Position the video using relative positioning 50% down and subtract half the height for a negative margin to account for element size.  This is pretty much the standard way but there are a bazillion others.

html,
body {
  height: 100%;
}
body {
  text-align: center;
  margin: 0;
}
video {
  top: 50%;
  position: relative;
  margin-top: -75px;
  height: 150px;
}
<html>

<head>
  <title>{TITLE}</title>
</head>

<body>
  <video height="{HEIGHT}" width="{WIDTH}" controls="">
    <source src="{SOURCE}" type="{TYPE}" />
  </video>
</body>

</html>

A: I'm new to web development. But I think what you want to do is to add an id to your video tag

Then in your CSS file, do this
#vid {
    position: absolute;
    top: 30%;
    left: 30%;
}

Experiment with the percentages to find what looks perfectly centered.
Again, I'm new to this and I'm sure there's a better way to do it. But hey you said you'd take what you can get!


text:
Q: How set counter and mode in Rails How do I set a counter with a loop?
@count=0

(w.submenu).each do |s|

    count=+1

      if(count == 4)

      else

      end

  count++

end

A: You can do it with the each_with_index method:
(w.submenu).each_with_index do |s, index|

      if(index == 4)
      else
      end
end

See the Enumerable documentation for more information.

A: For some reason you are using @count=0 on the first line and count on the others.
Also I agree that each_with_index would be ideal.


text:
Q: Yii2 pjax gridview ActionColumn issue with a view link I was trying to create a custom action column in the index and wrote this code:
     [
            'class' => 'yii\grid\ActionColumn',
            'contentOptions' => ['style' => 'width:50px;'],
            'header'=>'',
            'template' => '{view} {update}',
            'buttons' =>
            [

                //view button
                'view' => function ($url, $model) {
                    return Html::a('', $url, [
                                'title' => Yii::t('app', 'View'),
                    ]);
                },
                'update' => function ($url, $model) {
                    if (Yii::$app->user->can('change-offer'))
                    {
                        return Html::a('', $url, [
                                    'title' => Yii::t('app', 'Update'),
                        ]);
                    }
                },
                'delete' => function ($url, $model) {
                    if (Yii::$app->user->can('delete-offer'))
                    {
                        return Html::a('', $url, [
                                    'title' => Yii::t('app', 'Delete'),
                                    'data-confirm' => 'Are you sure you want to delete this item?',
                                    'data-method' => 'post',

                        ]);
                    }
                },
            ],
            'urlCreator' => function ($action, $model, $key, $index) {
                if ($action === 'view') {
                    return Url::to(['offer/view', 'id'=>$model->id]);
                }
                if ($action === 'update') {
                    return Url::to(['offer/update', 'id'=>$model->id]);
                }
                if ($action === 'delete') {
                    return Url::to(['offer/delete', 'id'=>$model->id]);
                }
            }
        ],

Delete and Update are working ok but view is opening without refreshing the page in the Index page. I updated my code as follows and added the
'data-method' => 'post' to the view button and it seems to help.
                    'view' => function ($url, $model) {
                    return Html::a('', $url, [
                                'title' => Yii::t('app', 'View'),
                                'data-method' => 'post',
                    ]);
                },

Is it a bug in the GridView or am I doing something wrong?

A:
You may disable pjax for a specific link inside the container by adding data-pjax="0" attribute to this link.

So, you should simply try this :
return Html::a('', $url, [
    'title' => Yii::t('app', 'View'),
    'data-pjax' => '0',
]);

Read more : http://www.yiiframework.com/doc-2.0/yii-widgets-pjax.html


text:
Q: Crontab not running Python script I've tried setting up Crontab for the first time using the below:
* * * * * cd /Users/alexlee/PycharmProjects/pythonProject1 && /usr/bin/python C19 Webscrape.py

however the script isn't running. I've given permissions full disk access to Terminal and Cron but that didn't do the trick.
Any suggestions?

A: Crontab takes shell commands only.
If you want to run a python script, write a shell script to run the python script within it. Use the shell script in the crontab.
For example the following can be a  shell script:
#!/bin/sh
# launcher.sh
# print Hello World!

sudo python /<location-here>/hello.py

This could be your python code:
# hello.py
print("Hello World!")

I found a post which helped me start with Crontab: https://linuxize.com/post/scheduling-cron-jobs-with-crontab/


text:
Q: DefaultControllerFactory vs IDependencyResolver I have a little misunderstanding: when we implement IDependencyResolver it means that we can use DI for every part in the project. So even if i don't inherit from DefaultControllerFactory i can build controllers regestering dependencies?
edits: i recommend look through all these  Brad Wilson's posts
also  this post  is useful

A: Pedant note first. You cannot inherit from an interface (IDependencyResolver) but I assume you mean implement.
In short you have a choice between using either, you would not use both.  So if you have the resolver set up you do not need to have a controller factory and vice versa.
I have only used DefaultControllerFactory in mvc with castle-windsor.  You will need to be wary of one loose end in using IDependencyResolver if you are using castle-windsor also, there is no release method but there are probably ways around this.
With other frameworks such as ninject or unity IDependencyResolver is sometimes preferable.


text:
Q: Xcode not letting me ctrl drag to add outlet I'm trying to add an action to my swift file from ctrl dragging from the storyboard. This doesn't seem to be working for my Screen Edge Pan Gesture Recognizer. Why could this be?

A: You're trying to create outlet in other view controller, which is is not a super class of controller. Check in identity inspector. Select automatic  from assistant window.


text:
Q: Remote style sheet attack vector - xss I'm trying to create a sanitize function, It's almost done, there is one attack which bothers me (from https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet#Remote_style_sheet_part_2 ):
Remote style sheet part 2
This works the same as above, but uses a STYLE tag instead of a LINK tag). A slight variation on this vector was used to hack Google Desktop. As a side note, you can remove the end /STYLE tag if there is HTML immediately after the vector to close it. This is useful if you cannot have either an equals sign or a slash in your cross site scripting attack, which has come up at least once in the real world:
<STYLE>@import'http://myserver/xss.css';</STYLE>
The question is what am I supposed to put in the xss.css file for it to work? I tried alert('xss'), then <script>alert('xss')</script>, neither works.


text:
Q: What makes a dynamic user unable to read personal files? I'm using a DNS service named dnscrypt-proxy. And I use the PPA to install it on Ubuntu 18.04. Here is the installed service file:
[Unit]
Description=DNSCrypt-proxy client
Documentation=https://github.com/jedisct1/dnscrypt-proxy/wiki
Requires=dnscrypt-proxy.socket
After=network.target
Before=nss-lookup.target
Wants=nss-lookup.target

[Service]
NonBlocking=true
ExecStart=/usr/bin/dnscrypt-proxy --config /etc/dnscrypt-proxy/dnscrypt-proxy.toml
ProtectHome=yes
ProtectControlGroups=yes
ProtectKernelModules=yes

# Run dnscrypt-proxy as unprivileged user with
# temporary assigned UID/GID. See man:systemd.exec
# for more info. Requires systemd 232+.
DynamicUser=yes
CacheDirectory=dnscrypt-proxy
LogsDirectory=dnscrypt-proxy
RuntimeDirectory=dnscrypt-proxy

[Install]
Also=dnscrypt-proxy.socket
WantedBy=multi-user.target

And I give a file path /etc/dnscrypt-proxy/blacklist.txt in that dnscrypt-proxy.toml file as a blacklist which is a symbolic link points to my home directory /home/user/.dnscrypt-proxy-config/blacklist.txt.
The reason why I did this is that blacklist.txt comes from the internet, so I only want to put it in my personal directory to keep safety.
But the problem is, this service fails because of Open blacklist.txt failed: Permission denied. While I don't understand which part causes this problem.
I can confirm that this file and its symbolic link both have at least xx4 permission. And if I directly put that file into /etc/dnscrypt-proxy directory, it works.
So could anyone tell me what is the root cause? And if I want to follow the symbolic link form, what should I do?

A: You have ProtectHome=yes enabled.

If true, the directories /home, /root, and /run/user are made inaccessible and empty for processes invoked by this unit. If set to "read-only", the three directories are made read-only instead.

To change this setting in a packaged unit file,

*

*you can copy the entire unit file to /etc/systemd/system/<name>.service and edit it there (/etc takes priority over /usr/lib);

*you can create an "add-on" file /etc/systemd/system/<name>.service.d/whatever.conf that just updates the settings you need: [Service]ProtectHome=read-only

*you can use systemctl edit [--full] <name> as a shortcut to do either of the above automatically;

*as a last resort, you can use your package manager's configuration (e.g. NoUpgrade or dpkg-divert) to exclude the file in /usr/lib from being upgraded.


text:
Q: Zeep not parsing the response I have soap response, which is not being parsed with my soap client. Using zeep==2.5.0
zeep.exceptions.XMLParseError: Unexpected element '{url1}SendMessage'
<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
  <soapenv:Body>
    <acb:GetDataResponse xmlns:acb="some url">
      <info>
        <ns4:SendMessageResponse xmlns:ns4="some url1">
          <response>
            <responseInfo>
              <messageId>8a5fd36d-9339-4026-8cb3-3ab69f7c29d1</messageId>
              <responseDate>2018-08-08T13:32:09.704+06:00</responseDate>
              <status>
                SCSS001
                <message>Message has been processed successfully</message>
              </status>
            </responseInfo>
            <responseData>
              <data xmlns:ns2="some url 2" xmlns:ns3="some url 3">
                <ns3:result>
                  <ns3:SomeList>
                    <ns3:IIN>999999222333</ns3:IIN>
                    <ns3:LNAME>ASD</ns3:LNAME>
                    <ns3:FNAME>ASD</ns3:FNAME>
                  </ns3:SomeList>
                </ns3:result>
                <ns3:responseInfo>
                  <ns2:GUID>29344984</ns2:GUID>
                  <ns2:dateMessage>2018-08-08T13:32:09.704+06:00</ns2:dateMessage>
                  <ns2:totalResults>4</ns2:totalResults>
                  <ns2:processingResult>
                    <ns2:code>202</ns2:code>
                    <ns2:description_ru>success</ns2:description_ru>
                    <ns2:description_kz>success</ns2:description_kz>
                    <ns2:isAnswer>true</ns2:isAnswer>
                  </ns2:processingResult>
                </ns3:responseInfo>
              </data>
            </responseData>
          </response>
        </ns4:SendMessageResponse>
      </info>
    </acb:GetDataResponse>
  </soapenv:Body>
</soapenv:Envelope>

I think that the response structure from the API is incorrect, but cannot find where

A: Your WDSL definition does not contain all needed XSD. Request service developer for xsd file containing "some url1" namespace.
Then load:
client.wsdl.types.add_document_by_url('/path/to/file.xsd')


text:
Q: PyQt5 QMYSQL driver building I have problem with building the QMYSQL driver on PyQt5. Every solution I find on the internet is focusing on pure Qt (including documentation), not the PyQt5. There is no such files as the ones mentioned in official Qt documentation about driver building, and everything is in wrappers.
Can someone do it or write simple instruction how to implement these methods from Qt documentation in PyQt?
Edit: The driver for QMYSQL are not installed. The error I receive occurs for every driver excluding QSQLITE


text:
Q: How to kill certain windows when out of focus automatically? I have i3-gaps installed and would like to kill a certain type of window instance whenever it is out of focus. Example, after launching a terminal typing in some command and then killing it once it is out of focus.
I know that the directive
for_window [instance="foobar"] <do something>
can be used to instruct a certain type of command for windows of that instance. For instance dropdown windows. I am also aware of the focused keyword but I can't find any example on how to use it.
What I expect is something like
for_window [instance="foobar" && __focused__] if not focused then kill

A: I'm achieving the same functionality with xdotool:
xdotool search --class xterm behave %@ blur windowclose

This will close an xterm window when it loses focus.
You can play with xdotool. It is quite flexible.


text:
Q: Socket io seems to keep reverting to pollin I'm trying to setup a socket io server using websockets with node and react.
Atm I have this on the server side:
const server = app.listen(port, () => {
  console.log(`App listening at http://localhost:${port}`);
});

const io = require('socket.io')(server, {
  cors: {
    origin: '*',
  },
});

io.on('connection', (socket) => {
  socket.on('chat message', (msg) => {
    io.emit('chat message', {
      ...msg,
      _id: Math.random(),
      createdAt: new Date(),
    });
  });
});

And this on the frontend:
  const socket = useRef(io('http://localhost:3000'));
  const [messages, setMessages] = useState([]);
  useEffect(() => {
    socket.current.on('chat message', function (msg) {
      setMessages([...messages, msg]);
    });
  }, [messages]);

  return(
      <Button
        onClick={() => {
          socket.current.emit('chat message', {
            text: 'msg sent by ',
            createdBy: { name: user.name, image: user.profileImage },
          });
        }}
      >
        Click
      </Button>
  )

Now this 'works' however instead of using websockets it seems to be using polling as shown in the network log:

Would really appreciate any help, thanks!


text:
Q: TypeScript type definition for Dropbox V2 Javascript API Where can I find the Typescript definition files for Dropbox v2 api and how do I load them into VS Code? I tried several times and cannot seem to figure it out. Most other libraries don't have any problems.

A: The typings are included with the Dropbox V2 library when you npm install the library.
You can tell by looking at the source code for the library, specifically at its package.json. If the package.json includes a key called typings, that means the TypeScript types are bundled with the source code, and will be installed along with the code when you npm install the library.
If the typings don't work for you in VSCode, there is some other issue - how are you installing the Dropbox library?


text:
Q: closing the sidenav by clicking enywhere outside the sidenav I want to Close the sidenav by clicking anywhere outside sidenav
my html code is

    <?php include("header.php");?>

        <?php include("slider.php");?>

 Category
            <button type="submit" class="btn btn-xs btn-success complete" id="more">More  </button>

            <?php include("functions/index_category.php"); ?>

 Daily News

        ×

        <?php include("functions/sub_category.php")?>

The Js i tried :
//close the side nav when clicked outside
 var primary = document.getElementById('primary');
 var sidenav = document.getElementById('mySidenav');
 window.onclick = function(event){
     if( event.target == primary ){
        sidenav.style.width = "0px";
        primary.style.marginLeft = "0px";
     }
 }

How ever it works  clicking enywhere on the side nav by replacing event.target == sidenav But i want to close it by clickng outside
js for opening and closing the side nav are
function openNav() {
    if($(window).width() > 600){
        $("#mySidenav").attr("style","width:350px");
        $(".primary").attr("style","margin-left:350px");
    }else{
        $("#mySidenav").attr("style","width:100%");
        $(".primary").attr("style","margin-left:100%");
    }

}

function closeNav() {
    $("#mySidenav").attr("style","width:0px");
    $(".primary").attr("style","margin-left:0px");
}

css code:
.wraper{
    min-height: 165px;
    overflow: hidden;
    height: 200px;
}
.content {
    margin-top: 30px;
}
#more{
    width:6%;
    margin-right:0px;
    float:right;
}
.wraper.complete{
    height: auto;
}
h3.sub{
    color:#d34615;
    text-decoration:underline;
    padding-left: 10px;
}
#index-hr{
    width:100%;
    border-top:1px solid #333;
    opacity:0.3;
}

A: Just check the event.target to see if it was NOT the side nav and that the nav is NOT already open:
//close the side nav when clicked outside
 var primary = document.getElementById('primary');
 var sidenav = document.getElementById('mySidenav');

 window.onclick = function(event){

     var sideNavWidth = sidenav.style.width;

     // check to see if the event target was not the side nav
     // AND that the side nav is open
     if( event.target !== sidenav && sideNavWidth !== "0" ){
        sidenav.style.width = "0";
        primary.style.marginLeft = "0";
     }
 }

This is a crude implementation of your code, but you can see that the side nav bar does, in fact open (yellow) and will not close if you click on it, but will close if you click anywhere else.

//close the side nav when clicked outside
 var primary = document.getElementById('primary');
 var sidenav = document.getElementById('mySidenav');

 window.onclick = function(event){

     var sideNavWidth = sidenav.style.width;

     // check to see if the event target was not the side nav
     // AND that the side nav is open
     if( event.target !== sidenav && sideNavWidth !== "0" ){
         closeNav();
     }
 }

 function closeNav(){
          sidenav.style.width = "0";
        primary.style.marginLeft = "0";
 }
.sidenav { background: yellow;}

        <?php include("slider.php");?>

 Category
            <button type="submit" class="btn btn-xs btn-success complete" id="more">More  </button>

            <?php include("functions/index_category.php"); ?>

 Daily News

        ×

        <?php include("functions/sub_category.php")?>


text:
Q: 'IDataErrorInfo' is a 'namespace' but is used like a 'type' - WPF I try use IDataErrorInfo in WPF app on validation data, but if I try implement interface IDataErrorInfo in my class, I get this error:
'IDataErrorInfo' is a 'namespace' but is used like a 'type' I using namespace System.ComponentModel. Any advance.
code is here:
public partial class MainWindow : Window
    {
        public class Friend : IDataErrorInfo
        {
            private string _id;

            public string ID
            {
                get { return _id; }

                set { _id = value; }
            }

            private string _lastError;

            public string Error
            {
                get { return _lastError; }
            }

            string IDataErrorInfo.this[string propertyName]
            {
                get
                {
                    switch (propertyName)
                    {
                        case "ID": if (String.IsNullOrEmpty(ID))
                                _lastError = "Please insert a name!";
                            break;

                        default: _lastError = string.Empty;
                            break;

                    }
                    return _lastError;
                }
            }
        }

        public MainWindow()
        {
            InitializeComponent();
        }
    }
}

A: Because it is a namespace
You may be importing a wrong DLL
Try to use Ctrl + Space in IDataErrorInfo. It is a namespace.
Or it might be the same name with your namespace that it gets confused.
In your import statement, you can try to rename your imported namespace:
using Error = System.ComponentModel; (for example)
Try this explanation:
http://msdn.microsoft.com/en-us/library/system.componentmodel.idataerrorinfo.aspx
Have a look at the Framework section
What is your OS? It said it does not support Windows 8, and stuff.
Maybe try to use another library, or change your OS, or wait until your OS supports it.
Thank you,


text:
Q: How to read data from xlsx in Perl if the xlsx file have collapsed rows Is the perl library Spreadsheet::ParseXLSX able to parse xlsx files that has collapsed rows?
I am trying to parse a xlsx file generated from another program. The xlsx file might have collapsed rows.
Trying to understand is there any methods in this library that can be used to expand all collapsed rows while parsing the file?

A: Yes it will count the collapsed columns.


text:
Q: Allowed file extensions for a Windows RT Application For my Windows Runtime Metro-Application written in c#, I want to use an own file format. For this file format I want to use an own file extension. In the package manifest I have declared the desired extension as a "File Type Association" and all works fine.
My question is, if there are some rules or limitations for assigning/using a file extension. I clearly would not use a commonly used file extension such as ".exe", ".cab", or ".docx". But are there any accessible guidelines, recommendations or rules, on how file extensions have to be built (3 chars, 4 chars, …) and which file extensions never should be used. Or even does exists a Microsoft-service where file-types have to be registered to be accepted later on in the app store?

A: Here are some generic best practices around file associations.  One relevant part ...

Do Not Use Short File Name Extensions
Long file name extensions offer the following advantages:
The limited length of short extensions make them prone to extension
  collisions. An extension collision occurs when the same extension is
  used to classify multiple file types. Using long extensions
  significantly decreases the chances of a collision. Short file names
  tend to be somewhat cryptic. Long extensions tend to be more
  meaningful because additional information can be embedded in the
  extension.

For Metro style apps, the only limit I could find is in this document ...

Important note:  Here is an alphabetic list of file type names that
  you cannot enter into the package manifest because they are either
  reserved or forbidden: Accountpicture-ms, Appx, application,
  Appref-ms, Bat, Cer, Chm, Cmd, Com, Cpl, crt, dll, drv, Exe, fon,
  gadget, Hlp, Hta, Inf ,Ins, jse, lnk, Msi, Msp, ocx, pif, Ps1, Reg,
  Scf, Scr, Shb, Shs, Sys, ttf, url, Vbe, Vbs, Ws, Wsc, Wsf, Wsh.


text:
Q: Changing a dropdown menu's value AND display name to SQL query results based on a radio button selection Important note: Most of the things I want from this are finished & functional -- the only part that doesn't work is getting a "value=" that is different from the name of the select option of the dropdown. That said I'm going to lay this whole thing out for the benefit of anyone who might want to use something similar.

Goal: When the user clicks a radio button, a dropdown menu elsewhere on the page is modified to show different values, which are drawn from an SQL query.
Specifically in this example, a user would pick an academic program (say, a Ph.D.) and the dropdown shows which start dates are available.
Here is an SQL query which gets the available start dates, and formats them for the Javascript:
$app_period_lookup_psyd =  mssql_query("select app_period_id,
app_period_display_online from  dbo.v_app001_application_period_for_dropdown
where pgm_id = 1 order by available_dt");
$app_period_options_psyd = "";
while($result = mssql_fetch_array($app_period_lookup_psyd)) {
$app_period_options_psyd .= "'" . $result['app_period_display_online'] ."', ";
}

The variable created here is $app_period_options_psyd, and it would spit out something like:
'September 2011', 'January 2012',
These are the radio buttons:
<input type="radio" name="pgm_id" id="macpe" value="4"
onclick="change([<?=$app_period_options_psyd?>]) " />Radio Button 1<br />

<input type="radio" name="pgm_id" id="macpd" value="5"
onclick="change(['January', 'February', 'March']) " />Radio Button 2

Clicking these two buttons would generate the following dropdowns:
<select id="app_period_id">
<option value="September 2011">September 2011</option>
<option value="January 2012">January 2012</option>
</select>

<select id="app_period_id">
<option value="January">January</option>
<option value="February">February</option>
<option value="March">March</option>
</select>

They work via this script in the header:
<script type="text/javascript">
    function change(arr) {
    var el = document.getElementById('app_period_id');
    el.options.length = 0;
    for(var i = 0; i< arr.length; i++ ) {
    el.options[el.options.length] = new Option( arr[i], arr[i]);
    }
    }
</script>

THE QUESTION: How do I modify the Javascript to create different values for value="" and the descriptor, with BOTH values coming from the query/queries? This is the ideal output:
<select id="app_period_id">
<option value="app_period_1">January 2012</option>
<option value="app_period_6">February 2012</option>
<option value="app period_18">March 2013</option>
</select>

Where "app_period_x" would be generated in the SQL query.

A: Try the following changes:
$app_period_options_psyd .= "'" . $result['app_period_display_online'] ."', ";

becomes
$app_period_options_psyd .= "'" . $results['app_period_id'] . "'," . $result['app_period_display_online'] ."', ";

This means your array now looks like
arr_[0] = Id
arr_[1] = Name associated
etc.
Now change the Javascript function to
<script type="text/javascript">
    function change(arr) {
    var el = document.getElementById('app_period_id');
    el.options.length = 0;
    for(var i = 0; i< arr.length; i+=2 ) {
    el.options[el.options.length] = new Option( arr[i], arr[i+1]);
    }
    }
</script>

You are now looping through the array two steps, and putting out both elements into your code.


text:
Q: VBA - Iteration through dropdown/validation list and save generated sheets to one PDF I am iterate through dropdown/validation list on given cell:
Sub SpitValues()
Dim dvCell As Range
Dim inputRange As Range
Dim c As Range
Dim i As Long

'Which cell has data validation
Set dvCell = Worksheets(3).Range("D4")
'Determine where validation comes from
Set inputRange = Worksheets(2).Range("C4:C5")

i = 1
'Begin our loop
Application.ScreenUpdating = False
For Each c In inputRange
    dvCell = c.Value

    i = i + 1
Next c
Application.ScreenUpdating = True

End Sub

On every iteration I need to save whole Worksheet(3) to variable and at the end I need to save all saved Worksheets to one PDF where every iteration data will be on separate page. So if I have for example five items in dropdown/validation list, there will be PDF with five pages. Is it possible?

A:
Is it possible?

Yes. It is possible.
Firstly, some cleanup. I have removed i as you don't use that variable. I have not turned off the screen updating because you want to extract each iteration. But, yes, turning off screen updating is usually a good performance measure.
The general algorithm to do this is to:
Identify where you are going to store the new pages
Make the change
Copy the page to the new store
loop
print

You had done some of this, now to complete the job.
Sub SpitValues()
    Dim dvCell As Range
    Dim inputRange As Range
    Dim c As Range
    Dim NewWorkbook as workbook

    'Which cell has data validation
    Set dvCell = ThisWorkbook.Worksheets(3).Range("D4")
    'Determine where validation comes from
    Set inputRange = ThisWorkbook.Worksheets(2).Range("C4:C5")
    Set NewWorkbook = Application.Workbooks.Add

    'Begin our loop
    For Each c In inputRange
        dvCell = c.Value
        ThisWorkbook.Worksheets(3).Copy Before:=NewWorkbook.Sheets(NewWorkbook.Sheets.Count)  ' should insert this before the blank sheet at the end.
    Next c
'After this loop, print/save the new workbook. Change the file name to something suitable
    NewWorkbook.ExportAsFixedFormat _
        Type:=xlTypePDF, _
        Filename:="Whatever", _
        Quality:=xlQualityStandard, _
        IncludeDocProperties:=True, _
        IgnorePrintAreas:=False, _
        OpenAfterPublish:=False

End Sub

Disclaimer: I have not had a chance to test this code yet.


text:
Q: Capture a group in RewriteCond I have this rule:
RewriteCond %{QUERY_STRING} size=(\d+)

and want to capture (\d+) for later use in RewriteRule or RewriteCond. Something like this:
RewriteCond %{QUERY_STRING} size=(\d+)
RewriteCond $1 <1024 ## that $1 refers to (\d+)

How can I achieve that?

A: You need to use the % backreferences:
RewriteCond %{QUERY_STRING} size=(\d+)
RewriteCond ^ /%1 [L]

The %1 backreferences a previously captured group in a rewrite cond.


text:
Q: How to pass parameter by Swagger into req.body in Express/Node?  "/auth/sign-in": {
      "post": {
        "summary": "Sign-in on the site.",
        "description": "You can sign in on the site by using login and password.",
        "parameters": [
          {
            "in": "query",
            "name": "email",
            "description": "You should pass here email",
            "required": true,
            "schema": {
              "type": "string"
            }
          },
          {
            "in": "query",
            "name": "password",
            "description": "You should pass here password",
            "required": true,
            "schema": {
              "type": "string"
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Here you will get token",
            "example": {
              "token": "token"
            }
    },

Above you can see my swagger.json route ( as an example of my code ) . I need to find out how to send value in req.body( by using swagger ) . I see that we can pass parameter in path(directrly in link , also we can pass it in cookie ,also in header, and in query)
         {
            "in": "query",
            "name": "email",
            "description": "You should pass here email",
            "required": true,
            "schema": {
              "type": "string"
            }
          }

I need to help with creating this object for getting parameter email in next way ( req.body.email ). How can I make it?

A: elyas-bhy have helped me so  much . I will give you more info about this answer .
  "parameters": [
          {
            "in": "body",
            "name": "body",
            "description": "You should pass here email",
            "required": true,
            "schema": {
              "type": "object",
              "properties": {
                "email": {
                  "type": "string"
                },
                "password": {
                  "type": "string"
                }
              }
            }
          }
        ],

it will be looks like this one :
enter image description here
Hope someone else it will be helpful

A: /**
 * @swagger
 *    produces:
 *      - "application/xml"
 *      - "application/json"
 *    parameters:
 *      - name: level_id
 *        in: path
 *        required: true
 *      - name: body
 *        description: Please enter an email here
 *        in: body
 *        required: true
 *        schema:
 *          $ref: '#/definitions/levels'
 *    responses:
 *      201:
 *        description: updated
 *      404:
 *        description: Not found
 *      500:
 *        description: Internal Server error
 */

A: If you are using OpenAPI 2.0:
{
  "in": "body",
  "name": "body",
  "description": "Resource payload",
  "required": true,
  "schema": {
    "type": "object",
    "properties": {
      "email": {
        "type": "string"
      }
    },
    "required": ["email"]
  }
}

Source: https://swagger.io/docs/specification/2-0/describing-request-body/

A: You can try this
"/your-path": {
    post: {
        summary: 'Example POST request',
        description: 'Test post',
        "consumes": [ "application/json" ],
        produces: ["application/json"],
        requestBody: {
            content: {
                "application/json": {
                    schema: {
                        "properties": {
                            "user": {
                                "type": "string"
                            },
                            "pass": {
                                "type": "string"
                            }
                        }
                    }
                }
            }
        },
        responses: {
            '200': { "description": "OK" },
            '401': { "description": "Unauthorized" },
            '402': { "description": "Bad Request" },
            '500': { "description": "Internal Server Error" }
        }
    }
}


text:
Q: Downloading file is so slow I tried same file with Opera browser and Java code.
Opera Browser is giving nearly 2 MB/s speed but Java code gives not more than 400 KB/s. What's wrong with my code?
I guess I'm doing it wrong with reading with BufferedReader but I have no idea why it does happen and how can I fix.
PS: I'm only speed-testing, not running the file. I know that it's a binary file, does this make any difference at speed?
            StringBuilder builder = new StringBuilder();
            HttpURLConnection uri = (HttpURLConnection) new URL("http://speedtest.tele2.net/3MB.zip").openConnection();
            uri.setRequestMethod("GET");
            uri.setConnectTimeout(5000);
            InputStream ent = uri.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(ent, "iso-8859-1"), 8);
            while ((line = reader.readLine()) != null) {
                builder.append(line + "\n");
            }

A: I would use binary download for binary files, when I run this I get
public class DownloadMain {
    public static void main(String[] args) throws IOException {
        HttpURLConnection uri = (HttpURLConnection) new URL("http://speedtest.tele2.net/3MB.zip").openConnection();
        uri.setRequestMethod("GET");
        uri.setConnectTimeout(5000);
        InputStream ent = uri.getInputStream();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] bytes = new byte[8192];
        long start = System.currentTimeMillis();
        for (int len; (len = ent.read(bytes)) > 0; )
            baos.write(bytes, 0, len);
        long time = System.currentTimeMillis() - start;
        System.out.printf("Took %.3f seconds to read %.3f MB of data%n",
                time / 1e3, baos.toByteArray().length / 1e6);
    }
}

prints
Took 0.541 seconds to read 3.146 MB of data

which is almost 6 MB/s
If you ignore the fact the file is binary, just for performance comparison purposes.
public class DownloadMain {
    public static void main(String[] args) throws IOException {
        HttpURLConnection uri = (HttpURLConnection) new URL("http://speedtest.tele2.net/3MB.zip").openConnection();
        uri.setRequestMethod("GET");
        uri.setConnectTimeout(5000);
        InputStream ent =uri.getInputStream();
        Reader reader = new InputStreamReader(ent, StandardCharsets.ISO_8859_1);
        StringWriter sw = new StringWriter();
        char[] chars = new char[8192];
        long start = System.currentTimeMillis();
        for (int len; (len = reader.read(chars)) > 0; )
            sw.write(chars, 0, len);
        long time = System.currentTimeMillis() - start;
        System.out.printf("Took %.3f seconds to read %.3f MB of data%n",
                time / 1e3, sw.toString().length() / 1e6);
    }
}

prints
Took 0.548 seconds to read 3.146 MB of data

So it might be slightly slower, or just random variation.
By comparison, using StringBuilder and reading one line at a time could be slower, but not dramatically
Took 0.555 seconds to read 3.146 MB of data


text:
Q: Nested methods testing with scanner public static void takeAnswers(int answerNumber){
        if(answerNumber<0){
            throw new IllegalStateException();
        }
        Scanner answer = new Scanner(System.in);
        testResponse = answer.next().charAt(0);
        while(!(validateAnswer(testResponse, answerNumber))){
            Question.inValidInput();
        }
    }

so i making this quiz in java and i am just stuck on the junit testing.
"Also, How are we suppose to test for nested methods?
Can we alter the value of a local variable (declared inside the method itself), since it's using scanner and thus waits for a user input and therefore the test just waits forever. "
So basically no matter what value I give to the testResponse , the test still waits for the scanner.
and thus the program just waits there forever.


text:
Q: Bug in Krusader lost directory subtree. How to recover the files? Using Krusader version 2.4.0-beta1 (thanks Canonical for using me as ginnea pig without my knowledge), I renamed two directories to replace the spaces in the names with underscores. Unfortunately, immediately after doing so, the files and directories below my Security Web directory completely vanished.
How can I recover them?
The path I altered was:
    /home/peter/Documents/Business from 2005/Security Web/
Which should have become:
    /home/peter/Documents/Business_from_2005/Security_Web/
I've altered it back, in the hope that the files would reappear, but they didn't.
I have just one disk, this being a laptop and it's all one partition, except for swap.
I attempted to force a disk check at the next restart using:
    touch ./forcefsck
But it didn't seem to work since the next startup took no longer than normal despite having nearly 400GB of files to check.
Also the above fsck method seems somewhat lame to me (even if it did work), since how can you pass parameters to fsck? Is there a way to do that?

A: Please check if the below link may be useful to you...
http://www.howtogeek.com/howto/15761/recover-data-like-a-forensics-expert-using-an-ubuntu-live-cd/


text:
Q: Как правильно экспортировать класс из динамической библиотеки (*.so) Linux С++ Продолжаю изучать программирование под линукс. Хотелось бы спросить совета, как верно прописать экспорт класс из динамической библиотеки в линуксе ? Тестовый проект пишу на C++.
Есть тестовый класс обозначенный :
class Book
{
private:
    int m_year;
    std::string m_author;
    std::string m_bookName;

public:

    Book(int year=0, const char* author="Default", const char* bookName="Default"):
        m_year{year},
        m_author{author},
        m_bookName{bookName}
    {
    }

    std::string getStr();

    int getYear();
};

Этот класс и будет вынесен в динамическую библиотеку.
Подскажите как правильно его экспортировать что бы он был доступен в проектах использующих данную библиотеку ? В сети много информации по экспорту C функций но не смог найти не чего дельного по экспорту классов под линукс.
Компилирую следующим образом:
g++ -shared -o libBook.so -Wall -fPIC Book.h Book.cpp

Нашел способ - использование атрибута:
__attribute__((visibility("default")))

Вроде работает. Есть ли еще какие нибудь пути ? на сколько этот способ верен ?
или же можно вовсе не указывать не какого атрибута ? Все равно программка работает и использует класс Book.

A: Для начала, при сборке elf с помощью gcc в linux все символы видимы по умолчанию, т.е. простой сборки.
 g++ -shared -o libBook.so -Wall -fPIC Book.h Book.cpp

Уже достаточно, чтобы интерфейс Book оказался видимым (экспортированным в терминах MS). Но, конечно, ради чистоты хорошей практикой является ограничивать интерфейс библиотек (здесь описано почему),
Как собственно скрыть символы
Для того чтобы gcc скрывал символы по умолчанию нужно явно передать ему ключ -fvisibility=hidden. А для того чтобы сделать видимыми отдельные символы необходимо пометить их с помощью соответствующего атрибута:
class __attribute__((visibility("default"))) Book;

или в стиле С++11:
class [[gnu::visibility("default")]] Book;

Аналогично можно сделать символ явно скрытым:
class __attribute__((visibility("hidden"))) BookInternalImp;

Применять эти атрибуты к объявлениям вполне достаточно. Указывать их для определения каждой  функции не обязательно. Но можно, например, спрятать отдельные статические члены и функции-члены класса:
class [[gnu::visibility("default")]] Book {
private:
  void [[gnu::visibility("hidden")]] doSomeInternalProcessing();
  static BookManager* [[gnu::visibility("hidden")]] internalManager;
}

Также можно воспользоваться прагмой с аналогичным эффектом на серию последовательных объявлений (но на отдельные члены классов эти прагмы не подействуют):
#pragma GCC visibility push(visibility)
class Book;
class Author;
#pragma GCC visibility pop

Есть и другие значения атрибута visibility: protected и internal, но пользы от них не так много и поэтому о них обычно мало-кто помнит (см. подробности в документации).