text:
Q: What does "Speak if you must" mean? I'm want to ask about something I heard in the last part of the movie staring Russell Crowe (Robin Hood) and Oscar Isaac (king John).
When the king John is trying to convince people to join forces against the French attack and Robin is approaching there is this dialog:

Robin: I want to speak.
People screaming: Let him speak, let him speak.
King John: Speak if you must.

So what's the meaning of the "Must" in this sentence "Speak if you must"? Looks awkward say this instead if "Speak if you want", "Speak if you need"?

A: It simply means speak if you have to.

A: King John evidently does not want Robin Hood to speak. Figuring the crowd wants to hear what Robin has to say, and since Robin is eager to speak, the King figures he may as well let him speak.
The expression "if you must" indicates a bit of impatience on the part of the one who says it. This person thinks there are better things to do than what you want to do, but he'll let you do your thing--again, only if you must. Notice, however, that in the case of Robin, the "must-ness" is on Robin's part, not the King's. If the King were to say, "You must not speak," then Robin would not have spoken. The King's words, in that case, are an order. Must-ness, as answerer Jasper Loy, above, suggests, indicates something that has to be done, in the opinion of the one who wants to do it.
Now if the person who wants to do or to say something thinks it can wait, he might say,

"Well, it's not really that important. I can wait until a later time,"

in which case, whatever needed to be said or done wasn't that important.
The word must denotes something urgent, but what you consider urgent and what another person (such as the King) thinks is urgent are not necessarily the same. If the person in charge thinks it's not urgent, he may still give his subordinate permission to speak, but only because he has the authority to grant permission.
In conclusion, perhaps an example might help. Keep in mind, the person who says "If you must" is a little impatient, and the person to whom it is said thinks what he has to say or do is urgent.

A husband and wife are having a serious discussion. All of a sudden, their 18-year-old daughter bursts into the room and says, "Mom. Dad. I have some really good news," to which the mother says to the daughter, "Can't you see your father and I are having a serious discussion?" to which the daughter says, "But Mom, it just can't wait!" The mother, a little annoyed, and with a sigh, says "Well, if you must tell us your good news, and it just can't wait, go ahead and tell us." The daughter then says excitedly, "Mom. Dad. I've just been accepted at Harvard!"

A: Semantics:

Robin: I want to speak.

I have something important to say.

People screaming: Let him speak, let him speak.

Yes - yes - yes

King John: Speak if you must.

I'm still King, whatever you say. I won't be so stupid to say no when the people say yes. But I'm not gonna endorse you. I'll just won't prevent you from speaking.
So this means kind of I don't really care about your opinion but if I cannot stop you from sharing it with me anyway, go ahead and leave me in peace afterwards.
;)

A: Here "speak if you must" clearly shows that king is not approving the idea of robin talking.but since robin wants to talk and people wants to hear him speak , the king unwillingly tells him to do so;but he still doesn't agree.here "must " is used in an assertive manner.it is used as a signal of intent to make the other person understand that "I don't like it" or "it's not a good idea"
Eg : tony wants to go for a movie
But his father doesn't want him to.so if tony insists, his father would unwillingly say "go if you must"
this is usually used in situations when you are in a fix or  if you have no other option and the other person happens to be someone you respect or love.

A: King John is saying... Speak if you have to do that..if you have no other choice than telling me what you have to say and people want you to do it. The use of MUST is correct.


text:
Q: Logback Android - file per process I have a multiprocess architecture in my Android application. The main process contains UI stuff and I have two more processes with foreground services which are working 24/7.
Application
|-main (process 1)
|-service 1 (process 2)
|-service 2 (process 3)

Logback is working fine but everything is saved in one file. I want to have a separated file for each process. I was searching over the internet and StackOverflow and there are no results with words android, logback and process.
Is it possible to achieve this goal?
My logback.xml file is as follow:
<configuration>
    <property name="LOG_DIR" value="${DATA_DIR}/logs" />

    <appender name="logcat" class="ch.qos.logback.classic.android.LogcatAppender">
        <tagEncoder>
            <pattern>%logger{12}</pattern>
        </tagEncoder>
        <encoder >
            <pattern>[%-20thread] %msg</pattern>
        </encoder>
    </appender>

    <appender name="roll" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
            <level>DEBUG</level>
        </filter>
        <file>${LOG_DIR}/log.txt</file>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>${LOG_DIR}/log.%d{dd-MM-yyyy}.txt
            </fileNamePattern>
            <maxHistory>100</maxHistory>
        </rollingPolicy>
        <encoder class="my_app.logging.ExtendedPatternLayoutEncoder">
            <pattern>%d{dd.MM.yyyy HH:mm:ss.SSS} PID:%process_id [%thread] %-5level %logger{36} - %msg%n</pattern>
        </encoder>
    </appender>

    <root level="DEBUG">
        <appender-ref ref="logcat" />
        <appender-ref ref="roll" />
    </root>
</configuration>

To read the process_id I'm using the following encoders:
import ch.qos.logback.classic.PatternLayout
import ch.qos.logback.classic.encoder.PatternLayoutEncoder

class ExtendedPatternLayoutEncoder : PatternLayoutEncoder() {
    override fun start() {
        PatternLayout.defaultConverterMap["process_id"] = ProcessIdConverter::class.java.name
        super.start()
    }
}

class ProcessIdConverter : ClassicConverter() {
    companion object {
        private val PROCESS_ID: String = android.os.Process.myPid().toString()
    }

