不忘初心

文章 评论 浏览 30

不忘初心 2025-02-20 22:41:19

可能是您要提取的ID在操作员数组中不存在的ID,这就是为什么您要获得一个空数组的原因,

无论ID是否存在,都可以运行此代码行

  const operator = operators.filter((operator) => operator.id !== operatorId)

Might be the id that you are extracting is not there in the operators array, that's why you are getting an empty array

you can run this line of code whether the id is there or not

  const operator = operators.filter((operator) => operator.id !== operatorId)

试图根据React-Redux Store过滤单个对象的ID过滤单个对象时获取一个空数组

不忘初心 2025-02-20 19:29:01

至少这些问题:

错误的分配大小 @Weather Vane

避免分配错误。分配给被告的对象的大小,而不是类型。

// t=(emp*)malloc(n*sizeof(int));
t = malloc(sizeof t[0] * n);

更容易正确编码,审查和维护。

非原始化p @craig estey

f(p =='y')是未定义的行为,因为p是非初始化的。

这暗示OP并未启用所有警告。节省时间 - 启用所有警告。

emp未定义

也许OP不是使用C编译器,而是使用C ++?

i未在中定义的(i = 0; i< n; i ++){

is int> int i;真正的代码?

“%s”

没有 width “%s”get> gets()差。使用宽度喜欢“%49S”

At least these issues:

Wrong allocation size @Weather Vane

Avoid allocation errors. Allocate to the size of the refenced object, not the type.

// t=(emp*)malloc(n*sizeof(int));
t = malloc(sizeof t[0] * n);

Easier to code right, review and maintain.

Uninitialized p @Craig Estey

f(p=='y') is undefined behavior as p is uninitialized.

This hints that OP is not compiling with all warnings enabled. Save time - enable all warnings.

emp not defined

Perhaps OP is not using a C compiler, but a C++ one?

i not defined in for (i = 0; i < n; i++) {

Is int I; the true code?

Bad "%s"

Without a width, "%s" is worse than gets(). Use a width like "%49s".

如何正确删除和修改功能正确

不忘初心 2025-02-20 16:29:39

假设结果需要为[[1,2,3,4],[5,6,7,8],[9,10]]您可以使用Array.Reduce:

const items = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]

const parts = 3
const wordsPerLine = Math.ceil(items.length / parts)

const result = items.reduce((resultArray, item, index) => {
  const arrayIndex = Math.floor(index / wordsPerLine)
  if (!resultArray[arrayIndex]) {
    resultArray[arrayIndex] = [] // start a new array
  }
  resultArray[arrayIndex].push(item)
  return resultArray
}, [])

// result => [[ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], [ 9, 10 ]]

Assuming the result needs to be [[ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], [ 9, 10 ]] you could use Array.reduce:

const items = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]

const parts = 3
const wordsPerLine = Math.ceil(items.length / parts)

const result = items.reduce((resultArray, item, index) => {
  const arrayIndex = Math.floor(index / wordsPerLine)
  if (!resultArray[arrayIndex]) {
    resultArray[arrayIndex] = [] // start a new array
  }
  resultArray[arrayIndex].push(item)
  return resultArray
}, [])

// result => [[ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], [ 9, 10 ]]

如何将和数组分为n数组JavaScript

不忘初心 2025-02-19 14:54:22

是的,您只能使用宏只能做到这一点:

macro_rules! compose {
    ($($rest:ident),+) => {
        |x| { compose!(expand x, $($rest),*) }
    };
    (expand $inner:expr, $function:ident, $($rest:ident),*) => {
        compose!(expand $function($inner), $($rest),*)
    };
    (expand $inner:expr, $function:ident) => {
        $function($inner)
    };
}

let a = compose!(f, g, h, i);
//expands into:
let a = |x| i(h(g(f(x))));

Yes, you can do that only using macros:

macro_rules! compose {
    ($($rest:ident),+) => {
        |x| { compose!(expand x, $($rest),*) }
    };
    (expand $inner:expr, $function:ident, $($rest:ident),*) => {
        compose!(expand $function($inner), $($rest),*)
    };
    (expand $inner:expr, $function:ident) => {
        $function($inner)
    };
}

