text:
Q: "gpg: signing failed: Inappropriate ioctl for device" on MacOS with Maven I have installed GPG via Homebrew with brew install gpg.
It is installed in version 2.2.17.
In my Maven POM I have this snippet:
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-gpg-plugin</artifactId>
    <version>1.6</version>
    <executions>
        <execution>
            <id>sign-artifacts</id>
            <phase>verify</phase>
            <goals>
                <goal>sign</goal>
            </goals>
        </execution>
    </executions>
</plugin>

However when running mvn clean verify I get this error:
gpg: Beglaubigung fehlgeschlagen: Inappropriate ioctl for device
gpg: signing failed: Inappropriate ioctl for device

How can I fix this error?

A: On macOS you may want to use pinentry-mac to have GUI window to enter pin and optionally store pin in keychain.
You can install it though Homebrew:
brew install pinentry-mac

And enable it with the following line in your ~/.gnupg/gpg-agent.conf config (create it if it doesn't exists):
pinentry-program /usr/local/bin/pinentry-mac

A: I have added
GPG_TTY=$(tty)
export GPG_TTY

to my ~/.bash_profile file. Now it is working.
See also https://github.com/Homebrew/homebrew-core/issues/14737#issuecomment-309848851

A: Try this
gpg --use-agent --armor --detach-sign --output $(mktemp) pom.xml

A: For me, this happened because the terminal window wasn't big enough to fit the passphrase TUI. Once I opened a bigger terminal tab and then I rerun the gpg command, I was able to see the passphrase terminal user interface.

A: If anybody gets this error message when typing gpg commands in bash, try adding --no-tty. That fixed it for me.


text:
Q: FastAPI : pass session provider through @manager.user_loader I'm confronted to an issue with fastapi_login. I'm trying to pass my db connection function to the manager user_loader.
I follow this doc : https://fastapi-login.readthedocs.io/advanced_usage/
database.py
def get_db():
    db = SessionLocal()
    try:
        yield db
    except:
        db.close()

users.py
@manager.user_loader(session_provider=database.get_db)
async def get_user(username: str, session_provider) :
    db = session_provider()
    user = db.query(UserDb).filter_by(username=username).first()

    return user

routes.py
@router.post('/login', response_model=UserSchema)
async def login(data: OAuth2PasswordRequestForm = Depends()):
    username = data.username
    password = data.password

    user = await users.get_user(username)

It look like the session_provider is not catched by the @manager. I have the feeling that I respect what that said in the documentation. Here is the guvicorn error I get:
eb_1      | Traceback (most recent call last):
web_1      |   File "/usr/local/lib/python3.9/site-packages/uvicorn/protocols/http/h11_impl.py", line 366, in run_asgi
web_1      |     result = await app(self.scope, self.receive, self.send)
web_1      |   File "/usr/local/lib/python3.9/site-packages/uvicorn/middleware/proxy_headers.py", line 75, in __call__
web_1      |     return await self.app(scope, receive, send)
web_1      |   File "/usr/local/lib/python3.9/site-packages/fastapi/applications.py", line 261, in __call__
web_1      |     await super().__call__(scope, receive, send)
web_1      |   File "/usr/local/lib/python3.9/site-packages/starlette/applications.py", line 112, in __call__
web_1      |     await self.middleware_stack(scope, receive, send)
web_1      |   File "/usr/local/lib/python3.9/site-packages/starlette/middleware/errors.py", line 181, in __call__
web_1      |     raise exc
web_1      |   File "/usr/local/lib/python3.9/site-packages/starlette/middleware/errors.py", line 159, in __call__
web_1      |     await self.app(scope, receive, _send)
web_1      |   File "/usr/local/lib/python3.9/site-packages/starlette/exceptions.py", line 82, in __call__
web_1      |     raise exc
web_1      |   File "/usr/local/lib/python3.9/site-packages/starlette/exceptions.py", line 71, in __call__
web_1      |     await self.app(scope, receive, sender)
web_1      |   File "/usr/local/lib/python3.9/site-packages/fastapi/middleware/asyncexitstack.py", line 21, in __call__
web_1      |     raise e
web_1      |   File "/usr/local/lib/python3.9/site-packages/fastapi/middleware/asyncexitstack.py", line 18, in __call__
web_1      |     await self.app(scope, receive, send)
web_1      |   File "/usr/local/lib/python3.9/site-packages/starlette/routing.py", line 656, in __call__
web_1      |     await route.handle(scope, receive, send)
web_1      |   File "/usr/local/lib/python3.9/site-packages/starlette/routing.py", line 259, in handle
web_1      |     await self.app(scope, receive, send)
web_1      |   File "/usr/local/lib/python3.9/site-packages/starlette/routing.py", line 61, in app
web_1      |     response = await func(request)
web_1      |   File "/usr/local/lib/python3.9/site-packages/fastapi/routing.py", line 227, in app
web_1      |     raw_response = await run_endpoint_function(
web_1      |   File "/usr/local/lib/python3.9/site-packages/fastapi/routing.py", line 160, in run_endpoint_function
web_1      |     return await dependant.call(**values)
web_1      |   File "/code/app/routers/users.py", line 56, in login
web_1      |     user = await lib.users.get_user(username)
web_1      | TypeError: get_user() missing 1 required positional argument: 'session_provider'

Any idea how to deal with this ?
Some references I tried without success :

*

*https://github.com/MushroomMaula/fastapi_login/issues/61
Actually, I bypass the problem by sending the connection session as parameter of get_user in the route.But I prefer put my connection directly in @manager

redpajama_set_name: RedPajamaStackExchange


text:
Q: android modern development: how can I understand user did not change any data in a screen? I built a fragment, using jetpack compose for adding views on screen and state and view model classes for saving state.
first time when I navigate to this fragment, fetch API is called and If I have any value on this API, I filled text fields with them. It is possible that the API is empty and do not return any value.
Users can enter any data on this text fields or can ignore them because filling the text fields is optional and when he/she clicks on submit button; the data is saved in server by calling save API and shows a successful message that data is saved.
my question is that when user navigates to this fragment and does not enter or change any value,
when clicks on submit button, I do not want to show that toast.
how can I handle it? thanks.

A: First you will need to create a data class to hold the values for your screen as a mutable state with a default value.
data class SampleState(
    val isLoading: Boolean = true,
    val someText1: String = "",
    val someText2: String = ""
)

It is also necessary to create a sealed class with the possible screen actions, such as changing someText1 and someText2 and also the click of a button.
sealed class SampleAction {
    object TestButton : SampleAction()
    data class ChangeSomeText1(val text1: String) : SampleAction()
    data class ChangeSomeText2(val text2: String) : SampleAction()
}

And finally, a sealed class to contain the possible one-time-event that can be triggered through some action, like after clicking on the button with the fields properly filled in.
sealed class SampleChannel {
    object ValidFields : SampleChannel()
}

The view model will be responsible for managing all the logic:
@HiltViewModel
class SampleViewModel @Inject constructor() : ViewModel() {
    var state by mutableStateOf(value = SampleState())
        private set

    private val _channel = Channel<SampleChannel>()
    val channel = _channel.receiveAsFlow()

    init {
        loadInitialFakeData()
    }

    fun onAction(action: SampleAction) {
        when (action) {
            is SampleAction.TestButton -> testButtonClicked()
            is SampleAction.ChangeSomeText1 -> state = state.copy(someText1 = action.text1)
            is SampleAction.ChangeSomeText2 -> state = state.copy(someText2 = action.text2)
        }
    }

    private fun loadInitialFakeData() = viewModelScope.launch {
        delay(timeMillis = 1000)

        if (Random.nextBoolean()) state = state.copy(
            someText1 = "fake text 1 from api",
            someText2 = "fake text 2 from api"
        )

        state = state.copy(isLoading = false)
    }

    private fun testButtonClicked() {
        val hasBlankField = listOf(
            state.someText1,
            state.someText2
        ).any { string ->
            string.isBlank()
        }

        if (hasBlankField) return

        viewModelScope.launch {
            _channel.send(SampleChannel.ValidFields)
        }
    }
}

In this case there is a loadInitialFakeData function that is executed as soon as the view model is instantiated, which simulates a delay only for testing purposes and according to a random boolean assigns or not values in the state class.
There is also a function testButtonClicked that will do the logic if any of the fields is empty, if any of them is empty nothing happens (I left it that way so as not to extend the code too much) and if it is not empty we notify the channel with the ValidFields.
The only public function in the view model is the onAction, which is responsible for receiving actions through the composable screen.
Now on the composable screen we can do it like this:
@Composable
fun SampleScreen(
    viewModel: SampleViewModel = hiltViewModel()
) {
    val state = viewModel.state
    val scaffoldState = rememberScaffoldState()

    LaunchedEffect(key1 = Unit) {
        viewModel.channel.collect { channel ->
            when (channel) {
                SampleChannel.ValidFields -> {
                    scaffoldState.snackbarHostState.showSnackbar(
                        message = "all right!"
                    )
                }
            }
        }
    }

    Scaffold(
        modifier = Modifier.fillMaxSize(),
        scaffoldState = scaffoldState
    ) {
        Column(modifier = Modifier.fillMaxSize()) {
            ComposeLoading(isLoading = state.isLoading)

            ComposeForm(
                changeSomeText1 = {
                    viewModel.onAction(SampleAction.ChangeSomeText1(it))
                },
                changeSomeText2 = {
                    viewModel.onAction(SampleAction.ChangeSomeText2(it))
                },
                testButtonClick = {
                    viewModel.onAction(SampleAction.TestButton)
                },
                state = state
            )
        }
    }
}

@Composable
private fun ComposeLoading(
    isLoading: Boolean
) = AnimatedVisibility(
    modifier = Modifier.fillMaxWidth(),
    visible = isLoading,
    enter = expandVertically(animationSpec = tween()),
    exit = shrinkVertically(animationSpec = tween())
) {
    Column(
        modifier = Modifier.fillMaxWidth(),
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        LinearProgressIndicator(modifier = Modifier.fillMaxWidth())

        Spacer(modifier = Modifier.height(height = 16.dp))

        Text(
            text = "loading...",
            color = MaterialTheme.colors.onBackground,
            style = MaterialTheme.typography.body2
        )

        Spacer(modifier = Modifier.height(height = 16.dp))
    }
}

@Composable
private fun ComposeForm(
    changeSomeText1: (String) -> Unit,
    changeSomeText2: (String) -> Unit,
    testButtonClick: () -> Unit,
    state: SampleState
) = Column(
    modifier = Modifier
        .fillMaxWidth()
        .padding(16.dp)
) {
    ComposeSimpleTextField(
        value = state.someText1,
        onValueChange = {
            changeSomeText1(it)
        },
        label = "text field 1"
    )

    Spacer(modifier = Modifier.height(height = 16.dp))

    ComposeSimpleTextField(
        value = state.someText2,
        onValueChange = {
            changeSomeText2(it)
        },
        label = "text field 2"
    )

    Spacer(modifier = Modifier.height(height = 16.dp))

    Button(
        modifier = Modifier.align(alignment = Alignment.End),
        onClick = testButtonClick
    ) {
        Text(text = "Test Button")
    }
}

@Composable
private fun ComposeSimpleTextField(
    value: String,
    onValueChange: (String) -> Unit,
    label: String
) = TextField(
    modifier = Modifier.fillMaxWidth(),
    value = value,
    onValueChange = { onValueChange(it) },
    label = {
        Text(text = label)
    }
)

The main thing here is the LaunchedEffect to collect all possible events from the SampleChannel (on this example there is only one) and the calls to screen events when the text of some field is changed or when the button is clicked... The rest is just a compose boilerplate that doesn't matter much for the main logic.
Note: I used Hilt for dependency injection in this example, so I had access to @HiltViewModel and hiltViewModel()
implementation 'com.google.dagger:hilt-android:2.42'
kapt 'com.google.dagger:hilt-android-compiler:2.42'
implementation 'androidx.hilt:hilt-navigation-compose:1.0.0'


text:
Q: User registration form without Entity Framework [HttpPost]
public ActionResult Create(UserModel userModel)
{

    using (SqlConnection sqlCon= new SqlConnection(connectionString))
    {
        sqlCon.Open();

        String query = "INSERT INTO User VALUES(@UserName, @UserPassword, @UserAddress)";

        SqlCommand sqlCmd = new SqlCommand(query,sqlCon);

        sqlCmd.Parameters.AddWithValue("@UserName",userModel.username);
        sqlCmd.Parameters.AddWithValue("@UserPassword", userModel.userpassword);
        sqlCmd.Parameters.AddWithValue("@UserAddress", userModel.useraddress);

        sqlCmd.ExecuteNonQuery();
    }

    return RedirectToAction("Index");
}

I'm learning C#. I tried to code CURD operations. In this code there is is a Open() method. I want to know why it used and explain line by line what is code  flow.

A: If you are performing any database operation from external applications. You need to establish a connection between the database and your application.
To establish a connection between database and your application you must require database "ConnectionString" this connection string is mandatory for performing CRUD operation from any external application.
SqlConnection sqlCon= new SqlConnection(connectionString);

To establish a database connection we are using
sqlCon.Open();

It is better to mention your connection string in web.config file. Because it is highly secured.

A: In your code Open() method is use for database connection open. You can refer https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.open(v=vs.110).aspx Microsoft document.
 sqlCon.Open();

To open database connection
    String query = "INSERT INTO User VALUES(@UserName,@UserPassword,@UserAddress)";

Database query
    SqlCommand sqlCmd = new SqlCommand(query,sqlCon);

To create database command
    sqlCmd.Parameters.AddWithValue("@UserName",userModel.username);
    sqlCmd.Parameters.AddWithValue("@UserPassword", userModel.userpassword);
    sqlCmd.Parameters.AddWithValue("@UserAddress", userModel.useraddress);

These are the parameters to pass with command
    sqlCmd.ExecuteNonQuery();

This will execute your command to open database


text:
Q: Aspectj pointcut expression I am having trouble with building aspectJ expression. I would like to run my advice when any of "QueryUtil" method is invoked from class "Report".
For example: if we invoke QueryUtil.*() inside of Report.*() -> Advice is executed.
If we invoke QueryUtil.*() from AnyOtherClass.* -> Advice is not executed.
I was thinking of cflow expression but still did not find a way to write it. I was thinking of something like this:
<pointcut name="scope"
    expression="( cflow(call(* ext.demo.Report.\*(..))) && execution(* ext.demo.QueryUtil.*(..)))"/>

Could anyone help me with that?

A: The only odd thing in your pointcut is the rogue '\' I see ahead of the * in the cflow pointcut component. I'd also suggest using execution() if you can rather than call() (there are typically lots of call sites to instrument but only one execution site).
cflow(execution(* ext.demo.Report.*(..))) && execution(* ext.demo.QueryUtil.*(..))

If it isn't behaving for you then break it down to work out which piece is at fault. Does execution(* ext.demo.QueryUtil.*(..)) match everything you expect? Does execution(* ext.demo.Report.*(..)) match everything you expect? (I'd use -showWeaveInfo to check)


text:
Q: Stubed Unit of Work method with Moq doesn't return the expected integer I have a project created using Asp.Net Core, but I have a problem with unit testing one part of my controller's action, I use xUnit.net(2.2.0-beta2-build3300) for testing and Moq(4.6.25-alpha) for mocking, and FluentAssertions(4.13.0) and GenFu(1.1.1) to help me with my tests, I have a Unit of Work class (note that I cut it down to what's relevant to my question):
public class UnitOfWork : IUnitOfWork
{

    private readonly WebForDbContext _context;

    public UnitOfWork(WebForDbContext context)
    {
        _context = context;
    }

     private IContactRepository _contactRepository;

     public IContactRepository ContactRepository
    {
        get
        {

            if (this._contactRepository == null)
            {
                this._contactRepository = new ContactRepository(_context);
            }
            return _contactRepository;
        }
    }
}

In my ContactRepository I have:
public class ContactRepository:IContactRepository
{
    private WebForDbContext _context;

    public ContactRepository(WebForDbContext context)
    {
        _context = context;
    }

    public Task<int> AddNewContactAsync(Contact contact)
    {
        _context.Contacts.Add(contact);
        return _context.SaveChangesAsync();
    }
}

I inject the Unit of Work to my controller, my action:
 [HttpPost]
 [ValidateAntiForgeryToken]
 public async Task<IActionResult> Create(ContactViewModel contactViewModel)
  {
       var contactWioutJavascript = _webForMapper.ContactViewModelToContact(contactViewModel);

       int addContactResultWioutJavascript = await _uw.ContactRepository.AddNewContactAsync(contactWioutJavascript);

        if (addContactResultWioutJavascript > 0)
        {
            return View("Success");
        }
  }

What I want to do is to stub my AddNewContactAsync method to return an integer bigger than 0 (10 in this case), to inter the if clause, and test to see if the correct view is returned, my test class:
public class ContactControllerTests
{

 private Mock<IUnitOfWork> _uw;
 private Mock<IWebForMapper> _webForMapper;

    public ContactControllerTests()
    {
        _uw = new Mock<IUnitOfWork>();

        _webForMapper = new Mock<IWebForMapper>();
    }

   [Fact]
    public async Task Create_SouldReturnSuccessView_IfNewContactAdded()
    {
        var contactViewModel = A.New<ContactViewModel>();

        _webForMapper.Setup(s => s.ContactViewModelToContact(contactViewModel)).Returns(A.New<Contact>());

        _uw.Setup(u => u.ContactRepository.AddNewContactAsync(A.New<Contact>())).ReturnsAsync(10);

        var sut = new ContactController(_uw.Object, _webForMapper.Object);

        var result = (ViewResult)await sut.Create(contactViewModel);

        result.ViewName.Should().Be("Success");
    }
 }

But the method AddNewContactAsync returns 0, and my test doesn't enter the if condition that leads to return View("Success"), I know that the problem doesn't have to do with ReturnAsync because I've used it with other async methods and it works, also _webForMapper is stubbed correctly and map the view model to my domain model and contactWioutJavascript is populated with value, but when I debug the test and reach the addContactResultWioutJavascript line, it returns 0, no matter what I do.
The things I did, but didn't work:
I mocked the ContactRepository, and tried to stub that instead:
_contactRepository.Setup(c => c.AddNewContactAsync(A.New<Contact>())).ReturnsAsync(10);

_uw.SetupGet<IContactRepository>(u => u.ContactRepository).Returns(_contactRepository.Object);

I also found other questions:
Moq Unit of Work
how to moq simple add function that uses Unit of Work and Repository Pattern
Mocking UnitOfWork with Moq and EF 4.1
But none of them helped, I'd appreciate any help.

A: You are almost there.  Two things:

*

*You do need to setup the ContactRepository property as Moq doesn't support "chaining" of setups.

*Also, you need to use It.IsAny<>() instead of A.New<>():
_contactRepository.Setup(c => c.AddNewContactAsync(It.IsAny<Contact>())).ReturnsAsync(10);

This says "match any Contact that is passed in".  When you used A.New<>(), you were saying "match the Contact instance that I just created with A.New<>().  In effect, that will never match anything since you didn't save or use the return value of A.New<>().


text:
Q: Text View and Image view not showing in android studio layout when I use a custom toolbar with its theme set using the materials library I made an android activity in which I had a custom toolbar (which had theme set to one of the themes of the material library) .However , I am facing serious issues as when I try to add an image view and a text view to my layout , I cannot see them in my layout and on running the app,the app crashes . Can someone recommend a solution to this problem?
Here is the snapshot of my code along with the layout
Here is the XML code
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".AddHappyPlace">
        <LinearLayout
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
        <com.google.android.material.appbar.MaterialToolbar
            android:id="@+id/toolbarAdd"
            android:layout_width="match_parent"
            android:background="@color/newColorPrimaryDark"
            android:theme="@style/CustomNoActionBarTheme"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            android:layout_height="?attr/actionBarSize" />
                <com.google.android.material.textfield.TextInputLayout
                    android:layout_width="match_parent"
                    style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
                    android:layout_marginTop="20dp"
                    android:layout_height="wrap_content">
                <com.google.android.material.textfield.TextInputEditText
              android:layout_width="match_parent" android:id="@+id/etTitle"
              android:hint="Title" android:textColorHint="#d3d3d3"
              android:layout_height="wrap_content"/>
                </com.google.android.material.textfield.TextInputLayout>
                <com.google.android.material.textfield.TextInputLayout
                    android:layout_width="match_parent"
                    style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
                    android:layout_marginTop="15dp"
                    android:layout_height="wrap_content">
                <com.google.android.material.textfield.TextInputEditText
                    android:layout_width="match_parent"
                    android:id="@+id/etDetails"
                    android:hint="Details"
                    android:textColorHint="#d3d3d3"
                    android:textColor="@color/black"
                    android:layout_height="wrap_content"/>
                </com.google.android.material.textfield.TextInputLayout>
                <com.google.android.material.textfield.TextInputLayout
                    android:layout_width="match_parent"
                    style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
                    android:layout_marginTop="20dp"
                    android:layout_height="wrap_content">
                        <com.google.android.material.textfield.TextInputEditText
                            android:layout_width="match_parent" android:id="@+id/etLocation"
                            android:hint="Location" android:textColorHint="#d3d3d3"
                            android:layout_height="wrap_content"/>
                </com.google.android.material.textfield.TextInputLayout>
                <com.google.android.material.textfield.TextInputLayout
                    android:layout_width="match_parent"
                    style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
                    android:layout_marginTop="20dp"
                    android:layout_height="wrap_content">

                        <com.google.android.material.textfield.TextInputEditText
                            android:id="@+id/etDate"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:hint="Date"
                            android:textColorHint="#d3d3d3" />
                </com.google.android.material.textfield.TextInputLayout>
        </LinearLayout>
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">
                <androidx.appcompat.widget.AppCompatImageView
                    android:layout_margin="10dp"
                    android:id="@+id/imgView"
                    android:layout_weight="1"
                    android:layout_width="0dp"
                    android:layout_height="250dp"/>
                <TextView
                    android:id="@+id/tvAddImage"
                    android:gravity="center"
                    android:layout_margin="10dp"
                    android:textSize="25sp"
                    android:layout_weight="1"
                    android:layout_width="0dp"
                    android:text="ADD IMAGE"
                    android:layout_height="250dp"/>
        </LinearLayout>
</ScrollView>

Here is what the layout is showing
enter image description here

A: The problem is you are hosting multiple child inside scrollview,
Scrollview can host only single child. Please check below code for reference
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".AddHappyPlace">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <com.google.android.material.appbar.MaterialToolbar
        android:id="@+id/toolbarAdd"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="@color/newColorPrimaryDark"
        android:theme="@style/CustomNoActionBarTheme"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <com.google.android.material.textfield.TextInputLayout
        style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp">

        <com.google.android.material.textfield.TextInputEditText
            android:id="@+id/etTitle"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Title"
            android:textColorHint="#d3d3d3" />
    </com.google.android.material.textfield.TextInputLayout>

    <com.google.android.material.textfield.TextInputLayout
        style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="15dp">

        <com.google.android.material.textfield.TextInputEditText
            android:id="@+id/etDetails"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Details"
            android:textColor="@color/black"
            android:textColorHint="#d3d3d3" />
    </com.google.android.material.textfield.TextInputLayout>

    <com.google.android.material.textfield.TextInputLayout
        style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp">

        <com.google.android.material.textfield.TextInputEditText
            android:id="@+id/etLocation"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Location"
            android:textColorHint="#d3d3d3" />
    </com.google.android.material.textfield.TextInputLayout>

    <com.google.android.material.textfield.TextInputLayout
        style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp">

        <com.google.android.material.textfield.TextInputEditText
            android:id="@+id/etDate"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Date"
            android:textColorHint="#d3d3d3" />
    </com.google.android.material.textfield.TextInputLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <androidx.appcompat.widget.AppCompatImageView
            android:id="@+id/imgView"
            android:layout_width="0dp"
            android:layout_height="250dp"
            android:layout_margin="10dp"
            android:layout_weight="1" />

        <TextView
            android:id="@+id/tvAddImage"
            android:layout_width="0dp"
            android:layout_height="250dp"
            android:layout_margin="10dp"
            android:layout_weight="1"
            android:gravity="center"
            android:text="ADD IMAGE"
            android:textSize="25sp" />
    </LinearLayout>
</LinearLayout>
</ScrollView>


text:
Q: Dispatching with Catalyst in FastCGI under Apache I am teaching myself Catalyst. I would very much like to organise my application with multiple controllers and multiple actions in each, and maybe try chains, but I am not sure how to make this work under my specific settings.
I have full control of the computer that runs the external FastCGI server, but I have no access whatsoever to the computer that runs Apache. The only way I can "configure" the server is by posting a support ticket, asking "Would you guys please try to add those couple lines to the Apache config?", and hoping for the best.
So far I have asked them to try this configuration:
Alias /myapp/ /tmp/myapp.fcgi
FastCgiExternalServer /tmp/myapp.fcgi -host myserver:3010

But of course, this works if someone connects to http://theirserver/myapp, but I cannot use http://theirserver/myapp/controller/action/etc with this configuration.
So here's my multipart question:

*

*Is there an easy way to configure Apache in such a way that I would be able to use a better dispatch, and maybe even chains — i.e. not have one Alias for each possible controller–action?

*In case that can't be done, that would mean only the query is available. What are best practices to dispatch a request in Catalyst under those circumstances?

A: I have found what is to me an acceptable solution, but I'm still looking for best practices in Apache configuration or Catalyst-as-external-FastCGI dispatch. By all means, answer the question if you know of a better way!
The module Catalyst::ActionRole::QueryParameter makes it possible to handle dispatching of requests based on query parameters. I have been able to use it to build a controller that looks like this:
package MyApp::Controller::Root;

use Moose;
use namespace::autoclean;

BEGIN { extends 'Catalyst::Controller::ActionRole'; }

__PACKAGE__->config(
    namespace    => '',
    action_roles => ['QueryParameter'],
);

sub default :Path {
  my ( $self, $c ) = @_;
  $c->response->body('no action specified!');
}

sub login :Path :QueryParam('action:eqlogin') {
    my ( $self, $c ) = @_;
    $c->response->body('login')
}

sub logout :Path :QueryParam('action:eqlogout') {
    my ( $self, $c ) = @_;
    $c->response->body('logout')
}

__PACKAGE__->meta->make_immutable;

1;

It is even possible to use some sort of chains, as shown in the provided example application, although that doesn't seem nowhere as satisfactory as what I have read about in the manual.
At the time of writing this, string comparison doesn't work in this module, so using this solution probably means applying a small patch to QueryParameter.pm, as suggested in this bug report.


text:
Q: How to get all translation key in next-i18next Question Summary
How do most users add the translation key to the json file when translating?
Manually...?
What do I want
I'm trying to get all the translation keys used on all the pages.
Also, is it possible to get the untranslated translation keys automatically?

A: Have you tried to use some extraction tools, for example https://github.com/i18next/i18next-parser or https://github.com/i18next/i18next-scanner?


text:
Q: How do I connect to a web app running on an image on docker hub? I am learning docker, just getting my feet wet... I begin begging your pardon since I will probably using terminology badly :-(
I have successfully built my first container and run it locally.
The container image is a node.js + express web app.
Locally I run my image this way:
docker run -p 80:3000 myname/myimage

If I point my browser to the local server IP
http://192.168.1.123:80/

I access my app in all of its glory.
Then, I push it to docker hub with this command:
docker push myname/myimage

So far so good. The question is: am I supposed to be able to run my app from docker cloud, already, or should I push it to AWS, for example?

A: By executing docker push myname/myimage you only sent your image to docker-hub.
This image can then be run to create a container; but as is, it is not running.
You effectively will have to run it on any machine or service in order to access your app.
concerning the terminology:

*

*you build an image, not a container

*you push (or pull) an image to (from) docker-hub

*you run a container from an image


text:
Q: Why is there no anomaly when particle mechanics is quantized? We know that if one or more symmetries of the action of a classical field theory is violated in its quantized version the corresponding quantum theory is said to have anomaly.

*

*Is this a sole feature of quantization of a field theory? If yes, why is it that anomalies appear only after quantizing a field theory but non in ordinary non-relativistic quantum mechanics?

In field theory, if under an arbitrary symmetry transformation $\phi\rightarrow \phi^\prime=\phi+\delta\phi$, the action $S[\phi]$ is left invariant, we have a symmetry in classical field theory. But we have a symmetry of quantum field theory, if the transformation leaves the path-integral $\int\mathcal{D}\phi \exp(\frac{i}{\hbar}S[\phi])$ invariant. Therefore, even if $S(\phi)$ is invariant but the measure is not, we can have an anomaly.

*Does it mean that the path-integral measure $\int \mathcal{D}q(t) \exp(\frac{i}{\hbar}S[q(t)])$ in ordinary quantum mechanics always remains invariant under any classical symmetry $q\to q^\prime= q+\delta q$?

A: Anomalies are not particular to quantum field theory, or even to quantum theory. An anomaly is an obstruction to representing some physically relevant group/algebra, often a symmetry group or an algebra of observables, on the state space, and means that your state space will carry not a representation of the symmetry group itself but of an extension. This notion is explained at length in this excellent answer by David Bar Moshe.
Whether the group/algebra that is obstructed is the classical Galilean group that needs the introduction of mass as a "central charge" to become the Bargmann group, the $\mathrm{SO}(3)$ of a particle as in Everett You's answer (which is a special case of a more general link between WZW models and anomalies) that needs the passage to its universal cover $\mathrm{SU}(2)$ on the spin-1/2 which is a central extension by $\mathbb{Z}_2$ or the algebra of fermionic non-Abelian charge densitites that is extended to the Mickelsson-Faddeev algebra (see again the answer by David) by the anomaly term is immaterial - it's all the same principle.
The fundamental character of an anomaly is not a non-invariance of the path integral measure, that's just a particular way to derive it.

A: Quantum mechanics can also become anomalous. An example is a charged particle moving in a uniform magnetic field. On the classical level, the system is translation invariant in both x- and y-direction. Because the magnetic field is uniform, all (gauge-invariant) measurement will yield the same result at any point of the space, hence the translation symmetry is preserved. But once the system is quantized, the momentum $p_x$ and $p_y$ no longer commute with each other, i.e. $$[p_x,p_y]=\mathrm{i}\hbar B.$$ The non-commutativity is exactly proportional to $\hbar$, implying that this is indeed a quantum effect. In this case, if one chooses to preserve the translation along x, the translation along y must be broken, as $p_x$ and $p_y$ become incompatible observables. This effect is manifested in the wave function under the Landau gauge. Therefore the system becomes anomalous under translation.
Another closely related example is a charged particle moving on a sphere with a magnetic monopole (Dirac monopole) inside the sphere. Let the unit vector $\boldsymbol{n}=(n_1,n_2,n_3)$ be the coordinate that parameterize the position of the particle on the sphere ($\boldsymbol{n}^2=1$). The classical action can be written as a Wess-Zumino-Witten model
$$S[\boldsymbol{n}(t)]=\frac{1}{4\pi}\int\mathrm{d}t\int_0^1\mathrm{d}u\;\boldsymbol{n}\cdot\partial_t\boldsymbol{n}\times\partial_u\boldsymbol{n}.$$
The action is invariant under the SO(3) transformation of $\boldsymbol{n}$. But after quantization, the eigenstates are spin-1/2 objects, which are not linear representations of the SO(3) symmetry group. So the system has an SO(3) anomaly.

A: In reference to the first reply: Alex was correct. This is not a quantum effect, since it also arises in the classical limit of the quantized Poisson bracket, which is defined as the commutator divided by iħ. The classical form of "does not commute" is that "the Hamiltonian fields associated with the quantities in question do not commute". Here, the Hamiltonian fields are X = {p,⋯}, and what we find is that
    [X₁,X₂] = X₁X₂ - X₂X₁ = {p₁,{p₂,⋯}} - {p₂,{p₁,⋯}} = {{p₁,p₂},⋯} = {B³,⋯} ≠ 0.

The "Hamilonian fields do not commute" criterion is also the quantum form of "does not commute", since the quantized Poisson brackets are, indeed, Poisson brackets over a suitably-defined Poisson manifold, and their Hamiltonian fields provide equivalent descriptions of the operators, themselves. So, the condition can be used uniformly across the board, independent of the classical versus quantum paradigm divide.
A "quantum effect" is what arises as a quantum correction, e.g. Q({p₁,p₂}) versus {Q(p₁),Q(p₂)}, where the second bracket is the quantized Poisson bracket; and where Q() denotes the quantization operation.
This follows the treatment given in Landsman (Mathematical Topics Between Classical and Quantum Mechanics (1998), Part II "Quantization and the Classical Limit"). Here, the difference Q({p₁,p₂}) - {Q(p₁),Q(p₂)} = Q(B³) - Q(B³) is 0. Discussion of projective Hilbert spaces as Poisson manifolds (actually symplectic manifolds) may be found in section I.2 in Landsman.
Anomalies are deficits that arise from an attempt to quantize a classical symmetry transform, which spoil the symmetry transform at the quantum level. Several examples, pertaining to the original question, are illustrated here https://www.physics.ncsu.edu/ntg/leegroup/library/Anomaly_QM.pdf and discussion of anomalies, in greater depth, may be found here https://en.wikipedia.org/wiki/Anomaly_%28physics%29


text:
Q: Convert progressive JPEG to baseline JPEG I'm getting a user profile image from Azure AD using below graph api. But when i'm trying to hit the api using POSTMAN tool its giving me a PJPEG image and then i'm not able to get the actual image. So is there any way i can get the jpeg image or convert that pjpeg bytes to base64 and then to image.
Please help.
Graph API.

A: If you want to update user photo with postman, please refer to the following steps

*

*Register Azure AD application

*Configure API permissions

*Get access token in Postman

*update photo. My test pjpeg file
PUT PUT https://graph.microsoft.com/v1.0/me/photo/$value
Content-type: image/pjpeg

Body: Binary data for the image

*Check

GET https://graph.microsoft.com/v1.0/me/photo/$value


text:
Q: Multiple tables not getting created in sqllite3 + iOS I am developing an iOS application in objective-c and i am using sqllite3 as local DB to hold some data.
There are multiple tables that I need to use but it not happening. If I try to create multiple tables in same DB {db path as DB1} then the second table is not created.
But if I try to create different tables in different db path, then it functions normally. ex : db path as DB1 for table T1 , DB2 for table T2 and so on ....
I am not able to understand Why is this happening!
Here is the code :
Statement to create table :
if(![[NSFileManager defaultManager] fileExistsAtPath:[self getEventDbFilePath]]) //if the file does not exist
    {
        [self createTable:[self getEventDbFilePath]];
    }

db path function :
-(NSString *) getUserInfoDbFilePath
{
    NSString * docsPath= NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES)[0];
    NSLog(@"docpath=%@",docsPath);

    return [docsPath stringByAppendingPathComponent:@"userinfo.db"];

}

create table
-(int) createUserInfoTable:(NSString*) filePath
   {
       sqlite3* db = NULL;
       int rc=0;

       rc = sqlite3_open_v2([filePath cStringUsingEncoding:NSUTF8StringEncoding], &db, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL);
       if (SQLITE_OK != rc)
       {
           sqlite3_close(db);
           NSLog(@"Failed to open db connection");
       }
       else
       {
           char * query ="CREATE TABLE IF NOT EXISTS userinfo (id INTEGER PRIMARY KEY AUTOINCREMENT, selfuserid  TEXT, profilepic TEXT, username TEXT, gender TEXT, profilelink TEXT )";
           char * errMsg;
           rc = sqlite3_exec(db, query,NULL,NULL,&errMsg);

           if(SQLITE_OK != rc)
           {
               NSLog(@"Failed to create table rc:%d, msg=%s",rc,errMsg);
           }

           sqlite3_close(db);
       }

       return rc;

   }

If I create a new table with similar function as above and different table name, with same db path, the second table will not be created.
Now for second table, if I provide a new path, the table gets created in thew db path.
Any suggestions would be great.


text:
Q: Measuring the amount of total influence between variables? I have a group of people with a series of yes/no questuins about preferences in various topics. The thing is they could see each other answers and change theirs hence might be influenced by a common answer. I know that non of them knew each other beforehand so I can asuuse no one is particularly biased by a spesifuc different instance
To out it more formally I have a random sample which I know the different sample points might not independent from each other. I want to measure or at least talk about the amount by which each point is influenced by all the rest. More formally - how each marginal distribution changes (say, in KL-divergence or Total-Variance distance) if we reveal/condition upon all the rest of the sample. It there some kind of notion to this type of dependency? Or is there anything close which I can relate to this quantity?


text:
Q: NaN error while summing in Java I am working on project in the university and I am facing a serious problem. In fact, my code is to sum over 2 variables, in order to do some staff after. As I will show below, the list is not empty, and the code extracts the values from the list, but while but it doesn't increment the counter. I will apreciate if someone could give me some help.
        //CHeck if we have already imported data, if yes we use it, unless we import
        if ((this.stockHistory != null) && (!(this.stockHistory.isEmpty())))
          {
            evolution = this.stockHistory;

          }
        else
          {
            evolution = getHostoricalData(cloned);
          }
        // Here I am sure the list ( evolution ) is not empty, in my case it has 63 elements
        double spot ;
        double sommeTendance = 0 ;
        double sommeVarianceQuotidienne = 0 ;
        for (int i=0;i<evolution.size()-1; i++)
            {
                double i1 =evolution.get(i+1) ;
                System.out.println(" i1 = " + i1);
                double i0 = evolution.get(i) ;
                System.out.println("i0 is " + i0);
                sommeTendance+= Math.log(i1/i0);
                System.out.println("tendance == " +sommeTendance);
                sommeVarianceQuotidienne += Math.pow(Math.log(i1/i0),2);
                System.out.println("variance daily  == " + sommeVarianceQuotidienne);
            }
        System.out.println("size == " + evolution.size());
        System.out.println("total tendance == " + sommeTendance);
        System.out.println("total daily variance == " + sommeVarianceQuotidienne);

And here is the last lines of the output
16:59:52,524 INFO  [stdout] (default task-62)  i1 = 51.619999
16:59:52,524 INFO  [stdout] (default task-62) i0 is 52.73
16:59:52,524 INFO  [stdout] (default task-62) tendance == NaN
16:59:52,524 INFO  [stdout] (default task-62) variance daily  == NaN
16:59:52,524 INFO  [stdout] (default task-62)  i1 = 53.330002
16:59:52,524 INFO  [stdout] (default task-62) i0 is 51.619999
16:59:52,525 INFO  [stdout] (default task-62) tendance == NaN
16:59:52,525 INFO  [stdout] (default task-62) variance daily  == NaN
16:59:52,525 INFO  [stdout] (default task-62) size == 63
16:59:52,525 INFO  [stdout] (default task-62) total tendance == NaN
16:59:52,525 INFO  [stdout] (default task-62) total daily variance == NaN

A: First, you need to understand what NaN stands for. Nan stands for Not a Number.
How you get NaN?

"Nan" is produced if a floating point operation has some input
  parameters that cause the operation to produce some undefined result.

What may cause NaN?

For example, 0.0 divided by 0.0 is arithmetically undefined. Finding
  out the square root of a negative number too is undefined.

Also,

All numeric operations with NaN as an operand produce NaN as a result.
  Reason behind this is that NaN is unordered, so a numeric comparison
  operation involving one or two NaNs returns false.

Since we fully understand NaN, now let's work our way around the solution now.

In your case the NaN is produced by Math.log(i1/i0);
Logarithmic functions are not defined on  (-oo,0]. Hence every negative number entered as parameter Math.log(i1/i0); will return a NaN as result in java.
What you can do?
-> Build a tiny test on i1/i0 before passing it as parameter in Math.log()

Suggestion:
for (int i=0;i<evolution.size()-1; i++)
    {
        double i1 =evolution.get(i+1) ;
        double i0 = evolution.get(i) ;
        if (i1/i0>0)
        {
            //you are good
            sommeTendance+= Math.log(i1/i0);
            sommeVarianceQuotidienne += Math.pow(Math.log(i1/i0),2);
        }
        else
        {
            //you are not good, the number will yield an undefined result
            //do something else... like displaying an error....?
            System.out.println("Math.log will yield into an undefined result. Please check your input");
        }
    }

Useful links:

*

*https://www.avocado.com.au/resources/tech-tips/java-double-nan-weirdness/

*https://www.geeksforgeeks.org/nan-not-number-java/
Hope this helps.


text:
Q: read data from one file(.xlsx), write into another I'm trying to read all rows and column's data from input.xlsx file , and insert into another file output.xlsx using python script (iterate through for loop).
Problem:
Using "for loop" in this script able to read data in each row and column but fails to write into output file (output.xlsx)
Here's the code I used:
    response = requests.get(url, params=params, auth=(username, password))
    with open('/Downloads/input.xlsx', 'wb') as f:
            f.write(response.content)

            workbook = load_workbook("/Downloads")

            # get all worksheets
            all_sheets = workbook.sheetnames

            first_sheet = all_sheets[0]

            # get a worksheet by its name
            worksheet = workbook[first_sheet]
            first_row = True
            for val in worksheet.values:
                if first_row:
                    # skip the first row: header row.
                    first_row = False
                    continue

                workbook = xlsxwriter.Workbook('output.xlsx')

                new_worksheet = workbook.add_worksheet()

                new_worksheet.write('A', val[0])
                new_worksheet.write('B', val[1])
                new_worksheet.write('C', val[2])

                workbook.close()

The Data in input.xlsx looks like the below:
**Student Name | Course | Rank**
Tony             ECE      4
Bob              CSE.     1
Chris            MECH     7
David            CSE      5
Krishna          CSE      2


text:
Q: Возможно ли анимировать смену состояния? Делаю компонент по заполнению шкалы (код далеко не идеален, не до этого пока что):
App.js
   import React from "react";
import "./styles.css";

export default function App() {
  const [chanels, setChanels] = React.useState([
    {
      name: "chanel1",
      color: "blue",
      memoryPercent: 30
    },{
      name: "chanel2",
      color: "grey",
      memoryPercent: 70
    }]
  )
  return (

        {chanels.map(chanel =>
          <div
          style={{
            background: chanel.color,
            width: `${chanel.memoryPecent}%`
          }}>
            {chanel.name}

          )}

      <button>+</button>
      chanel1
      <button>-</button>
      <button>+</button>
      chanel2
      <button>-</button>

  );
}

style.css:
.App {
  font-family: sans-serif;
  text-align: center;
}
.scale {
  width: 100%;
  background: red;
  height: 20px;
  display: flex;
}

Суть следующая:
По нажатию на +/- происходит смена диапазона у нужного канала и данные о смененном диапазоне отправляются на сервер. На сервере происходит перерасчет занимаемого диапазона у каналов и обновленный объект оправляется обратно на клиент.
Вопрос:
Реально ли анимировать изменение ширины каждого канала в зависимости от данных которые пришли с сервера? Например:
Сейчас memoryPercent у chanel1 = 30%, после того как я отправил запрос на увеличение диапазона у chanel1 - я получил с сервера обновленный объект: memoryPercent у chanel1 стал равен 40, а у chanel2 = 60.
Или разумнее анимировать это все с помощью данных которые уже есть в state?

A: Мда, вопрос писал дольше чем искал решение.
transition: "all 1s" в style добавил.


text:
Q: Small o-notation in probability [Raab 1998 proof] I need a clarification about the notation used in the main theorem of the proof "Balls into Bins" - A Simple and Tight Analysis
The theorem states that:
Let $M$ be the random variable that counts the maximum number of balls into any bin, if we throw $m$ balls independently and uniformly at random into $n$ bins. Then $Pr[M > k_\alpha] = o(1)$ if $\alpha > 1$ and $Pr[M > k_\alpha] = 1 - o(1)$ if $ 0 < \alpha < 1 $, where
$k_\alpha = \frac{m}{n} + \sqrt{\frac{2m \log_n}{n}(1 - \frac{1}{\alpha}\frac{log^{(2)} n}{2 \log n})}$, if $ m >> n (log n)^3$
I skipped the result for other cases of m because I want to ask the meaning of notations. I come from a Comp Sci background. I don't understand about the interpretation of using the small-o notation in probability: $Pr[M > k_\alpha] = o(1)$.
I also quickly checked the wikipedia https://en.wikipedia.org/wiki/Big_O_in_probability_notation. But it does not help. They are walking about a set of Random Variables. Is the "Balls into Bins" talking about a set when it said $M > k_\alpha$?
Thanks

A: Perhaps I can help shed some light.
Little-o notation is used to compare the behavior of two functions $f$, $g$ when inputs are arbitrarily large: it's  merely a tool used in the study of asymptotics.
In a non-probabalistic setting what we have is $$ f(n) = o(g(n)) \iff \lim_{n \to \infty} \frac{f(n)}{g(n)}=0 $$
which describes a situation where the function $f$ grows much much slower than the function $g$ as inputs approach infinity. An example: $x = o(x^2)$ since $\frac{x}{x^2} \to 0$ as $x \to \infty$.
As to your specific case: unfortunately their notation is a bit sloppy. What is presumed in the context of the problem is that we let the number of bins $n \to \infty$.
Define $M_n$ as a random variable representing the maximum number of balls in any bin when we have exactly $n$ bins. In the case when $\alpha>1$ and there are WAYY more balls than bins  i.e. $m >> n (\log n) ^3$ what we have is:
$$P(M_n > k_{\alpha}) = o(1)$$ which means that $$\lim_{n\to \infty} P(M_n > k_{\alpha}) =0$$ so there is a vanishing chance that we find a bin with more than $k_{\alpha}$ balls in as the number of bins approaches infinity.
The case where $\alpha <1$ and $m >> n (\log n )^3$ can be rewritten as $$1-P(M_n>k_{\alpha}) = P(M_n \leq k_{\alpha}) = o(1)$$
which means that we will almost certainly find a bin with at least $k_{\alpha}$ balls in it if we have arbitrarily many bins.
Your interpretation is then dependent on $\alpha$ and the definition of $k_{\alpha}$. Consider that the first term $\frac{m}{n}$ in $k_{\alpha}$ represents the expected number of balls in any given bin then interpret the square root business as a function of $\alpha$.


text:
Q: VBA to produce the same page "x" amount of times In Word, I've created a template for a payment coupon book. So far I've written some code to load an input box/user form upon opening the word file. The user inputs stuff like name, payment date, payment amount, etc. After hitting submit, the user input is automatically entered into the template in the appropriate fields. I'm using bookmarks to do this.
My last piece of the puzzle is this: I need it to produce however many coupons that the user defines in one of my input boxes. Each coupon would have the same information. The only difference is the coupon ID needs to auto-increment to be a unique ID.
Think of this like producing a virtual checkbook almost. Your name, address, etc is all the same. The check number is different. This program is essentially asking how many checks you want.
Also, if this would be easier in Excel or even creating a form in Adobe please let me know. This was the only way I knew how to do it.
Feel free to ask any questions. Hope this makes sense.
Code is as follows:
Private Sub Submit_Click()

Dim flName As Range
Set flName = ActiveDocument.Bookmarks("flName").Range

    flName.Text = Me.firstNameTxt.Value

Dim acctNumber As Range
Set acctNumber = ActiveDocument.Bookmarks("acctNumber").Range
    acctNumber.Text = Me.accountNumberTxt.Value

Dim trailerNumber As Range
Set trailerNumber = ActiveDocument.Bookmarks("trailerNumber").Range
    trailerNumber.Text = Me.trailerTxt.Value

Dim DueDate As Range
Set DueDate = ActiveDocument.Bookmarks("dueDate").Range
    DueDate.Text = Me.dueDateTxt.Value

Dim PaymentAmount As Range
Set PaymentAmount = ActiveDocument.Bookmarks("paymentAmount").Range
    PaymentAmount.Text = Me.paymentAmountTxt.Value

Unload Me

End Sub

A: A fairly common approach is to use a mailmerge, where you'd have an Excel worksheet as the data source and a Word mailmerge main document attached to that. The numbering column in Excel would perhaps have no more than single cell for the input of a number, and the cells on subsequent rows would simply increment that. When completing the merge, simply choose how many record to process. Your description suggests you might need an Excel workbook where you can keep a permanent record of the names, payment dates, payment amounts, coupon #s, etc., all of which can be processed as part of the mailmerge. For the basics, see: https://support.office.com/en-us/article/use-mail-merge-for-bulk-email-letters-labels-and-envelopes-f488ed5b-b849-4c11-9cff-932c49474705
For a variety of macro-based approaches for simple Word form replication, see:
http://www.msofficeforums.com/word-vba/12959-sequential-document-numbering.html#post34477
http://www.msofficeforums.com/word-vba/12641-sequential-print-numbering.html#post33829http://www.msofficeforums.com/word-vba/35106-printing-multiple-copies-docm-word-pdf-saving.html#post113655


text:
Q: Quickly detect if VM is running on Azure One way of detecting if a VM (in my case a Docker container running on a Linux VM) is running on Azure is to query the metadata service for some information using HTTP.
This trick works nicely on AWS and GCP where the query can be done using DNS names (instance-data.ec2.internal and metadata.google.internal) and thus the query will fail quickly when the DNS lookup is being done.
But for Azure I do not know of any DNS name for the metadata service, only its raw IP address (169.254.169.254) and the code has to wait for the request to time out instead which take much longer time.
One solution to this would be to find a DNS name for the Azure Metadata Service, but there might be other solutions to the problem as well.

A: "Check your /etc/resolv.conf. There's an Azure specific domain part you can query for."
The domain I found was: cloudapp.net
Check the domain you find against this list:

*

*https://learn.microsoft.com/en-us/azure/security/fundamentals/azure-domains
Thanks to @evilSnobu.


text:
Q: How to find non-overlapping triangles? There are at least a few non-overlapping triangles made by the lines in the following graphic, how would I isolate them?
pts = RandomReal[1, {7, 2, 2}];
g = Graphics[{InfiniteLine @@@ pts}, Frame -> True,
  PlotRange -> {{-1, 2}, {-1, 3}}]

Update:
Jason B gave a nice answer, but it needs it to work with both Line[] and InfiniteLine[], for which the triangles[] function below doesn't work:
SeedRandom[4430];
pts = RandomReal[1, {3, 2, 2}];
l = InfiniteLine @@@ pts; h =
 Line@{{{0, 0}, {0, 2}}, {{0, 1}, {1, 1}}, {{1, 0}, {1, 2}}};
lines = Join[l, {h}];
g = Graphics[{lines, LightBlue, Triangle /@ triangles[lines]},
  Frame -> True, PlotRange -> All, AspectRatio -> 1]

A: Borrowing from this answer,
triangles[lines:{__InfiniteLine}]:= Module[
    {lineSegments,vertices,edges,triangles},
    lineSegments = Flatten[
        Map[Function @ Partition[Sort @ #, 2, 1],
            Table[
                Flatten[
                    List@@@Map[RegionIntersection[Part[lines, n], #]&, Delete[lines, n]],
                    1
                ],
                {n, Length @ lines}
            ]
        ],
        1
    ];

   vertices = Flatten[lineSegments, 1] // DeleteDuplicates;
   edges = lineSegments /. MapIndexed[#1 -> First@#2 &, vertices];
   triangles = FindCycle[Graph[#1 \[UndirectedEdge] #2 & @@@ edges], {3}, All];
   triangles = triangles[[All,All,1]];
   vertices[[#]]&/@triangles
]

Plotting directly as
SeedRandom[4430];
pts = RandomReal[1, {7, 2, 2}];
lines = InfiniteLine @@@ pts;
g = Graphics[{lines, LightBlue, Triangle /@ triangles[lines]},
  Frame -> True, PlotRange -> All]


text:
Q: Formalizing arithmetic prroofs using Agda I am trying to proof some lemmas using agda, and to do so, I need to prove facts about natural numbers like:

*

*An even natural number m can be represented as 2*k where k is another natural number.

*if m^2 is even, then m is even.

*if 2 * n^2 = 4 * k^2 then n^2 = 2 * k^2 . .

*if 0 < m then 0 < m^2.

I do not know where to start to prove these facts. I am not sure if Agda has any predefined definitons that may help in that task.
Any help s highly appreciated.

A: Some imports first.
open import Relation.Binary.PropositionalEquality
open import Data.Nat
open import Data.Product
open import Data.Empty
open import Relation.Nullary
open ≡-Reasoning
open import Function
open import Algebra
open import Data.Nat.Properties
open CommutativeSemiring commutativeSemiring hiding (zero; _+_; _*_; sym; refl)

You can express evenness as a function or as an inductive type.
The difference is explained here: http://oxij.org/note/BrutalDepTypes/
It's introduction, so you really should read it, as well, as other introductions,
if you want to use agda. There are quite a few such texts.
Here is the definition of Even:
data Even : ℕ -> Set where
  ezero : Even 0
  esuc  : {n : ℕ} -> Even n -> Even (suc (suc n))

Then you need to define exponentiation.
infixr 8 _^_

_^_ : ℕ -> ℕ -> ℕ
n ^  0      = 1
n ^ (suc m) = n * n ^ m

But n ^ 2 reduces to n * (n * 1), which is unconvenient. So I'll be using this instead:
_^2 : ℕ -> ℕ
n ^2 = n * n

Auxiliary lemma
m+1+n≡1+m+n : ∀ m n → m + suc n ≡ suc (m + n)
m+1+n≡1+m+n zero    n = refl
m+1+n≡1+m+n (suc m) n = cong suc (m+1+n≡1+m+n m n)

Next statement reads just as your first fact.
as-2*k : {n : ℕ} -> Even n -> ∃ λ k -> n ≡ 2 * k
as-2*k  ezero    = 0 , refl
as-2*k (esuc en) with as-2*k en
...              | n , refl = {!!}

The type of the hole is Σ ℕ (λ k → suc (suc (n + (n + 0))) ≡ k + (k + 0)).
It's a reduced version of ∃ (λ k → suc (suc (n + (n + 0))) ≡ k + (k + 0)).
Obviously k should be equal suc n.
as-2*k : {n : ℕ} -> Even n -> ∃ λ k -> n ≡ 2 * k
as-2*k  ezero    = 0 , refl
as-2*k (esuc en) with as-2*k en
...              | n , refl = suc n , {!!}

Now the type of the hole is suc (suc (n + (n + 0))) ≡ suc (n + suc (n + 0)).
So you need to skip sucs by cong and rearrange the rest of the expression by the previously defined lemma.
cong : ∀ {a b} {A : Set a} {B : Set b}
       (f : A → B) {x y} → x ≡ y → f x ≡ f y
cong f refl = refl

as-2*k : {n : ℕ} -> Even n -> ∃ λ k -> n ≡ 2 * k
as-2*k  ezero    = 0 , refl
as-2*k (esuc en) with as-2*k en
...              | n , refl = suc n , cong suc (sym (m+1+n≡1+m+n n (n + 0)))

sym makes y ≡ x from x ≡ y.
Another auxiliary lemma:
remove-*2 : (n : ℕ) -> {m : ℕ} -> Even (n + n + m) -> Even m
remove-*2  0          e = e
remove-*2 (suc n) {m} e
    with subst (λ n' -> Even (suc (n' + m))) (+-comm n (suc n)) e
... | esuc e1 = remove-*2 n e1

And rather dirty proof of the second fact. First you need to prove some basic cases.
even-sqrt : {n : ℕ} -> Even (n ^2) -> Even n
even-sqrt {0}            ezero   = ezero
even-sqrt {1}            ()
even-sqrt {suc (suc n)} (esuc e) = {!!}

If n is 1 then n ^2 is not the inhabitant of Even, so you can exclude this case by (). The context now looks like this:
Goal: Even (suc (suc n))
————————————————————————————————————————————————————————————
e : Even (n + suc (suc (n + n * suc (suc n))))
n : ℕ

The proof is quite long, so I give you a link to the whole code: http://lpaste.net/101722
There is a proof for the third fact too.
The fourth fact is the simplest one:
0<n^2 : {n : ℕ} -> 0 < n -> 0 < n ^2
0<n^2 (s≤s le) = s≤s z≤n

A: You might find it useful to take a look how to proove (x - 1) (x ^ + 1) = x ^ 3 - 1 using ring axioms:
https://github.com/solomatov/AgdaSandbox/blob/master/Ring.agda

A: Agda's standard library is fairly minimal and hard to browse through.
You might want to consider looking into Data/Nat.agda and Data/Nat/*.agda for things related to natural number arithmetics.
You will probably have to define the even and odd predicates for instance, grepping them yielded nothing. You might want to define them inductively over natural numbers, or to reuse more general notions of divisibility found in the files I mentioned.


text:
Q: For any finitely-generated abelian group, show M(G,n) exists Let $G$ be a finitely-generated abelian group. Prove there is a CW complex $M(G,n)$ which has $\tilde H_k(M(G,n))$ equals $G$ if $k=n$ or zero otherwise.
Here's what I have so far:
By the fundamental theorem for finitely generated abelian groups, $G \cong \mathbb{Z}^k \times \mathbb{Z}/p_1^{n_1}\times \dots \times \mathbb{Z}/p_k^{n_k}$ for primes $p_i$.
$S^n$ is an $M(\mathbb{Z},n)$.
I'm thinking the CW complex I'm looking for will be a wedge sum with $k$ $S^n$ and other spaces.
How can I continue from here?

A: You're right that using wedge sums is a good idea. In fact, it should be clear that using wedge sums and using $S^n$, you only need to prove that $M(\mathbb Z/p^k\mathbb Z, n)$ exists for all $k,n$.
Hint: use the fact that $\mathbb Z/p^k\mathbb Z$ is the homology of $\mathbb Z\overset{p^k}\to \mathbb Z$, together with cellular homology.


text:
Q: Trying to instantiate Commercial Paper smart contract, error starting container /host/var/run/docker.sock: connect: no such file or directory I am using HF 1.4.9 and VS Code 1.39.2 with the IBP extension. Docker version 19.03.13 running on MacOS Catalina. Several other people that are doing the same lab with me and have different operating system are running into exactly the same error.
This is the command: docker exec cliMagnetoCorp peer chaincode instantiate -n papercontract -v 0.0.3 -l node -c '{"Args":["org.papernet.commercialpaper:instantiate"]}' -C mychannel -P "AND ('Org1MSP.member')"
and the output in the MagnetoCorp terminal window is:
2020-10-17 18:31:35.067 UTC [chaincodeCmd] InitCmdFactory -> INFO 001 Retrieved channel (mychannel) orderer endpoint: orderer.example.com:7050
2020-10-17 18:31:35.076 UTC [chaincodeCmd] checkChaincodeCmdParams -> INFO 002 Using default escc
2020-10-17 18:31:35.076 UTC [chaincodeCmd] checkChaincodeCmdParams -> INFO 003 Using default vscc
Error: could not assemble transaction, err proposal response was not successful, error code 500, msg error starting container: error starting container: Post http://unix.sock/containers/create?name=dev-peer0.org1.example.com-papercontract-0.0.3: dial unix /host/var/run/docker.sock: connect: no such file or directory

In the monitor logs terminal window I get the following error:
peer0.org1.example.com|2020-10-17 18:31:35.167 UTC [dockercontroller] Start -> ERRO 049 create container failed: Post http://unix.sock/containers/create?name=dev-peer0.org1.example.com-papercontract-0.0.3: dial unix /host/var/run/docker.sock: connect: no such file or directory imageName=dev-peer0.org1.example.com-papercontract-0.0.3-5f1d60e28249e81faa02102ce57e28b86443fdc9c08e350371a8b90ac690ae6e containerName=dev-peer0.org1.example.com-papercontract-0.0.3
peer0.org1.example.com|2020-10-17 18:31:35.182 UTC [endorser] callChaincode -> INFO 04a [mychannel][721d6ed1] Exit chaincode: name:"lscc"  (98ms)
peer0.org1.example.com|2020-10-17 18:31:35.182 UTC [endorser] SimulateProposal -> ERRO 04b [mychannel][721d6ed1] failed to invoke chaincode name:"lscc" , error: Post http://unix.sock/containers/create?name=dev-peer0.org1.example.com-papercontract-0.0.3: dial unix /host/var/run/docker.sock: connect: no such file or directory
peer0.org1.example.com|error starting container
peer0.org1.example.com|error starting container
peer0.org1.example.com|2020-10-17 18:31:35.183 UTC [comm.grpc.server] 1 -> INFO 04c unary call completed grpc.service=protos.Endorser grpc.method=ProcessProposal grpc.peer_address=172.19.0.7:40046 grpc.code=OK grpc.call_duration=100.6563ms
   orderer.example.com|2020-10-17 18:31:35.200 UTC [orderer.common.broadcast] Handle -> WARN 00e Error reading from 172.19.0.7:36270: rpc error: code = Canceled desc = context canceled
   orderer.example.com|2020-10-17 18:31:35.200 UTC [comm.grpc.server] 1 -> INFO 00f streaming call completed grpc.service=orderer.AtomicBroadcast grpc.method=Broadcast grpc.peer_address=172.19.0.7:36270 error="rpc error: code = Canceled desc = context canceled" grpc.code=Canceled grpc.call_duration=120.6555ms

A: So, I was able to solve it. With the version of Docker that now has the "Use gRPC FUSE for file sharing" enabled by default. Unclicked that, restarted my environment. I teardowned everything and recreated and was able to instantiate. This was what lead me to the solution https://jira.hyperledger.org/browse/FAB-18134 https://github.com/docker/for-mac/issues/4955


text:
Q: Symfony2: Set flash message after UNsuccessful login I am using FOSUSerBundle and have successfully overwritten Controllers, Forms and Views.
But I cannot find the correct place to set a flash message after unsuccessful login.
I already tried modifying the checkAction() in SecurityController.php, but it doesnt work.
Where is the correct place to set my flash message?
Thank you very much in advance!

A: I solved the problem pretty straight-forward:
1.) have overwritten the SecurityController and edited the loginAction
2.) hooked into the case where the login process returns an not empty $error
// in case the login process returns an error...
if ($error) {
    $error = $error->getMessage();

    // ... add the desired flash message to display
    $session->getFlashBag()->add('error', 'my error message here');
}

A: You dont need to overwrite the controller for it.
I overwrite the login.html.twig file and give the user the errors with the following line:
{% if error %}

{{ error.messageKey|trans(error.messageData, 'security') }}

 {% endif %}


text:
Q: Как использовать glVertexPointer для различных пользовательских данных OpenGL Проблема заключается в следующем, создаю пользовательский тип данных хранящий точки объекта в структуре (представляю их как 2-ный массив) и передаю в функцию следующим образом.
double a = 0.5;
    struct {
        double e[3];
    } ver_cub[24] = {
            {-a, -a, a},  {a, -a, a},  {a, a, a},  {-a, a, a},
            {a, -a, -a},  {-a, -a, -a},  {-a, a, -a}, {a, a, -a},
            {-a, -a, -a},  {-a, -a, a},  {-a, a, a},  {-a, a, -a},
            {a, -a, a},  {a, -a, -a},  {a, a, -a},  {a, a, a},
            {-a, -a, a},  {a, -a, a},  {a, -a, -a},  {-a, -a, -a},
            {-a, a, a},  {a, a, a},  {a, a, -a},  {-a, a, -a}
        };

glVertexPointer(3, GL_DOUBLE, 0, &arr);

Всё отображается и меня устраивает, но что если моё хранение данных выглядит иначе, к примеру внешние библиотеки которые парсят модели из obj файлов представлены иначе. И реализациия их в примерах проходит с задействием 3 параметра функции glVertexPointer и выглядят они следующим образом.
class objLoader {
 public:
  objLoader() {}
  ~objLoader() { delete_obj_data(&data); }

  int load(char *filename);

  obj_vector **vertexList;
  obj_vector **normalList;
  obj_vector **textureList;

  obj_face **faceList;
  obj_sphere **sphereList;
  obj_plane **planeList;

  obj_light_point **lightPointList;
  obj_light_quad **lightQuadList;
  obj_light_disc **lightDiscList;

  obj_material **materialList;

  int vertexCount;
  int normalCount;
  int textureCount;

  int faceCount;
  int sphereCount;
  int planeCount;

  int lightPointCount;
  int lightQuadCount;
  int lightDiscCount;

  int materialCount;

  obj_camera *camera;

 private:
  obj_scene_data data;
};

На данный момент из этой струкруры мне необходимы только вершины
typedef struct obj_vector {
  double e[3];
} obj_vector;

Каким образом мне передать данные этого массива в glVertexPointer
, чтобы тот обрабатывал данные с моего obj файла.
v -0.5 -0.5 0.5
v 0.5 -0.5 0.5
v 0.5 0.5 0.5
v -0.5 0.5 0.5
v 0.5 -0.5 -0.5
v -0.5 -0.5 -0.5
v -0.5 0.5 -0.5
v 0.5 0.5 -0.5
v -0.5 -0.5 -0.5
v -0.5 -0.5 0.5
v -0.5 0.5 0.5
v -0.5 0.5 -0.5
v 0.5 -0.5 0.5
v 0.5 -0.5 -0.5
v 0.5 0.5 -0.5
v 0.5 0.5 0.5
v -0.5 -0.5 0.5
v 0.5 -0.5 0.5
v 0.5 -0.5 -0.5
v -0.5 -0.5 -0.5
v -0.5 0.5 0.5
v 0.5 0.5 0.5
v 0.5 0.5 -0.5
v -0.5 0.5 -0.5

Мне необходимо конструкция подобна следующией записи
glVertexPointer(3, GL_DOUBLE, sizeof(obj_vector), &(objData->vertexList[0]->e));

как ёто описывается на внешних ресурсах.
Хочется использовать внешние библиотеки, а не
double arr[24][3];

for (int i = 0; i < 24; ++i) {
    for (int j = 0; j < 3; ++j) {
        arr[i][j] = objData->vertexList[i]->e[j];
    }
}

glVertexPointer(3, GL_DOUBLE, 0, &arr);


text:
Q: click function called multiple times The thing is there are various products on my homepage , on clicking on it there is a popup opening after it. There is a like button on the modal popup. On clicking on it i fire ajax and populate the database and close it , but when i open another popup model and click on the like button the ajax fires two times similarly after closing and opening another popup the ajax call increases.
I tried to make modal html to blank on clicking the close button on button. but, it is not working.
On the home page

this is the container where i am populating the data .
This is the like icon html

    <img src="<?php echo base_url(); ?>assets/blog/feed_image/likeBlack.png" />

and this is the code for click
$(document.body).on('click','.change', function(e) {
    alert('clicked');
    $.ajax({
        url: base_url + 'Like',
        type: 'POST',
        data: "product_id=" + $('#product_id').val() + "&from=product",
        dataType: "json",
        success: function (response)
        {
            if (response.exists == "1")
            {
                //$('#success_wish').html(response.message);
                //$('#success_wish').show("slow");
                // $('.hello').attr('src', swap).attr("data",current);
                $(".product_like_li").html(response.likeText);
                window.setTimeout(function () {
                    $('#success_wish').hide("slow")
                }, 3000);
            }
            if (response.exists == "2")
            {
                //$('#success_error').html(response.message);
                //$('#success_error').show("slow");
                window.setTimeout(function () {
                    $('#success_error').hide("slow")
                }, 3000);
                window.setTimeout(function () {
                    window.location.href = base_url + 'Login'
                }, 3000);
            }
            if (response.exists == "0")
            {
                $('#success_error').html(response.message);
                $('#success_error').show("slow");
                window.setTimeout(function () {
                    $('#success_error').hide("slow")
                }, 3000);
            }
        }
    });

});

A: Try to unbind the click event whenever page loads.You can use unbind method as follows.
$(document).unbind('click');

A: Try like below. It seems that $(document.body).on event is getting bind each time you open popup.
$(document.body).off('click','.change');
$(document.body).on('click','.change', function(e) {
    // Your code
});

A: Try to use off to unbind the events:
$('.commonClose').off('click').click(function(e) {
    $('.prod_vbody').html('');
})

A: please add your function on document.ready function something like this.
$(document).ready(function(){
   $('.change').on('click', function(e) {
    alert('clicked');
    $.ajax({
        url: base_url + 'Like',
        type: 'POST',
        data: "product_id=" + $('#product_id').val() + "&from=product",
        dataType: "json",
        success: function (response)
        {
            if (response.exists == "1")
            {
                //$('#success_wish').html(response.message);
                //$('#success_wish').show("slow");
                // $('.hello').attr('src', swap).attr("data",current);
                $(".product_like_li").html(response.likeText);
                window.setTimeout(function () {
                    $('#success_wish').hide("slow")
                }, 3000);
            }
            if (response.exists == "2")
            {
                //$('#success_error').html(response.message);
                //$('#success_error').show("slow");
                window.setTimeout(function () {
                    $('#success_error').hide("slow")
                }, 3000);
                window.setTimeout(function () {
                    window.location.href = base_url + 'Login'
                }, 3000);
            }
            if (response.exists == "0")
            {
                $('#success_error').html(response.message);
                $('#success_error').show("slow");
                window.setTimeout(function () {
                    $('#success_error').hide("slow")
                }, 3000);
            }
        }
    });

   });
})


text:
Q: Reading data from file to struct using fread I'm writing a piece of code and a part of it is reading "records" from file to n-length array, n given as an argument. Records in file have constant length(in this case 1024) and contain only numerics, spaces and lower letters. Each record is terminated with \n. I'm using following structure to keep one record:
typedef struct{
char rec[1024];
} record;

And Code for extracting n of them and storing in n-length array of records is written this way:
record * recs=malloc(n*sizeof(record));
size_t read=fread(recs,sizeof(record),(size_t)n,f);

When I checked output of this operations it turns out that first element of array recs contains all of the records, second all but first and so on instead of keeping one at each element of array. I'm kind of lost, because i thought that it should store each record in different element of array.
As suggested, I'm also providing code for opening a file and printing elements of array:
if((f=fopen(argv[2],"r"))==NULL){
        perror("error opening file\n");
        exit(1);
    }

for(int i=0;i<(int)read;i++){
        printf("record number %d\n %s\n",i,recs[i].rec);
    }

A: The problem is that your records rec isn't a zero terminated string.
So printing using %s shows all records because the printing will just continue until it sees a '\0'.
So either make sure to add a zero-termination in each rec or use another way of printing than %s.
BTW: If there isn't any zero-termination inside recs you actually have undefined behavior.
This little program mimics the problem:
#include <stdio.h>

struct r {
    char c[1];
};

int main(void) {
    int i;
    struct r recs[4] = {{'a'}, {'b'}, {'c'}, {'\0'}};
                                      //       ^^^^^
                                      //       Just to stop printing here
    for (i=0; i<3; i++)
    {
        printf("%d %s\n", i, recs[i].c);
    }

    return 0;
}

Output:
0 abc
1 bc
2 c


text:
Q: Why can't I schedule a timer through a function? I am using a crate called timer and I'm trying to put a timer "guard" into a hashmap to store it so that I can either drop it before it ends or make sure I don't create a duplicate.
The problem is that the timer does not trigger when inserted into a hashmap through a function, but works fine if the body of the function is moved to main instead.
extern crate chrono;
extern crate timer;

use std::collections::HashMap;
use std::thread;
use std::time::Duration;

fn insert_to_guard_map(guard_map: &mut HashMap<i32, timer::Guard>) {
    let timer = timer::Timer::new();
    let guard = timer.schedule_with_delay(chrono::Duration::seconds(2), || {
        println!("Called after 2s.");
    });

    guard_map.insert(42, guard);
}

fn main() {
    let mut guard_map = HashMap::new();

    insert_to_guard_map(&mut guard_map);
    thread::sleep(Duration::from_secs(4));
}

A: The documentation of Timer and Guard mention that if either the Timer or the Guard is dropped, then the scheduled execution is ultimately cancelled.
So in that case, either insert both the timer and guard into the HashMap.
use timer::{Guard, Timer};

fn insert_to_guard_map(guard_map: &mut HashMap<i32, (Timer, Guard)>) {
    let timer = Timer::new();
    let guard = timer.schedule_with_delay(chrono::Duration::seconds(2), || {
        println!("Called after 2s.");
    });

    guard_map.insert(42, (timer, guard));
}

Alternatively (and likely better), pass a reference of Timer to insert_to_guard_map().
use timer::{Guard, Timer};

fn insert_to_guard_map(guard_map: &mut HashMap<i32, Guard>, timer: &Timer) {
    let guard = timer.schedule_with_delay(chrono::Duration::seconds(2), || {
        println!("Called after 2s.");
    });

    guard_map.insert(42, guard);
}

fn main() {
    let timer = Timer::new();
    let mut guard_map = HashMap::new();

    insert_to_guard_map(&mut guard_map, &timer);
    thread::sleep(Duration::from_secs(4));
}


text:
Q: Inserting null values to database using prepared statements PHP MYSQL Hi I am using prepared statements for the first time. I have a form whose values, i am inserting in Mysql database using Mysqli prepared statements. But the problem is if user leaves an input box empty, Query doesn't insert row to the database.
Form
<form action="test.php" method="post" class="signupform">
    <input type="text" Placeholder="Name" name="name" Required="required"/>

    <input type="email" Placeholder="Email-id" name="email" Required="required"/>

    <input type="password" Placeholder="Password" name="pass" Required="required"/>

    Male<input type="radio" name="sex" value="M" checked="checked"/>   Female<input type="radio" name="sex" value="F"/>

    <input type="text" Placeholder="City" name="city"/>

    <input type="submit" value="CREATE MY ACCOUNT" name="submit"/>
</form>

<?php

if(isset($_POST['submit'])){
    include_once('includes/db.php');
    $name=$_POST['name'];
    $pass=$_POST['pass'];
    $email=$_POST['email'];
    $sex=$_POST['sex'];
    $city = $_POST['city'];
    if ($stmt = $mysqli->prepare("INSERT INTO login VALUES('',?,?,?,?,?,'')")) {
        $stmt->bind_param("sssss", $name, $email, $pass, $sex, $city);
        $stmt->execute();
        if($stmt){
            echo "result inserted";
        }
    }
}

?>

On using above form and query when i fill all the boxes of form it insert a new row for me. But if i leave an input box empty, It doesn't insert any row.
I also have seen a lot of questions which says that if i use variables like this
if(empty($_POST['city'])) { $city = null; } else { $city = $_POST['city']; }

then it will work and most of them are accepted answers. I am confused why this solution is not working for me ???
Any help is appreciated...Thanks

A: Your query is wrong:
if ($stmt = $mysqli->prepare("INSERT INTO login VALUES('',?,?,?,?,?,'')")) {

It should be something like:
if (!empty($name) || !empty($pass) || !empty($email))
    {
        $stmt = $mysqli->prepare("INSERT INTO login(`name`,`password`,`email`,`sex`,`city`) VALUES(?,?,?,?,?)");
        $stmt->execute([$name, $pass, $email, $sex, $city]);
        echo "result inserted";

    } else {
        echo 'You have not entered all of the fields.';
    }

In this instance, if the variables are not empty then perform insert. Else if they are empty fire a echo stating the fields haven't been filled in.
If you are happy for the fields to be null simply change !empty() to empty() but as Fred -ii- stated above, ensure your database allows NULL within them fields.

A: Probably this is not one of the smartest way to do it, but hey, it will get the job done.
One of the things that you need to do before assigning a variable to an $_POST field, you need to check if that $_POST field isset and its  not empty, then assign the value if not empty, Currently if someone leaves out a field in your form when you run the query you will probably get a notice of undefined.
This is what you can do.
<?php

if (isset($_POST['submit'])) {
    include_once('includes/db.php');

    if (!empty($_POST['name'])) {

        $name = $_POST['name'];
    } else {

        $name = " ";
    }

    if (!empty($_POST['pass'])) {

        $pass = $_POST['pass'];
    } else {

        $pass = " ";
    }

    if (!empty($_POST['email'])) {

        $email = $_POST['email'];
    } else {

        $email = " ";
    }

    if (isset($_POST['sex'])) {

        $sex = $_POST['sex'];
    } else {

        $sex = " ";
    }

    if (!empty($_POST['city'])) {
        $city = $_POST['city'];
    } else {

        $city = " ";
    }
    if ($stmt = $mysqli->prepare("INSERT INTO login VALUES(?,?,?,?,?)")) {
        $stmt->bind_param("sssss", $name, $email, $pass, $sex, $city);
        $stmt->execute();
        if ($stmt) {
            echo "result inserted";
        } else {

            echo "could not insert";
        }
    }
}

?>

There are other better ways to do this.


text:
Q: Filtered view is leading to incorrect detail view when tapped on, but correct detail view when swiped I think this is my last question before I can finally 1.0 release this thing. Here's my last remaining "can't launch yet" issue: When I filter by state, the resulting rows are not opening the appropriate detail view.
For example, if I search for TX, I see the seven Texas bonuses. If I tap on the 3rd one, I end up in AK3 (which is the 3rd item in the list if it isn't being filtered). The weird part, is that my swipe action DOES know that I am on TX3. Only when tapping to go to the detail does it jump to the wrong bonus.
Here is the full UITableViewController page:
import UIKit
import os.log
import Foundation

class BonusListViewController: UITableViewController {

    var bonuses = [JsonFile.JsonBonuses]()
    var bonus: JsonFile.JsonBonuses?
    var filteredBonuses = [JsonFile.JsonBonuses]()
    var detailViewController: BonusDetailViewController? = nil

    var riderNumToH:String = UserDefaults.standard.string(forKey: Constants.RiderData().riderNumToH) ?? "000"
    var pillionNumToH:String = UserDefaults.standard.string(forKey: Constants.RiderData().pillionNumToH) ?? "000"
    var emailDestinationToH:String = UserDefaults.standard.string(forKey: Constants.RallyData().emailDestinationToH) ?? "photos@tourofhonor.com"

    struct Constants {
        struct RiderData {
            let riderNumToH = "riderNumToH"
            let pillionNumToH = "pillionNumToH"
        }
        struct RallyData {
            let emailDestinationToH = "emailDestinationToH"
        }
    }

    let defaults = UserDefaults.standard

    let searchController = UISearchController(searchResultsController: nil)

    override func viewDidLoad() {
        super.viewDidLoad()

        // MARK: Search Support
        searchController.searchResultsUpdater = self
        searchController.obscuresBackgroundDuringPresentation = false
        searchController.searchBar.placeholder = "Enter two letter state"
        navigationItem.searchController = searchController
        definesPresentationContext = true

        // MARK: Settings Data Struct
        struct Constants {
            struct RiderData {
                let riderNumToH = "riderNumToH"
                let pillionNumToH = "pillionNumToH"
            }
            struct RallyData {
                let emailDestinationToH = "emailDestinationToH"
            }
        }
        //MARK: Load the bonuses
        print("About to call loadBonuses")
        loadBonuses { [weak self] bonuses in
            self?.bonuses = bonuses ?? []
            DispatchQueue.main.async {
                self?.tableView.reloadData()
            }
            print("loadBonuses called")
        }

        // MARK: Set Rider Defaults to Initial Values.
        let defaults = UserDefaults.standard
        print("Setting initial defaults")

        if riderNumToH == "" {
            print("riderNumToH is blank")
            defaults.set("000", forKey: Constants.RiderData().riderNumToH)
        } else if riderNumToH == "000" {
            print("riderNumToH is 000")
        } else {
            print("riderNumToH is custom")
        }

        if pillionNumToH == "" {
            print("pillionNumToH is blank")
            defaults.set("000", forKey: Constants.RiderData().pillionNumToH)
        } else if pillionNumToH == "000" {
            print("pillionNumToH is 000")
        } else {
            print("pillionNumToH is custom")
        }

        if emailDestinationToH == "" {
            print("emailDestinationToH is blank")
            defaults.set("photos@tourofhonor.com", forKey: Constants.RallyData().emailDestinationToH)
        } else if emailDestinationToH == "photos@tourofhonor.com" {
            print("emailDestinationToH is set to default")
        } else {
            print("emailDestinationToH has been customized")
        }

    }
    // MARK: - Table View Configuration
    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if isFiltering() {
            print("Showing \(filteredBonuses.count) Filtered Results")
            return filteredBonuses.count
        }

        print("Found \(bonuses.count) rows in section.")
        return bonuses.count
    }

    override func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration?
    {
        let clearAction = UIContextualAction(style: .normal, title: "Clear Data") { (contextAction: UIContextualAction, sourceView: UIView, completionHandler: (Bool) -> Void) in
            print("Clear Action Tapped")
            // Delete the created images
            let bonus: JsonFile.JsonBonuses
            if self.isFiltering() {
                bonus = self.filteredBonuses[indexPath.row]
            } else {
                bonus = self.bonuses[indexPath.row]
            }
            print("Selected Bonus is \(bonus.bonusCode)")
            let fileNameToDeletePri = "\(bonus.bonusCode)_1.jpg"
            let fileNameToDeleteOpt = "\(bonus.bonusCode)_2.jpg"
            var filePathPri = ""
            var filePathOpt = ""
            // Find documents directory on device
            let dirs : [String] = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.allDomainsMask, true)
            if dirs.count > 0 {
                let dir = dirs[0] //documents directory
                filePathPri = dir.appendingFormat("/" + fileNameToDeletePri)
                filePathOpt = dir.appendingFormat("/" + fileNameToDeleteOpt)
                print("Local path = \(filePathPri)")
                print("Local path = \(filePathOpt)")
            } else {
                print("Could not find local directory to store file")
                return
            }
            do {
                let fileManager = FileManager.default
                // Check if primary file exists
                if fileManager.fileExists(atPath: filePathPri) {
                    // Delete file
                    try fileManager.removeItem(atPath: filePathPri)
                } else {
                    print("Primary image does not exist")
                }
                // Check if optional file exists
                if fileManager.fileExists(atPath: filePathOpt) {
                    // Delete file
                    try fileManager.removeItem(atPath: filePathOpt)
                } else {
                    print("Optional image does not exist")
                }
            }
            catch let error as NSError {
                print("An error took place: \(error)")
            }
            tableView.reloadData()
            completionHandler(true)
        }

        clearAction.backgroundColor = .blue
        let swipeConfig = UISwipeActionsConfiguration(actions: [clearAction])
        return swipeConfig
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cellIdentifier = "BonusListViewCell"
        guard let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as? BonusListViewCell else {
            fatalError("The dequeued cell is not an instance of BonusListViewCell.")
        }
        let bonus: JsonFile.JsonBonuses
        if self.isFiltering() {
            bonus = self.filteredBonuses[indexPath.row]
        } else {
            bonus = self.bonuses[indexPath.row]
        }
        // Set Primary Image
        let documentsUrl = URL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0])
        let imgUrl =  documentsUrl.appendingPathComponent(bonus.bonusCode + "_1.jpg")
        if(FileManager.default.fileExists(atPath:imgUrl.path))
        {
            do
            {
                let data = try Data.init(contentsOf:imgUrl)
                cell.primaryImage.image = UIImage.init(data:data)
            }
            catch {
                print(error)
            }
        }
        else
        {
            cell.primaryImage.image = #imageLiteral(resourceName: "DefaultImage")
        }

        cell.nameLabel.text = bonus.name
        cell.bonusCodeLabel.text = bonus.bonusCode.localizedUppercase
        cell.categoryLabel.text = bonus.category
        cell.valueLabel.text = "\(bonus.value)"
        cell.cityLabel.text = "\(bonus.city.capitalized),"
        cell.stateLabel.text = bonus.state.localizedUppercase

        return cell
    }

    // MARK: Functions
    // MARK: - Fetch JSON from ToH webserver

    func downloadJSON(completed: @escaping ([JsonFile.JsonBonuses]?) -> ()) {
        let url = URL(string: "http://tourofhonor.com/BonusData.json")!
        URLSession.shared.dataTask(with: url) { (data, response, error) in
            if error == nil, let data = data {
                do {
                    let posts = try JSONDecoder().decode(JsonFile.self, from: data)
                    completed(posts.bonuses)
                    self.defaults.set(posts.meta.version, forKey: "jsonVersion")
                    print("URLSession did not fail")
                    print("JSON Version Set to \(posts.meta.version)")
                } catch {
                    print("Can't decode JSON: \(error)")
                }
            } else {
                print("downloadJSON completed")
                completed(nil)
            }
        }.resume()
    }

    func saveBonuses(_ bonuses: [JsonFile.JsonBonuses], to url: URL) {
        try? FileManager.default.removeItem(at: url)
        do {
            let data = try JSONEncoder().encode(bonuses)
            try data.write(to: url)
            print("saveBonuses successful")
        } catch {
            print("Error saving bonuses to file:", error)
        }
    }

    func loadBonusesFromFile(_ url: URL) -> [JsonFile.JsonBonuses]? {
        do {
            let data = try Data(contentsOf: url)
            let bonuses = try JSONDecoder().decode([JsonFile.JsonBonuses].self, from: data)
            print("loadBonusesFromFile successful")
            return bonuses
        } catch {
            print("Error loading bonuses from file:", error)
            return nil
        }
    }

    func loadBonuses(completion: @escaping ([JsonFile.JsonBonuses]?) -> Void) {
        let localBonusesURL = try! FileManager.default
            .url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
            .appendingPathComponent("BonusData.json")
        downloadJSON { bonuses in
            if let bonuses = bonuses {
                completion(bonuses)
                self.saveBonuses(bonuses, to: localBonusesURL)
            } else {
                print("versions did not match")
                completion(self.loadBonusesFromFile(localBonusesURL))
            }
        }
    }

    func searchBarIsEmpty() -> Bool {
        // Returns true if the text is empty or nil
        return searchController.searchBar.text?.isEmpty ?? true
    }

    func filterContentForSearchText(_ searchText: String, scope: String = "All") {
        filteredBonuses = bonuses.filter({( bonus: JsonFile.JsonBonuses) -> Bool in
            return bonus.state.localizedCaseInsensitiveContains(searchText)
        })
        tableView.reloadData()
    }

    func isFiltering() -> Bool {
        return searchController.isActive && !searchBarIsEmpty()
    }

    // MARK: - Navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if let destination = segue.destination as? BonusDetailViewController {
            destination.bonus = bonuses[(tableView.indexPathForSelectedRow?.row)!]
        }
    }
}

extension BonusListViewController: UISearchResultsUpdating {
    // MARK: - UISearchResultsUpdating Delegate
    func updateSearchResults(for searchController: UISearchController) {
        filterContentForSearchText(searchController.searchBar.text!)
    }
}

The part of the code that should be filtering the view is identical in both the cellForRowAt and the swipeAction methods:
let bonus: JsonFile.JsonBonuses
            if self.isFiltering() {
                bonus = self.filteredBonuses[indexPath.row]
            } else {
                bonus = self.bonuses[indexPath.row]
            }

Originally the cellForRowAt did not have the self entries, but I added those to see if it would resolve it, and it didn't.

A: I found the cause of the issue. Near the bottom of the UITableViewController I had the following:
// MARK: - Navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if let destination = segue.destination as? BonusDetailViewController {
            destination.bonus = bonuses[(tableView.indexPathForSelectedRow?.row)!]
        }
    }

This is where the issue was. I fixed it by adding the same if/else logic I used in my cellForRowAt and SwipeAction:
// MARK: - Navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if let destination = segue.destination as? BonusDetailViewController {
            if self.isFiltering() {
                destination.bonus = filteredBonuses[(tableView.indexPathForSelectedRow?.row)!]
            } else {
                destination.bonus = bonuses[(tableView.indexPathForSelectedRow?.row)!]
            }

        }
    }