    override fun convert(event: ILoggingEvent): String {
        return PROCESS_ID
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Loading a textarea without new lines Here is my problem : in my database, I got a VACHAR2 of length 2000. Let's call it the "commentReception".
It is mapped to a String in my Struts bean.
The jspx (that handles both consult and update, within the form) looks that way :
<s:if test="%{consultAction}">
  <s:textarea name="dto.commentReception" readonly="true" cssClass="textAreaValue readonly" />
</s:if>
<s:else>
  <s:textarea name="dto.commentReception" readonly="false" cssClass="textAreaValue" />
</s:else>

When I submit the form, the bean is filled correctly, meaning without any \r\n at the end, and I get only one line, even in the database : no newlines.
But when I switch to consultAction, or let's say re-edit the form (not consultAction) another time, I get my string with an extra 2 newlines. That's really annoying and I don't know if it comes from Struts or from the  tag. (with me probably missing a tag attribute?)
Of course, if I submit the form again, the comment string will be stored in the database with the newlines. So it will add two more new lines every saving of my comment...
Do you know where my problem comes from? Thanks already.
Edit : the generated form
<textarea class="textAreaValue" id="saveControleReception_dto_commentReceiption" rows="" cols="" name="dto.commentReceiption">commentaire contrôle avant reception.

</textarea>

You can see there are some newlines, but they are not taken into account in my bean. But they are somehow when I reload it.

A: So, it seems that the struts tag  is adding by default two \r\n to the String upon loading the bean. That must be some kind of bug. So here is my solution :
<s:if test="%{consultAction}">
  <textarea readonly="true" class="textAreaValue readonly"><s:property value="dto.commentReceiption"/></textarea>
</s:if>
<s:else>
  <textarea class="textAreaValue" name="dto.commentReceiption"><s:property value="dto.commentReceiption"/></textarea>
</s:else>

I used the html tag instead of Strut's, and the property tag... If someone has a better answer (there must be), I'm still listening ;)

A: When you save or retreive your data add trim() in case you use mySQL. this will remove the remaining white spaces when you retrieve/seve it


text:
Q: Nutch numSlaves parameter in crawl script I am using Nutch 1.9 to crawl a set of 500 websites. I am running nutch in Amazon EMR cluster and indexing the data to Solr.
While starting an EMR cluster I have started with 5 slave nodes. I have specified the numSlaves parameter to 5 in crawl script. I would like to increase my slaves to 10 to fasten the process. I am able to increase the number of slave nodes in the AWS console to 10. Will the nutch utilize all the 10 slave nodes without restarting my crawl or modifying the crawl script.
Thanks

A: Nope. You'll need to modify the crawl script and restart it. No big deal though, just SSH to the master node and create a file .STOP in runtime/deploy/bin. This will stop the crawl loop when the current iteration is complete. You can then restart the script after setting the value to 10.
BTW you'd get quicker answers by asking on the Nutch mailing lists


text:
Q: Firebase error no debug.keystore in .android folder I tried to connect Firebase to my android app but the error says

Firebase: Could not find keystore in file ({0}) specified for debug
  build type. {2}

I see that there is no debug.keystore in my .android folder.

A: I've got the same issue, for fixing it, I've done the following step

*

*Go to your google firebase account

*Click on Project Settings

*Download the google-services.json file and save it in {your-project}/app/google-services.json

*The rebuild your project and it should work

A: Open your project structure File -> Project structure
Than goto Signing, if you use default key clear all fill like this, or select debug and set up correct path to your keystore file (fill Store File). In Linux, by default, it is ~/.android/debug.keystore.
Also, goto Build Types, and select debug and you see this, if you cleaned fills in previouse step your Signing Config must be empty, else select debug
Hope it's help you.


text:
Q: How export jar not executable with their lib I'm working on a project that will add mediator in the header of the backend request of api manager so I need to export jar(not runnable) that need libraries, could you please tell me how to resolve the exceptions of class not found
Thank you

A: When you are going to add external libraries, you have to add them in to $WSO2_Product_home/repository/components/lib folder.
Then those libraries will be added to dropins folder ($Product_home/repository/components/dropins) while server starts.
Note: If you add libraries while server running, you should restart the server.


text:
Q: Is it possible to rewrite selectors using reselect? I am using the redux toolkit in my project.
My selector looks like this:
export const selectFilterCinemas = (state) =>
    state.filmSlice.cinemas.filter(
        (cinema) =>
            cinema.name.toLowerCase().includes(state.filmSlice.search.toLowerCase()) ||
            cinema.address.toLowerCase().includes(state.filmSlice.search.toLowerCase())
    )

Is it possible to rewrite my selector using reselect and how?

A: Yes. You need to use the createSelector API from Reselect, extract the pieces of data that you need through "input selectors", and then derive the actual results in the output function:
const selectFilterCinemas = createSelector(
  (state) => state.filmSlice.cinemas,
  (state) => state.filmSlice.search,
  (cinemas, search) => {
    const lowerSearch = search.toLowerCase();
    return cinemas.filter(cinema => {
      return cinema.name.toLowerCase().includes(lowerSearch) ||
              cinema.address.toLowerCase().includes(lowerSearch);
    })
  }
)

That way the filtering will only re-run if either cinemas or search changes.
Also see the Redux docs page on Deriving Data With Selectors.


text:
Q: Replacing placeholder with another table's data (without knowing in advance the substitutions) I need to replace placeholders in a text, reading from a query matched to that specific message.
Table Template_Messages
| ID        | String                                                       | Query
| PICKUP_MSG|Your {vehicle_name} will be ready for pick-up on {pickup_date}|SELECT * FROM vehicles WHERE ID = ?

If I take the query I find in the 'Query' column, I will find the following table:
Table Vehicles
| ID  | vehicle_name | plate  | pickup_date | ... |
| P981| BMW X5       | AA014CC| 2022-09-20  | ... |
| Z323| Ford Focus   | HH000JJ| 2022-10-21  | ... |

Then with the following query:
SELECT * FROM vehicles WHERE ID = 'Z323'

By making the appropriate substitutions I should obtain this output:
Your Ford Focus will be ready for pick-up on 2022-10-21
How can I achieve this?
And since the 'query' column of the first table does not only refer to the 'vehicles' table, can it work dynamically on any placeholder/query?


text:
Q: Include NULLs in MAX() OVER PARTITION I have an Oracle query that I'd like to return a MAX() over a PARTITION while incorporating NULLs.
For instance, if the raw data is:

NAME   |  DATE
-----------------------
ADAM   | 01/21/14 00:00
ADAM   |
ADAM   | 01/22/14 00:01
ADAM   | 01/23/14 00:02

Using the following query it returns the following:
MAX(date) OVER (PARTITION BY name ORDER BY date)

NAME   |  DATE
-----------------------
ADAM   | 01/21/14 00:00
ADAM   | 01/22/14 00:01
ADAM   | 01/23/14 00:02
ADAM   | 01/23/14 00:02

Is it possible to have it act as if the NULLs were a MAX() value so it would return the following?

NAME   |  DATE
-----------------------
ADAM   | 01/21/14 00:00
ADAM   |
ADAM   |
ADAM   |

A: Yes, you can use the analytic function:
FIRST_VALUE(date_col) OVER (PARTITION BY name ORDER BY date_col DESC NULLS FIRST)

Test at SQL-Fiddle


text:
Q: Knit, using group_by() on a frame with a timestamp-column I have a data frame with case IDs and timestamps.
str(Frame$Timestamp)
POSIXct[1:3320], format: "2018-01-02 09:10:14" "2018-01-02 09:10:14" "2018-01-02 09:35:30" "2018-01-02 10:30:43" "2018-01-02 17:10:09" ...

In the console I can execute group_by(Frame, CaseID) without problems.
When I knit a .Rmd-notebook with the same command I receive the following error:
Error in grouped_df_impl(data, unname(vars), drop) :
Column 'Timestamp'is of unsupported POSIXlt/POSIXt calls:
<Anonymous> ... group_by.data.frame -> grouped_df -> grouped_df_impl Execution halted.

What can I do  to make it possible to use group_by() in that case?
Ben

A: Below approach works.
Output of group_by()
group_by(Frame, Timestamp)
## # A tibble: 1,000 x 2
## # Groups:   Timestamp [999]
##    Timestamp           CaseID
##    <dttm>               <int>
##  1 2018-10-01 19:09:56  18592
##  2 2018-10-16 14:20:57  49269
##  3 2018-09-30 02:37:33  66986
##  4 2018-10-11 20:16:19  22090
##  5 2018-10-20 13:16:46  11802
##  6 2018-10-05 17:05:00  70791
##  7 2018-10-14 05:54:05  32192
##  8 2018-10-13 22:44:01  92938
##  9 2018-09-28 21:40:36  86432
## 10 2018-10-14 03:53:11  90539
## # ... with 990 more rows

Contents of Test.Rmd
---
title: "Test"
author: "Roman Abashin"
date: "13 Oct 2018"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

Load library
```{r}
library(dplyr)
```

Create data
```{r}
set.seed(1701)
Frame <- data.frame(
    Timestamp = (as.POSIXct("2018-10-10 10:10:10") +
        sample(-1000000:1000000,1000, replace = TRUE)),
    CaseID = sample(10000:99999, 1000, replace = FALSE))
str(df)
```

Group by
```{r}
group_by(Frame, Timestamp)
```


text:
Q: store data in a csv file using the curl command following this image:

through a bash script invoked from the terminal I should store the values of "latitude, longitude, timestamp and speed" in a csv file. However, these values update every 1 second, which is why I wrote the following scrip bash to stop when necessary:
#!/bin/bash

while true;

do curl -s -H "Accept: application/json" -H "Content-Type: application/json" http://172.17.0.2:8080/api/clients/giammi-VirtualBox/6/0 >> myresponse.csv

sleep 1s

done

the problem is that in this way it returns the csv file as follows:

the parameters of my interest are: 0,1,5,6 which correspond to latitude, longitude, timestamp and speed, so what I would like is a representation like:
0,1,5,6
xxx,xxx,xxx,xxx
yyy,yyy,yyy,yyy


text:
Q: Using AudioUnits to play and eq songs from music library I'm building an app that involves playing songs from the user's music library while applying an equalization (EQ) effect.  I've only used AudioUnits to generate sound before, so I'm having a bit of trouble.
My current plan is to use AVAssetReader to get the samples, and though I'm a bit fuzzy on that, my question here is with regards to the correct AudioUnit design pattern to use from Apple's documentation:  https://developer.apple.com/library/ios/documentation/MusicAudio/Conceptual/AudioUnitHostingGuide_iOS/ConstructingAudioUnitApps/ConstructingAudioUnitApps.html#//apple_ref/doc/uid/TP40009492-CH16-SW1.
My guess is that a render callback is needed to perform my EQ effect (I was thinking kAudioUnitSubType_ParametricEQ), so that leaves either the "I/O with a Render Callback Function" pattern or the "Output-Only with a Render Callback Function."  If I'm reading data from the music library (potentially via AVAssetReader), which of these two patterns would be the best fit?

A: I think you would need to use an Output-Only with a Render Callback Function. The callback function should be responsible for reading/decoding the audio data, and applying the EQ effect.
By the way, I don't know if this might be useful in any way, but here it says that there's an already existing EQ audio unit that you could use.


text:
Q: Can a newbie be automatically question banned if an upvoted answer is deleted? Let's say I'm a newbie on Site X. I begin by writing two answers to that get two upvotes and three upvotes, respectively (total of five, for 50 reputation points).
Then I write some bad questions, enough to get me banned if I had zero answer upvotes, but below a threshold raised by the answer upvotes. (My understanding is that some fraction of answer upvotes mitigate against a question ban.)
A mod then deletes one or both of my upvoted answers so I no longer have the "threshold" protection. Does the question ban now kick in automatically, or do I have to ask another "bad" question before it does?

A: Deleted posts affect the post ban just the same as undeleted posts do.  Your answer being deleted doesn't make it stop counting towards your question ban, although all feedback on answers is, in general, weighted less than feedback on questions with respect to the question ban (and vice versa for answer bans).
As for whether any given action can put you on the other side of the threshold and stop you from asking another question, it absolutely can.  At the time you go to ask a question an algorithm is run that looks at all of the feedback on your questions (and to a lesser extent, answers and other forms of interaction with the site) and determines if your total contributions are above or below a set threshold.  If you're below it, you can't submit the question, if you're above it you can.  You don't need to submit a new question for the calculation to be run; it's run every time you attempt to ask a new question.

A: Details of the algorithm that determines bans are known only to SE staff but this answer to What can I do when getting "We are no longer accepting questions/answers from this account"? says:

deleted answers always count towards an automatic ban on new accounts.

Assuming that counting towards question bans is not totally independent of counting towards answer bans, my expectation is that a moderator deletion of an upvoted answer on someone very narrowly avoiding a question ban would put them into it at its next calculation.
but ... as commented by @rene:

Keep in mind that you're not going from everything is fine to Q-banned
  at an instant. If you're in the danger zone you'll get the warning
  banner. I have not seen any users that were banned without [being]
  shown that warning. Plenty of users happily ignore it though or don't
  follow up its guidance. Strangely enough once banned they have no
  trouble finding Meta to complain.


text:
Q: I can't seem to import tensorflow to python VSCODE Traceback (most recent call last):
File "d:\kuliah\aa\aaa\aaaa\bpnn.py", line 1, in <module>
    import tensorflow as tf

File "C:\Users\xxx\AppData\Roaming\Python\Python36\sitepackages\tensorflow\__init__.py", line 24, in <module> from tensorflow.python import pywrap_tensorflow  # pylint: disable=unused-import

File "C:\Users\xxx\AppData\Roaming\Python\Python36\site-packages\tensorflow\python\__init__.py", line 59, in <module> from tensorflow.core.framework.graph_pb2 import *

File "C:\Users\xxx\AppData\Roaming\Python\Python36\site-packages\tensorflow\core\framework\graph_pb2.py", line 6, in <module>
    from google.protobuf import descriptor as _descriptor

File "C:\Program Files\Python36\lib\site-packages\google\protobuf\descriptor.py", line 47, in <module>
    from google.protobuf.pyext import _message

ImportError: DLL load failed: The specified procedure could not be found.

This happened when I'm importing my tensorflow on a .py code, what am i missing?

A: This problem occurs beacuse VScode and Coderunner extension can not activate the conda environment you are using. To fix this.

*

*Start anaconda command prompt then type in activate <your environment name>

*Type in code to start VSCode. Your import should be working now.

Thanks!


text:
Q: Unauthorized user can access related model in loopback I've added a model MyModel and extended Client model from User model. I've set up relation between MyModel and Client. A Client can have many MyModel while each MyModel belongs a client.
In Client.json
...
"relations": {
    "myModels": {
      "type": "hasMany",
      "model": "MyModel",
      "foreignKey": "createdBy"
    }
  }
...

In MyModel.json
...
"relations": {
    "client": {
      "type": "belongsTo",
      "model": "Client",
      "foreignKey": "createdBy"
    }
  },
...

After setting the relation, I get an endpoints like /clients/:id/myModels and others. The MyModel related to the client gets loaded even if the user is not authenticated.
Now I've setup ACL as follow,
In MyModel.json,
...
"acls": [
    {
      "accessType": "*",
      "principalType": "ROLE",
      "principalId": "$unauthenticated",
      "permission": "DENY"
    }
  ],
...

While trying to get list of MyModel related to the client, no authentication check is applied. i.e. The list of MyModel gets retrieved even if the user is not authenticated.
I thought I need to add ACL to restrict unauthenticated user from accessing the related models. So I tried adding following ACL in Client.json
    ...
    "acls": [
        {
          "accessType": "*",
          "principalType": "ROLE",
          "principalId": "$unauthenticated",
          "permission": "DENY",
          "property":"__get__myModels"
        }
      ]
    ...

but it doesn't change anything.
But if an authenticated user tries the route /client/:id/mymodels/count, Unauthorized User error is displayed.
What needs to be done to solve this issue?

A: Please use this configuration.
 {
    property: '*', //define your property.
    accessType: '*',
    principalType: 'ROLE',
    principalId: '$authenticated',
    permission: 'ALLOW'
  },

A: If you are using dynamic ways with Role and RoleMapping, you can try like this.
Role :
 {
    "name" : "admin",
    "description" : "admin role",
    "created" : "2018-02-23T15:48:40.514+0000",
    "modified" : ISODate("2018-02-23T15:48:40.514+0000")
   }

RoleMapping :
{
    "principalId" : ObjectId("5b06825775abbd45b3f02719"),
    "roleId" : ObjectId("5a903836876b6f0bbaa64c40"),
    "principalType" : "USER",
    "created_by" : "user",
    "created_at" : ISODate("2018-05-24T09:13:59.352+0000")
}

and ACL :
{
    "model" : "YourModel",
    "property": 'find',
    "accessType": '*',
    "principalType": 'ROLE',
    "principalId": 'admin', // depends on role name
    "permission": 'ALLOW'
}

and for other property as well like findOne, deleteById etc.
For everyone unauthenticated :
You can also try like this
{
    "model" : "YourModel",
    "property" : "find",
    "accessType" : "*",
    "permission" : "DENY",
    "principalType" : "ROLE",
    "principalId" : "$everyone"
}

For a particular user
{
    "model" : "YourModel",
    "property" : "find",
    "accessType" : "*",
    "permission" : "ALLOW",
    "principalType" : "ROLE",
    "principalId" : "5a817425e09bdb38f9217c20", // user doc id
}


text:
Q: break a FOR loop with keyboard in C I have  a program that runs through a few steps before it starts a for (;;) loop.
I want to be able to break; this for loop using a keystroke (such a 'e' for exit, for example)
I've tried scanf_s but I don't think I am using them correctly. the loop just doesn't initiate if I try to write scanf_s in.
I'm not very familiar with C programming so I'm struggling a little bit.
Can someone shed some light on this?
extra info:
Operating system is Win 8.1.
Program is a TCP server program. it creates a socket and begins listening. Then it starts accepting client connections in a for loop. then begins another for loop to receive messages from the client.
Edit: using this I have managed to stop the second for loop with s. added the changes to the simplified code (and just  bellow).
added:
if (_kbhit()) {
    key = _getch();
    if (key == 's');
    break;
}

here is some simplified code:
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    // prelim info goes here
    // like SOCKET
    // and struct sockaddr_in

