问:
problem in TextView in android
hi all i m making a sample app. for update List.
i have a list class and its xml is like.

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ListView android:id="@+id/ListView01" android:layout_height="wrap_content"
android:layout_width="fill_parent"></ListView>
<TextView android:id="@+id/more"
android:layout_height="wrap_content"
android:text="Click to view more..."
android:textStyle="normal|bold" android:textColor="#FF8000"      android:textSize="10dip"
android:gravity="center_vertical|center_horizontal" android:layout_width="fill_parent">
</TextView>
</LinearLayout>
</code>```

now i have set TouchListener of text View and added the following code in it

```<code>    @Override
         public boolean onTouch(View v, MotionEvent event) {
        switch(v.getId())
        {
        case R.id.more:
        //update List Method Call..
        more.setText("Click to view More..");
        adapter.notifyDataSetChanged();
        }

        // TODO Auto-generated method stub
        return false;
    }
</code>```

You see on the 3rd line of switch statement i have added

```<code> more.setText("Click to view More..");
</code>```

line but when my list is updated . The text View is no longer shows in the bottom .
Please Guide my why this is happening to me and whats the solution??

答:
use the following code..
footer_layout.xml

```<code><?xml version="1.0" encoding="utf-8"?>
  <LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="7dip"
android:paddingBottom="7dip"
android:orientation="horizontal"
android:gravity="center">
<LinearLayout
android:id="@+id/footer_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center"
android:layout_gravity="center">

<TextView
    android:text="footer_text_1"
    android:id="@+id/footer_1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textSize="14dip"
    android:textStyle="bold"
    android:layout_marginRight="5dip">
</TextView>

 </LinearLayout>
  </LinearLayout>
