问:
It's a pytorch question. Backward() is executed only the first time or two and no further progress is made
enter image description here

So we've translated this image into a code.

class pre_h(nn.Module):
    def __init__(self, vocab_size, hidden_size, window_size):
        super().__init__()
        self.window_size = window_size
        self.in_layer = nn.Embedding(vocab_size, hidden_size)
        self.weight_list = []

    def forward(self, contexts):
        for i in range(2 * self.window_size):
            weight = self.in_layer(contexts[:,i])
            self.weight_list.append(weight)

        h = sum(self.weight_list)
        h = h / len(self.weight_list)

        return h

class UnigramSampler:
    def __init__(self, corpus, power, sample_size):
        super().__init__()
        self.sample_size = sample_size
        self.vocab_size = None
        self.word_p = None

        counts = collections.Counter()

        for word_id in corpus:
            counts[word_id] += 1

        vocab_size = len(counts)
        self.vocab_size = vocab_size

        self.word_p = np.zeros(vocab_size)

        for i in range(vocab_size):
            self.word_p[i] = counts[i]

        self.word_p = np.power(self.word_p, power)
        self.word_p /= np.sum(self.word_p)

    def get_negative_sample(self, target):
        batch_size = target.shape[0]

        negative_sample = np.random.choice(self.vocab_size, size=(batch_size, self.sample_size), replace=True, p=self.word_p)
        negative_sample = torch.tensor(negative_sample)

        return negative_sample

class NegativeSampling(nn.Module):
    def __init__(self, vocab_size, hidden_size, corpus, power = 0.75, sample_size = 5):
        super().__init__()
        self.sample_size = sample_size
        self.sampler = UnigramSampler(corpus, power, sample_size)

        self.embedding = nn.Embedding(vocab_size, hidden_size)
        self.sigmoid = nn.Sigmoid()
        self.loss_layer = nn.CrossEntropyLoss()

        self.hidden_size = hidden_size

    def forward(self, h, target):
        loss_data = 0

        w = self.embedding(target)
        w = torch.squeeze(w).reshape(self.hidden_size, -1)
        loss = h @ w
        loss = self.sigmoid(loss)
        correct_label = torch.ones_like(loss)
        loss = self.loss_layer(loss, correct_label)
        loss_data += loss

        negative_target = self.sampler.get_negative_sample(target)

        for i in range(self.sample_size):
            w = self.embedding(negative_target[:,i])
            w = torch.squeeze(w).reshape(self.hidden_size, -1)
            loss = h @ w
            loss = self.sigmoid(loss)
            negative_label = torch.zeros_like(loss)
            loss = self.loss_layer(loss, negative_label)

        return loss_data

class sample_cbow(nn.Module):
    def __init__(self, vocab_size, hidden_size, corpus, window_size, power = 0.75, sample_size = 5):
        super().__init__()

        self.model_1 = pre_h(vocab_size, hidden_size, window_size)
        self.model_2 = NegativeSampling(vocab_size, hidden_size, corpus, power, sample_size)

    def forward(self, contexts, target):
        out = self.model_1(contexts)
        out = self.model_2(out, target)

        return out

vocab_size = len(id_to_word)
model = sample_cbow(vocab_size, 100, corpus, 1)
learning_rate = 0.001
optimizer = torch.optim.Adam(model.parameters(), lr = learning_rate) # 아담으로 옵티마이저 설정

i = 1

for contexts, target in dataloader:
    print('===================================')
    print(i,'experiment')
    contexts.to(device)
    target.to(device)
    model.to(device)

    output = model(contexts, target)
    optimizer.zero_grad()
    output.backward()
    optimizer.step()
```
<p>Here is the dataset I used. I'm leaving this just in case.</p>
<pre class="lang-py prettyprint-override"><code>class Corpus_Dataset(Dataset):
    def __init__(self, corpus, window_size = 1):
        contexts, target = create_contexts_target(corpus, window_size)
        self.contexts = contexts
        self.target = target

    def __len__(self):
        return len(self.contexts)

    def __getitem__(self, idx):
        contexts = torch.tensor(self.contexts[idx], dtype = torch.long)
        target = torch.tensor(self.target[idx], dtype = torch.long)
        return contexts, target

dataset = Corpus_Dataset(corpus, window_size = 2)
dataloader = DataLoader(dataset, batch_size = 100)

</code>```

RuntimeError: Trying to backward through the graph a second time (or directly access saved tensors after they have already been freed). Saved intermediate values of the graph are freed when you call .backward() or autograd.grad(). Specify retain_graph=True if you need to backward through the graph a second time or if you need to access saved tensors after calling backward

We know that with backward(), the graph is no longer formed.
But I've only used one backward(), and I get this error even though I didn't recycle it again.

If the backward() of the model was not executed from the beginning, it would have been suspected as a problem with the model, but only the first or second time the backward() runs normally and does not proceed any further.

Clone() or detach() were used for more diverse tensors, but this error was not resolved.

I searched and thought about what the problem was, but I can't think of a solution anymore.

I'm sorry for my poor English.

Body:
enter image description here

So we've translated this image into a code.

class pre_h(nn.Module):
    def __init__(self, vocab_size, hidden_size, window_size):
        super().__init__()
        self.window_size = window_size
        self.in_layer = nn.Embedding(vocab_size, hidden_size)
        self.weight_list = []

    def forward(self, contexts):
        for i in range(2 * self.window_size):
            weight = self.in_layer(contexts[:,i])
            self.weight_list.append(weight)

        h = sum(self.weight_list)
        h = h / len(self.weight_list)

        return h

class UnigramSampler:
    def __init__(self, corpus, power, sample_size):
        super().__init__()
        self.sample_size = sample_size
        self.vocab_size = None
        self.word_p = None

        counts = collections.Counter()

        for word_id in corpus:
            counts[word_id] += 1

        vocab_size = len(counts)
        self.vocab_size = vocab_size

        self.word_p = np.zeros(vocab_size)

        for i in range(vocab_size):
            self.word_p[i] = counts[i]

        self.word_p = np.power(self.word_p, power)
        self.word_p /= np.sum(self.word_p)

    def get_negative_sample(self, target):
        batch_size = target.shape[0]

        negative_sample = np.random.choice(self.vocab_size, size=(batch_size, self.sample_size), replace=True, p=self.word_p)
        negative_sample = torch.tensor(negative_sample)

        return negative_sample

class NegativeSampling(nn.Module):
    def __init__(self, vocab_size, hidden_size, corpus, power = 0.75, sample_size = 5):
        super().__init__()
        self.sample_size = sample_size
        self.sampler = UnigramSampler(corpus, power, sample_size)

        self.embedding = nn.Embedding(vocab_size, hidden_size)
        self.sigmoid = nn.Sigmoid()
        self.loss_layer = nn.CrossEntropyLoss()

        self.hidden_size = hidden_size

    def forward(self, h, target):
        loss_data = 0

        w = self.embedding(target)
        w = torch.squeeze(w).reshape(self.hidden_size, -1)
        loss = h @ w
        loss = self.sigmoid(loss)
        correct_label = torch.ones_like(loss)
        loss = self.loss_layer(loss, correct_label)
        loss_data += loss

        negative_target = self.sampler.get_negative_sample(target)

        for i in range(self.sample_size):
            w = self.embedding(negative_target[:,i])
            w = torch.squeeze(w).reshape(self.hidden_size, -1)
            loss = h @ w
            loss = self.sigmoid(loss)
            negative_label = torch.zeros_like(loss)
            loss = self.loss_layer(loss, negative_label)

        return loss_data

class sample_cbow(nn.Module):
    def __init__(self, vocab_size, hidden_size, corpus, window_size, power = 0.75, sample_size = 5):
        super().__init__()

        self.model_1 = pre_h(vocab_size, hidden_size, window_size)
        self.model_2 = NegativeSampling(vocab_size, hidden_size, corpus, power, sample_size)

    def forward(self, contexts, target):
        out = self.model_1(contexts)
        out = self.model_2(out, target)

        return out

vocab_size = len(id_to_word)
model = sample_cbow(vocab_size, 100, corpus, 1)
learning_rate = 0.001
optimizer = torch.optim.Adam(model.parameters(), lr = learning_rate) # 아담으로 옵티마이저 설정

i = 1

for contexts, target in dataloader:
    print('===================================')
    print(i,'experiment')
    contexts.to(device)
    target.to(device)
    model.to(device)

    output = model(contexts, target)
    optimizer.zero_grad()
    output.backward()
    optimizer.step()

Here is the dataset I used. I'm leaving this just in case.

class Corpus_Dataset(Dataset):
    def __init__(self, corpus, window_size = 1):
        contexts, target = create_contexts_target(corpus, window_size)
        self.contexts = contexts
        self.target = target

    def __len__(self):
        return len(self.contexts)

    def __getitem__(self, idx):
        contexts = torch.tensor(self.contexts[idx], dtype = torch.long)
        target = torch.tensor(self.target[idx], dtype = torch.long)
        return contexts, target

dataset = Corpus_Dataset(corpus, window_size = 2)
dataloader = DataLoader(dataset, batch_size = 100)

RuntimeError: Trying to backward through the graph a second time (or directly access saved tensors after they have already been freed). Saved intermediate values of the graph are freed when you call .backward() or autograd.grad(). Specify retain_graph=True if you need to backward through the graph a second time or if you need to access saved tensors after calling backward

We know that with backward(), the graph is no longer formed.
But I've only used one backward(), and I get this error even though I didn't recycle it again.

If the backward() of the model was not executed from the beginning, it would have been suspected as a problem with the model, but only the first or second time the backward() runs normally and does not proceed any further.

Clone() or detach() were used for more diverse tensors, but this error was not resolved.

I searched and thought about what the problem was, but I can't think of a solution anymore.

I'm sorry for my poor English.


来源: stackexchange

问:
Multiple List Comprehensions Or One For Loop?
Is it better (in terms of speed and efficiency) to use multiple list comprehensions or a single for loop when adding items from one collection to multiple separate collections, such as in the example(s) provided? Or is there any better solutions?

In the examples, 'data' is a two dimensional array.

Example 1 (For Loop):

```<code>ids = []
usernames = []
passwords = []

for i in data:
    ids.append(i[0])
    usernames.append(i[1])
    passwords.append(i[2])
</code>```

Example 2 (List Comprehensions):

```<code>ids = [i[0] for i in data]
usernames = [i[1] for i in data]
passwords = [i[2] for i in data]
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Is it better (in terms of speed and efficiency) to use multiple list comprehensions or a single for loop when adding items from one collection to multiple separate collections, such as in the example(s) provided? Or is there any better solutions?

In the examples, 'data' is a two dimensional array.

Example 1 (For Loop):

ids = []
usernames = []
passwords = []

for i in data:
    ids.append(i[0])
    usernames.append(i[1])
    passwords.append(i[2])

Example 2 (List Comprehensions):

ids = [i[0] for i in data]
usernames = [i[1] for i in data]
passwords = [i[2] for i in data]


问:
SQLModel in Fastapi using __table_args__ is unable to create tables for unit testing
My Model is as follows, this model is defined in a file called tool_model.py, Hence the creation using tool_model.SQLModel.metadata.create_all(engine)

```<code>class Tool(SQLModel, table=True):
    __tablename__='tools'
    __table_args__ = {'schema': 'rna'}

    id: Optional[int] = Field(default=None, primary_key=True)
    tool_name: str = Field(sa_column=Column("tool_name", VARCHAR(500), nullable=False))
    tool_description: str = Field(
        sa_column=Column("tool_description", VARCHAR(1000), nullable=False)
    )