    // Initialize Winsock
    WSAStartup();

    // Create socket
    mysocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

    // server parameters go here
    // like sin_addr and sin_port

    bind(mysocket);

    // start listening
    listen(mysocket, SOMAXCONN);

    // begin the damn for loops

    for (;;)
        {

        myclient = accept();

         //second for loop
        for (;;)
        {
            receivedata = recv(myclient);

            printf(<data>)

            if (_kbhit()) {
                key = _getch();
                if (key == 's');
                    break;
            }

        }
    }

    // close socket
    closesocket(mysocket);

   // call WSACleanup
   WSACleanup();

   return 0;
}

thanks to everyone who supplied links and the helpful answers. The issue with the outer loop turned out to be a bit more involved than just breaking it. However, if any future visitors are wondering how to break a loop with a keyboard press, this has been achieved. See the correct answer or my simplified code.

A: You can try using kbhit and getchar to check keystroke and handle the action accordingly.
Check this post: Return pressed key without enter for confirmation
This code breaks the while loop when e is pressed:
[Code updated with one more extra while loop]
#include <stdio.h>
#include <conio.h>

int main(){
    int ch = '1';
    while(ch != 'e'){                        //outer while for accepting connection
        printf("waiting for connection\n");  //do something

        while(ch != 'e'){                    //inner while for checking key press
            if(kbhit())                      //if key is pressed
                ch = getch();                //get the char and set ch to 'e'
        }
    }

    return 0;
}

Old Code using break:
#include <stdio.h>
#include <conio.h>
#include <windows.h>
int main(){
    int ch;
    while(1){
        printf("*");
        if(kbhit()){               //if key is pressed
            ch = getch();          //get the char
            if(ch == 'e')          //if pressed key is 'e'
                break;             //break while loop
        }
    }

    return 0;
}