let a = compose!(f, g, h, i);
//expands into:
let a = |x| i(h(g(f(x))));

带有纯宏的功能组成链

不忘初心 2025-02-19 04:54:40

尝试此

FirebaseDatabase.getInstance().getReference().child("Users").orderByChild("username");

在这里了解更多信息

Try this

FirebaseDatabase.getInstance().getReference().child("Users").orderByChild("username");

Learn more here

将用户列表分类为Android Studio中的字母顺序

不忘初心 2025-02-18 18:25:15

这是延续方法的另一个好候选人。讨论是在链接上的,但我将使用c进行以下操作,以控制方程的更非线性术语:

import sympy as sym
x,y = sym.symbols('x,y')
dmin = 70 #minimum of the actuator
dmax = 140 #maximum of the actuator

l3 = 10
l4 = 10

Amin = 0.523599 #min angle in radians
Amax = 2.0944 #max angle in radians
for c in range(10):
    c=c/S(10)
    cos1 = sym.cos(Amin - sym.atan(l4/x)*c - sym.atan(l3/y)*c)
    cos2 = sym.cos(Amax - sym.atan(l4/x)*c - sym.atan(l3/y)*c)
    a2 = x**2 + l4**2
    b2 = y**2 + l3**2
    f=sym.Eq(a2 + b2 - 2*sym.sqrt(a2)*sym.sqrt(b2)*cos1, dmin**2)
    g=sym.Eq(a2 + b2 - 2*sym.sqrt(a2)*sym.sqrt(b2)*cos2, dmax**2)
    if not c:
        gs = solve((f,g),(x,y),dict=False)
    else:
        sol = []
        for gi in gs:
            sol.append(nsolve((f,g),(x,y),gi))

gs

[(-107.967591836877, -48.6044884662980), 
(-107.967591836877, 48.6044884662980),
(-48.6044884662980, -107.967591836877),
(-48.6044884662980, 107.967591836877),
(48.6044884662980, -107.967591836877),
(48.6044884662980, 107.967591836877),
(107.967591836877, -48.6044884662980),
(107.967591836877, 48.6044884662980)]

' c转到1成为最终解决方案

>>> for i in ordered(sol):tuple(i)
...
(-111.790176548536, 48.5400429865187)
(-96.2635727943765, -52.7612279529407)
(-52.7612279529407, -96.2635727943765)
(-49.3470005072566, 104.216202951134)
(48.5400429865187, -111.790176548536)
(49.8069789979713, 117.241028072945)
(104.216202951134, -49.3470005072566)
(117.241028072945, 49.8069789979713)

This is another good candidate for the continuation method. The discussion is at the link but I would apply it as follows using c to control the more non-linear term of your equations:

import sympy as sym
x,y = sym.symbols('x,y')
dmin = 70 #minimum of the actuator
dmax = 140 #maximum of the actuator

l3 = 10
l4 = 10

Amin = 0.523599 #min angle in radians
Amax = 2.0944 #max angle in radians
for c in range(10):
    c=c/S(10)
    cos1 = sym.cos(Amin - sym.atan(l4/x)*c - sym.atan(l3/y)*c)
    cos2 = sym.cos(Amax - sym.atan(l4/x)*c - sym.atan(l3/y)*c)
    a2 = x**2 + l4**2
    b2 = y**2 + l3**2
    f=sym.Eq(a2 + b2 - 2*sym.sqrt(a2)*sym.sqrt(b2)*cos1, dmin**2)
    g=sym.Eq(a2 + b2 - 2*sym.sqrt(a2)*sym.sqrt(b2)*cos2, dmax**2)
    if not c:
        gs = solve((f,g),(x,y),dict=False)
    else:
        sol = []
        for gi in gs:
            sol.append(nsolve((f,g),(x,y),gi))

gs starts out as

