Transition PageCurl to Scroll with UIPageViewController

Question: I would like to change my animation between the view.
Currently i have the PageCurl but i would like to have a Scroll animation like Snapchat.
I can not use the var transitionStyle: UIPageViewControllerTransitionStyle { get }

My ViewController :
import UIKit

class ViewController: UIPageViewController, UIPageViewControllerDataSource{

    let pageViewController = UIPageViewController(transitionStyle: .Scroll, navigationOrientation: .Horizontal, options: nil)
    var messagesViewController : MessagesViewController!
    var searchViewController : SearchViewController!
    var friendsViewController : FriendsViewController!

    override func viewDidLoad() {
        super.viewDidLoad()

        // set UIPageViewControllerDataSource
        self.dataSource = self

        // Reference all of the view controllers on the storyboard
        self.messagesViewController = self.storyboard?.instantiateViewControllerWithIdentifier("messagesViewController") as? MessagesViewController
        self.messagesViewController.title = "Messages"

        self.searchViewController = self.storyboard?.instantiateViewControllerWithIdentifier("searchViewController") as? SearchViewController
        self.searchViewController.title = "Search"

        self.friendsViewController = self.storyboard?.instantiateViewControllerWithIdentifier("friendsViewController") as? FriendsViewController
        self.friendsViewController.title = "Friends"

        // Set starting view controllers
        var startingViewControllers : NSArray = [self.searchViewController]
        self.setViewControllers(startingViewControllers, direction: .Forward, animated: false, completion: nil)
    }

    func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? {

        switch viewController.title! {
        case "Messages":
            return nil
        case "Search":
            return messagesViewController
        case "Friends":
            return searchViewController
        default:
            return nil
        }
    }

    // pink green blue