A:
just enter these lines in for loop. this will exit when user will enter 'e' char.

    if(kbhit()){
  ch = getch();
  if(ch == 'e')
    break;
    }`

A: Assuming Microsoft's compiler, the simplest method is to use its conio library.  I suggest wrapping the details into a single function, to allow reuse.  For example, you may need to test the keyboard before entry to the second loop.
#include <conio.h>

int nonBlockingGetch( void )
{
    int ch = -1 ;
    if( _kbhit() )
    {
        ch = _getch() ;
    }

    return ch ;
}

int main( void )
{
    int ch = -1 ;

    //  Outer loop
    while( ch != 'e' )
    {

        // inner loop
        while( ch != 'e' )
        {
            ch = nonBlockingGetch() ;
        }
    }

    return 0;
}

As I suggested there may be circumstances where you would not want the inner loop to run if an exit were requested, in which case:
//  Outer loop
while( ch != 'e' )
{
    ch = nonBlockingGetch() ;

    // inner loop
    while( ch != 'e' )
    {
        ch = nonBlockingGetch() ;
    }
}

A: You can try with user defined Interrupts


text:
Q: Counting characters in char array? Currently i'm trying to sort a paragraph based on first char of each word. I'm initializing two alphabetic (Upper and Lower) char arrays to compare to the first char of the word to the array index.
My Plan for the problem;

*

*Initialize two Arrays with the Alphabet to know which alphabet goes before which.

*Have a function that actually compares first char to the two Arrays.

*return the words sorted :)

My problem is i'm trying to see if the two arrays have 26 characters to make sure every alphabet is counted for but it prints 1 and i have no idea why.
Code:
#include <stdio.h>

int main(int argc, const char * argv[]) {

    char _alphabetUpperCase[100] = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R,","S","T","U","V","W","X","Y","Z"};
    char _alpabetLowerCase[100] = {"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"};

    int i = 0;
    int n = 0;
    while(_alpabetLowerCase[i] != NULL)
    {
        n = n+1;
        i++;
    }

    printf("%d\n",n);
    return 0;
}

A: This "A" is not same as 'A'. You should assign 'A' to a character instead.
Replace all "" strings with corresponding '' characters. e.g.
char _alpabetLowerCase[100] = {'a','b','c' ... };

A: You want characters or strings? "a" is a string while 'a' is a character. From your definition of array it seems you want characters. So change your code for that as
char _alpabetLowerCase[100] = {"a", ...

Instead use
char _alpabetLowerCase[100] = {'a', 'b', ....

A: Try this:
#include <stdio.h>

int main(int argc, const char * argv[]) {
    char _alphabetUpperCase[27] = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R,','S','T','U','V','W','X','Y','Z', '\0'};
    char _alphabetLowerCase[27] = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z', '\0'};

    int i = 0;
    int n = 0;
    while(_alphabetLowerCase[i] != '\0')
    {
        n = n+1;
        i++;
    }

    printf("%d\n",n);
    return 0;
}

Explanation: 'a' is char, but "a" is string. Also I added 27-th character to become sure that this loop will stop after 'z' (so I changed the array size to 27 (100 was correct too, but it is wrong to write arbitrary numbers when you can put correct value)).


text:
Q: python Output specific characters only if they are after a number a = 'adk7.86311kgskg'
r = "".join(re.sub('[^0-9*kg.]', "", a.strip().replace(' ', '')))

print(r)
#'k7.86311kgkg'

The results I want are as follows.
'7.86311kg'

Thank you

A: import re
print(re.findall(r'[\d.]+kg', 'adk7.86311kgskg')[0])

This outputs:
7.86311kg


text:
Q: Regular expression for public keys I want to match keys from file which looks like this:
KEY_ID: 1
STATUS: VALID
-----BEGIN PUBLIC KEY-----
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEaq6djyzkpHdX7kt8DsSt6IuSoXjp
WVlLfnZPoLaGKc/2BSfYQuFIO2hfgueQINJN3ZdujYXfUJ7Who+XkcJqHQ==
-----END PUBLIC KEY-----

I want to subtract KEY ID and the key itself from it via preg_match_all. I tried this one:
preg_match_all('/-----BEGIN PUBLIC KEY-----(.*)-----END PUBLIC KEY-----/', $ECDS_KEYS, $matches);

But I got empty array from this one. Can you help me out? Thanks

A: by default, "." doesn't match line breaks. You have to add an "s" at the end of your regex to catch it:
preg_match_all('/-----BEGIN PUBLIC KEY-----(.*)-----END PUBLIC KEY-----/s', $ECDS_KEYS, $matches);

result: https://regex101.com/r/rN7oZ1/1
EDIT:
If you wish to seperate each key, you don't need "preg_match_all", you don't need linebreaks before and after your first catch, and you have to explode it after the regex:
// catch all keys
preg_match('/-----BEGIN PUBLIC KEY-----\n(.*)\n-----END PUBLIC KEY-----/s', $ECDS_KEYS, $groupedKeys);
// once you get a list of key, seperate them with an explode on linebreaks
$lonelyKeys = explode("\n", $groupedKeys[1]);

use "\n" or "\r\n", depending what you receive.

A: If you take in account that you need to load a file and to compile and search with a regex pattern, You should consider this another way that is faster and use less memory:
$fh = fopen($filename, 'r');

$start = "-----BEGIN PUBLIC KEY-----\n";
$end = "\n-----END PUBLIC KEY-----";
$maxSizeBetweenKeys = 262144;
$results = [];

while ( stream_get_line($fh, $maxSizeBetweenKeys, $start) !== false &&
        ($key = stream_get_line($fh, 4096, $end)) !== false )
    $results[] = $key;

fclose($fh);

If you compare it with:
$fileContent = file_get_contents($filename);
if (preg_match_all('~^-----BEGIN PUBLIC KEY-----\n\K.*+(?>\n.*)*?(?=\n-----END PUBLIC KEY-----)~m', $fileContent, $matches))
    $results = $matches[0];

that is a little shorter but slower.

A: Pattern for test public and private keys
(-----BEGIN PUBLIC KEY-----(\n|\r|\r\n)([0-9a-zA-Z\+\/=]{64}(\n|\r|\r\n))*([0-9a-zA-Z\+\/=]{1,63}(\n|\r|\r\n))?-----END PUBLIC KEY-----)|(-----BEGIN PRIVATE KEY-----(\n|\r|\r\n)([0-9a-zA-Z\+\/=]{64}(\n|\r|\r\n))*([0-9a-zA-Z\+\/=]{1,63}(\n|\r|\r\n))?-----END PRIVATE KEY-----)

Tests
Regex101.com - PEM RSA KEY PATTERN - ECMASCRIPT - PCRE


text:
Q: Configure bibitem command in tex4ebook/make4ht I am looking for a place to find how to configure the \bibitem tag in  tex4ebook/make4ht. All bibitems are inlined without

I tried: {\Configure{bibitem}{\NoFonts \HCode{
}}{}\EndNoFonts}}
but the result is:
1
X1García,  P.  A.,  Compen....
I would like something like

 1X1García,  P.  A.,  Compen....
or inside some p or div or...
=================== act 2 =======================
i narrow the problem :
2 version :
    1 with

\documentclass{book}
\usepackage[french]{babel}
\usepackage{pxfonts}
\begin{document}
oh \cite{1} aahhh
\begin{thebibliography}{99}
\bibitem{1}Sample Bib text
\bibitem{2}Sample Bib text
\end{thebibliography}
\end{document}

1 without

\documentclass{book}
\usepackage[french]{babel}
\usepackage{pxfonts}
\usepackage{titlesec}
\titleformat{\chapter}
[block]
{\normalfont\huge\bfseries \scshape \flushleft}
{\thechapter.}{0pt}{\hspace{5pt}\huge \bfseries \scshape}
\titlespacing*{\chapter}{0pt}{0pt}{20pt}
\begin{document}
 oh \cite{1} aahhh
 \begin{thebibliography}{99}
 \bibitem{1}Sample Bib text
 \bibitem{2}Sample Bib text
 \end{thebibliography}
 \end{document}

the problem is that i need  the chapter thing in my document to format how chapter appears in the pdf and in the epub

A: The issue is caused by your titlesec configuration for \chapter. In particular, the line:
{\normalfont\huge\bfseries \scshape \flushleft}

The \flushleft command starts a list environment that overwrites tex4ht configuration for the bibliography, which is also a list environment. For use as a text switch, \raggedright is the correct command to use. So your TeX file should look like this:
\documentclass{book}
\usepackage[french]{babel}
\usepackage{pxfonts}
\usepackage{titlesec}

\titleformat{\chapter}
[block]
{\normalfont\huge\bfseries \scshape\flushleft}
{\thechapter.}{0pt}{\hspace{5pt}\huge \bfseries \scshape}
\titlespacing*{\chapter}{0pt}{0pt}{20pt}
\begin{document}
\chapter{hello}

world

 oh \cite{1}

 \begin{thebibliography}{99}
   % \expandafter\show\csname a:bibitem\endcsname
 \bibitem{1}Sample Bib text
 \bibitem{2}Sample Bib text
 \end{thebibliography}

 \end{document}

This is the result:

Bibliographie

  [1]   Sample Bib text

  [2]   Sample Bib text


text:
Q: ASP.NET MVC Design Pattern Best Practice with Services I have an ASP.NET MVC 3 application.
I have a Model, ViewModel, View, Controller.
I use Ninject as IoC.
My Controller uses a ViewModel to pass data to the View.
I've started to use Services (concrete and interface types) to take information from the ViewModel and query it against the database to manipulate it.
Can I use the same Service to setup the ViewModel? Or is this going against the grain of the design pattern?
I.e. Can I abstract setting up the ViewModel in the Service layer?
Scenario
The scenario is; my Model has lots of references to other Models, so when I setup the ViewModel in the controller it's to verbose, and I feel the Controller is doing too much. So I want to be able to just do something like:
var vm = _serviceProvider.SetupViewModel(Guid model1Id, Guid model2Id, /*etc..*/)
And the SetupViewModel function in the ServiceProvider would look like this:
public MyModelViewModel SetupViewModel(Guid model1Id, Guid model2Id, /*etc...*/)
{
    var vm = new MyModelViewModel();
    var model1 = _repository.Model1s.FirstOrDefault(x => x.Id.Equals(model1Id));
    var model2 = _repository.Model2s.FirstOrDefault(x => x.Id.Equals(model2Id));
// etc....

    vm.Model1 = model1;
    vm.Model2 = model2;

    return vm;
}

By doing this I could also add some null conditions as well, not worrying about making my Controller really really really big!!
I use 1 ViewModel for the Create/Edit actions. I don't reuse the ViewModel elsewhere.

A: I would let the service layer return a Domain Model and map it to a ViewModel in the controller.
This way you can use a service method with multiple ViewModels, for a desktop and mobile view for example.
You can let AutoMapper do the hard work for you or do it manually, by creating a constructor in the ViewModel which takes the Domain Model.
The domain model:
public class Customer
{
    public int Id { get; set; }

    public string FirstName { get; set; }

    public string LastName { get; set; }

    public string Telephone { get; set; }

    public string Email { get; set; }

    public virtual ICollection<Order> Orders { get; set; }
}

The ViewModel:
public class CustomerWithOrdersModel
{
    public CustomerWithOrdersModel(Customer customer)
    {
        Id = customer.Id;
        FullName = string.Format("{0}, {1}", customer.LastName, customer.FirstName);
        Orders = customer.Orders.ToList();
    }

    public int Id { get; set; }

    public string FullName { get; set; }

    public IEnumerable<Order> Orders { get; set; }
}

EDIT: AutoMapper example:
The AutoMapper profile containing the mapping from a Customer to a CustomerWithOrdersModel:
public class ViewModelProfile : Profile
{
    public override string ProfileName
    {
        get { return "ViewModel"; }
    }

    protected override void Configure()
    {
        CreateMap<Customer, CustomerWithOrdersModel>()
            .ForMember(dest => dest.FullName, opt => opt.MapFrom(src => string.Format("{0}, {1}", src.LastName, src.FirstName)))
            .ForMember(dest => dest.Orders, opt => opt.MapFrom(src => src.Orders.ToList()));
    }
}

Id is mapped by convention.
Extension methods for the ViewModelProfile:
public static class ViewModelProfileExtensions
{
    public static CustomerWithOrdersModel ToModel(this Customer customer)
    {
        return Mapper.Map<CustomerWithOrdersModel>(customer);
    }

    public static Customer ToEntity(this CustomerWithOrdersModel customerWithOrdersModel)
    {
        return Mapper.Map<Customer>(customerWithOrdersModel);
    }
}

The controller action:
public ActionResult Details(int customerId)
{
    Customer customer = _customerService.GetById(customerId);
    CustomerWithOrdersModel customerWithOrders = customer.ToModel();
    return View(customerWithOrders);
}

If you create a mapping from CustomerWithOrdersModel to Customer, you can use customerWithOrdersModel.ToEntity() to map it back to the Domain Model.
Thats it! You can remove the constructor with the Customer domain model from the ViewModel.

A: If you have the view models as their own project and handle the mapping and returning of view models in your service layer, I see nothing wrong with that.  For separation of concerns you could always have another component that handles the mapping.


text:
Q: Passing a config file into a custom library codeigniter So I was reading in the Codeigniter user guide and they say that:

You can also pass parameters stored in a config file. Simply create a config file named identically to the class file name and store it in your application/config/ folder. Note that if you dynamically pass parameters as described above, the config file option will not be available.

I have a config file set up with the identical name as my library and I am wondering how I can access the contents of that file. Do I need to load the config before loading the lib? Do all of the variables need to be elements of an array?
examples:
-- Config file --
<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
$var1 = "Variable 1";
$var2['name'] = "foo";
$var2['title']= "bar";
$var2['content'] = "Lorem ipsm dolar sit imut";

-- Library file --
class Library
{
    var $data;
    function __construct($data)
    {
            $this->data = $data;
    }
}

-- Then something along the lines of --
function __construct() {
    parent::__construct();
    $this->load->library("library");
}
function index()
{
    var_dump($this->library->data);
}

(Yes I figure the name Library is reserved but this is an example)
Shouldn't the var_dump simply dump the contents of the config file? What am I doing wrong?

A: Few things to make this work :
Your classname FILE should start with a capital letter, Your config array must be defined as $config = array() (and not $var or any other name), Your config file must be lowercase.
The config file is passed through the constructor, so class($config=array()), you can then access and store the config variables on an instance variable.
hope it helps:
class Foo // Foo.php
{
    function __construct($config=array())
    {
        $this->config = $config;
    }

} //end of class

config file:
$config['url'] = 'stuff'; // config file : foo.php

good luck :)

A: To access the variables of config file in your custom library, you can initialize a new CI instance and access the content of config like below:
$this->ci = & get_instance();

$configs = $this->ci->config;

Now do var_dump($configs) to see content of config file.


text:
Q: I am getting this error "use of undeclared identifier 'recipe' Please refer to below code.
#import "RecipeDetail.h"
#import "Recipe.h"

@implementation RecipeDetail

@synthesize recipeLabel;
@synthesize recipeName;

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.title = recipe.name;
    self.prepTimeLabel.text = recipe.prepTime;
    self.recipePhoto.image = [UIImage imageNamed:recipe.imageFile];

    NSMutableString *ingredientText = [NSMutableString string];
    for (NSString* ingredient in recipe.ingredients) {
        [ingredientText appendFormat:@"%@\n", ingredient];
    }
    self.ingredientTextView.text = ingredientText;

}

A: you alloc you class object in viewDidLoad method like this.
Recipe *recipe=[[Recipe alloc]init];

then after you can use recipe object like that.
self.title = recipe.name;

A: You are getting the Correct error.
The the variable recipe is undeclared and you are trying to assign values from a non-existing variable.
So, either you should declare it before using it in your viewDidLoad method like:
Recipe *recipe = [Recipe alloc] init];

and then use it.
Or if you want to pass an existing recipe variable from outside this class, as it appears that you are trying to do that, then where ever you are declaring and initializing an instance of this class RecipeDetial make a Recipe property in RecipeDetail.h like:
@property (strong, nonatomic) Recipe *recipe;

and assign that variable to this property before presenting this UIViewController and use it as you are using it already.
Hope this helps...


text:
Q: My code will not read and display data from a file using ifstream and ofstream While my data is put into the file named based on the user's input of "myfile", when I go to read and display it in the else statement, the name shows up as "", the balance is 0, and the file data is deleted.
We just learned fstream and its commands in my C++ class yesterday.  Still new to using it.  The teacher said that using getline(inputfile, name) and inputfile >> balance should read the data.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{

string myfile;
int balance = 0;
string name;

cout << "Enter your first name." << endl;
getline (cin, myfile);

ifstream inputfile(myfile);
ofstream outputfile(myfile);

if ( ! inputfile.good() )
{
        cout << "Enter your FIRST and LAST name." << endl;
        getline(cin, name);
        outputfile << name << endl;
        cout << "Hello " << name << endl;

        cout << "Enter your initial balance." << endl;
        cin >> balance;
        outputfile << balance << endl;
}
else
{
        getline(inputfile, name);
        cout << "Welcome Back" << name << endl;
        cout << "Here is a log of all your BALANCE activity." << endl;

       inputfile >> balance;
       cout << "Your balance is " << balance << endl;
}

outputfile.close();
inputfile.close();

return 0;
}

it should read the data from the file and display the full name as well as the balance integer value.

A: The computer is doing exactly what you told it to do.
getline (cin, myfile);

Get some text from the user and store it in myFile.
ifstream inputfile(myfile);

Open the file named by myFile for reading (if it exists).
ofstream outputfile(myfile);

Open the same file you just opened, but this time for writing. If the file exists, destroy its contents. If the file does not exist, create it.
Then you proceed to the if statement. If the file had existed, you proceed to the else clause. There you discover that the contents of the file have been destroyed. Not a surprise, since that is the default behavior when ofstream opens an existing file.
What you probably want to do is move the declaration of outputfile into the if statement so that it is only hit when the file does not exist.
if ( ! inputfile.good() )
{
        ofstream outputfile(myfile);

        cout << "Enter your FIRST and LAST name." << endl;
        getline(cin, name);
        outputfile << name << endl;
        cout << "Hello " << name << endl;

        cout << "Enter your initial balance." << endl;
        cin >> balance;
        outputfile << balance << endl;
        // No need to explicitly close the file, as the destructor will handle that.
}
else
{
    // etc.


text:
Q: Is product (not the cartesian product) of two open balls in $\mathbb R$ an open ball? Suppose that I have an open set $S\subset\mathbb R\setminus\{0\}$ and we define $T=\{xy:(x,y)\in S^2\}$
The question is: is $T$ open in $\mathbb R$?
First I assert that T is open in $\mathbb R$.
To prove my assertion, I proceed by taking an arbitrary point $xy\in T$. Now, I want to find a radius  $\delta\gt 0$ such that $B(xy, \delta)\subset T$.
Since $S$ is open in $\mathbb R$, it follows that there exists an $r\gt 0$ such that $B(x,r)\subset S\land B(y,r)\subset S$.
I define the product $P:=B(x,r)B(y,r):=\{pq: (p,q)\in B(x,r)\times B(y,r)\}$ and clearly $P\subset T$. So my question here is: is $P$ an open ball (that is, an interval) in $\mathbb R$? If yes, then I am stuck at finding its centre and radius. If not, then if my assertion is true, there should exist some $r'\in (0,r)$ such that $B(xy, r')\subset P$ but I am having difficulty showing this also. (#)
I tried to take inspiration from an example: $S=(1,2)$. I claim that $T=(1,4)$ and my proof for this goes like this:
It's clear that $T\subset (1,4)$. Now if $z\in (1,4)$ then clearly $\sqrt z\in S$ and we use the result $z=(\sqrt z)(\sqrt z)$ whence it follows that $z\in T$ (since $\sqrt z\in (1,2)$). Therefore, $(1,4)\subset T$ and we are done.
But I don't know how to do it in general case (#). Another way was to use the fact that every open set in $\mathbb R$ is a countable union of open intervals but that will make things very complicated.
Any hints/suggestions are welcome. Thank you.

A: First show that if $S \subset \Bbb R$ is open and $x \ne 0$ then $xS = \{ xy \mid y \in S \}$ is open. (This is true for subsets of $\Bbb R^n$ or arbitrary normed vector spaces.)
It follows that if $S_1, S_2\subset\mathbb R\setminus\{0\}$ are open then
$$
 S_1 S_2 =  \{ xy \mid (x, y) \in S_1 \times S_2 \} = \bigcup_{x \in S_1} xS_2
$$
is open as a union of open sets.
Actually this is true for all open subsets of $\Bbb R$, even if they contain zero: If either $S_1$ or $S_2$ does not contain zero then the above argument works. And if both sets contain zero then $S_1 S_2 = S_1'S_2$ where $S_1' = S_1 \setminus \{ 0 \}$.

A: In every topological group the product of an open set with an arbitrary set is open because multiplication with a fixed element defines a homeomorphism. So you have a union of open sets.


text:
Q: Update array based on current time I have an array of times that I got from my database.
let list = ["15:15", "15:30", "15:45", "16:00", "16:15", "16:30", "16:45", "17:00", "17:15", "17:30", "17:45", "18:00"];

I want to update and remove the element when the time has expired.
Is there a way to do this without the use of setInterval method?
thanks.

A: Here is the sample to remove expired time intervals from the array:

let list = ["13:01", "15:30", "15:45", "16:00", "16:15", "16:30", "16:45", "17:00", "17:15", "17:30", "17:45", "18:00"];
let currentTime = moment().format("HH:mm");
let result = list.filter(x => x > currentTime);
console.log(result);
<!DOCTYPE html>
<html lang="en">
<head>
    <title></title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
</head>
<body>
</body>
</html>

Sample is using Moment to find the current timezone.

A: There is, two ways one is setInterval, and setTimeout. You can use anyone of this. If you don't want to use these two inbuilt functions. Then, you need to do some manual calculations using some manual methods.
You can do, cookie concept, also...


text:
Q: How to fix this layout? Margin or padding? How to fix this problem?
The staring of "I have read and understand..." and the starting of "Applicant's signature..." are not at the same pacing. One is in
 and one is a table in
. Here is my code of this part.

I have read and understand the "Personal Information Collection Statement" attached in this form.

Please confirm that your instructions have been clearly, accurately, and completely set out in this form
before signing it.

  Applicant's signature:

  <input style="width: 100%;
  margin-left: 5px;
  border: none;
  border-bottom: 1px solid #000;
  background: transparent;
  outline: none !important;"/>

  Date:

  <input style="width: 100%;
  margin-left: 5px;
  border: none;
  border-bottom: 1px solid #000;
  background: transparent;
  outline: none !important;"/>

  Applicant's name:

  <input style="width: 100%;
  margin-left: 5px;
  border: none;
  border-bottom: 1px solid #000;
  background: transparent;
  outline: none !important;"/>

After using the "cellspace=0" method, it is much better. But there is still a small space between them. This is the other application I in a similar way. (I use this example because it can show the different much more easier. The one used above is harder to see the problem.)
Code for this part:

Your Registration Information

  Name:

  <input style="width: 100%;
  margin-left: 5px;
  border: none;
  border-bottom: 1px solid #000;
  background: transparent;
  outline: none !important;"/>

  Email:

  <input style="width: 100%;
  margin-left: 5px;
  border: none;
  border-bottom: 1px solid #000;
  background: transparent;
  outline: none !important;"/>

  Phone:

  <input style="width: 100%;
  margin-left: 5px;
  border: none;
  border-bottom: 1px solid #000;
  background: transparent;
  outline: none !important;"/>

  Reference number:

  <input style="width: 100%;
  margin-left: 5px;
  border: none;
  border-bottom: 1px solid #000;
  background: transparent;
  outline: none !important;"/>

  Date of submission:

  <input style="width: 100%;
  margin-left: 5px;
  border: none;
  border-bottom: 1px solid #000;
  background: transparent;
  outline: none !important;"/>

Thank you very much for your help!

A: Set cellspacing attribute for the table to 0.

I have read and understand the "Personal Information Collection Statement" attached in this form.

Please confirm that your instructions have been clearly, accurately, and completely set out in this form
before signing it.

  Applicant's signature:

  <input style="width: 100%;
  margin-left: 5px;
  border: none;
  border-bottom: 1px solid #000;
  background: transparent;
  outline: none !important;"/>

  Date:

  <input style="width: 100%;
  margin-left: 5px;
  border: none;
  border-bottom: 1px solid #000;
  background: transparent;
  outline: none !important;"/>

  Applicant's name:

  <input style="width: 100%;
  margin-left: 5px;
  border: none;
  border-bottom: 1px solid #000;
  background: transparent;
  outline: none !important;"/>

A: padding is for the parent..
margin is for the child. so either of the 2 you can use for the positioning.
or you can set position:relative to an object and set its position (left,top,right,bottom
)

A: I have added  margin-left: -1px; in the required div.

Your Registration Information

  Name:

  <input style="width: 100%;
  margin-left: 5px;
  border: none;
  border-bottom: 1px solid #000;
  background: transparent;
  outline: none !important;"/>

  Email:

  <input style="width: 100%;
  margin-left: 5px;
  border: none;
  border-bottom: 1px solid #000;
  background: transparent;
  outline: none !important;"/>

  Phone:

  <input style="width: 100%;
  margin-left: 5px;
  border: none;
  border-bottom: 1px solid #000;
  background: transparent;
  outline: none !important;"/>

  Reference number:

  <input style="width: 100%;
  margin-left: 5px;
  border: none;
  border-bottom: 1px solid #000;
  background: transparent;
  outline: none !important;"/>

  Date of submission:

  <input style="width: 100%;
  margin-left: 5px;
  border: none;
  border-bottom: 1px solid #000;
  background: transparent;
  outline: none !important;"/>


text:
Q: .Net Framework 4.5.3 missing from targeting list in visual studio 2013 I have installed .Net Framework 4.5.3 on my machine but Visual Studio is not showing this version in targeting list.
the thing that is happening is that I am loading a project that needs .Net Framework 4.5.3 . While loading, VS tells me that I have to Either change it to 4.5 or download the version required. choosing the download option opens browser with this link:
http://go.microsoft.com/fwlink/?prd=12485&pver=12&sbp=TargetPackMissing&plcid=0x409&o1=.NETFramework,Version=v4.5.3
which does not open and redirects me to microsoft home page.
any solutions?


text:
Q: Why can we suddenly not connect two guitars and drums to Rock Band on Wii? So, we've had Rock Band 3 for the Wii for about a month, and it's been working fine. We've got two guitars (one rock band 2 vintage, one newer), plus the pro drumset.
Everything was working fine, but suddenly, we can't get all three of these instruments to connect at the same time. It seems like any two work, but if we connect a third, the blue light goes on but none of the four controller LEDs lights. We've resynced, unplugged, replugged and so on.
I don't think we changed anything, but maybe we did and I don't know what it was.

A: I'm presuming you're talking about the wireless instruments with the little USB dongles that plug into the Wii. I moved to xbox a while back, but I played RB on Wii so I'll try to dredge up some advice...
I'd guess that your most likely problem is a lack of enough power to the dongles. Are you chaining the dongles together (bass plugged into guitar plugged into drums plugged into console)? If so, you might want to play with the order of the chain, or see if you can break it and plug the dongles into multiple USB ports (I think the Wii has a couple, but my memory's fuzzy).
Even if the order makes a difference, you might want to invest in a powered USB hub and plug all three dongles directly into the hub (make sure you get a powered model with an adapter that plugs into the wall, not one of the super-cheap "self-powered" ones). This will ensure that all your dongles are getting plenty of juice so they can communicate with your instruments.


text:
Q: Custom pidgin plugin crashes (GTK library and GLib on C )   I am developing plugin for Pidgin. I want to share one of my windows that are open on my computer  with other user  via VNC. When I select the window to be shared and press the button, Pidgin freezes and closes.
Here is working well: opening vnc connection and sends Port name to other users. (but this one for sharing all of screen.)
static void
send_button_cb(GtkButton *button, PidginConversation *gtkconv)
{
  gchar *url_vnc;
  gchar *url_http;
  gchar *joinstr;

  int std_out[2];

  int autoport = purple_prefs_get_bool(PREF_AUTOPORT);
  char x11vnc_port[10] = "0";
  if (purple_prefs_get_bool(PREF_X11VNC) && ((x11vnc_pid == 0) || (kill(x11vnc_pid, 0) != 0)))
  {
    if (purple_prefs_get_bool(PREF_GENPASSWD))
    {
      readableRandomString(password, 4);
    }
    else
    {
      strcpy(password, purple_prefs_get_string(PREF_PASSWD));
    }
    sprintf(x11vnc_port, "%d", 5900 + purple_prefs_get_int(PREF_PORT));
    pipe(std_out);
    if ((x11vnc_pid = fork()) == 0)
    {
      close(1);
      close(std_out[0]);
      dup2(std_out[1], 1);
      close(std_out[1]);

      int ret = execlp("x11vnc", "x11vnc", "-shared", "-gui", "tray", "-http", "-viewonly", "-passwd", password, ((autoport) ? "-autoport" : "-rfbport"), x11vnc_port, NULL);

      perror("pidgin_vnc:x11vnc");
      exit(ret);
    }
    close(std_out[1]);
    port_num = x11vnc_port;
    if (fd = fdopen(std_out[0], "r"))
    {
      while (!feof(fd))
      {
        if (fscanf(fd, "PORT=%d", &port_num))
          break;
      }
      port_num -= 5900;
      //close (fd);
      printf("FINI\n");
    }
    else
    {
      port_num = x11vnc_port;
    }
  }
  const char *ip;
  PurpleStunNatDiscovery *stun_res = purple_stun_discover(NULL);
  if (stun_res && stun_res->status == PURPLE_STUN_STATUS_DISCOVERED)
  {
    printf("STUN mode %d %d\n", stun_res->status, stun_res->type);
    ip = purple_network_get_my_ip(-1);
  }
  else
  {
    ip = purple_upnp_get_public_ip();
    if (ip == NULL)
    {
      printf("LOCAL mode\n");
      ip = purple_network_get_my_ip(-1);
    }
    else
    {
      printf("UPNP mode\n");
    }
  }

  url_http = g_strdup_printf("http://%s:%d/", ip, 5800 + port_num);
  url_vnc = g_strdup_printf("vnc://invitation:%s@%s:%d", password, ip, port_num);
  g_log(G_LOG_DOMAIN, G_LOG_LEVEL_DEBUG, url_vnc);

  joinstr = g_strdup_printf("%s.\ntry %s\nor  %s. Password=%s", purple_prefs_get_string(PREF_TEXT), url_vnc, url_vnc, url_http, url_http, password);

  gtk_imhtml_append_text(GTK_IMHTML(gtkconv->entry), joinstr, FALSE);
  g_log(G_LOG_DOMAIN, G_LOG_LEVEL_DEBUG, "imhtml display vnc\n");

  g_signal_emit_by_name(gtkconv->entry, "message_send");
  g_log(G_LOG_DOMAIN, G_LOG_LEVEL_DEBUG, "message sent\n");

  g_free(url_vnc);
  g_free(url_http);
  g_free(joinstr);
}

There is a problem in here. When I click to button which is calling this function program crashes when you click the button.(this function for sharing one of my windows that are open on my computer.)
static void
send_button_cb_win(GtkButton *button, PidginConversation *gtkconv)
{
  gchar *url_vnc;
  gchar *url_http;
  gchar *joinstr;

  int std_out[2];

  int comboBoxSelectedRow = gtk_combo_box_get_active(combo_box);
  char *selectedId[1] = {0};
  selectedId[0] = ekranIds[0][comboBoxSelectedRow];

  int autoport = purple_prefs_get_bool(PREF_AUTOPORT);
  char x11vnc_port[10] = "0";

  if (purple_prefs_get_bool(PREF_X11VNC) && ((x11vnc_pid == 0) || (kill(x11vnc_pid, 0) != 0)))
  {
    if (purple_prefs_get_bool(PREF_GENPASSWD))
    {
      readableRandomString(password, 4);
    }
    else
    {
      strcpy(password, purple_prefs_get_string(PREF_PASSWD));
    }

    sprintf(x11vnc_port, "%d", 5900 + purple_prefs_get_int(PREF_PORT));
    pipe(std_out);

    if((x11vnc_pid = fork()) == 0)
    {
      close(1);
      close(std_out[0]);
      dup2(std_out[1], 1);
      close(std_out[1]);

      int ret = execlp("x11vnc", "x11vnc", "-id", selectedId[0], "-gui", "-shared", "tray", "-http", "-viewonly", "-passwd", password, ((autoport) ? "-autoport" : "-rfbport"), x11vnc_port, NULL);

      perror("pidgin_vnc:x11vnc");

      exit(ret);
    }

    close(std_out[1]);
    port_num = x11vnc_port;

    if (fd = fdopen(std_out[0], "r"))
    {
      while (!feof(fd))
      {
        if (fscanf(fd, "PORT=%d", &port_num))
          break;
      }
      port_num -= 5900;
      //close (fd);
      printf("FINI\n");
    }
    else
    {
      port_num = x11vnc_port;
    }
  }
  const char *ip;
  PurpleStunNatDiscovery *stun_res = purple_stun_discover(NULL);
  if (stun_res && stun_res->status == PURPLE_STUN_STATUS_DISCOVERED)

  {
    printf("STUN mode %d %d\n", stun_res->status, stun_res->type);
    ip = purple_network_get_my_ip(-1);
  }
  else
  {
    ip = purple_upnp_get_public_ip();
    if (ip == NULL)
    {
      printf("LOCAL mode\n");
      ip = purple_network_get_my_ip(-1);
    }
    else
    {
      printf("UPNP mode\n");
    }
  }
  url_http = g_strdup_printf("http://%s:%d/", ip, 5800 + port_num);

  url_vnc = g_strdup_printf("vnc://invitation:%s@%s:%d", password, ip, port_num);
  g_log(G_LOG_DOMAIN, G_LOG_LEVEL_DEBUG, url_vnc);

  joinstr = g_strdup_printf("%s.\ntry %s\nor  %s. Password=%s", purple_prefs_get_string(PREF_TEXT), url_vnc, url_vnc, url_http, url_http, password);

  gtk_imhtml_append_text(GTK_IMHTML(gtkconv->entry), joinstr, FALSE);
  g_log(G_LOG_DOMAIN, G_LOG_LEVEL_DEBUG, "imhtml display vnc\n");

  g_signal_emit_by_name(gtkconv->entry, "message_send");
  g_log(G_LOG_DOMAIN, G_LOG_LEVEL_DEBUG, "message sent\n");

  g_free(url_vnc);
  g_free(url_http);
  g_free(joinstr);
  gtk_widget_show_all(button);
}

This function to fill combobox with opened windows names
static void
refresh_combo_box(GtkWidget *widget, PidginConversation *gtkconv)
{

  FILE *fp1;
  FILE *fp2;
  char path[1035];
  char path2[1035];
  char sum[1035];

  /* Open the command for reading. */
  fp1 = popen("xprop -root | grep '_NET_CLIENT_LIST_STACKING(WINDOW)'", "r");
  if (fp1 == NULL)
  {
    printf("Failed to run command\n" );
    exit(1);
  }

  /* Read the output a line at a time - output it. */
  while (fgets(path, sizeof(path) - 1, fp1) != NULL)
  {
    // printf("%s", path);
    strcat(sum, path);

  }

  char *splitter = strtok(sum, "#");
  splitter = strtok(NULL, "#");
  char *virgulSplitter = strtok(splitter, ", ");
  ekranIds[0][0] = strdup(virgulSplitter);
  int a = 1;
  while (virgulSplitter != NULL)
  {
    virgulSplitter = strtok(NULL, ",");
    if (virgulSplitter != NULL)
    {
      ekranIds[0][a] = strdup(virgulSplitter);
      a++;
    }
  }

  for (int x = 0; x < a; x++)
  {

    ekranIds[0][a - 1][strcspn(ekranIds[0][a - 1], "\n")] = 0;
    char tmp[500] = {0};
    //here is get window names by id
    sprintf(tmp, "xprop -id %s | grep '^WM_NAME'", ekranIds[0][x]);
    fp2 = popen(tmp, "r");
    if (fp1 == NULL)
    {
     printf("Failed to run command\n" );
      exit(1);
    }

    // Read the output a line at a time - output it.
    while (fgets(path2, sizeof(path2) - 1, fp2) != NULL)
    {
      char *windowSplitter = strtok(path2, "=");
      windowSplitter = strtok(NULL, "=");
      ekranIds[1][x] = strdup(windowSplitter);
    }
  }
  pclose(fp2);
  pclose(fp1);
  char *combobox_source[30];
  for (int yf = 0; yf < 30; yf++)
  {
    if (ekranIds[1][yf] != NULL)
    {
      combobox_source[yf] = strdup(ekranIds[1][yf]);
    }
  }
  gtk_list_store_clear(GTK_LIST_STORE(gtk_combo_box_get_model(combo_box)));
  for (int i = 0; i < G_N_ELEMENTS(combobox_source); i++)
  {
    gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(combo_box), combobox_source[i]);
  }
  gtk_combo_box_set_active(GTK_COMBO_BOX(combo_box), 0);
  gtk_widget_show_all(combo_box);
}

First function is working well: opening vnc connection and sends Port name to other users. (but this one for sharing all of screen.)
Second function has problem. When I click to button which is calling this function program crashes when you click the button.(this function for sharing one of my windows that are open on my computer.)
Third function to fill combobox with opened windows' names.


text:
Q: If N Bayesians estimate the probability of something, how do you aggregate their estimations? If N Bayesians all estimate the probability of some event, how do you aggregate their estimates to get a final estimate? (Assume they are all equally trustworthy, or at least you have no reason to favor one over another)
For example, if one says 50%, another 80%, and a third 70%, do you take the mean, median, geometric mean?

A: Your question is presently ill-posed, and it really depends on what kind of "aggregation" you have in mind.  Each Bayesian has a legitimate posterior estimate based on observed data and a prior belief, so presumably if you want "aggregate" these posterior estimates, you want to use a prior that is related somehow to the priors of the Bayesians in your question (e.g., a combination of their priors).  One way to specify the "aggregation" is to specify how your own prior relates to the priors of these Bayesians, which in turn determines how your posterior relates to their posteriors.  I will show you how you can do this below.

Since you have not specified to the contrary, I am going to assume that all the Bayesians in your question observe the same data $\mathbf{x}$, which they all take to come from the same sampling distribution with likelihood function $L(\theta)$.  I will also assume that, conditional on the unknown parameter $\theta \in \Theta$, the probability of the event of interest is $0 \leqslant h(\theta) \leqslant 1$.  This setup means that all the Bayesians perform the same inference, but they may each have different priors for the unknown parameter.  (And hence, their estimated probabilities of the event may differ.)
Now, suppose that your Bayesians have priors $\pi_1,...,\pi_N$.  Then for Bayesian $i$ the posterior probability of the event of interest is:
$$H_i = \mathbb{E}(h(\theta)| \mathbf{x},\pi_i) = \frac{\int_\Theta h(\theta) L(\theta) \pi_i(\theta) d\theta}{\int_\Theta L(\theta) \pi_i(\theta) d\theta}.$$
Now, how you aggregate these probabilities depends on how your own prior relates to the priors of the $N$ Bayesians in the analysis.  For example, if your prior is some convex combination of priors of these Bayesians, then you have $\pi_* = \sum_{i=1}^n \lambda_i \pi_i$ and your corresponding posterior probability is:
$$H_* = \frac{\int_\Theta h(\theta) L(\theta) \pi_*(\theta) d\theta}{\int_\Theta L(\theta) \pi_*(\theta) d\theta} = \frac{\sum_{i=1}^n \lambda_i \int_\Theta h(\theta) L(\theta) \pi_i(\theta) d\theta}{\sum_{i=1}^n \lambda_i \int_\Theta L(\theta) \pi_i(\theta) d\theta} = \sum_{i=1}^n \lambda_i^* H_i,$$
where the updated posterior weights $\lambda_1^*,...,\lambda_N^*$ are given by:
$$\lambda_i^* = \frac{\lambda_i \int_\Theta L(\theta) \pi_i(\theta) d\theta}{\sum_{i=1}^n \lambda_i \int_\Theta L(\theta) \pi_i(\theta) d\theta}.$$
This gives you a rule for "aggregating" the posterior estimates of your Bayesians, based on an assumption that your preferred prior is some combination of their priors.  As you can see, the updated posterior weightings are related to the prior weightings by a linear weighting that depends on the likelihood and priors.  In the case where the Bayesians are "equally trustworthy" you might decide that your prior is a simple average of their priors,so that $\lambda_1 = ... = \lambda_N = \tfrac{1}{N}$.  In this special case, the posterior weightings for the estimated probability of the event are:
$$\lambda_i^* = \frac{\int_\Theta L(\theta) \pi_i(\theta) d\theta}{\sum_{i=1}^n \int_\Theta L(\theta) \pi_i(\theta) d\theta}.$$
This result could arguably meet your requirement to "aggregate" the posterior estimates based on each Bayesian being "equally trustworthy".  As you can see, even with the simplification of equal weighting on the priors, the aggregation is still more complicated than taking a simple mean, median or geometric mean.


text:
Q: Mysql custom post types I am using WpDataTables for Wordpress plugin. However, this is general mySQL Query and it works fine until this point.
SELECT posts_apex_po.ID AS apex_po_ID,
posts_apex_po.post_title AS apex_po_post_title,
posts_apex_po_payment.ID AS apex_po_payment_ID,
posts_apex_po_payment.post_title AS apex_po_payment_post_title
FROM wp_posts AS posts_apex_po, wp_posts AS posts_apex_po_payment
WHERE 1=1
AND posts_apex_po.post_status = 'publish'
AND posts_apex_po.post_type = 'apex_po'
AND posts_apex_po_payment.post_status = 'publish'
AND posts_apex_po_payment.post_type = 'apex_po_payment'

The problem is that when I try to get post meta values of apex_po or apex_po_payment custom post types, it does not work.
apex_po_payment has a meta key apex_po_meta.purchase_order which has value of apex_po ID
So basically Apex_PO is a purchase order and when you create a payment using apex_po_payment, you select a apex_po ID to link it ito.
I am trying to display the linked PO & PO Payment but its not working.
Any help?

A: I was able to figure it out on my own after a little search here n there and making sense of mysql join queries. I had to make two separate queries on each custom post type in same mysql table and then left join them on the field I wanted.
Posting answer for any one that come across the same issue in future.
SELECT * FROM (
    SELECT
    posts_apex_po.ID AS apex_po_id,
    posts_apex_po.post_title AS apex_po_post_title,
    apex_po_meta_grand_total_tbl.meta_value AS apex_po_meta_grand_total,

FROM wp_posts AS posts_apex_po
  INNER JOIN (SELECT apex_po_meta_grand_total_tbl_posts.ID as id, meta_value, meta_key  FROM wp_postmeta AS apex_po_meta_grand_total_tbl_postmeta  INNER JOIN wp_posts AS apex_po_meta_grand_total_tbl_posts   ON apex_po_meta_grand_total_tbl_postmeta.post_id = apex_po_meta_grand_total_tbl_posts.ID   AND apex_po_meta_grand_total_tbl_posts.post_type = 'apex_po') AS apex_po_meta_grand_total_tbl
     ON apex_po_meta_grand_total_tbl.meta_key = 'grand_total' AND apex_po_meta_grand_total_tbl.id = posts_apex_po.ID
WHERE 1=1
   AND posts_apex_po.post_status = 'publish'
   AND posts_apex_po.post_type = 'apex_po' ) x

LEFT JOIN

( SELECT posts_apex_po_payment.post_date AS apex_po_payment_post_date,
       posts_apex_po_payment.post_title AS apex_po_payment_post_title,
       apex_po_payment_meta_amount_paid_tbl.meta_value AS apex_po_payment_meta_amount_paid,
       apex_po_payment_meta_purchase_order_tbl.meta_value AS apex_po_payment_meta_purchase_order
FROM wp_posts AS posts_apex_po_payment
  INNER JOIN (SELECT apex_po_payment_meta_amount_paid_tbl_posts.ID as id, meta_value, meta_key  FROM wp_postmeta AS apex_po_payment_meta_amount_paid_tbl_postmeta  INNER JOIN wp_posts AS apex_po_payment_meta_amount_paid_tbl_posts   ON apex_po_payment_meta_amount_paid_tbl_postmeta.post_id = apex_po_payment_meta_amount_paid_tbl_posts.ID   AND apex_po_payment_meta_amount_paid_tbl_posts.post_type = 'apex_po_payment') AS apex_po_payment_meta_amount_paid_tbl
     ON apex_po_payment_meta_amount_paid_tbl.meta_key = 'amount_paid' AND apex_po_payment_meta_amount_paid_tbl.id = posts_apex_po_payment.ID
  INNER JOIN (SELECT apex_po_payment_meta_purchase_order_tbl_posts.ID as id, meta_value, meta_key  FROM wp_postmeta AS apex_po_payment_meta_purchase_order_tbl_postmeta  INNER JOIN wp_posts AS apex_po_payment_meta_purchase_order_tbl_posts   ON apex_po_payment_meta_purchase_order_tbl_postmeta.post_id = apex_po_payment_meta_purchase_order_tbl_posts.ID   AND apex_po_payment_meta_purchase_order_tbl_posts.post_type = 'apex_po_payment') AS apex_po_payment_meta_purchase_order_tbl
     ON apex_po_payment_meta_purchase_order_tbl.meta_key = 'purchase_order' AND apex_po_payment_meta_purchase_order_tbl.id = posts_apex_po_payment.ID
WHERE 1=1
   AND posts_apex_po_payment.post_status = 'publish'
   AND posts_apex_po_payment.post_type = 'apex_po_payment' ) y
ON  y.apex_po_payment_meta_purchase_order = x.apex_po_id

A: According to your mentioned query you are trying to get a post having two post types at same time.
AND posts_apex_po.post_type = 'apex_po'
AND posts_apex_po_payment.post_type = 'apex_po_payment'

Its not possible that a single post have two different post types at same time, so you should OR in between that.


text:
Q: bash: [: 1+1: integer expression expected I have a main directory with 40 subdirectories with names [Set 1], [Set 2] ... [Set 40], each containing 20 wallpapers with name 1.jpg, 2.jpg, ... 20.jpg. I want to move all these wallpapers to the main directory and rename them as 1.jpg, 2.jpg ... 800.jpg. I wrote the following Bash script but getting error.
i=1; j=1; k=1;
while [ $i -ne 41 ]; do
  j=1;
  while [ $j -ne 21 ]; do
    mv \[Set\ $i\]/$j.jpg $k.jpg;
    j=$j+1;
    k=$k+1;
  done;
  i=$i+1;
done

bash: [: 1+1: integer expression expected
bash: [: 1+1: integer expression expected

Where am I making a mistake?

A: In bash you enclose mathmatical/arithmetical operations in $(()), so
i=1; j=1; k=1;
while [ $i -ne 41 ]; do
    j=1
    while [ $j -ne 21 ]; do
        mv "[Set ${i}]/${j}.jpg" $k.jpg
        j=$(($j+1)) k=$(($k+1))
    done
    i=$(($i+1))
done

Should do what you want..


text:
Q: How do I define parameters in a convolution equation? I am trying to compute the convolution of a sound signal without using the built in conv function but instead using arrays. x is the input signal and h is are the impulse responses. However, when I run my other main function to call onto my_conv I am getting these errors:

Undefined function or variable 'nx'.**

Error in my_conv (line 6)
ly=nx+nh-1;

Error in main_stereo (line 66)
leftchannel = my_conv(leftimp, mono); % convolution of left ear impulse response and mono

This is my function my_conv:
function [y]=my_conv(x,h)
  x=x(:);
  h=h(:);
  lx=length(x);
  lh=length(h);
  ly=nx+nh-1;
  Y=zeros(nh,ny);
  for i =1:nh
    Y((1:nx)+(i-1),i)=x;
  end
  y=Y*h;

What changes should I make to fix these errors and get this code running?
I am trying to immplement the function into this code:
input_filename = 'speech.wav';
stereo_filename = 'stereo2.wav';
imp_filename = 'H0e090a.dat';
len_imp = 128;
fp = fopen(imp_filename, 'r', 'ieee-be');
data = fread(fp, 2*len_imp, 'short');
fclose(fp);
[mono,Fs] = audioread(input_filename);
if (Fs~=44100)
end
len_mono = length(mono);

leftimp  = data(1:2:2*len_imp);
rightimp = data(2:2:2*len_imp);
leftchannel  = my_conv(leftimp, mono);
rightchannel = my_conv(rightimp, mono);

leftchannel  = reshape(leftchannel , length(leftchannel ), 1);
rightchannel = reshape(rightchannel, length(rightchannel), 1);
norml = max(abs([leftchannel; rightchannel]))*1.05;
audiowrite(stereo_filename,  [leftchannel rightchannel]/norml, Fs);

A: As pointed out by @SardarUsama in comments, the error

Undefined function or variable 'nx'.
Error in my_conv (line 6) ly=nx+nh-1;

tells you that the variable nx has not been defined before before its usage on the line ly=nx+nh-1. Given the naming of the variables and their usage, it looks like what you intended to do was:
nx = length(x);
nh = length(h);
ny = nx+nh-1;

After making these modifications and solving the first error, you are likely going to get another error telling you that

error: my_conv: operator *: nonconformant arguments

This error is due to an inversion in the specified size of the Y matrix. This can be fixed by initializing Y with Y = zeros(ny, nh);. The resulting my_conv function follows:
function [y]=my_conv(x,h)
  nx=length(x);
  nh=length(h);
  ny=nx+nh-1;

  Y=zeros(ny,nh);
  for i =1:nh
    Y((1:nx)+(i-1),i)=x;
  end
  y=Y*h;

Note that storing every possible shifts of one of the input vectors in the matrix Y to compute the convolution as a matrix multiplication is not very memory efficient (requiring O(NM) storage). A more memory efficient implementation would compute each element of the output vector directly:
function [y]=my_conv(x,h)
  nx=length(x);
  nh=length(h);
  if (nx < nh)
    y = my_conv(h,x);
  else
    ny=nx+nh-1;

    y = zeros(1,ny);
    for i =1:ny
      idh = [max(i-(ny-nh),1):min(i,nh)]
      idx = [min(i,nx):-1:max(nx-(ny-i),1)]
      y(i) = sum(x(idx).*h(idh));
    end
  end

An alternate implementation which can be more computationally efficient for large arrays would make use of the convolution theorem and use the Fast Fourier Transform (FFT):
function [y]=my_conv2(x,h)
  nx=length(x);
  nh=length(h);
  ny=nx+nh-1;

  if (size(x,1)>size(x,2))
    x = transpose(x);
  end
  if (size(h,1)>size(h,2))
    h = transpose(h);
  end
  Xf = fft([x zeros(size(x,1),ny-nx)]);
  Hf = fft([h zeros(size(h,1),ny-nh)]);

  y = ifft(Xf .* Hf);


text:
Q: How to debug widget applications in Xamarin studio? I'm experimenting with Simple widget application in Xamarin studio and would like to know how to debug it. Trying regular 'Run -> Start Debugging' (F5) produces

Application does not contain a launchable activity

As far as I understand ActivityAttribute.MainLauncher property is designed specifically for this purpose but there is no activity to apply it to in the example I'm playing with.
p.s.
Is there something similar to 'Attach to process' feature?

A: It seems that there is still no simple solution other than embedding your widget into a self created activity just for the debugging purposes. The last post from the Xamarin team I've found is here.
I've tried a few approaches with an empty activity and trying to trick the debugger - but failed.


text:
Q: Firebase: Send OTP but disable sign in using phone number I am working on a simple registration. I planned to use email to create an account, the problem is upon submission of form, the phone number also signed in as new user.
How can I prevent that from happening? What I only need to use is the send otp feature.
      sendOTP() {
        var self = this
        const phoneNumber = '+' + this.phone;
        const appVerifier = window.recaptchaVerifier;
        firebase.auth().signInWithPhoneNumber(phoneNumber, appVerifier)
          .then((confirmationResult) => {
            window.confirmationResult = confirmationResult;
            self.otpSent = true
          }).catch((error) => {
            self.errorMsg = error.code + ': ' + error.message;
          });
      },
      register() {
        var self = this
        const code = this.otp;
        window.confirmationResult.confirm(code).then((result) => {
          console.log(result)
          firebase.auth().createUserWithEmailAndPassword(this.email, this.password)
            .then((userCredential) => {
              firebase.database().ref('users').set({
                email: this.email,
                name: this.name,
                password: this.password,
                phone: this.phone,
                userCredential: userCredential
              }, (error) => {
                if (error) {
                  // The write failed...
                  self.errorMsg = error.message
                } else {
                  self.$router.push('/dashboard')

                }
              });
            })
            .catch((error) => {
              self.errorMsg = error.message
            });

        }).catch((error) => {
          self.errorMsg = error.message;
        });
      }

A: glad to see you are trying to utilize the firebase's mobile verifications but see the problem is you are trying to use the SDK, which has been programmed by the people at Firebase to perform things in a certain way.
Below example takes an assumption that you have a Firebase Firestore DB at the backend, but this can even work with RealTime DB too.

If you can write a cloud function backend and maintain say a profile of user in a /userDetails collection where the individual document records are stored with the User UID of your Firebase Authentication, there you can store a phone number and its boolean status as phoneVerified: true or false.

Hence the collection in the Firestore would look like /userDetails/UserUID/ with fields phoneNumber as Number and phoneVerified:true or false

Do it at the backend by triggering an API call to the cloudfunction.
Then you can refer to this link too
Best Regards !!
:-)


text:
Q: Is it possible to query systemd services not having Restart=always? I would like to make sure all our services have Restart=always.
A list of services with the Restart value would be fine too, I could use grep on that.

A: Use drop-in config files to override this value.
For unit thing.service create /etc/systemd/system/thing.service.d/restart.conf containing
[Service]
Restart=always


text:
Q: Local Storage to store ascending/descending order I have this 'sort' button in my code that sorts the prices of courses according to highest to lowest and vice versa. The button works perfectly fine, I am now trying to do local storage to preserve the order (descending or ascending) so that the order stays the same even if the page refreshes. Here is my local storage code:
  window.addEventListener('beforeunload', () => {
    localStorage.setItem('order', JSON.stringify(courses));
    });

var orderList = localStorage.getItem('order');

   function getCourseOrder() {
      if (orderList) {
        return JSON.parse(orderList);
      } else {
        return [];
      }
    }

 window.onload = function() {
 generateList(getCourseOrder())
}
//generateList is to create elements and append etc

The problem is the order (descending/ascending) stays the same for only one refresh, then it returns to the original after the second refresh. I have created a codepen: https://codepen.io/ShawnTan15/pen/vYxebyO

A: I have gone through your JS code and there is only one minor mistake you have made, in onload function you also have to modify the courses variable, so when next (2nd) unload happens, it will take the correct sorted courses (because you are setting the local courses list to localstorage) instead of global courses list.
// Made it let
let courses = [
  {
    name: "Complete ReactJS course",
    price: "2.3",
  },
  {
    name: "Complete Angular course",
    price: "2.1",
  },
  {
    name: "Complete Mern course",
    price: "2.9",
  },
  {
    name: "Complete C++ course",
    price: "2.4",
  },
];

function generateList(courseList) {
  const ul = document.querySelector(".list-group");
  ul.innerHTML = "";
  courseList.forEach((course) => {
    const li = document.createElement("li");
    li.classList.add("list-group-item");
    const name = document.createTextNode(course.name);
    li.appendChild(name);
    const span = document.createElement("span");
    span.classList.add("float-right");
    const price = document.createTextNode("$ " + course.price);
    span.appendChild(price);
    li.appendChild(span);
    ul.appendChild(li);
  });
}

generateList(courses);

const btn = document.querySelector(".btn-success");
let activeSortingType;
let isSortingDirty = false;
btn.addEventListener("click", function () {
  isSortingDirty = true;
  if (activeSortingType === "asc") {
    activeSortingType = "desc";
    courses.sort((a, b) => b.price - a.price);
  } else if (activeSortingType === "desc") {
    activeSortingType = "asc";
    courses.sort((a, b) => a.price - b.price);
  } else if (activeSortingType === null) {
    activeSortingType = "asc";
    courses.sort((a, b) => a.price - b.price);
  }
  generateList(courses);
});

////////Local Storage////////
/////////////////////////////

window.addEventListener("beforeunload", (e) => {
  localStorage.setItem("order", JSON.stringify(courses));
  if (activeSortingType !== null && isSortingDirty) {
    const currentSortingType = localStorage.setItem(
      "activeSortingType",
      activeSortingType
    );
  }
});

const orderList = localStorage.getItem("order");

function getCourseOrder() {
  if (orderList) {
    // Updating the courses list here in onload
    courses = JSON.parse(orderList);
    return courses;
  } else {
    return [];
  }
}

window.onload = function () {
  const courseList = getCourseOrder();
  activeSortingType = localStorage.getItem("activeSortingType");
  if (courseList.length) {
    generateList(courseList);
  }
};

A: I would suggest you don't save all the courses into local storage, but instead just save the order:
let courses = [
  {
    name: "Complete ReactJS course",
    price: "2.3"
  },
  {
    name: "Complete Angular course",
    price: "2.1"
  },
  {
    name: "Complete Mern course",
    price: "2.9"
  },
  {
    name: "Complete C++ course",
    price: "2.4"
  }
];

function generateList() {
  const ul = document.querySelector(".list-group");
  ul.innerHTML = "";

  courses.forEach((course) => {
    const li = document.createElement("li");
    li.classList.add("list-group-item");
    const name = document.createTextNode(course.name);
    li.appendChild(name);
    const span = document.createElement("span");
    span.classList.add("float-right");
    const price = document.createTextNode("$ " + course.price);
    span.appendChild(price);
    li.appendChild(span);
    ul.appendChild(li);
  });
}

const btn = document.querySelector(".btn-success");

let desc = localStorage.getItem("order") == "descending";

function sortCourses() {
  courses.sort((a, b) => desc ? b.price - a.price : a.price - b.price);
}

sortCourses();

btn.onclick = () => {
  desc = !desc;

  sortCourses();

  generateList();
}

//////// Local Storage ////////
///////////////////////////////

window.addEventListener("beforeunload", (e) => {
  localStorage.setItem("order", desc ? "descending" : "ascending");
});

window.onload = () => generateList();

Link to codepen


text:
Q: What page function occurs after event handling? This is probably a silly question. Let's say I have 20 event handlers that will go off after the postback. I want to open a connection to the database right before the events start, and then close it right after they end. Where would I put my open and close statements in my webform?

A: Events are raised after Page_Load event in the page's life cycle. So you could open it there and close it in Page_PreRender.
But actually i would suggest to avoid open connections at all. An open connection can not be reused. So you should always close connections as soon as possible where you've used it, best by using using-statement.

A: You need to understand the ASP.NET page life cycle
The postback events occur between the Load and LoacComplete page's events, therefore if you want to guarantee that the connection is opened, you could open it in the Load (or before) event and close it in the LoadComplete event (or later)
However if an error occurs, probably the LoadComplete event won't be called.
It is a better approach to use a using statement to work with database connections:
using(var cn = new SqlConnection(".."))
{
   cn.open();
   // here your database code
}

As a quick view:


text:
Q: htaccess wordpresses accessing files in sub directory without 404 I've set up Wordpress in the root directory on a server for a client. They previously had an old version of Wordpress installed before and whatever way the htaccess was set up it allowed them to view sub directories of files in the FTP without getting a wordpress 404 page.
I managed to get it working by turning off RewriteEngine, but all of the links broken on the website.
This is the htaccess at the moment:
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress


text:
Q: Spacing after \declaretheoremstyle I'm trying to implement a theoremstyle which is shaded and found a way by using mdframed in \declaretheoremstyle and it looks pretty good, but I want to increase the spacing after the text. Above the text I can control the spacing without any problems using spaceaboveand skipabove, but the corresponding commands spacebelow and skipbelow don't work. Does anybody know why?
\documentclass[11pt,a4paper]{amsproc}
\usepackage{amssymb, amsthm, amsmath, amsfonts}
\usepackage{xcolor, color}
\usepackage{thmtools}
\newcounter{counter}
\usepackage{lipsum}

\declaretheoremstyle[
headfont=\normalfont\bfseries,
notefont=\mdseries, notebraces={(}{)},
bodyfont=\normalfont,
postheadspace=0.5em,
spaceabove=10pt,
spacebelow=20pt,
mdframed={
    skipabove=10pt,
    skipbelow=0pt,
    hidealllines=true,
    backgroundcolor={gray!50!white},
    innerleftmargin=10pt,
    innerrightmargin=10pt}
]{shaded}
\declaretheorem[style=shaded,sibling=counter]{aufgabe}

\begin{document}
    \lipsum[1][1-3]
    \begin{aufgabe}
        \lipsum[1][4-7]
    \end{aufgabe}
    \lipsum[1][7-9]
\end{document}


text:
Q: Lightbox Gallery in OpenLayers PopUp I am currently designing a website that uses openlayers extensively. There are various vector markers placed on the map and when the user clicks a marker a popup appears. Within this popup there is some images that have been set up for lightbox. The only problem is that when the thumbnail is clicked on the image opens in a new window (i.e. There was no event recognition by Lightbox for the link). The html for the lightbox is perfectly fine as I have tested it outside the popups.
I would like to have lightbox working in the popups and any help would be greatly appreciated.
Here is my code:
Popup Created:
function onFeatureSelect(feature) {
    selectedFeature = feature;
    popup = new OpenLayers.Popup.AnchoredBubble("PopUp",
                    feature.geometry.getBounds().getCenterLonLat(),
                    null,
                    null,
                    null, true, onPopupClose);
    popup.setContentHTML('

');
    feature.popup = popup;

    map.addPopup(popup);
}

Excerpt from Lightbox.js concerning the click listening:
updateImageList: function() {
    this.updateImageList = Prototype.emptyFunction;
    document.observe('click', (function(event){
        var target = event.findElement('a[rel^=lightbox]') || event.findElement('area[rel^=lightbox]');
        if (target) {
            event.stop();
            this.start(target);
        }
    }).bind(this));
},

Thanks for reading. Any help would be greatly appreciated.

A: Although I never solved the issue with Lightbox, switching to Lightbox2.js solved the problem for me.

A: For me the switch to Lightbox2 doesn't work because I have currently no jquery in my project ... so here the steps to bring it on with Openlayers 2.13.1
At first initialize lightbox manually. A given onload function in the body tag seems to overwrite the standard initialization in lightbox.js
function initMap() {
    // manually call the init function from lightbox.js
    if (initLightbox)
        initLightbox();
...

Next step is to add the onclick function to your image thumbs by hand. Normally lightbox does this for you, but the popup content is loaded dynamic after click on a feature symbol.
The image link should look in a way like this

After this changes the image loading should work. Unfortunately the picture is shown behind the map. A simple change of css solve this problem.
#overlay {
    z-index: 1100 ! important;
}

#lightbox {
    z-index: 1101 ! important;
}

Hope it helps somebody :-D


text:
Q: What happens on a Cache miss? In the present day processors more than one level of memory is present for trying for the realization of an ideal memory system and to do more work for clock cycle more than one instruction is in the pipeline of execution by exploiting the ILP (Instruction Level Parallelism).
My question is, upon a cache miss, what happens? i.e., whether the instructions prior to and instructions after the instruction causing the cache miss are stalled or only the instructions after the instruction causing cache miss are stalled?
I know that the cases may arise depending on whether the processor is having speculative and out-of-order execution and if the processor also have the ability to exploit the MLP (Memory Level Parallelism).
I want to know about the cases of processor having MLP and not having it
I was not able to find helpful information.

A: Instructions before (in program order) the data cache miss will flow down the pipeline as normal. (An unusual exception would be a push-based pipeline as used by some early VLIWs. Such required subsequent operations to push previous operations down the pipelines.)
For a cache miss on a store, the stored value can be placed into a buffer allowing the store to complete despite the cache miss. (This is possible because the buffer does not require any data from memory, typically accomplished by having a valid bit for each storable unit [typically byte].)
Many processors using in-order execution allow instructions after a load to execute and complete—even another load—if the following instructions are not data dependent on the load (or, of course, after an instruction that is data dependent). This can be accomplished by the use of a scoreboard marking the availability of each register.
For an out-of-order processor, instructions after an instruction that is dependent on the cache missing load instruction can be completely executed and results stored in rename registers (or a store queue for stores to memory) but not committed.
Control flow instructions like branches and indirect jumps are special in that following instructions are dependent on the result, but often prediction can be effectively used to hide this dependency. Although value prediction for load misses has been studied, the benefit is relatively limited given the cost.
In theory it would sometimes also be possible to speculatively partially execute dependent instructions. E.g.:
  lw r3, [r5]; // load word
  add r3, r3, #50; // r3 = r3 + 50
  slt r6, r3, #1000; // (r3<1000)?r6=1:r6=0
  bez r6 LABEL; // if r6=0 goto LABEL
  addi r3, r3, #10; // r3 = r3 + 10
LABEL:

Theoretically, hardware could speculate that the branch is not taken and add 50 and 10 so that 60 would be added to the value when it becomes available. This kind of optimization has been proposed for (instruction) trace caches.
Some instructions may also be broken into component operations which are not dependent on the not-yet-available value to allow partial execution of the instruction. E.g., division using a Newton-Raphson mechanism can generate the reciprocal while the dividend is unavailable.

A: I have seen several solutions depending on the processor and memory architecture. Sometimes there is a simple stall while main memory is accessed, being slower than cache. Sometimes a pipeline is flushed and a full page is brought from the MMU to cache. On more complicated systems multiple strategies are employed. Are you looking at a particular architecture?
I recall a discussion about half of cache being lockable on some ARM processors and you can load that section with time-critical kernel code or code from an important loop that needs the speed, then lock the cache. This could mean the difference between fetching code from 100 MHz RAM versus always running at 400 or 600 MHZ or even 1.5GHZ. I have not tried it and don't know the upper limit on the cache memory speed. I will need it one day and have to find out if it is true.


text:
Q: External list with hyperlinks sharepoint 2013 How do I make a column (content) a hyperlink with an external list in SharePoint 2013? I have the url in the database and need to turn it into a hyperlink.

A: In SP2013 you can use CSR - Client Side Rendering to change the display and add HTML around the url.
You could try adding a Calculated Column with Formula:
   ="" & Title & ""

and set the datatype to Number
This will output as HTML... But only on ListViews!  Then again it works in 2010 as well.