[(-107.967591836877, -48.6044884662980), 
(-107.967591836877, 48.6044884662980),
(-48.6044884662980, -107.967591836877),
(-48.6044884662980, 107.967591836877),
(48.6044884662980, -107.967591836877),
(48.6044884662980, 107.967591836877),
(107.967591836877, -48.6044884662980),
(107.967591836877, 48.6044884662980)]

and is gradually modified as c goes to 1 to become the final solution

>>> for i in ordered(sol):tuple(i)
...
(-111.790176548536, 48.5400429865187)
(-96.2635727943765, -52.7612279529407)
(-52.7612279529407, -96.2635727943765)
(-49.3470005072566, 104.216202951134)
(48.5400429865187, -111.790176548536)
(49.8069789979713, 117.241028072945)
(104.216202951134, -49.3470005072566)
(117.241028072945, 49.8069789979713)

等待一个小时后,方程式无法解决

不忘初心 2025-02-17 21:50:37
In [11]: arr = np.array([[1,0],[2,3]])
In [12]: id(arr)
Out[12]: 1915221691344

In [13]: M = sparse.csr_matrix(arr)
In [14]: id(M)
Out[14]: 1915221319840

In [15]: arr += arr

In [16]: id(arr)
Out[16]: 1915221691344

+=用于数组的就位。

In [17]: M += M    
In [18]: id(M)
Out[18]: 1915221323200

对于稀疏矩阵,它会创建一个新的稀疏矩阵对象。它不会在现场修改矩阵。

对于此操作,可以将数据属性修改到位:

In [20]: M.data
Out[20]: array([2, 4, 6], dtype=int32)

In [21]: M.data += M.data

In [22]: M.A
Out[22]: 
array([[ 4,  0],
       [ 8, 12]], dtype=int32)

但是通常,在稀疏矩阵中添加一些东西可以修改其稀疏性。稀疏的开发人员以智慧决定了不可能的,或者只是不成本效益(编程或运行时间?),而无需创建新的矩阵。

虽然在np.matrix子类上构图稀疏矩阵,但它不是ndarray的子类,并且没有义务以完全相同的方式行事。

In [30]: type(M).__mro__
Out[30]: 
(scipy.sparse.csr.csr_matrix,
 scipy.sparse.compressed._cs_matrix,
 scipy.sparse.data._data_matrix,
 scipy.sparse.base.spmatrix,
 scipy.sparse.data._minmax_mixin,
 scipy.sparse._index.IndexMixin,
 object)
In [11]: arr = np.array([[1,0],[2,3]])
In [12]: id(arr)
Out[12]: 1915221691344

In [13]: M = sparse.csr_matrix(arr)
In [14]: id(M)
Out[14]: 1915221319840

In [15]: arr += arr

In [16]: id(arr)
Out[16]: 1915221691344

+= operates in-place for array.

In [17]: M += M    
In [18]: id(M)
Out[18]: 1915221323200

For the sparse matrix it creates a new sparse matrix object. It doesn't modify the matrix in-place.

For this operation, the data attribute could be modified in place:

In [20]: M.data
Out[20]: array([2, 4, 6], dtype=int32)

In [21]: M.data += M.data

In [22]: M.A
Out[22]: 
array([[ 4,  0],
       [ 8, 12]], dtype=int32)

But in general, adding something to a sparse matrix can modify its sparsity. The sparse developers, in their wisdom, decided it wasn't possible, or just not cost effective (programming or run time?) to do this without creating a new matrix.

While a sparse matrix is patterned on the np.matrix subclass, it is not a subclass of ndarray, and is not obligated to behave in exactly the same way.

In [30]: type(M).__mro__
Out[30]: 
(scipy.sparse.csr.csr_matrix,
 scipy.sparse.compressed._cs_matrix,
 scipy.sparse.data._data_matrix,
 scipy.sparse.base.spmatrix,
 scipy.sparse.data._minmax_mixin,
 scipy.sparse._index.IndexMixin,
 object)

传递到功能时,Scipy稀疏矩阵未修改

不忘初心 2025-02-17 12:02:16

您可以使用联合所有以简单的方式获得玩家的分数。然后,您可以订购分数并使用limit以最大分数获取行:

WITH scores AS
(
  SELECT pontuacao_jog1 AS score, data_jogo
  FROM partidas
  WHERE id_jogador1 = 'CR7'
  UNION ALL
  SELECT pontuacao_jog2 AS score, data_jogo
  FROM partidas
  WHERE id_jogador2 = 'CR7'
)
SELECT *
FROM scores
ORDER BY score DESC
LIMIT 1;

唯一问题:如果有两天的最高分数相同,则只会显示其中一个任意选择。如果您想显示这两者:

WITH scores AS ( <same as above> )
SELECT *
FROM scores
WHERE score = (SELECT MAX(score) FROM scores);

这是编写CTE的另一种方法(aka 使用子句):

WITH scores AS
(
  SELECT
    CASE WHEN id_jogador1 = 'CR7'
      THEN pontuacao_jog1
      ELSE pontuacao_jog2
    END AS score,
    data_jogo
  FROM partidas
  WHERE (id_jogador1 = 'CR7' OR id_jogador2 = 'CR7')
)

You can use UNION ALL to get a player's scores in an easy way. Then you can order the scores and use LIMIT to get the row with the maximum score:

WITH scores AS
(
  SELECT pontuacao_jog1 AS score, data_jogo
  FROM partidas
  WHERE id_jogador1 = 'CR7'
  UNION ALL
  SELECT pontuacao_jog2 AS score, data_jogo
  FROM partidas
  WHERE id_jogador2 = 'CR7'
)
SELECT *
FROM scores
ORDER BY score DESC
LIMIT 1;

Only problem: If there are two days with the same maximum score, you'll only show one of them arbitrarily chosen. If you want to show both:

WITH scores AS ( <same as above> )
SELECT *
FROM scores
WHERE score = (SELECT MAX(score) FROM scores);

And here is an alternative way to write the CTE (aka WITH clause):

WITH scores AS
(
  SELECT
    CASE WHEN id_jogador1 = 'CR7'
      THEN pontuacao_jog1
      ELSE pontuacao_jog2
    END AS score,
    data_jogo
  FROM partidas
  WHERE (id_jogador1 = 'CR7' OR id_jogador2 = 'CR7')
)

如何根据SQL中的第二和第三列之间的最大值在哪里选择列的值?

不忘初心 2025-02-17 02:40:16

首先,尝试获取最新的Chrome驱动程序,并检查是否解决了问题。

就我而言,它没有解决这个问题。但是,到目前为止,以下解决方案对我有用。以下是C#代码,但您可以使用特定语言遵循相同的逻辑。我们在这里做的是,

步骤1:使用硒操作对象专注于元素,

步骤2:然后单击元素

步骤3:如果有例外,那么我们在元素上触发javascript“ click”事件。通过Selenium浏览器驱动程序的“ ExecuteCript”方法执行JavaScript脚本。

您也可以跳过步骤1和2,也只尝试步骤3。步骤3会独自工作,但在一种情况下,我注意到某个方案中的某些奇怪行为,即使它成功单击了该元素,但在单击元素后仍会在我的代码其他部分中引起意外的行为。

            try
            {
                //Setup the driver and navigate to the web page...
                var driver = new ChromeDriver("folder path to the Chrome driver");
                driver.Navigate().GoToUrl("UrlToThePage");

                //Find the element...
                var element = driver.FindElement(By.Id("elementHtmlId")); 

                //Step 1
                new Actions(driver).MoveToElement(element).Perform();  

                //Step 2
                element.Click();
            }
            catch (Exception)
            {
                //Step 3
                driver.ExecuteScript("document.getElementById('elementHtmlId').click();");

            }

First, try to get the latest Chrome driver and check if it solves the issue.

In my case, it didn't fix the issue. But, the following solution worked for me so far. The following is C# code but you can follow same logic in your specific language. What we do here is,

Step 1: Focus on the element using the Selenium Actions object,

Step 2: Then do a click on the element

Step 3: If there's an exception, then we trigger a javascript "Click" event on the element by executing the javascript script through the Selenium browser driver's "ExecuteScript" method.