    func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController? {

        switch viewController.title! {
        case "Messages":
            return searchViewController
        case "Search":
            return friendsViewController
        case "Friends":
            return nil
        default:
            return nil

        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

Answer: From the Apple Docs:
"The value of this property is set when the page view controller is initialized, and cannot be changed."
You must specify the transition style when you initialize.  If you do that in code, you will need something like:
let pageViewController = ViewController(transitionStyle: .Scroll, navigationOrientation: .Horizontal, options: nil)

(Since ViewController is a subclass of UIPageViewController)
If you are setting up the Page View Controller in a storyboard, amend the transition style in the attributes inspector:
Comment: `UIPageViewController` has only two transition styles: `Scroll` or `PageCurl`.  `FlipHorizontal` is a `UIModalTransitionStyle` used when a view controller is presented modally.  If you want FlipHorizontal, or something similar, you will need to use something other than a UIPageViewController.
Comment: With the last version of Xcode i have choose the "Flip horizontal" in transition style in the playground. but nothing work. I add the let pageViewController too mais but nothing change :/
Comment: No i want the same transition than snapchat, how can i do that please.
Comment: How do you create the above ViewController?  Via a storyboard/segue or in code?
Comment: I have create my view controller on the playground with the same name in the code paste in the question.
Comment: You should use the line `let pageViewController = ....` directly in the playground - you don't need to add it to the start of your class definition.
Answer: If you need to use storyboard and still need to set the transition style in code you can use this trick in the Class you made inheriting UIPageViewController. The trick is that in the init with coder you call super.init() which takes transition style like this
class ViewController: UIPageViewController {

    required init?(coder: NSCoder) {
        super.init(transitionStyle: Configs.transitionStyle, navigationOrientation: .horizontal, options: nil)
    }
}

Comment: This works for me, but it botthers me not calling the init(coder:) initializer... I'm not sure if we're supposed to do this...


IDL WHERE in python?

Question: I am having trouble translating an old IDL script to python- my issue lies in understanding exactly how to interpret IDL's "WHERE" function.
Here is my code:
FUNCTION noise,day,y

N = N_ELEMENTS(y)
valid = WHERE(ABS(day[0:N-3]-day[2:N-1]) LT 20,cc)
IF cc LT 2 THEN RETURN,[-9.99,-9.99,-9.99,-9.99]

y_int = (y[0:N-3] * (day[2:N-1] - day[1:N-2]) + y[2:N-1] * (day[1:N-2] - day[0:N-3]))/ (day[2:N-1] - day[0:N-3])
dif  = ABS(y_int - y[1:N-2])
difR = ABS(y_int/y[1:N-2] - 1.)

dif = dif [valid]
difR= difR[valid]

; Remove 5% of higher values
Nv = LONG(cc*0.95)
s = SORT(dif) & s = s[0:Nv-1]
noise5 = SQRT(TOTAL(dif[s]^2)/(Nv-1)) ; Absolu Noise minus 5% of higher values
noise = SQRT(TOTAL(dif^2)/(cc-1)) ; Absolu Noise

s = SORT(difR) & s = s[0:Nv-1]
noiseR5 = SQRT(TOTAL(difR[s]^2)/(Nv-1)) ; Relative Noise minus 5% of higher values
noiseR = SQRT(TOTAL(difR^2)/(cc-1)) ; Relative Noise

RETURN,[noise5,noiseR5*100.,noise,noiseR*100.]

END

Can anyone help me understand the python equivalent? TY.
Comment: What is the objective of this script?
Comment: Obtain BRDF Coefficients
Answer: I would translate:
valid = WHERE(ABS(day[0:N-3]-day[2:N-1]) LT 20,cc)

as:
valid = (numpy.abs(day[0:-2] - day[2:]) < 20).nonzero()

IDL WHERE in python?


TableView não exibe os dados com JavaFx

Question: Bom dia, estou montando um layout com tableView carregado com informações do banco de dados e FXML, ao executar percebi que o tableview recebe os valores do meu dao pois ele exibe exatamente a quantidade de linhas vinda da query, ao fazer um foreach e os dados estão ok, porém o tableview aparece sem as linhas preenchidas.
Fonte: controller
public class TableViewController {
private TagsDAO dao;
private List<Tags> tagsList;
//private DateTimeFormatter fomatador = DateTimeFormatter.ofPattern("dd/MM/yyyy");
@FXML
private TableView<Tags> tbv1;
@FXML
private void initialize(){
    //obtém o objeto DAO
    dao = DAOFactory.getTagsDAO();
    // Adiciona um listener para ser notificado quando o usuário seleciona um item na tabela.
    // Dessa forma é possível definir os bindings corretamente.
    loadData();
}
private void loadData(){
    try {
        tagsList = dao.load();
        ObservableList<Tags> list = FXCollections.observableArrayList(tagsList);
        tbv1.setItems(list);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

}
Método DAO
public List<Tags> load() {
    try (Connection conn = ConnectionFactory.openConnection()) {
        sql = "SELECT dt.Tag, dt.Id FROM DadoTag dt ORDER BY dt.Id ASC";
        try (PreparedStatement stmt = conn.prepareStatement(sql)) {
        // executa a busca
        try (ResultSet rs = stmt.executeQuery()) {
            List<Tags> tags = new ArrayList<>();

            // para cada registro encontrado na tabela, cria um objeto
            // Tag e coloca na lista
            while (rs.next()) {
                Tags tagsModel = new Tags();
                tagsModel.setDescTag(rs.getString("Tag"));
                tagsModel.setId(rs.getInt("Id"));
                tags.add(tagsModel);
            }

            return tags;
        }

    }
} catch (SQLException e) {
    alert = new Alert(AlertType.ERROR);
    alert.setTitle("...");
    alert.setHeaderText("Erro");
    alert.setContentText(e.toString());
    alert.showAndWait();
    throw new DAOException(e);
}

}
FXML:
<TableView fx:id="tbv1" layoutX="8.0" layoutY="9.0" prefHeight="215.0" prefWidth="316.0">
          <columns>
            <TableColumn text="TAG" prefWidth="100">
                <cellValueFactory property="TAG"/>
            </TableColumn>
          </columns>
        </TableView>

Comment: Veja se isso te ajuda: http://code.makery.ch/library/javafx-8-tutorial/pt/part2/
Comment: Bom dia, obrigado pela resposta, eu já tinha visto o tutorial e tentando fazer desta forma e mesmo assim não obtive sucesso. Grato pela ajuda.
Answer: Dentro do seu método List load()
já tentou popular as colunas da tableview para somente depois retorná-la?
Por exemplo:
Coluna "NOME" (clName)
clName.setCellValueFactory(data->data.getValue().getName());
E na classe da respectiva entidade, por exemplo:
public class Person {
private final StringProperty Name;
public Person(String Name) {
        this.firstName = new SimpleStringProperty(Name);
}

public String getName() {
    return Name.get();
}

public void setName(String Name) {
    this.Name.set(Name);
}

public StringProperty NameProperty() {
    return Name;
}

}
Desta forma teu método ficaria:
 public List<Tags> load() {
     try (Connection conn = ConnectionFactory.openConnection()) {
         sql = "SELECT dt.Tag, dt.Id FROM DadoTag dt ORDER BY dt.Id ASC";
         try (PreparedStatement stmt = conn.prepareStatement(sql)) {
         // executa a busca
         try (ResultSet rs = stmt.executeQuery()) {
             List<Tags> tags = new ArrayList<>();

             // para cada registro encontrado na tabela, cria um objeto
             // Tag e coloca na lista
             while (rs.next()) {
               Tags tagsModel = new Tags();
               tagsModel.setDescTag(rs.getString("Tag"));
               tagsModel.setId(rs.getInt("Id"));
               tags.add(tagsModel);
            }

           **//populando a coluna Name da TableView
           clName.setCellValueFactory(data->data.getValue().getName());**

           return tags;
       }

   }

TableView não exibe os dados com JavaFx


Dovecot Unable to access letsencrypt certificates on LEMP server

Question: I am attempting to setup postfix and dovecot on a LEMP server. I am using letsencrypt certificates. I suspect I am having a permissions problem because I cannot access the /etc/letsencrypt/live folder using cd unless I preface it with the sudo su command.
This seems to be affecting my dovecot configuration because dovecot is giving me the following fatal error:

doveconf: Fatal: Error in configuration file
  /etc/dovecot/conf.d/10-ssl.conf line 13: ssl_key: Can't open file
  /etc/letsencrpyt/

I have checked my letsencrypt certificate and pemchain path in dovecot settings multiple times and they are correct. So it appears that something else is blocking dovecot from accessing my certificate chain. I'm assuming it is the same thing that won't let me access my chain with out being root.
The Top of my /etc/dovecot/conf.d/10-ssl.conf page looks like this:
##
## SSL settings
##

# SSL/TLS support: yes, no, required. <doc/wiki/SSL.txt>
ssl = required

# PEM encoded X.509 SSL/TLS certificate and private key. They're opened before
# dropping root privileges, so keep the key file unreadable by anyone but
# root. Included doc/mkcert.sh can be used to easily generate self-signed
# certificate, just make sure to update the domains in dovecot-openssl.cnf
ssl_cert = </etc/letsencrypt/live/mail.mysite.com/fullchain.pem
ssl_key = </etc/letsencrpyt/live/mail.mysite.com/privkey.pem

My /etc/dovecot/conf.d/10-ssl.conf has the following lines uncommented and edited. I am not actually using mail.mysite.com :
ssl = required
ssl_cert = </etc/letsencrypt/live/mail.mysite.com/fullchain.pem
ssl_key = </etc/letsencrpyt/live/mail.mysite.com/privkey.pem
ssl_client_ca_dir = /etc/ssl/certs
ssl_dh = </usr/share/dovecot/dh.pem

The Results of:
ls -l /etc | grep letsencrypt
drwxr-xr-x  9 root  root     4096 Feb 20 12:44 letsencrypt

My question is, how can I fix the above error and allow dovecot to access my letsencrypt certificate path correctly?
Comment: Show your dovecot configuration lines. Permissions shouldn't be problem, because dovecot opens these files while running as root.
Comment: And also - what are permissions on `/etc/letsencrypt`? Show result of this command `ls -l /etc | grep letsencrypt`.
Comment: I updated the question to include the requested information.
Answer: Damn spelling. :) Didn't catch this myself first time. You have letsencrPYt in your config, and it's clearly shown in error message as well.
Comment: Wow! Thank you!!!!!!!!
Comment: Homer simpson 'Doh'! Thankyou thank you! I have been going over this for days! Somehow I totally looked over the spelling! Thank you!
Answer: To solve this, I just had to spell ssl_key = </etc/letsencrpyt correctly for my ssl_key.
The proper syntax is:
ssl_key = </etc/letsencrypt/live/mail.mysite.com/privkey.pem

NOT
ssl_key = </etc/letsencrpyt/live/mail.mysite.com/privkey.pem


$\{f_n\}$ is uniformly convergent on $[-\alpha, \alpha]$ for and $\alpha>0.$

Question: Let $\{a_n\}$ is sequence of bounded numbers and $$f_n(x)=a_0+a_1x+\frac{a_2x^2}{2!}+...+\frac{a_nx^n}{n!}.$$ Then $\{f_n\}$ is uniformly convergent on $[-\alpha, \alpha]$ for and $\alpha>0.$
First I tried to find the limit function, but I failed.
\begin{align*} \lim f_n(x)&=\lim (a_0+a_1x+\frac{a_2x^2}{2!}+...+\frac{a_nx^n}{n!}) \\ & < M\lim (1+x+\frac{x^2}{2!}+...+\frac{x^n}{n!}) = Me^x.\end{align*} But how can I find the limit function, or is there any way to show uniform convergence without finding limit function?
Comment: Weierstraß $M$-test.
Answer: One can prove that the sequence $\left(f_n\right)_{n\geqslant 1}$ is uniformly Cauchy: let $m> n$ and $x\in [-\alpha,\alpha]$. Then
$$
\lvert f_m(x)-f_n(x)\rvert=\left\lvert \sum_{j=n+1}^ma_jx^j/j!\right\rvert
$$
and using the triangle inequality, the fact that $\lvert a_jx^j\rvert\leqslant \sup_{k\geqslant 1}\lvert a_k\rvert\cdot \alpha^j$ and the series $\sum_{j\geqslant 1}\alpha_j/j!$ converges gives that
$$
\lim_{m,n\to +\infty}\sup_{x\in [-\alpha,\alpha]}\lvert f_m(x)-f_n(x)\rvert=0.
$$


Disable driver signature enforcement on AWS (Amazon) server | Windows 2012

Question: I need to disable driver signature enforcement on a Windows 2012 that is running on Amazon AWS.
So there is no way for me to get to the server on the restart screen to choose that feature on the server starting phase.
Answer: Run in elevated cmd and then reboot:
bcdedit -set loadoptions DDISABLE_INTEGRITY_CHECKS
bcdedit -set TESTSIGNING ON

Note that extra D in DDISABLE_INTEGRITY_CHECKS is not a typo.
More information:

Enable the Intel 82579V NIC in Windows Server 2012
HOWTO: Create a Boot Configuration That Has No Driver Signature Checks. Disable Driver Integrity Checks and Install a Custom Non-Signed Driver

I've tried that but it still won't work, the server is restarting in
  "Test Mode"

Looks like support for DDISABLE_INTEGRITY_CHECKS was removed.

when I try to install the driver (Ghostscript PDF) the wizard tell me
  its unsigned when I press next ofter giving the printer a name it
  won't go to the next step...

There is alternate ways to get unsigned driver installed. Given that you already have your Windows in Test Mode you can sign Ghostscript driver yourself or just grab already signed binaries from here
More information:

Driver Signature Enforcement Overrider 1.3b (Gui tool to test-sign files)

If everything fails, you can also try ReadyDriver Plus (tutorial) , but it will be hard to debug if it fails, because you don't have access to boot menu.

ReadyDriver Plus install itself as boot.bin file, and then modifies
  Windows Vista Boot Configuration Data (BCD), which is then read by
  Windows Boot Manager (the bootloader for Vista) to load ReadyDriver.
  When Windows Vista boot loader reads BCD, it loads ReadyDriver which
  will then makes the appropriate selection to disable Signed Driver
  Signature Enforcement, based on what user choose to install. So in a
  way, ReadyDriver Plus manages to permanently disable driver signing
  enforcement in Windows Vista, both x32 and x64, by automatically
  select "Disable Driver Signature Enforcement" option in the "Advanced
  Boot Options" menu on system startup.
Comment: Great! I'm checking your suggestion
Comment: I've tried that but it still won't work, the server is restarting in "Test Mode", when I try to install the driver (Ghostscript PDF) the wizard tell me its unsigned when I press next ofter giving the printer a name it won't go to the next step...
Comment: In this case you can test-sign driver yourself or use already signed binaries. See update.
Comment: At the end I've self signed the drivers according to the [http://stackoverflow.com/questions/19520540/signed-ghostscript-postscript-print-driver/19585322#19585322] (link you gave me here) - it worked :)


On Swipe to delete and IndexOutOfBoundsException

Question: java.lang.IndexOutOfBoundsException: Index: 1, Size: 1
line 42

at 42 line I have
        bind(items[position])

Myadapter

class RvNotesAdapter: ListAdapter<NoteData, RvNotesAdapter.NotesViewHolder>(DiffUtilCallback()) {

    var items = emptyList<NoteData>()

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): NotesViewHolder {
        val inflater = LayoutInflater.from(parent.context)
        return NoteItemLayoutBinding.inflate(inflater, parent, false)
            .let(::NotesViewHolder)
        setListData(items)
    }

    override fun onBindViewHolder(holder: NotesViewHolder, position: Int): Unit = with(holder) {
        itemView
        bind(items[position])
    }

    inner class NotesViewHolder(val layout: NoteItemLayoutBinding) : RecyclerView.ViewHolder(layout.root) {
        fun bind(item: NoteData) = with(layout) {

            val title: MaterialTextView = layout.noteItemTitle
            val content: TextView = layout.noteContentItem
            val date: MaterialTextView = layout.noteDate
            val parent: MaterialCardView = layout.noteItemLayoutParent
            val markWon = Markwon.builder(itemView.context)
                .usePlugin(StrikethroughPlugin.create())
                .usePlugin(TaskListPlugin.create(itemView.context))
                .usePlugin(object : AbstractMarkwonPlugin() {
                    override fun configureVisitor(builder: MarkwonVisitor.Builder) {
                        super.configureVisitor(builder)
                        builder.on(
                            SoftLineBreak::class.java
                        ) { visitor, _ -> visitor.forceNewLine() }
                    }
                })
                .build()

            getItem(position).let { noteData ->

                parent.transitionName = "recyclerView_${item.id}"
                title.text = item.title
                markWon.setMarkdown(content, item.content)
                date.text = item.date
                parent.setBackgroundColor(item.color)
            }
            itemView.setOnClickListener {

                val action = ViewPagerFragmentDirections.actionViewPagerFragmentToSaveUpdateFragment2()
                    .setNote(item)
                val extras = FragmentNavigatorExtras(parent to "recycler_View_${item.id}")
                //hidekeyboard
                Navigation.findNavController(it).navigate(action, extras)

            }
            content.setOnClickListener {
                val action = ViewPagerFragmentDirections.actionViewPagerFragmentToSaveUpdateFragment2()
                    .setNote(item)
                val extras = FragmentNavigatorExtras(parent to "recycler_View_${item.id}")
                //hidekeyboard
                Navigation.findNavController(it).navigate(action, extras)
            }
        }
    }
//        getItem(position).let {noteData ->
//        holder.apply {

//            parent.transitionName="recyclerView_${noteData.id}"
//            title.text = noteData.title
//            markWon.setMarkdown(content, noteData.content)
//            date.text=noteData.date
//            parent.setBackgroundColor(noteData.color)

//            itemView.setOnClickListener {
//
//                val action = ViewPagerFragmentDirections.actionViewPagerFragmentToSaveUpdateFragment2()
//                    .setNote(noteData)
//                val extras = FragmentNavigatorExtras(parent to "recycler_View_${noteData.id}")
//                //hidekeyboard
//                Navigation.findNavController(it).navigate(action, extras)
//
//            }
//            content.setOnClickListener {
//                val action = ViewPagerFragmentDirections.actionViewPagerFragmentToSaveUpdateFragment2()
//                    .setNote(noteData)
//                val extras = FragmentNavigatorExtras(parent to "recycler_View_${noteData.id}")
//                //hidekeyboard
//                Navigation.findNavController(it).navigate(action, extras)
//            }
//        }
//        }
//    }

    fun getPositionAt(position: Int): NoteData {
        return items[position]
    }

    fun setListData(list: List<NoteData>) {
        this.items = emptyList()
        this.items = list
        notifyDataSetChanged()
    }

}

fragmentNotesManager
@AndroidEntryPoint
class NotesManagerFragment @Inject constructor() :
    BaseFragment<FragmentNotesManagerBinding, NotesManagerViewModel>(
        FragmentNotesManagerBinding::inflate
    ) {
    override val vm: NotesManagerViewModel by viewModels()
    private lateinit var rvNotesAdapter: RvNotesAdapter

    override fun onCreate(
        savedInstanceState: Bundle?
    ) {
        super.onCreate(savedInstanceState)

        exitTransition = MaterialElevationScale(false).apply {
            duration = 350
        }
        exitTransition = MaterialElevationScale(true).apply {
            duration = 350
        }
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        rvNotesAdapter = RvNotesAdapter()
        recyclerViewDisplay()
        collectNotesItems()
        observerDataChanges()
        //Check this
        lifecycleScope.launch {
            activity!!.window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
            activity!!.window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
            activity!!.window.statusBarColor = Color.parseColor("#9E9D9D")
        }
        // do zmiany navigation
        val navHostFragment =
            activity!!.supportFragmentManager.findFragmentById(R.id.fragmentContainerView) as NavHostFragment
        val navController = navHostFragment.navController

        layout.addNoteFab.setOnClickListener {
            layout.appBarLayout.visibility = View.INVISIBLE
            navController.navigate(ViewPagerFragmentDirections.actionViewPagerFragmentToSaveUpdateFragment2())

        }

        layout.innerFab.setOnClickListener {
            layout.appBarLayout.visibility = View.INVISIBLE
            navController.navigate(ViewPagerFragmentDirections.actionViewPagerFragmentToSaveUpdateFragment2())
        }
        collectNotesItems()
//        collectNotesItems()
//        observerDataChanges()
        //implements search here

        layout.search.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
                layout.noData.isVisible = false
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                if (s.toString().isNotEmpty()) {
                    val text = s.toString()
                    val query = "%$text%"
                    if (query.isNotEmpty()) {
                        // livedata with observe to change
                        vm.searchNote(query).let {

                        }

                    } else {
                        collectNotesItems()
                        // obs
                    }
                } else {
                    collectNotesItems()
                    //obs
                }
            }

            override fun afterTextChanged(s: Editable?) {

            }

        })

        layout.search.setOnEditorActionListener { v, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                v.clearFocus()
                // hide keyboard
            }
            return@setOnEditorActionListener true
        }

        layout.rvNote.setOnScrollChangeListener()
        { _, scrollX, scrollY, _, oldScrollY ->

            when {
                scrollY > oldScrollY -> {
                    layout.chatFabText.isVisible = false
                }
                scrollX == scrollY -> {
                    layout.chatFabText.isVisible = true
                }
                else -> {
                    layout.chatFabText.isVisible = true
                }
            }
        }

    }

    private fun swipeToDelete(rvNote: RecyclerView) {
        val swipeToDeleteCallBack = object : SwipeToDelete() {
            override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
                val positionAdapter = viewHolder.layoutPosition
                val positionRoom = rvNotesAdapter.getPositionAt(positionAdapter).id
                val note = rvNotesAdapter.currentList[positionAdapter]

                val noteResponse = NoteDataDetailsResponse(
                    id = note.id,
                    title = note.title,
                    content = note.content,
                    date = note.date,
                    color = note.color
                )
                // val noteToDelete

                var actionBtnTapped = false

                vm.deleteNote(note).let {rvNotesAdapter.notifyItemRemoved(positionRoom)}

//                observerDataChanges()
//                collectNotesItems()
                layout.search.apply {
                    //hidekey
                    clearFocus()
                }
                if (layout.search.text.toString().isEmpty()) {
                    collectNotesItems()
                }
                val snackBar = Snackbar.make(
                    requireView(), "Note Deleted", Snackbar.LENGTH_LONG
                ).addCallback(object : BaseTransientBottomBar.BaseCallback<Snackbar>() {
                    override fun onDismissed(transientBottomBar: Snackbar?, event: Int) {
                        super.onDismissed(transientBottomBar, event)
                    }

                    override fun onShown(transientBottomBar: Snackbar?) {
                        transientBottomBar?.setAction("UNDO") {
                            vm.saveNote(noteResponse)
                            actionBtnTapped = true
                            layout.noData.isVisible = false
                        }

                        super.onShown(transientBottomBar)
                    }
                }).apply {
                    animationMode = Snackbar.ANIMATION_MODE_FADE
                    setAnchorView(R.id.add_note_fab)
                }
                snackBar.setActionTextColor(
                    ContextCompat.getColor(
                        requireContext(),
                        R.color.yellowOrange
                    )
                )
                snackBar.show()
            }

        }
        val itemTouchHelper = ItemTouchHelper(swipeToDeleteCallBack)
        itemTouchHelper.attachToRecyclerView(rvNote)
    }

