问:
How to add water mark in recorded video at a proper position [ Top Middle ] in swift5
I tried a lot of code to add watermark (Image) in my recorded video but still unable to add. My video is in portrait mode.

Reference : https://stackoverflow.com/a/45304222

Issues :

Video size got changed but water mark not visible to video.

Video size got zero and blank but water mark not visible to video.

I set video orientation then video got blank by 30 pixel from right but water mark not visible to video.

Code that I applied:

```<code>    func setWaterMarkVideoOutput(inputURL: URL) {
        //input file
        let asset = AVAsset.init(url: inputURL)
        let composition = AVMutableComposition.init()
        composition.addMutableTrack(withMediaType: AVMediaType.video, preferredTrackID: kCMPersistentTrackID_Invalid)

        //input clip
        let clipVideoTrack = asset.tracks(withMediaType: AVMediaType.video)[0]

        //adding the image layer
        let imglogo = UIImage(named: "WatermarkImage")
        let watermarkLayer = CALayer()
        watermarkLayer.contents = imglogo?.cgImage
        watermarkLayer.frame = CGRect(x: 25, y: 25 ,width: 417, height: 103)
        watermarkLayer.opacity = 0.86

        let videoSize = clipVideoTrack.naturalSize
        let parentlayer = CALayer()
        let videoLayer = CALayer()

        parentlayer.frame = CGRect(x: 0, y: 0, width: videoSize.width, height: videoSize.height)
        videoLayer.frame = CGRect(x: 0, y: 0, width: videoSize.width, height: videoSize.height)
        parentlayer.addSublayer(videoLayer)
        parentlayer.addSublayer(watermarkLayer)

        //make it square
        let videoComposition = AVMutableVideoComposition()
        videoComposition.renderSize = CGSize(width: videoSize.width, height: videoSize.height)
        //change it as per your needs.
        videoComposition.frameDuration = CMTimeMake(value: 1, timescale: 30)
        videoComposition.renderScale = 1.0

        //Magic line for adding watermark to the video
        videoComposition.animationTool = AVVideoCompositionCoreAnimationTool(postProcessingAsVideoLayers: [videoLayer], in: parentlayer)

        let instruction = AVMutableVideoCompositionInstruction()
        instruction.timeRange = CMTimeRangeMake(start: CMTime.zero, duration: CMTimeMakeWithSeconds(60, preferredTimescale: 30))

        //rotate to potrait
        let transformer = AVMutableVideoCompositionLayerInstruction(assetTrack: clipVideoTrack)
        let t1 = CGAffineTransform(translationX: clipVideoTrack.naturalSize.height, y: -(clipVideoTrack.naturalSize.width - clipVideoTrack.naturalSize.height) / 2)
        let t2: CGAffineTransform = t1.rotated(by: .pi/2)
        let finalTransform: CGAffineTransform = t2
        transformer.setTransform(finalTransform, at: CMTime.zero)
        instruction.layerInstructions = [transformer]
        videoComposition.instructions = [instruction]

        let documentsPath = NSTemporaryDirectory()
        let outputPath = "\(documentsPath)/\(String.uniqueFilename(withPrefix: "NewVideo")).mp4"
        let outputURL = URL(fileURLWithPath: outputPath)

        let exporter = AVAssetExportSession.init(asset: asset, presetName: AVAssetExportPresetMediumQuality)
        exporter?.outputFileType = AVFileType.mov
        exporter?.outputURL = outputURL
        exporter?.videoComposition = videoComposition

        exporter?.exportAsynchronously() {
            if exporter?.status == .completed {
                print("Export complete")
                DispatchQueue.main.async {
                    print("videoUrl:::", outputURL)
                }
                return
            } else if exporter?.status == .failed {
                print("Export failed - \(String(describing: exporter?.error))")
            }
            return
        }
    }

</code>```

Please correct me what I did wrong in this method.
Thank you in Advance.

Body:
I tried a lot of code to add watermark (Image) in my recorded video but still unable to add. My video is in portrait mode.

Reference : https://stackoverflow.com/a/45304222

Issues :

Video size got changed but water mark not visible to video.

Video size got zero and blank but water mark not visible to video.

I set video orientation then video got blank by 30 pixel from right but water mark not visible to video.

Code that I applied:

    func setWaterMarkVideoOutput(inputURL: URL) {
        //input file
        let asset = AVAsset.init(url: inputURL)
        let composition = AVMutableComposition.init()
        composition.addMutableTrack(withMediaType: AVMediaType.video, preferredTrackID: kCMPersistentTrackID_Invalid)

        //input clip
        let clipVideoTrack = asset.tracks(withMediaType: AVMediaType.video)[0]

        //adding the image layer
        let imglogo = UIImage(named: "WatermarkImage")
        let watermarkLayer = CALayer()
        watermarkLayer.contents = imglogo?.cgImage
        watermarkLayer.frame = CGRect(x: 25, y: 25 ,width: 417, height: 103)
        watermarkLayer.opacity = 0.86

        let videoSize = clipVideoTrack.naturalSize
        let parentlayer = CALayer()
        let videoLayer = CALayer()

        parentlayer.frame = CGRect(x: 0, y: 0, width: videoSize.width, height: videoSize.height)
        videoLayer.frame = CGRect(x: 0, y: 0, width: videoSize.width, height: videoSize.height)
        parentlayer.addSublayer(videoLayer)
        parentlayer.addSublayer(watermarkLayer)

        //make it square
        let videoComposition = AVMutableVideoComposition()
        videoComposition.renderSize = CGSize(width: videoSize.width, height: videoSize.height)
        //change it as per your needs.
        videoComposition.frameDuration = CMTimeMake(value: 1, timescale: 30)
        videoComposition.renderScale = 1.0

        //Magic line for adding watermark to the video
        videoComposition.animationTool = AVVideoCompositionCoreAnimationTool(postProcessingAsVideoLayers: [videoLayer], in: parentlayer)

        let instruction = AVMutableVideoCompositionInstruction()
        instruction.timeRange = CMTimeRangeMake(start: CMTime.zero, duration: CMTimeMakeWithSeconds(60, preferredTimescale: 30))

        //rotate to potrait
        let transformer = AVMutableVideoCompositionLayerInstruction(assetTrack: clipVideoTrack)
        let t1 = CGAffineTransform(translationX: clipVideoTrack.naturalSize.height, y: -(clipVideoTrack.naturalSize.width - clipVideoTrack.naturalSize.height) / 2)
        let t2: CGAffineTransform = t1.rotated(by: .pi/2)
        let finalTransform: CGAffineTransform = t2
        transformer.setTransform(finalTransform, at: CMTime.zero)
        instruction.layerInstructions = [transformer]
        videoComposition.instructions = [instruction]

        let documentsPath = NSTemporaryDirectory()
        let outputPath = "\(documentsPath)/\(String.uniqueFilename(withPrefix: "NewVideo")).mp4"
        let outputURL = URL(fileURLWithPath: outputPath)

        let exporter = AVAssetExportSession.init(asset: asset, presetName: AVAssetExportPresetMediumQuality)
        exporter?.outputFileType = AVFileType.mov
        exporter?.outputURL = outputURL
        exporter?.videoComposition = videoComposition

        exporter?.exportAsynchronously() {
            if exporter?.status == .completed {
                print("Export complete")
                DispatchQueue.main.async {
                    print("videoUrl:::", outputURL)
                }
                return
            } else if exporter?.status == .failed {
                print("Export failed - \(String(describing: exporter?.error))")
            }
            return
        }
    }

Please correct me what I did wrong in this method.
Thank you in Advance.


来源: stackexchange

问:
how to create a virtual audio input/output device on Windows in C++
background:

I want to broadcast the Windows system audio except my own app's one. application loopbackcapture exactly does what I want, but it only supports Windows 11 (I want a much more general solution, Windows 7/8/10/11).

current solution:

create a virtual audio output device, and set it as system default.

capture audio from the virtual audio output device, and broadcast it.

route audio from the virtual audio output device to the system physical one.

I tried VAC (Virtual Audio Cable), things work fine. However it does not provide any APIs to create virtual audio device and route audio streams between audio devices.

So my question is how to create virtual audio devices and route audio streams between them.

Thanks.

platform:

Windows 10

WASAPI

visual studio 2019

information I googled:

How to create a virtual audio input device to simulate a microphone in MacOS

https://vb-audio.com/Cable/

https://github.com/HSpear/virtual-audio-wire

https://jackaudio.org/faq/jack_on_windows.html

ContentLicense: CC BY-SA 4.0


问:
why datetime.datetime.fromtimestamp(0).timestamp() should raise exception (python>=3.7)
is there a logical reason or it's a bug that

```<code>datetime.datetime.fromtimestamp(0).timestamp()
</code>```

raises OSError: [Errno 22] Invalid argument?

I would expect as result 0.0 as I'm passing from timestamp 0 to datetime and again back to timestamp

I'm on Win10 (tested with 3.7, 3.11)

Body:
is there a logical reason or it's a bug that

datetime.datetime.fromtimestamp(0).timestamp()

raises OSError: [Errno 22] Invalid argument?

I would expect as result 0.0 as I'm passing from timestamp 0 to datetime and again back to timestamp

I'm on Win10 (tested with 3.7, 3.11)


问:
How to associate keyboard shortcut with respect to IntelliJ IDE for running Groovy scripts?
I want to run groovy script in IDE Scripting Console through keyboard shortcut . Help me with it .</p>


问:
pandas rolling with varying window size
I need to do a calculation on a rolling window of datapoints in a pandas dataframe, where the number of periods include in the window is different for different datapoints. While this was never supported by the rolling function it used to be possible by using a workaround with a custom indexer. I defined the following indexer:

```<code>class CustomIndexer(BaseIndexer):
    def get_window_bounds(self, num_values, min_periods, center, closed):
        start = np.empty(num_values, dtype=np.int64)
        end = np.empty(num_values, dtype=np.int64)
        for i in range(num_values):
            start[i] = i
            end[i] = i + self.true_window_size[i]
        return start, end
</code>```

And then used it like this

```<code>IndividualValueIndexer(window_size=1,true_window_size=list_of_window_sizes)
</code>```

I had to pass the fixed window size of 1 but I could just ignore it in the "get_window_bounds" function. This worked with pandas 1.4.1. However after updating to pandas 1.5.2 there seems to be a new function that checks if the windows returned by the "get_window_bounds" function actually match the specified window and throws an error.

Is there a good alternative to performing a rolling operation with varying window size? I tried simply looping over my data but that is more than an order of magnitude slower.

Title: pandas rolling with varying window size

Body:
I need to do a calculation on a rolling window of datapoints in a pandas dataframe, where the number of periods include in the window is different for different datapoints. While this was never supported by the rolling function it used to be possible by using a workaround with a custom indexer. I defined the following indexer:

class CustomIndexer(BaseIndexer):
    def get_window_bounds(self, num_values, min_periods, center, closed):
        start = np.empty(num_values, dtype=np.int64)
        end = np.empty(num_values, dtype=np.int64)
        for i in range(num_values):
            start[i] = i
            end[i] = i + self.true_window_size[i]
        return start, end