</code>```

This seems to be working fine, but when I try to create unit test for the same and try to create the models in fixture

conftest.py

```<code>@pytest.fixture(name="session",scope="module")
def session_fixture():
    engine = create_engine(
        "sqlite:///./test.db", connect_args={"check_same_thread": False}, poolclass=StaticPool
    )
    SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
    tool_model.SQLModel.metadata.create_all(engine)
</code>```

it is giving me the following error

```<code>E sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) unknown database "rna"
E [SQL: PRAGMA "rna".table_info("tools")]
E (Background on this error at: https://sqlalche.me/e/14/e3q8)
</code>```

Body:
My Model is as follows, this model is defined in a file called tool_model.py, Hence the creation using tool_model.SQLModel.metadata.create_all(engine)

class Tool(SQLModel, table=True):
    __tablename__='tools'
    __table_args__ = {'schema': 'rna'}

    id: Optional[int] = Field(default=None, primary_key=True)
    tool_name: str = Field(sa_column=Column("tool_name", VARCHAR(500), nullable=False))
    tool_description: str = Field(
        sa_column=Column("tool_description", VARCHAR(1000), nullable=False)
    )

This seems to be working fine, but when I try to create unit test for the same and try to create the models in fixture

conftest.py

@pytest.fixture(name="session",scope="module")
def session_fixture():
    engine = create_engine(
        "sqlite:///./test.db", connect_args={"check_same_thread": False}, poolclass=StaticPool
    )
    SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
    tool_model.SQLModel.metadata.create_all(engine)

it is giving me the following error

E sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) unknown database "rna"
E [SQL: PRAGMA "rna".table_info("tools")]
E (Background on this error at: https://sqlalche.me/e/14/e3q8)


问:
QT Translator Issue
I have recently started working with QT and am currently trying to get the QTranslator to work.

I am using Visual Studio 2022 and the QT Tools plugin with QT 6.4.1.
Attached the lines from main method.

```<code>QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
QQmlContext* context = engine.rootContext();

QTranslator* t1 = new QTranslator();
qDebug() << t1->load(":/i18n/assets/i18n/rm80eplus_de");
qDebug() << app.installTranslator(t1);
qDebug() << t1->tr("Reset");

QTranslator t2;
qDebug() << t2.load(":/i18n/assets/i18n/rm80eplus_de");
qDebug() << app.installTranslator(&t2);
qDebug() << t2.tr("Reset");
</code>```

Both variants (pointer, without pointer) run without errors but the text is not translated. Instead of "Zurücksetzen" the output is "Reset.

Path to translation files are stored in a ressouce file.

I found many posts here about QT Translator but I do not see what I am doing wrong.

Title: QT Translator Issue

Body:
I have recently started working with QT and am currently trying to get the QTranslator to work.

I am using Visual Studio 2022 and the QT Tools plugin with QT 6.4.1.
Attached the lines from main method.

QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
QQmlContext* context = engine.rootContext();

QTranslator* t1 = new QTranslator();
qDebug() << t1->load(":/i18n/assets/i18n/rm80eplus_de");
qDebug() << app.installTranslator(t1);
qDebug() << t1->tr("Reset");

QTranslator t2;
qDebug() << t2.load(":/i18n/assets/i18n/rm80eplus_de");
qDebug() << app.installTranslator(&t2);
qDebug() << t2.tr("Reset");

Both variants (pointer, without pointer) run without errors but the text is not translated. Instead of "Zurücksetzen" the output is "Reset.

Path to translation files are stored in a ressouce file.

I found many posts here about QT Translator but I do not see what I am doing wrong.


问:
Not Rolling the log figleaf_inboundevent.log every two hours testing using HH in filePattern
In the Log4J2 FileNamePattern that specifies Hours(HH) for the second logfile called figleaf- it is not creating a new file every two hours?  Also - I noticed that the logs/LOGFILE1.log is created, but it is not getting the year-month-day and hour extension it its naming.  The file is created without the extensions after the application is restarted.

Do you see anything wrong with the logfile properties preventing the figleaf log file from being created every two hours?

```<code>status = info

property.Default.Pattern = [%d{MM-dd-yyyy HH:mm:ss,SSS}] %X{context} %X{tenant} %-5p [%t] [%c] %m%n
property.Default.Level = info
appender.LOGFILE1.type = RollingFile
appender.LOGFILE1.name = LOGFILE1
appender.LOGFILE1.fileName = logs/LOGFILE1.log
appender.LOGFILE1.filePattern = logs/LOGFILE1-%d{yyyy-MM-dd}.log.%i
appender.LOGFILE1.layout.type = PatternLayout
appender.LOGFILE1.layout.pattern = ${Default.Pattern}
appender.LOGFILE1.policies.type = Policies
# To rollover the log file LOGFILE1 daily testing
appender.LOGFILE1.policies.time.type = TimeBasedTriggeringPolicy
appender.LOGFILE1.policies.time.interval = 1
appender.LOGFILE1.policies.time.modulate = true
# To change log file after 50mb size
appender.LOGFILE1.policies.size.type = SizeBasedTriggeringPolicy
appender.LOGFILE1.policies.size.size = 50mb
appender.LOGFILE1.strategy.type = DefaultRolloverStrategy
appender.LOGFILE1.strategy.max = 31
rootLogger.level = info
rootLogger.appenderRefs = root
rootLogger.appenderRef.root.ref = LOGFILE1

#------ Configuration for Inbound Logging for figleaf ------
appender.figleaf_inboundevent.type = RollingFile
appender.figleaf_inboundevent.name = figleaf_inboundevent
appender.figleaf_inboundevent.fileName = logs/figleaf_inboundevent.log
# To rollover the log file every two hours testing using HH in filePattern
appender.figleaf_inboundevent.filePattern = logs/figleaf_inboundevent-%d{yyyy-MM-dd HH}.log.%i
appender.figleaf_inboundevent.layout.type = PatternLayout
appender.figleaf_inboundevent.layout.pattern = ${Default.Pattern}
appender.figleaf_inboundevent.policies.type = Policies
# To rollover the log file every two hours testing
appender.figleaf_inboundevent.policies.time.type = TimeBasedTriggeringPolicy
appender.figleaf_inboundevent.policies.time.interval = 2
appender.figleaf_inboundevent.policies.time.modulate = true
appender.figleaf_inboundevent.policies.size.type = SizeBasedTriggeringPolicy
appender.figleaf_inboundevent.policies.size.size = 50mb
appender.figleaf_inboundevent.strategy.type = DefaultRolloverStrategy
appender.figleaf_inboundevent.strategy.max = 31

logger.figleaf_inbound_InboundSchedulable.name = com.lawson.ma.sdi.figleaf.adapter.InboundSchedulable
logger.figleaf_inbound_InboundSchedulable.level = INFO

logger.figleaf_inbound_InboundSchedulable.additivity = false
logger.figleaf_inbound_InboundSchedulable.appenderRef.figleaf_inboundevent.ref = figleaf_inboundevent

logger.figleaf_inbound_ProcessInbound.name = com.lawson.ma.sdi.figleaf.inbound.ProcessInbound
logger.figleaf_inbound_ProcessInbound.level = INFO
logger.figleaf_inbound_ProcessInbound.additivity = false
logger.figleaf_inbound_ProcessInbound.appenderRef.figleaf_inboundevent.ref = figleaf_inboundevent

logger.figleaf_inbound_ProcessADT.name = com.lawson.ma.sdi.figleaf.inbound.ProcessADT
logger.figleaf_inbound_ProcessADT.level = INFO
logger.figleaf_inbound_ProcessADT.additivity = false
logger.figleaf_inbound_ProcessADT.appenderRef.figleaf_inboundevent.ref = figleaf_inboundevent

logger.figleaf_inbound_ProcessSIU.name = com.lawson.ma.sdi.figleaf.inbound.ProcessSIU
logger.figleaf_inbound_ProcessSIU.level = INFO
logger.figleaf_inbound_ProcessSIU.additivity = false
logger.figleaf_inbound_ProcessSIU.appenderRef.figleaf_inboundevent.ref = figleaf_inboundevent

logger.figleaf_inbound_ProcessCSU.name = com.lawson.ma.sdi.figleaf.inbound.ProcessCSU
logger.figleaf_inbound_ProcessCSU.level = INFO
logger.figleaf_inbound_ProcessCSU.additivity = false
logger.figleaf_inbound_ProcessCSU.appenderRef.figleaf_inboundevent.ref = figleaf_inboundevent

logger.figleaf_inbound_InboundManager.name = com.lawson.ma.sdi.figleaf.inbound.data.InboundManager
logger.figleaf_inbound_InboundManager.level = INFO
logger.figleaf_inbound_InboundManager.additivity = false
logger.figleaf_inbound_InboundManager.appenderRef.figleaf_inboundevent.ref = figleaf_inboundevent

logger.figleaf_inbound_InboundManagerImpl.name = com.lawson.ma.sdi.figleaf.inbound.data.InboundManagerImpl
logger.figleaf_inbound_InboundManagerImpl.level = INFO
logger.figleaf_inbound_InboundManagerImpl.additivity = false
logger.figleaf_inbound_InboundManagerImpl.appenderRef.figleaf_inboundevent.ref = figleaf_inboundevent

logger.figleaf_inbound_ADTManager.name = com.lawson.ma.sdi.figleaf.inbound.data.ADTManager
logger.figleaf_inbound_ADTManager.level = INFO
logger.figleaf_inbound_ADTManager.additivity = false
logger.figleaf_inbound_ADTManager.appenderRef.figleaf_inboundevent.ref = figleaf_inboundevent

logger.figleaf_inbound_ADTManagerImpl.name = com.lawson.ma.sdi.figleaf.inbound.data.ADTManagerImpl
logger.figleaf_inbound_ADTManagerImpl.level = INFO
logger.figleaf_inbound_ADTManagerImpl.additivity = false
logger.figleaf_inbound_ADTManagerImpl.appenderRef.figleaf_inboundevent.ref = figleaf_inboundevent

logger.figleaf_inbound_CSUManager.name = com.lawson.ma.sdi.figleaf.inbound.data.CSUManager
logger.figleaf_inbound_CSUManager.level = INFO
logger.figleaf_inbound_CSUManager.additivity = false
logger.figleaf_inbound_CSUManager.appenderRef.figleaf_inboundevent.ref = figleaf_inboundevent

logger.figleaf_inbound_CSUManagerImpl.name = com.lawson.ma.sdi.figleaf.inbound.data.CSUManagerImpl
logger.figleaf_inbound_CSUManagerImpl.level = INFO
logger.figleaf_inbound_CSUManagerImpl.additivity = false
logger.figleaf_inbound_CSUManagerImpl.appenderRef.figleaf_inboundevent.ref = figleaf_inboundevent

logger.figleaf_inbound_SIUManager.name = com.lawson.ma.sdi.figleaf.inbound.data.SIUManager
logger.figleaf_inbound_SIUManager.level = INFO
logger.figleaf_inbound_SIUManager.additivity = false
logger.figleaf_inbound_SIUManager.appenderRef.figleaf_inboundevent.ref = figleaf_inboundevent

logger.figleaf_inbound_SIUManagerImpl.name = com.lawson.ma.sdi.figleaf.inbound.data.SIUManagerImpl
logger.figleaf_inbound_SIUManagerImpl.level = INFO
logger.figleaf_inbound_SIUManagerImpl.additivity = false
logger.figleaf_inbound_SIUManagerImpl.appenderRef.figleaf_inboundevent.ref = figleaf_inboundevent

logger.figleaf_inbound_InboundException.name = com.lawson.ma.sdi.figleaf.exception.InboundException
logger.figleaf_inbound_InboundException.level = INFO
logger.figleaf_inbound_InboundException.additivity = false
logger.figleaf_inbound_InboundException.appenderRef.figleaf_inboundevent.ref = figleaf_inboundevent

</code>```

Body:
In the Log4J2 FileNamePattern that specifies Hours(HH) for the second logfile called figleaf- it is not creating a new file every two hours?  Also - I noticed that the logs/LOGFILE1.log is created, but it is not getting the year-month-day and hour extension it its naming.  The file is created without the extensions after the application is restarted.

Do you see anything wrong with the logfile properties preventing the figleaf log file from being created every two hours?

status = info

property.Default.Pattern = [%d{MM-dd-yyyy HH:mm:ss,SSS}] %X{context} %X{tenant} %-5p [%t] [%c] %m%n
property.Default.Level = info
appender.LOGFILE1.type = RollingFile
appender.LOGFILE1.name = LOGFILE1
appender.LOGFILE1.fileName = logs/LOGFILE1.log
appender.LOGFILE1.filePattern = logs/LOGFILE1-%d{yyyy-MM-dd}.log.%i
appender.LOGFILE1.layout.type = PatternLayout
appender.LOGFILE1.layout.pattern = ${Default.Pattern}
appender.LOGFILE1.policies.type = Policies
# To rollover the log file LOGFILE1 daily testing
appender.LOGFILE1.policies.time.type = TimeBasedTriggeringPolicy
appender.LOGFILE1.policies.time.interval = 1
appender.LOGFILE1.policies.time.modulate = true
# To change log file after 50mb size
appender.LOGFILE1.policies.size.type = SizeBasedTriggeringPolicy
appender.LOGFILE1.policies.size.size = 50mb
appender.LOGFILE1.strategy.type = DefaultRolloverStrategy
appender.LOGFILE1.strategy.max = 31
rootLogger.level = info
rootLogger.appenderRefs = root
rootLogger.appenderRef.root.ref = LOGFILE1

#------ Configuration for Inbound Logging for figleaf ------
appender.figleaf_inboundevent.type = RollingFile
appender.figleaf_inboundevent.name = figleaf_inboundevent
appender.figleaf_inboundevent.fileName = logs/figleaf_inboundevent.log
# To rollover the log file every two hours testing using HH in filePattern
appender.figleaf_inboundevent.filePattern = logs/figleaf_inboundevent-%d{yyyy-MM-dd HH}.log.%i
appender.figleaf_inboundevent.layout.type = PatternLayout
appender.figleaf_inboundevent.layout.pattern = ${Default.Pattern}
appender.figleaf_inboundevent.policies.type = Policies
# To rollover the log file every two hours testing
appender.figleaf_inboundevent.policies.time.type = TimeBasedTriggeringPolicy
appender.figleaf_inboundevent.policies.time.interval = 2
appender.figleaf_inboundevent.policies.time.modulate = true
appender.figleaf_inboundevent.policies.size.type = SizeBasedTriggeringPolicy
appender.figleaf_inboundevent.policies.size.size = 50mb
appender.figleaf_inboundevent.strategy.type = DefaultRolloverStrategy
appender.figleaf_inboundevent.strategy.max = 31

logger.figleaf_inbound_InboundSchedulable.name = com.lawson.ma.sdi.figleaf.adapter.InboundSchedulable
logger.figleaf_inbound_InboundSchedulable.level = INFO

logger.figleaf_inbound_InboundSchedulable.additivity = false
logger.figleaf_inbound_InboundSchedulable.appenderRef.figleaf_inboundevent.ref = figleaf_inboundevent

logger.figleaf_inbound_ProcessInbound.name = com.lawson.ma.sdi.figleaf.inbound.ProcessInbound
logger.figleaf_inbound_ProcessInbound.level = INFO
logger.figleaf_inbound_ProcessInbound.additivity = false
logger.figleaf_inbound_ProcessInbound.appenderRef.figleaf_inboundevent.ref = figleaf_inboundevent

logger.figleaf_inbound_ProcessADT.name = com.lawson.ma.sdi.figleaf.inbound.ProcessADT
logger.figleaf_inbound_ProcessADT.level = INFO
logger.figleaf_inbound_ProcessADT.additivity = false
logger.figleaf_inbound_ProcessADT.appenderRef.figleaf_inboundevent.ref = figleaf_inboundevent

logger.figleaf_inbound_ProcessSIU.name = com.lawson.ma.sdi.figleaf.inbound.ProcessSIU
logger.figleaf_inbound_ProcessSIU.level = INFO
logger.figleaf_inbound_ProcessSIU.additivity = false
logger.figleaf_inbound_ProcessSIU.appenderRef.figleaf_inboundevent.ref = figleaf_inboundevent

logger.figleaf_inbound_ProcessCSU.name = com.lawson.ma.sdi.figleaf.inbound.ProcessCSU
logger.figleaf_inbound_ProcessCSU.level = INFO
logger.figleaf_inbound_ProcessCSU.additivity = false
logger.figleaf_inbound_ProcessCSU.appenderRef.figleaf_inboundevent.ref = figleaf_inboundevent

logger.figleaf_inbound_InboundManager.name = com.lawson.ma.sdi.figleaf.inbound.data.InboundManager
logger.figleaf_inbound_InboundManager.level = INFO
logger.figleaf_inbound_InboundManager.additivity = false
logger.figleaf_inbound_InboundManager.appenderRef.figleaf_inboundevent.ref = figleaf_inboundevent

logger.figleaf_inbound_InboundManagerImpl.name = com.lawson.ma.sdi.figleaf.inbound.data.InboundManagerImpl
logger.figleaf_inbound_InboundManagerImpl.level = INFO
logger.figleaf_inbound_InboundManagerImpl.additivity = false
logger.figleaf_inbound_InboundManagerImpl.appenderRef.figleaf_inboundevent.ref = figleaf_inboundevent

logger.figleaf_inbound_ADTManager.name = com.lawson.ma.sdi.figleaf.inbound.data.ADTManager
logger.figleaf_inbound_ADTManager.level = INFO
logger.figleaf_inbound_ADTManager.additivity = false
logger.figleaf_inbound_ADTManager.appenderRef.figleaf_inboundevent.ref = figleaf_inboundevent

logger.figleaf_inbound_ADTManagerImpl.name = com.lawson.ma.sdi.figleaf.inbound.data.ADTManagerImpl
logger.figleaf_inbound_ADTManagerImpl.level = INFO
logger.figleaf_inbound_ADTManagerImpl.additivity = false
logger.figleaf_inbound_ADTManagerImpl.appenderRef.figleaf_inboundevent.ref = figleaf_inboundevent

logger.figleaf_inbound_CSUManager.name = com.lawson.ma.sdi.figleaf.inbound.data.CSUManager
logger.figleaf_inbound_CSUManager.level = INFO
logger.figleaf_inbound_CSUManager.additivity = false
logger.figleaf_inbound_CSUManager.appenderRef.figleaf_inboundevent.ref = figleaf_inboundevent

logger.figleaf_inbound_CSUManagerImpl.name = com.lawson.ma.sdi.figleaf.inbound.data.CSUManagerImpl
logger.figleaf_inbound_CSUManagerImpl.level = INFO
logger.figleaf_inbound_CSUManagerImpl.additivity = false
logger.figleaf_inbound_CSUManagerImpl.appenderRef.figleaf_inboundevent.ref = figleaf_inboundevent

logger.figleaf_inbound_SIUManager.name = com.lawson.ma.sdi.figleaf.inbound.data.SIUManager
logger.figleaf_inbound_SIUManager.level = INFO
logger.figleaf_inbound_SIUManager.additivity = false
logger.figleaf_inbound_SIUManager.appenderRef.figleaf_inboundevent.ref = figleaf_inboundevent

logger.figleaf_inbound_SIUManagerImpl.name = com.lawson.ma.sdi.figleaf.inbound.data.SIUManagerImpl
logger.figleaf_inbound_SIUManagerImpl.level = INFO
logger.figleaf_inbound_SIUManagerImpl.additivity = false
logger.figleaf_inbound_SIUManagerImpl.appenderRef.figleaf_inboundevent.ref = figleaf_inboundevent

logger.figleaf_inbound_InboundException.name = com.lawson.ma.sdi.figleaf.exception.InboundException
logger.figleaf_inbound_InboundException.level = INFO
logger.figleaf_inbound_InboundException.additivity = false
logger.figleaf_inbound_InboundException.appenderRef.figleaf_inboundevent.ref = figleaf_inboundevent


问:
How to play audio from server use expo-av in react-native
I try to play video from server. This is my code:

```<code>import React, {useState,  useEffect} from 'react';
import {  Button } from 'react-native';
import { Audio } from 'expo-av';

export default function App() {
  const [audioStatus, setAudioStatus] = useState(false)
  const [sound, setSound] = useState(new Audio.Sound());

  useEffect(()=>{
    (async () => {
            console.log('status', audioStatus)
            if (audioStatus) {
                await sound.loadAsync('https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3')
                try {
                    await sound.playAsync()
                } catch (e) {
                    console.log(e)
                }
            }else {
                await sound.stopAsync()
                await sound.unloadAsync()
            }
          })()
  },[audioStatus])

  return (
      <Button color={audioStatus ? 'red' : 'green'} title={'play'} onPress={()=>setAudioStatus(!audioStatus)} />
  );
}
</code>```

And I get error:

```<code> LOG  status false
 WARN  Possible Unhandled Promise Rejection (id: 15):
Error: Cannot complete operation because sound is not loaded.
http://192.168.100.60:19000/node_modules/expo/AppEntry.bundle?platform=android&dev=true&hot=false:100133:28
generatorResume@[native code]
asyncGeneratorStep@http://192.168.100.60:19000/node_modules/expo/AppEntry.bundle?platform=android&dev=true&hot=false:20982:26
</code>```

It looks like your post is mostly code; please add some more details.It looks like your post is mostly code; please add some more details.

Body:
I try to play video from server. This is my code:

import React, {useState,  useEffect} from 'react';
import {  Button } from 'react-native';
import { Audio } from 'expo-av';

export default function App() {
  const [audioStatus, setAudioStatus] = useState(false)
  const [sound, setSound] = useState(new Audio.Sound());

  useEffect(()=>{
    (async () => {
            console.log('status', audioStatus)
            if (audioStatus) {
                await sound.loadAsync('https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3')
                try {
                    await sound.playAsync()
                } catch (e) {
                    console.log(e)
                }
            }else {
                await sound.stopAsync()
                await sound.unloadAsync()
            }
          })()
  },[audioStatus])

  return (
      <Button color={audioStatus ? 'red' : 'green'} title={'play'} onPress={()=>setAudioStatus(!audioStatus)} />
  );
}

And I get error:

 LOG  status false
 WARN  Possible Unhandled Promise Rejection (id: 15):
Error: Cannot complete operation because sound is not loaded.
http://192.168.100.60:19000/node_modules/expo/AppEntry.bundle?platform=android&dev=true&hot=false:100133:28
generatorResume@[native code]
asyncGeneratorStep@http://192.168.100.60:19000/node_modules/expo/AppEntry.bundle?platform=android&dev=true&hot=false:20982:26

It looks like your post is mostly code; please add some more details.It looks like your post is mostly code; please add some more details.


问:
SwiftUI Navigation Stacks for different levels with in the app
I have this TabView based SwiftUI app and each tab has its own navigation stack which works as expected and there are no issues because all my 4 tabs have 4 separate independent navigation stacks.
However, in many cases, on those navigations, I want to provide the navigation on top of tab bar so that it looks like a real push happening on top of main tab bar. If I add NavigationStack on top of tab view then app crashes. For now I am using .toolbar(.hidden, for: .tabBar) API but that looks like a hack because it does not have same effect as it would be if there is push on top of tab bar.
So how can I have one global app level navigation stack that is parent of whole app and also local navigation stacks one for each tab item. And if I use global navigation stack it should push on top of tab bar and if I use local navigation stack then it should push within that tab only.

I have seen Facebook messenger apps "People" tab and "Settings" tab are showing this working but I dont know how did they do that.


问:
Shipping Methods not showing when ship to different address selected (WooCommerce)
Be appreciative if anyone has the knowledge to give me a little help with this, as I have no idea why this is happening.

So I have the ship to alternative address option enabled, when I select the option, shipping methods are not available.

No issue at all when delivering to the same address as billing, only when I select the deliver to alternative address option.

Any help would be much appreciated, as i'm going round in circles with this one.

Many thanks in advance.

Arron


问:
Exporting and importing type's JSON's in typescript
I want use mongodb with typescript:
How to import-export. In a models/person.ts:

```<code>export interface IPerson {
    name: string;
    phone: string;
    street?: string;
    city: string;
}

export const Person = {
    name: {
        type: String,
        required: true,
        minlength: 5
    },
    phone: {
        type: String,
        minlength: 5
    },
    street: {
        type: String,
        required: true,
        minlength: 5
    },
    city: {
        type: String,
        required: true,
        minlength: 3
    }
};
</code>```

And in a index.ts are rows like

```<code>import { IPerson, Person } from './models/Person'
const Person = model<IPerson>('Person', new Schema<IPerson>(Person));
</code>```

Allways I receive an error message: Error [ERR_MODULE_NOT_FOUND]: Cannot find module 'C:\myproject\dist\models\Person' imported from C:\myproject\dist\index.js . Is it possible to import-export defind types?

Body:
I want use mongodb with typescript:
How to import-export. In a models/person.ts:

export interface IPerson {
    name: string;
    phone: string;
    street?: string;
    city: string;
}

export const Person = {
    name: {
        type: String,
        required: true,
        minlength: 5
    },
    phone: {
        type: String,
        minlength: 5
    },
    street: {
        type: String,
        required: true,
        minlength: 5
    },
    city: {
        type: String,
        required: true,
        minlength: 3
    }
};

And in a index.ts are rows like

import { IPerson, Person } from './models/Person'
const Person = model<IPerson>('Person', new Schema<IPerson>(Person));

Allways I receive an error message: Error [ERR_MODULE_NOT_FOUND]: Cannot find module 'C:\myproject\dist\models\Person' imported from C:\myproject\dist\index.js . Is it possible to import-export defind types?


问:
Prevent Gatsby Cloud Build from triggering on server side changes
I have a monorepo and I notice that even if I don't change my client-side folder (just changing my rails app), Gatsby Cloud still does a build on github when I push.  How can I have it so builds are only triggered by changes to certain packages/directories?

Note: I already set my base directory to the specific package I want to deploy.  Nonetheless when I make changes outside that directory it triggers a build


问:
Targeting specific text in a Label with Kivy / Python
Similar to a hyperlink in HTML, is there a way to have a specific piece of text act almost like a button in Kivy that is within a Label?

i.e.

```<code>Label:
        Text:LongText*100 (Key pressable word) LongText*100
</code>```

Body:
Similar to a hyperlink in HTML, is there a way to have a specific piece of text act almost like a button in Kivy that is within a Label?

i.e.

Label:
        Text:LongText*100 (Key pressable word) LongText*100


问:
Springboot app cant lunch on vps, just on localhost
I have Springboot app, which can run on localhost, but when i export it in VSCode and try it run on vps, i get this error:

```<code>Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Hikari.class]: Failed to instantiate [com.zaxxer.hikari.HikariDataSource]: Factory method 'dataSource' threw exception with message: Failed to determine a suitable driver class
    at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:657)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:645)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1324)