    private fun observerDataChanges() {
        vm.getActualState()
        // again with observer
        if (vm.noteDataList.value.isNotEmpty()) {
//            collectNotesItems()
            rvNotesAdapter.submitList(vm.noteDataList.value)
//        rvNotesAdapter.notifyDataSetChanged()
        }
    }

    private fun initItemsRecyclerView() {
        swipeToDelete(layout.rvNote)
        layout.rvNote.adapter = rvNotesAdapter
    }

    private fun recyclerViewDisplay() {
        initItemsRecyclerView()
        when (resources.configuration.orientation) {
            Configuration.ORIENTATION_PORTRAIT -> setUpRecyclerView(2)
            Configuration.ORIENTATION_LANDSCAPE -> setUpRecyclerView(3)
        }
    }

    private fun setUpRecyclerView(spanCount: Int) {
        layout.rvNote.apply {
            layoutManager =
                StaggeredGridLayoutManager(spanCount, StaggeredGridLayoutManager.VERTICAL)
            setHasFixedSize(true)
//            rvNotesAdapter = RvNotesAdapter()
//    rvNotesAdapter.stateRestorationPolicy = RecyclerView.Adapter.StateRestorationPolicy.PREVENT_WHEN_EMPTY
//            adapter = rvNotesAdapter
            postponeEnterTransition(300L, TimeUnit.MILLISECONDS)
            viewTreeObserver.addOnPreDrawListener {
                startPostponedEnterTransition()
                true
            }
        }
//        collectNotesItems()
    }
    private fun collectNotesItems() {
        vm.noteDataList.collectWith(viewLifecycleOwner) {
            if(it.isEmpty()) {
                Log.d("collect", " empty $it")
                rvNotesAdapter.notifyDataSetChanged()
            } else {
                Log.d("collect", "NOT empty $it")
                rvNotesAdapter.items = it
                rvNotesAdapter.notifyDataSetChanged()
            }
        }
    }
}

NotesManagerViewMOdel
@HiltViewModel
class NotesManagerViewModel @Inject constructor(
    private val application: Application,
    private val addNotesItemsUseCase: AddNotesItemsUseCase,
    private val deleteNotesItemsUseCase: DeleteNotesItemsUseCase,
    private val getNotesItemsUseCase: GetNotesItemsUseCase,
    private val searchNotesItemUseCase: SearchNotesItemUseCase,
    private val updateNotesItemsUseCase: UpdateNotesItemsUseCase
) : BaseViewModel() {
    val noteDataList = MutableStateFlow<List<NoteData>>(emptyList())

    init {
        getActualState()
    }
    fun getActualState() {
        viewModelScope.launch {
            getNotesItemsUseCase.build(Unit).collect {
                noteDataList.value = it
                Log.d("newNoteData", "${noteDataList.value}")
            }
        }
    }

    fun updateNote(existingNoteData: NoteData) {
        viewModelScope.launch {
            updateNotesItemsUseCase.create(existingNoteData)
            getActualState()
        }
    }

    fun deleteNote(existingNoteData: NoteData) {
        viewModelScope.launch {
            deleteNotesItemsUseCase.create(existingNoteData)
            getActualState()
        }
    }
    fun saveNote(newNoteData: NoteDataDetailsResponse) {
        viewModelScope.launch {
            addNotesItemsUseCase.create(newNoteData)
            Log.d("newNoteData", "$newNoteData")
        }
    }

    fun searchNote(query: String) {
        viewModelScope.launch {
            searchNotesItemUseCase.create(query)
        }
    }
}

I would like to get my actual data after deleting and additionaly I don't get my data when I enter my fragment ( it is one of three fragments (in the list) in viewpager)
When I go to another fragment which is not related with viewpager and come back it works, after it I have my data displayed:
for example going to SaveUpdateFragment

class SaveUpdateFragment @Inject constructor() :
    BaseFragment<FragmentSaveUpdateBinding, NotesManagerViewModel>(
        FragmentSaveUpdateBinding::inflate
    ) {
    override val vm: NotesManagerViewModel by activityViewModels()
    private lateinit var navController: NavController
    private val currentData = SimpleDateFormat.getInstance().format(Date())
    private var note: NoteData? = null
    private var result = ""

    private var color = -1
    private val args: SaveUpdateFragmentArgs by navArgs()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val animation = MaterialContainerTransform().apply {
            drawingViewId = R.id.fragmentContainerView
            scrimColor = Color.TRANSPARENT
            duration = 300L
        }
        sharedElementEnterTransition = animation
        sharedElementReturnTransition = animation
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        val navHostFragment =
            activity!!.supportFragmentManager.findFragmentById(R.id.fragmentContainerView) as NavHostFragment
        val navController = navHostFragment.navController

        ViewCompat.setTransitionName(
            layout.noteContentFragmentParent, "recyclerView_${args.note?.id}"
        )

        layout.backBtn.setOnClickListener {
            navController.popBackStack()
        }

        layout.saveNote.setOnClickListener {
            saveNote()
        }
        try {
            layout.etNoteContent.setOnFocusChangeListener { _, hasFocus ->
                if (hasFocus) {
                    layout.bottomBar.visibility = View.VISIBLE
                    layout.etNoteContent.setStylesBar(layout.styleBar)
                } else layout.bottomBar.visibility = View.GONE

            }
        } catch (e: Throwable) {
            Log.d("TAG", "${e.stackTrace}")

            layout.fabColorPick.setOnClickListener {
                val bottomSheetDialog = BottomSheetDialog(
                    requireContext(),
                    R.style.BottomSheetDialogTheme
                )

                val bottomSheetView: View = layoutInflater.inflate(
                    R.layout.bottom_sheet_layout,
                    null
                )
                bottomSheetView.post {
                    bottomSheetDialog.behavior.state = BottomSheetBehavior.STATE_COLLAPSED
                }
                with(bottomSheetDialog)
                {
                    bottomSheetView.visibility = View.VISIBLE
                    setCanceledOnTouchOutside(false)
                    setContentView(bottomSheetView)
                    BottomSheetBehavior.from(bottomSheetView).state =
                        BottomSheetBehavior.STATE_COLLAPSED
                    val behavior: BottomSheetBehavior<*> =
                        BottomSheetBehavior.from<View>(bottomSheetView)
                    behavior.peekHeight = bottomSheetView.height
                    show()
                }
                bottomSheetDialog.show()

                val bottomSheetBinding = BottomSheetLayoutBinding.bind(bottomSheetView)
                bottomSheetBinding.apply {
                    colorPicker.apply {
                        setSelectedColor(color)
                        setOnColorSelectedListener { value ->
                            color = value
                            layout.apply {
                                noteContentFragmentParent.setBackgroundColor(color)
                                toolbarFragmentNoteContent.setBackgroundColor(color)
                                bottomBar.setBackgroundColor(color)
                                activity!!.window.statusBarColor = color
                            }
                            bottomSheetBinding.bottomSheetParent.setCardBackgroundColor(color)
                        }
                    }
                    bottomSheetParent.setCardBackgroundColor(color)
                }
                bottomSheetView.post {
                    bottomSheetDialog.behavior.state = BottomSheetBehavior.STATE_EXPANDED
                }
            }

            //open with existing note item
            setUpNote()
        }
    }

    private fun setUpNote() {
        val note = args.note
        val title = layout.etTitle
        val content = layout.etNoteContent
        val lastEdited = layout.lastEdited

        if (note == null) {
            layout.lastEdited.text =
                getString(R.string.edited_on, SimpleDateFormat.getDateInstance().format(Date()))
        }
        if (note != null) {
            title.setText(note.title)
            content.renderMD(note.content)
            lastEdited.text = getString(R.string.edited_on, note.date)
            color = note.color
            layout.apply {
                CoroutineScope(Dispatchers.Main).launch {
                    delay(10)
                    noteContentFragmentParent.setBackgroundColor(color)
                }
                toolbarFragmentNoteContent.setBackgroundColor(color)
                bottomBar.setBackgroundColor(color)
            }
            activity?.window?.statusBarColor = note.color
        }
    }

    private fun saveNote() {
        val navHostFragment =
            activity!!.supportFragmentManager.findFragmentById(R.id.fragmentContainerView) as NavHostFragment
        val navController = navHostFragment.navController
        if (layout.etNoteContent.text.toString().isEmpty() || layout.etTitle.text.toString()
                .isEmpty()
        ) {
            Toast.makeText(activity, "Something is Empty", Toast.LENGTH_SHORT).show()
        } else {
            note = args.note
            when (note) {
                null -> {
                    vm.saveNote(
                        NoteDataDetailsResponse(
                            0,
                            layout.etTitle.text.toString(),
                            layout.etNoteContent.getMD(),
                            currentData,
                            color
                        )
                    )
                    // moze niepotrzebne we can use flow
                    result = "Note Saved"
                    parentFragmentManager.setFragmentResult(
                        "key",
                        bundleOf("bundleKey" to result)
                    )

                    Log.d("note", "$note")
//                    navController.navigate(SaveUpdateFragmentDirections.actionSaveUpdateFragment2ToViewPagerFragment())
//
                    navController.popBackStack()
                }
                else -> {
                    updateNote()
                    navController.popBackStack()
                }
            }
        }
    }

    private fun updateNote() {
        if (note != null) {
            vm.updateNote(
                NoteData(
                    note!!.id,
                    layout.etTitle.text.toString(),
                    layout.etNoteContent.getMD(),
                    currentData,
                    color
                )
            )

        }
    }
}