You can also skip step 1 and 2 and try only step 3 too. Step 3 would work on it's own but I noticed some strange behavior in one scenario in which step 3, even though it successfully clicked the element, caused unexpected behavior in other parts of my code after clicking the element.

            try
            {
                //Setup the driver and navigate to the web page...
                var driver = new ChromeDriver("folder path to the Chrome driver");
                driver.Navigate().GoToUrl("UrlToThePage");

                //Find the element...
                var element = driver.FindElement(By.Id("elementHtmlId")); 

                //Step 1
                new Actions(driver).MoveToElement(element).Perform();  

                //Step 2
                element.Click();
            }
            catch (Exception)
            {
                //Step 3
                driver.ExecuteScript("document.getElementById('elementHtmlId').click();");

            }

调试“元素”不可点击点。错误

不忘初心 2025-02-15 21:28:38

您的最后一个选择是要走的方法(错字除外):

MyType Reversed2(MyType value)
{
    Reverse(value);
    return value;
}

[n] RVO不适用于返回结果;,但至少它是隐式移动的,而不是复制的。

您要么根据参数的值类别,要么有一个副本 + a动作或两步。

Your last option is the way to go (except for the typo):

MyType Reversed2(MyType value)
{
    Reverse(value);
    return value;
}

[N]RVO doesn't apply to return result;, but at least it's implicitly moved, rather than copied.

You'll have either a copy + a move, or two moves, depending on the value category of the argument.

从函数返回参数时是否可以避免副本?

不忘初心 2025-02-15 19:47:11

我知道这是一个旧的线程,但是今天我写了以下问题(混合上面的答案以及更多内容),这是一个明确的解决方案:

@commands.Cog.listener()
async def on_voice_state_update(self, member, before, after):
    
    # Ignore if change from voice channels not from bot
    if not member.id == self.bot.user.id:
        return
    
    # Ignore if change from voice channels was triggered by disconnect()
    elif before.channel is not None:
        return
    
    # Check if playing when in voice channel, every 180 seconds
    else:
        voice = after.channel.guild.voice_client
        while True:
            await asyncio.sleep(180)
            
            # If not playing, disconnect
            if voice.is_playing() == False:
                await voice.disconnect()
                break

I'm aware that this is an old thread, but coming accross this problem today I wrote the following (mixing up the answers from above and more) and it was a definite solution:

@commands.Cog.listener()
async def on_voice_state_update(self, member, before, after):
    
    # Ignore if change from voice channels not from bot
    if not member.id == self.bot.user.id:
        return
    
    # Ignore if change from voice channels was triggered by disconnect()
    elif before.channel is not None:
        return
    
    # Check if playing when in voice channel, every 180 seconds
    else:
        voice = after.channel.guild.voice_client
        while True:
            await asyncio.sleep(180)
            
            # If not playing, disconnect
            if voice.is_playing() == False:
                await voice.disconnect()
                break

如何使Discord机器人在X分钟不活动后离开语音频道?

不忘初心 2025-02-15 15:26:58

没有这样的功能可以隐藏多行的一部分。我们只能在列中显示或隐藏整个项目。 SharePoint将显示前5行,并将其隐藏为默认情况。

There is no such function to hide a part of the multiline. We can only show or hide the whole item in the column. SharePoint will display top 5 lines and hide the others as default.

SharePoint(列表) - 多行夹具(仅显示第一行)

不忘初心 2025-02-15 13:13:02

请尝试以下操作:

constructor(
  private router: Router
) {
  router.events.pipe(
    filter(event => event instanceof NavigationStart)  
  ).subscribe((event: NavigationStart) => {
     // You only receive NavigationStart events
    console.log(event.url);
  });
}

对于严格的模式,您可以尝试以下操作:

constructor(
  private router: Router
) {
  router.events.pipe(
    filter((event): event is NavigationEnd => event instanceof NavigationStart)  
  ).subscribe((event: NavigationStart) => {
     // You only receive NavigationStart events
    console.log(event.url);
  });
}

Please try this:

constructor(
  private router: Router
) {
  router.events.pipe(
    filter(event => event instanceof NavigationStart)  
  ).subscribe((event: NavigationStart) => {
     // You only receive NavigationStart events
    console.log(event.url);
  });
}

For a strict mode you can try this:

constructor(
  private router: Router
) {
  router.events.pipe(
    filter((event): event is NavigationEnd => event instanceof NavigationStart)  
  ).subscribe((event: NavigationStart) => {
     // You only receive NavigationStart events
    console.log(event.url);
  });
}

更改URL,但不要允许浏览器加载该页面

不忘初心 2025-02-15 05:28:12

Spring automatically calls quit() on your injected driver

public class MyChromeDriver extends ChromeDriver
{
    private static final String SCREENSHOT_DIR = "/path/for/screenshots/";
   
    public void takeScreenshot(String fileName) throws IOException
    {
        File srcfile = getScreenshotAs(OutputType.FILE);
        File dstFile = new File(SCREENSHOT_DIR + fileName + ".png");

        dstFile.getParentFile().mkdirs();
        FileCopyUtils.copy(srcfile, dstFile);
    }
  
    /**
     * No-op quit which Spring can call after each test w/o doing any damage
     * @deprecated use {@link #realQuit()}
     */
    @Override
    @Deprecated
    public void quit() {}

    /**
     * Call this to actually invoke {@link ChromeDriver#quit()}
     */
    public void realQuit()
    {
        super.quit();
    }
}

这使我能够使我的基础测试类能够在错误时拍摄屏幕截图。

@ExtendWith(SeleniumMvcIntegrationTest.class)
public class SeleniumMvcIntegrationTest implements TestWatcher
{
    @Inject
    protected MyChromeDriver driver;

    @Override
    public void testFailed(ExtensionContext context, Throwable throwable)
    {
        getTestInstanceDriver(context).takeScreenshot(throwable.getClass().getSimpleName() + "-screenshot");

        // Can't call quit() in @AfterEach, or else it closes before we get the chance to take a screenshot
        getTestInstanceDriver(context).realQuit();
    }

    @Override
    public void testSuccessful(ExtensionContext context)
    {
        getTestInstanceDriver(context).realQuit();
    }

    @Override
    public void testDisabled(ExtensionContext context, Optional<String> reason)
    {
        getTestInstanceDriver(context).realQuit();
    }

    @Override
    public void testAborted(ExtensionContext context, Throwable cause)
    {
        getTestInstanceDriver(context).realQuit();
    }

    /**
     * This class is used to extend itself, which creates a new instance of SeleniumMvcIntegrationTest as a TestWatcher.
     * In the TestWatcher context, we want to access the driver belonging to the decorated instance; this convenience
     * method provides the ability to do that.
     */
    private MyChromeDriver getTestInstanceDriver(ExtensionContext context)
    {
        return ((SeleniumMvcIntegrationTest) context.getRequiredTestInstance()).driver;
    }
}

我在调用realquit()的地方,您可以轻松地使驱动程序打开。

Spring automatically calls quit() on your injected driver here. I was attempting to take screenshots whenever my tests failed, and finding the driver was already closed. I already had the need for a custom driver, so I fixed this with a no-op quit() override.

public class MyChromeDriver extends ChromeDriver
{
    private static final String SCREENSHOT_DIR = "/path/for/screenshots/";
   
    public void takeScreenshot(String fileName) throws IOException
    {
        File srcfile = getScreenshotAs(OutputType.FILE);
        File dstFile = new File(SCREENSHOT_DIR + fileName + ".png");

        dstFile.getParentFile().mkdirs();
        FileCopyUtils.copy(srcfile, dstFile);
    }
  
    /**
     * No-op quit which Spring can call after each test w/o doing any damage
     * @deprecated use {@link #realQuit()}
     */
    @Override
    @Deprecated
    public void quit() {}

    /**
     * Call this to actually invoke {@link ChromeDriver#quit()}
     */
    public void realQuit()
    {
        super.quit();
    }
}

This allowed me to give my base test class the ability to snap screenshots on error.