</code>```

My application.properties is:

```<code>spring.main.banner-mode=off
logging.level.org.springframework=ERROR

spring.jpa.hibernate.ddl-auto=none

spring.datasource.initialization-mode=always
spring.datasource.platform=postgres
spring.datasource.url=jdbc:postgresql://myurl
spring.datasource.username=myuser
spring.datasource.password=mypass

spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration

spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true

spring.servlet.multipart.maxFileSize=10MB
spring.servlet.multipart.maxRequestSize=10MB

#spring.servlet.multipart.location=
</code>```

Can anyone help, thanks!

Body:
I have Springboot app, which can run on localhost, but when i export it in VSCode and try it run on vps, i get this error:

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Hikari.class]: Failed to instantiate [com.zaxxer.hikari.HikariDataSource]: Factory method 'dataSource' threw exception with message: Failed to determine a suitable driver class
    at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:657)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:645)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1324)

My application.properties is:

spring.main.banner-mode=off
logging.level.org.springframework=ERROR

spring.jpa.hibernate.ddl-auto=none

spring.datasource.initialization-mode=always
spring.datasource.platform=postgres
spring.datasource.url=jdbc:postgresql://myurl
spring.datasource.username=myuser
spring.datasource.password=mypass

spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration

spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true

spring.servlet.multipart.maxFileSize=10MB
spring.servlet.multipart.maxRequestSize=10MB

#spring.servlet.multipart.location=

Can anyone help, thanks!


问:
My site uploaded on Git hub doesn't load with CSS on net but it loads correctly with chrome on my laptop
I uploaded my own created personal site on Github (includes CSS and HTML only). The link doesn't open the site very well as my CSS contents doesn't get displayed but when I open the same file locally on my chrome browser it opens correctly.

Below I'm attaching the 2 screenshots of what it's like when I open.

1)With Github(Error while loading)

2)Locally opened using VScode(Correctly opened)

I was hoping that my uploaded file gets opened correctly like did in VScode so that I can share the link of my site.I am mentioning the link here too if anyone finds the fault then please help me rectify it.
https://dewansh28.github.io/PersonalSite/


问:
How to bypass SSL certificate for WSS in React Native?
I'm building an Expo (React Native) app in which I need to talk to multiple internal servers that user self-signed SSL certificates.

I've been able to bypass the SSL issues when making an HTTPS request by using rn-fetch-blob.
However, I haven't been able to figure out how to bypass those same issues when using the Websocket API.

Is there a way to bypass SSL certificate issues when connecting to wss://<some-ip>:<some-port>?

When I try to connect to the wss:// endpoint on the server, I see an error on the server logs that terminates the connection:

```<code>Illegal SNI hostname received [49, 50, 55, 46, 48, 46, 48, 46, 49]
</code>```

However, if I disable TLS and use an insecure endpoint ws:// then it all works fine.

Body:
I'm building an Expo (React Native) app in which I need to talk to multiple internal servers that user self-signed SSL certificates.

I've been able to bypass the SSL issues when making an HTTPS request by using rn-fetch-blob.
However, I haven't been able to figure out how to bypass those same issues when using the Websocket API.

Is there a way to bypass SSL certificate issues when connecting to wss://<some-ip>:<some-port>?

When I try to connect to the wss:// endpoint on the server, I see an error on the server logs that terminates the connection:

Illegal SNI hostname received [49, 50, 55, 46, 48, 46, 48, 46, 49]

However, if I disable TLS and use an insecure endpoint ws:// then it all works fine.


问:
Unable to invoke Task module in MS Teams botbuilder bot via adaptive card
I have been trying to invoke the task module using adaptive card in Microsoft Teams bot by modifying the echo bot sample from botbuilder framework v1.3 in nodejs. I'm using the TeamsActivityHandler as instructed by the docs. Normal buttons seems to work fine, but the button type with task/fetch doesn't seems to be working as expected. Here is the card json:

{
  "type": "AdaptiveCard",
  "$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
  "version": "1.3",
  "body": [
      {
          "type": "TextBlock",
          "text": "TaskModule Card",
          "wrap": true
      },
      {
          "type": "ActionSet",
          "actions": [
              {
                  "type": "Action.Submit",
                  "title": "Invoke",
                  "data": {
                    "msteams": {
                      "type": "task/fetch"
                    }
                  }
              }
          ]
      }
  ]
}```