Answer: In list adapter you shouldn't store the items in a field inside the adapter class if you want to access a specific item you can use this code:
currentList[position]

and when you want to update recycler view list just call this function:
adapter.submitList(newList)

list adapter will be handling the notifyDataSetChanges and you shouldn't call this function too.


Apagar um ficheiro executável ( .exe ) após finalizar sem saber a sua localização?

Question: O ficheiro bat foi convertido em executável.
O comando del "%~f0" não funciona! Será necessário terminar a execução do executável primeiro taskkill /f "nome_do_executável.exe" e só depois o eliminar?
Questão:
- Como localizar o ficheiro no windows e o eliminar?
Desde já obrigado @SachaDee pelo %~dpnx0!
start "nome_da_aplicação" cmd.exe /k "mode 90,5 & del /s /q %~dpnx0 >nul 2>&1 & exit"

Comment: testou `del "%~dpnx0"`no final do script ?
Comment: @SachaDee sim, obrigado!
Comment: A onde posso encontrar informação sobre 'dpnx'?
Comment: com `for /?` (ultima tela)
Comment: @SachaDee, obrigado!
Comment: @SachaDee, O comando `del /s /q "%~dpnx0"` parece não estar a funcionar no executável... Mas se utilizar `start cmd /k  "del /s /q %~dpnx0"` funciona, só que uma nova janela é aberta! Como fechar essa janela num comando só? Ex: `start cmd /k  "del %~dpnx0 & exit /b"`?
Comment: executar taskkill pode fazer com que o Windows Defender exclua seu arquivo executável
Comment: @Sveen Como... assim? `taskkill /F /FI "WindowTitle eq  Administrator: nome_do_programa" /T >nul 2>&1 & del /s /q "%~dpnx0" & exit /b`?
Comment: Se utilizar `start cmd /k  "del %~dpnx0"` vai funcionar (mas depois fica uma linha de comandos aberta), só se terminar a linha de comandos com o taskkill! Parece-me um bocado martelado... Não existe a possibilidade em efetuar tudo junto dentro do `""`?
Comment: O Windows Defender verifica se o programa executa um comando como taskkill e classifica com malware.
Comment: Tente assim @b8engl : `start cmd /k "del %~dpnx0 && exit"`
Comment: @ SachaDee Bem jogado!
Answer: Pode usar isso no final do script bat :
start cmd /k  "del %~dpnx0"


LogicException node save via ResourceBase post()

Question: When i try to create a node via rest api (8.4) I keep getting

LogicException: The controller result claims to be providing relevant cache metadata, but leaked metadata was detected. Please ensure you are not rendering content too early. Returned object class: Drupal\rest\ResourceResponse

The node is created but my app recieves an error.
the end point code is as follows
<code>namespace Drupal\transactions\Plugin\rest\resource;
use Drupal\rest\Plugin\ResourceBase;
use Drupal\rest\ResourceResponse;
use Drupal\node\Entity\Node;

/**
 * Provides a Transactions Resource
 *
 * @RestResource(
 *   id = "transactions",
 *   label = @Translation("Stripe Transactions"),
 *   uri_paths = {
 *     "canonical" = "/api/v1/transactions",
 *     "create" = "/api/v1/transactions",
 *   }
 * )
 */

class TransactionsResource extends ResourceBase{

  public function get() {
    return new ResourceResponse("Implement REST State GET!");
  }

  /**
   * Responds to entity POST requests.
   * @return \Drupal\rest\ResourceResponse
   */
  public function post($payload) {
    $recipient = Node::create([
      'type' => 'recipient',
      'field_firstname'=>"name3",
      'field_lastname'=>"name2",
      'field_mobile'=>"3128371973193",
      'field_city'=>"london",
      'field_country_to'=>"UK"
    ]);
    $recipient->save(); //error occurs here

  $response = new ResourceResponse(['nid', $recipient->id()]);
  $response->addCacheableDependency($recipient);

    return $response;
  }

}
</code>
Answer: Responses to a POST request should not be cached. Use an uncacheable response like ModifiedResourceResponse:
<code>  $response = new ModifiedResourceResponse(['nid', $recipient->id()]);
</code>


Showing that cosine is continous (not uniformly continuous)

Question: I know that there exist many proofs that show $cos(x)$ is uniformly continous that rely on Lipschitz continuity and/or the mean value theorem. However, how can I show that $cos(x)$ is continuous in the first place? The mean value theorem requires that the function be differentiable (hence continuous) in the first place so I can't really use it without proving continuity.
Comment: Use the definition of continuity.
Comment: How do you define $\cos$? If you use the Taylor series, then continuity and differentiability follow since the radius of convergence in $\infty$.
Answer: Use the unit circle.  Suppose $0< x < \pi/2$.  Then if you progress clockwise on the unit circle distance $x,$
you arrive at the point $(\cos(x), \sin(x))$.
The shortest distance to the origin from this point is $\sin(x)$.  That is shorter than the distance traveling along the unit circle, which is $x$.  We therefore know
$$\sin(x) < x, \qquad 0 < x <\pi/2.$$
You should be able to use the properties of sine and cosine to get to your general result.
Comment: Indeed, using this approach you have $\|(\cos x, \sin x) - (\cos y, \sin y)\| \le |x-y|$ directly.
Answer: $\begin{array}\\
\cos x-\cos y
&=-2\sin((x+y)/2)\sin((x-y)/2)\\
\text{so}\\
|\cos x-\cos y|
&=2|\sin((x+y)/2)\sin((x-y)/2)|\\
&\le 2|\sin((x-y)/2)|
\qquad\text{since } |\sin| \le 1\\
&\le |x-y|
\qquad\text{since }|\sin(z)| \le |z|\\
\end{array}
$


How to verify that the input text allows the first and second digits to be only letters

Question: I need to validate a input text, the first 2 digits only letters after adding a hyphen and finally 5 numerical digits.
format example: aa-12345
now i have
<asp:TextBox ID="txtCodigoTopografo" onkeydown="test(this)"   runat="server"></asp:TextBox>

function test(e) {
        console.log(e);

        switch (e.value.length) {

            case 0:
                if (e.value)
                e.value = e.value.replace(/[^a-z]/gi, '');
                break;

            case 1:
                e.value = e.value.replace(/[^a-z]/gi, '');
                break;
            case 2:
               e.value = e.value.replace(/[^0-9]/gi, '');
                break;
            case 3:
                e.value = e.value.replace(/[^0-9]/gi, '');

                break;
        }

    }

Answer: Your current method is trying to replace stuff with regex. Instead, use regex to verify your input string is in the correct format.
This regex assumes the letters must be lower case. You can change [a-z] to [A-z] if you allow upper or lower case.

function test() {
  var textboxContent = document.getElementById("input").value;
  var passed = /^[a-z]{2}-\d{5}$/.test(textboxContent);

  if (passed) {
    document.getElementById("result").textContent = "Passed!";
  } else {
    document.getElementById("result").textContent = "Failed!";
  }
}
<input type="text" id="input" placeholder="Type here!" oninput="test()" />

An explanation of the regex:

^     Match the start of the input. Used so that you don't match part way along the input
[a-z] Match a lowercase letter...
{2}   ...2 times (you could do "[a-z][a-z]" instead)
-     Match hyphen
\d    Match a digit...
{5}   ...5 times (you could do "\d\d\d\d\d" instead)
$     Match the end of the input. Used so that you don't match part way along the input


Alterar classe css de um item já renderizado pelo ng-repeat

Question: Necessito de uma ajuda com AngularJs (1.6), eu preciso alterar a classe css de apenas um ou mais itens ja renderizados pelo ng-repeat.
Vi em alguns lugares que clicando no item é possível enviar seu $index e assim alterar a classe apenas desse elemento, o que me ajudaria, porém eu necessito que isso seja alterado pela controller, sem passar o $index pela view.
Eu sei qual $index precisa alterar, só preciso saber como alterar ele depois de renderizado sem passar passar nada pela view.
Exemplo, eu tenho isso e quero alterar a classe dinamicamente do 3 (ou 4, 5) item já renderizado.

{{item.item}}

{{item.alterarClasseDesseItem}}

Answer: Tem algumas possíveis soluções:
EXEMPLO 1:
Uma forma usando o "jeito Angular", seria usar o ng-class e alterá-lo dinamicamente, assim:

{{item.item}}

e na controller:
$scope.classeDinamica= 'nome-da-classe';

Mas isso irá alterar todos os elementos com classeDinamica, e pelo que vi não é isso que você quer.
EXEMPLO 2
Para um elemento em especial, você pode usar um seletor, o que não é muito o "jeito angular", mas funciona:
angular.element(document.querySelector('#li-1')).addClass('nome-da-classe')

EXEMPLO 3
Uma outra solução mais elegante no "jeito angular" é usar uma expressão lógica com ng-class usando o elemento ou o próprio objeto que foi feito o binding, no seu exemplo item:

{{item.item}}

e na controller, já que você sabe qual o elemento (usei o índice x):
$scope.itens[x].selecionado = true;

Isso irá aplicar a classe quando o atributo selecionado do item seja igual a true.
EXEMPLO 4
Por fim, se for somente um item selecionado em vários, e como você disse que tem o $index, você pode criar um valor no $scope pra guardar o elemento selecionado, baseado no $index e fazer como no elemento anterior de um ng-class condicional, assim:

{{item.item}}

e finalmente na controller:
$scope.itemSelecionado= $index;

Alguma dessas soluções deve te ajudar


Azure function how to use DefaultAzureCredential for development using Visual studio

Question: I creating an Azure Function app with ServiceBusTrigger. I am running Visual Studio under an account which is also used to logging into Visual Studio.
I have added this user account under Service Bus Access Control & assigned Azure Service Bus Data Receiver and Azure Service Bus Data Sender roles.
[FunctionName("Function1")]
        public void Run([ServiceBusTrigger("topic-one", "sub-one", Connection = "ServiceBusConnString")]string mySbMsg)
        {
            var credentail = new DefaultAzureCredential();
            _logger.LogInformation($"C# ServiceBus topic trigger function processed message: {mySbMsg}");
        }