@ExtendWith(SeleniumMvcIntegrationTest.class)
public class SeleniumMvcIntegrationTest implements TestWatcher
{
    @Inject
    protected MyChromeDriver driver;

    @Override
    public void testFailed(ExtensionContext context, Throwable throwable)
    {
        getTestInstanceDriver(context).takeScreenshot(throwable.getClass().getSimpleName() + "-screenshot");

        // Can't call quit() in @AfterEach, or else it closes before we get the chance to take a screenshot
        getTestInstanceDriver(context).realQuit();
    }

    @Override
    public void testSuccessful(ExtensionContext context)
    {
        getTestInstanceDriver(context).realQuit();
    }

    @Override
    public void testDisabled(ExtensionContext context, Optional<String> reason)
    {
        getTestInstanceDriver(context).realQuit();
    }

    @Override
    public void testAborted(ExtensionContext context, Throwable cause)
    {
        getTestInstanceDriver(context).realQuit();
    }

    /**
     * This class is used to extend itself, which creates a new instance of SeleniumMvcIntegrationTest as a TestWatcher.
     * In the TestWatcher context, we want to access the driver belonging to the decorated instance; this convenience
     * method provides the ability to do that.
     */
    private MyChromeDriver getTestInstanceDriver(ExtensionContext context)
    {
        return ((SeleniumMvcIntegrationTest) context.getRequiredTestInstance()).driver;
    }
}

Where I'm calling realQuit(), you could just as easily leave the driver open.

弹簧导致WebDriver降低()&#x27;每次测试之后

不忘初心 2025-02-14 14:15:24

tl; dr:如果结果对象引用[第一个操作数]不是null,则将返回。否则,返回第二操作数(可能为null)的值。此外,如果返回null,则操作员可以抛出异常。


猫王操作员是许多编程语言的一部分,例如Kotlin,但也是Groovy或C#。
我发现 wikipedia 定义非常准确:

在某些计算机编程语言中,猫王操作员 ?:二进制运算符,如果该操作数为true ,否则评估并返回其第二操作数。它是三元条件运算符的变体? :,在这些语言(以及其他许多语言)中找到:猫王操作员是 ternary操作员,其第二个操作数省略了

Kotlin尤其如此:

某些计算机编程语言对于此操作员具有不同的语义。 必须导致对象参考,而不是必须产生布尔值的第一操作数。如果结果对象引用不是null,则将返回。否则,将返回第二操作数(可能为null)的值。如果第二操作数为null,则操作员也能够抛出异常。

一个例子:

x ?: y // yields `x` if `x` is not null, `y` otherwise.
x ?: throw SomeException() // yields `x` if `x` is not null, throws SomeException otherwise

TL;DR: If the resulting object reference [first operand] is not null, it is returned. Otherwise the value of the second operand (which may be null) is returned. Additionally, the operator can throw an exception if null is returned.


The Elvis operator is part of many programming languages, e.g. Kotlin but also Groovy or C#.
I find the Wikipedia definition pretty accurate:

In certain computer programming languages, the Elvis operator ?: is a binary operator that returns its first operand if that operand is true, and otherwise evaluates and returns its second operand. It is a variant of the ternary conditional operator, ? :, found in those languages (and many others): the Elvis operator is the ternary operator with its second operand omitted.

The following is especially true for Kotlin:

Some computer programming languages have different semantics for this operator. Instead of the first operand having to result in a boolean, it must result in an object reference. If the resulting object reference is not null, it is returned. Otherwise the value of the second operand (which may be null) is returned. If the second operand is null, the operator is also able to throw an exception.

An example:

x ?: y // yields `x` if `x` is not null, `y` otherwise.
x ?: throw SomeException() // yields `x` if `x` is not null, throws SomeException otherwise

做什么?:在科特林做? (猫王操作员)

更多

推荐作者

櫻之舞

文章 0 评论 0

弥枳

文章 0 评论 0

m2429

文章 0 评论 0

野却迷人

文章 0 评论 0

我怀念的。

文章 0 评论 0

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文