And then used it like this

IndividualValueIndexer(window_size=1,true_window_size=list_of_window_sizes)

I had to pass the fixed window size of 1 but I could just ignore it in the "get_window_bounds" function. This worked with pandas 1.4.1. However after updating to pandas 1.5.2 there seems to be a new function that checks if the windows returned by the "get_window_bounds" function actually match the specified window and throws an error.

Is there a good alternative to performing a rolling operation with varying window size? I tried simply looping over my data but that is more than an order of magnitude slower.


问:
Python Needle in Haystack issue with return value / convert string to boolean
I´ve been trying to implement a simple needle in haystack function in Python to check if the word (needle) is part of the other string (haystack) and if yes output the index of the position. If the answer is no it should return "false" in boolean. My code looks as following:

```<code>def needleinhaystack(haystack,needle):

    for i in range(len(haystack) - len(needle)+1):
        if haystack[i:i+len(needle)] == needle:
            return i
    return "False"
</code>```

It works but it return the false as a string

```<code>Expected return value: False (<class 'bool'>)

Got return value: False (<class 'str'>)
</code>```

I tried to fix it with a simple bool("False")

```<code>def needleinhaystack(haystack,needle):

    for i in range(len(haystack) - len(needle)+1):
        if haystack[i:i+len(needle)] == needle:
            return i
    return bool("False")
</code>```

If I do that the whole script stops working.

Im pretty new to Python and a bit stuck any help is highly appreciated :-)

Thanks

Body:
I´ve been trying to implement a simple needle in haystack function in Python to check if the word (needle) is part of the other string (haystack) and if yes output the index of the position. If the answer is no it should return "false" in boolean. My code looks as following:

def needleinhaystack(haystack,needle):

    for i in range(len(haystack) - len(needle)+1):
        if haystack[i:i+len(needle)] == needle:
            return i
    return "False"

It works but it return the false as a string

Expected return value: False (<class 'bool'>)

Got return value: False (<class 'str'>)

I tried to fix it with a simple bool("False")

def needleinhaystack(haystack,needle):

    for i in range(len(haystack) - len(needle)+1):
        if haystack[i:i+len(needle)] == needle:
            return i
    return bool("False")

If I do that the whole script stops working.

Im pretty new to Python and a bit stuck any help is highly appreciated :-)

Thanks


问:
Running Shell Script through salt
I am new to Saltstack, trying to run shell script from salt but its not able to cache the script.

code :
run_test.sh:
cmd.script:

name: test.sh

source: salt://{path-to-script}/test.sh

Error - Comment: Unable to cache script salt://{path-to-script}/test.sh from saltenv 'branch_name'

Have set all permission to file

Title: Running Shell Script through salt


问:
BarbaJS doesn't animate the proper way and stops when enter homepage
I want the animation that starts after entering the home page to start every time you enter it.

In addition, I want the transitions between pages to have a different type of animation.

I managed to do almost everything, but unfortunately, at the moment of transition between the project page and the main page, the animation stops. I do not understand why.

Here is the website: https://dzm11.github.io/portfolio/

The error appear when you scroll down to "Kiddy" project and click VIEW PROJECT. Then page do animation that I want. Then You have to scroll up to the top of the website and click LOGO. This is the time when the error happen. The black screen freeze and dont transform anyway.

JS code:

```<code>// entryAnimation
const text = document.querySelector(".preloader__text--content");
const strText = text.textContent;
const splitText = strText.split("");
text.textContent = "";

for (let i = 0; i < splitText.length; i++) {
text.innerHTML += "<span>" + splitText[i] + "</span>"
}

let char = 0;
let timer = setInterval(onTick, 50);

function onTick(){
  const span = text.querySelectorAll('span')[char]
  span.classList.add('fade');
  console.log(char)
  char++;
  if(char===splitText.length){
    complete();
    setTimeout(() => {
      preloader.classList.add('hide');
    }, 1500);

    return;
  }
}

function complete(){
  clearInterval(timer);
  timer = null;
}

barba.use(barbaCss);

// barba.hooks.enter(() => {
//   window.scrollTo(0, 0);
// });

barba.init({
  transitions: [
{
      name: 'cover',
      to:{
        namespace: ['home', 'project']
      },
      leave(){},
      enter(){},
    },
    {
      name: 'entry',
      once(){}
    }
  ],
  views: [{
    namespace: 'home',
    beforeEnter(data) {
      preloader.classList.add('hide');
    }
  }]
});

const preloader = document.querySelector(".preloader");
</code>```

HTML Code:

```<code> <div class="preloader">

                <h1 class="fs-header-1 fw-demi preloader__text--content">H E N L O</h1>

        </div>
</code>```

Css code:

```<code>.preloader {
    position: fixed;
    transform: translateY(0);
    background-color: var(--clr-neutral-900);
    height: 100vh;
    width: 100%;
    z-index: 2;
    overflow: hidden;
    display: flex;
    justify-content: center;
    align-items: center;
    transition: transform .7s cubic-bezier(0.7, 0, 0.3, 1);
    &.hide{
        transform: translateY(-100%);
    }

    &__text--content {
        overflow: hidden;
        display: block;
        position: absolute;

        span {
            transition: transform 1s cubic-bezier(0.7, 0, 0.3, 1);
            display: inline-block;
            position: relative;
            color: var(--clr-neutral-100);
            transform: translateY(100%);
        }

        span.fade {
            transform: translateY(0%);

        }
    }
}

.entry-once .preloader {
    transform: translateY(0%);
}

.entry-once-active,
.entry-once-active .preloader {
    transition: transform .7s cubic-bezier(0.7, 0, 0.3, 1) 1.3s;
}

.entry-once-to .preloader {
    transform: translateY(100%);
}

.transition {
    position: fixed;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    background-color: var(--clr-neutral-900);
    display: flex;
    align-items: center;
    justify-content: center;
    transform: translateY(-100%);
    z-index: 1;
}

.cover-leave-active,
.cover-enter-active,
.cover-leave-active .transition,
.cover-enter-active .transition {
    transition: transform .7s cubic-bezier(0.7, 0, 0.3, 1);
}

.cover-leave .transition {
    transform: translateY(-100%);
}

.cover-leave-to .transition {
    transform: translateY(0);
}

.cover-enter .transition {
    transform: translateY(0);
}

.cover-enter-to .transition {
    transform: translateY(100%);
}
</code>```

I tried almost everything and I think I just dont understand the mechanics of BarbaJS

Body:
I want the animation that starts after entering the home page to start every time you enter it.

In addition, I want the transitions between pages to have a different type of animation.

I managed to do almost everything, but unfortunately, at the moment of transition between the project page and the main page, the animation stops. I do not understand why.

Here is the website: https://dzm11.github.io/portfolio/

The error appear when you scroll down to "Kiddy" project and click VIEW PROJECT. Then page do animation that I want. Then You have to scroll up to the top of the website and click LOGO. This is the time when the error happen. The black screen freeze and dont transform anyway.

JS code:

// entryAnimation
const text = document.querySelector(".preloader__text--content");
const strText = text.textContent;
const splitText = strText.split("");
text.textContent = "";

for (let i = 0; i < splitText.length; i++) {
text.innerHTML += "" + splitText[i] + ""
}

let char = 0;
let timer = setInterval(onTick, 50);

function onTick(){
  const span = text.querySelectorAll('span')[char]
  span.classList.add('fade');
  console.log(char)
  char++;
  if(char===splitText.length){
    complete();
    setTimeout(() => {
      preloader.classList.add('hide');
    }, 1500);

    return;
  }
}

function complete(){
  clearInterval(timer);
  timer = null;
}

barba.use(barbaCss);

// barba.hooks.enter(() => {
//   window.scrollTo(0, 0);
// });

barba.init({
  transitions: [
{
      name: 'cover',
      to:{
        namespace: ['home', 'project']
      },
      leave(){},
      enter(){},
    },
    {
      name: 'entry',
      once(){}
    }
  ],
  views: [{
    namespace: 'home',
    beforeEnter(data) {
      preloader.classList.add('hide');
    }
  }]
});

const preloader = document.querySelector(".preloader");

HTML Code:

H E N L O

Css code:

.preloader {
    position: fixed;
    transform: translateY(0);
    background-color: var(--clr-neutral-900);
    height: 100vh;
    width: 100%;
    z-index: 2;
    overflow: hidden;
    display: flex;
    justify-content: center;
    align-items: center;
    transition: transform .7s cubic-bezier(0.7, 0, 0.3, 1);
    &.hide{
        transform: translateY(-100%);
    }

    &__text--content {
        overflow: hidden;
        display: block;
        position: absolute;

        span {
            transition: transform 1s cubic-bezier(0.7, 0, 0.3, 1);
            display: inline-block;
            position: relative;
            color: var(--clr-neutral-100);
            transform: translateY(100%);
        }

        span.fade {
            transform: translateY(0%);

        }
    }
}

.entry-once .preloader {
    transform: translateY(0%);
}

.entry-once-active,
.entry-once-active .preloader {
    transition: transform .7s cubic-bezier(0.7, 0, 0.3, 1) 1.3s;
}

.entry-once-to .preloader {
    transform: translateY(100%);
}

.transition {
    position: fixed;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    background-color: var(--clr-neutral-900);
    display: flex;
    align-items: center;
    justify-content: center;
    transform: translateY(-100%);
    z-index: 1;
}

.cover-leave-active,
.cover-enter-active,
.cover-leave-active .transition,
.cover-enter-active .transition {
    transition: transform .7s cubic-bezier(0.7, 0, 0.3, 1);
}

.cover-leave .transition {
    transform: translateY(-100%);
}

.cover-leave-to .transition {
    transform: translateY(0);
}

.cover-enter .transition {
    transform: translateY(0);
}

.cover-enter-to .transition {
    transform: translateY(100%);
}

I tried almost everything and I think I just dont understand the mechanics of BarbaJS


问:
How to solve the problem of memory slowly getting larger？
I have a .net framework WinForms project for IR camera temperature measurement. I checked the memory with the performance monitor and found that after about 12 hours of running, the memory seems to be slowly getting larger. Since the project needed to run steadily over time, I was concerned that the constant increase in memory would eventually cause the system to crash.

Can someone help me?

Thanks.

Code

```<code>    `if(pictureBox1.Image != null && pictureBox1!=null)
    {
        pictureBox1.Image.Dispose();
        if(Count>1000)
        {
            GC.Collect();
            Count = 0;
        }
    }
    pictureBox1.Image = MatImageShow.ToBitmap();`
</code>```

IR

enter image description here

12 Hours ago

enter image description here

12 Hours later

enter image description here

Body:
I have a .net framework WinForms project for IR camera temperature measurement. I checked the memory with the performance monitor and found that after about 12 hours of running, the memory seems to be slowly getting larger. Since the project needed to run steadily over time, I was concerned that the constant increase in memory would eventually cause the system to crash.

Can someone help me?

Thanks.

Code

    `if(pictureBox1.Image != null && pictureBox1!=null)
    {
        pictureBox1.Image.Dispose();
        if(Count>1000)
        {
            GC.Collect();
            Count = 0;
        }
    }
    pictureBox1.Image = MatImageShow.ToBitmap();`