This is how local.settings.json file look:
{
    "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "UseDevelopmentStorage=true",
    "FUNCTIONS_WORKER_RUNTIME": "dotnet",
    "ServiceBusConnString__serviceUri": "https://sb-test-three.servicebus.windows.net/",
    "ServiceBusConnString__fullyQualifiedNamespace": "https://sb-test-three.servicebus.windows.net/",
    "ServiceBusConnString": "https://sb-test-three.servicebus.windows.net/ManagedIdentity",
    "ConnectionString": "https://sb-test-three.servicebus.windows.net/"
  }
}

I am getting below error when running the app locally using Visual Studio.

How can I run Azure function from Visual Studio using managed identity? I am not sure how to use DefaultAzureCredential class
Comment: can you try changing the `ServiceBusConnString` to `Endpoint=sb://sb-test-three.servicebus.windows.net/;Authentication=ManagedIdentity` ?
Comment: @Jayendran I am not getting following error: `The listener for function FunctionWthMI was unable to start. Azure.Messaging.ServiceBus: The connection string used for an Service Bus client must specify the Service Bus namespace host and either a Shared Access Key (both the name and value) OR a Shared Access Signature to be valid. (Parameter 'connectionString').` . I added following `"ServiceBusConnString": "Endpoint=sb://sb-test-three.servicebus.windows.net/;Authentication=ManagedIdentity",`
Comment: did you make sure the version of  `Microsoft.Azure.WebJobs.Extensions.ServiceBus version` 5.x ? https://learn.microsoft.com/en-us/dotnet/api/overview/azure/microsoft.azure.webjobs.extensions.servicebus-readme-pre
Comment: @Jayendran: I am using version 5.7.0  ``
Answer: Looks like you only need ServiceBusConnString__fullyQualifiedNamespace for the managed identity and you can remove the below configs
 "AzureWebJobsStorage": "UseDevelopmentStorage=true",
    "ServiceBusConnString__serviceUri": "https://sb-test-three.servicebus.windows.net/",
    "ConnectionString": "https://sb-test-three.servicebus.windows.net/"

You only need the below
    "FUNCTIONS_WORKER_RUNTIME": "dotnet",
    "ServiceBusConnString__fullyQualifiedNamespace": "sb-test-three.servicebus.windows.net",

And make sure you identity is having the below Roles

Azure Service Bus Data Receiver
Azure Service Bus Data Owner

Refer the official docs
Comment: No luck with the change. May be I am making some basic mistake.
Comment: whats error you are getting? For me its working fine
Comment: I am getting following error `(Stored credentials not found. Need to authenticate user in VSCode Azure Account. See the troubleshooting guide for more information. https://aka.ms/azsdk/net/identity/vscodecredential/troubleshoot) (Please run 'az login' to set up account) (Az.Account module >= 2.2.0 is not installed.). System.Private.CoreLib: EnvironmentCredential authentication unavailable. Environment variables are not fully configured. See the troubleshooting guide for more information. https://aka.ms/azsdk/net/identity/environmentcredential/troubleshoot.`
Comment: looks like you have to add your account in vs code using azure account extension. Also the error mentioned the az.account module is not installed with right version you have to install that too
Comment: I am not using Visual Studio code and that is why I am confused why do I need to install extension is VS Code ? To Install AZ.Account module I used ` Install-Module -Name Az.Accounts -RequiredVersion 2.2.3`  command. at the time of Installation I am getting warning `You are installing the modules from an untrusted repository` What is the best way to handle this ?
Comment: You can ignore the warning and proceed with the installation. After the installation, Do `az login` and use the interactive login with your creds and try again running the code. Since you are debugging from login you have to login using azure cli using your creds
Comment: Now there are no errors but service bus trigger is not firing even though service bus has 20 messages
Comment: after running the function, can you insert a new message from the azure portal and see whether it triggers


Random effects model handling redundancies

Question: I am trying to deal with a time-to-event analysis using repeated binary outcomes.  Suppose that time-to-event is measured in days but for the moment we discretize time to weeks.  I want to approximate a Kaplan-Meier estimator (but allow for covariates) using repeated binary outcomes.  This will seem like a roundabout way to go but I'm exploring how this extends to ordinal outcomes and recurrent events.
If you create a binary sequence that looks like 000 for someone censored at 3 weeks, 0000 for someone censored at 4w, and 0000111111111111.... for a subject who failed at 5w (the 1s extend to the point at which the last subject was followed in the study), when you compute week-specific proportions of 1s you can get ordinary cumulative incidences (until you get to variable censoring times, where this only approximates but doesn't equal Kaplan-Meier cumulative incidence estimates).
I can fit the repeated binary observations with a binary logistic model using GEE, instead of making time discrete as above but instead using a spline in time.  The cluster sandwich covariance estimator works reasonably well.  But I'd like to get more exact inference by using a mixed effects model.  The problem is the that the 1's after the first 1 are redundant.  Does anyone know of a way to specify random effects or to specify a model that takes the redundancies into account so that standard errors will not be deflated?
Note that this setup differs from Efron's because he was using logistic models to estimate conditional probabilities in risk sets.  I'm estimating unconditional probabilities.
Answer: As far as I can see with both the GEE or a mixed model for repeated binary observations, you will have the problem that the model will assign a positive probability for a '0' after the first '1' has been observed.
In any case, given that you want to get estimates from a mixed effects logistic regression that will have the same interpretation as in the GEE (see here for more info), you could fit the model using the mixed_model() function from the GLMMadaptive package, and then use marginal_coefs(). For an example, see here.
Comment: Thanks Dimitris.  For my case with redundant 1's (to get the mean function right) I think I'll need a modified model or a strange random effects setup.  The `GLMMadaptive` package looks terrific for the more general setup.
Answer: Couple of thoughts about this:

It seems that a mixed-effect model is fundamentally a 'conditional' probability model, i.e., what is the probability of an event for a subject that is at risk for that event.
We know the probability of a '1' after the first '1' is one. Thus, there is no additional information in the subsequent '1' values.
It seems that, because subsequent '1' values contain no additional information, they should have no impact on the likelihood function, and thus have no impact on standard errors of likelihood-based estimators, nor the estimates themselves. Indeed, there would be no impact of subsequent '1' values if p(y='1'|x)=1 regardless of model parameter values, as it should be.
We might be able to force this behavior (i.e., p(y='1'|x)=1), and retain the desired mean function, by adding an indicator covariate to the model that marks subsequent ones, and by forcing its coefficient to be very large so that effectively p(y='1'|x)=1.
As you mentioned, there may also be a way to force the first '1' and subsequent responses to have 100% correlation. But in a binomial model, that is the same as p(y='1'|x)=1 for subsequent responses.
Comment: Thanks Matt.  If I wasn't wanting a full model but was content with estimating equations, what you are getting at is adding the duplicate responses to the score function to get the mean function right, but not adding them to the information function.  I don't think I can add an indicator covariate, because that would take about from, e.g., the treatment effect.  I think of the mixed effect model as more of an unconditional model.  When the event is not an absorbing state, you're modeling marginal effects in a time-dependent way.
Answer: I'm not exactly sure what you're trying to do, but can you fit a pooled logistic regression model (https://www.ncbi.nlm.nih.gov/pubmed/2281238)? In this case you would only include 1 during the interval of the terminal event -- it would not repeat after the event has occurred.  You would include time in the model in a flexible manner (e.g., expanded using splines).
Comment: Hey Bryan - I really like pooled logistic regression and have used it often.  But if you terminate a subject's observations at the terminal event, and have other subjects followed beyond that point without an event, you'll get the mean function (P(event by time t)) wrong.  I want to get near-Kaplan-Meier cumulative incidence estimates for the mean function at least in special cases.


Guitar training issues

Question: I am an amateur having some issues with my guitar playing practice. I am not sure if my question is appropriate, but I can't make it shorter for now, because the issues I am talking about might intersect somewhere.
These are my issues:

I find it awkward to play with right and left hand from
time to time. Could anyone recommend some good posture tutorial? If someone had similar problems, I'd like to listen about the solution.
When I am practicing playing with metronome, repetition becomes very
boring even after 10 minutes, especially when I am trying to play
slower. Is there a better method to train with it? I've read about using
background melody and I'll give it a try. Should I give a try to Guitar Pro too? It has a slow-down mode, but I think it distorts the melody a bit.
When I am using electric guitar, I can't find the proper tuning and I am never happy with its sound. Should I play with current sound for now, or should I watch some tutorials about basics of tuning? It would be nice if someone will recommend these.

Each time I train I become very irritated by these problems. Thanks for any advice.
Comment: What exactly is the first problem? Play with right and left hand from time time? That you play left handed and then right handed?
Comment: A session with a tutor would solve all of these problems.
Answer: I'm just getting started learning guitar, so please feel free to take my answer with a pinch of salt. I've tried learing guitar many times but always end up giving up due to the lack of progress I appeared to be making. My recommendation is to simply stick with it. Yes it will get boring at times, yes you will get irritated, but the only way is to battle through until it starts to 'click'.
For me it was finding the Justin Sandercoe tutorials that convinced me to have another go, his recommendation is to practice a little but often. 4 or 5 15 minute practice sessions a week are far more enjoyable than a single hour session at the end of the week. Honestly it's far less frustrating if you can work out a simple practice routine for yourself. I find 10-15 minutes every day once I get home from work far easier to fit into my life than playing till my fingers bleed at the weekend. :-)

I find it awkward to play with right and left hand from time to time. Could anyone recommend some good posture tutorial?

http://www.justinguitar.com/en/BC-106-PostureFingerPlacement.php
Justin provides some good posture advice here. :-)

When I am practicing playing with metronome, repetition becomes very boring even after 10 minutes, especially when I am trying to play
  slower. Is there a better method to train with it? I've read about
  using background melody and I'll give it a try. Should I give a try to
  Guitar Pro too? It has a slow-down mode, but I think it distorts the
  melody a bit.

Then don't practice for 10 minutes. Again, Justin recommends some 1 minute practice sessions on his site. If you feel up to it, you can do loads of 1 minute sessions in one sitting, but if all you can handle is 1 or 2, then there's nothing wrong with that. This is meant to be fun, right? :-)

When I am using electric guitar, I can't find the proper tuning and I am never happy with its sound. Should I play with current sound
  for now, or should I watch some tutorials about basics of tuning? It
  would be nice if someone will recommend these.

I personally practice on my Strat unplugged, firstly bacause it would irritate the missus if I cranked my amp up too much, and secondly bacause I don't want to be distracted and spend hours getting the right sound for a 15 minute practice session.
As for tuning your guitar, get a cheap tuner. It's one of the best investments you can get. I've a small clip on tuner that lives on my guitar, it only cont me about £10. I check the tuning every time I pick iup the guitar. As you get more confident you'll learn how to tune by ear, but I always double check with the tuner just in case.

Each time I train I become very irritated by these problems. Thanks
  for any advice.

Stick at it, the irritation will disappear as things start to work for you. Rushing isn't going to help you one little bit. You will get better with time, honest. :-)
Best of luck.
Comment: You can get clip-on tuners for pennies. Take away the guesswork. Also little and often works better, and if you're really struggling on one particular day going away and do something else for a while, but make sure you come back that same day
Answer:
When I am practicing playing with metronome, repetition becomes very boring even after 10 minutes, especially when I am trying to play slower.

What exactly do you mean by repetitive ? A metronome is to help you keep the tempo steady. Whether practice is repetitive depends on the song/exercise you are practicing. The tempo doesn't have to do with a 'repetitive' practice.