</code>```

and use the following in code:

```<code>public class listactivty extends ListActivity{
 private Context context = null;
 private ListView list = null;

 public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
  list = (ListView)findViewById(android.R.id.list);
//code to set adapter to populate list

 View footerView =
      ((LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.footer_layout, null, false);
    list.addFooterView(footerView);
}
</code>```

use seperate XML file for ListView..

Thanks
Shahjahan Ahmad

Title: problem in TextView in android

Body:
hi all i m making a sample app. for update List.
i have a list class and its xml is like.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ListView android:id="@+id/ListView01" android:layout_height="wrap_content"
android:layout_width="fill_parent"></ListView>
<TextView android:id="@+id/more"
android:layout_height="wrap_content"
android:text="Click to view more..."
android:textStyle="normal|bold" android:textColor="#FF8000"      android:textSize="10dip"
android:gravity="center_vertical|center_horizontal" android:layout_width="fill_parent">
</TextView>
</LinearLayout>

now i have set TouchListener of text View and added the following code in it

    @Override
         public boolean onTouch(View v, MotionEvent event) {
        switch(v.getId())
        {
        case R.id.more:
        //update List Method Call..
        more.setText("Click to view More..");
        adapter.notifyDataSetChanged();
        }

        // TODO Auto-generated method stub
        return false;
    }

You see on the 3rd line of switch statement i have added

 more.setText("Click to view More..");

line but when my list is updated . The text View is no longer shows in the bottom .
Please Guide my why this is happening to me and whats the solution??

Body:
use the following code..
footer_layout.xml

<?xml version="1.0" encoding="utf-8"?>
  <LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="7dip"
android:paddingBottom="7dip"
android:orientation="horizontal"
android:gravity="center">
<LinearLayout
android:id="@+id/footer_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center"
android:layout_gravity="center">

<TextView
    android:text="footer_text_1"
    android:id="@+id/footer_1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textSize="14dip"
    android:textStyle="bold"
    android:layout_marginRight="5dip">
</TextView>

 </LinearLayout>
  </LinearLayout>

and use the following in code:

public class listactivty extends ListActivity{
 private Context context = null;
 private ListView list = null;

 public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
  list = (ListView)findViewById(android.R.id.list);
//code to set adapter to populate list

 View footerView =
      ((LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.footer_layout, null, false);
    list.addFooterView(footerView);
}

use seperate XML file for ListView..

Thanks
Shahjahan Ahmad


来源: stackexchange

问:
How to mock multiprocessing.Event.is_set() - AttributeError
I'm trying to mock a multiprocessing.Event object so that a call to event.is_set() returns False on the first iteration and true on the second iteration. I've failed at the following attempt:

```<code>import unittest
import unittest.mock as mock
import multiprocessing

class MyClassUnderTest:
    def __init__(self):
        self.event = multiprocessing.Event()
        # start a Process which immediately uses self.event

    def my_method_under_test(self):
        while not self.event.is_set():
            pass  # do something
        return True

class TestMyClassUnderTest(unittest.TestCase):
    @mock.patch.object(multiprocessing.Event, 'is_set', return_value=False)
    def test_my_method(self, mock_event):
        mock_event.side_effect = [False, True]

        myobj = MyClassUnderTest()
        self.assertTrue(myobj.my_method_under_test())
</code>```

I end up with the error:

```<code>AttributeError: <bound method BaseContext.Event of <multiprocessing.context.DefaultContext object at 0x7f1068a50e48>> does not have the attribute 'is_set'
</code>```

I cannot override MyClassUnderTest.event because the event object is used immediately, so I'm trying to override the entire multiprocessing.Event class.

答:
Here's a way to do it with configure_mock:

```<code>import unittest
import unittest.mock as mock
import multiprocessing

class MyClassUnderTest:
    def __init__(self):
        self.event = multiprocessing.Event()
        # start a Process which immediately uses self.event

    def my_method_under_test(self):
        while not self.event.is_set():
            pass  # do something
        return True

class TestMyClassUnderTest(unittest.TestCase):
    @mock.patch('multiprocessing.Event')
    def test_my_method(self, mock_event):
        mock_event.configure_mock(**{'is_set.side_effect': [False, True]})

        myobj = MyClassUnderTest()
        self.assertTrue(myobj.my_method_under_test())
</code>```

If anyone knows how to condense this entirely into @mock.patch(...) that would still be useful.

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to mock a multiprocessing.Event object so that a call to event.is_set() returns False on the first iteration and true on the second iteration. I've failed at the following attempt:

import unittest
import unittest.mock as mock
import multiprocessing

class MyClassUnderTest:
    def __init__(self):
        self.event = multiprocessing.Event()
        # start a Process which immediately uses self.event

    def my_method_under_test(self):
        while not self.event.is_set():
            pass  # do something
        return True

class TestMyClassUnderTest(unittest.TestCase):
    @mock.patch.object(multiprocessing.Event, 'is_set', return_value=False)
    def test_my_method(self, mock_event):
        mock_event.side_effect = [False, True]

        myobj = MyClassUnderTest()
        self.assertTrue(myobj.my_method_under_test())

I end up with the error:

AttributeError: <bound method BaseContext.Event of <multiprocessing.context.DefaultContext object at 0x7f1068a50e48>> does not have the attribute 'is_set'

I cannot override MyClassUnderTest.event because the event object is used immediately, so I'm trying to override the entire multiprocessing.Event class.

Body:
Here's a way to do it with configure_mock:

import unittest
import unittest.mock as mock
import multiprocessing

class MyClassUnderTest:
    def __init__(self):
        self.event = multiprocessing.Event()
        # start a Process which immediately uses self.event

    def my_method_under_test(self):
        while not self.event.is_set():
            pass  # do something
        return True

class TestMyClassUnderTest(unittest.TestCase):
    @mock.patch('multiprocessing.Event')
    def test_my_method(self, mock_event):
        mock_event.configure_mock(**{'is_set.side_effect': [False, True]})

        myobj = MyClassUnderTest()
        self.assertTrue(myobj.my_method_under_test())

If anyone knows how to condense this entirely into @mock.patch(...) that would still be useful.


问:
SAM build - does it also build layers?
I'm new to both lambda's and also SAM - so if I've screwed anything simple up don't yell :D.

Summary: I can't get sam build to build a layer specified in template.yaml, it only builds the lambda function.

Background: I'm trying to build a lambda function in python3.7 that uses the skimage (scikit-image) module.  To do that, I'm trying to use SAM to build and deploy it all.  ...this is working

I'm trying to deploy the scikit-image module as a layer (and also build with SAM), rather than having it included in the lambda function direction  ...this isn't working

As a start, I'm simply extending the standard SAM Hello World app.

I've got skimage working by simply add it to requirements.txt , then using sam build -u, then manually removing the numpy/scipy dependencies from the built package directory (I've got the AWS scipy/numpy layer included).

(I added import numpy, scipy.ndimage and skimage.draw to the standard hello world app, and included some test function calls to each)

requirements.txt:

```<code>requests
scikit-image
</code>```

After that, everything works fine (running locally and/or on AWS).

However, I'd now like to move the skimage module out of my app and into a new custom layer (I'd like to have skimage in a layer to re-use for a few functions)

To set that up, I've created a dependencies directory and moved requirements.txt into there (leaving empty requirements.txt in the app directory).
I then updated template.yaml to also specify the new layer:

```<code>AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: >
  sam-app

  Sample SAM Template for sam-app

# More info about Globals: https://github.com/awslabs/serverless-application-model/blob/master/docs/globals.rst
Globals:
  Function:
    Timeout: 3

Resources:
  HelloWorldFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: hello_world/
      Handler: app.lambda_handler
      Runtime: python3.7
      Layers:
              - arn:aws:lambda:us-west-2:420165488524:layer:AWSLambda-Python37-SciPy1x:2
              - !Ref SkimageLayer
      Events:
        HelloWorld:
          Type: Api
          Properties:
            Path: /hello
            Method: get

  SkimageLayer:
    Type: AWS::Serverless::LayerVersion
    Properties:
      LayerName: Skimage
      Description: Skimage module layer
      ContentUri: dependencies/
      CompatibleRuntimes:
              - python3.7
      RetentionPolicy: Retain
    DependsOn:
            - Skimage
</code>```

directory structure:

```<code>▾ dependencies/
    requirements.txt (responses and scikit-image)
▸ events/
▾ hello_world/
    __init__.py
    app.py
    requirements.txt (now empty)
▸ tests/
  README.md
  template.yaml
</code>```

However, when I run sam build -u with that template file, nothing gets built for the layer specified in ./dependencies: SkimageLayer in the template.yml file.  However the HelloWorldFunction still gets built correctly (now of course without any included modules)

答:
I got it to work with the following script. Tested with Ubuntu 18 and CodeBuild

It pip install's the layer's requirements to .aws-sam/build/layername/python/. Then you can run sam package and sam deploy as normal

build-layers.py:

```<code>import yaml
import subprocess
import sys
import shutil

SAM_BUILD_PATH = ".aws-sam/build"

with open("template.yaml", "r") as f:
    template = yaml.safe_load(f)

for key, resource in template["Resources"].items():
    if resource["Type"] not in ["AWS::Serverless::LayerVersion", "AWS::Lambda::LayerVersion"]:
        continue
    properties = resource["Properties"]
    content_uri = properties["ContentUri"]
    layer_name = properties["LayerName"]
    requirements_path = f"{content_uri}/requirements.txt"

    subprocess.check_call([sys.executable, "-m", "pip", "install", "-r", requirements_path, "-t", f"{SAM_BUILD_PATH}/{layer_name}/python"])

shutil.copyfile("template.yaml", f"{SAM_BUILD_PATH}/template.yaml")
</code>```

template.yaml:

```<code>Transform: AWS::Serverless-2016-10-31

Resources:
  pandas:
    Type: AWS::Serverless::LayerVersion
    Properties:
      LayerName: pandas
      ContentUri: pandas
      CompatibleRuntimes:
        - python3.6
        - python3.7
        - python3.8
  sqlparse:
    Type: AWS::Serverless::LayerVersion
    Properties:
      LayerName: sqlparse
      ContentUri: sqlparse
      CompatibleRuntimes:
        - python3.6
        - python3.7
        - python3.8
</code>```

so call python build-layers.py first, then sam package then sam deploy

my directories look like this:

```<code>lambda
  layers
    pandas
      requirements.txt (content = pandas)
    sqlparse
      requirements.txt (content = sqlparse)
  template.yaml
  build-layers.py
</code>```

buildspec.yml:

```<code>---  # build spec for AWS CodeBuild

version: 0.2

phases:
  install:
    runtime-versions:
      python: 3.8
    commands:
      - pip install aws-sam-cli
  build:
    commands:
      - cd lambda/layers
      - python build-layers.py
      - sam package --s3-bucket foo --s3-prefix sam/lambda/layers | sam deploy --capabilities CAPABILITY_IAM -t /dev/stdin --stack-name LAYERS
</code>```

Title: SAM build - does it also build layers?

Body:
I'm new to both lambda's and also SAM - so if I've screwed anything simple up don't yell :D.

Summary: I can't get sam build to build a layer specified in template.yaml, it only builds the lambda function.

Background: I'm trying to build a lambda function in python3.7 that uses the skimage (scikit-image) module.  To do that, I'm trying to use SAM to build and deploy it all.  ...this is working

I'm trying to deploy the scikit-image module as a layer (and also build with SAM), rather than having it included in the lambda function direction  ...this isn't working

As a start, I'm simply extending the standard SAM Hello World app.

I've got skimage working by simply add it to requirements.txt , then using sam build -u, then manually removing the numpy/scipy dependencies from the built package directory (I've got the AWS scipy/numpy layer included).

(I added import numpy, scipy.ndimage and skimage.draw to the standard hello world app, and included some test function calls to each)

requirements.txt:

requests
scikit-image

After that, everything works fine (running locally and/or on AWS).

However, I'd now like to move the skimage module out of my app and into a new custom layer (I'd like to have skimage in a layer to re-use for a few functions)

To set that up, I've created a dependencies directory and moved requirements.txt into there (leaving empty requirements.txt in the app directory).
I then updated template.yaml to also specify the new layer:

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: >
  sam-app

  Sample SAM Template for sam-app

# More info about Globals: https://github.com/awslabs/serverless-application-model/blob/master/docs/globals.rst
Globals:
  Function:
    Timeout: 3

Resources:
  HelloWorldFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: hello_world/
      Handler: app.lambda_handler
      Runtime: python3.7
      Layers:
              - arn:aws:lambda:us-west-2:420165488524:layer:AWSLambda-Python37-SciPy1x:2
              - !Ref SkimageLayer
      Events:
        HelloWorld:
          Type: Api
          Properties:
            Path: /hello
            Method: get

  SkimageLayer:
    Type: AWS::Serverless::LayerVersion
    Properties:
      LayerName: Skimage
      Description: Skimage module layer
      ContentUri: dependencies/
      CompatibleRuntimes:
              - python3.7
      RetentionPolicy: Retain
    DependsOn:
            - Skimage

directory structure:

▾ dependencies/
    requirements.txt (responses and scikit-image)
▸ events/
▾ hello_world/
    __init__.py
    app.py
    requirements.txt (now empty)
▸ tests/
  README.md
  template.yaml

However, when I run sam build -u with that template file, nothing gets built for the layer specified in ./dependencies: SkimageLayer in the template.yml file.  However the HelloWorldFunction still gets built correctly (now of course without any included modules)

Body:
I got it to work with the following script. Tested with Ubuntu 18 and CodeBuild

It pip install's the layer's requirements to .aws-sam/build/layername/python/. Then you can run sam package and sam deploy as normal

build-layers.py:

import yaml
import subprocess
import sys
import shutil

SAM_BUILD_PATH = ".aws-sam/build"

with open("template.yaml", "r") as f:
    template = yaml.safe_load(f)

for key, resource in template["Resources"].items():
    if resource["Type"] not in ["AWS::Serverless::LayerVersion", "AWS::Lambda::LayerVersion"]:
        continue
    properties = resource["Properties"]
    content_uri = properties["ContentUri"]
    layer_name = properties["LayerName"]
    requirements_path = f"{content_uri}/requirements.txt"

    subprocess.check_call([sys.executable, "-m", "pip", "install", "-r", requirements_path, "-t", f"{SAM_BUILD_PATH}/{layer_name}/python"])

shutil.copyfile("template.yaml", f"{SAM_BUILD_PATH}/template.yaml")

template.yaml:

Transform: AWS::Serverless-2016-10-31

Resources:
  pandas:
    Type: AWS::Serverless::LayerVersion
    Properties:
      LayerName: pandas
      ContentUri: pandas
      CompatibleRuntimes:
        - python3.6
        - python3.7
        - python3.8
  sqlparse:
    Type: AWS::Serverless::LayerVersion
    Properties:
      LayerName: sqlparse
      ContentUri: sqlparse
      CompatibleRuntimes:
        - python3.6
        - python3.7
        - python3.8

so call python build-layers.py first, then sam package then sam deploy

my directories look like this:

lambda
  layers
    pandas
      requirements.txt (content = pandas)
    sqlparse
      requirements.txt (content = sqlparse)
  template.yaml
  build-layers.py

buildspec.yml:

---  # build spec for AWS CodeBuild

version: 0.2

phases:
  install:
    runtime-versions:
      python: 3.8
    commands:
      - pip install aws-sam-cli
  build:
    commands:
      - cd lambda/layers
      - python build-layers.py
      - sam package --s3-bucket foo --s3-prefix sam/lambda/layers | sam deploy --capabilities CAPABILITY_IAM -t /dev/stdin --stack-name LAYERS


问:
can someone help me solve this problem, look for many solutions but they have not worked for me
error al entrenar
the images have a size of ([64, 3, 224, 224])
I tried to change the batch-size or image size but I still get errors

```<code>Epoch 1/30
----------
---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
<ipython-input-160-dbcdb17ea6ee> in <module>()
      1 epochs = 30
      2 net.to(device)
----> 3 net = train_model(net, criterion, optimizer, sched, epochs)

2 frames
<ipython-input-157-d34ea1683b12> in forward(self, x)
     12     x = self.pool(F.relu(self.conv1(x)))
     13     x = self.pool(F.relu(self.conv2(x)))
---> 14     x = x.view(x.size(0), 16 * 38 * 38)
     15     x = F.relu(self.fc1(x))
     16     x = F.relu(self.fc2(x))

RuntimeError: shape '[64, 23104]' is invalid for input of size 2876416
</code>```

答: This is because the product of your spatial & channel dimensions is not equivalent to 23104 but rather is equal to 2876416. To flatten your tensor, you can try out = out.view(out.size(0), -1) instead, which should work fine.

Body:
error al entrenar
the images have a size of ([64, 3, 224, 224])
I tried to change the batch-size or image size but I still get errors

Epoch 1/30
----------
---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
<ipython-input-160-dbcdb17ea6ee> in <module>()
      1 epochs = 30
      2 net.to(device)
----> 3 net = train_model(net, criterion, optimizer, sched, epochs)

2 frames
<ipython-input-157-d34ea1683b12> in forward(self, x)
     12     x = self.pool(F.relu(self.conv1(x)))
     13     x = self.pool(F.relu(self.conv2(x)))
---> 14     x = x.view(x.size(0), 16 * 38 * 38)
     15     x = F.relu(self.fc1(x))
     16     x = F.relu(self.fc2(x))

RuntimeError: shape '[64, 23104]' is invalid for input of size 2876416


问:
Real * Bigint not return right value
I have two column in Sql server

Amount as real type

Price as bigint type

Amount is 3059.9 and Price is 29000

Price * amount should be 88737100 but it does not return correct value.

Should I cast any columns to other data type ?

 The result is 8.87371E+07, how can I display it without scientific notation?

答: Try CAST(Amount AS DECIMAL(38, 2)) * Price.  Read up on DECIMAL and adjust accordingly depending on the number of digits & decimal places.

ContentLicense: CC BY-SA 3.0

Title: Real * Bigint not return right value


问:
Data.Binary encodeFile does not seem to be thread safe - corrupted file?
I'm trying to replicate a situation where a binary file was essentially corrupted with a filesize of 0 in a real world application via encodeFile, this occurred after a hard reboot.

Although I've not been able to replicate this behavior exactly, I have gotten it to replicate a corrupted(?) file with code below.

When we first run it (some text is garbled due to multiple threads printing):

```<code>"New valid file written"
Example "hmm" [0]
"Testing..."
"Donenn"oo
tt  een#no~ouGugHghCh I bDby-ytSteTesAs
R
CTCa~al#lllSSttaacckk  ((ffrroomm  HHaassCCaallllStS#at~caGkcH)kC:)I
:D
-  Fe IreNrrIorSroH,r- ,5c ~ac#la
llelde #da~ tGa HtsC rIscDr/-cMS/aTMiAanRi.Tnh~.s#h:s5:35:31:51 5i ni nm amiani:nM:aMiani
n
"d"ideiien#ig~n.Gg.H..C..I..D..-..S."T.
Command "cabal v2-repl app" exited unexpectedly
</code>```

After a few runs eventually we get an error of:

```<code>*** Exception: not enough bytes
CallStack (from HasCallStack):
  error, called at src/Main.hs:53:15 in main:Main
</code>```

What is the cause of this error? Is it just the case that encodeFile is not safe when used via multiple threads (which is kind of odd as there is no mention of threads on https://hackage.haskell.org/package/binary-0.10.0.0/docs/Data-Binary.html).

```<code>{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE LambdaCase #-}
module Main where

import System.PosixCompat.Files
import System.Process
import System.Process.Internals
import System.Posix.Signals
import System.Posix.Process
import Control.Concurrent
import Control.Monad
import Data.Binary
import GHC.Generics (Generic)
import Control.Exception

data Example = Example String [Int] deriving (Generic, Show)
instance Binary Example

main :: IO ()
main = do
  checkFile
  encodeFile "output.txt" $ Example "hmm" [0]
  checkFile
  print "New valid file written"
  decodeFileOrFail "output.txt" >>= \case
      Right v@(Example s z) -> print v
      Left (e,e') -> do
            error $ e'
            rip
  print "Testing..."
  forM_ [1..3] (const $ forkIO $ catch (do
                     checkFile
                     somethingIO
                     checkFile) (\e -> do
                                            print (e :: SomeException)
                                            rip
                                        )
    )
  print "Done"

checkFile :: IO ()
checkFile = do
  fileExist "output.txt" >>= \case
    True -> do
      x <- getFileSize "output.txt"
      if x == 0 then
        rip
      else
        pure ()
      decodeFileOrFail "output.txt" >>= \case
        Right (Example s z) -> pure ()
        Left (e,e') -> do
              error $ e'
              rip
    False -> pure ()

rip :: IO ()
rip = do
  print "dieing......."
  getProcessID >>= signalProcess sigKILL

somethingIO :: IO ()
somethingIO = do
  let v = 10 :: Int
  decodeFileOrFail "output.txt" >>= \case
    Right (Example s z) -> encodeFile "output.txt" $ z ++ [v]
    Left (e,e') -> do
          error $ e'
          rip

getFileSize :: String -> IO Int
getFileSize path = getFileStatus path >>= return . fromIntegral . fileSize
</code>```

With a cabal file of:

```<code>cabal-version: 1.12
name:                HaskellNixCabalStarter
version:             0.1.0.0
author:              HaskellNixCabalStarter
maintainer:          HaskellNixCabalStarter
license:             MIT
build-type:          Simple

executable app
  main-is: Main.hs
  other-modules:
      Paths_HaskellNixCabalStarter
  hs-source-dirs:
      src
  build-depends:
      base >=4.12 && <4.13
    , binary
    , process
    , random
    , unix
    , unix-compat
  default-language: Haskell2010
</code>```

答:
There's nothing particularly mysterious going on here. Reading and writing files simply aren't atomic operations, and this is biting you. If you have one thread writing output.txt and another reading output.txt, it is completely normal and expected for the reader to occasionally see only part of the file that the writer would eventually produce.

This is not particularly special to the binary package, nor even to the language -- this is, to a first approximation, true of nearly every library and language that deals with a filesystem. Guaranteeing atomicity of the appropriate kind is quite hard, indeed; but many, many engineering years have gone into providing this kind of thing for databases, so if that's a need for you, you might consider using one of them.

Alternately, a significantly simpler solution is to have a single thread that is responsible for reading and writing the appropriate file, and to communicate with it via one of Haskell's excellent inter-thread communication tools.

Some OSs do offer an atomic file-rename operation. In such a situation, one could also consider writing to a temporary file, then using an atomic rename to overwrite the filename you actually care about. (Thanks to a commenter who I will leave anonymous because they chose to delete their comment for suggesting this.)

Body:
I'm trying to replicate a situation where a binary file was essentially corrupted with a filesize of 0 in a real world application via encodeFile, this occurred after a hard reboot.

Although I've not been able to replicate this behavior exactly, I have gotten it to replicate a corrupted(?) file with code below.

When we first run it (some text is garbled due to multiple threads printing):

"New valid file written"
Example "hmm" [0]
"Testing..."
"Donenn"oo
tt  een#no~ouGugHghCh I bDby-ytSteTesAs
R
CTCa~al#lllSSttaacckk  ((ffrroomm  HHaassCCaallllStS#at~caGkcH)kC:)I
:D
-  Fe IreNrrIorSroH,r- ,5c ~ac#la
llelde #da~ tGa HtsC rIscDr/-cMS/aTMiAanRi.Tnh~.s#h:s5:35:31:51 5i ni nm amiani:nM:aMiani
n
"d"ideiien#ig~n.Gg.H..C..I..D..-..S."T.
Command "cabal v2-repl app" exited unexpectedly

After a few runs eventually we get an error of:

*** Exception: not enough bytes
CallStack (from HasCallStack):
  error, called at src/Main.hs:53:15 in main:Main

What is the cause of this error? Is it just the case that encodeFile is not safe when used via multiple threads (which is kind of odd as there is no mention of threads on https://hackage.haskell.org/package/binary-0.10.0.0/docs/Data-Binary.html).

{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE LambdaCase #-}
module Main where

import System.PosixCompat.Files
import System.Process
import System.Process.Internals
import System.Posix.Signals
import System.Posix.Process
import Control.Concurrent
import Control.Monad
import Data.Binary
import GHC.Generics (Generic)
import Control.Exception

data Example = Example String [Int] deriving (Generic, Show)
instance Binary Example

main :: IO ()
main = do
  checkFile
  encodeFile "output.txt" $ Example "hmm" [0]
  checkFile
  print "New valid file written"
  decodeFileOrFail "output.txt" >>= \case
      Right v@(Example s z) -> print v
      Left (e,e') -> do
            error $ e'
            rip
  print "Testing..."
  forM_ [1..3] (const $ forkIO $ catch (do
                     checkFile
                     somethingIO
                     checkFile) (\e -> do
                                            print (e :: SomeException)
                                            rip
                                        )
    )
  print "Done"

checkFile :: IO ()
checkFile = do
  fileExist "output.txt" >>= \case
    True -> do
      x <- getFileSize "output.txt"
      if x == 0 then
        rip
      else
        pure ()
      decodeFileOrFail "output.txt" >>= \case
        Right (Example s z) -> pure ()
        Left (e,e') -> do
              error $ e'
              rip
    False -> pure ()

rip :: IO ()
rip = do
  print "dieing......."
  getProcessID >>= signalProcess sigKILL

somethingIO :: IO ()
somethingIO = do
  let v = 10 :: Int
  decodeFileOrFail "output.txt" >>= \case
    Right (Example s z) -> encodeFile "output.txt" $ z ++ [v]
    Left (e,e') -> do
          error $ e'
          rip

getFileSize :: String -> IO Int
getFileSize path = getFileStatus path >>= return . fromIntegral . fileSize

With a cabal file of:

cabal-version: 1.12
name:                HaskellNixCabalStarter
version:             0.1.0.0
author:              HaskellNixCabalStarter
maintainer:          HaskellNixCabalStarter
license:             MIT
build-type:          Simple

executable app
  main-is: Main.hs
  other-modules:
      Paths_HaskellNixCabalStarter
  hs-source-dirs:
      src
  build-depends:
      base >=4.12 && <4.13
    , binary
    , process
    , random
    , unix
    , unix-compat
  default-language: Haskell2010


问:
Type mismatch: cannot convert from double [] to int []
I am trying to have the method return the new array that was made by the for loop. </p>

```<code>import java.util.Arrays;
public class stocks {

public static void main(String[] args) {

    double stockV [] = {55.6, 63.2, 68.1, 70.1, 72.4, 73.9, 71.5, 68.3, 67.1, 66.2};
    double isOverprices [] = overpriced(stockV);

}
    public int [] overpriced(double[] rsiValues)
    {
        for (int i = 0; i < rsiValues.length; i++)
        {
            if (rsiValues[i] > 70)
            {
                rsiValues[i] = 1;
            }
            else if (rsiValues[i] <= 70)
            {
                rsiValues[i] = 0;
            }
            return rsiValues;
        }
    }
 }
</code>```

答:
Change to

```<code>public double[] overpriced(double[] rsiValues)
</code>```

You are obviously returning what you pass into the method, so why do you think its kind will change?

Also, you want to return the values after the for loop has ended.

```<code>for (int i = 0; i < rsiValues.length; i++)
{
    if (rsiValues[i] > 70)
    {
        rsiValues[i] = 1;
    }
    else if (rsiValues[i] <= 70)
    {
        rsiValues[i] = 0;
    }

}
return rsiValues;
</code>```

Body:
I am trying to have the method return the new array that was made by the for loop.

import java.util.Arrays;
public class stocks {

public static void main(String[] args) {

    double stockV [] = {55.6, 63.2, 68.1, 70.1, 72.4, 73.9, 71.5, 68.3, 67.1, 66.2};
    double isOverprices [] = overpriced(stockV);

}
    public int [] overpriced(double[] rsiValues)
    {
        for (int i = 0; i < rsiValues.length; i++)
        {
            if (rsiValues[i] > 70)
            {
                rsiValues[i] = 1;
            }
            else if (rsiValues[i] <= 70)
            {
                rsiValues[i] = 0;
            }
            return rsiValues;
        }
    }
 }

Body:
Change to

public double[] overpriced(double[] rsiValues)

You are obviously returning what you pass into the method, so why do you think its kind will change?

Also, you want to return the values after the for loop has ended.

for (int i = 0; i < rsiValues.length; i++)
{
    if (rsiValues[i] > 70)
    {
        rsiValues[i] = 1;
    }
    else if (rsiValues[i] <= 70)
    {
        rsiValues[i] = 0;
    }

}
return rsiValues;


问:
SuiteScript 2 RESTlet Insufficient Permissions
I have a restlet, that returns insufficient permissions even though I have the table on the role with full permissions. The setup for this is the same as one I did yesterday and I just copied and renamed the role. That one works fine. It connects fine and I can get rid of the error by not accessing the table. The table is a custom type, ordinary columns, no segments. I have the permissions in the transactions subtab of the role, I also have 'lists" filled out, along with setup and custom record. The same setup works on my other restlet flawlessly. I can find no difference between the two aside from the tables they access. Yet I have a permissions error. Any help or insight would be appreciated thanks

Edit: Yes I do mean record type when I say table. Here is the paste from postman that gets returned

"INSUFFICIENT_PERMISSION\",\"message\":\"Permission Violation: You need a higher permission for custom record type Tower Equipment Information to access this page. Please contact your account administrator.\"

Like I said I have the role added to the restlet, I have transactions subtab, lists and setup filled out. The Record type is present in the permissions. I have done restlets before and I had one from the day before to compare to on the same instance that is fine. So I am at a loss. Thanks for your help with this.

答:
I was having the same issue when moving a script from Sandbox to Production.

What fixed it for me was setting the "Audience" on the script to allow the token user's Role. I didn't have to do this in Sandbox.


问:
How to show entries in Table_1 that have exactly n entries in Table_2?
So I'm not entirely sure how to ask this question in a general way so I'll just ask the way its been presented to me. The two relevant tables are:

```<code>Manager (
    ID: integer,
    LoginID: varchar(16),
    Name: varchar(64),
    Password: varchar(8),
    Birthday: date,
    Address: varchar(128),
    Email: varchar(32),
    PhoneNumber: char(10)
)

ManagerCertificate (
    ManagerID: integer, -- Foreign key: ManagerID references Manager(ID)
    CertificateId: integer,
    Certificate: blob
)
</code>```

Show the names and emails of every manager who has exactly 3 distinct certificates.

I've tried a few things but I keep failing.
Do I use a nested subquery, count operator maybe...

```<code>select M.Name, M.Email
from Manager M, ManagerCertificate MC
??? where MC.ManagerID = M.ID    ???
</code>```

I'm looking to be pointed in the right direction. I might be over complicating this.

Thanks

答:
I can give you an answer in Oracle SQL which you can likely translate.</p>

```<code>Select m.manager_id, m.manager_name
from managers m,
(select manager_id, count(*)
from certificates
group by manager_id
having count = 3) c
where m.manager_id = c.manager_id
</code>```

Body:
So I'm not entirely sure how to ask this question in a general way so I'll just ask the way its been presented to me. The two relevant tables are:

Manager (
    ID: integer,
    LoginID: varchar(16),
    Name: varchar(64),
    Password: varchar(8),
    Birthday: date,
    Address: varchar(128),
    Email: varchar(32),
    PhoneNumber: char(10)
)

ManagerCertificate (
    ManagerID: integer, -- Foreign key: ManagerID references Manager(ID)
    CertificateId: integer,
    Certificate: blob
)

Show the names and emails of every manager who has exactly 3 distinct certificates.

I've tried a few things but I keep failing.
Do I use a nested subquery, count operator maybe...

select M.Name, M.Email
from Manager M, ManagerCertificate MC
??? where MC.ManagerID = M.ID    ???

I'm looking to be pointed in the right direction. I might be over complicating this.

Thanks

Body:
I can give you an answer in Oracle SQL which you can likely translate.

Select m.manager_id, m.manager_name
from managers m,
(select manager_id, count(*)
from certificates
group by manager_id
having count = 3) c
where m.manager_id = c.manager_id


问:
File explorer automatically opens in Tkinter Python program
When I run my python program, the file explorer automatically opens. I would like this to only happen when the user presses the "Open" button.

Above has been solved.

The issue I am currently having, in terms of encrypting or decrypting text, is that either the upload a file functionality works or the type a string functionality. Both do not work in the same program.

I would appreciate any help.

```<code>from tkinter import *
from tkinter import filedialog

class Caesar(Frame):
    LETTERS = "abcdefghijklmnopqrstuvwxyz"

    def UploadAction(self):
        filename = filedialog.askopenfilename(initialdir="/",
                                          title="Open File",
                                          filetypes=(("Text Files", "*.txt"), ("All Files", "*.*")))

        with open('caesartest.txt') as f:
        contents = f.read().splitlines()
        contents = ' '.join(map(str, contents))
        return contents

    def __init__(self, pencere):
        Frame.__init__(self, pencere)
        self.pencere = pencere

        Label(pencere, text="Enter your message: ", relief=GROOVE, width=20).place(x=20, y=30)
        self.Ent1 = Entry(pencere, width=30)
        self.Ent1.place(x=230, y=30)

        Label(pencere, text="Upload a .txt file: ", relief=GROOVE, width=20).place(x=20, y=80)
        Button(pencere, text="Open", relief=GROOVE, font="bold", command=self.UploadAction).place(x=230, y=80)
        self.Ent3 = Entry(pencere, width=24)
        self.Ent3.place(x=280, y=80)
        self.Ent3.insert(100, self.UploadAction())

        Label(pencere, text="Enter key: ", relief=GROOVE, width=20).place(x=20, y=120)
        self.Ent2 = Entry(pencere, width=30)
        self.Ent2.place(x=230, y=120)

        Button(pencere, text="Encrypt", relief=GROOVE, font="bold", command=self.Encrypt).place(x=200, y=150)
        Button(pencere, text="Decrypt", relief=GROOVE, font="bold", command=self.Decrypt).place(x=280, y=150)

        Label(pencere, text="Result: ", relief=GROOVE, width=20).place(x=20, y=203)
        self.RESULT = Entry(pencere, width=30)
        self.RESULT.place(x=230, y=200)

    def Encrypt(self):
        key = int(self.Ent2.get())
        length = len(self.LETTERS)

        translation = ''

        text = self.Ent1.get()
        text = self.Ent3.get()
        text = re.sub('[^A-Za-z]+', '', text.lower())

        for character in text:
            if character in self.LETTERS:
                sayı = self.LETTERS.find(character)
                sayı = (sayı + key) % length
                translation += self.LETTERS[sayı]
            else:
                translation += character

        self.RESULT.delete(0, END)
        self.RESULT.insert(0, translation)

    def Decrypt(self):
        key = int(self.Ent2.get())
        length = len(self.LETTERS)

        translation = ''

        text = self.RESULT.get()
        text = re.sub('[^A-Za-z]+', '', text.lower())

        for character in text:
            if character in self.LETTERS:
                sayı = self.LETTERS.find(character)
                sayı = (sayı - key) % length
                translation += self.LETTERS[sayı]
            else:
                translation += character

        self.RESULT.delete(0, END)
        self.RESULT.insert(0, translation)

if __name__ == "__main__":
    root = Tk()
    root.title("Caesar")
    root.geometry("580x280+70+70")
    Caesar(root).pack(side="top", fill="both")
    root.mainloop()
</code>```

答:
As for me problem is because you use

```<code>    self.Ent3.insert(100, self.UploadAction())
</code>```

inside __init__ so it executes UploadAction() at start, not when you press button.

You have to use insert inside UploadAction() which is executed by button.

```<code>def UploadAction(self):
    filename = filedialog.askopenfilename(initialdir="/",
                                      title="Open File",
                                      filetypes=(("Text Files", "*.txt"), ("All Files", "*.*")))

    if filename:
        with open('caesartest.txt') as f:
            contents = f.read().splitlines()
            contents = ' '.join(map(str, contents))
        self.Ent3.insert(100, content) # <-- use it

    # return contents # useless when used with `Button`

def __init__(self, pencere):
    Frame.__init__(self, pencere)
    self.pencere = pencere

    Label(pencere, text="Enter your message: ", relief=GROOVE, width=20).place(x=20, y=30)
    self.Ent1 = Entry(pencere, width=30)
    self.Ent1.place(x=230, y=30)

    Label(pencere, text="Upload a .txt file: ", relief=GROOVE, width=20).place(x=20, y=80)
    Button(pencere, text="Open", relief=GROOVE, font="bold", command=self.UploadAction).place(x=230, y=80)
    self.Ent3 = Entry(pencere, width=24)

    self.Ent3.place(x=280, y=80)

    # self.Ent3.insert(100, self.UploadAction()) # <-- don't do this
</code>```

Body:
When I run my python program, the file explorer automatically opens. I would like this to only happen when the user presses the "Open" button.

Above has been solved.

The issue I am currently having, in terms of encrypting or decrypting text, is that either the upload a file functionality works or the type a string functionality. Both do not work in the same program.

I would appreciate any help.

from tkinter import *
from tkinter import filedialog

class Caesar(Frame):
    LETTERS = "abcdefghijklmnopqrstuvwxyz"

    def UploadAction(self):
        filename = filedialog.askopenfilename(initialdir="/",
                                          title="Open File",
                                          filetypes=(("Text Files", "*.txt"), ("All Files", "*.*")))

        with open('caesartest.txt') as f:
        contents = f.read().splitlines()
        contents = ' '.join(map(str, contents))
        return contents

    def __init__(self, pencere):
        Frame.__init__(self, pencere)
        self.pencere = pencere

        Label(pencere, text="Enter your message: ", relief=GROOVE, width=20).place(x=20, y=30)
        self.Ent1 = Entry(pencere, width=30)
        self.Ent1.place(x=230, y=30)

        Label(pencere, text="Upload a .txt file: ", relief=GROOVE, width=20).place(x=20, y=80)
        Button(pencere, text="Open", relief=GROOVE, font="bold", command=self.UploadAction).place(x=230, y=80)
        self.Ent3 = Entry(pencere, width=24)
        self.Ent3.place(x=280, y=80)
        self.Ent3.insert(100, self.UploadAction())

        Label(pencere, text="Enter key: ", relief=GROOVE, width=20).place(x=20, y=120)
        self.Ent2 = Entry(pencere, width=30)
        self.Ent2.place(x=230, y=120)

        Button(pencere, text="Encrypt", relief=GROOVE, font="bold", command=self.Encrypt).place(x=200, y=150)
        Button(pencere, text="Decrypt", relief=GROOVE, font="bold", command=self.Decrypt).place(x=280, y=150)

        Label(pencere, text="Result: ", relief=GROOVE, width=20).place(x=20, y=203)
        self.RESULT = Entry(pencere, width=30)
        self.RESULT.place(x=230, y=200)

    def Encrypt(self):
        key = int(self.Ent2.get())
        length = len(self.LETTERS)

        translation = ''

        text = self.Ent1.get()
        text = self.Ent3.get()
        text = re.sub('[^A-Za-z]+', '', text.lower())

        for character in text:
            if character in self.LETTERS:
                sayı = self.LETTERS.find(character)
                sayı = (sayı + key) % length
                translation += self.LETTERS[sayı]
            else:
                translation += character

        self.RESULT.delete(0, END)
        self.RESULT.insert(0, translation)

    def Decrypt(self):
        key = int(self.Ent2.get())
        length = len(self.LETTERS)

        translation = ''

        text = self.RESULT.get()
        text = re.sub('[^A-Za-z]+', '', text.lower())

        for character in text:
            if character in self.LETTERS:
                sayı = self.LETTERS.find(character)
                sayı = (sayı - key) % length
                translation += self.LETTERS[sayı]
            else:
                translation += character

        self.RESULT.delete(0, END)
        self.RESULT.insert(0, translation)

if __name__ == "__main__":
    root = Tk()
    root.title("Caesar")
    root.geometry("580x280+70+70")
    Caesar(root).pack(side="top", fill="both")
    root.mainloop()

Body:
As for me problem is because you use

    self.Ent3.insert(100, self.UploadAction())

inside __init__ so it executes UploadAction() at start, not when you press button.

You have to use insert inside UploadAction() which is executed by button.

def UploadAction(self):
    filename = filedialog.askopenfilename(initialdir="/",
                                      title="Open File",
                                      filetypes=(("Text Files", "*.txt"), ("All Files", "*.*")))

    if filename:
        with open('caesartest.txt') as f:
            contents = f.read().splitlines()
            contents = ' '.join(map(str, contents))
        self.Ent3.insert(100, content) # <-- use it

    # return contents # useless when used with `Button`

def __init__(self, pencere):
    Frame.__init__(self, pencere)
    self.pencere = pencere

    Label(pencere, text="Enter your message: ", relief=GROOVE, width=20).place(x=20, y=30)
    self.Ent1 = Entry(pencere, width=30)
    self.Ent1.place(x=230, y=30)

    Label(pencere, text="Upload a .txt file: ", relief=GROOVE, width=20).place(x=20, y=80)
    Button(pencere, text="Open", relief=GROOVE, font="bold", command=self.UploadAction).place(x=230, y=80)
    self.Ent3 = Entry(pencere, width=24)

    self.Ent3.place(x=280, y=80)

    # self.Ent3.insert(100, self.UploadAction()) # <-- don't do this


问:
Error - ''Uncaught TypeError: Cannot read property 'length"? of undefined''
I'm currently learning Javascript and they want me to build a Rock, paper and scissors game.

Here's the code I have so far:

```<code>let computerPlay = (array) => {
  return array[Math.floor(Math.random() *
  array.length)]
}

const array = (["Rock", "Paper", "Scissors"])
console.log(computerPlay(array))

let singleRound = (playerSelection,
computerSelection) => {

if ( playerSelection == "rock" || playerSelection
== "Paper" ||
playerSelection == "scissors") {
  computerSelection = computerPlay
} else if (playerSelection == null) {
  "Canceled"
}

}

let playerSelection = prompt("What do you
select?")
const computerSelection = computerPlay()
</code>```

Thank You

答:
Function Definition:

let computerPlay = (array) => { //... }

Calling The Funciton:

Remember computerPlay requires an array as a parameter when you call it.

computerPlay(YOUR_ARRAY_HERE);

Body:
I'm currently learning Javascript and they want me to build a Rock, paper and scissors game.

Here's the code I have so far:

let computerPlay = (array) => {
  return array[Math.floor(Math.random() *
  array.length)]
}

const array = (["Rock", "Paper", "Scissors"])
console.log(computerPlay(array))

let singleRound = (playerSelection,
computerSelection) => {

if ( playerSelection == "rock" || playerSelection
== "Paper" ||
playerSelection == "scissors") {
  computerSelection = computerPlay
} else if (playerSelection == null) {
  "Canceled"
}

}

let playerSelection = prompt("What do you
select?")
const computerSelection = computerPlay()

Thank You


问:
How to pass a variable from views to base.html in Django?
I want to show the user's first name on the navbar of my project. This navbar is on the base.html file.

In my views.py I have created a variable that does this

```<code>def base(request):
    user = request.user
    u = User.objects.get(username=user)
    us = u.clients.first_name
    context = {'u': u, 'us': us}
    return render(request, "backend/base.html", context)
</code>```

I can get it to work on any other .html file, but not on the base.html, that looks like this

```<code><span class="mb-0 text-sm  font-weight-bold">{{us}}</span>
</code>```

This is my model

```<code>class Clients(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    first_name = models.CharField(max_length=30, verbose_name="Primeiro Nome")
    last_name = models.CharField(max_length=30, verbose_name="Apelido")
    address = models.CharField(max_length=200, verbose_name="Morada")
    nif = models.CharField(max_length=9, verbose_name="NIF", validators=[RegexValidator(r'^\d{1,10}$')], primary_key=True)
    mobile = models.CharField(max_length=9, verbose_name="Telemóvel", validators=[RegexValidator(r'^\d{1,10}$')])
    email = models.CharField(max_length=200, null=True, verbose_name="Email")

    def __str__(self):
        return "%s %s" % (self.first_name, self.last_name)

    class Meta:
        verbose_name_plural = "Clientes"
</code>```

答:
I am answering my own question.

I was able to solve this by creating a context_processor.py with the following code

```<code>from .models import Clients, Hotels, Trip, Flight
from django.contrib.auth.models import User

def add_variable_to_context(request):
    user = request.user
    u = User.objects.get(username=user)
    us = u.clients.first_name
    uv = u.clients.avatar
    return {
        'u': u,
        'us': us,
        'uv': uv
    }
</code>```

Body:
I want to show the user's first name on the navbar of my project. This navbar is on the base.html file.

In my views.py I have created a variable that does this

def base(request):
    user = request.user
    u = User.objects.get(username=user)
    us = u.clients.first_name
    context = {'u': u, 'us': us}
    return render(request, "backend/base.html", context)

I can get it to work on any other .html file, but not on the base.html, that looks like this

{{us}}

This is my model

class Clients(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    first_name = models.CharField(max_length=30, verbose_name="Primeiro Nome")
    last_name = models.CharField(max_length=30, verbose_name="Apelido")
    address = models.CharField(max_length=200, verbose_name="Morada")
    nif = models.CharField(max_length=9, verbose_name="NIF", validators=[RegexValidator(r'^\d{1,10}$')], primary_key=True)
    mobile = models.CharField(max_length=9, verbose_name="Telemóvel", validators=[RegexValidator(r'^\d{1,10}$')])
    email = models.CharField(max_length=200, null=True, verbose_name="Email")

    def __str__(self):
        return "%s %s" % (self.first_name, self.last_name)

    class Meta:
        verbose_name_plural = "Clientes"

Body:
I am answering my own question.

I was able to solve this by creating a context_processor.py with the following code

from .models import Clients, Hotels, Trip, Flight
from django.contrib.auth.models import User

def add_variable_to_context(request):
    user = request.user
    u = User.objects.get(username=user)
    us = u.clients.first_name
    uv = u.clients.avatar
    return {
        'u': u,
        'us': us,
        'uv': uv
    }


问:
Skip a sql statement from replication (Mysql) ? [ Disables or enables binary logging for the current session ]
I want to do some inserts on a table (master mysql DB) but I dont want to replicate without effecting the replication process. </p>

答: SET sql_log_bin = {0|1} Disables or enables binary logging for the current session (sql_log_bin is a session variable) if the client has the SUPER privilege. The statement fails with an error if the client does not have that privilege</p>


答:
A JOIN with COUNT is one way to do this, grouping on the manager name and email and checking (using HAVING) that the manager has exactly 3 distinct certificates. Note that MySQL < 5.7 would allow you to group on M.ID but it is preferable to write queries that will still work on later versions). Also note that explicit JOIN syntax (with an ON clause) is preferred to the old-style comma joins.

```<code>SELECT M.Name, M.Email
FROM Manager M
JOIN ManagerCertificate MC ON MC.ManagerID = M.ID
GROUP BY M.Name, M.Email
HAVING COUNT(DISTINCT MC.CertificateId) = 3
</code>```

Title: How to show entries in Table_1 that have exactly n entries in Table_2?

Body:
A JOIN with COUNT is one way to do this, grouping on the manager name and email and checking (using HAVING) that the manager has exactly 3 distinct certificates. Note that MySQL < 5.7 would allow you to group on M.ID but it is preferable to write queries that will still work on later versions). Also note that explicit JOIN syntax (with an ON clause) is preferred to the old-style comma joins.

SELECT M.Name, M.Email
FROM Manager M
JOIN ManagerCertificate MC ON MC.ManagerID = M.ID
GROUP BY M.Name, M.Email
HAVING COUNT(DISTINCT MC.CertificateId) = 3


答:
I like using a subquery and COUNT(DISTINCT) here.

```<code>SELECT
    M.Name
    , M.Email
FROM Manager M
INNER JOIN (
            SELECT ManagerID
            FROM ManagerCertificate MC
            GROUP BY ManagerID
            HAVING COUNT(DISTINCT CertificateId) = 3
            ) C
    ON M.ManagerID = C.ManagerID;
</code>```

Body:
I like using a subquery and COUNT(DISTINCT) here.

SELECT
    M.Name
    , M.Email
FROM Manager M
INNER JOIN (
            SELECT ManagerID
            FROM ManagerCertificate MC
            GROUP BY ManagerID
            HAVING COUNT(DISTINCT CertificateId) = 3
            ) C
    ON M.ManagerID = C.ManagerID;


问:
Clear Fragment Backstack except top fragment
In my app I have some menu items in a Navigation Drawer. When the user taps one of these items and navigates to the corresponding fragment, I want the fragment backstack to be cleared EXCEPT for the fragment they just navigated to. Let me illustrate:

In my nav drawer the user has options to open fragments F1, F2, F3, F4, F5, F6. When the app is first opened, the user starts on F1. Let's say from F1, the user opens fragments F7 -> F8 -> F9 -> F10 using buttons within the fragment views themselves. At this point, the backstack looks like:

F1 -> F7 -> F8 -> F9 -> F10

Suppose from here, the user opens the nav drawer and selects F2. What I want to happen is that the above backstack is cleared and is populated with ONLY F2, so that they user can't go back to F10 from F2. In otherwords, the backstack should become:

Not this: F1 -> F7 -> F8 -> F9 -> F10 -> F2

But this: F2

How can I accomplish this?

EDIT 1:
One of my attempted solutions was to add an OnNavigationItemSelectedListener to the navigationView when the activity is loading that would clear the backstack when one of the items was pressed. My solution worked, but in the process I overrode the default code that actually changes to the new fragment. I snooped through the Android API and found this:

navigationView.setNavigationItemSelectedListener(
    new NavigationView.OnNavigationItemSelectedListener() {
    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        boolean handled = onNavDestinationSelected(item, navController);
        if (handled) {
            ViewParent parent = navigationView.getParent();
            if (parent instanceof DrawerLayout) {
                ((DrawerLayout) parent).closeDrawer(navigationView);
            } else {
                BottomSheetBehavior bottomSheetBehavior =
                                    findBottomSheetBehavior(navigationView);
                if (bottomSheetBehavior != null) {
                     bottomSheetBehavior.setState(BottomSheetBehavior.STATE_HIDDEN);
                }
            }
        }
        return handled;
    }
});
```

This is NOT my code. This is the native code that handles selection of menu items on the navigation drawer (found in the NavigationUI class). If I want to add my own OnNavigationItemSelectedListener I would have to recreate the functionality shown above, which I can't do since some of the methods in there are protected. So that's why I don't believe this solution will work.

答:
You can try to clear fragments which are in backstack</p>

```<code>FragmentManager manager = getSupportFragmentManager();
if (manager.getBackStackEntryCount() > 0) {
    FragmentManager.BackStackEntry first = manager.getBackStackEntryAt(0);
     manager.popBackStack(first.getId(), FragmentManager.POP_BACK_STACK_INCLUSIVE);
}
</code>```

Body:
In my app I have some menu items in a Navigation Drawer. When the user taps one of these items and navigates to the corresponding fragment, I want the fragment backstack to be cleared EXCEPT for the fragment they just navigated to. Let me illustrate:

In my nav drawer the user has options to open fragments F1, F2, F3, F4, F5, F6. When the app is first opened, the user starts on F1. Let's say from F1, the user opens fragments F7 -> F8 -> F9 -> F10 using buttons within the fragment views themselves. At this point, the backstack looks like:

F1 -> F7 -> F8 -> F9 -> F10

Suppose from here, the user opens the nav drawer and selects F2. What I want to happen is that the above backstack is cleared and is populated with ONLY F2, so that they user can't go back to F10 from F2. In otherwords, the backstack should become:

Not this: F1 -> F7 -> F8 -> F9 -> F10 -> F2

But this: F2

How can I accomplish this?

EDIT 1:
One of my attempted solutions was to add an OnNavigationItemSelectedListener to the navigationView when the activity is loading that would clear the backstack when one of the items was pressed. My solution worked, but in the process I overrode the default code that actually changes to the new fragment. I snooped through the Android API and found this:

navigationView.setNavigationItemSelectedListener(
    new NavigationView.OnNavigationItemSelectedListener() {
    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        boolean handled = onNavDestinationSelected(item, navController);
        if (handled) {
            ViewParent parent = navigationView.getParent();
            if (parent instanceof DrawerLayout) {
                ((DrawerLayout) parent).closeDrawer(navigationView);
            } else {
                BottomSheetBehavior bottomSheetBehavior =
                                    findBottomSheetBehavior(navigationView);
                if (bottomSheetBehavior != null) {
                     bottomSheetBehavior.setState(BottomSheetBehavior.STATE_HIDDEN);
                }
            }
        }
        return handled;
    }
});

This is NOT my code. This is the native code that handles selection of menu items on the navigation drawer (found in the NavigationUI class). If I want to add my own OnNavigationItemSelectedListener I would have to recreate the functionality shown above, which I can't do since some of the methods in there are protected. So that's why I don't believe this solution will work.

Body:
You can try to clear fragments which are in backstack

FragmentManager manager = getSupportFragmentManager();
if (manager.getBackStackEntryCount() > 0) {
    FragmentManager.BackStackEntry first = manager.getBackStackEntryAt(0);
     manager.popBackStack(first.getId(), FragmentManager.POP_BACK_STACK_INCLUSIVE);
}


问:
There is some error while signing in PlatformException(ERROR_ADMIN_RESTRICTED_OPERATION, This operation is restricted to administrators only., null)
I'm new in firebase I am trying to authenticate user by using anonymous authentication of firebase but it giving the following error.

The example code is here:

Authenticating dart file.

```<code>class AuthServices {
  final FirebaseAuth _auth = FirebaseAuth.instance;

  //sign in method.
  Future signningAnon() async {
    try {
      AuthResult result = await _auth.signInAnonymously();
      FirebaseUser user = result.user;
      return user;
    } catch (e) {
      print("There is some error while singing $e");
      return null;
    }
  }
}

</code>```

Main file:

```<code>void main() {
  AuthServices _auth = AuthServices();
  runApp(MaterialApp(
    title: 'chekcing firbase authentication',
    home: Scaffold(
      backgroundColor: Colors.blueAccent,
        appBar: AppBar(
          title: Text("Firbase authentication"),
        ),
        body: Center(
          child: RaisedButton(
            color: Colors.white,
            child: Text('click me'),
            onPressed: () async{
              print("object");
              dynamic result = await _auth.signningAnon();
              print('result is $result');
            },
          ),
        )),
  ));
}
</code>```

here is yaml dependency file.

```<code>dependencies:
  flutter:
    sdk: flutter

  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^0.1.2
  toast: ^0.1.5
  rflutter_alert: ^1.0.3
  timeline_list: ^0.0.3
  font_awesome_flutter: ^8.5.0
  carousel_slider: ^1.3.1
  photo_view: ^0.8.0
  url_launcher: ^5.4.1
  get_it: ^3.1.0
  flutter_compass: ^0.3.4
  firebase_auth: ^0.15.3 // here is firebase dependency.
  cloud_firestore: ^0.13.0+1

</code>```

If, someone has a solution please help.

答: You need to add the anonymous sign in option in the Firebase Authentication section of the console. Where you have setup your project.</p>

Body:
I'm new in firebase I am trying to authenticate user by using anonymous authentication of firebase but it giving the following error.

The example code is here:

Authenticating dart file.

class AuthServices {
  final FirebaseAuth _auth = FirebaseAuth.instance;

  //sign in method.
  Future signningAnon() async {
    try {
      AuthResult result = await _auth.signInAnonymously();
      FirebaseUser user = result.user;
      return user;
    } catch (e) {
      print("There is some error while singing $e");
      return null;
    }
  }
}

Main file:

void main() {
  AuthServices _auth = AuthServices();
  runApp(MaterialApp(
    title: 'chekcing firbase authentication',
    home: Scaffold(
      backgroundColor: Colors.blueAccent,
        appBar: AppBar(
          title: Text("Firbase authentication"),
        ),
        body: Center(
          child: RaisedButton(
            color: Colors.white,
            child: Text('click me'),
            onPressed: () async{
              print("object");
              dynamic result = await _auth.signningAnon();
              print('result is $result');
            },
          ),
        )),
  ));
}

here is yaml dependency file.

dependencies:
  flutter:
    sdk: flutter

  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^0.1.2
  toast: ^0.1.5
  rflutter_alert: ^1.0.3
  timeline_list: ^0.0.3
  font_awesome_flutter: ^8.5.0
  carousel_slider: ^1.3.1
  photo_view: ^0.8.0
  url_launcher: ^5.4.1
  get_it: ^3.1.0
  flutter_compass: ^0.3.4
  firebase_auth: ^0.15.3 // here is firebase dependency.
  cloud_firestore: ^0.13.0+1

If, someone has a solution please help.


问:
pyCharm cant access packages directory
I have created a new pyCharm file and im trying to bring in my anaconda 3.7 environment (that ive been using for Jupyter) that has all my packages. But for some reason the only packages that are brought in a few random ones. First image shows PyCharm interpreter the second the folder directory with all my packages.

How do i tell Pycharm

use this version of python

and use this specific directory's packages

答:
add modules in pycharm from a specific directory

import sys

sys.path.insert(0, 'C:/Users/MyNAME/Anaconda3/Lib/site-packages')

import a whole package

import pandas as pd

import sub-module

from arcgis.gis import GIS

Title: pyCharm cant access packages directory


问:
Adding IoT rule with an error action through cloudformation yaml
I am trying to add an iot rule with error action using following cloudformation yaml file

extract from yaml:

```<code> DaIoTRule:
    Type: AWS::IoT::TopicRule
    Properties:
      RuleName: sda
      TopicRulePayload:
        RuleDisabled: false
        Sql: SELECT *, topic(2) AS source FROM 'topic/sensors/+'
        Actions:
          - Lambda:
              FunctionArn: !GetAtt LambdaFunction.Arn
        ErrorAction:
          S3:
            RoleArn: !GetAtt DAIoTRuleErrorActionIamRole.Arn
            Bucket: iot-message-dump
            Key: "errors/${topic()}/${timestamp()}"
</code>```

But I keep getting this error:

```<code>{
            "StackId": "arn:aws:cloudformation:us-east-1:961234632786:stack/wx-da-lambda/91423s00-4e97-11ea-aedd-0ee829hbc650",
            "EventId": "DAIoTRule-CREATE_FAILED-2020-02-17T06:51:38.299Z",
            "StackName": "da-lambda",
            "LogicalResourceId": "DaIoTRule",
            "PhysicalResourceId": "",
            "ResourceType": "AWS::IoT::TopicRule",
            "Timestamp": "2020-02-17T06:51:38.299Z",
            "ResourceStatus": "CREATE_FAILED",
            "ResourceStatusReason": "Encountered unsupported property bucket"
        }
</code>```

I created this yaml using https://docs.aws.amazon.com/iot/latest/developerguide/rule-error-handling.html as reference.

Can someone point me to what I am doing wrong ?

答:
CloudFormation uses the BucketName property instead of Bucket for S3 actions (including error actions).

See https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-s3action.html#cfn-iot-topicrule-s3action-bucketname

Body:
I am trying to add an iot rule with error action using following cloudformation yaml file

extract from yaml:

 DaIoTRule:
    Type: AWS::IoT::TopicRule
    Properties:
      RuleName: sda
      TopicRulePayload:
        RuleDisabled: false
        Sql: SELECT *, topic(2) AS source FROM 'topic/sensors/+'
        Actions:
          - Lambda:
              FunctionArn: !GetAtt LambdaFunction.Arn
        ErrorAction:
          S3:
            RoleArn: !GetAtt DAIoTRuleErrorActionIamRole.Arn
            Bucket: iot-message-dump
            Key: "errors/${topic()}/${timestamp()}"

But I keep getting this error:

{
            "StackId": "arn:aws:cloudformation:us-east-1:961234632786:stack/wx-da-lambda/91423s00-4e97-11ea-aedd-0ee829hbc650",
            "EventId": "DAIoTRule-CREATE_FAILED-2020-02-17T06:51:38.299Z",
            "StackName": "da-lambda",
            "LogicalResourceId": "DaIoTRule",
            "PhysicalResourceId": "",
            "ResourceType": "AWS::IoT::TopicRule",
            "Timestamp": "2020-02-17T06:51:38.299Z",
            "ResourceStatus": "CREATE_FAILED",
            "ResourceStatusReason": "Encountered unsupported property bucket"
        }

I created this yaml using https://docs.aws.amazon.com/iot/latest/developerguide/rule-error-handling.html as reference.

Can someone point me to what I am doing wrong ?


问:
Password change jQuery validation error message does not appear
I face a problem when I enter wrong matching password - the jQuery validation error message not appear.

```<code>jQuery.validator.setDefaults({
    debug: true,
    success: "valid"
});

$('#passwordchange').validate({
    rules:{
        newpass:{
            required: true
        },
        retypepass:{
            required:true,
            equalto: '#newpassword'
        }
    },
    messages:{
        retypepass:{
            equalto:"should enter matching pass"
        }
    }
});
</code>```

Here is the full code on codepen

答:
AS @Azametzin's comment and the document, You should use equalTo instead of equalto

Syntax

equalTo( other )    Returns: Boolean

Description: Requires the element
  to be the same as another one

jQuery.validator.setDefaults({
  debug: true,
  success: "valid"
});

$('#passwordchange').validate({
        rules:{
            newpass:{
                required: true
            },
            retypepass:{
                required:true,
                equalTo: '#newpassword'
            }
        },
  messages:{
    retypepass:{
      equalTo:"should enter matching pass"
    }
  }
    });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jquery-validation@1.19.1/dist/jquery.validate.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/additional-methods.min.js"></script>

<form method="GET" action="" id="passwordchange">
     <div class="form-row">
         <div class="form-group row no-gutters col-12">
           <label for="newpassword" class="col-md-3">كلمة المرور الجديدة</label>
           <div class="col-md-9">
             <input type="password" class="form-control" id="newpassword" name="newpass" placeholder="GHIBKL@$*132581">
           </div>
       </div>

  </div>
  <div class="form-row">
    <div class="form-group row no-gutters col-12">
      <label for="retype" class="col-md-3">إعادة كلمة المرور</label>
      <div class="col-md-9">
        <input type="password" class="form-control" id="retype" name="retypepass" placeholder="GHIBKL@$*132581">
      </div>
    </div>

  </div>
  <button type="submit">submit</button>

</form></code>```

Body:
I face a problem when I enter wrong matching password - the jQuery validation error message not appear.

jQuery.validator.setDefaults({
    debug: true,
    success: "valid"
});

$('#passwordchange').validate({
    rules:{
        newpass:{
            required: true
        },
        retypepass:{
            required:true,
            equalto: '#newpassword'
        }
    },
    messages:{
        retypepass:{
            equalto:"should enter matching pass"
        }
    }
});

Here is the full code on codepen

Body:
AS @Azametzin's comment and the document, You should use equalTo instead of equalto

Syntax

equalTo( other )    Returns: Boolean

Description: Requires the element
  to be the same as another one

jQuery.validator.setDefaults({
  debug: true,
  success: "valid"
});

$('#passwordchange').validate({
        rules:{
            newpass:{
                required: true
            },
            retypepass:{
                required:true,
                equalTo: '#newpassword'
            }
        },
  messages:{
    retypepass:{
      equalTo:"should enter matching pass"
    }
  }
    });

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jquery-validation@1.19.1/dist/jquery.validate.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.16.0/additional-methods.min.js"></script>

<form method="GET" action="" id="passwordchange">
     <div class="form-row">
         <div class="form-group row no-gutters col-12">
           <label for="newpassword" class="col-md-3">كلمة المرور الجديدة</label>
           <div class="col-md-9">
             <input type="password" class="form-control" id="newpassword" name="newpass" placeholder="GHIBKL@$*132581">
           </div>
       </div>

  </div>
  <div class="form-row">
    <div class="form-group row no-gutters col-12">
      <label for="retype" class="col-md-3">إعادة كلمة المرور</label>
      <div class="col-md-9">
        <input type="password" class="form-control" id="retype" name="retypepass" placeholder="GHIBKL@$*132581">
      </div>
    </div>

  </div>
  <button type="submit">submit</button>

</form>


问:
How do I build 32-bit binaries with Red Hat Developer Toolset?
I can't find any documentation whatsoever on how to target 32-bit with Red Hat Developer Toolset (version 9.0 in this case running on CentOS 7). The release notes mention:

Generation and manipulation of 32-bit binaries is also supported

It also ships the needed 32-bit libraries in:

```<code>/opt/rh/devtoolset-9/root/usr/lib/gcc/x86_64-redhat-linux/9/32/
</code>```

However, building fails. Example trying to build a minimal int main() {} program:

```<code>$ scl enable devtoolset-9 'g++ -m32 tst.cpp'
/opt/rh/devtoolset-9/root/usr/libexec/gcc/x86_64-redhat-linux/9/ld: skipping incompatible /opt/rh/devtoolset-9/root/usr/lib/gcc/x86_64-redhat-linux/9/libstdc++_nonshared.a when searching for -lstdc++_nonshared
/opt/rh/devtoolset-9/root/usr/libexec/gcc/x86_64-redhat-linux/9/ld: cannot find -lstdc++_nonshared
collect2: error: ld returned 1 exit status
</code>```

The library it fails to find actually exists though:

```<code>/opt/rh/devtoolset-9/root/usr/lib/gcc/x86_64-redhat-linux/9/32/libstdc++_nonshared.a
</code>```

No amount of -L flags fixes it (and it would be the wrong solution anyway; the linker should not even be attempting to load 64-bit libraries in -m32 mode.)

What am I missing here?

答:
I guess you didn't notice that /opt/rh/devtoolset-9/root/usr/lib/gcc/x86_64-redhat-linux/9/32/libstdc++_nonshared.a is quite likely a dangling symlink:

```<code>$ file /opt/rh/devtoolset-9/root/usr/lib/gcc/x86_64-redhat-linux/9/32/libstdc++_nonshared.a
/opt/rh/devtoolset-9/root/usr/lib/gcc/x86_64-redhat-linux/9/32/libstdc++_nonshared.a: broken symbolic link to `../../../i686-redhat-linux/9/libstdc++_nonshared.a'
$
</code>```

The destination file /opt/rh/devtoolset-9/root/usr/lib/gcc/i686-redhat-linux/9/libstdc++_nonshared.a is however unfortunately not provided by any CentOS package (but it should be in devtoolset-9-libstdc++-devel.i686). Thus it's likely a CentOS-specific packaging mistake as RHEA-2019:4134 provides the questioned package devtoolset-9-libstdc++-devel-9.1.1-2.6.el7.i686.rpm for Red Hat Enterprise Linux 7 including the desired file (explicitly verified by yum install /opt/rh/devtoolset-9/root/usr/lib/gcc/i686-redhat-linux/9/libstdc++_nonshared.a on RHEL 7).

Body:
I can't find any documentation whatsoever on how to target 32-bit with Red Hat Developer Toolset (version 9.0 in this case running on CentOS 7). The release notes mention:

Generation and manipulation of 32-bit binaries is also supported

It also ships the needed 32-bit libraries in:

/opt/rh/devtoolset-9/root/usr/lib/gcc/x86_64-redhat-linux/9/32/

However, building fails. Example trying to build a minimal int main() {} program:

$ scl enable devtoolset-9 'g++ -m32 tst.cpp'
/opt/rh/devtoolset-9/root/usr/libexec/gcc/x86_64-redhat-linux/9/ld: skipping incompatible /opt/rh/devtoolset-9/root/usr/lib/gcc/x86_64-redhat-linux/9/libstdc++_nonshared.a when searching for -lstdc++_nonshared
/opt/rh/devtoolset-9/root/usr/libexec/gcc/x86_64-redhat-linux/9/ld: cannot find -lstdc++_nonshared
collect2: error: ld returned 1 exit status

The library it fails to find actually exists though:

/opt/rh/devtoolset-9/root/usr/lib/gcc/x86_64-redhat-linux/9/32/libstdc++_nonshared.a

No amount of -L flags fixes it (and it would be the wrong solution anyway; the linker should not even be attempting to load 64-bit libraries in -m32 mode.)

What am I missing here?

Body:
I guess you didn't notice that /opt/rh/devtoolset-9/root/usr/lib/gcc/x86_64-redhat-linux/9/32/libstdc++_nonshared.a is quite likely a dangling symlink:

$ file /opt/rh/devtoolset-9/root/usr/lib/gcc/x86_64-redhat-linux/9/32/libstdc++_nonshared.a
/opt/rh/devtoolset-9/root/usr/lib/gcc/x86_64-redhat-linux/9/32/libstdc++_nonshared.a: broken symbolic link to `../../../i686-redhat-linux/9/libstdc++_nonshared.a'
$

The destination file /opt/rh/devtoolset-9/root/usr/lib/gcc/i686-redhat-linux/9/libstdc++_nonshared.a is however unfortunately not provided by any CentOS package (but it should be in devtoolset-9-libstdc++-devel.i686). Thus it's likely a CentOS-specific packaging mistake as RHEA-2019:4134 provides the questioned package devtoolset-9-libstdc++-devel-9.1.1-2.6.el7.i686.rpm for Red Hat Enterprise Linux 7 including the desired file (explicitly verified by yum install /opt/rh/devtoolset-9/root/usr/lib/gcc/i686-redhat-linux/9/libstdc++_nonshared.a on RHEL 7).


问:
Data Table Solution In R To Find Group Min/Max
Data

```<code>data=data.frame("student"=c(1,1,1,2,2,2,3,3,3),
                "score"=c(NA,7,6,6,1,4,8,NA,3),
                "min"=c(6,6,6,1,1,1,3,3,3),
                "max"=c(7,7,7,6,6,6,8,8,8))
</code>```

I have columns 'student' and 'score' and wish to use data.table to create 'min' and 'max' which simply put are the minimum and maximum values for each student IGNORING NA Values. If all values are NA then simply list 'NA' as the min/max.

答:
You can do this using the function ave:

```<code>data=data.frame("student"=c(1,1,1,2,2,2,3,3,3),
                "score"=c(NA,7,6,6,1,4,8,NA,3))

data$min = ave(data$score, data$student, FUN = function(x){ min(x, na.rm = T) })
data$max = ave(data$score, data$student, FUN = function(x){ max(x, na.rm = T) })
</code>```

Result:

```<code>> data
  student score min max
1       1    NA   6   7
2       1     7   6   7
3       1     6   6   7
4       2     6   1   6
5       2     1   1   6
6       2     4   1   6
7       3     8   3   8
8       3    NA   3   8
9       3     3   3   8
</code>```

The function ave takes a numeric vector as the first parameter and all following vectors are the grouping variables. The FUN parameter is the function you wish to apply.

Body:
Data

data=data.frame("student"=c(1,1,1,2,2,2,3,3,3),
                "score"=c(NA,7,6,6,1,4,8,NA,3),
                "min"=c(6,6,6,1,1,1,3,3,3),
                "max"=c(7,7,7,6,6,6,8,8,8))

I have columns 'student' and 'score' and wish to use data.table to create 'min' and 'max' which simply put are the minimum and maximum values for each student IGNORING NA Values. If all values are NA then simply list 'NA' as the min/max.

Body:
You can do this using the function ave:

data=data.frame("student"=c(1,1,1,2,2,2,3,3,3),
                "score"=c(NA,7,6,6,1,4,8,NA,3))

data$min = ave(data$score, data$student, FUN = function(x){ min(x, na.rm = T) })
data$max = ave(data$score, data$student, FUN = function(x){ max(x, na.rm = T) })

Result:

> data
  student score min max
1       1    NA   6   7
2       1     7   6   7
3       1     6   6   7
4       2     6   1   6
5       2     1   1   6
6       2     4   1   6
7       3     8   3   8
8       3    NA   3   8
9       3     3   3   8

The function ave takes a numeric vector as the first parameter and all following vectors are the grouping variables. The FUN parameter is the function you wish to apply.


问:
git repo in a git repo? (non submodule)
```<code>.git // <-- pushed to bitbucket
  |- gulpfile.js // <-- process src files to dist files
  |- ...(more files)
  |- src
      |- ...(more files)
  |- dist
      |- .git // <-- pushed to server
      |- ...(more files)
</code>```

Anyway for a git repo to include another git repo in it? I have a development structure which uses gulp to process it to a dist directory, in that directory sits a git repo which I am able to push to my server.

I know that submodule exists however that requires me to upload the dist .git to a remote repo. I do not need a centralized repo for this one, it feels like overkill, I just need to upload the files to the server in different versions.

So is this possible? If not how do developers tackle this workflow I am using?

答: If you don't know how to use submodule, you can set one git repo as a compressed package to avoid git conflict，but there should be a better method.</p>

Title: git repo in a git repo? (non submodule)

Body:
.git // <-- pushed to bitbucket
  |- gulpfile.js // <-- process src files to dist files
  |- ...(more files)
  |- src
      |- ...(more files)
  |- dist
      |- .git // <-- pushed to server
      |- ...(more files)

Anyway for a git repo to include another git repo in it? I have a development structure which uses gulp to process it to a dist directory, in that directory sits a git repo which I am able to push to my server.

I know that submodule exists however that requires me to upload the dist .git to a remote repo. I do not need a centralized repo for this one, it feels like overkill, I just need to upload the files to the server in different versions.

So is this possible? If not how do developers tackle this workflow I am using?


问:
Segmentation Fault (core dumped) in find/remove of linked list In C
So I am doing a very basic C exercise with a basic linked list. I keep receiving a segmentation error and I'm not too sure what it might be about.

Basically my program adds successfully and then I cant quite tell if the remove or find methods are what are giving me the error.

The structure of the Node is

```<code>struct Node {
        char * word ;
        struct Node * next ;
} ;
</code>```

I'll attach the add, find, and remove because the rest of the code is of my professors handy-work and that all runs, it is simply the issue I created.

add

```<code>void add_ll( struct Node * anchor, char * word ) {
        // given a pointer to the anchor of the list, and a word, add the word
        // to the list, does not matter where (except don't replace the anchor)
        struct Node * newNode = (struct Node *) malloc(sizeof(struct Node)) ;
        newNode -> word = word;
        newNode -> next = anchor -> next;
        anchor -> next = newNode;
        if(anchor == NULL){
          anchor -> next = NULL;
          anchor -> word = word;
      }
      return ;
  }
</code>```

find

```<code>struct Node * find_ll(struct Node * anchor, char * word) {
        // given a pointer to the anchor of the list, and a word, search
        // the list for the word. return the pointer to the with the word, if found,
        // or NULL if not found
        if (anchor -> word == NULL)
          {
            struct Node * node = new_ll();
            return node;
          }
        while(anchor != NULL)
          {
            if(anchor -> word == word)
              return anchor;
            else
              anchor = anchor -> next;
          }
        return NULL ;
}
</code>```

remove

```<code>void remove_ll( struct Node * anchor, struct Node * node_to_remove ) {
        // given a list anchor, and a pointer to a node in the list (but not the anchor)
        // do pointer surgery to remove the node, and free it.
        // sanity checks
        assert(node_to_remove) ;
        assert(node_to_remove!=anchor) ;
        while(anchor != NULL)
          {
            struct Node * temp = anchor;
            struct Node * prev = anchor;
            while(temp != NULL && temp != node_to_remove)
              {
                prev = temp;
                temp = temp -> next;
              }
            prev -> next = temp -> next;
            free(temp);
          }
        return ;
}
</code>```

A thing I have tried to see if it would fix it includes changing

while(temp != NULL && temp -> next != node_to_remove)
to
 while(temp != NULL && temp != node_to_remove)

incase it had something to do with accessing information too early, but it did not fix anything.

Also this is not graded class work if that affects you helping me morally!

So my question basically is... What is causing the segmentation error and if that truly is the only issue, how can I go about fixing it? If you notice any other mistakes please point them out too. I would really appreciate it! If I am missing any information I can add that too! All method headers are my professors and shouldn't be touched!

答:
The function add_ll() will break if anchor is NULL, but constructs a valid list otherwise.  I noticed that it does not make a copy of the string into the Node structure.  Is this what's desired?  It seems weird to add the new element after the head of the list.  Typically the simplest way is to just create a new head-node.

```<code>struct Node *add_ll( struct Node *anchor, char *word )
{
    // given a pointer to the anchor of the list, and a word, add the word
    // to the list, does not matter where (except don't replace the anchor)
    // returns the new list

    struct Node * new_node = (struct Node *)malloc( sizeof( struct Node ) );
    if ( new_node != NULL )
    {
        new_node->word = word;
        new_node->next = anchor;
    }
    else
    {
        // TODO: Handle Out of memory error
    }

    return new_node;
}
</code>```

When a new node is created, perhaps with a NULL anchor, it creates a new list.  The new item is always added at the head of the list:

```<code>struct Node *my_list = NULL;
...
my_list = add_ll( my_list, "some string" );
</code>```

I don't really understand the reasoning behind some parts of find_ll().  Why would it create a new empty(?) node.  A better implementation might be:

```<code>struct Node *find_ll( struct Node *anchor, char *word )
{
    // given a pointer to the anchor of the list, and a word, search
    // the list for the word. return the pointer to the Node with the word, if found,
    // or NULL if not found

    struct Node *result = NULL;

    while( anchor != NULL )
    {
        if ( anchor->word == word )         // Should this be a strcmp()?
        {
            result = anchor;                // found it
            break;
        }
        else
        {
            anchor = anchor->next;          // skip to the next item
        }
    }

    return result;                          // PRO-TIP: return from a single place
}
</code>```

And the remove_ll() - How can this remove the "head" element from the list?  It needs to return a modified list somehow.

```<code>struct Node *remove_ll( struct Node *anchor, struct Node *node_to_remove )
{
    struct Node *result = anchor;

    // given a list anchor, and a pointer to a node in the list (but not the anchor)
    // do pointer surgery to remove the node, and free it.
    // return a pointer to the changed list

    // sanity checks
    assert( anchor );
    assert( node_to_remove );

    // Case where head-node is to be removed
    if ( node_to_remove == anchor )
    {
        // make a new head
        result = anchor->next;                              // snip (of head)
    }
    else
    {
        while( anchor->next != NULL )
        {
            if ( anchor->next == node_to_remove )
            {
                // point to anchor's next-next, removing the node
                anchor->next = node_to_remove->next;   // snip (in body)
            }
            else
            {
                // no match, search ahead
                anchor = anchor->next;
            }
        }
    }
    return result;
}
</code>```

This way removing the head could be called:

```<code>my_list = remove_ll( my_list, head_node );
</code>```

And the my_list might have the same head as before, or the 2nd-node.

Body:
So I am doing a very basic C exercise with a basic linked list. I keep receiving a segmentation error and I'm not too sure what it might be about.

Basically my program adds successfully and then I cant quite tell if the remove or find methods are what are giving me the error.

The structure of the Node is

struct Node {
        char * word ;
        struct Node * next ;
} ;

I'll attach the add, find, and remove because the rest of the code is of my professors handy-work and that all runs, it is simply the issue I created.

add

void add_ll( struct Node * anchor, char * word ) {
        // given a pointer to the anchor of the list, and a word, add the word
        // to the list, does not matter where (except don't replace the anchor)
        struct Node * newNode = (struct Node *) malloc(sizeof(struct Node)) ;
        newNode -> word = word;
        newNode -> next = anchor -> next;
        anchor -> next = newNode;
        if(anchor == NULL){
          anchor -> next = NULL;
          anchor -> word = word;
      }
      return ;
  }

find

struct Node * find_ll(struct Node * anchor, char * word) {
        // given a pointer to the anchor of the list, and a word, search
        // the list for the word. return the pointer to the with the word, if found,
        // or NULL if not found
        if (anchor -> word == NULL)
          {
            struct Node * node = new_ll();
            return node;
          }
        while(anchor != NULL)
          {
            if(anchor -> word == word)
              return anchor;
            else
              anchor = anchor -> next;
          }
        return NULL ;
}

remove

void remove_ll( struct Node * anchor, struct Node * node_to_remove ) {
        // given a list anchor, and a pointer to a node in the list (but not the anchor)
        // do pointer surgery to remove the node, and free it.
        // sanity checks
        assert(node_to_remove) ;
        assert(node_to_remove!=anchor) ;
        while(anchor != NULL)
          {
            struct Node * temp = anchor;
            struct Node * prev = anchor;
            while(temp != NULL && temp != node_to_remove)
              {
                prev = temp;
                temp = temp -> next;
              }
            prev -> next = temp -> next;
            free(temp);
          }
        return ;
}

A thing I have tried to see if it would fix it includes changing

while(temp != NULL && temp -> next != node_to_remove)
to
 while(temp != NULL && temp != node_to_remove)

incase it had something to do with accessing information too early, but it did not fix anything.

Also this is not graded class work if that affects you helping me morally!

So my question basically is... What is causing the segmentation error and if that truly is the only issue, how can I go about fixing it? If you notice any other mistakes please point them out too. I would really appreciate it! If I am missing any information I can add that too! All method headers are my professors and shouldn't be touched!

Body:
The function add_ll() will break if anchor is NULL, but constructs a valid list otherwise.  I noticed that it does not make a copy of the string into the Node structure.  Is this what's desired?  It seems weird to add the new element after the head of the list.  Typically the simplest way is to just create a new head-node.

struct Node *add_ll( struct Node *anchor, char *word )
{
    // given a pointer to the anchor of the list, and a word, add the word
    // to the list, does not matter where (except don't replace the anchor)
    // returns the new list

    struct Node * new_node = (struct Node *)malloc( sizeof( struct Node ) );
    if ( new_node != NULL )
    {
        new_node->word = word;
        new_node->next = anchor;
    }
    else
    {
        // TODO: Handle Out of memory error
    }

    return new_node;
}

When a new node is created, perhaps with a NULL anchor, it creates a new list.  The new item is always added at the head of the list:

struct Node *my_list = NULL;
...
my_list = add_ll( my_list, "some string" );

I don't really understand the reasoning behind some parts of find_ll().  Why would it create a new empty(?) node.  A better implementation might be:

struct Node *find_ll( struct Node *anchor, char *word )
{
    // given a pointer to the anchor of the list, and a word, search
    // the list for the word. return the pointer to the Node with the word, if found,
    // or NULL if not found

    struct Node *result = NULL;

    while( anchor != NULL )
    {
        if ( anchor->word == word )         // Should this be a strcmp()?
        {
            result = anchor;                // found it
            break;
        }
        else
        {
            anchor = anchor->next;          // skip to the next item
        }
    }

    return result;                          // PRO-TIP: return from a single place
}

And the remove_ll() - How can this remove the "head" element from the list?  It needs to return a modified list somehow.

struct Node *remove_ll( struct Node *anchor, struct Node *node_to_remove )
{
    struct Node *result = anchor;

    // given a list anchor, and a pointer to a node in the list (but not the anchor)
    // do pointer surgery to remove the node, and free it.
    // return a pointer to the changed list

    // sanity checks
    assert( anchor );
    assert( node_to_remove );

    // Case where head-node is to be removed
    if ( node_to_remove == anchor )
    {
        // make a new head
        result = anchor->next;                              // snip (of head)
    }
    else
    {
        while( anchor->next != NULL )
        {
            if ( anchor->next == node_to_remove )
            {
                // point to anchor's next-next, removing the node
                anchor->next = node_to_remove->next;   // snip (in body)
            }
            else
            {
                // no match, search ahead
                anchor = anchor->next;
            }
        }
    }
    return result;
}

This way removing the head could be called:

my_list = remove_ll( my_list, head_node );

And the my_list might have the same head as before, or the 2nd-node.


问:
can we use order by clause with group by
Hi
   I am using following query --

```<code>select * from table_name order by status desc
</code>```

It shows the desired result with all records,but as n when i use following query -

```<code>select * from table_name group by category order by status desc
</code>```

It shows only 2 records of distinct category with sorted order.

Is it because i am using order by with group by.....

答:
Yes. "Group by" will aggregate data and group it by the field specified.

And when you use a group by you need to include some aggregating function, else it won't work, e.g.

```<code>SELECT Category, COUNT(*) AS Total
FROM [table]
GROUP BY Category
</code>```

Also, an ORDER BY is applied on the result set of the query only.

EDIT: From your comments it sounds like you are actually trying to "visually group" the records in your result set. If that is indeed the case, then don't use GROUP BY and just go:

```<code>SELECT *
FROM [table]
ORDER BY Category, Status
</code>```

Is that what you need?

Body:
Hi
   I am using following query --

select * from table_name order by status desc

It shows the desired result with all records,but as n when i use following query -

select * from table_name group by category order by status desc

It shows only 2 records of distinct category with sorted order.

Is it because i am using order by with group by.....

Body:
Yes. "Group by" will aggregate data and group it by the field specified.

And when you use a group by you need to include some aggregating function, else it won't work, e.g.

SELECT Category, COUNT(*) AS Total
FROM [table]
GROUP BY Category

Also, an ORDER BY is applied on the result set of the query only.

EDIT: From your comments it sounds like you are actually trying to "visually group" the records in your result set. If that is indeed the case, then don't use GROUP BY and just go:

SELECT *
FROM [table]
ORDER BY Category, Status

Is that what you need?


问:
How to create a simple form on my website (cPanel based) that only activates during certain periods?
I have a weekly conference and I would like to log which participants are attending. I have a website I own I would like them to go to, then put in their name and click "Enter". Afterwards, I'd like for it to save into a database on my website. I currently have cPanel behind my website.

I would like the form to ONLY activate, say, on Thursdays from 10 am to 12 pm. After that, I would like it to close up and not allow entires.

Is there a simple way to do this time exclusion and sample scripts I can find online? Thank you!

答:
PHP date function would work well for this.

// get day and hour
$day = date("l");
$hour = date("h");

if($day == "Thursday") { // make sure day is right
  if($hour > "10" && $hour < "24") { // make sure hour is right
   echo "print form";
  }
}
```

Keep in mind that date() returns a string value that is given from timestamp()

Body:
PHP date function would work well for this.

// get day and hour
$day = date("l");
$hour = date("h");

if($day == "Thursday") { // make sure day is right
  if($hour > "10" && $hour < "24") { // make sure hour is right
   echo "print form";
  }
}

Keep in mind that date() returns a string value that is given from timestamp()


问:
I would like to return res1 and res but I don't know how. Thank you for your help :)

function createInput(text) {
    var regExp = /\{%([^%]+)%\}/g;
    var res = text.replace(regExp, '<input>');

    var regeXp = /dzien_i_miesiac/g;
    var res1 = text.replace(regeXp, '<input type="date">');

    return res1;
}
```

答:
Instead of returning just res1 you can return an object that contains both res and res1, for example:

```<code>function createInput(text){
  var regExp = /\{%([^%]+)%\}/g;
  var res = text.replace(regExp, '<input>');

  var regeXp = /dzien_i_miesiac/g;
  var res1 = text.replace(regeXp, '<input type="date">');

  return { res, res1 };
}
</code>```

And then you could call and the function and get the response as an object:

```<code>const result = createInput('someText')
console.log(result.res)
console.log(result.res1)
</code>```

or, if you want to use destructuring

```<code>const { res, res1 } = createInput('someText')
console.log(res)
console.log(res1)
</code>```

Body:
Instead of returning just res1 you can return an object that contains both res and res1, for example:

function createInput(text){
  var regExp = /\{%([^%]+)%\}/g;
  var res = text.replace(regExp, '<input>');

  var regeXp = /dzien_i_miesiac/g;
  var res1 = text.replace(regeXp, '<input type="date">');

  return { res, res1 };
}

And then you could call and the function and get the response as an object:

const result = createInput('someText')
console.log(result.res)
console.log(result.res1)

or, if you want to use destructuring

const { res, res1 } = createInput('someText')
console.log(res)
console.log(res1)