IR

enter image description here

12 Hours ago

enter image description here

12 Hours later

enter image description here


问:
Custom react-testing-library test setup causes tests to hang indefinitely on API calls
I'm using Jest to do some integration testing on my React App (AWS, Redux Toolkit, MSW).
I have a custom setup files that I am using in my tests as per react-testing-library instructions (https://testing-library.com/docs/react-testing-library/setup/).

testsUtils.js

```<code>import { App } from 'containers';
import { BrowserRouter } from 'react-router-dom';
import { I18nextProvider } from 'react-i18next';
import { Provider } from 'react-redux';
import { configureStore } from '@reduxjs/toolkit';
import i18n from './i18n';
import { persistedReducer } from 'store';
import { render } from '@testing-library/react';

const getStore = (store) => {
  const str = { ...store };
  return configureStore({
    preloadedState: {
      ...str,
    },
    reducer: persistedReducer,
  });
};

const renderTestApp = ({ route = '/', store }) => {
  const str = getStore(store);
  window.history.replaceState({}, '', route);
  return render(
    <Provider store={str}>
      <BrowserRouter>
        <I18nextProvider i18n={i18n}>
          <App />
        </I18nextProvider>
      </BrowserRouter>
    </Provider>,
  );
};

export * from '@testing-library/react';

export { renderTestApp as render };
</code>```

This file allow me to render the app in a test, pass a route and an initial store to test a specific screen.
However, when an API call is made (I'm mocking the AWS requests using MSW) this warning shows up :

A worker process has failed to exit gracefully and has been force exited. This is likely caused by tests leaking due to improper teardown. Try running with --detectOpenHandles to find leaks. Active timers can also cause this, ensure that .unref() was called on them.

On top of that, running 42 tests from 5 tests suites is really slow the first time, it takes around 180 seconds to complete and there are been instances where launching the tests plainly freezes my machine.

FileSelection.test.js

```<code>import { render, screen, waitFor } from 'testsUtils';

import userEvent from '@testing-library/user-event';

describe('FileSelection', () => {
  beforeEach(async () => {
    render({
      route:
        '/selection/human?id=kixUziFOWKpBhnTrknaA6w&des=SUM',
      store: {
        users: {
          secondary: 'MSW msw',
          main: 'JSW jsw',
        },
        files: {},
      },
    });
    const title = await screen.findByText('Selection');
    expect(title);
  });

  test('FileSelection screen renders', async () => {
    await waitFor(() => {
      expect(screen.getByText('Selection')).toBeInTheDocument();
      expect(
        screen.getByRole('button', { name: 'Continue' }),
      ).toBeInTheDocument();
    });
  });
}
</code>```

App.js

```<code>import {
  FileSelection,
} from 'containers';
import { Route, Routes } from 'react-router-dom';

import styled from '@emotion/styled';
import useApp from './hook/useApp';
import { useEffect } from 'react';
import { useTranslation } from 'react-i18next';

const AppLoading = styled.div`
  align-items: center;
  display: flex;
  height: 100vh;
  justify-content: center;
`;

const AppContainer = styled.div`
  flex: 1;
`;

const App = (props) => {
  const {
    location,
    processing,
  } = useApp(props);
  const { t } = useTranslation();

 return (
    <ThemeProvider>
      {processing ? (
        <AppLoading>
          <Loading size={240} />
        </AppLoading>
      ) : (
        <AppContainer>
          <Routes>
            {tabsList.map((tab, index) => {
              return (
                <Route
                  element={
                    <Selection/>
                  }
                  key={t('Selection.path', {
                    slug: tab.slug,
                  })}
                  path={t('Selection.path', {
                    slug: tab.slug,
                  })}
                />
              );
            })}
          </Routes>
        </AppContainer>
      )}
    </ThemeProvider>
  );

export default App;

</code>```

useApp.js

```<code>import {
  apiGetData,
  getId,
} from 'store';
import { useDispatch, useSelector } from 'react-redux';
import { useEffect, useState } from 'react';
import { useLocation, useNavigate } from 'react-router';

import _ from 'lodash';
import slugify from 'slugify';
import styled from '@emotion/styled';
import { useTranslation } from 'react-i18next';

const BoExchangeTitle = styled.div`
  flex: 1;
`;

const BoExchangeTitleContainer = styled.div`
  align-items: flex-end;
  display: flex;
  justiycontent: space-between;
`;

const useApp = (props) => {
  const dispatch = useDispatch();
  const headings = useSelector(getHeadings);
  const location = useLocation();
  const navigate = useNavigate();
  const id =
    props?.id || useSelector(getId);
  const { t } = useTranslation();
  const [processing, setProcessing] = useState(false);

  useEffect(async () => {
    const queryParams = new URLSearchParams(location.search);
    const searchId = queryParams.get('id');
    const des = props?.des || queryParams.get('des');
    let i = id;
    if (searchId && searchId !== id) {
      i = searchId;
    }
    if (destination) {
      dispatch(setRecipient(destination));
    }
    if (i) {
      try {
        setProcessing(true);
        await dispatch(apiGetData({ id })); //Api Call right here
        dispatch(setId(id));
        setProcessing(false);
      } catch (error) {
        setProcessing(false);
        navigate(t('TechnicalError.path'));
        console.log(error);
      }
    } else {
      navigate(t('TechnicalError.path'));
    }
  }, []);

  return {
    location,
    processing,
  };
};

export default useApp;

</code>```

apiGetData

```<code>export const apiGetData = ({ id }) => {
  return async (dispatch) => {
    try {
      const response = await API.get(
        "Endpoint gateway name",
        "Endpoint path",
        {
          headers: {
            'private key': 'private key value',
          },
          response: true,
        },
      );
      if (response.status === 200) {
        const { data } = response;
        return data;
      }
    } catch (error) {
      const { data, status, statusText } = error.response || {};
      console.log('error', error);
      throw {
        data,
        status,
        statusText,
      };
    }
  };
};
</code>```

To me, it looks like this mocked AWS call is not detected as finished which causes the performance issues... Any idea on how to tackle this ? (Sorry if some code is missing, I had to cut a lot since I can't share the original one).
To clarify, the application is working fine on it's own, the tests are the issue.

I tried commenting the API call in useApp.js which makes the test run as expected. The test run fast and no warning logs in the console.
I tried running the tests with  --runInBand and --detectOpenHandles which didn't print anything useful.
I tried disabling MSW which didnt change anything as expected.

Body:
I'm using Jest to do some integration testing on my React App (AWS, Redux Toolkit, MSW).
I have a custom setup files that I am using in my tests as per react-testing-library instructions (https://testing-library.com/docs/react-testing-library/setup/).

testsUtils.js

import { App } from 'containers';
import { BrowserRouter } from 'react-router-dom';
import { I18nextProvider } from 'react-i18next';
import { Provider } from 'react-redux';
import { configureStore } from '@reduxjs/toolkit';
import i18n from './i18n';
import { persistedReducer } from 'store';
import { render } from '@testing-library/react';

const getStore = (store) => {
  const str = { ...store };
  return configureStore({
    preloadedState: {
      ...str,
    },
    reducer: persistedReducer,
  });
};

const renderTestApp = ({ route = '/', store }) => {
  const str = getStore(store);
  window.history.replaceState({}, '', route);
  return render(
    <Provider store={str}>
      <BrowserRouter>
        <I18nextProvider i18n={i18n}>
          <App />
        </I18nextProvider>
      </BrowserRouter>
    </Provider>,
  );
};

export * from '@testing-library/react';

export { renderTestApp as render };

This file allow me to render the app in a test, pass a route and an initial store to test a specific screen.
However, when an API call is made (I'm mocking the AWS requests using MSW) this warning shows up :

A worker process has failed to exit gracefully and has been force exited. This is likely caused by tests leaking due to improper teardown. Try running with --detectOpenHandles to find leaks. Active timers can also cause this, ensure that .unref() was called on them.

On top of that, running 42 tests from 5 tests suites is really slow the first time, it takes around 180 seconds to complete and there are been instances where launching the tests plainly freezes my machine.

FileSelection.test.js

import { render, screen, waitFor } from 'testsUtils';

import userEvent from '@testing-library/user-event';

describe('FileSelection', () => {
  beforeEach(async () => {
    render({
      route:
        '/selection/human?id=kixUziFOWKpBhnTrknaA6w&des=SUM',
      store: {
        users: {
          secondary: 'MSW msw',
          main: 'JSW jsw',
        },
        files: {},
      },
    });
    const title = await screen.findByText('Selection');
    expect(title);
  });

  test('FileSelection screen renders', async () => {
    await waitFor(() => {
      expect(screen.getByText('Selection')).toBeInTheDocument();
      expect(
        screen.getByRole('button', { name: 'Continue' }),
      ).toBeInTheDocument();
    });
  });
}

App.js

import {
  FileSelection,
} from 'containers';
import { Route, Routes } from 'react-router-dom';

import styled from '@emotion/styled';
import useApp from './hook/useApp';
import { useEffect } from 'react';
import { useTranslation } from 'react-i18next';

const AppLoading = styled.div`
  align-items: center;
  display: flex;
  height: 100vh;
  justify-content: center;
`;

const AppContainer = styled.div`
  flex: 1;
`;

const App = (props) => {
  const {
    location,
    processing,
  } = useApp(props);
  const { t } = useTranslation();

 return (
    <ThemeProvider>
      {processing ? (
        <AppLoading>
          <Loading size={240} />
        </AppLoading>
      ) : (
        <AppContainer>
          <Routes>
            {tabsList.map((tab, index) => {
              return (
                <Route
                  element={
                    <Selection/>
                  }
                  key={t('Selection.path', {
                    slug: tab.slug,
                  })}
                  path={t('Selection.path', {
                    slug: tab.slug,
                  })}
                />
              );
            })}
          </Routes>
        </AppContainer>
      )}
    </ThemeProvider>
  );

export default App;

useApp.js

import {
  apiGetData,
  getId,
} from 'store';
import { useDispatch, useSelector } from 'react-redux';
import { useEffect, useState } from 'react';
import { useLocation, useNavigate } from 'react-router';

import _ from 'lodash';
import slugify from 'slugify';
import styled from '@emotion/styled';
import { useTranslation } from 'react-i18next';

const BoExchangeTitle = styled.div`
  flex: 1;
`;

const BoExchangeTitleContainer = styled.div`
  align-items: flex-end;
  display: flex;
  justiycontent: space-between;
`;

const useApp = (props) => {
  const dispatch = useDispatch();
  const headings = useSelector(getHeadings);
  const location = useLocation();
  const navigate = useNavigate();
  const id =
    props?.id || useSelector(getId);
  const { t } = useTranslation();
  const [processing, setProcessing] = useState(false);

  useEffect(async () => {
    const queryParams = new URLSearchParams(location.search);
    const searchId = queryParams.get('id');
    const des = props?.des || queryParams.get('des');
    let i = id;
    if (searchId && searchId !== id) {
      i = searchId;
    }
    if (destination) {
      dispatch(setRecipient(destination));
    }
    if (i) {
      try {
        setProcessing(true);
        await dispatch(apiGetData({ id })); //Api Call right here
        dispatch(setId(id));
        setProcessing(false);
      } catch (error) {
        setProcessing(false);
        navigate(t('TechnicalError.path'));
        console.log(error);
      }
    } else {
      navigate(t('TechnicalError.path'));
    }
  }, []);

  return {
    location,
    processing,
  };
};

export default useApp;

apiGetData

export const apiGetData = ({ id }) => {
  return async (dispatch) => {
    try {
      const response = await API.get(
        "Endpoint gateway name",
        "Endpoint path",
        {
          headers: {
            'private key': 'private key value',
          },
          response: true,
        },
      );
      if (response.status === 200) {
        const { data } = response;
        return data;
      }
    } catch (error) {
      const { data, status, statusText } = error.response || {};
      console.log('error', error);
      throw {
        data,
        status,
        statusText,
      };
    }
  };
};

To me, it looks like this mocked AWS call is not detected as finished which causes the performance issues... Any idea on how to tackle this ? (Sorry if some code is missing, I had to cut a lot since I can't share the original one).
To clarify, the application is working fine on it's own, the tests are the issue.

I tried commenting the API call in useApp.js which makes the test run as expected. The test run fast and no warning logs in the console.
I tried running the tests with  --runInBand and --detectOpenHandles which didn't print anything useful.
I tried disabling MSW which didnt change anything as expected.


问:
Current Measurement from ADC - Remove Offset
Support on ADC current measurement and Offset removal.

I am kindly asking for support and details in understanding the concept of dc-offset removal from an ADC current measurement in a motor drive application. In particular, I have my calibration parameters (i.e., gain and offset) to convert the raw ADC data to real current in Ampere. I report the function I wrote in the following.

```<code>#define GAIN    (0.0042)
#define OFFSET  (36.007)
void ADC_Convertion(unsigned short ADC_RAW, float CURRENT)
{
    CURRENT = ADC_RAW*GAIN- OFFSET;
}
</code>```

I understand that a further function is needed to remove the offset dynamically that takes into account the sampling frequency of the controller and other information regarding the LSB. If the above is correct, is there anyone who can explain the concept in detail and/or refer to any significant paper/book on the topic? I would really appreciate any help on this.

Kind regards

Body:
Support on ADC current measurement and Offset removal.

I am kindly asking for support and details in understanding the concept of dc-offset removal from an ADC current measurement in a motor drive application. In particular, I have my calibration parameters (i.e., gain and offset) to convert the raw ADC data to real current in Ampere. I report the function I wrote in the following.

#define GAIN    (0.0042)
#define OFFSET  (36.007)
void ADC_Convertion(unsigned short ADC_RAW, float CURRENT)
{
    CURRENT = ADC_RAW*GAIN- OFFSET;
}

I understand that a further function is needed to remove the offset dynamically that takes into account the sampling frequency of the controller and other information regarding the LSB. If the above is correct, is there anyone who can explain the concept in detail and/or refer to any significant paper/book on the topic? I would really appreciate any help on this.

Kind regards


问:
Initial zoom and max/min zoom level in react-3d-viewer
Can someone please tell me how can I set initial zoom and max/min zoom level in react-3d-viewer? I went through documentaion but didn't find anything related to this. I also visited the issues posted on the GitHub repo of this package but the questions are unanswered.

Codesandbox link: https://codesandbox.io/s/react-4c8q4


问:
How to trigger "input on call" widget on Twilio REST API
I am trying to setup an IVR where I have number for outlets nearby. So I will make an automate call and it will ask owner to press 1,2 in case of shop is open or close respectively.

I am not able to make a call over here.

```<code>curl -X POST https://studio.twilio.com/v2/Flows/F***********/Executions --data-urlencode "To=+9196******" --data-urlencode "From=+120*********" -u "AC****:8****"
</code>```

This is how I am triggering. Also, Is it possible to validate the number in the flow and check if the number is cell phone then message would trigger and if it is landline then voicemail/call will trigger and get the respective input?

Body:
I am trying to setup an IVR where I have number for outlets nearby. So I will make an automate call and it will ask owner to press 1,2 in case of shop is open or close respectively.

I am not able to make a call over here.

curl -X POST https://studio.twilio.com/v2/Flows/F***********/Executions --data-urlencode "To=+9196******" --data-urlencode "From=+120*********" -u "AC****:8****"

This is how I am triggering. Also, Is it possible to validate the number in the flow and check if the number is cell phone then message would trigger and if it is landline then voicemail/call will trigger and get the respective input?


问:
What Datadog metrics are useful for detecting network bottlenecks
How do I know if my machine has network bottlenecks using Datadog? I see https://docs.datadoghq.com/integrations/network/ but I am not sure which one to use. Other resources like memory, CPU, and disk have metrics that are fairly easy to interpret like utilization. For networking would it be something like system.net.tcp.recv_q.avg and system.net.tcp.send_q.avg? What would be a good or bad number for the TCP queues?</p>


问:
JEST with Vue: Failed to mount component: template or render function not defined
I am trying to import a module that was created by me like this:

 import { Modal } from '@rave/commons';

Everything works fine on the development side, but when trying to run some jest test I have the following error:

[Vue warn]: Failed to mount component: template or render function not defined.

If I change @rave/commons to the full path ../node_modules/@rave/commons/..etc the error is gone.

Is there a way to specify some configuration in order for jest to understand the @rave/commons import?


问:
Why did docker.service fails after editing daemon.json?
I got

```<code>sudo systemctl status docker
● docker.service - Docker Application Container Engine
     Loaded: loaded (/lib/systemd/system/docker.service; enabled; vendor preset: enabled)
     Active: failed (Result: exit-code) since Tue 2022-12-20 10:28:45 CET; 29min ago
TriggeredBy: ● docker.socket
       Docs: https://docs.docker.com
    Process: 185839 ExecStart=/usr/bin/dockerd -H fd:// --containerd=/run/containerd/containerd.sock (code=exited, status=1/FAILURE)
   Main PID: 185839 (code=exited, status=1/FAILURE)

Dec 20 10:28:45 miki-ancic systemd[1]: docker.service: Scheduled restart job, restart counter is at 3.
Dec 20 10:28:45 miki-ancic systemd[1]: Stopped Docker Application Container Engine.
Dec 20 10:28:45 miki-ancic systemd[1]: docker.service: Start request repeated too quickly.
Dec 20 10:28:45 miki-ancic systemd[1]: docker.service: Failed with result 'exit-code'.
Dec 20 10:28:45 miki-ancic systemd[1]: Failed to start Docker Application Container Engine.
</code>```

I edited /etc/docker/daemon.json

```<code>{
"icc" : false,
"userns-remap": "default",
"log-driver": "syslog",
"live-restore": true,
"userland-proxy": false,
"no-new-privileges": true
}
</code>```

I tried

```<code>sudo dockerd --debug

DEBU[2022-12-20T11:04:03.988039125+01:00] Registering POST, /networks/{id:.*}/connect
DEBU[2022-12-20T11:04:03.988200113+01:00] Registering POST, /networks/{id:.*}/disconnect
DEBU[2022-12-20T11:04:03.988360830+01:00] Registering POST, /networks/prune
DEBU[2022-12-20T11:04:03.988510707+01:00] Registering DELETE, /networks/{id:.*}
INFO[2022-12-20T11:04:03.989134350+01:00] API listen on /var/run/docker.sock
</code>```

How do I debug this issue?
What does Start request repeated too quickly really mean?

Body:
I got

sudo systemctl status docker
● docker.service - Docker Application Container Engine
     Loaded: loaded (/lib/systemd/system/docker.service; enabled; vendor preset: enabled)
     Active: failed (Result: exit-code) since Tue 2022-12-20 10:28:45 CET; 29min ago
TriggeredBy: ● docker.socket
       Docs: https://docs.docker.com
    Process: 185839 ExecStart=/usr/bin/dockerd -H fd:// --containerd=/run/containerd/containerd.sock (code=exited, status=1/FAILURE)
   Main PID: 185839 (code=exited, status=1/FAILURE)

Dec 20 10:28:45 miki-ancic systemd[1]: docker.service: Scheduled restart job, restart counter is at 3.
Dec 20 10:28:45 miki-ancic systemd[1]: Stopped Docker Application Container Engine.
Dec 20 10:28:45 miki-ancic systemd[1]: docker.service: Start request repeated too quickly.
Dec 20 10:28:45 miki-ancic systemd[1]: docker.service: Failed with result 'exit-code'.
Dec 20 10:28:45 miki-ancic systemd[1]: Failed to start Docker Application Container Engine.

I edited /etc/docker/daemon.json

{
"icc" : false,
"userns-remap": "default",
"log-driver": "syslog",
"live-restore": true,
"userland-proxy": false,
"no-new-privileges": true
}

I tried

sudo dockerd --debug

DEBU[2022-12-20T11:04:03.988039125+01:00] Registering POST, /networks/{id:.*}/connect
DEBU[2022-12-20T11:04:03.988200113+01:00] Registering POST, /networks/{id:.*}/disconnect
DEBU[2022-12-20T11:04:03.988360830+01:00] Registering POST, /networks/prune
DEBU[2022-12-20T11:04:03.988510707+01:00] Registering DELETE, /networks/{id:.*}
INFO[2022-12-20T11:04:03.989134350+01:00] API listen on /var/run/docker.sock

How do I debug this issue?
What does Start request repeated too quickly really mean?


问:
MongoDart Authentication format issue
I'm trying to use MongoDart with Dart as backend. It was working fine till I shifted to a dedicated instance instead of serverless. This is the issue I see:

```<code>MongoDartError (MongoDart Error: Authentication failed.)
</code>```

I'm using dedicated cluster with 3 nodes, deployment name is com-new and db name is main:

```<code>var db = await Db.create('mongodb+srv://com-admin:*****@com-new.iv00u.mongodb.net/main');
await db.open(); // MongoDart Error
</code>```

This is working correctly on mongodb compass and mongoose, but on mongodart it gives the error auth failed. I also tried this:

```<code>mongodb+srv://com-admin:*****@com-new.iv00u.mongodb.net/main?authSource=admin
</code>```

& this

```<code>mongodb+srv://com-admin:*****@com-new.iv00u.mongodb.net/main/?authSource=admin
</code>```

This exact command is working with the old serverless db instance, but I want to use changeStreams which is not available unless we use a dedicated or shared cluster.

Title: MongoDart Authentication format issue

Body:
I'm trying to use MongoDart with Dart as backend. It was working fine till I shifted to a dedicated instance instead of serverless. This is the issue I see:

MongoDartError (MongoDart Error: Authentication failed.)

I'm using dedicated cluster with 3 nodes, deployment name is com-new and db name is main:

var db = await Db.create('mongodb+srv://com-admin:*****@com-new.iv00u.mongodb.net/main');
await db.open(); // MongoDart Error

This is working correctly on mongodb compass and mongoose, but on mongodart it gives the error auth failed. I also tried this:

mongodb+srv://com-admin:*****@com-new.iv00u.mongodb.net/main?authSource=admin

& this

mongodb+srv://com-admin:*****@com-new.iv00u.mongodb.net/main/?authSource=admin

This exact command is working with the old serverless db instance, but I want to use changeStreams which is not available unless we use a dedicated or shared cluster.


问:
Can i create a LOGON trigger to change the value of 'STATUS' on a table when the user login in? | SQL Server
The idea is to Update the status of the User on User's Table during the login process using a trigger. The LOGON trigger will only fire on that database only

It is possible to do? plus a trigger that will change that value when the user closes the session.

The purpose of this is to make sure that the PROCEDURE'S that check the condition and let the user know the 'it's not available', when the user isn't logged in.

This is for a school project, it's not ideal.


问:
Alpine js x-text not defined after drag and drop operation
Hi all alpine js geeks,

I am trying to set datatransfer property of drag and drop api with the html of the current html element.

```<code><span draggable="true" class="dropdown-item fs-6 cursor-pointer databoard-grid-draggable"
:id="$id('databoard-grid-draggable')" @dragstart="
    (event) => {
        event.dataTransfer.setData('text', event.target.innerHTML);
    }
">
    <i class="fa fa-fw me-2" :class="module.icon"></i>
    <span x-text="module.name"></span>
</span>
</code>```

However, when this element is dropped at certain dropping place and I am trying to pickup the html which was set via dataTransfer method this way, Alpine js is re-evaluating x-text attribute at that drop place and giving error about module being not defined.

```<code>@drop.prevent="(event) => {
        $(event.target).html(event.dataTransfer.getData('text'))
    }"
</code>```

Uncaught ReferenceError: module is not defined

Obviously it gives this error due to x-data for module is not defined at dropping place.
I can of course prepare html in that dragstart function via string concatenation in same fashion as inner html and then set dataTransfer's text but it feels somewhat cumbersome.

How to strip out those x- attributes or any other alpine attributes from html so that it does not complaint about the data is not defined?

Body:
Hi all alpine js geeks,

I am trying to set datatransfer property of drag and drop api with the html of the current html element.

 {
        event.dataTransfer.setData('text', event.target.innerHTML);
    }
">

However, when this element is dropped at certain dropping place and I am trying to pickup the html which was set via dataTransfer method this way, Alpine js is re-evaluating x-text attribute at that drop place and giving error about module being not defined.

@drop.prevent="(event) => {
        $(event.target).html(event.dataTransfer.getData('text'))
    }"

Uncaught ReferenceError: module is not defined

Obviously it gives this error due to x-data for module is not defined at dropping place.
I can of course prepare html in that dragstart function via string concatenation in same fashion as inner html and then set dataTransfer's text but it feels somewhat cumbersome.

How to strip out those x- attributes or any other alpine attributes from html so that it does not complaint about the data is not defined?


问:
Blocked bots from websites using JavaScripting
I have made a website that has some information that people are desperate to get, but the amount of data is extremely high which prevent  people to manually copy/past the data. But what I'm worried about is web scrapers such as selenium, I've realised websites like YouTube automatically detect if the user/client is a bot or a real human. There is two ways this could eventually be done, A: use reCAPTCHA, B: write a JavaScript code to detect it automatically.

Option A would have worked perfectly but my website does not require the user to log in to see the information which makes reCAPTCHA useless. In my opinion option B has a lot more potentials because i have experience working with selenium and in my knowledge when u open a selenium screen you will get a text like this photo which gives me a bit of hope to find it out using JavaScript. Can anyone help me?


问:
Firebase and React JS Authentication
I want to design a web page in which User can register via phone number, OTP Received and password set by user and then login with that phone number and password in future. How can i implement this feature in firebase as backend and React JS as Frontend.

i tried using firebase but there is only login method via email and Password, there is no method for phone number and password login available.

Title: Firebase and React JS Authentication


问:
Clicking on Multiple Local Notifications on Android only opens the associated Application, not a specific activity/Screen
My current Android application generates local notifications.

When a user clicks on a specific local notification the associated activity is navigated too.

However, when there are multiple local notifications presented and the user clicks on them in an unexpanded state all that happens is my application simple opens on the last visited page.

Is there any way I can change this behaviour?

For example could I pick the first local notification in a group and navigate to its associated activity within my application instead of simply opening my application?


问:
Is google chart supported in Preact?
I am trying to complete my application in preact. I am running into an issue now, I can't display and update google donut chart with data from preact. Is this possible? Can I use react-google-chart package in preact?</p>

Title: Is google chart supported in Preact?


问:
Started Snackbar animation from any view and not in bottom screen
I want my Snackbar to start the animation from the view in red and not at the bottom of the screen as by default, I wanted to give the feeling that the snackbar is appearing behind this view, unfortunately, I don't get good results.

Note: The project I'm working on is not using coordinatorlayout, but I can use.

Activity

```<code>class MainActivity : AppCompatActivity() {

    private lateinit var snackbar : Snackbar
    private lateinit var binding: ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        with(binding) {
            val view = root
            setContentView(view)
            snackbar = Snackbar.make(this@MainActivity, view, "Teste", Snackbar.LENGTH_SHORT)
            snackbar.anchorView = textText
            snackbar.animationMode = BaseTransientBottomBar.ANIMATION_MODE_SLIDE
            btnSnackbar.setOnClickListener {
                snackbar.show()
            }
        }
    }
}
</code>```

Layout

```<code><?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">

        <Button
            android:id="@+id/btn_snackbar"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            android:text="@string/snackbar" />

        <TextView
            android:id="@+id/text_text"
            android:layout_width="match_parent"
            android:layout_height="70dp"
            android:background="@color/design_default_color_error"
            android:gravity="center"
            android:text="Hello World!"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent" />

    </androidx.constraintlayout.widget.ConstraintLayout>
</layout>
</code>```
```<code>com.google.android.material:material:1.7.0
</code>```

I tried using elevation to override the snackbar and it doesn't work either.

Body:
I want my Snackbar to start the animation from the view in red and not at the bottom of the screen as by default, I wanted to give the feeling that the snackbar is appearing behind this view, unfortunately, I don't get good results.

Note: The project I'm working on is not using coordinatorlayout, but I can use.

Activity

class MainActivity : AppCompatActivity() {

    private lateinit var snackbar : Snackbar
    private lateinit var binding: ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        with(binding) {
            val view = root
            setContentView(view)
            snackbar = Snackbar.make(this@MainActivity, view, "Teste", Snackbar.LENGTH_SHORT)
            snackbar.anchorView = textText
            snackbar.animationMode = BaseTransientBottomBar.ANIMATION_MODE_SLIDE
            btnSnackbar.setOnClickListener {
                snackbar.show()
            }
        }
    }
}

Layout

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">

        <Button
            android:id="@+id/btn_snackbar"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            android:text="@string/snackbar" />

        <TextView
            android:id="@+id/text_text"
            android:layout_width="match_parent"
            android:layout_height="70dp"
            android:background="@color/design_default_color_error"
            android:gravity="center"
            android:text="Hello World!"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent" />

    </androidx.constraintlayout.widget.ConstraintLayout>
</layout>

com.google.android.material:material:1.7.0

I tried using elevation to override the snackbar and it doesn't work either.


问:
No Intellisense for c# files and not being able to create them in vs code
I have this problem, where i can't create new .cs files in vs code. I also dont see any Intellisense for c# and it seems like vs code isn't even recoginizing the language even though i have the C# extension downloaded.
I am on Windows, use the newest vs code version and also the lates .NET sdk 7.0.
Example

I tried to reinstall vscode and the .NET sdk.
Also tried to manually select the paths that OmniSharp should use.
I saw a lot of times on here that i should use an older version of the C# extension, so i tried it and so far none of the above have worked.


问:
What is the query for COLUMN hashing using SHA-256 algorithm in presto?
COLUMN hashing using SHA-256 algorithm in presto.

I tried and I am getting hashed column output but I need the output in SHA-256 format in Presto.


问:
Why don't Proximity Prompts work without a character?
I'm in a pickle. (not literally, of course)

I had a ship game, which used Proximity Prompts to enter the docks. This worked well enough. However, that was for a click to move system, and now I'm attempting to make a direct control system (e.g. you press WASD to move your ship instead of clicking a point on the ocean), and as such, there is no character in the game, and have done everything else without a character.

In short: They don't work now and I have no clue why.

The script is near enough the exact same on both games (The original game's script has a lot more other functions in it, but nothing that would affect this), and so is the configuration of the  Proximity Prompt. But I don't see how it could be to do with the lack of a player Character, and if it is, how do I edit the default code for it, to work without one? (I had a look, but couldn't find anything useful) As it doesn't seem like it will have direct dependence on the character, as any animations or custom behaviour would have to be done connecting to the ProximityPromptService/Prompt itself to add those via the events.

This is literally the whole server-side script I have for it.

```<code>local proximitypromptservice = game:GetService("ProximityPromptService")

local function get_player_data (player)
... --Unrelated, it's just a function to get player data, no issues here.
end

proximitypromptservice.PromptTriggered:Connect(function(promptobject,player)
    print("Prompt TRIGGERED") --Not seen in the log when the Prompt is pressed.
    if promptobject.Name == "DockControl" then
        print("DOCKCONTROL")
        if player.IsLoading.Value == false then
            game.ReplicatedStorage.Dock.AccessDock:Fire(player,...)
        end

    end

end)
</code>```

It's probably worth noting that when you press the key, e.g. E, it does the hold Duration animation and then disappears, and reappears as you'd normally expect. Creating a custom docking system is not out of the question, but I would really really prefer not to create an overcomplicated, clunky system for something that should work out of the box.

Any help would be appreciated,
The Frog.

PS: Also tried this on both local and server scripts as a child of the prompt to no avail.

```<code>script.Parent.Triggered:Connect(function()
    print("TRIGGERED")
end)
</code>```

Body:
I'm in a pickle. (not literally, of course)

I had a ship game, which used Proximity Prompts to enter the docks. This worked well enough. However, that was for a click to move system, and now I'm attempting to make a direct control system (e.g. you press WASD to move your ship instead of clicking a point on the ocean), and as such, there is no character in the game, and have done everything else without a character.

In short: They don't work now and I have no clue why.

The script is near enough the exact same on both games (The original game's script has a lot more other functions in it, but nothing that would affect this), and so is the configuration of the  Proximity Prompt. But I don't see how it could be to do with the lack of a player Character, and if it is, how do I edit the default code for it, to work without one? (I had a look, but couldn't find anything useful) As it doesn't seem like it will have direct dependence on the character, as any animations or custom behaviour would have to be done connecting to the ProximityPromptService/Prompt itself to add those via the events.

This is literally the whole server-side script I have for it.

local proximitypromptservice = game:GetService("ProximityPromptService")

local function get_player_data (player)
... --Unrelated, it's just a function to get player data, no issues here.
end

proximitypromptservice.PromptTriggered:Connect(function(promptobject,player)
    print("Prompt TRIGGERED") --Not seen in the log when the Prompt is pressed.
    if promptobject.Name == "DockControl" then
        print("DOCKCONTROL")
        if player.IsLoading.Value == false then
            game.ReplicatedStorage.Dock.AccessDock:Fire(player,...)
        end

    end

end)

It's probably worth noting that when you press the key, e.g. E, it does the hold Duration animation and then disappears, and reappears as you'd normally expect. Creating a custom docking system is not out of the question, but I would really really prefer not to create an overcomplicated, clunky system for something that should work out of the box.

Any help would be appreciated,
The Frog.

PS: Also tried this on both local and server scripts as a child of the prompt to no avail.

script.Parent.Triggered:Connect(function()
    print("TRIGGERED")
end)


问:
Daath AI Parser does not work if replaced with Amazon product
I have this code that is working as expected that I got from https://github.com/kagermanov27/daath-ai-parser:

```<code>import requests

uri = "https://ai.kagermanov.com/classify"

headers = {"Content-Type": "application/json"}

data = {
  "path": "google.google_local_results",
  "targets": [
    " some_long_text"
  ],
  "openai_key": "<OPENAI KEY>"
}

r = requests.post(url=uri, headers=headers, json=data)

print(r.json()["results"])
</code>```

But the problem is that if I change the path to "amazon.amazon_listings" and replace targets by the HTML code from Amazon listing, it does not return the product details. Is there anything else I need to change other than openai_key variable?

Body:
I have this code that is working as expected that I got from https://github.com/kagermanov27/daath-ai-parser:

import requests

uri = "https://ai.kagermanov.com/classify"

headers = {"Content-Type": "application/json"}

data = {
  "path": "google.google_local_results",
  "targets": [
    " some_long_text"
  ],
  "openai_key": "<OPENAI KEY>"
}

r = requests.post(url=uri, headers=headers, json=data)

print(r.json()["results"])

But the problem is that if I change the path to "amazon.amazon_listings" and replace targets by the HTML code from Amazon listing, it does not return the product details. Is there anything else I need to change other than openai_key variable?


问:
How to tell if user cancels html file input on ios
I have a custom file input button that should change styling when it is pressed and the native context menu / file chooser is open

It should revert the styling changes when you dismiss or cancel the file chooser.

A standard way of noticing a cancelled file input in js is by listening to focus events, but the context menu on ios does not change focus. To hack around this I'm also listening to touchend events for when the user touches outside the context menu. The problem is when the user press on photo library or choose file. This opens up a bottom sheet that does not change focus in the browser and when you dismiss it there are seemingly no events noticing the browser of this. Taking a photo works because it opens up the camera which gives new focus to the window when cancelled.

Remember that this can only be replicated on ios (I notice the touchend and focus events are having trouble in stack overflow's code runner. It works better on jsfiddle https://jsfiddle.net/L02q5h8u/1/)

const button = document.querySelector('button');
const fileInput = document.querySelector('input');

button.onclick = () => {
  button.style.background = 'red'
  fileInput.click();
}

const resetButtonStyling = () => {
  button.style.background = 'initial'
}

window.addEventListener('touchend', resetButtonStyling);
window.addEventListener('focus', resetButtonStyling);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>input {
  display: none;
}</code>```

<button>
  Upload file
</button>
<input type='file' id='fileInput' />```

Body:
I have a custom file input button that should change styling when it is pressed and the native context menu / file chooser is open

It should revert the styling changes when you dismiss or cancel the file chooser.

A standard way of noticing a cancelled file input in js is by listening to focus events, but the context menu on ios does not change focus. To hack around this I'm also listening to touchend events for when the user touches outside the context menu. The problem is when the user press on photo library or choose file. This opens up a bottom sheet that does not change focus in the browser and when you dismiss it there are seemingly no events noticing the browser of this. Taking a photo works because it opens up the camera which gives new focus to the window when cancelled.

Remember that this can only be replicated on ios (I notice the touchend and focus events are having trouble in stack overflow's code runner. It works better on jsfiddle https://jsfiddle.net/L02q5h8u/1/)

const button = document.querySelector('button');
const fileInput = document.querySelector('input');

button.onclick = () => {
  button.style.background = 'red'
  fileInput.click();
}

const resetButtonStyling = () => {
  button.style.background = 'initial'
}

window.addEventListener('touchend', resetButtonStyling);
window.addEventListener('focus', resetButtonStyling);

input {
  display: none;
}

<button>
  Upload file
</button>
<input type='file' id='fileInput' />


问:
arXiv not recognizing tex file as a tex file (type unknown)
I'm trying to upload a paper to arXiv and it's not recognizing one of my tex files as a tex file

When I try to process it like this, I get a general error message suggesting I check my file types.

My Macbook is recognizing the file as a tex file.

I've tried redownloading my files from overleaf multiple times.
I've unzipped and rezipped my files after making sure the file is recognized as a tex file by my macbook.


问:
am getting a "Flutter XML Request Error" every time i try to scrape data from the internet
```<code>var client = http.Client();

    var uri = Uri.https('verywellmind.com', 'what-is-happiness-4869755');
    var response = await client.get(uri);
</code>```

I have tries multiple options but am still getting the error below;

```<code>XMLHttpRequest error.
    dart:sdk_internal 136759:30                  get current
packages/http/src/browser_client.dart 69:22
dart:sdk_internal 42919:58                   runUnary
dart:sdk_internal 37493:29                   handleValue
dart:sdk_internal 38088:49                   handleValueCallback
dart:sdk_internal 38126:17                   _propagateToListeners
dart:sdk_internal 37947:25                   [_complete]
dart:sdk_internal 43372:24                   _cancelAndValue
dart:sdk_internal 22383:17
dart:sdk_internal 5609:16                    _checkAndCall
dart:sdk_internal 5614:17                    dcall
dart:sdk_internal 115542:23

No branch

</code>```

I really don't know why.. is there possible solutions?

XMLHttpRequest error in flutter web [Enabling CORS AWS API gateway]

I tried out all the solutions from the above link but it still failed to work

Body:
var client = http.Client();

    var uri = Uri.https('verywellmind.com', 'what-is-happiness-4869755');
    var response = await client.get(uri);

I have tries multiple options but am still getting the error below;

XMLHttpRequest error.
    dart:sdk_internal 136759:30                  get current
packages/http/src/browser_client.dart 69:22
dart:sdk_internal 42919:58                   runUnary
dart:sdk_internal 37493:29                   handleValue
dart:sdk_internal 38088:49                   handleValueCallback
dart:sdk_internal 38126:17                   _propagateToListeners
dart:sdk_internal 37947:25                   [_complete]
dart:sdk_internal 43372:24                   _cancelAndValue
dart:sdk_internal 22383:17
dart:sdk_internal 5609:16                    _checkAndCall
dart:sdk_internal 5614:17                    dcall
dart:sdk_internal 115542:23

No branch

I really don't know why.. is there possible solutions?

XMLHttpRequest error in flutter web [Enabling CORS AWS API gateway]

I tried out all the solutions from the above link but it still failed to work


问:
How to get result from jquery datepicker `onSelected` property?
I have this code in JavaScript that generates table row based on user inputs. Now I used switch to point out a column, on what it must render. If it is case 0, it will render an editable which contains a jquery datepicker(). If it is case 1, it will render  in read-only mode. Now what I want is every time a user clicked on jquery datepicker(), it will get the current year date and be subtracted to selected year date, which is possible using onSelected property of datepicker(), and must output the result in  from my case 1.

Sample Table:

//Here the user inputted 2, which rendered 2 rows
|      Date Of Birth  |     Age          |
|---------------------|------------------|
|     10/01/2007      |        15        |
|     10/01/2005      |        18        |

//Here the user clicked datepicker() with a date of  10/01/2007 in row 1 and 10/01/2005  in row 2

Code:

```<code>    let rowCount = //user inputted number

  let columnCount = 3;
            let html = "<tbody>";

            for (let i = 0; i <parseInt(rowCount); i++)
            {
                html += "<tr>";
                for (let k = 0; k < columnCount; k++)
                {
                    switch (k)
                    {
                        case 0:
                            html += "<td \"contenteditable=\"true\" ><div contenteditable>  <input id=\"dobData-" + i + "\"type = \"text\" > </div ></td>";
                            break;
                        case 1:
                            html += "<td id=\"ageData-" + i + "\" contenteditable=\"false\"></td>";
                            break;

                        default:
                            html += "<td contenteditable=\"true\"></td>";
                            break;

                    }

                }
                html += "</tr>";

            }

            html += "</tbody>"

;
</code>```

What I have done so far:

//This function makes my case 4, above to support datepicker()

```<code>function dobDatePicker() {
    for (var i = 0; i < parseInt(rowCount); i++) {
        var currentYear = new Date().getFullYear()
        let acceptedAge= 15

        $("#dobData-" + i).datepicker({
            maxDate: new Date(currentYear - acceptedAge, 11, 31) ,
            onSelect: function (date) {
                var selectedDate = new Date(date);
                var age = currentYear - selectedDate.getFullYear();

                 //Now I do not know what is next, so that I can pass the variable age to `${"#ageData-" + i}`
            }

        });

    }
</code>```

Body:
I have this code in JavaScript that generates table row based on user inputs. Now I used switch to point out a column, on what it must render. If it is case 0, it will render an editable which contains a jquery datepicker(). If it is case 1, it will render  in read-only mode. Now what I want is every time a user clicked on jquery datepicker(), it will get the current year date and be subtracted to selected year date, which is possible using onSelected property of datepicker(), and must output the result in  from my case 1.

Sample Table:

//Here the user inputted 2, which rendered 2 rows
|      Date Of Birth  |     Age          |
|---------------------|------------------|
|     10/01/2007      |        15        |
|     10/01/2005      |        18        |

//Here the user clicked datepicker() with a date of  10/01/2007 in row 1 and 10/01/2005  in row 2

Code:

    let rowCount = //user inputted number

  let columnCount = 3;
            let html = "
";

            for (let i = 0; i <parseInt(rowCount); i++)
            {
                html += "
";
                for (let k = 0; k < columnCount; k++)
                {
                    switch (k)
                    {
                        case 0:
                            html += "
  <input id=\"dobData-" + i + "\"type = \"text\" >
	";
                            break;
                        case 1:
                            html += "	";
                            break;

                        default:
                            html += "	";
                            break;

                    }

                }
                html += "
";

            }

            html += "
"

;

What I have done so far:

//This function makes my case 4, above to support datepicker()

function dobDatePicker() {
    for (var i = 0; i < parseInt(rowCount); i++) {
        var currentYear = new Date().getFullYear()
        let acceptedAge= 15

        $("#dobData-" + i).datepicker({
            maxDate: new Date(currentYear - acceptedAge, 11, 31) ,
            onSelect: function (date) {
                var selectedDate = new Date(date);
                var age = currentYear - selectedDate.getFullYear();

                 //Now I do not know what is next, so that I can pass the variable age to `${"#ageData-" + i}`
            }

        });

    }


问:
How to create a dynamic hexagon with Angular?
I'm trying to create the following input hexagon:

```<code>  1  2  3

4   5  6   7

  8   9  10
</code>```

The number of columns and rows is dynamic.
The numbers represents fields where the user can input his numbers. Any number between 1 - 999.
Currently my problem is placing the fields in the correct position.
I have a two dimentional array (matrix) that holds the fields / data.
I just don't know how to place the fields on the screen.

I have the following code :

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

  <input number [(ngModel)]="matrix[r][c]"  >

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

Currently (line 1) I get a squre matrix displayed justified to the left side of the screen.
What I need is something like {{c*30}}px which is in line 2. If I'll know how to dynamically place the colums I'll know how to place the rows.
Thanks
Moshik

Body:
I'm trying to create the following input hexagon:

  1  2  3

4   5  6   7

  8   9  10

The number of columns and rows is dynamic.
The numbers represents fields where the user can input his numbers. Any number between 1 - 999.
Currently my problem is placing the fields in the correct position.
I have a two dimentional array (matrix) that holds the fields / data.
I just don't know how to place the fields on the screen.

I have the following code :

  <input number [(ngModel)]="matrix[r][c]"  >

Currently (line 1) I get a squre matrix displayed justified to the left side of the screen.
What I need is something like {{c*30}}px which is in line 2. If I'll know how to dynamically place the colums I'll know how to place the rows.
Thanks
Moshik


问:
CATIA VBA Connection with Excel
I wrote a piece of code in VBA of CATIA, using Selection object. I needed an access to a Excel file to get some value from it, so I ticked the library "Microsoft Excel Object Library", but whenever I do that, an error appear with the message "Run-time error '91. Object variable or With block variable not set" (see the image). Otherwise there is no problem. I can't make out why? Any help would be appreciated, please!

Title: CATIA VBA Connection with Excel


问:
Spring Boot & QueryDSL with compilation error: due to QClass symbol not found
I am new to Querydsl , but I am having problems with generating Q classes.
I get a lot of errors that a Q'class' cannot be resolved , like this :

```<code>Cannot find symbol class QProduct
</code>```

the code

```<code>private final QProduct qProduct = QProduct.product;
</code>```

my project is built with :

spring-boot.version : 2.0.8 ;

Java version : 1.8 ;

Maven version : 3.0  ;

Hibernate version : 5.2.17 ;

postgresql : 42.2.5 ;

i'm use "maven-apt-plugin" for generated Q class.

porn.xml

```<code>        <dependency>
            <groupId>com.querydsl</groupId>
            <artifactId>querydsl-apt</artifactId>
            <version>4.2.1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>com.querydsl</groupId>
            <artifactId>querydsl-jpa</artifactId>
            <version>4.2.1</version>
        </dependency>
</code>```
```<code>

            <plugin>
                <groupId>com.mysema.maven</groupId>
                <artifactId>apt-maven-plugin</artifactId>
                <version>1.1.3</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>process</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>target/generated-sources</outputDirectory>
                            <processor>com.querydsl.apt.jpa.JPAAnnotationProcessor</processor>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
</code>```

I have already tried this solution but the problem persists

```<code><executions>
    <execution>
        <goals>
            <goal>process</goal>
        </goals>
        <phase>generate-sources</phase>
        <configuration>
            <outputDirectory>target/generated-sources/querydsl/java
            </outputDirectory>
            <processor>com.querydsl.apt.QuerydslAnnotationProcessor</processor>
            <options>
                <querydsl.logInfo>true</querydsl.logInfo>
                <querydsl.listAccessors>false</querydsl.listAccessors>
                <querydsl.useGetters>true</querydsl.useGetters>
                <querydsl.unknownAsEmbeddable>true</querydsl.unknownAsEmbeddable>
            </options>
        </configuration>
    </execution>
</executions>
</code>```

I looked at other topic similar to mine but their solution does not work on my project

What is wrong?

Thanks!

Body:
I am new to Querydsl , but I am having problems with generating Q classes.
I get a lot of errors that a Q'class' cannot be resolved , like this :

Cannot find symbol class QProduct

the code

private final QProduct qProduct = QProduct.product;

my project is built with :

spring-boot.version : 2.0.8 ;

Java version : 1.8 ;

Maven version : 3.0  ;

Hibernate version : 5.2.17 ;

postgresql : 42.2.5 ;

i'm use "maven-apt-plugin" for generated Q class.

porn.xml

        <dependency>
            <groupId>com.querydsl</groupId>
            <artifactId>querydsl-apt</artifactId>
            <version>4.2.1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>com.querydsl</groupId>
            <artifactId>querydsl-jpa</artifactId>
            <version>4.2.1</version>
        </dependency>

            <plugin>
                <groupId>com.mysema.maven</groupId>
                <artifactId>apt-maven-plugin</artifactId>
                <version>1.1.3</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>process</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>target/generated-sources</outputDirectory>
                            <processor>com.querydsl.apt.jpa.JPAAnnotationProcessor</processor>
                        </configuration>
                    </execution>
                </executions>
            </plugin>

I have already tried this solution but the problem persists

<executions>
    <execution>
        <goals>
            <goal>process</goal>
        </goals>
        <phase>generate-sources</phase>
        <configuration>
            <outputDirectory>target/generated-sources/querydsl/java
            </outputDirectory>
            <processor>com.querydsl.apt.QuerydslAnnotationProcessor</processor>
            <options>
                <querydsl.logInfo>true</querydsl.logInfo>
                <querydsl.listAccessors>false</querydsl.listAccessors>
                <querydsl.useGetters>true</querydsl.useGetters>
                <querydsl.unknownAsEmbeddable>true</querydsl.unknownAsEmbeddable>
            </options>
        </configuration>
    </execution>
</executions>

I looked at other topic similar to mine but their solution does not work on my project

What is wrong?

Thanks!


问:
Save RTSP to mp4 with ffmpeg/libav? Video is not of the right length, possibly too fast?
inspired by other stackoverflow answers, I wrote a code to get an rtps stream into an mp4 file. I tried commenting as much as possible:

#include <stdio.h>
#include <stdlib.h>
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
#include <libavformat/avio.h>
#include <sys/time.h>

time_t get_time()
{
  struct timeval tv;

  gettimeofday(&tv, NULL);

  return tv.tv_sec;
}

int main(int argc, char* argv[])
{
  AVFormatContext* ifcx = NULL;
  AVCodecContext* iccx;
  AVStream* ist;
  int i_index;
  time_t timenow, timestart;

  AVFormatContext* ofcx;
  AVOutputFormat* ofmt;
  AVStream* ost;

  AVPacket pkt;

  int ix;

  const char* sProg = argv[0];
  const char* sFileInput;
  const char* sFileOutput;
  int bRunTime;

  if (argc != 4)
  {
    printf("Usage: %s url outfile runtime\n", sProg);
    return EXIT_FAILURE;
  }
  sFileInput = argv[1];
  sFileOutput = argv[2];
  bRunTime = atoi(argv[3]);

  // Initialize library
  av_log_set_level(AV_LOG_ERROR);
  avformat_network_init();

  //
  // Input
  //

  // open rtsp
  AVDictionary* opts = 0;
  av_dict_set(&opts, "rtsp_transport", "tcp", 0);
  if (avformat_open_input(&ifcx, sFileInput, 0, &opts) != 0)
  {
    printf("ERROR: Cannot open input file\n");
    return EXIT_FAILURE;
  }

  if (avformat_find_stream_info(ifcx, NULL) < 0)
  {
    printf("ERROR: Cannot find stream info\n");
    avformat_close_input(&ifcx);
    return EXIT_FAILURE;
  }

  snprintf(ifcx->url, sizeof(ifcx->url), "%s", sFileInput);

  // search video stream
  i_index = -1;
  AVCodecParameters* iccx_par;
  for (ix = 0; ix < ifcx->nb_streams; ix++)
  {
    iccx_par = ifcx->streams[ix]->codecpar;
    if (iccx_par->codec_type == AVMEDIA_TYPE_VIDEO)
    {
      ist = ifcx->streams[ix];
      i_index = ix;
      break;
    }
  }
  if (i_index < 0)
  {
    printf("ERROR: Cannot find input video stream\n");
    avformat_close_input(&ifcx);
    return EXIT_FAILURE;
  }

  // Allocate codec context and convert codec parameters to codec context
  iccx = avcodec_alloc_context3(NULL);
  avcodec_parameters_to_context(iccx, iccx_par);

  // set output format
  ofmt = av_guess_format("mp4", NULL, NULL);

  // create output context
  if (avformat_alloc_output_context2(&ofcx, ofmt, NULL, sFileOutput) < 0)
  {
    printf("ERROR: Cannot create output context\n");
    avformat_close_input(&ifcx);
    return EXIT_FAILURE;
  }

  // add video stream
  ost = avformat_new_stream(ofcx, NULL);
  if (!ost)
  {
    printf("ERROR: Cannot add output stream\n");
    avformat_close_input(&ifcx);
    avformat_free_context(ofcx);
    return EXIT_FAILURE;
  }

  // copy codec context
  if (avcodec_parameters_from_context(ost->codecpar, iccx) < 0)
  {
    printf("ERROR: Cannot copy codec context\n");
    avformat_close_input(&ifcx);
    avformat_free_context(ofcx);
    return EXIT_FAILURE;
  }

  // open output file
  if (!(ofmt->flags & AVFMT_NOFILE))
  {
    if (avio_open(&ofcx->pb, sFileOutput, AVIO_FLAG_WRITE) < 0)
    {
      printf("ERROR: Cannot open output file\n");
      avformat_close_input(&ifcx);
      avformat_free_context(ofcx);
      return EXIT_FAILURE;
    }
  }

  // write output file header
  if (avformat_write_header(ofcx, NULL) < 0)
  {
    printf("ERROR: Cannot write output file header\n");
    avformat_close_input(&ifcx);
    avio_close(ofcx->pb);
    avformat_free_context(ofcx);
    return EXIT_FAILURE;
  }

  //
  // Write data
  //
  AVRational time_base = ist->time_base;
  timestart = get_time();
  int64_t pts = 0;
  while (av_read_frame(ifcx, &pkt) >= 0)
  {
    if (get_time() - timestart > bRunTime)
    {
      break;
    }
    if (pkt.stream_index == i_index)
    {
      pkt.stream_index = ost->id;

      pkt.pts = pkt.duration * pts;
      pkt.dts = pkt.pts;

      if (av_interleaved_write_frame(ofcx, &pkt) < 0)
      {
        printf("ERROR: Cannot write packet\n");
        av_packet_unref(&pkt);
        break;
      }
      pts++;
    }
  }

  // write output file trailer
  if (av_write_trailer(ofcx) < 0)
  {
    printf("ERROR: Cannot write output file trailer\n");
  }

  //
  // Close
  //

  avformat_close_input(&ifcx);
  avio_close(ofcx->pb);
  avformat_free_context(ofcx);

  avformat_network_deinit();

  return EXIT_SUCCESS;
}
```
<p>Compile:</p>
<pre class="lang-bash prettyprint-override"><code>gcc test.c  -Wunused-variable -lavcodec -lavformat -lavfilter -lavdevice -lswresample -lswscale -lavutil -o a.out
</code>```

Run:

./a.out rtsp://wowzaec2demo.streamlock.net/vod/mp4:BigBuckBunny_115k.mp4 out.mp4 5
```
<p>Then using ffprobe, the video will last different time every time:
5.875000
6.500000</p>
<p>If i run the CLI</p>
<pre class="lang-bash prettyprint-override"><code>ffmpeg  -t 5 -i rtsp://wowzaec2demo.streamlock.net/vod/mp4:BigBuckBunny_115k.mp4 -vcodec copy -acodec copy -map 0 -f mp4 out.mp4
</code>```

It will always give 5.124000

What am I doing wrong?

Thanks!

Body:
inspired by other stackoverflow answers, I wrote a code to get an rtps stream into an mp4 file. I tried commenting as much as possible:

#include <stdio.h>
#include <stdlib.h>
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
#include <libavformat/avio.h>
#include <sys/time.h>

time_t get_time()
{
  struct timeval tv;

  gettimeofday(&tv, NULL);

  return tv.tv_sec;
}

int main(int argc, char* argv[])
{
  AVFormatContext* ifcx = NULL;
  AVCodecContext* iccx;
  AVStream* ist;
  int i_index;
  time_t timenow, timestart;

  AVFormatContext* ofcx;
  AVOutputFormat* ofmt;
  AVStream* ost;

  AVPacket pkt;

  int ix;

  const char* sProg = argv[0];
  const char* sFileInput;
  const char* sFileOutput;
  int bRunTime;

  if (argc != 4)
  {
    printf("Usage: %s url outfile runtime\n", sProg);
    return EXIT_FAILURE;
  }
  sFileInput = argv[1];
  sFileOutput = argv[2];
  bRunTime = atoi(argv[3]);

  // Initialize library
  av_log_set_level(AV_LOG_ERROR);
  avformat_network_init();

  //
  // Input
  //

  // open rtsp
  AVDictionary* opts = 0;
  av_dict_set(&opts, "rtsp_transport", "tcp", 0);
  if (avformat_open_input(&ifcx, sFileInput, 0, &opts) != 0)
  {
    printf("ERROR: Cannot open input file\n");
    return EXIT_FAILURE;
  }

  if (avformat_find_stream_info(ifcx, NULL) < 0)
  {
    printf("ERROR: Cannot find stream info\n");
    avformat_close_input(&ifcx);
    return EXIT_FAILURE;
  }

  snprintf(ifcx->url, sizeof(ifcx->url), "%s", sFileInput);

  // search video stream
  i_index = -1;
  AVCodecParameters* iccx_par;
  for (ix = 0; ix < ifcx->nb_streams; ix++)
  {
    iccx_par = ifcx->streams[ix]->codecpar;
    if (iccx_par->codec_type == AVMEDIA_TYPE_VIDEO)
    {
      ist = ifcx->streams[ix];
      i_index = ix;
      break;
    }
  }
  if (i_index < 0)
  {
    printf("ERROR: Cannot find input video stream\n");
    avformat_close_input(&ifcx);
    return EXIT_FAILURE;
  }

  // Allocate codec context and convert codec parameters to codec context
  iccx = avcodec_alloc_context3(NULL);
  avcodec_parameters_to_context(iccx, iccx_par);

  // set output format
  ofmt = av_guess_format("mp4", NULL, NULL);

  // create output context
  if (avformat_alloc_output_context2(&ofcx, ofmt, NULL, sFileOutput) < 0)
  {
    printf("ERROR: Cannot create output context\n");
    avformat_close_input(&ifcx);
    return EXIT_FAILURE;
  }

  // add video stream
  ost = avformat_new_stream(ofcx, NULL);
  if (!ost)
  {
    printf("ERROR: Cannot add output stream\n");
    avformat_close_input(&ifcx);
    avformat_free_context(ofcx);
    return EXIT_FAILURE;
  }

  // copy codec context
  if (avcodec_parameters_from_context(ost->codecpar, iccx) < 0)
  {
    printf("ERROR: Cannot copy codec context\n");
    avformat_close_input(&ifcx);
    avformat_free_context(ofcx);
    return EXIT_FAILURE;
  }

  // open output file
  if (!(ofmt->flags & AVFMT_NOFILE))
  {
    if (avio_open(&ofcx->pb, sFileOutput, AVIO_FLAG_WRITE) < 0)
    {
      printf("ERROR: Cannot open output file\n");
      avformat_close_input(&ifcx);
      avformat_free_context(ofcx);
      return EXIT_FAILURE;
    }
  }

  // write output file header
  if (avformat_write_header(ofcx, NULL) < 0)
  {
    printf("ERROR: Cannot write output file header\n");
    avformat_close_input(&ifcx);
    avio_close(ofcx->pb);
    avformat_free_context(ofcx);
    return EXIT_FAILURE;
  }

  //
  // Write data
  //
  AVRational time_base = ist->time_base;
  timestart = get_time();
  int64_t pts = 0;
  while (av_read_frame(ifcx, &pkt) >= 0)
  {
    if (get_time() - timestart > bRunTime)
    {
      break;
    }
    if (pkt.stream_index == i_index)
    {
      pkt.stream_index = ost->id;

      pkt.pts = pkt.duration * pts;
      pkt.dts = pkt.pts;

      if (av_interleaved_write_frame(ofcx, &pkt) < 0)
      {
        printf("ERROR: Cannot write packet\n");
        av_packet_unref(&pkt);
        break;
      }
      pts++;
    }
  }

  // write output file trailer
  if (av_write_trailer(ofcx) < 0)
  {
    printf("ERROR: Cannot write output file trailer\n");
  }

  //
  // Close
  //

  avformat_close_input(&ifcx);
  avio_close(ofcx->pb);
  avformat_free_context(ofcx);

  avformat_network_deinit();

  return EXIT_SUCCESS;
}

Compile:

gcc test.c  -Wunused-variable -lavcodec -lavformat -lavfilter -lavdevice -lswresample -lswscale -lavutil -o a.out

Run:

./a.out rtsp://wowzaec2demo.streamlock.net/vod/mp4:BigBuckBunny_115k.mp4 out.mp4 5

Then using ffprobe, the video will last different time every time:
5.875000
6.500000

If i run the CLI

ffmpeg  -t 5 -i rtsp://wowzaec2demo.streamlock.net/vod/mp4:BigBuckBunny_115k.mp4 -vcodec copy -acodec copy -map 0 -f mp4 out.mp4

It will always give 5.124000

What am I doing wrong?

Thanks!


问:
Is there a way to add audio to Tkinter video player?
When I run this code a window pops up and I can upload a video of which I can play/stop/pause the video; however the video will not have sound. Is there any way I can solve this issue? I am new to Python. Thanks.

```<code>from tkinter import *
from tkinter.filedialog import askopenfile
from tkVideoPlayer import TkinterVideo

# customtkinter.set_appearance_mode("System")  # Modes: system (default), light, dark
# customtkinter.set_default_color_theme("blue")  # Themes: blue (default), dark-blue, green

# create box
window = Tk()
# title of the box, not the text in the box
window.title("Tkinter Play Videos in Video Player")
window.geometry("700x450")
window.configure(bg="white")

def open_file():
    file = askopenfile(mode='r', filetypes=[
        ('Video Files', ["*.mp4"])])
    if file is not None:
        global filename
        filename = file.name
        global videoplayer
        videoplayer = TkinterVideo(master=window, scaled=True)
        videoplayer.load(r"{}".format(filename))
        videoplayer.pack(expand=True, fill="both")
        videoplayer.play()

def playAgain():
    print(filename)
    videoplayer.play()

def StopVideo():
    print(filename)
    videoplayer.stop()

def PauseVideo():
    print(filename)
    videoplayer.pause()

# center this label
lbl1 = Label(window, text="Video Player", bg="white",
             fg="blue", font="none 24 bold")
lbl1.config(anchor=CENTER)
lbl1.pack()

openbtn = Button(window, text='Open', command=lambda: open_file())
openbtn.pack(side=TOP, pady=2)

playbtn = Button(window, text='Play Video', command=lambda: playAgain())
playbtn.pack(side=TOP, pady=3)

stopbtn = Button(window, text='Stop Video', command=lambda: StopVideo())
stopbtn.pack(side=TOP, padx=4)

pausebtn = Button(window, text='Pause Video', command=lambda: PauseVideo())
pausebtn.pack(side=TOP, padx=5)

window.mainloop()
</code>```

The result video does not have audio.

Body:
When I run this code a window pops up and I can upload a video of which I can play/stop/pause the video; however the video will not have sound. Is there any way I can solve this issue? I am new to Python. Thanks.

from tkinter import *
from tkinter.filedialog import askopenfile
from tkVideoPlayer import TkinterVideo

# customtkinter.set_appearance_mode("System")  # Modes: system (default), light, dark
# customtkinter.set_default_color_theme("blue")  # Themes: blue (default), dark-blue, green

# create box
window = Tk()
# title of the box, not the text in the box
window.title("Tkinter Play Videos in Video Player")
window.geometry("700x450")
window.configure(bg="white")

def open_file():
    file = askopenfile(mode='r', filetypes=[
        ('Video Files', ["*.mp4"])])
    if file is not None:
        global filename
        filename = file.name
        global videoplayer
        videoplayer = TkinterVideo(master=window, scaled=True)
        videoplayer.load(r"{}".format(filename))
        videoplayer.pack(expand=True, fill="both")
        videoplayer.play()

def playAgain():
    print(filename)
    videoplayer.play()

def StopVideo():
    print(filename)
    videoplayer.stop()

def PauseVideo():
    print(filename)
    videoplayer.pause()

# center this label
lbl1 = Label(window, text="Video Player", bg="white",
             fg="blue", font="none 24 bold")
lbl1.config(anchor=CENTER)
lbl1.pack()

openbtn = Button(window, text='Open', command=lambda: open_file())
openbtn.pack(side=TOP, pady=2)

playbtn = Button(window, text='Play Video', command=lambda: playAgain())
playbtn.pack(side=TOP, pady=3)

stopbtn = Button(window, text='Stop Video', command=lambda: StopVideo())
stopbtn.pack(side=TOP, padx=4)

pausebtn = Button(window, text='Pause Video', command=lambda: PauseVideo())
pausebtn.pack(side=TOP, padx=5)

window.mainloop()

The result video does not have audio.


问:
Maximo Anywhere lookup filtering
I am working in Maximo Anywhere 7.6.4 - WorkExecution.

I wanted to filter the labor lookup based on the defsite of the connected user .

Let's say the user defsite is ='AAA' then the labors that have to appear are the labors who are in the site AAA

Any help would be appreciated. Thanks

```<code><whereClause clause="spi:worksite=${defsite}" id="additionallaborcraftrate_whereClause"/>
</code>```

Title: Maximo Anywhere lookup filtering

Body:
I am working in Maximo Anywhere 7.6.4 - WorkExecution.

I wanted to filter the labor lookup based on the defsite of the connected user .

Let's say the user defsite is ='AAA' then the labors that have to appear are the labors who are in the site AAA

Any help would be appreciated. Thanks

<whereClause clause="spi:worksite=${defsite}" id="additionallaborcraftrate_whereClause"/>