Is there a better method to train with it?

You can use a drum machine (actual or virtual). This is a way to program drums. Instead of using a metronome which can be boring, practicing with drums is much more fun. You can also use programs like Guitar Pro or Band in a Box where you can write some chords to accompany you, and that is pretty helpful and fun as well.
Αnother thing to try would be to get a looper pedal and play the accompaniment yourself on the loop and then play on top of your own recording. This wouldn't be easy for a beginner, but it'd really interesting as you develop your playing technique.

When I am using electric guitar, I can't find the proper tuning and I am never happy with its sound.

These are two different things. First, let's talk about the tuning. There is always the standard tuning (EADGBE) and many guitarists tune to this. There are numerous alternative tunings that you can try and see which one you like best. You can google many of these tunings.
Now let's talk about the sound. The sound of the guitar itself might not be that good or it might not be to your taste. The same goes for your amp. You can also try some sounds with a pedalboard. There are pedalboards with many different sounds that can give you something you like.

Should I play with current sound for now

You can stick with that sound for now, until you find something else you like and then switch to that.

or should I watch some tutorials about basics of tuning?

You can watch some basic tutorials on how to tune to the standard tuning and then you can try alternative ones. These kind of tutorials will help a beginner.

Guitar training issues


A map which is trivial on homology but not on cohomology?