When I click the button, it does not send any data back to the bot's backend to trigger handleTeamsTaskModuleFetch() method. Even the button animation that makes it gray while making call to the backend is not happening here.

Even the same happens with the example provided here github. How to fix this issue?

Body:
I have been trying to invoke the task module using adaptive card in Microsoft Teams bot by modifying the echo bot sample from botbuilder framework v1.3 in nodejs. I'm using the TeamsActivityHandler as instructed by the docs. Normal buttons seems to work fine, but the button type with task/fetch doesn't seems to be working as expected. Here is the card json:

{
  "type": "AdaptiveCard",
  "$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
  "version": "1.3",
  "body": [
      {
          "type": "TextBlock",
          "text": "TaskModule Card",
          "wrap": true
      },
      {
          "type": "ActionSet",
          "actions": [
              {
                  "type": "Action.Submit",
                  "title": "Invoke",
                  "data": {
                    "msteams": {
                      "type": "task/fetch"
                    }
                  }
              }
          ]
      }
  ]
}

When I click the button, it does not send any data back to the bot's backend to trigger handleTeamsTaskModuleFetch() method. Even the button animation that makes it gray while making call to the backend is not happening here.

Even the same happens with the example provided here github. How to fix this issue?


问:
Adapting quantile regression to the caret package
I want to try adpat quantile regression to caret package. I wrote below code to adapt but I get the error as below:

```<code>library(quantreg)
quantregression <- list(type='Regression', library='quantreg',loop=NULL)
param <- data.frame(parameter = c("tau"), class = c("numeric"), label = c("tau"))
quantregression$parameters <- param
quantGrid  <- function(x, y, len=NULL, search="grid"){
  if(search == "grid"){
    out <- expand.grid(tau=c(.05, .25, .5, .75, .95))
  }
  out
}
quantregression$grid <- quantGrid
quantregFit <- function(x, y, wts, param, lev, last, weights, classProbs, ...){
  dat <- if(is.data.frame(x)) x else as.data.frame(x)
  dat$.outcome <- y
  if(!is.null(wts))
  {
    if (param$tau)
      out <- quantreg::rq(.outcome ~ ., data = dat, weights = wts,tau=tau, ...)
    else
      out <- quantreg::rq(.outcome ~0 + ., data = dat, weights = wts,tau=tau, ...)
  } else
  {
    if (param$tau)
      out <- quantreg::rq(.outcome ~ ., data = dat,tau=tau, ...)
    else
      out <- quantreg::rq(.outcome ~0 + ., data = dat,tau=tau, ...)
  }
  out
}
quantregression$fit <- quantregFit
quantPred <- function(modelFit, newdata, preProc=NULL, submodels=NULL){
  if(!is.data.frame(newdata)) newdata <- as.data.frame(newdata)
  quantreg::predict.rq(modelFit, newdata)
}
quantregression$predict <- quantPred
quantProb <- function(){
  return(NULL)
}
quantregression$prob <- quantProb
</code>```

I get the error as below:

Something is wrong; all the RMSE metric values are missing:
RMSE        Rsquared        MAE

Min.   : NA   Min.   : NA   Min.   : NA

1st Qu.: NA   1st Qu.: NA   1st Qu.: NA

Median : NA   Median : NA   Median : NA

Mean   :NaN   Mean   :NaN   Mean   :NaN

3rd Qu.: NA   3rd Qu.: NA   3rd Qu.: NA

Max.   : NA   Max.   : NA   Max.   : NA

NA's   :5     NA's   :5     NA's   :5

Error: Stopping
In addition: There were 50 or more warnings (use warnings() to see the first 50)

warnings()
Warning messages:
1: model fit failed for Fold01.Rep1: tau=0.05 Error in unique(tau) : object 'tau' not found

I want to adopt the quantile regression using "quantreg" package for caret to obtain cross validation results for quantile regression. I wrote above code but I could not find the error in the code.

Body:
I want to try adpat quantile regression to caret package. I wrote below code to adapt but I get the error as below:

library(quantreg)
quantregression <- list(type='Regression', library='quantreg',loop=NULL)
param <- data.frame(parameter = c("tau"), class = c("numeric"), label = c("tau"))
quantregression$parameters <- param
quantGrid  <- function(x, y, len=NULL, search="grid"){
  if(search == "grid"){
    out <- expand.grid(tau=c(.05, .25, .5, .75, .95))
  }
  out
}
quantregression$grid <- quantGrid
quantregFit <- function(x, y, wts, param, lev, last, weights, classProbs, ...){
  dat <- if(is.data.frame(x)) x else as.data.frame(x)
  dat$.outcome <- y
  if(!is.null(wts))
  {
    if (param$tau)
      out <- quantreg::rq(.outcome ~ ., data = dat, weights = wts,tau=tau, ...)
    else
      out <- quantreg::rq(.outcome ~0 + ., data = dat, weights = wts,tau=tau, ...)
  } else
  {
    if (param$tau)
      out <- quantreg::rq(.outcome ~ ., data = dat,tau=tau, ...)
    else
      out <- quantreg::rq(.outcome ~0 + ., data = dat,tau=tau, ...)
  }
  out
}
quantregression$fit <- quantregFit
quantPred <- function(modelFit, newdata, preProc=NULL, submodels=NULL){
  if(!is.data.frame(newdata)) newdata <- as.data.frame(newdata)
  quantreg::predict.rq(modelFit, newdata)
}
quantregression$predict <- quantPred
quantProb <- function(){
  return(NULL)
}
quantregression$prob <- quantProb

I get the error as below:

Something is wrong; all the RMSE metric values are missing:
RMSE        Rsquared        MAE

Min.   : NA   Min.   : NA   Min.   : NA

1st Qu.: NA   1st Qu.: NA   1st Qu.: NA

Median : NA   Median : NA   Median : NA

Mean   :NaN   Mean   :NaN   Mean   :NaN

3rd Qu.: NA   3rd Qu.: NA   3rd Qu.: NA

Max.   : NA   Max.   : NA   Max.   : NA

NA's   :5     NA's   :5     NA's   :5

Error: Stopping
In addition: There were 50 or more warnings (use warnings() to see the first 50)

warnings()
Warning messages:
1: model fit failed for Fold01.Rep1: tau=0.05 Error in unique(tau) : object 'tau' not found

I want to adopt the quantile regression using "quantreg" package for caret to obtain cross validation results for quantile regression. I wrote above code but I could not find the error in the code.


问:
Does SQLCMD have a way to access it's input filename
SQLCMD can be run interactively and therefore it doesn't always have an input file but when it does, is there any way to access its name?  I don't see one documented but it wouldn't be the first time I just couldn't find something.

For example:

```<code>Print 'Executing $(ScriptPath)';
-- or
insert into Log(Path) values ('$(ScriptPath)');
</code>```

Body:
SQLCMD can be run interactively and therefore it doesn't always have an input file but when it does, is there any way to access its name?  I don't see one documented but it wouldn't be the first time I just couldn't find something.

For example:

Print 'Executing $(ScriptPath)';
-- or
insert into Log(Path) values ('$(ScriptPath)');


问:
What does the operator id() return in Python3?
Program:

```<code>a = 5
b = 5
print(a == b)
print(id(a) == id(b))
</code>```

Output:

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

I understand the first line of the output should be True, but why is the second line also True?
Doesn't the operator id() spit out the memory location? Does the constant 5 get a specific memory location when it is used in the program?

Also, if that is the case, how can we return the memory location of the variables a and b?

Body:
Program:

a = 5
b = 5
print(a == b)
print(id(a) == id(b))

Output:

True
True

I understand the first line of the output should be True, but why is the second line also True?
Doesn't the operator id() spit out the memory location? Does the constant 5 get a specific memory location when it is used in the program?

Also, if that is the case, how can we return the memory location of the variables a and b?


问:
Spark Java Map processing entire data set in all executors
I have 2 executors, 2 cores each (total 4 partitions), the following function executed 22824 times for my data set containing only 5706 records. I see messages repeated 33824 (5706 x 4) in my logs:
here is my code:

Dataset<Row> dbDataSet= dbSvc.getRecords(fkId);
RDD<String> rdd= dbDataSet.toJavaRDD()
    .map(row-> transformSvc.transformBlobToString(row)).rdd();

public class TransformService{