Question: Is there a map $f:X\to Y$ of connected CW-complexes which induces the trivial map $f_*=0:H_i(X,\Bbb Z) \to H_i(Y,\Bbb Z)$ for all $i\ge 1$, but with the property that the induced map on cohomology $f^*:H^i(Y,\Bbb Z)\to H^i(X, \Bbb Z)$ is nonzero for at least one $i \ge 1$?
Note that the universal coefficient theorem does not a priori imply that the induced map is trivial because the splitting $H^i(X, \mathbb{Z}) = H_i(X, \mathbb{Z})^* \oplus \operatorname{Ext}^{i-1}(X, \mathbb{Z})$ is not natural. Since I don't see any other reason against it,
I believe such a counterexample should exist.
Comment: @Pseudo: that's not true. $H^2(\mathbb{RP}^2, \mathbb{Z}) \cong \mathbb{Z}_2$ by universal coefficients, and the identity induces the identity on this.
Comment: @PseudoNeo Trivial cohomology $\implies$ trivial homology (see eg. [this](http://math.stackexchange.com/q/600323/10014)), if that helps you not repeat that mistake :)
Comment: Tiny remark: the identity map of the real projective plane gives a trivial answer to the question you **didn't** ask: it is trivial in cohomology (because the cohomology is itself trivial) but not in homology.
Comment: Oh, right. Thank you very much...
Answer: Take the $n$-sphere and attach a $n+1$-cell with a degree $m$ map. Consider $X \to X/S^{n+1}$ where $X$ is the described space.
You can write down the cellular chain complexes:
$$
\begin{array}{c}
\cdots & \to& 0 &\to& \mathbb Z&\stackrel {* m} \to& \mathbb Z &  \to  &0& \cdots \\
&&\downarrow&&\downarrow&&\downarrow \\
\cdots & \to &0&\to&\mathbb Z& \to&0&  \to  & 0 &\cdots
\end{array}
$$
Apply homology, you will kill every possible map (the degrees where the non-trivial groups lie are disjoint, except for the trivial degree).
Apply $hom(-,\mathbb Z)$ and then homology (ie cohomology), you will get on degree $n+1$ the quotient map $\mathbb Z \to \mathbb Z/m$.
Answer: you can see exercise 11 of chapter 3.1 of hatcher.let X obtained from$S^n$ by attaching a cell of degree m.you can easily see (by cellular homology and cohomology) the map
$X\to X/S^n$ is trivial on $H_i$ but not on $H^{n+1}$


PrintOut de Microsoft.Office.Interop.word.dll só realiza impressão de documento com 1 página

Question: Bom dia pessoal. Estou usanso a lib Microsof.Office.Interop.Word.dll para realizar a impressão de um documento do word.
Quando o documento tem apenas uma página, a impressão funciona normalmente.
O problema é quando tem mais de uma página, ele não funciona. Não apresenta erro nem nada, apenas não sai na impressora.
Estou usando esses parametros:
word.ActiveDocument.PrintOut(
                   true,
                   false,
                   Microsoft.Office.Interop.Word.WdPrintOutRange.wdPrintAllDocument,
                   Item: Microsoft.Office.Interop.Word.WdPrintOutItem.wdPrintDocumentContent,
                   Copies: "1",
                   //Pages: "1,2",
                   PageType: Microsoft.Office.Interop.Word.WdPrintOutPages.wdPrintAllPages,
                   PrintToFile: false,
                   Collate: true,
                   ManualDuplexPrint: false);

Já coloquei Pages: "1,2", Pages: "1-2" e nada,
Já fiz sem passar os argumentos também, e nada
Answer: Consegui resolver.
O problema era que eu estava fechando o documento logo depois do PrintOut
então alterei o codigo para esperar o términdo da impressão e só depois fechar o documento:
 Log.LoggerAPI.LogInfo("Aguarando término da impressão");
                while (word.BackgroundPrintingStatus == 1) { }

                if (word.BackgroundPrintingStatus == 0)
                {
                    Log.LoggerAPI.LogInfo("Fechando documento sem salvar as alterações");
                    doc.Close(SaveChanges: false);

                    doc = null;
                    ((Microsoft.Office.Interop.Word._Application)word).Quit(SaveChanges: false);
                    word = null;
                }


Proving that 3 regular NFA equivalent to NFA

Question:
Let 3 regular NFA be an NFA automata, which satisfies the following: $$\forall q\in Q,\forall\sigma\in \Sigma:|\delta(q,\sigma)|=3$$
Prove that the 3 regular NFA model is equivalent to NFA.

$Proof.$ we shall prove that the given 3 regular NFA model is equivalent to DFA model.
$First\ Direction.$ for the first direction, we can turn any DFA automata to 3 regular NFA automata which gets the same language, doing the following:$$\text{if}\ \delta_D(q,a)=p \  \ \text{then: } \ \delta_{N_3}(q,a)=\{p,q_{pit_1},q_{pit_2}\}$$
$Second\ Direction.$ for the second direction, we can turn any NFA automata to DFA automata which gets the same language, doing the following:
Let $N$ be 3 regular NFA, while $Q_{N_3}$ is the states' set, $\Sigma$ is the alphabet, starting state $q_0$, a set of accepted states $F_{N_3}$, and the transition function $\delta_{N_3}$. We define the following DFA:

The set of states is the set of all subsets of length 3 belongs to $Q_{N_3}$, which means that: $Q_{D} =\left\{X\in \mathcal{P}( Q_{N_{3}})\Bigl| |X|=3\right\}$.
An alphabet $\Sigma$.
a starting state ${q_0}$
An accepted states' set $F_D$: contains any subset of $Q_{N_3}$ in length 3, which contains an element from $F_{N_3}$.
A transition function $\delta_D:$ such that $\delta_D({q_1,\dots, q_k},a)$ is the set generated by the union of each $i=1,\dots ,k$ of $\delta_{N_3}(q_i,a)$

Now, we know already that the DFA model is equivalent to the NFA model, and therefore, we get that the 3 regular NFA model is equivalent to the NFA model. $Q.E.D$

I am not sure whether it's correct or not because it is a bit complex. I will be glad to see what you think.
Answer: This looks good to me! I particularly like your idea to use DFAs instead of NFAs directly, as it's easy to add transitions but potentially hard to remove transitions (which would be necessary for an NFA with some large number of out transitions). Here are a few pointers, though, to make your life a bit easier. I'll write $3$-NFA instead of $3$-regular NFA throughout, because life is short.
First, you should be a bit more clear in your DFA $\implies$ $3$-NFA direction. What are $q_{\text{pit}_1}$ and $q_{\text{pit}_2}$? You should be a bit more explicit as to their intended behavior (even though it's obvious from the names). Depending on how much of a stickler your grader is, this could matter. Similarly, it's worth taking one (1) sentence to show that your modified DFA really is a $3$-NFA. Obviously it is, but again, a mean grader could take off points for you not including a proof.
Second, there's no need to duplicate work. In showing that $3$-NFAs can be turned into equivalent DFAs, you're basically redoing the argument that a general NFA can be converted into a DFA. Of course, you've almost certainly seen this argument before, which lets you sidestep this argument entirely! Every $3$-NFA is, in particular, an NFA. So if you know that NFAs can be converted into DFAs, then you also know $3$-NFAs can be! Because a $3$-NFA is a special case of an NFA! This means you can say something like "Since any NFA has an equivalent DFA, and every $3$-NFA is an NFA, we get the $3$-NFA $\implies$ DFA direction as a corollary of an earlier result".

I hope this helps ^_^
Comment: Thank you so much! I like what you wrote and especially how you wrote it.
In addition, in the second direction, can I also define $Q_{D} =\left\{X\in \mathcal{P}( Q_{N_{3}})\Bigl| |X| \geq 3\right\}$ instead?
Comment: That probably works, but why think? Just add a state for _every_ possible subset. If you end up with some extra states, who cares. This is an existence proof, so there's no need to split hairs about efficiency
Comment: Right, but in $F_D$ I still have to take all subsets of length 3, which contains an element from $F_{N_3}$. Right? because if I just take all subsets from $F_{N_3}$ then it doesn't work right?


How to use an IF statement to pull cells only with >= XXXX

Question: I'm trying to look at the number of users who are on screens larger than 1400. I have my Excel sheet, and tried doing an IF statement, but because of the "x" in the middle, it's not working properly and is instead just pulling all of the cells, even the ones with screen sizes less than 1400. I've attached my formula and data example for reference. I've also tried putting a space after the fourth integer to separate things that way, but that also goofs things up since there are some screen sizes with only three numbers.
This is my formula:
=IF(A2>=1400,A2,"No")
Comment: you want this in google sheets ?
Comment: I'm on Excel, I threw the Google Sheets tag on just for relevance
Answer: The values in Column A are strings.  A string will always be larger than a number to Excel.  You need to parse the string to pull the first number:
<code>=IF(--LEFT(A2,SEARCH("x",A2&"x")-1)>1400,A2,"No")
</code>
Comment: Thank you! This worked. Would you mind just breaking the formula down a bit? I know the LEFT tells Excel to look for the leftmost part of the cell, but what does the -1 mean, why are there 2 "x"'s, etc.? Thank you so much for your help!!
Comment: SEARCH returns the first position of the value searching for.  We use this position to limit the left.  the `--` turns the string into a number so we can properly compare the inequality.  The second `x` is to ensure no errors in case it was written without an `x`
Comment: @ScottCraner - The `VALUE(...)` function would be clearer than `--`.
Comment: @Enigmativity it is perfectly clear to me and a lot less typing.
Comment: @ScottCraner - It's not perfectly clear to the OP and possibly not for future readers.


6 vs 7 string guitar for a student for multiple tunings

Question: I'm currently studying in an overseas University, without my guitar(s). I generally play in Standard/Eb/Drop D tunings on my 6 string, but I've been wanting to play songs that are in Drop B/Drop A.
Would it be a good idea to buy a 6 string guitar and deal with having to keep restringing for different tunings or to get a 7 string guitar and treat the low strings as a 6 string in Drop A and the high strings as a 6 string in Standard?
I've never touched a 7 string guitar in my life and I'd say that I'm only an intermediate player so the jump to a 7 string is rather intimidating. As a student budget is definitely a factor, so I wouldn't be comfortable buying two separate 6 strings just for the multiple tunings
Comment: 7 string guitars start at 129€, it can't get much cheaper than that.
Comment: Just to clarify: You would be comfortable to buy a 7 string for the other tuning, but not another 6 string (maybe a baritone?). This seems contradictory. If you are honest to yourself, are you sure you're not making up an excuse to buy a 7 string?
Comment: 7 strings aren't cheap. Take one of your guitars with you, and buy another, cheap 6 string for another tuning. Consider changing the machine heads for Hipshot Detuners. Buy a Spyder capo.
Comment: @infinitezero I genuinely don't want a 7 string for the 7 string (if that makes any sense).The only reason I want one is for the multiple tunings
Answer: Unless you have a specific reason to buy a 7-string, I'd advise buying a second 6-string to use for a different tuning - while you can use the same string gauges for, say, a drop-D tuning, you'll want to look at different string gauges for very different tunings. You still get better quality for your money with 6-strings. As @infinitezero commented, you could buy a baritone scale-length guitar.
The reason I say this is a 7 string will throw off your technique for a while - I got my first 7 string after I'd been playing for about 25 years (and had about 15 6-strings of varying types and tunings) and I got them for very specific reasons (tone, lower bass while keeping top end, experimenting with multi-scale etc) and my first few gigs with my Ibanez 7-string were a little bit of a struggle if I'm honest - I cannot easily see my guitars on stage due to my costume, so some things I had thought would be easy were actually very challenging in the heat of the moment during solos, with lights down, lasers, pyro etc
Wait awhile before you get a 7 string. So many 6 strings to play with.
Comment: It is not advisable to use the same string gauges for Standard E Tuning and Standard B Tuning. You'd use your current guitar for the standard stuff and the baritone guitar with thicker gauges for the lower tuned stuff.
Comment: for a baritone scale guitar wouldn't I still need to change the string gauge when going from say standard tuning to drop B
Comment: I'll make that more explicit in my answer.


How to fix this error I encountered while creating and accessing a remote repository in GitHub through VS code

Question:
This error is occurring when I'm trying to access a remote repository from my VS Code terminal, it seems to work on my friend's device but I'm facing this problem when i try to execute it.
Tried to delete the repository and recreated it on both GitHub and on my local machine, deleted previous instances and tried again, And I ended up with the same error.
Comment: https://stackoverflow.com/search?q=%5Bgit%5D+src+refspec+main+does+not+match+any
Answer: The error message you're seeing, src refspec main does not match any, suggests that you're trying to push a branch named main to the remote repository, but Git can't find a branch with that name in your local repository.
In the screenshot, you've run git status which shows that you're currently on the master branch. This implies that your local repository does not have a branch named main, which is why the push is failing.


CSS3 Animation for IE9

Question: Currently working on my custom jquery plugin, which only requires jquery to run.
I don't want to have to include additional 3rd party jquery plugins.
I have a CSS3 animation running on my search button when clicked which works fine except for ie9. CSS is as follows :
.loader {
    display: block;
    width: 25px;
    height: 25px;
    border-radius: 50%;
    border: 3px solid transparent;
    border-top-color: #fff;
    outline:none;
    -webkit-animation: spin 1s linear infinite; /* Chrome, Opera 15+, Safari 5+ */
    animation: spin 1s linear infinite; /* Chrome, Firefox 16+, IE 10+, Opera */
    font-size:0;
    line-height:0
}

@-webkit-keyframes spin {
    0%   {
        -webkit-transform: rotate(0deg);  /* Chrome, Opera 15+, Safari 3.1+ */
        -ms-transform: rotate(0deg);  /* IE 9 */
        transform: rotate(0deg);  /* Firefox 16+, IE 10+, Opera */
    }
    100% {
        -webkit-transform: rotate(360deg);  /* Chrome, Opera 15+, Safari 3.1+ */
        -ms-transform: rotate(360deg);  /* IE 9 */
        transform: rotate(360deg);  /* Firefox 16+, IE 10+, Opera */
    }
}
@keyframes spin {
    0%   {
        -webkit-transform: rotate(0deg);  /* Chrome, Opera 15+, Safari 3.1+ */
        -ms-transform: rotate(0deg);  /* IE 9 */
        transform: rotate(0deg);  /* Firefox 16+, IE 10+, Opera */
    }
    100% {
        -webkit-transform: rotate(360deg);  /* Chrome, Opera 15+, Safari 3.1+ */
        -ms-transform: rotate(360deg);  /* IE 9 */
        transform: rotate(360deg);  /* Firefox 16+, IE 10+, Opera */
    }
}

However it does not work in IE9, is a pure css solution I can do in IE9 to get this working ?
Comment: Sorry, but animations are not supported in IE9. http://caniuse.com/#feat=css-animation Out of luck with CSS!
Comment: Is there even a way I can do a fallback for IE9 in CSS
Comment: You can do a fallback for transform using `-ms-` prefix but CSS animations do not have any fallback for IE9.
Answer: Animation, transition and transformations are not supported in IE9 or lower. There is a support for them from IE 10+, but even in this case there are a lot of issues users find when working with IE. The best thing to do, is to work with javascript. With javascript you can avoid the CSS3 animations and run your results much better even in IE.
For looking at browser compatibility for animations, transitions and transformations look at this link: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Transitions/Using_CSS_transitions#Browser_compatibility

CSS3 Animation for IE9


Default tab by date or day

Question: I'm building a TV listing and I'm using quicktabs module with tabs:

Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday

Every tab shows a node that have a TV listing.
Is it possible these tabs to be shown by date/day?
Example: today is Monday, so when a user enters the page for TV schedule the active tab will be Monday.
I've inspected the tab links and I find out that every tab has additional link to the main URL.
Example: The first tab (in mine case - Monday) has /program?qt-quicktabs_tv_schedule=0#qt-quicktabs_tv_schedule
The second tab (in my case - Tuesday) has /program?qt-quicktabs_tv_schedule=1#qt-quicktabs_tv_schedule
etc.
EDIT:
I've tried this code:
(function($){

$(document).ready(function(){
var d = new Date();
var n = d.getDay();
$(".quicktabs-tabs li").removeClass('active');
$('#quicktabs-tab-quicktabs_tv_schedule-0' + n).parent().addClass('active');

});
})(jQuery);

The removing active class is working, but the days changing based on
var d = new Date();
var n = d.getDay();

it's not working. Maybe I'm missing something...
EDIT 2:
Here's what I've tried:
     (function($){

        $(document).ready(function(){
        var d = new Date();
        var n = d.getDay()-1;
        if ( n == -1) {
        n = 6;
        };

        $(".quicktabs-tabs li").removeClass('active');
        $('#quicktabs-tab-quicktabs_tv_schedule' + n).parent().addClass('active');
        $('.quicktabs-tabpage').addClass('quicktabs-hide');
        $('#quicktabs-tab-page-id-' + n).removeClass('quicktabs-hide');

        });

})(jQuery);

With this code it simply hides the default tab.
Comment: do you want it to sort or just make the Current day active?
Comment: I just want make the current day active.
Comment: $('#quicktabs-tab-quicktabs_tv_schedule-0' + n).parent().addClass('active'); change this to $('#quicktabs-tab-quicktabs_tv_schedule-' + n).parent().addClass('active'); this. don't have to give the 0
Comment: Thank you. It's working, however I'm still trying to figure out how to set Monday as 0, 'cos right now it's displaying Thursday.
Comment: Ahh YES, I've changed the position of the tab and now it's displaying GREAT! Thank you so much!
Comment: Good to know that it helped.
Comment: Hello, Mohammed. The tabs are working, but now I've noticed that the content from the tab is not activating on visiting the page and instead of that even the active tab right now is Monday, the content shows from Saturday (the tab that is default by Quciktabs UI). When I click on Monday tab, the showing content is for Monday, but that works after clicking on Monday tab. The idea is when a user enters the TV schedule page to see the right tab with the right content for the day.
Comment: do you have a link that I can look at?
Comment: I've updated the first thread
Comment: have updated my answer. Please check if that works.
Comment: I've added the code in the first thread. Please check. I'm not sure what do I change here: $('#quicktabs-tab-page-id-' + n).removeClass('quicktabs-hide');
Comment: you need to change this #quicktabs-tab-page-id- to #quicktabs-tabpage-quicktabs_tv_schedule- in your case
Answer: You can use javascript for this.
Each quicktab "A" tag has an ID something like quicktabs-tab-name-0 (replace name with the quicktab name you have given)
You can use some thing like the below code to get the current day of the week
var d = new Date();
var n = d.getDay();

this would return a number which would be something from 0 to 6 where 0 Represents Sunday and so on.
The active class is set to li tag with in which the a tag is placed.
So first we need to remove the active class from all the li with in quick tab this can be done with
$(".quicktabs-tabs li").removeClass('active');

Next we need to add the active class to the current day's tab for which you could do something like.
$('#quicktabs-tab-name-' + n).parent().addClass('active');
// n is the day number we got from the code above.

Next you need to enable the tab page for the corresponding tab for that you would do the following. The first one would add the hide class to all tab pages and the second code removes the hide class from the current div.
$('.quicktabs-tabpage').addClass('quicktabs-hide');
$('#quicktabs-tab-page-id-' + n).removeClass('quicktabs-hide');

That should do it.
Just make sure that the tabs are arranged form Sunday to Saturday. So that quicktab ids also get the same numbering. If you want a different order then you can offset the number accordingly by adding the offset value and then getting the reminder value of a division by 7.
So in effect the complete code would be
var d = new Date();
var n = d.getDay();
$(".quicktabs-tabs li").removeClass('active');
$('quicktabs-tab-name-' + n).parent().addClass('active');
$('.quicktabs-tabpage').addClass('quicktabs-hide');
$('#quicktabs-tab-page-id-' + n).removeClass('quicktabs-hide');

This would go inside the document ready function.
Comment: Hi, Mohammed. I'm sorry for the late answer. I've tried your code, but it still didn't work. I'll edit the main thread, so I can show you what did I tried.

Default tab by date or day


Should I call deliver method when sending mail using rails?

Question: In rails guide, I see the way to deliver email is calling like this:
UserMailer.welcome(@user).deliver

But in our codebase, I see code like this using sidekiq:
UserMailer.delay.welcome(@user)

And likely it works. I am wondering, should I call deliver to make the action happen or sidekiq does some magic here?
Comment: According to [this](https://github.com/mperham/sidekiq/wiki/Delayed-Extensions) documentation, I think it does.
Answer: As you can see in Sidekiq's sources (click here) it calls deliver for you. Thats why you don't need to call it when you delay email.


MySQL Column Constraint

Question: I need a table which will allow to insert values into a column with values greater than 10.
When I tried in net, they suggested to create table in following way.
CREATE TABLE test (
  UID int(11) NOT NULL auto_increment,
  ID int(11) default NULL,
  CHECK (ID > 10),
  PRIMARY KEY  (UID)
);
And when I try to insert an entry with values less than 10, still values are getting inserted.
I can use Before trigger on the table to restrict insertion of values less than 10.
But I wanted other approach which satisfies this condition.
I am using MySQL server 5.0.24
Please help me out of this.
Answer: According to MySQL doc:
"The CHECK clause is parsed but ignored by all storage engines."
Comment: Thanks for the answer. Is there any other approach to have check on the column other than trigger.
Comment: Not at a the moment. It's the only solution so far.

MySQL Column Constraint


How do I filter exposed taxonomy terms with other exposed taxonomy terms?

Question: OK, so I have 3 different Taxonomy Vocabularies filled like this: One for Carriers [AT&T, T-Mobile] One for Manufacturers [Samsung, iPhone, etc] And one for the Models [Galaxy S3, S4, etc]
All of these are set as an Exposed Filter for a custom view, But what I want is for the last Exposed Filter, "Models" to be Filtered by whatever Selection is made in "Manufacturers"
So if I Select iPhone, I only see Models for iPhones.
I've searched everywhere without the solution I need. And if it is what I needed, I wasn't able to set it up, or directions weren't clear enough.
I have Term References Linked from the Models to the Manufacturers, but idk how to Filter the Exposed Filter to only show Model choices for the selected manufacturer.
How do I filter exposed taxonomy terms with other exposed taxonomy terms?
Any help is appreciated!
I'm Working with Drupal 7.
Comment: As @heart.cooks.mind already suggested, one option would be to use Search API. The keyword you are looking for is however Faceted Search, this is what describes the functionality you described. Cheers!
Comment: I don't see how I can Filter Selectable Taxonomy Terms with it though.
I have 3 selectable [Exposed] content Filters coming from 3 different Taxonomy Vocabs. Each one has it's own Vocab, and I want the Second Vocab Term choice to Limit the amounts to the last one based on Term References.

So if I select iPhone Term for the Manufacturers Vocab, then I want the Model Vocab Content Filter to only List iPhone Models, even though that Vocab contains Terms for Many different Models.

Vocab 2: Manufacturers:
 Terms:
   iPhone
   Samsung

Vocab 3: Models
 Terms:
   iPhone 4
   Galaxy 3
Comment: I don't want people to be able to Select "Manufacturer: iPhone" & "Model: Galaxy S3" cause that wouldn't Make any sense.

My View Looks like this: http://s1345.photobucket.com/user/Lilith_Anthel/media/2016-06-02%201_zpsyzzgzfc1.png.html
Answer: Use the Search API.  Totally awesome.  It will provide you with the Facets you need.  Don't be intimidated.  The instructions below are great.
http://envisioninteractive.com/drupal/drupal-7-views-with-faceted-filters-without-apachesolr/
Comment: view looks like this http://i1345.photobucket.com/albums/p673/Lilith_Anthel/2016-06-02%201_zpsyzzgzfc1.png

When I search for things, it works, trouble is I want the last
"Content: Has taxonomy term (exposed)" to be Limited by the Second
"Content: Has taxonomy term (exposed)"

View render: http://i1345.photobucket.com/albums/p673/Lilith_Anthel/2016-06-02_zpsx35p1w5f.png

So when I select "iPhone" in the Second
"Content: Has taxonomy term"
The Last "Content: Has taxonomy term"
Only will show iPhone Models as a Result, instead of ALL of the Phone Models I have in the Taxonomy Terms
Comment: If you use the Search API, it provides the Facets as blocks for you based on the Fields you choose to Index.  If you want your facets in drop down select boxes as shown in your photo, you would want this additional module https://www.drupal.org/project/facetapi_select.  Each selection the user makes, will exclude options in the other boxes (that are no longer available).
Comment: "Each selection the user makes, will exclude options in the other boxes"
How? I'm not sure I get how to set this up properly
Answer: Simple Hierarchical Select did the trick, I just need to Combine the Manufacturers & Models list, and make the Models Childs to the Manufacturers, so when I select Samsung, it poofs another dropdown that lets me Select the Samsung children I set up in the Taxonomy Terms! I set Depth to -1
I tried to get it to work earlier to no avail, but it works now!
Found out it was Conflicting with another Module.
Answer: Another option would be this module : Views Selective Filters
A new kind of filter is available in the Views listing (named "your field (selective filter)". You may add three selective filters, each related to a vocabulary (even different ones). When you select a value in the first filter, the two others will only suggest possible values for contents with the first tag.


Stereographic Projection Notation

Question: I am trying to interpret some notation for functions on the extended plane involving the Riemann Sphere & complex plane but cannot find an explanation in the same form (Wikipedia & other websites mostly have different set of calculations). Note that in this case the south pole of the sphere is tangent to the plane.
$z = re^{i\theta} \neq 0$
So in the above, I realise that this states that $z$ on the complex plane is equal to the rest when not equal to 0.
But I am unsure about the rest:

$r$ is the radius of the Riemann Sphere (1 for unit sphere)?
$e$ is Euler's number or something else?
$^{i\theta}$ is the angle from the equator? In radians or degrees?

There is another function which shares the notation but introduces nothing novel:
$w = (1/r)e^{-i\theta}$
The following webpage has similar notation although I was reading from Mathematics: Form & Function by Saunders Mac Lane (chapter 4, section 11, 'Stereographic Projection and Infinity').
http://mathfaculty.fullerton.edu/mathews/c2003/ComplexFunReciprocalMod.html
An explanation of the above would be great; examples including numbers would also be useful, I am learning from a basic level.
Thanks in advance!
Answer: $z=re^{i\theta}$ is a way to represent a complex number $z$ in terms of its polar coordinates: $r$ is the magnitude of $z$ and $\theta$ is the angle (in radians) between the real axis and the line that passes through $z$ and $0+i0$.
And yes, $e$ is just Euler's number: the exponential function $e^z$ is extended in the complex domain by defining it over the imaginary numbers as
$e^{i\alpha}=cos(\alpha)+isin(\alpha)$
To understand why, I suggest watching this video (if you have a basic understanding of exponentiation or derivatives. If you don't, then the channel is still a gold mine to get started)
In a way, $z=re^{i\theta}$ holds true even when it's equal to $0$, because the magnitude becomes zero; the only problem is that $\theta$ becomes undefined at that point.
Now, the second equation just means that $w$ is equal to $z^{-1}$ (its magnitude is inverted and the angle is opposite, and because the multiplication of two complex numbers yields a number which has the angle equal to the sum of the angles and the magnitude equal to the product of the magnitudes, if you multiply the two together you get $1$).
Hope I helped clear things up, I wish you good luck in your learning process!

Stereographic Projection Notation


Is there a better way to achieve this using Perl?

Question: I am writing a Perl script which does this :

Reads the values of the environment variables a to z in a loop.
Depending on the value of the environment variables, generates a result file similar to
a - 1,2,3,4
b - a,b,c
c - $234.34,$123.12
keyword1 %a%
keyword2 %b%
keyword3 %c%

The point to note is that all the declarations have to come before the usages.
The problem is that for example I read a, and generate this result file
a - 1,2,3,4
keyword3 %c%

Now when I read b , I need the result file to look like this
a - 1,2,3,4
b - a,b,c
keyword1 %a%
keyword2 %b%

How should I do this using Perl?
One way I can think of is to  generate two different files - one with the declarations and other with the usages, and then concatenate the files at the end of execution of the script.
Is there a better way?
Comment: Better than what? It doesn't seem like you showed us the current way you're doing things.
Comment: @Lazer: This is not any more clear at all. What do you mean by "declarations"? Do you mean a list of variables which are defined and a list of variables which are not defined?
Comment: What would the purpose of this be -- how is it useful? What is the consumer of this script's output?
Comment: Can you add more info about what you're trying to do? It's not completely clear what actions you want to take. What if a variable is unset? What do you want to do with any given one based on the setting?
Comment: @Lazer: *What problem are you trying to solve*. You still haven't told us what you're *actually* trying to do. Why do you need them printed in this format? Once you read them, what do you want to do? What have you tried and why didn't it work? Do you not understand the syntax for doing this in perl? Or is it a logic issue?
Comment: @Ether: This formatted output is finally parsed by yet another script that does some further work.
Comment: @Daenyth: I shall be handling all the error cases (variable unset etc.) What I want to know is that how can I progressively generate the output file?
Comment: @rafl: Better than generating two different files and concatenating. I am not sure why that was not clear.
Comment: I have updated the question, hope I make myself clear now.
Comment: @Daenyth: The problem is only generating the output file. I think, it does not add to the question at all what the use is. Anyways, please see the updated question.
Answer: No need for separate files. Accumulate the declarations and usages in two different array variables, @declarations and @usages. After you've read all your environment variables and determined the contents of the two arrays, print them:
say for @declarations;
say for @usages;

You might even be able to omit the first array. Once you figure out what a declaration should be, print it out immediately. You only need to accumulate the usages until you know there will be no more declarations.
Comment: @Ether, evidently, Lazer's script is generating code to be executed later by some other interpreter. I don't see why there's so much resistance to the idea of having a Perl script whose purpose is to create a file.
Comment: @Lazer: I think this was the point of all the commenters above -- what is the purpose of the output -- why output to files at all?
Comment: Thanks @Rob, arrays are a good choice, and are definitely better than having to create two separate files and concatenating.
Comment: having a script create a file which is just going to be processed again by another script implies that the two scripts could be combined.
Answer: use strict;
use warnings;

my @keys = sort keys %ENV;
print "$_ - $ENV{$_}\n" foreach @keys;
my $kwcnt = 1;
print "keyword${ \( $kwcnt++ ) } \%$_\%\n" foreach @keys;

I sort the keys once, and run through them twice.


$f(x-y)$ considered as a function of $(x,y)\in \mathbb{R^{2n}}$ is measurable if $f$ is measurable

Question: I know there are similar questions up proving this, but I had a question specific to the following proof (specifically in bold):
Let $f$ be a Lebesgue measurable function on $\mathbb{R^n}$. Then the function $f(x)$ considered as a function of $(x,x)\in \mathbb{R^n}$ is Lebesgue measurable.
The linear transformation given by $T:(x,y)\rightarrow (x−y, y)$ is invertible, and so $f(x−y)$ is a Lebesgue measurable function of $(x,y)\in \mathbb{R^n}$. Thus, we see that $f(y)g(x − y)$ is measurable on $\mathbb{R^2n}$.
I know it has something to do with the fact that $T$ maps measurable sets to measurable sets, meaning that $F\circ T = f(x-y)$ is measurable if $F(x,y) = f(x)$, and I'm guessing it has something to do with proving that $T^{-1}$ is Lipschitz, but I just can't make the connection.
Answer: For every open $U$, $\{(x, y) : f(x - y) \in U\} = \{(x, y) : x - y \in f^{-1}[U]\}$. So it is enough to show that the function $(x, y) \mapsto x - y$ pull back Leb. measurable sets to Leb. measurable sets. But this follows from the fact that it is continuous and pulls back null sets to null sets. For the latter fact, you can use Fubini's theorem.
Comment: Thanks a lot Alfred, I'm still not entirely sure continuous functions always pull back measurable sets to measurable sets, though. I'm thinking of the cantor function as a counter-example. see here: http://math.stackexchange.com/questions/207040/pre-image-of-a-measurable-set-a-is-always-measurable?lq=1