    public static String transformBlobToString(Row row)
        logger.info("*** transformBlobToString() Invoked on ExecutorId " + SparkEnv.get().executorId());
```
<p>In logs I see
this repeated 11412 times (5706 x2 cores)</p>
```23/01/06 18:01:11 INFO TransformService: *** transformBlobToString() Invoked on ExecutorId 1
23/01/06 18:01:11 INFO TransformService: *** transformBlobToString() Invoked on ExecutorId 1
23/01/06 18:01:11 INFO TransformService: *** transformBlobToString() Invoked on ExecutorId 1
```
<p>this repeated 11412 times (5706 x2 cores)</p>
```23/01/06 18:01:11 INFO TransformService: *** transformBlobToString() Invoked on ExecutorId 2
23/01/06 18:01:11 INFO TransformService: *** transformBlobToString() Invoked on ExecutorId 2
23/01/06 18:01:11 INFO TransformService: *** transformBlobToString() Invoked on ExecutorId 2
```
<p>Why is this happening? What I want to do is split my total of 5706 records in 4 partitions and process 1426 in each of the partition. The function I used to fetch the DB (<code>dbService.getRecords()</code>) already splits the data in 4 equal parts through an incremental column. So I expected these 4 parts to be executed in parallel in 4 cores each one processing 1426 per partition. Instead it is doing entirely opposite of what I expected -- processing the entire 5706 records in each partition. Please help how I can fix this and only process 1/4rth of records in each partition.</p>
<p>Full code:</p>
```Mainfunction() {
Dataset < Row > topLevelDataSet = dbSvc.getRecords(id);

JavaRDD < String > stringifiedDataSet = processRecords(topLevelDataSet);
Dataset < Row > xmlDataSet = sparkSession.read().json(stringifiedDataSet);
csvDataSet = filterFormatDataFrame(xmlDataSet);
int requiredPartitions = calculatePartitions(csvDataSet);
if (requiredPartitions > dbSvc.getNumberOfDBPartitions()) {
    csvDataSet.repartition((requiredPartitions).write().format("csv").option("header", "true")
        .save(filepath);
    }
    else {
        csvDataSet.write().format("csv").option("header", "true")
            .save(filepath);
    }
}

public Dataset < Row > getRecords(Long id) throws SQLException {
    String table = "(select t1.*, ROWNUM as num_rows from (select * from myTableName where id= " + id + " ) t1) mytable";
    String totalRowCount = getTotalRowCount(id, otherFIlters);
    Properties properties = new Properties();
    properties.setProperty("partitionColumn", "num_rows");
    properties.setProperty("lowerBound", "0");
    properties.setProperty("upperBound", totalRowCount);
    properties.setProperty("numPartitions", 4);
    properties.setProperty("fetchsize", "100");
    properties.setProperty("Driver", driver);
    properties.setProperty("user", user);
    properties.setProperty("password", password);
    Dataset < Row > records = SparkSession.getActiveSession().get().read().jdbc(jdbcUrl, table, properties);
    return records;
}
```
<p>}</p>
```private JavaRDD < String > processRecords(Dataset < Row > topLevelDataSet) {
JavaRDD < Row > rdd = topLevelDataSet.toJavaRDD();
//  have confirmed that each Partition ONLY has 1426 records
JavaRDD < String > transformed = rdd.mapPartitions(xmlRows - > {
    logger.info("*** Inside Parallellize function mapPArtition");
    List < String > transformedX = new ArrayList < String > ();
    int count = 0;
    while (xmlRows.hasNext()) {
        count++;
        transformedX.add(extractBlobToString(xmlRows.next()));
    }
    logger.info("*** processRecords outside loop total count of records :" + count); < -Only 1405 records
    return transformedX.iterator();
});
return transformed;
```
<p>}</p>
```private int calculatePartitions(Dataset < Row > csvDataset) {
LongAccumulator numberOfPartitionAccumulator = sparkSession.sparkContext()
    .longAccumulator("NumberOfPartitions");
csvDataset.foreachPartition(rows - > {
    numberOfPartitionAccumulator.add(1);
    Long dataSize = 0;
    while (rows.hasNext()) {
        dataSize += rows.next().json();
        if (dataSize >= MAX_FILE_SIZE) {
            numberOfPartitionAccumulator.add(1);
            dataSize = 0;
        }
    }

});
return numberOfPartitionAccumulator.value().intValue();
```

}

An update to the original post:
another piece of critical info I found. I have stages in the DAG, stage0  executes fine as expected (each partition only processing 1/4rth of the recordset). then next stage1 "save" reexecutes the loop from the very beginning, and then the count operation stage reexecutes the loop all over again. That explains why same row was processed multiple times, but that does not explain why the stage0 steps are reexecuted in next stages. what in my code above is causing it?

Body:
I have 2 executors, 2 cores each (total 4 partitions), the following function executed 22824 times for my data set containing only 5706 records. I see messages repeated 33824 (5706 x 4) in my logs:
here is my code:

Dataset<Row> dbDataSet= dbSvc.getRecords(fkId);
RDD<String> rdd= dbDataSet.toJavaRDD()
    .map(row-> transformSvc.transformBlobToString(row)).rdd();

public class TransformService{

    public static String transformBlobToString(Row row)
        logger.info("*** transformBlobToString() Invoked on ExecutorId " + SparkEnv.get().executorId());

In logs I see
this repeated 11412 times (5706 x2 cores)

23/01/06 18:01:11 INFO TransformService: *** transformBlobToString() Invoked on ExecutorId 1
23/01/06 18:01:11 INFO TransformService: *** transformBlobToString() Invoked on ExecutorId 1
23/01/06 18:01:11 INFO TransformService: *** transformBlobToString() Invoked on ExecutorId 1

this repeated 11412 times (5706 x2 cores)

23/01/06 18:01:11 INFO TransformService: *** transformBlobToString() Invoked on ExecutorId 2
23/01/06 18:01:11 INFO TransformService: *** transformBlobToString() Invoked on ExecutorId 2
23/01/06 18:01:11 INFO TransformService: *** transformBlobToString() Invoked on ExecutorId 2

Why is this happening? What I want to do is split my total of 5706 records in 4 partitions and process 1426 in each of the partition. The function I used to fetch the DB (dbService.getRecords()) already splits the data in 4 equal parts through an incremental column. So I expected these 4 parts to be executed in parallel in 4 cores each one processing 1426 per partition. Instead it is doing entirely opposite of what I expected -- processing the entire 5706 records in each partition. Please help how I can fix this and only process 1/4rth of records in each partition.

Full code:

Mainfunction() {
Dataset < Row > topLevelDataSet = dbSvc.getRecords(id);

JavaRDD < String > stringifiedDataSet = processRecords(topLevelDataSet);
Dataset < Row > xmlDataSet = sparkSession.read().json(stringifiedDataSet);
csvDataSet = filterFormatDataFrame(xmlDataSet);
int requiredPartitions = calculatePartitions(csvDataSet);
if (requiredPartitions > dbSvc.getNumberOfDBPartitions()) {
    csvDataSet.repartition((requiredPartitions).write().format("csv").option("header", "true")
        .save(filepath);
    }
    else {
        csvDataSet.write().format("csv").option("header", "true")
            .save(filepath);
    }
}

public Dataset < Row > getRecords(Long id) throws SQLException {
    String table = "(select t1.*, ROWNUM as num_rows from (select * from myTableName where id= " + id + " ) t1) mytable";
    String totalRowCount = getTotalRowCount(id, otherFIlters);
    Properties properties = new Properties();
    properties.setProperty("partitionColumn", "num_rows");
    properties.setProperty("lowerBound", "0");
    properties.setProperty("upperBound", totalRowCount);
    properties.setProperty("numPartitions", 4);
    properties.setProperty("fetchsize", "100");
    properties.setProperty("Driver", driver);
    properties.setProperty("user", user);
    properties.setProperty("password", password);
    Dataset < Row > records = SparkSession.getActiveSession().get().read().jdbc(jdbcUrl, table, properties);
    return records;
}

}

private JavaRDD < String > processRecords(Dataset < Row > topLevelDataSet) {
JavaRDD < Row > rdd = topLevelDataSet.toJavaRDD();
//  have confirmed that each Partition ONLY has 1426 records
JavaRDD < String > transformed = rdd.mapPartitions(xmlRows - > {
    logger.info("*** Inside Parallellize function mapPArtition");
    List < String > transformedX = new ArrayList < String > ();
    int count = 0;
    while (xmlRows.hasNext()) {
        count++;
        transformedX.add(extractBlobToString(xmlRows.next()));
    }
    logger.info("*** processRecords outside loop total count of records :" + count); < -Only 1405 records
    return transformedX.iterator();
});
return transformed;

}

private int calculatePartitions(Dataset < Row > csvDataset) {
LongAccumulator numberOfPartitionAccumulator = sparkSession.sparkContext()
    .longAccumulator("NumberOfPartitions");
csvDataset.foreachPartition(rows - > {
    numberOfPartitionAccumulator.add(1);
    Long dataSize = 0;
    while (rows.hasNext()) {
        dataSize += rows.next().json();
        if (dataSize >= MAX_FILE_SIZE) {
            numberOfPartitionAccumulator.add(1);
            dataSize = 0;
        }
    }

});
return numberOfPartitionAccumulator.value().intValue();

}

An update to the original post:
another piece of critical info I found. I have stages in the DAG, stage0  executes fine as expected (each partition only processing 1/4rth of the recordset). then next stage1 "save" reexecutes the loop from the very beginning, and then the count operation stage reexecutes the loop all over again. That explains why same row was processed multiple times, but that does not explain why the stage0 steps are reexecuted in next stages. what in my code above is causing it?


问:
C#- Using reflection to populate an object with nested objects
Say I have an C#.net DataTable Object, with all the data necessary to populate the below 3 object classes (Note that Foo contains a Bar and Cas)

I am not well versed in reflection, but I am working with a system that uses reflection to turn DataTable rows into ICollection's of Foo's, and it currently isn't sophisticated enough to populate the nested Bar and Cas objects in Foo without making additional database calls.

I trying to modify the existing function to make it recursive so it can can handle the potential future of Bar and Cas getting sub objects. Any help getting this to work would be appreciated. Moving away from refection would be a major overhaul and isn't going to be entertained by the team.
Thanks in advance!

```<code>public static T Reflect<T>(DataTable dt, DataRow row, T item)
{
//all the T's on initial entry into this function will be Foo

   foreach (var prop in item.GetType().GetProperties())
   {
      //if current prop is primitive, populate with value from row

      //if current prop not primitive,
      //recursively call this function with T of the type of Prop
      if (!prop.PropertyType.IsPrimitive)
         prop.SetValue(PropType, Reflect(dt, row, PropType));

   }
}
</code>```
```<code>Class Foo()
{
   string Field1;
   string Field2;
   Bar Obj1;
   Cas Obj2;
}
Class Bar()
{
   string Field1;
   string Field2;
}
Class Cas()
{
   string Field1;
   string Field2;
}
</code>```

Body:
Say I have an C#.net DataTable Object, with all the data necessary to populate the below 3 object classes (Note that Foo contains a Bar and Cas)

I am not well versed in reflection, but I am working with a system that uses reflection to turn DataTable rows into ICollection's of Foo's, and it currently isn't sophisticated enough to populate the nested Bar and Cas objects in Foo without making additional database calls.

I trying to modify the existing function to make it recursive so it can can handle the potential future of Bar and Cas getting sub objects. Any help getting this to work would be appreciated. Moving away from refection would be a major overhaul and isn't going to be entertained by the team.
Thanks in advance!

public static T Reflect<T>(DataTable dt, DataRow row, T item)
{
//all the T's on initial entry into this function will be Foo

   foreach (var prop in item.GetType().GetProperties())
   {
      //if current prop is primitive, populate with value from row

      //if current prop not primitive,
      //recursively call this function with T of the type of Prop
      if (!prop.PropertyType.IsPrimitive)
         prop.SetValue(PropType, Reflect(dt, row, PropType));

   }
}

Class Foo()
{
   string Field1;
   string Field2;
   Bar Obj1;
   Cas Obj2;
}
Class Bar()
{
   string Field1;
   string Field2;
}
Class Cas()
{
   string Field1;
   string Field2;
}


问:
MongoDb, explanation fo _fts index
I use NestJs, TypeOrm, MongoDb.
since TypeOrm does not support setting a type of indexes I use the wrapper to access MongoDB directly:

```<code>itemRepo.createCollectionIndexes([
    { key: { name: 'text' }, name: 'itemTextIndex', unique: true },
  ]);
</code>```

key: seems to be the index type

name is just a name I can give the index

If I look at the index via MongoCompass I see this:

Its great I got the Text index, but what is _fts _ftsx and why is it Compound?
I want it to only be for the name field :/

Title: MongoDb, explanation fo _fts index

Body:
I use NestJs, TypeOrm, MongoDb.
since TypeOrm does not support setting a type of indexes I use the wrapper to access MongoDB directly:

itemRepo.createCollectionIndexes([
    { key: { name: 'text' }, name: 'itemTextIndex', unique: true },
  ]);

key: seems to be the index type

name is just a name I can give the index

If I look at the index via MongoCompass I see this:

Its great I got the Text index, but what is _fts _ftsx and why is it Compound?
I want it to only be for the name field :/


问:
How to fetch JSON files with NextJS
Am a beginner developer trying to better understand how NextJS works, and am having some trouble with my project and data fetching.

To keep things simple: I am building a Pokemon 'team builder', where users can select Pokemon, add their moves and abilities etc, and add them to a team.

There are over 800+ Pokemon, and a open-source api project called PokeAPI, has all the data possibly needed for all and each Pokemon.

I have dropdowns (using a component library), with search features that I am using for users to select Pokemon and add its info.

Depending on which Pokemon is selected at a time, I would like to fetch its unique data from either the PokeAPI, my database, or somehow a local JSON file, but I am not sure at all which is best and most efficient/optimal. I do not want to constantly have users query the PokeAPI, and also doesnt feel necessary since the Pokemon data is pretty consistent throughout the years.

How would I be able to fetch individual JSON files in my project instead? Would I save a 'pokemon' folder in my /public directory and have a JSON file for each pokemon 1.json  etc? And if so how is this possible with NextJS? Would I just do something like import? Or how would each single JSON file be imported  upon client request? Would the server be getting the files and serving it on request, or is it all bundled because its on my public directory on build time?

Title: How to fetch JSON files with NextJS


问:
How to dynamically import a file based on user input
I'm writing an npm module and want to allow users to create a config file to control how the command line calls to this module run. How can I import this config file reliably? Ideally this should work in development using NPM link as well as in production.

Example file structure:

```<code>- project folder
  - node_modules
    - my_module
      - cli.mjs (Where the command line processing is running)
  - k.config.mjs
</code>```

So, ideally, I want to reliably be able to import my.config.mjs if it exists. I've tried several ways of using the dynamic import. The most(?) successful has been:

const baseDir = process.cwd();
const configPath = path.resolve(baseDir,'./k.config.mjs');
const configURL = new URL(configPath);
const userOpts = import(configURL.pathname);
console.log('userOpts',userOpts);
```
<p>This gives me an error though (using npm link):</p>
```TypeError [ERR_INVALID_MODULE_SPECIFIER]: Invalid module "\Git\Kurohyou_studios\inittest\k.config.mjs" is not a valid package name imported from E:\Git\Kurohyou_studios\k-scaffold\cli.mjs
```

So, what's the proper way for me to dynamically import this config file?

Body:
I'm writing an npm module and want to allow users to create a config file to control how the command line calls to this module run. How can I import this config file reliably? Ideally this should work in development using NPM link as well as in production.

Example file structure:

- project folder
  - node_modules
    - my_module
      - cli.mjs (Where the command line processing is running)
  - k.config.mjs

So, ideally, I want to reliably be able to import my.config.mjs if it exists. I've tried several ways of using the dynamic import. The most(?) successful has been:

const baseDir = process.cwd();
const configPath = path.resolve(baseDir,'./k.config.mjs');
const configURL = new URL(configPath);
const userOpts = import(configURL.pathname);
console.log('userOpts',userOpts);

This gives me an error though (using npm link):

TypeError [ERR_INVALID_MODULE_SPECIFIER]: Invalid module "\Git\Kurohyou_studios\inittest\k.config.mjs" is not a valid package name imported from E:\Git\Kurohyou_studios\k-scaffold\cli.mjs

So, what's the proper way for me to dynamically import this config file?


问:
what is the suitable architecture for compose in existing Fragment based app
Im having a bigger app with lots of fragment with at-most 4 levels of drill down fragments glued together with Jetpack Navigation (Graph based).

I have to create a new section with 3 levels of drill down in Compose. I'm having some questions like,

Should I create all the pages as separate Fragments with ComposeView or create everything as composables?
What type of navigation can I follow with existing navigation mechanism if I created everything as composable?

Im Looking for a method to use compose based views in the existing Fragment based architecture.


问:
Selenium in production Spring boot
I'm writing a web page in Spring Boot and using Selenium to get data from another website based on user's action, which means Selenium will get data on the fly. The website will require login to get the data. So the website will first need to initiate the webDriver and log in (I'm using user-data attribute but sometimes the login will expire so need to check every time). I'm trying to find the best approach for using Selenium to get data on the fly. From what I have experienced, if I use something like this to initialize Selenium driver:

```<code>try {
            webDriver.get(url);
            WebDriverWait wait = new WebDriverWait(webDriver, Duration.ofSeconds(TIME_OUT));
            wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("button")));
            logger.info("Already logged in");
        } catch (TimeoutException e) {
            logger.error("Not logged in yet");
            login(webDriver);
        }
</code>```

The "button" here will only be present if it is logged in. I added a log above and after this line and found out it will take about 8 seconds to finish this part, which is too long. I initially added this when user triggers the action, but this will obviously be too long.
My thought to overcome this is: for each connection, once user hits the website main page (does not need Selenium at main page) then start creating a new instance of webDriver and the login process and hold the webDriver for each of the connections. But how should I approach in such a way? Should I use Spring boot HttpSession and do something like:

```<code>session.setAttribute("driver", webDriver);
</code>```

And then later if user actually makes the request that needs Selenium, then it can retrieve the webDriver using

```<code>session.getAttribute("driver");
</code>```

Is this something that is reliable to use?
Or could anyone please enlighten me on how should I optimize this?

Thanks a lot!

Title: Selenium in production Spring boot

Body:
I'm writing a web page in Spring Boot and using Selenium to get data from another website based on user's action, which means Selenium will get data on the fly. The website will require login to get the data. So the website will first need to initiate the webDriver and log in (I'm using user-data attribute but sometimes the login will expire so need to check every time). I'm trying to find the best approach for using Selenium to get data on the fly. From what I have experienced, if I use something like this to initialize Selenium driver:

try {
            webDriver.get(url);
            WebDriverWait wait = new WebDriverWait(webDriver, Duration.ofSeconds(TIME_OUT));
            wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("button")));
            logger.info("Already logged in");
        } catch (TimeoutException e) {
            logger.error("Not logged in yet");
            login(webDriver);
        }

The "button" here will only be present if it is logged in. I added a log above and after this line and found out it will take about 8 seconds to finish this part, which is too long. I initially added this when user triggers the action, but this will obviously be too long.
My thought to overcome this is: for each connection, once user hits the website main page (does not need Selenium at main page) then start creating a new instance of webDriver and the login process and hold the webDriver for each of the connections. But how should I approach in such a way? Should I use Spring boot HttpSession and do something like:

session.setAttribute("driver", webDriver);

And then later if user actually makes the request that needs Selenium, then it can retrieve the webDriver using

session.getAttribute("driver");

Is this something that is reliable to use?
Or could anyone please enlighten me on how should I optimize this?

Thanks a lot!


问:
Problem accessing imported modules with browser console
When i try to log imported modules on browser console I get this error:

As you can see, portal has app and default but it breaks when logging because the modules have other name given by webpack. My goal is log them with the original source name for debug purposes. I think the problem is related with source maps configuration but i cant figure it out.

Below are the pseudo configuration files for explanation purposes:

tsconfig.json

```<code>{
    "compilerOptions": {
        "sourceMap": true,
        "declaration": true,
        "noImplicitAny": true,
        "module": "esnext",
        "target": "es2017",
        "allowJs": true,
        "moduleResolution": "node",
        "skipLibCheck": true,
        "jsx": "react",
        "allowSyntheticDefaultImports": true,
        "paths": {
            "*": ["../../node_modules/@org/*", "../node_modules/@org/*"]
        },
        "baseUrl" : "./src",
        "outDir": "./dist"
    },
    "include": [
        "./src"
    ]
}
</code>```

webpack.config

```<code>const path = require("path");

module.exports={
    devtool: 'source-map',
    mode: "development",
    output: {
        filename: "[name].js",
        library: {
            type: 'amd'
        },
        path: path.resolve( "dist"),
        chunkFormat: 'array-push'

    },
    target: "web",
    resolve: {
        extensions: ['.ts', '.js','.jsx','.json', '.tsx', '.scss']
    },
    resolveLoader: {
        modules: [
            path.resolve(__dirname, '..', '..', 'dist', 'loaders'),
            path.resolve('node_modules')
        ]
    },
    module:{
        rules: [
            {
                test: /\.(ts|tsx)$/,
                use: 'ts-loader',
                exclude: /node_modules/
            },
            {
                test: /\.(js|jsx)$/,
                use:  'babel-loader',
                exclude: /node_modules/
            }
        ]
    },
    externalsType: 'amd',
    entry: {
        index: './src/Index.ts',
    },
    resolve: {
        alias: {
            module: path.resolve(__dirname, 'src', 'module')
        }
    },
}
</code>```

package.json

```<code>{
    "name": "MyProject",
    "version": "1.0.0",
    "main": "./dist/index.js",
    "types": "./dist/index.d.ts",
    "dependencies": {
        "requirejs": "^2.3.6"
    },
    "devDependencies": {
        "copy-webpack-plugin": "^11.0.0",
        "html-webpack-plugin": "^5.5.0",
        "webpack": "^5.75.0",
        "webpack-cli": "^4.10.0",
    }
}
</code>```

Hope to have explained my problem well. Thanks in advance.

Body:
When i try to log imported modules on browser console I get this error:

As you can see, portal has app and default but it breaks when logging because the modules have other name given by webpack. My goal is log them with the original source name for debug purposes. I think the problem is related with source maps configuration but i cant figure it out.

Below are the pseudo configuration files for explanation purposes:

tsconfig.json

{
    "compilerOptions": {
        "sourceMap": true,
        "declaration": true,
        "noImplicitAny": true,
        "module": "esnext",
        "target": "es2017",
        "allowJs": true,
        "moduleResolution": "node",
        "skipLibCheck": true,
        "jsx": "react",
        "allowSyntheticDefaultImports": true,
        "paths": {
            "*": ["../../node_modules/@org/*", "../node_modules/@org/*"]
        },
        "baseUrl" : "./src",
        "outDir": "./dist"
    },
    "include": [
        "./src"
    ]
}

webpack.config

const path = require("path");

module.exports={
    devtool: 'source-map',
    mode: "development",
    output: {
        filename: "[name].js",
        library: {
            type: 'amd'
        },
        path: path.resolve( "dist"),
        chunkFormat: 'array-push'

    },
    target: "web",
    resolve: {
        extensions: ['.ts', '.js','.jsx','.json', '.tsx', '.scss']
    },
    resolveLoader: {
        modules: [
            path.resolve(__dirname, '..', '..', 'dist', 'loaders'),
            path.resolve('node_modules')
        ]
    },
    module:{
        rules: [
            {
                test: /\.(ts|tsx)$/,
                use: 'ts-loader',
                exclude: /node_modules/
            },
            {
                test: /\.(js|jsx)$/,
                use:  'babel-loader',
                exclude: /node_modules/
            }
        ]
    },
    externalsType: 'amd',
    entry: {
        index: './src/Index.ts',
    },
    resolve: {
        alias: {
            module: path.resolve(__dirname, 'src', 'module')
        }
    },
}

package.json

{
    "name": "MyProject",
    "version": "1.0.0",
    "main": "./dist/index.js",
    "types": "./dist/index.d.ts",
    "dependencies": {
        "requirejs": "^2.3.6"
    },
    "devDependencies": {
        "copy-webpack-plugin": "^11.0.0",
        "html-webpack-plugin": "^5.5.0",
        "webpack": "^5.75.0",
        "webpack-cli": "^4.10.0",
    }
}

Hope to have explained my problem well. Thanks in advance.


问:
Headless browser to access proxy NodeJS
I am trying to access a website using a proxy.
I have a NodeJS script, and I'm using puppeteer to access a website.

Basically, the browser goes to https://proxysite.com
It then enters the targeted URL and clicks the go button.

All I need is the URL of that proxy.
(A correct one looks like this: https://us13.proxysite.com/process.php?d=esAa%2BgDqN3CODRcWQtNWmP5ghf%2B0n6adNV8KDqyb&b=1)

However, when I print the URL and enter it into my browser, It just redirects me back to the main website.

Title: Headless browser to access proxy NodeJS


问:
MAUI Http calls to local API freeze on android device, but not on windows
For some reason my http calls to local api freezes on await when running MAUI application on my android device, but works as intended when running it on windows.

The flow:

```<code>public ICommand LoginCommand => _loginCommand ??=
            new Command(async () =>
            {
                if (await _userService.Login(Username, Password))
                {
                    Navigate("//chatrooms");
                }
            });
</code>```
```<code>public async Task<bool> Login(string username, string password)
        {
            try
            {
                var response = await _barigaProApiClient.SignIn(
                    new SignInRequest
                    {
                        Username = username,
                        Password = password
                    });
            }
            catch (Exception)
            {
                return false;
            }

            return true;
        }
</code>```
```<code>public async Task<SignInResponse> SignIn(SignInRequest request)
        {
            var content = new StringContent(JsonConvert.SerializeObject(request), Encoding.UTF8, "application/json");
            var response = await _client.PostAsync("/api/User/SignIn", content); // stuck here
            response.EnsureSuccessStatusCode();
            return JsonConvert.DeserializeObject<SignInResponse>(await response.Content.ReadAsStringAsync());
        }
</code>```

At first I thought it could be a deadlock and unmanaged synchronization context.
Found an article with similar problem, got a suggestion to use .ConfigureAwait(false) to fix that, but it still did not work.

Body:
For some reason my http calls to local api freezes on await when running MAUI application on my android device, but works as intended when running it on windows.

The flow:

public ICommand LoginCommand => _loginCommand ??=
            new Command(async () =>
            {
                if (await _userService.Login(Username, Password))
                {
                    Navigate("//chatrooms");
                }
            });

public async Task<bool> Login(string username, string password)
        {
            try
            {
                var response = await _barigaProApiClient.SignIn(
                    new SignInRequest
                    {
                        Username = username,
                        Password = password
                    });
            }
            catch (Exception)
            {
                return false;
            }

            return true;
        }

public async Task<SignInResponse> SignIn(SignInRequest request)
        {
            var content = new StringContent(JsonConvert.SerializeObject(request), Encoding.UTF8, "application/json");
            var response = await _client.PostAsync("/api/User/SignIn", content); // stuck here
            response.EnsureSuccessStatusCode();
            return JsonConvert.DeserializeObject<SignInResponse>(await response.Content.ReadAsStringAsync());
        }

At first I thought it could be a deadlock and unmanaged synchronization context.
Found an article with similar problem, got a suggestion to use .ConfigureAwait(false) to fix that, but it still did not work.


问:
How to make binance-options request?
I can't understand how to make requests to Binance API.

I have tried:

```<code>url='https://eapi.binance.com/eapi/v1/trades'
request_param={'symbol':'BTC-13JAN23-15000-C'}
data=requests.get('url,params=request_param')
print(data.json())
</code>```

And I'm always getting this Error:

```<code>Traceback (most recent call last):
  File "D:\МОЕ\Python_script\Request_Binance.py", line 4, in <module>
    data=requests.get('url,params=request_param')
  File "C:\Users\m.frolov.PBG\AppData\Local\Programs\Python\Python311\Lib\site-packages\requests\api.py", line 73, in get
    return request("get", url, params=params, **kwargs)
  File "C:\Users\m.frolov.PBG\AppData\Local\Programs\Python\Python311\Lib\site-packages\requests\api.py", line 59, in request
    return session.request(method=method, url=url, **kwargs)
  File "C:\Users\m.frolov.PBG\AppData\Local\Programs\Python\Python311\Lib\site-packages\requests\sessions.py", line 573, in request
    prep = self.prepare_request(req)
  File "C:\Users\m.frolov.PBG\AppData\Local\Programs\Python\Python311\Lib\site-packages\requests\sessions.py", line 484, in prepare_request
    p.prepare(
  File "C:\Users\m.frolov.PBG\AppData\Local\Programs\Python\Python311\Lib\site-packages\requests\models.py", line 368, in prepare
    self.prepare_url(url, params)
  File "C:\Users\m.frolov.PBG\AppData\Local\Programs\Python\Python311\Lib\site-packages\requests\models.py", line 439, in prepare_url
    raise MissingSchema(
requests.exceptions.MissingSchema: Invalid URL 'url,params=request_param': No scheme supplied. Perhaps you meant http://url,params=request_param?
</code>```

Title: How to make binance-options request?

Body:
I can't understand how to make requests to Binance API.

I have tried:

url='https://eapi.binance.com/eapi/v1/trades'
request_param={'symbol':'BTC-13JAN23-15000-C'}
data=requests.get('url,params=request_param')
print(data.json())

And I'm always getting this Error:

Traceback (most recent call last):
  File "D:\МОЕ\Python_script\Request_Binance.py", line 4, in <module>
    data=requests.get('url,params=request_param')
  File "C:\Users\m.frolov.PBG\AppData\Local\Programs\Python\Python311\Lib\site-packages\requests\api.py", line 73, in get
    return request("get", url, params=params, **kwargs)
  File "C:\Users\m.frolov.PBG\AppData\Local\Programs\Python\Python311\Lib\site-packages\requests\api.py", line 59, in request
    return session.request(method=method, url=url, **kwargs)
  File "C:\Users\m.frolov.PBG\AppData\Local\Programs\Python\Python311\Lib\site-packages\requests\sessions.py", line 573, in request
    prep = self.prepare_request(req)
  File "C:\Users\m.frolov.PBG\AppData\Local\Programs\Python\Python311\Lib\site-packages\requests\sessions.py", line 484, in prepare_request
    p.prepare(
  File "C:\Users\m.frolov.PBG\AppData\Local\Programs\Python\Python311\Lib\site-packages\requests\models.py", line 368, in prepare
    self.prepare_url(url, params)
  File "C:\Users\m.frolov.PBG\AppData\Local\Programs\Python\Python311\Lib\site-packages\requests\models.py", line 439, in prepare_url
    raise MissingSchema(
requests.exceptions.MissingSchema: Invalid URL 'url,params=request_param': No scheme supplied. Perhaps you meant http://url,params=request_param?


问:
Vue Router doesn't update page when named variable is manually changed
I have the following definition in my Vue router

{
    path: '/search/entity/:entity',
    name: PageType.SEARCH_RESULTS_ENTITY_ID,
    component: Entity
}
```
<p>If a user types in <code>id3</code> into a search box, they end up at <code>/#/search/entity/id3</code> either shows the data or a "Not Found" exception.</p>
<p>The challenge I'm facing is that if one of my users manually changes the URL to <code>/#/search/entity/id4</code> the page stays on <code>3</code> and doesn't update to <code>4</code>'s content. The only way to get that to happen is with a full page refresh.</p>
<p>I tried this hack</p>
```window.addEventListener("hashchange", (e: HashChangeEvent) => {
    router.push({
        path: window.location.hash.substr(1),
    });
})
```

but it gives this error:

NavigationDuplicated: Avoided redundant navigation to current location: "/search/entity/id4

How can I get Vue to detect and update the page when these changes happen? Note that I have this schema on a large number of pages, so I'm looking for a global project solution.

Body:
I have the following definition in my Vue router

{
    path: '/search/entity/:entity',
    name: PageType.SEARCH_RESULTS_ENTITY_ID,
    component: Entity
}

If a user types in id3 into a search box, they end up at /#/search/entity/id3 either shows the data or a "Not Found" exception.

The challenge I'm facing is that if one of my users manually changes the URL to /#/search/entity/id4 the page stays on 3 and doesn't update to 4's content. The only way to get that to happen is with a full page refresh.

I tried this hack

window.addEventListener("hashchange", (e: HashChangeEvent) => {
    router.push({
        path: window.location.hash.substr(1),
    });
})

but it gives this error:

NavigationDuplicated: Avoided redundant navigation to current location: "/search/entity/id4

How can I get Vue to detect and update the page when these changes happen? Note that I have this schema on a large number of pages, so I'm looking for a global project solution.


问:
Chrome Extension Authentication with ReactJS
Im trying to build a chrome extension with ReactJS that also has authentication. Ive followed the google oauth flow here https://developer.chrome.com/docs/extensions/mv3/tut_oauth/ and I continuously get undefined on the token. Welcome.tsx:14 Uncaught TypeError: Cannot read properties of undefined (reading 'getAuthToken')

```<code>const Welcome = () => {

  const handleAuth = () => {
    console.log('chrome', chrome)
    chrome.identity.getAuthToken({interactive: true}, function(token) {
      console.log(token);
    });
  }

  return(
  <div>
    <Typography>
        Hello World
    </Typography>
    <Button variant="contained" onClick={handleAuth}>Log In Google</Button>

  </div>
  )
}

export default Welcome;
</code>```

Is this because I need to use this as sort of a background script to handle it? Note my manifest has the key  "permissions": ["identity"], and the oauth2 configured correctly. Any guidance appreciated

Body:
Im trying to build a chrome extension with ReactJS that also has authentication. Ive followed the google oauth flow here https://developer.chrome.com/docs/extensions/mv3/tut_oauth/ and I continuously get undefined on the token. Welcome.tsx:14 Uncaught TypeError: Cannot read properties of undefined (reading 'getAuthToken')

const Welcome = () => {

  const handleAuth = () => {
    console.log('chrome', chrome)
    chrome.identity.getAuthToken({interactive: true}, function(token) {
      console.log(token);
    });
  }

  return(

    <Typography>
        Hello World
    </Typography>
    <Button variant="contained" onClick={handleAuth}>Log In Google</Button>

  )
}

export default Welcome;

Is this because I need to use this as sort of a background script to handle it? Note my manifest has the key  "permissions": ["identity"], and the oauth2 configured correctly. Any guidance appreciated


问:
PowerApps for MS Teams - Duplicate record added to combobox when setting DefaultSelectedItems
I am developing a Power App using the Teams version. We have two tables in Dataverse acting as the main data sources. There is an inheritance relationship between these two tables, where one holds parent objects and the other child. I have an overview screen which displays a single record and it is important that a user can select both parent and child records from a single combobox and have the data associated to the selected record displayed.
In order to achieve this I have a collection which holds the ID and Parent/Child type of each record to form a full list of records from both tables. Collection is built as follows:

ClearCollect(Collection_RecordSelect,AddColumns(ShowColumns(record_parents,"recordID","recordID_numeric"),"type","parent")); Collect(Collection_RecordSelect, AddColumns(ShowColumns(record_children,"recordID","recordID_numeric"),"type","child"));

When a user selects a record from the combobox, the ID value from the collection is looked up against the respective data source to get the rest of the data for the record.

The issue I have now is, when a user makes a change to a record in another screen, the app returns to this overview screen to show the record they have just changed. To achieve this I used the DefaultSelectedItems property of the combobox which looks at a selectedRecord variable containing the record ID as a string, set after a user changes the record in another screen. As the combobox requires a record, the combobox uses the selectedRecord variable to Lookup into the collection I referenced earlier to get the full record, unless it's blank in which case it default to the first record. Shown below:

If(IsBlank(selectedRecordID),First(Collection_RecordSelect),Lookup(Collection_RecordSelect, recordID = selectedRecordID))

This results in the combobox displaying two instances of the selected record and showing the old version of the record before the user made changes on the overview screen. If you select another record, the duplicate disappears. If you select the other duplicate record in the combobox, the user's changes are then shown on the overview screen.

Screenshot of duplicate record in combobox.

I have tried creating a single collection, containing all records from both tables, however as they are slightly different due to the inheritance field in the child table they don't merge properly and data is missed. Unfortunately, I need the inheritance field on the overview screen so I can't use ShowColumns and remove it.

I have recently re-built the app in Teams as opposed to standard Power Apps. This solution worked fine in the standard Power Apps environment, so I have a suspicion it may be a bug with the Power Apps for Teams combobox? Unless I am making a mistake, I think this is probably true as I've just tested and the "Classic Control" combobox doesn't have the same behavior, shame because it looks rubbish compared to the Teams one!

I have turned off multi-select on the combobox and search and the problem still exists.

Any help would be hugely appreciated!


问:
how to pass useInfiniteQuery Hook from one screen to another using react-query
I have a flatList with 3columns in a row in screenA and also there is screenB with a flatList that also shows screenA data in different way. Once user click an item in screenA it navigate to screenB and scrolls to item's index. I am using react-query for fetching data. My question is how can I handle fetchNextPage in true way. Because if user scrolls in screenB next page data should be loaded in both screens. Is it correct to pass all {data, fetchNextPage, hasNextPage, refetch} returned from useInfiniteQuery to screenB? or there is another solution?
Briefly something like instagram's profile screen. As you can see in main profile screen under a tab user click on item and it's navigate to second image. All the data loaded in second screen when user scrolls also loaded in main profile tab.

thanks for any help


问:
How can I use a custom refresh indicator in a FlatList in React Native?
I want to replace the "refresh indicator" that is used in FlatList, etc. inside the RefreshControl. I am aware that there are some minor styling changes you can make with tint and colors to adjust the colors of the spinners on iOS and Android but I want to make my own spinner indicator entirely and disable the native spinners.

Is it possible to either disable the native spinners used during the refresh operation, or to replace them with my own custom spinners?