instruction stringlengths 0 30k ⌀ |
|---|
null |
Every 3rd or 4th time I attempt to debug my application (.NET 8, WPF, C#) the debug session freezes at startup. I see my splash screen and nothing further happens. The code is locked in a call to log4Net's `LogManager.GetLogger`.
Even Debug >> Break does not work at this point. (I get an error message from Visual Studio that cannot pause the application with *"This usually indicates the application is in a broken state"*).
If I stop the app and debug it again and it goes just fine, for maybe 2 or 3 more times. Then this happens again. This only happens when debugging. Never in a release build. But it's so frequent it's really annoying.
I turned on internal log4Net debugging. When it hangs, I get these lines at the very end of the internal logging statements and then no further output
```
log4net: Setting Property [Layout] to object [log4net.Layout.PatternLayout]
log4net: Searched for existing files in [C:\Users\jmole\AppData\Local\Temp]
log4net: curSizeRollBackups starts at [0]
log4net: Opening file for writing [C:\Users\jmole\AppData\Local\Temp\Mobile.log] append [True]
```
But when it does *not* hang, this is what I get (first line is the same as above but the subsequent lines are different)
```
log4net: Setting Property [Layout] to object [log4net.Layout.PatternLayout]
log4net: Created Appender [debug]
log4net: Adding appender named [debug] to logger [root].
log4net: Hierarchy Threshold []
```
After that, the `GetLogger` call returns and my application proceeds normally.
Here is my code that retrieves the logger
private ILog? LoggerImpl
{
get
{
lock(_lock)
{
if (_logger != null)
return _logger;
if (_failedToGetLogger)
return null;
enter code here
Debug.WriteLine($"Logger getting first time for app type {_appType.Name}");
try
{
_logger = LogManager.GetLogger(_appType);
SetLogging(true, false); // Start off with logging enabled (but don't log this)
}
catch (Exception e)
{
_failedToGetLogger = true;
_logger = null;
}
return _logger;
}
}
}
Here is my log4Net config file
```
<log4net>
<root>
<level value="ALL" />
<!-- <appender-ref ref="console" /> -->
<appender-ref ref="file" />
<appender-ref ref="debug"/>
</root>
<!--
-->
<appender name="debug" type="log4net.Appender.DebugAppender">
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date{HH:mm:ss.fff} [%3thread] %5level - %message%newline" />
</layout>
</appender>
<appender name="file" type="log4net.Appender.RollingFileAppender">
<file type="log4net.Util.PatternString" value="%env{TEMP}/Mobile.log" />
<appendToFile value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="5" />
<maximumFileSize value="25MB" />
<staticLogFileName value="true" />
<lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date{HH:mm:ss.fff} [%3thread] %5level - %message%newline" />
</layout>
</appender>
</log4net>
```
Here is the complete set of lines dumped out by log4net when it hangs. The first line is mine, just before the call to `GetLogger` all the rest are from log4net
```
Logger getting first time for app type App
log4net: log4net assembly [log4net, Version=2.0.15.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a]. Loaded from [C:\Users\jmole\source\repos\Main\Mobile\x64\Debug\net8.0-windows\log4net.dll]. (.NET Runtime [8.0.1] on Microsoft Windows NT 10.0.22631.0)
log4net: defaultRepositoryType [log4net.Repository.Hierarchy.Hierarchy]
log4net: Creating repository for assembly [Mobile, Version=3.7.0.0, Culture=neutral, PublicKeyToken=null]
log4net: Assembly [Mobile, Version=3.7.0.0, Culture=neutral, PublicKeyToken=null] Loaded From [C:\Users\jmole\source\repos\Main\Mobile\x64\Debug\net8.0-windows\Mobile.dll]
log4net: Assembly [Mobile, Version=3.7.0.0, Culture=neutral, PublicKeyToken=null] does not have a RepositoryAttribute specified.
log4net: Assembly [Mobile, Version=3.7.0.0, Culture=neutral, PublicKeyToken=null] using repository [log4net-default-repository] and repository type [log4net.Repository.Hierarchy.Hierarchy]
log4net: Creating repository [log4net-default-repository] using type [log4net.Repository.Hierarchy.Hierarchy]
log4net: configuring repository [log4net-default-repository] using file [C:\Users\jmole\source\repos\Main\Mobile\x64\Debug\net8.0-windows\log4net_mobile.config]
log4net: configuring repository [log4net-default-repository] using stream
log4net: loading XML configuration
log4net: Configuring Repository [log4net-default-repository]
log4net: Configuration update mode [Merge].
log4net: Logger [root] Level string is [ALL].
log4net: Logger [root] level set to [name="ALL",value=-2147483648].
log4net: Loading Appender [file] type: [log4net.Appender.RollingFileAppender]
log4net: Parameter [file] specified subtype [log4net.Util.PatternString]
log4net: Converter [env] Option [TEMP] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [literal] Option [/Mobile.log] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Performing additional conversion of value from [PatternString] to [String]
log4net: Setting Property [File] to String value [C:\Users\jmole\AppData\Local\Temp/Mobile.log]
log4net: Setting Property [AppendToFile] to Boolean value [True]
log4net: Setting Property [RollingStyle] to RollingMode value [Size]
log4net: Setting Property [MaxSizeRollBackups] to Int32 value [5]
log4net: Setting Property [MaximumFileSize] to String value [25MB]
log4net: Setting Property [StaticLogFileName] to Boolean value [True]
log4net: Setting Property [LockingModel] to object [log4net.Appender.FileAppender+MinimalLock]
log4net: Converter [message] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [newline] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Setting Property [ConversionPattern] to String value [%date{HH:mm:ss.fff} [%3thread] %5level - %message%newline]
log4net: Converter [date] Option [HH:mm:ss.fff] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [literal] Option [ [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [thread] Option [] Format [min=3,max=2147483647,leftAlign=False]
log4net: Converter [literal] Option [] ] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [level] Option [] Format [min=5,max=2147483647,leftAlign=False]
log4net: Converter [literal] Option [ - ] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [message] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [newline] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Setting Property [Layout] to object [log4net.Layout.PatternLayout]
log4net: Searched for existing files in [C:\Users\jmole\AppData\Local\Temp]
log4net: curSizeRollBackups starts at [0]
log4net: Opening file for writing [C:\Users\jmole\AppData\Local\Temp\Mobile.log] append [True]
```
And here is the complete set of log lines of one that does *not* hang.
```
Logger getting first time for app type App
log4net: log4net assembly [log4net, Version=2.0.15.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a]. Loaded from [C:\Users\jmole\source\repos\Main\Mobile\x64\Debug\net8.0-windows\log4net.dll]. (.NET Runtime [8.0.1] on Microsoft Windows NT 10.0.22631.0)
log4net: defaultRepositoryType [log4net.Repository.Hierarchy.Hierarchy]
log4net: Creating repository for assembly [Mobile, Version=3.7.0.0, Culture=neutral, PublicKeyToken=null]
log4net: Assembly [Mobile, Version=3.7.0.0, Culture=neutral, PublicKeyToken=null] Loaded From [C:\Users\jmole\source\repos\Main\Mobile\x64\Debug\net8.0-windows\Mobile.dll]
log4net: Assembly [Mobile, Version=3.7.0.0, Culture=neutral, PublicKeyToken=null] does not have a RepositoryAttribute specified.
log4net: Assembly [Mobile, Version=3.7.0.0, Culture=neutral, PublicKeyToken=null] using repository [log4net-default-repository] and repository type [log4net.Repository.Hierarchy.Hierarchy]
log4net: Creating repository [log4net-default-repository] using type [log4net.Repository.Hierarchy.Hierarchy]
log4net: configuring repository [log4net-default-repository] using file [C:\Users\jmole\source\repos\Main\Mobile\x64\Debug\net8.0-windows\log4net_mobile.config]
log4net: configuring repository [log4net-default-repository] using stream
log4net: loading XML configuration
log4net: Configuring Repository [log4net-default-repository]
log4net: Configuration update mode [Merge].
log4net: Logger [root] Level string is [ALL].
log4net: Logger [root] level set to [name="ALL",value=-2147483648].
log4net: Loading Appender [file] type: [log4net.Appender.RollingFileAppender]
log4net: Parameter [file] specified subtype [log4net.Util.PatternString]
log4net: Converter [env] Option [TEMP] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [literal] Option [/Mobile.log] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Performing additional conversion of value from [PatternString] to [String]
log4net: Setting Property [File] to String value [C:\Users\jmole\AppData\Local\Temp/Mobile.log]
log4net: Setting Property [AppendToFile] to Boolean value [True]
log4net: Setting Property [RollingStyle] to RollingMode value [Size]
log4net: Setting Property [MaxSizeRollBackups] to Int32 value [5]
log4net: Setting Property [MaximumFileSize] to String value [25MB]
log4net: Setting Property [StaticLogFileName] to Boolean value [True]
log4net: Setting Property [LockingModel] to object [log4net.Appender.FileAppender+MinimalLock]
log4net: Converter [message] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [newline] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Setting Property [ConversionPattern] to String value [%date{HH:mm:ss.fff} [%3thread] %5level - %message%newline]
log4net: Converter [date] Option [HH:mm:ss.fff] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [literal] Option [ [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [thread] Option [] Format [min=3,max=2147483647,leftAlign=False]
log4net: Converter [literal] Option [] ] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [level] Option [] Format [min=5,max=2147483647,leftAlign=False]
log4net: Converter [literal] Option [ - ] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [message] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [newline] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Setting Property [Layout] to object [log4net.Layout.PatternLayout]
log4net: Searched for existing files in [C:\Users\jmole\AppData\Local\Temp]
log4net: curSizeRollBackups starts at [0]
log4net: Opening file for writing [C:\Users\jmole\AppData\Local\Temp\Mobile.log] append [True]
log4net: Created Appender [file]
log4net: Adding appender named [file] to logger [root].
log4net: Loading Appender [debug] type: [log4net.Appender.DebugAppender]
log4net: Converter [logger] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [message] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [newline] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Setting Property [ConversionPattern] to String value [%date{HH:mm:ss.fff} [%3thread] %5level - %message%newline]
log4net: Converter [date] Option [HH:mm:ss.fff] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [literal] Option [ [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [thread] Option [] Format [min=3,max=2147483647,leftAlign=False]
log4net: Converter [literal] Option [] ] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [level] Option [] Format [min=5,max=2147483647,leftAlign=False]
log4net: Converter [literal] Option [ - ] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [message] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Converter [newline] Option [] Format [min=-1,max=2147483647,leftAlign=False]
log4net: Setting Property [Layout] to object [log4net.Layout.PatternLayout]
log4net: Created Appender [debug]
log4net: Adding appender named [debug] to logger [root].
log4net: Hierarchy Threshold []
```
|
Log4Net hangs my app every 3rd or 4th debugging session |
|c#|.net|log4net| |
My query
```
select
custname, case when date < '11/26/2023' then -1 else datepart(wk,date) end 'week#', sum(amount) sales,
count(salesid) orders from SalesTable inner join CustomerTable c
on salestable.CustID=c.CustID
where date < '1/27/2024' and c.CustID = 10285 or c.CustID = -2
group by c.custid,custname, [address],case when date < '11/26/2023' then -1 else datepart(wk,date) end,
case when date < '11/26/2023' then '11/25/2023' else DATEADD(dd,7-(DATEPART(dw,date)),date) end
order by 1,2
```
Gets all customers sales (sum amount, week number, amount orders) by one week any row.
like:
| custname | week# | sales | orders |
|---------|----------|----------|-----------|
|CustAAA | -1 | 974697.41 | 62013 |
|CustAAA |1| 10.01 | 5 |
|CustAAA |2| 10 |2|
|CustAAA |2| 372.95| 11|
|CustAAA |3| 70.86| 13|
|CustAAA |3| 0| 3|
|CustAAA |4| 8.08| 2|
|CustAAA |5| 20 |6|
|CustAAA |48| 0 |38|
|CustAAA |49 |84.27| 2|
|CustXYZ |-1 |12.12| 1|
|CustXYZ |1 |22.59| 1|
|CustXYZ |4 |117.9| 1|
|CustXYZ |48 |19.3| 1|
[enter image description here](https://i.stack.imgur.com/3qC7j.png)
How do I PIVOT one row per customer, 'week' number as column-\> amount, 'week' number as column -\> orders.
and again the next week number, like example:
| custname | week -1 sales | week -1 orders | week 1 sales | week 1 orders | week 2 sales | week 2 orders | week 3 sales | week 3 orders | week 4 sales | week 4 orders | week 5 sales | week 5 orders | week 48 sales | week 48 orders | week 49 sales | week 49 orders |
|---------|----------|----------|-----------|---------|----------|----------|-----------|---------|----------|----------|-----------|---------|----------|----------|-----------|-----------|
|CustAAA | 974697.41 | 62013 | 10.01 | 5 | 382.95 | 13 | 70.86 | 16 | 8.08 | 2 | 20 | 6 | 0 | 38 | 84.27 | 2 |
|CustXYZ | 12.12 | 1 | 22.59 | 1 | | | | | 117.9 | 1 | | | 19.3 | 1 | | |
[enter image description here](https://i.stack.imgur.com/Z8sHj.png) |
Structure your NavigationLinks with a label and then change the width of the frame per below. This solved my issue of making the oval behind the image disappear.
NavigationLink {
FenderXperience()
} label: {
Image("Fender II")
.resizable()
.scaledToFit()
.frame(width: 300, height: 95)
.overlay(
RoundedRectangle(cornerRadius: 0)
.stroke(Color.white, lineWidth: 2))
}
.frame(width: 250) |
|css|svg|clip-path|css-mask| |
I am developing a Web Application with a Node/JS frontend and a Python backend. Development is done in two DevContainer environments with one DevContainer definition for each sub-project. So far, I open two instances of `vscode`, one for each sub-project. Each of the DevContainer setups mounts the overall project folder and points the workfolder to the right sub-folder. Also, I use a common `docker-compose.yml` to place both containers into the same docker network and to add a database.
```text
my_project/
docker-compose.yml
backend/
.devcontainers/
devcontainer.json
docker-compose.yml
Dockerfile
frontend/
.devcontainers/
devcontainer.json
docker-compose.yml
Dockerfile
```
A `devcontainer.json` looks like this:
```json
{
"name": "Python & Poetry",
"dockerComposeFile": [
"../../docker-compose.yml",
"./docker-compose.yml"
],
"service": "demo",
"workspaceFolder": "/workspaces/${localWorkspaceFolderBasename}",
...
```
Now, I came across the workspace concept in `vscode`. I want to add a workspaces definition into the root of the overall project and enjoy the advantage of only having one `vscode` window. This would be such a `my_project/code-workspace` file:
```json
{
"folders": [
{
"name": "ROOT",
"path": "."
},
{
"name": "backend",
"path": "./backend"
},
{
"name": "frontend",
"path": "./frontend"
},
]
}
```
However, I do not manage to let `vscode` open the DevContainers of the sub-projects.
I succeeded to place a `.devcontainer/` folder into the root folder of the overall project, which opens one DevContainer and connects to it for both sub-projects. But that is not what I want.
What is wrong? Is my wanted setup possible with the internal architecture of `VSCode` managing the different settings, areas, agent-connects, etc? |
I have a complex model written in Fortran which is a self contained entity which reads an input file, allocates memory for all the data structures, initializes the model, provides guesses to the solution, uses a derivative-based solver to solve the nonlinear equations, and populates the output structures, deallocates memory, and finishes.
I am able to call this complete model as a once through from Python fairly easily. This I do as follows:
import sys
import ctypes as ct
lib = ct.CDLL('prog.dll')
f = getattr(lib,'M_EXFUN_mp_EXFUN')
f.argtypes = [ct.c_char_p,ct.c_int]
f.restype = None
x = b'x ' + sys.argv[1].encode('UTF-8') + b' debug=yes'
f(x,len(x))
However my next task is more complex. I want to use a Python optimizer which will call my model as an objective function. That is, the Python optimizer will pass the current values of the independent variables, X, to the Fortran model which will return the value of some defined objective function.
The Python code is pretty simple and looks as follows:
def fun(x):
return f(x)
x0 = [2.0, 0.0]
res = minimize(fun, x0)
Where "minimize" is a function provided by the Python library I am using.
The definition of f(x) is deep in my Fortran model, as is the code for estimating the starting values of X. Clearly I don't want to call my entire model for each function evaluation, not least because it will stop and return, deallocating all data structures, but also because the function evaluation and starting point code are very small parts of the model.
What I need to do is run the Fortran code from Python (which is easy to do), but then that code has to pause and return control back to the Python code where that will start asking for the starting point and repeated function evaluations by coming back into the Fortran code.
Is this possible? Or am I stretching the Python <> Fortran interface capabilities?
|
I am getting the following error when writing the `@Query` Decorator for `getAccountAssets` resolver method:-
> Unable to resolve signature of method decorator when called as an expression.
Argument of type 'TypedPropertyDescriptor<(userTokenPayload: UserTokenPayload, accountType: AccountType) => Promise<AllAccountAssetsResponse>>' is not assignable to parameter of type 'number'.ts(1241)
No overload matches this call.
Overload 1 of 3, '(...pipes: (PipeTransform<any, any> | Type<PipeTransform<any, any>>)[]): ParameterDecorator', gave the following error.
Argument of type '() => typeof AllAccountAssetsResponse' is not assignable to parameter of type 'PipeTransform<any, any> | Type<PipeTransform<any, any>>'.
Overload 2 of 3, '(property: string, ...pipes: (PipeTransform<any, any> | Type<PipeTransform<any, any>>)[]): ParameterDecorator', gave the following error.
Argument of type '() => typeof AllAccountAssetsResponse' is not assignable to parameter of type 'string'.ts(2769)
```js
import { CustomerService } from '@app/customers/customers.service';
import { CurrentUserTokenPayload } from '@auth/decorators';
import { UserTokenPayload } from '@auth/dto/auth.interfaces';
import { GqlAuthGuard } from '@auth/guards';
import { Query, UseGuards } from '@nestjs/common';
import {
Args, Mutation, Resolver,
} from '@nestjs/graphql';
import { AccountType } from './dto/accounts.interfaces';
import {
UpdateThirdPartyFundingInfoInput,
} from './dto/common-account.input';
import {
AccountResponse, AllAccountAssetsResponse,
} from './dto/common-account.response';
import { OpportunityAccountsService } from './opportunity-accounts.service';
import { StandardAccountsService } from './standard-accounts.service';
@Resolver(() => AccountResponse)
export class CommonAccountResolver {
constructor(
private readonly standardAccountsService: StandardAccountsService,
private readonly opportunityAccountsService: OpportunityAccountsService,
private readonly customerService: CustomerService,
) { }
async getAccountServiceByType(params: {
accountType: AccountType; userId: string;
}) {
const { accountType, userId } = params;
const {
customerId,
resourceRelationships: { standardAccountId, opportunityAccountId },
} = await this.customerService.validateCustomerRelationship({ userId });
return {
[AccountType.OPPORTUNITY]: {
accountService: this.opportunityAccountsService,
accountId: opportunityAccountId,
customerId,
},
[AccountType.STANDARD]: {
accountService: this.standardAccountsService,
accountId: standardAccountId,
customerId,
},
}[accountType];
}
@UseGuards(GqlAuthGuard)
@Query(() => AllAccountAssetsResponse) // error is happening here
async getAccountAssets(
@CurrentUserTokenPayload() userTokenPayload: UserTokenPayload,
@Args('accountType', { type: () => AccountType }) accountType: AccountType,
) : Promise<AllAccountAssetsResponse> {
const { accountId, accountService } = await this.getAccountServiceByType({
accountType, userId: userTokenPayload.sub,
});
const accountAssetDetails = await accountService.getAccountAssets({
accountId,
});
return accountAssetDetails;
}
}
```
**response.ts** :-
```js
import {
createUnionType, Field, ObjectType,
registerEnumType,
} from '@nestjs/graphql';
import { Type } from 'class-transformer';
import { IsArray } from 'class-validator';
import { AssetStatus, ProductType } from '@/generated-cbms-api-client';
import { AccountType } from './accounts.interfaces';
import { OpportunityAccount } from './opportunity-account.response';
import { StandardAccount } from './standard-account.response';
registerEnumType(AssetStatus, { name: 'AssetStatus' });
registerEnumType(ProductType, { name: 'ProductType' });
export const AccountDetails = createUnionType({
name: 'AccountDetails',
types: () => [OpportunityAccount, StandardAccount] as const,
resolveType:
(accountDetails) => {
if ('accountPurpose' in accountDetails) {
return StandardAccount;
}
return OpportunityAccount;
},
});
@ObjectType()
export class AccountResponse {
@Field(() => AccountType)
accountType: AccountType;
@Field(() => AccountDetails)
accountDetails: OpportunityAccount | StandardAccount;
}
@ObjectType()
export class AccountAssetResponse {
@Field(() => AssetStatus)
status: AssetStatus;
@Field(() => ProductType)
productType: ProductType;
@Field(() => String)
createdAt?: string;
@Field(() => String)
updatedAt?: string;
@Field(() => String)
assetTypeId: string;
@Field(() => String)
productId: string;
@Field(() => String)
customerId: string;
@Field(() => String)
currentBalance: string;
@Field(() => String)
availableBalance: string;
@Field(() => String)
parentAccountId: string;
}
@ObjectType()
export class AllAccountAssetsResponse {
@IsArray()
@Type(() => AccountAssetResponse)
@Field(() => [AccountAssetResponse], { description: 'Expected investment support info' })
accountAssets: AccountAssetResponse[];
@Field(() => String)
nextCursor: string;
@Field(() => Boolean)
hasMore: boolean;
@Field(() => Number)
totalCount: number;
}
```
I don't know what I am missing. The Response of `accountService.getAccountAssets` also conforms to `Promise<AllAccountAssetsResponse>`. |
I'm experiencing a bug that only occur in iPhone X/XS that runs iOS 16.2. I couldn't tap the push notification when the app is already active. I need to trigger a feature when the push notification is tapped. When the app is on the background, it worked. But when the app is already active / on the foreground, it didn't. I tried this on an iPhone 8 Plus running iOS 16.2.1 and iPhone 14 and iPhone XR running iOS 17.1.2, but this bug didn't occur (ie. the tap was working and I can trigger the `didReceiveResponse` and `willPresentNotification` callbacks). Why does this happen? Can anybody help me?
Thanks.
|
Push notification can't be activated in certain phone models and OS |
|ios|push-notification| |
I am new in Python and I am trying to follow this [tutorial](https://python.langchain.com/docs/get_started/quickstart#building-with-langchain).
I am using `Python 3.12.2`.
I followed until the end of [Retrieval Chain](https://python.langchain.com/docs/get_started/quickstart#retrieval-chain).
I am running it using `ollama` to run it locally.
But when I tried to run my `main.py` file I got the following error:
```bash
Traceback (most recent call last):
File "/home/myUser/repos/python/myFirstProject/main.py", line 1, in <module>
from langchain_community.llms import Ollama
ModuleNotFoundError: No module named 'langchain_community'
```
My environment is active and all the packages are installed in the environment, because when I run `pip list` shows all the packages installed and there is the `langchain-community`:
|Package|Version|
|-|-|
|other packages...|x.x.x|
|langchain|0.1.13|
|langchain-cli|0.0.21|
|langchain-community|0.0.29|
|langchain-core|0.1.34|
|langchain-text-splitters|0.0.1|
|langserve|0.0.51|
|langsmith|0.1.33|
|other packages...|x.x.x|
I tried reinstalling the packages again but still have the same result.
I am using `PyCharm` and all of the packages mentioned before are in the folder: `.venv/include/lib/python3.12/site-packages`. Even when I go to `file -> settings -> Project:myProjectName -> Python Interpreter` it shows the same `Python` version in the interpreter and it list all of the packages installed.
I am using `wsl2`, `Ubuntu-22.04` and `PyCharm` got the interpreter from there, so I don't think those thinks are the problem. |
Python doesn't detect the library |
|python-3.x|windows-subsystem-for-linux|langchain|ubuntu-22.04|ollama| |
null |
**Medallion Architecture** (or Milti hop architecture) in Data Lakehouse recommends multi-layered approach to building a single source of truth for enterprise data products. Below are the 3 layers describing the quality of the data in each of these layers.
**BRONZE** layer contains raw data. This layer contains just raw data located on csv subfolder.
**SILVER** layer contains refined data (Example: adding good column names, data types, etc.). This holds the cleansed and transformed data in Delta format.
**GOLD** layer contains business-level aggregates. Gold layer contains a model in star schema, in Facts and Dimensions.
Since you have the Silver layer already implemented, Below are the next steps you can think of implementing using Azure Synapse Analytics notebooks for implementing your Gold layer.
**Step 1:** Create a dataframe on the silver table
dfs = spark.read.load("your location")
**Step 2:** Keep only the related columns
dfc= dfs.select("column1","column2")
**Step 3:** create a temporary view on the dedublicated data set
dfc.createOrReplaceTempView("stg_dim")
**Step 4:** Create your dimension and facts tables for
%sql
MERGE INTO edw_gold.dim_table as target
USING stg_dim as source
ON target.column1=source.column1
WHEN NOT MATCHED
THEN INSERT (column1,column2) values (source.column1,source.column2)
**Step 5:** Create a Synapse pipeline and import the notebook
**Step 6:** Validate the Gold layer
%sql
SELECT 'DIM_TABLE' AS TABLE_NAME ,count(*) as Count FROM EDW_GOLD.DIM_TABLE
Hope the below steps will help to implement your Gold layer in Synapse Delta lake. |
I am trying to create embeddings for the chunk text which I have created, but when I try to use the method from_texts, i am getting the following error
AttributeError: 'Pinecone' object has no attribute 'from_texts'
This is my code.
model_name = "sentence-transformers/all-mpnet-base-v2"
model_kwargs = {'device': 'cpu'}
encode_kwargs = {'normalize_embeddings': False}
hf = HuggingFaceEmbeddings(
model_name=model_name,
model_kwargs=model_kwargs,
encode_kwargs=encode_kwargs
)
pc = Pinecone(api_key=pinecone_api_key)
pc.Index=pinecone_index
pc.from_texts([t.page_content for t in text_chunks],hf,pinecone_index)
Is this method got depreceated? what is the alternate method for this
|
AttributeError: 'Pinecone' object has no attribute 'from_texts' |
|vector-database|pinecone| |
null |
null |
null |
null |
`Code.exe` isn't designed to be invoked _directly_; Visual Studio Code's designated CLI entry point is the `code.cmd` _batch file_, located in the `bin` subdirectory of where `Code.exe` is located.
`code.cmd` *automatically* suppresses the - asynchronously arriving - console messages you're seeing.
Therefore, you should make your alias invoke `code.cmd` / add *its* directory to `$env:PATH`
---
To recreate what `code.cmd` does in a direct call to `Code.exe`, you'd need a _wrapper function_ along the following lines:
```
function code {
$prev1 = $env:ELECTRON_RUN_AS_NODE; $env:ELECTRON_RUN_AS_NODE=1
$prev2 = $env:VSCODE_DEV; $env:VSCODE_DEV = [NullString]::Value
# This uses the path of a user-level VS Code installation.
# Adjust as needed to point to the dir. in which Code.exe
# resides on your USB drive.
$exeDir = "$env:LOCALAPPDATA\Programs\Microsoft VS Code"
& "$exeDir\Code.exe" "$exeDir\resources\app\out\cli.js" @args
$env:ELECTRON_RUN_AS_NODE = $prev1
$env:VSCODE_DEV = $prev2
}
``` |
I have the following code, the RepositoryException will be handled by a global ExceptionHandle.
```
```
public Category update(Category entity) {
try {
em = emf.createEntityManager();
em.getTransaction().begin();
Category category = em.find(Category.class, entity.getId());
if(category == null)
throw new RepositoryException("category not found");
category.setName(entity.getName());
em.getTransaction().commit();
return entity;
} catch (PersistenceException e) {
em.getTransaction().rollback();
if (e.getCause().getCause() instanceof ConstraintViolationException
&& ((ConstraintViolationException) e.getCause().getCause()).getSQLException().getMessage()
.contains("UC_categories_name"))
throw new RepositoryException("category already exists");
throw e;
} finally {
em.close();
}
}
```
If you know another way to update entities while minimizing the number of database queries, you can comment it. |
Sub DeleteRowsonCriteria()
Dim lastRow As Long, dataRow As Long
Dim prodTran As String, prodTran2 As String, prodOIS As String, prodOIS2 As String
lastRow = ActiveSheet.UsedRange.SpecialCells(xlCellTypeLastCell).Row
For dataRow = lastRow To 3 Step -1
prodTran = Range("A" & dataRow).Text
prodOIS = Range("AA" & dataRow).Text
If prodTran = "Ordered" Then
Rows(dataRow).Delete
ElseIf prodTran = "Cancelled" Then
Rows(dataRow).Delete
ElseIf prodOIS = "Cancelled" Then
Rows(dataRow).Delete
ElseIf prodOIS = "Refund" Then
Rows(dataRow).Delete
End If
Next dataRow
End Sub |
So I'm not sure what the `az ad sp` command is really for, but I just found out that to make service principal client secrets you need to use `az ad app`
az ad app credential reset --id ${CLIENT_ID}
az ad app credential list --id ${CLIENT_ID}
These are visible in **Azure Portal > Entra ID (Active Directory) > App Registrations > sp-name > Certificates & Secrets > Client Secrets**
I'm not sure where the ones made by `az ad sp` go or how they can be used.
Also, the commands appear to be linked in a way that's not logical. Note that both the application and service principal have the same `APPLICATION_ID`.
export APPLICATION_ID=uuid-here
export SERVICE_PRINCIPAL_OBJECT_ID=uuid-here
export ENTERPRISE_APPLICATION_OBJECT_ID=uuid-here
Both `credential list` commands work with `APPLICATION_ID` but give separate sets of results.
az ad app credential list --id $APPLICATION_ID
az ad sp credential list --id $APPLICATION_ID
These commands only work with these exact variables and also give separate sets of results, but the same results as if using `APPLICATION_ID`.
az ad app credential list --id $SERVICE_PRINCIPAL_OBJECT_ID
az ad sp credential list --id $ENTERPRISE_APPLICATION_OBJECT_ID
|
I am using go-gorm
this is my model struct
type Inventory struct {
ID int `gorm:"primaryKey;notNull" json:"id"`
Qty uint `json:"qty"`
In *int `gorm:"-:all"`
Out *int `gorm:"-:all"`
}
Notice `In` and `Out` Fields, I dont want *Gorm* to create these fields in database when running migration, so I give `-:all` tags, but I want these fields to be filled out by calculation value like this:
"IFNULL(SUM(IF(qty > 0, qty, 0)),0) AS in"
and
"IFNULL(SUM(IF(qty < 0, qty, 0)),0) AS out"
Unfortunately because this tag `-:all` *Gorm* wont fill out those two fields therefore its value always nil (the default value)
my question is how to instruct *Gorm* to not perform create/update/select/migration but fill those fields if there are values for them?
For now my solution is to use this tag `<-:false`, allowing *Gorm* to migrate (create) those columns in inventories table but never **write** nor **update** them (their value always null), this way Gorm will perform **select query** to these column and fill the struct field out if there are values, but those column are useless in database perspective
edit
Qty is uint type |
How to fill out ignored Field to store query calculation result |
|go|go-gorm| |
Clip/mask (remove) top-right image corner with SVG |
This is purely for experimental purposes and/or a learning exercise. In essence, I'd like to see if I can reduce the footprint of the closure created when we use `Task.Run(()=>Func<>())` by creating a class that I initialize only once. One, the objective would be to avoid creating a 'new' instance of this every time we run, which would probably be less efficient than the closure itself I imagine (but this is mere speculation, I know). So, creating a basic class to do so is rather simple, as you can find examples of that here on the stack.
However, where I run into issue, is that it would appear to me, that if I want to use members and functions from another class, that having to encapsulate them, or inject them into the class we're going to `Run` on, while it may be less data than the original class itself, it's probably not going to be that much of an improvement.
So say, I have something along the lines of:
```
internal async Task<PathObject> PopulatePathObjectAsync(Vector3Int origin, Vector3Int destination, PathObject path)
{
return await Task.Factory.StartNew(() => PopulatePathObject(origin, destination, path));
}
/// Not sure if we want to make this a task or not because we may just parallelize and await the outer task.
/// We'll have to decide when we get down to finalization of the architecture and how it's used.
internal PathObject PopulatePathObject(Vector3Int origin, Vector3Int destination, PathObject path)
{
Debug.Log($"Pathfinding Search On Thread: ({System.Threading.Thread.CurrentThread.ManagedThreadId})");
if (!TryVerifyPath(origin, destination, ref path, out PathingNode currentNode))
return path;
var openNodes = m_OpenNodeHeap;
m_ClosedNodes.Clear();
openNodes.ClearAndReset();
openNodes.AddNode(currentNode);
for (int i = CollectionBufferSize; openNodes.Count > 0 && i >= 0; i--)
{
currentNode = ProcessNextOpenNode(openNodes);
if (NodePositionMatchesVector(currentNode, destination))
{
return path.PopulatePathBufferFromOriginToDestination(currentNode, origin, PathState.CompletePath);
}
ProcessNeighboringNodes(currentNode, destination);
}
return path.PopulatePathBufferFromOriginToDestination(currentNode, origin, PathState.IncompletePath);
}
```
In order to ditch the lambda, the closure, and the creation (or perhaps cast?) of the delegate, I would need a class that actually encapsulates that `PopulatePathObject` function in its entirety, either by literally copying the members necessary, or passing them as arguments. This all seems like it would probably render any benefits gained. So is there a way I could have something like..
```
private class PopulatePathObjectTask
{
private readonly Vector2Int m_Origin;
private readonly Vector3Int m_Destination;
private readonly PathObject m_Path;
public PopulatePathObjectTask(Vector2Int origin, Vector3Int destination, PathObject path)
{
m_Origin = origin;
m_Destination = destination;
m_Path = path;
}
public PathObject PopulatePathObject(Vector3Int origin, Vector3Int destination, PathObject path)
{
///Obviously here, without access to the actual AStar class responsible for the search,
///I don't have access to the functions or the class members such as the heap or the hashset
///that represents the closed nodes as well as the calculated buffer size based on the space-state
///dimensions. With that, I'd just be recreating the class and not avoiding much, if any,
///of the overhead created by the closure capturing the class in the first place.
}
}
```
That I could use to access the function that already exists? I've been toying with the idea of creating a static member and using dependency injection for the open/closed node collections, but I thought, or rather hoped, someone might have some more insight into this, other than it's pointless and the even *possible* overhead reduction or performance gains will be so minimal that it's pointless. Which, granted you're probably right, but I'm doing this as an exercise and I'd like to be able to actually measure the differences. I'm probably not even going to use it, might even ditch the AStar for JPS instead, but I would like to know before moving on. I'm not entirely sure, but it would seem as if the closure would have to have the entire AStar object captured in time, one would hope by reference. |
Reducing closure overhead in Task.Run/Factory.StartNew with predefined object |
By using Lambda@Edge inside CloudFront I am not able to install packages thourgh `npm` as `CloudFront `does not allow layers:
**According to AWS doc:**
https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/lambda-at-edge-function-restrictions.html
[enter image description here](https://i.stack.imgur.com/EujxH.png)
My approach is to validate jwt tokens using Viewer Request
[enter image description here](https://i.stack.imgur.com/wYK0b.png)
There are multiple examples doing this, and they use common libraries such as:
```
import y from 'jsonwebtoken';
import z from 'jwk-to-pem';
```
But How should be referred if layers are not allowed? Using thus modules the application report errors:
*Cannot find package 'jsonwebtoken' imported from /var/task/index.mjs"*
On the other hand, creating a lambda with a cusotm layer with the following packages worked (But unable to use in aws-cloudfront):
```
{
"dependencies": {
"@types/jwk-to-pem": "^2.0.3",
"jsonwebtoken": "^9.0.2",
"jwk-to-pem": "^2.0.5",
"lodash": "^4.17.21"
}
}
```
Tried:
- Create a layer on behalf of my lambda@Edge function.
Expected to happen:
- Validate tokens in AWS@Lambda edge functions with external 3rd parties.
Actually result:
- Layers are not allowed in AWS@Lambda
|
null |
What are you trying to do is called _pivoting_, so use [`DataFrame.pivot()`][1]:
```py
import pandas as pd
df = pd.read_csv("your_file.csv", header=None)
out = (
df.pivot(index=1, columns=0, values=2)
.rename_axis(index="ID", columns=None)
.reset_index()
)
print(out)
```
Prints:
```none
ID 1:100011159-T-G 1:10002775-GA 1:100122796-C-T 1:100152282-CAAA-T
0 CDD3-597 GG GG TT CC
1 CDD3-598 GG NaN NaN CC
```
[1]: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.pivot.html#pandas-dataframe-pivot |
I'm trying to set up Flink SQL with the Apache Iceberg catalog and Hive Metastore, but having no luck. Below are the steps I've taken on a clean Flink 1.18.1 installation, and the resulting error that I get.
## Set up components
Run Hive MetaStore:
```bash
docker run --rm --detach --name hms-standalone \
--publish 9083:9083 \
ghcr.io/recap-build/hive-metastore-standalone:latest
```
Run MinIO using Docker:
```bash
docker run --rm --detach --name minio \
-p 9001:9001 -p 9000:9000 \
-e "MINIO_ROOT_USER=admin" \
-e "MINIO_ROOT_PASSWORD=password" \
minio/minio server /data --console-address ":9001"
```
Provision a bucket:
```bash
docker exec minio \
mc config host add minio http://localhost:9000 admin password
docker exec minio \
mc mb minio/warehouse
```
Add the required MinIO configuration to `./conf/flink-conf.yaml`:
```bash
cat >> ./conf/flink-conf.yaml <<EOF
fs.s3a.access.key: admin
fs.s3a.secret.key: password
fs.s3a.endpoint: http://localhost:9000
fs.s3a.path.style.access: true
EOF
```
## Add JARs to Flink
Flink's S3 plugin:
```bash
mkdir ./plugins/s3-fs-hadoop
cp ./opt/flink-s3-fs-hadoop-1.18.1.jar ./plugins/s3-fs-hadoop/
```
Flink's Hive connector:
```bash
mkdir -p ./lib/hive
curl -s https://repo1.maven.org/maven2/org/apache/flink/flink-sql-connector-hive-3.1.3_2.12/1.18.1/flink-sql-connector-hive-3.1.3_2.12-1.18.1.jar -o ./lib/hive/flink-sql-connector-hive-3.1.3_2.12-1.18.1.jar
```
Dependencies for Iceberg:
```bash
mkdir ./lib/iceberg
curl https://repo1.maven.org/maven2/org/apache/iceberg/iceberg-flink-runtime-1.17/1.4.3/iceberg-flink-runtime-1.17-1.4.3.jar -o ./lib/iceberg/iceberg-flink-runtime-1.17-1.4.3.jar
mkdir -p ./lib/aws
curl https://repo1.maven.org/maven2/org/apache/hadoop/hadoop-aws/3.3.6/hadoop-aws-3.3.6.jar -o ./lib/aws/hadoop-aws-3.3.6.jar
```
## Run it
Set the Hadoop dependency:
```bash
export HADOOP_CLASSPATH=$(~/hadoop/hadoop-3.3.2/bin/hadoop classpath)
```
Launch SQL Client:
```bash
./bin/sql-client.sh
```
```sql
Flink SQL> CREATE CATALOG c_iceberg_hive WITH (
> 'type' = 'iceberg',
> 'client.assume-role.region' = 'us-east-1',
> 'warehouse' = 's3a://warehouse',
> 's3.endpoint' = 'http://localhost:9000',
> 's3.path-style-access' = 'true',
> 'catalog-type'='hive',
> 'uri'='thrift://localhost:9083');
[INFO] Execute statement succeed.
Flink SQL> USE CATALOG c_iceberg_hive;
[INFO] Execute statement succeed.
Flink SQL> CREATE DATABASE db_rmoff;
[ERROR] Could not execute SQL statement. Reason:
MetaException(message:java.lang.RuntimeException: java.lang.ClassNotFoundException: Class org.apache.hadoop.fs.s3a.S3AFileSystem not found)
Flink SQL>
```
## Diagnostics
Verify that `hadoop-aws` is on the Classpath:
```bash
❯ ps -ef|grep sql-client|grep hadoop-aws
501 51499 45632 0 7:38pm ttys007 0:06.81 /Users/rmoff/.sdkman/candidates/java/current/bin/java -XX:+IgnoreUnrecognizedVMOptions --add-exports=java.base/sun.net.util=ALL-UNNAMED --ad
d-exports=java.rmi/sun.rmi.registry=ALL-UNNAMED --add-exports=jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED --add-exports=jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED --add-exports=
jdk.compiler/com.sun.tools.javac.parser=ALL-UNNAMED --add-exports=jdk.compiler/com.sun.tools.javac.tree=ALL-UNNAMED --add-exports=jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED --add-exp
orts=java.security.jgss/sun.security.krb5=ALL-UNNAMED --add-opens=java.base/java.lang=ALL-UNNAMED --add-opens=java.base/java.net=ALL-UNNAMED --add-opens=java.base/java.io=ALL-UNNAMED --add-
opens=java.base/java.nio=ALL-UNNAMED --add-opens=java.base/sun.nio.ch=ALL-UNNAMED --add-opens=java.base/java.lang.reflect=ALL-UNNAMED --add-opens=java.base/java.text=ALL-UNNAMED --add-opens
=java.base/java.time=ALL-UNNAMED --add-opens=java.base/java.util=ALL-UNNAMED --add-opens=java.base/java.util.concurrent=ALL-UNNAMED --add-opens=java.base/java.util.concurrent.atomic=ALL-UNN
AMED --add-opens=java.base/java.util.concurrent.locks=ALL-UNNAMED -Dlog.file=/Users/rmoff/flink/flink-1.18.1/log/flink-rmoff-sql-client-asgard08.log -Dlog4j.configuration=file:/Users/rmoff/
flink/flink-1.18.1/conf/log4j-cli.properties -Dlog4j.configurationFile=file:/Users/rmoff/flink/flink-1.18.1/conf/log4j-cli.properties -Dlogback.configurationFile=file:/Users/rmoff/flink/fli
nk-1.18.1/conf/logback.xml -classpath /Users/rmoff/flink/flink-1.18.1/lib/aws/hadoop-aws-3.3.6.jar:/Users/rmoff/flink/flink-1.18.1/lib/flink-cep-1.18.1.jar:/Users/rmoff/flink/flink-1.18.1/l[…]
```
Confirm that the JAR holds the S3AFileSystem class:
```bash
❯ jar tvf lib/aws/hadoop-aws-3.3.6.jar|grep -i filesystem.class
157923 Sun Jun 18 08:56:00 BST 2023 org/apache/hadoop/fs/s3a/S3AFileSystem.class
3821 Sun Jun 18 08:56:02 BST 2023 org/apache/hadoop/fs/s3native/NativeS3FileSystem.class
```
I get the same error if I strip the `CREATE CATALOG` back to bare-bones too:
```sql
Flink SQL> CREATE CATALOG c_iceberg_hive2 WITH (
> 'type' = 'iceberg',
> 'warehouse' = 's3a://warehouse',
> 'catalog-type'='hive',
> 'uri'='thrift://localhost:9083');
[INFO] Execute statement succeed.
Flink SQL> USE CATALOG c_iceberg_hive2;
[INFO] Execute statement succeed.
Flink SQL> CREATE DATABASE db_rmoff;
[ERROR] Could not execute SQL statement. Reason:
MetaException(message:java.lang.RuntimeException: java.lang.ClassNotFoundException: Class org.apache.hadoop.fs.s3a.S3AFileSystem not found)
```
Java version:
```bash
❯ java --version
openjdk 11.0.21 2023-10-17
OpenJDK Runtime Environment Temurin-11.0.21+9 (build 11.0.21+9)
OpenJDK 64-Bit Server VM Temurin-11.0.21+9 (build 11.0.21+9, mixed mode)
``` |
Flink with Iceberg Catalog and Hive Metastore: org.apache.hadoop.fs.s3a.S3AFileSystem not found |
|apache-flink|hive-metastore|apache-iceberg| |
|vb.net|timer|scheduled-tasks|windows-task-scheduler| |
I am trying to split the data and rearrange the data in a CSV file. My data looks something like this
```none
1:100011159-T-G,CDD3-597,G,G
1:10002775-GA,CDD3-597,G,G
1:100122796-C-T,CDD3-597,T,T
1:100152282-CAAA-T,CDD3-597,C,C
1:100011159-T-G,CDD3-598,G,G
1:100152282-CAAA-T,CDD3-598,C,C
```
and I want a table that looks like this:
| ID | 1:100011159-T-G | 1:10002775-GA | 1:100122796-C-T |1:100152282-CAAA-T |
|---------------|-----------------|---------------|------------------|-------------------|
| CDD3-597 | GG | GG | TT | CC |
| CDD3-598 | GG | | | CC |
I have written the following code:
import pandas as pd
input_file = "trail_berry.csv"
output_file = "trail_output_result.csv"
# Read the CSV file without header
df = pd.read_csv(input_file, header=None)
print(df[0].str.split(',', n=2, expand=True))
# Extract SNP Name, ID, and Alleles from the data
df[['SNP_Name', 'ID', 'Alleles']] = df[0].str.split(',', n=-1, expand=True)
# Create a new DataFrame with unique SNP_Name values as columns
result_df = pd.DataFrame(columns=df['SNP_Name'].unique(), dtype=str)
# Populate the new DataFrame with ID and Alleles data
for _, row in df.iterrows():
result_df.at[row['ID'], row['SNP_Name']] = row['Alleles']
# Reset the index
result_df.reset_index(inplace=True)
result_df.rename(columns={'index': 'ID'}, inplace=True)
# Fill NaN values with an appropriate representation (e.g., 'NULL' or '')
result_df = result_df.fillna('NULL')
# Save the result to a new CSV file
result_df.to_csv(output_file, index=False)
# Print a message indicating that the file has been saved
print("Result has been saved to {}".format(output_file))
but this has been giving me the following error:
```none
Traceback (most recent call last):
File "berry_trail.py", line 11, in <module>
df[['SNP_Name', 'ID', 'Alleles']] = df[0].str.split(',', n=-1, expand=True)
File "/nas/longleaf/home/svennam/.local/lib/python3.5/site-packages/pandas/core/frame.py", line 3367, in __setitem__
self._setitem_array(key, value)
File "/nas/longleaf/home/svennam/.local/lib/python3.5/site-packages/pandas/core/frame.py", line 3389, in _setitem_array
raise ValueError('Columns must be same length as key')
```
Can someone please help, I am having hard time figuring this out.Thanks in advance!
`ValueError: Columns must be same length as key`
|
|python|tkinter| |
{"Voters":[{"Id":23450026,"DisplayName":"Clayton Manda"}]} |
I have the following code, the RepositoryException will be handled by a global ExceptionHandle.
```
public Category update(Category entity) {
try {
em = emf.createEntityManager();
em.getTransaction().begin();
Category category = em.find(Category.class, entity.getId());
if(category == null)
throw new RepositoryException("category not found");
category.setName(entity.getName());
em.getTransaction().commit();
return entity;
} catch (PersistenceException e) {
em.getTransaction().rollback();
if (e.getCause().getCause() instanceof ConstraintViolationException
&& ((ConstraintViolationException) e.getCause().getCause()).getSQLException().getMessage()
.contains("UC_categories_name"))
throw new RepositoryException("category already exists");
throw e;
} finally {
em.close();
}
}
```
If you know another way to update entities while minimizing the number of database queries, you can comment it. |
The goal is to populate a model using OnGet() and display the results of all records in a table and finally, be able to change only the state of the checkbox on multiple records and then submit the changes to OnPostAsync().
The .cshtml page loads with all data from the database as expected. Existing records reflect the current checkbox state. But, I am not able to successfully post checkbox changes.
My issue is that the model is always empty (count = 0) in the OnPostAsync(). I'm sure it's something simple I'm missing, but I just can't figure it out or find a similar post that solves the problem.
I have researched and can't find a similar scenario or code sample that I can modify to fit my case.
.cshtml.cs
```
[Authorize()]
public class OverviewModel : PageModel
{
private readonly IAircraftModelsRepository aircraftModelsRepository;
[BindProperty]
public List<AllAircraftModels> listAircraftModels { get; set; }
public OverviewModel(IAircraftModelsRepository aircraftModelsRepository)
{
this.aircraftModelsRepository = aircraftModelsRepository;
}
public async Task OnGet()
{
listAircraftModels = (await aircraftModelsRepository.GetAsync())?.ToList();
}
public async Task<IActionResult> OnPostAsync()
{
foreach (var aircraftModel in listAircraftModels)
{
// listAircraftModels count is always zero here....
await aircraftModelsRepository.UpdateAsync(aircraftModel);
}
return RedirectToPage("/AircraftModel/Overview");
}
}
```
.cshtml
```
@if (Model.listAircraftModels != null && Model.listAircraftModels.Any())
{
<form method="post">
<div class="container">
<table class="table">
<thead>
<tr>
<td>Active</td>
<td>Mfg</td>
<td>Make</td>
<td>Model</td>
<td>Size Category</td>
</tr>
</thead>
<tbody>
@foreach (var aircraftModel in Model.listAircraftModels)
{
<tr>
<td>
<input class="form-check-input" type="checkbox" asp-for="@aircraftModel.isChecked"/>
</td>
<td>
@aircraftModel.mfg
</td>
<td>
@aircraftModel.make
</td>
<td>
@aircraftModel.model
</td>
<td>
@aircraftModel.sizeCategory
</td>
</tr>
}
</tbody>
</table>
<input class="btn btn-dark me-2" type="submit" value="Submit" />
</div>
</form>
}
else
{
<div class="container">
<p>No aircraft models found!</p>
</div>
}
```
.cs AllAircraftModels
```
public class AllAircraftModels
{
public Guid Id { get; set; }
public int modelId { get; set; }
public string mfg { get; set; }
public string make { get; set; }
public string model { get; set; }
public string sizeCategory { get; set; }
public bool isChecked { get; set; }
}
``` |
CloudFront Lambda@Edge in NodeJS. Layer is not supported for cloudfront. How to use external libraries in edge lambda? |
|aws-lambda|amazon-cloudfront| |
null |
>The third document will not be returned by the query I am using so mongoDB does not seem to search subarrays recursively.
This is correct.
---
Now let's understand why the behavior is as such, Mongo iterates over each item in the database array and evaluates them to see if they match the constraint.
From the MongoDB source code:
```
if (isArray) {
// When the path we are comparing is a path to an array, the comparison is
// considered true if it evaluates to true for the array itself or for any of the
// array’s elements.
result = make<PathComposeA>(make<PathTraverse>(result, PathTraverse::kSingleLevel),
result);
}
```
This is how Mongo generates the comparison tree syntax, or as they refer to it "AST", as you can see by the comment the array has a special consideration that enables this behavior.
Essentially the comparison tree built by Mongo is trying to find a match for `[1,2]`, it starts traversing the array in the DB.
For the document `{tags: [1, 2, 3]}`, the generated AST will traverse the tags field and compare it with the query array `[1, 2]`. Since the document's array `[1, 2, 3]` contains the elements [1, 2] in the same order as the query array `[1, 2]`, the document matches the query.
For the document `{tags: [[1, 2]]}`, the generated AST will also traverse the tags field and compare it with the query array `[1, 2]`. In this case, the document's array `[[1, 2]]` contains an inner array `[1, 2]`, which matches the query array `[1, 2]`. Therefore, the document matches the query.
`[[[1,2]]]` will not match as it will not hold under any constraint. |
IntelliJ Idea 2021.3.2 (Ultimate Edition)
I have such a service
import org.springframework.boot.info.BuildProperties;
@Service
public class MyVeryBestService {
private final BuildProperties buildProperties;
@Autowired
public MyVeryBestService(BuildProperties buildProperties) {
this.buildProperties = buildProperties;
}
//some other code
}
Application failed to start with this error
Parameter 0 of constructor in MyVeryBestService required a bean of type 'org.springframework.boot.info.BuildProperties' that could not be found
I execute maven goal clean and go to **File -> Repair IDE...** and it helps. I've tried **Invalidate Caches...** but it doesn't help. |
I have created a new app with type academic research. With this I have completed the verification process for Verify your Identity, Verify your relationship with an academic institution and Complete researcher profile.
However, the most basic flow to fetch data with @GET /v19 /me?fields=id,name API is not working and giving error: Feature Unavailable This feature is unavailable because this app is not approved for the public_profile permission.
[![screenshot][1]][1]
Is there anything missing steps in the procedure ?
[1]: https://i.stack.imgur.com/yr01j.jpg |
Unable to generate access token in facebook graph api explorer |
|facebook|facebook-graph-api| |
I'm working on a project in Reac Native Expo and using "expo-router" to navigate between pages.
I need to send a nested object array from one screen to another.
My object structure is something like this:
item: {
id: '123',
name: 'name',
nestedObjectArray: [{id: 1, name: 'name'}, {id: 2, name: 'name'}, {id: 3, name: 'name'}],
}
I've used router.navigate(`({pathname: 'path/to/screen', params: item}) but in the other screen I'm receiving this:
item: {
id: '123',
name: 'name',
nestedObjectArray: [object Object], [object Object], [object Object],
}
Any suggestions? |
Does this query determine if a SQL Server login can execute the CREATE DATABASE command?
```SQL
select the_login.name as the_login_name,
the_login.principal_id as the_login_principal_id,
case sysadmin_role_assoc.role_principal_id
when null then 0 else 1 end as user_has_sysadmin_role,
case serveradmin_role_assoc.role_principal_id
when null then 0 else 1 end as user_has_serveradmin_role,
case dbcreator_role_assoc.role_principal_id
when null then 0 else 1 end as user_has_dbcreator_role,
case the_diskadmin_role_assoc.role_principal_id
when null then 0 else 1 end as user_has_diskadmin_role,
case alter_any_database_perm.grantee_principal_id
when null then 0 else 1 end as user_has_alter_any_database
from master.sys.server_principals the_login
left outer join sys.server_principals the_sysadmin_role
on (the_sysadmin_role.name = 'sysadmin')
left outer join sys.server_role_members sysadmin_role_assoc
on (the_login.principal_id = sysadmin_role_assoc.member_principal_id
and the_sysadmin_role.principal_id = sysadmin_role_assoc.role_principal_id)
left outer join sys.server_principals the_serveradmin_role
on (the_serveradmin_role.name = 'serveradmin')
left outer join sys.server_role_members serveradmin_role_assoc
on (the_login.principal_id = serveradmin_role_assoc.member_principal_id
and the_serveradmin_role.principal_id = serveradmin_role_assoc.role_principal_id)
left outer join sys.server_principals the_dbcreator_role
on (the_dbcreator_role.name = 'dbcreator')
left outer join sys.server_role_members dbcreator_role_assoc
on (the_login.principal_id = dbcreator_role_assoc.member_principal_id
and the_dbcreator_role.principal_id = dbcreator_role_assoc.role_principal_id)
left outer join sys.server_principals the_diskadmin_role
on (the_diskadmin_role.name = 'diskadmin')
left outer join sys.server_role_members the_diskadmin_role_assoc
on (the_login.principal_id = the_diskadmin_role_assoc.member_principal_id
and the_diskadmin_role.principal_id = the_diskadmin_role_assoc.role_principal_id)
left outer join sys.server_permissions alter_any_database_perm
on (the_login.principal_id=alter_any_database_perm.grantee_principal_id
and alter_any_database_perm.permission_name = 'alter any database'
and alter_any_database_perm.state_desc='grant')
where the_login.name='sa';
```
If the third, fourth, fifth, sixth, or seventh column of this query is "1", then the login named in the WHERE clause has permission to execute CREATE DATABASE.
I need this query to set up the automatic creation of a SQL Server database. The name of the SQL Server host and the name of the login and the password are required for setting up the creation; this query is to validate that an acceptable login has been entered. |
Why is my asp.net core razor pages model always empty in the OnPostAsync() |
|c#|asp.net-core|razor|razor-pages| |
null |
I'm just building an GCC version from source.
During the make step, I get the error message
```
"WARNING: `makeinfo' is missing on your system. You should only need it if you modified a `texi' or a
`.texinfo' file, or any other file indirectly affecting the aspect of the manual. The spurious call might also be the consequence of using a buggy
`make' (AIX, DU, IRIX). You might want to install the `Texinfo' package or the `GNU make' package. Grab either from any GNU archive site."
```
texinfo was installed with the command `sudo apt install texinfo`.
What can I do about the problem?
texinfo was installed with the command `sudo apt install texinfo`. |
Local connections don't go through the listener, so they don't use a TNS string or connection string of any kind. They use the bequeath protocol whereby your client process becomes your database process (e.g. there is no separate shadow process like a listener-created connection makes). Because they don't go through the listener via TCP, they don't use a host, a port, or a service name.
Rather than the command line, your *environment* (principally `$ORACLE_SID` naming the instance, but also requiring `$ORACLE_HOME`, a `$PATH` that includes `$ORACLE_HOME/bin` and in some cases also `$LD_LIBRARY_PATH` that includes `$ORACLE_HOME/lib`) will determine which instance you connect to, as you can have multiple instances on the box, and which software installation/version to use (as you can have multiple software installations, and you must use the one that the instance is using).
Set this environment either manually, in login scripts, or with `. oraenv` (which you apparently already have, as you are able to connect in one of your tests), and then invoke `sqlplus` simply with:
`sqlplus aryan/12345`
All by itself. Be aware though, **you are putting your password on the command line**, visible to anybody logged into the box who does a `ps` or anyone logging into the same OS account later and browsing command history. For scripting, far better to use `/NOLOG` and use a *here-doc* (simplest), or pipe in via stdin from a file to provide the login info:
**Here-doc:**
sqlplus /nolog << EOF
connect aryan/12345
--do stuff...
exit
EOF
**Or file via stdin:**
file contents:
connect aryan/12345
--do stuff...
exit
And pipe it in:
sqlplus /nolog < file
Or
cat file | sqlplus /nolog
That way your password isn't part of the command string. Far safer.
|
In this declaration
int *p1 = arr;
the array designator is implicitly converted to a pointer to its first element. It is equivalent to the following declatayion
int *p1 = &arr[0];
An expression like that `arr[i]` where `i` is some integer is evaluated like `*( arr + i )`. That is the expession `a[0]` is evaluated like `*( a + 0 )` that is the same as `*( a )` or `*a`. And the expression `a[2]` is evaluated like `*( a + 2 )`. Applying the address of operator for the expressions you will get that the valie of `p1` is equal to `a + 0` or `a` and the value of `p2` is equal to the value of the expression `a + 2`.
So the difference `p2 - p1` is the same as `( a + 2 ) - a` that is equal to `2`.
From the C Standard (6.5.6 Additive operators)
8 When an expression that has integer type is added to or subtracted from a pointer, the result has the type of the pointer operand. If the pointer operand points to an element of an array object, and the
array is large enough, the result points to an element offset from the original element such that the difference of the subscripts of the resulting and original array elements equals the integer expression.
**In other words, if the expression P points to the i-th element of an array object, the expressions (P)+N (equivalently, N+(P)) and (P)-N (where N has the value n) point to, respectively, the i + n-th
and i − n-th elements of the array object, provided they exist.** Moreover, if the expression P points to the last element of an array object, the expression (P)+1 points one past the last element of the array object, and if the expression Q points one past the last element of an array object, the expression (Q)-1 points to the last element of the array object. If both the pointer operand and the result point
to elements of the same array object, or one past the last element of the array object, the evaluation shall not produce an overflow; otherwise, the behavior is undefined. If the result points one past
the last element of the array object, it shall not be used as the operand of a unary * operator that is evaluated.
Pay attention to that the type of the expression is `ptrdiff_t`. So you should write
printf("%td",p2-p1);
instead of
printf("%d",p2-p1); |
|sql-server|visual-c++|sql-server-2019|sql-server-2022| |
Keeping your original code as much the same as possible, this should do what you're looking for.
To explain it a little, when sorting, you want to return which direction you want the object to move. 1/-1 shift is left or right, and 0 keeps the order the same. Taking the difference of the indices is not going to produce the desired sorting effect.
The `!indexA` is added in there because you don't have a `node_7_...` in your sample data array.
```javascript
export function orderDialogNodes(nodes) {
// Create a mapping of dialog_node to its corresponding index in the array
const nodeIndexMap = {};
nodes.forEach((node, index) => {
nodeIndexMap[node.dialog_node] = index;
});
// Sort the array based on the previous_sibling property
nodes.sort((a, b) => {
const indexA = nodeIndexMap[a.previous_sibling];
const indexB = nodeIndexMap[b.previous_sibling];
if (indexA < indexB) {
return 1;
} else if (!indexA || indexA > indexB) {
return -1;
}
return 0;
});
return nodes;
}
const inputArray = [
{
type: "folder",
dialog_node: "node_3_1702794877277",
previous_sibling: "node_2_1702794723026",
}, {
type: "folder",
dialog_node: "node_2_1702794723026",
previous_sibling: "node_9_1702956631016",
},
{
type: "folder",
dialog_node: "node_9_1702956631016",
previous_sibling: "node_7_1702794902054",
},
];
const orderedArray = orderDialogNodes(inputArray);
console.log(orderedArray);
``` |
To make a copy of an array where every non-zero element is replaced by 1 and without using numpy, you just have to iterate over the array and apply a ternary operator, where you will define the condition and the output:
import numpy as np
a = np.array([2, 7, -2, 0, 0, 9])
b = [1 if i != 0 else 0 for i in a] # if not zero -> 1; else -> 0
Note that b is now a "list" not a numpy.array object.
You could also achieve it by using map and lambda:
b = list(map(lambda number: 1 if number != 0 else 0, a)) |
I figured out the issue. I was using ' and I needed to use ` |
I need your help with this. I want to left click on a country, ex Italy. Print the name Italy and color Italy on the map. Should be usable with any country. Here is my code:
found this:
https://stackoverflow.com/questions/23399704/polygon-containment-test-in-matplotlib-artist
```
import matplotlib.pyplot as plt
import cartopy
import cartopy.io.shapereader as shpreader
import cartopy.crs as ccrs
ax = plt.axes(projection=ccrs.PlateCarree())
ax.add_feature(cartopy.feature.LAND)
ax.add_feature(cartopy.feature.OCEAN)
ax.add_feature(cartopy.feature.COASTLINE)
ax.add_feature(cartopy.feature.BORDERS, linestyle='-', alpha=.5)
ax.add_feature(cartopy.feature.LAKES, alpha=0.95)
#ax.add_feature(cartopy.feature.RIVERS)
ax.set_extent([-150, 60, -25, 60])
shpfilename = shpreader.natural_earth(resolution='110m',
category='cultural',
name='admin_0_countries')
reader = shpreader.Reader(shpfilename)
countries = reader.records()
for country in countries:
if country.attributes['NAME_LONG'] == 'Italy':
ax.add_geometries(country.geometry, ccrs.PlateCarree(), facecolor=(0, 1, 0), label = "A")
else:
ax.add_geometries(country.geometry, ccrs.PlateCarree(), facecolor=(1, 1, 1), label = country.attributes['NAME_LONG'])
def onclick(event):
x,y = event.xdata, event.ydata
print(x, y)
plt.connect('button_press_event', onclick)
plt.rcParams["figure.figsize"] = (50,50)
plt.show()
```
|
null |
How do I get a data variable from a Promise function using node js? |
i just created a fresh installation of docusaurus 3.1
Now I want to enable mermaid. The docu says:
```
export default {
markdown: {
mermaid: true,
},
themes: ['@docusaurus/theme-mermaid'],
};
```
But when I open the docusarus.config.js and add this lines, I get an error:
Cause: ParseError: Only one default export allowed per module.
So it is not clear to me how I should add plugins to docusarus ...
I added the codeblock at the end of the configuration files:
```
export default config;
export default {
markdown: {
mermaid: true,
},
themes: ['@docusaurus/theme-mermaid'],
};
```
|
Docusaurus config - syntax unclear |
|config| |
null |
I managed to do it this way: I found hierarchy of all contours and then found 4 contours with the same hierarchy number. Those 4 contours are the 4 squares in the picture.
for cnt in zip(contours, hierarchy):
approx = cv2.approxPolyDP(cnt[0], 0.01 * cv2.arcLength(cnt[0], True), True)
if len(approx) == 4:
x, y, w, h = cv2.boundingRect(cnt[0])
ratio = float(w) / h
#print(cnt[1])
if 0.9 <= ratio <= 1.1:
correct_contours.append(cnt[1].tolist())
hierarchy_values = []
for array in correct_contours:
hierarchy_values.append(array[3])
value_counts = Counter(hierarchy_values)
values_occuring_exactly_four_times = [value for value, count in value_counts.items() if count == 4 and value != 0]
for cnt in zip(contours, hierarchy):
approx = cv2.approxPolyDP(cnt[0], 0.01 * cv2.arcLength(cnt[0], True), True)
if len(approx) == 4:
x, y, w, h = cv2.boundingRect(cnt[0])
ratio = float(w) / h
#print(cnt[1])
if 0.9 <= ratio <= 1.1:
if cnt[1][3] == values_occuring_exactly_four_times[0]:
cv2.putText(frame, 'Correct', (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (36, 255, 12), 2)
Moments = cv2.moments(cnt[0])
xCenter = int(Moments["m10"] / Moments["m00"])
yCenter = int(Moments["m01"] / Moments["m00"])
yValues.append(yCenter)
xValues.append(xCenter)
detected_squares.append(approx)
cv2.drawContours(frame, detected_squares, -1, (0,255, 0), 2)
cv2.imshow('image with drawn contours', frame)
cv2.waitKey(0)
cv2.destroyAllWindows()
|
Short version: Tailwind works by scanning your code and looking for things that it recognizes as classes. It then only outputs those classes into the css and everything works. This breaks down when dynamically generate a className. :/
Despite what some believe though, (and the editorial emphasis of their own docs), this is *not* forbidden in TW. They have a mechanism specifically to support this and other cases: `config.safelist`. You simply list out (or define w regex) all the classes that you intend to dynamically generate in your code (or that might not appear in your codebase for some other reason).
Somewhere in your code:
// other logic
const cn = `${startingBP}:grid-cols-${columns} `
// other logic
In tailwind.config :
```javascript
export default {
// ...other config stuff
content: {
// make sure to specify all the files you'd like tw to scan
files: [ 'src/**/*.tsx', './node_modules/@myorg/shared-ui/**/*.{ts,tsx}'
},
safelist: [
'sm:grid-cols-1',
'sm:grid-cols-2',
'sm:grid-cols-3',
'md:grid-cols-1',
'md:grid-cols-2',
'md:grid-cols-3',
// etc (could also use regex)
]
}
```
(I actually use this a lot, since I maintain a shared framework that sometimes has to rely on logic to style things. I actually separate them into their own file, `safelist.tailwind.js` and then just import it and pass it to the config.)
https://tailwindcss.com/docs/content-configuration#configuring-source-paths
https://tailwindcss.com/docs/content-configuration#safelisting-classes
(They recommend using whole classname literals as much as possible, but this approach is tried and true by many of us as well)
|
I'm just building an GCC version from source.
During the make step, I get the error message
```
"WARNING: `makeinfo' is missing on your system. You should only need it if you modified a `texi' or a
`.texinfo' file, or any other file indirectly affecting the aspect of the manual. The spurious call might also be the consequence of using a buggy
`make' (AIX, DU, IRIX). You might want to install the `Texinfo' package or the `GNU make' package. Grab either from any GNU archive site."
```
texinfo was installed with the command `sudo apt install texinfo`.
What can I do about the problem? |
{"OriginalQuestionIds":[24466615],"Voters":[{"Id":523612,"DisplayName":"Karl Knechtel"},{"Id":-1,"DisplayName":"Community","BindingReason":{"DuplicateApprovedByAsker":""}}]} |
This is for [Kotlin DSL][1] (build.gradle.**kts**).
### Method 1 (no need for `application` or other plugins)
```kotlin
tasks.jar {
manifest.attributes["Main-Class"] = "com.example.MyMainClass"
// OR another notation
// manifest {
// attributes["Main-Class"] = "com.example.MyMainClass"
// }
}
```
If you use any external libraries, use below code. Copy library JARs in *libs* sub-directory of where you put your result JAR. Make sure your library JAR files do not contain space in their file name.
```kotlin
tasks.jar {
manifest.attributes["Main-Class"] = "com.example.MyMainClass"
manifest.attributes["Class-Path"] = configurations
.runtimeClasspath
.get()
.joinToString(separator = " ") { file ->
"libs/${file.name}"
}
}
```
Note that Java requires us to use relative URLs for the `Class-Path` attribute. So, we cannot use the absolute path of Gradle dependencies (which is also prone to being changed and not available on other systems). If you want to use absolute paths, maybe [this workaround][2] will work.
Create the JAR with the following command:
```shell
./gradlew jar
```
The result JAR will be created in *build/libs/* directory by default.
### Method 2: Embedding libraries (if any) in the result JAR (fat or uber JAR)
```kotlin
tasks.jar {
manifest.attributes["Main-Class"] = "com.example.MyMainClass"
val dependencies = configurations
.runtimeClasspath
.get()
.map(::zipTree) // OR .map { zipTree(it) }
from(dependencies)
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
}
```
Creating the JAR is exactly the same as the previous method.
### Method 3: Using the [Shadow plugin][3] (to create a fat or uber JAR)
```kotlin
plugins {
id("com.github.johnrengelman.shadow") version "6.0.0"
}
// Shadow task depends on Jar task, so these will be reflected for Shadow as well
tasks.jar {
manifest.attributes["Main-Class"] = "org.example.MainKt"
}
```
Create the JAR with this command:
```shell
./gradlew shadowJar
```
See [Shadow documentations][4] for more information about configuring the plugin.
# Running the created JAR
```shell
java -jar my-artifact.jar
```
The above solutions were tested with:
- Java 17
- Gradle 7.1 (which uses Kotlin 1.4.31 for *.kts* build scripts)
See the official [Gradle documentation for creating uber (fat) JARs][5].
For more information about manifests, see [Oracle Java Documentation: Working with Manifest files](https://docs.oracle.com/javase/tutorial/deployment/jar/manifestindex.html).
Note that your resource files will be included in the JAR file automatically (assuming they were placed in */src/main/resources/* directory or any custom directory set as resources root in the build file). To access a resource file in your application, use this code (note the `/` at the start of names):
- Kotlin
```kotlin
val vegetables = MyClass::class.java.getResource("/vegetables.txt").readText()
// Alternative ways:
// val vegetables = object{}.javaClass.getResource("/vegetables.txt").readText()
// val vegetables = MyClass::class.java.getResourceAsStream("/vegetables.txt").reader().readText()
// val vegetables = object{}.javaClass.getResourceAsStream("/vegetables.txt").reader().readText()
```
- Java
```java
var stream = MyClass.class.getResource("/vegetables.txt").openStream();
// OR var stream = MyClass.class.getResourceAsStream("/vegetables.txt");
var reader = new BufferedReader(new InputStreamReader(stream));
var vegetables = reader.lines().collect(Collectors.joining("\n"));
```
[1]: https://docs.gradle.org/current/userguide/kotlin_dsl.html
[2]: https://stackoverflow.com/q/47961942/8583692
[3]: https://github.com/johnrengelman/shadow
[4]: https://imperceptiblethoughts.com/shadow/configuration/#configuring-the-jar-manifest
[5]: https://docs.gradle.org/current/userguide/working_with_files.html#sec:creating_uber_jar_example |
I came with issues with my custom server built on Java Socket.
Server works great and transmits data properly with exception of when after HTML form submission I want to redirect browser to success or failure notification address.
I send 303 See Other in response to POST sent from mentioned form and page starts refreshing but never ends. It also looks like there is still body on the new request seeking the redirection page.
Here are form request and my 303 response:
```
POST /html/configPositive.html HTTP/1.1<br/>
Host: localhost:8080<br/>
Connection: keep-alive<br/>
Content-Length: 27<br/>
Cache-Control: max-age=0<br/>
sec-ch-ua: "Google Chrome";v="119", "Chromium";v="119", "Not?A_Brand";v="24"<br/>
sec-ch-ua-mobile: ?0<br/>
sec-ch-ua-platform: "macOS"<br/>
Upgrade-Insecure-Requests: 1<br/>
Origin: http://localhost:8080<br/>
Content-Type: application/x-www-form-urlencoded<br/>
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36<br/>
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7<br/>
Sec-Fetch-Site: same-origin<br/>
Sec-Fetch-Mode: navigate<br/>
Sec-Fetch-User: ?1<br/>
Sec-Fetch-Dest: document<br/>
Referer: http://localhost:8080/html/configIndexAbout.html<br/>
Accept-Encoding: gzip, deflate, br<br/>
Accept-Language: pl-PL,pl;q=0.9,en-US;q=0.8,en;q=0.7<br/>
Cookie: Idea-93a338da=1106edad-21ca-4e1f-a631-c60429549309; playername=kotek behemotek; recordblocks=245; recordrows=86<br/>
HTTP/1.1 303 See Other<br/>
Location: /html/configPositive.html
```
Here is the HTML form:
```
<form action="/html/configPositive.html" method="post" enctype="application/x-www-form-urlencoded">
<h3>Tutaj wpisz tekst widoczny w About</h3>
<label>
<input type="text" name="/text/about/index">
</label>
<h3>Kiedy skończysz kliknij przycisk. Inaczej zmiany nie zostaną zapisane</h3>
<input type="submit">
</form>
```
|
I'm just building an GCC version from source.
During the make step, I get the error message
```
"WARNING: `makeinfo' is missing on your system. You should only need it if you modified a `texi' or a
`.texinfo' file, or any other file indirectly affecting the aspect of the manual. The spurious call might also be the consequence of using a buggy
`make' (AIX, DU, IRIX). You might want to install the `Texinfo' package or the `GNU make' package. Grab either from any GNU archive site."
```
texinfo is already installed with the command `sudo apt install texinfo`.
What can I do about the problem? |
Consider the slope plot below:
``` r
library(tidyverse)
df <- tibble(
id = 1:100,
x1 = sample(1:50, 100, replace = TRUE),
x2 = x1 + sample(1:50, 100, replace = TRUE)
) %>%
pivot_longer(
2:3,
names_to = "var",
values_to = "val"
)
ggplot(df, aes(x = var, y = val, group = id)) +
geom_point() +
geom_line()
```
<!-- -->
<sup>Created on 2024-01-31 with [reprex v2.0.2](https://reprex.tidyverse.org)</sup>
I want to show the distribution of x1 and x2 alongside the points. This can almost be accomplished with [the gghalves package:][1]
``` r
library(tidyverse)
library(gghalves)
df <- tibble(
id = 1:100,
x1 = sample(1:50, 100, replace = TRUE),
x2 = x1 + sample(1:50, 100, replace = TRUE)
) %>%
pivot_longer(
2:3,
names_to = "var",
values_to = "val"
)
ggplot(df, aes(x = var, y = val)) +
geom_half_violin() +
geom_point()
```
<!-- -->
<sup>Created on 2024-01-31 with [reprex v2.0.2](https://reprex.tidyverse.org)</sup>
But I also want to (1) complete the slope graph by connecting the points with the slope lines; and (2) flip the second violin distribution so the points are inside and the distribution is on the outside. Is it possible to accomplish both in the same plot?
[1]: https://erocoar.github.io/gghalves/ |
Slope plot with marginal distributions using ggplot2 |
|r|ggplot2| |
I know that `atomic<T>` will apply a lock on type "T" variable when multiple threads are reading and writing the variable, making sure only one of them is doing the R/W.
But in a multi-CPU core computer, threads can run on different cores, and different cores would have different L1-cache, L2-cache, while share L3-cache. We know sometimes C++ compiler will optimize a variable to be stored inside register, so that if a variable is not stored in memory, then there's no memory synchronization between different core-cache on the variable.
If an `atomic<T>` variable is optimized to be some register variable by compiler, then it's not stored in memory, when one core writes its value, another core could read out a stale value, right? Is there any guarantee on this data consistency?
|
Does C++11 atomic automatically solve multi-core race on variable read-write? |
|c++|multithreading|c++11|atomic|cpu-cores| |
function new_date(){
var ss = SpreadsheetApp.getActive();
var rg = ss.getRange("A2:A10");
var vs = rg.getDisplayValues();
Logger.log(JSON.stringify(vs));
}
DATA:
||A|
|:---:|:---|
|1|COL1|
|2|1/1/2024|
|3|1/2/2024|
|4|1/3/2024|
|5|1/4/2024|
|6|1/5/2024|
|7|1/6/2024|
|8|1/7/2024|
|9|1/8/2024|
|10|1/9/2024|
Execution log
12:40:53 PM Notice Execution started
12:40:48 PM Info [["1/1/2024"],["1/2/2024"],["1/3/2024"],["1/4/2024"],["1/5/2024"],["1/6/2024"],["1/7/2024"],["1/8/2024"],["1/9/2024"]]
12:40:56 PM Notice Execution completed
It returns a 2 dimensional array even for just one column. So in your case if you wish to refer to each cell value it would be `vs[i][0]` |
When Socket connect is refused, you aways want to check the connect callback.
def connect(params, socket, info) do
# You are doing something here that makes the connect fail.
end
My guess is the token that is `undefined`, you are likely validating the token or some condition that fails and results in the connect failure. |
I wrote below bash Shell script to check whether the input value is a character string or a number (using Mathematical function):
#!/bin/bash
uniq_value=$1
if `$(echo "$uniq_value / $uniq_value" | bc)` ; then
echo "Given value is number"
else
echo "Given value is string"
fi
The execution result is as follows:
$ sh -x test.sh abc
+ uniq_value=abc
+++ echo 'abc / abc'
+++ bc
Runtime error (func=(main), adr=5): Divide by zero
+ echo 'Given value is number'
Given value is number
There is an error like this:
> Runtime error (func=(main), adr=5): Divide by zero.
Can anyone please suggest how to rectify this error?
- The expected result for the input `abc123xy` should be `Given value is string`.
- The expected result for the input `3.045` should be `Given value is number`.
- The expected result for the input `6725302` should be `Given value is number`.
After this I will assign a series of values to `uniq_value` variable in a loop. Hence getting the output for this script is very important.
|
{"OriginalQuestionIds":[9191803],"Voters":[{"Id":8620333,"DisplayName":"Temani Afif","BindingReason":{"GoldTagBadge":"css"}}]} |
I used [git-filter-repo][1] to remove several large binary files from my git repo after migration from SVN. Now, I have to add few selected files back and was wondering what will happen to the git repo size if I add the identical 3.14MB binary file to 5 branches: Does git detect that the file has the identical hash? Does repo size grow by 3.14MB, or by 5x3.14MB?
And, similar question for text files: Does git detect if I add a copy of a text file to a different branch? What if it is slightly modified?
[1]: https://github.com/newren/git-filter-repo |
git repo size due to commit binary file to multiple branches |
|git|hash|binaryfiles|filesize|git-filter-repo| |
My problem is the following, I want to make a query where I bring all (*) of a table (ELEMENT) and another table (IMAGE) may have 3 different images, but I only want to bring the first element, unfortunately with my query brings me 3 times the same ELEMENT but with different IMAGE since I have 3.
I want to bring 1 image from table A, B and C, but in the table B or C i could have 4 or 5 images extra.
I tried with DISTINCT but it doesn't work.
I also don't understand why SQFLite doesn't support subqueries, if I want to do another SELECT, why doesn't it allow me to do it?
```dart
final List<Map<String, Object?>> res = await database.rawQuery(
'''
SELECT DISTINCT
e.*,
a.id AS aId, a.name AS aName,
[...]
b.id AS bId, b.name AS bName,
[...]
c.id AS cId, c.name AS cName,
[...]
FROM element_table e
LEFT JOIN image_table a ON e.imageId = a.id
LEFT JOIN element_picture_table ep ON ep.elementId = e.id /// nested table with ids between PICTURE TABLE and ELEMENT TABLE
LEFT JOIN picture_table p ON ep.pictureId = p.id
LEFT JOIN image_table b ON b.id= p.imageOne /// Here in the IMAGE TABLE B, i could have 2 or 5 images...
LEFT JOIN image_table c ON c.id= p.imageTwo
WHERE [...]
ORDER BY [...]
''',
[
...
],
);
```
I try to do this because i don't want to use dart logic, this to avoid a lot of process extra, imagine that I have 2000 rows in the database? if I do some kind of map or for, my process takes time.
This can be mi Object :
```dart
class Element {
final int id,
final String name,
final int imageId,
final List<Picture> pictures,
}
class Picture {
final int id,
final String name,
final int imageOne,
final int imageTwo
}
``` |
You should uncomment the `test_sequence` and include only the tests you want, for example:
scenario:
test_sequence:
- destroy
- create
- converge
# - idempotence
- lint
- verify
Read more: [Advanced testing](https://ansible.readthedocs.io/projects/molecule/configuration/?h=test_sequence#advanced-testing). |
I'm just building an GCC version from source.
During the make step, I get the error message
```
"WARNING: `makeinfo' is missing on your system. You should only need it if you modified a `texi' or a
`.texinfo' file, or any other file indirectly affecting the aspect of the manual. The spurious call might also be the consequence of using a buggy
`make' (AIX, DU, IRIX). You might want to install the `Texinfo' package or the `GNU make' package. Grab either from any GNU archive site."
```
texinfo was already installed with the command `sudo apt install texinfo`.
What can I do about the problem? |
|python|numpy|opencv|image-processing|integer-overflow| |
```haskell
import Network.Socket
import Control.Monad
import Network
import System.Environment (getArgs)
import System.IO
import Control.Concurrent (forkIO)
main :: IO ()
main = withSocketsDo $ do
putStrLn ("up top\n")
[portStr] <- getArgs
sock' <- socket AF_INET Stream defaultProtocol
let port = fromIntegral (read portStr :: Int)
socketAddress = SockAddrInet port 0000
bindSocket sock' socketAddress
listen sock' 1
putStrLn $ "Listening on " ++ (show port)
(sock, sockAddr) <- Network.Socket.accept sock'
handle <- socketToHandle sock ReadWriteMode
sockHandler sock handle
-- hClose handle putStrLn ("close handle\n")
sockHandler :: Socket -> Handle -> IO ()
sockHandler sock' handle = forever $ do
hSetBuffering handle LineBuffering
forkIO $ commandProcessor handle
commandProcessor :: Handle -> IO ()
commandProcessor handle = do
line <- hGetLine handle
let (cmd:arg) = words line
case cmd of
"echo" -> echoCommand handle arg
"add" -> addCommand handle arg
_ -> do hPutStrLn handle "Unknown command"
echoCommand :: Handle -> [String] -> IO ()
echoCommand handle arg = do
hPutStrLn handle (unwords arg)
addCommand :: Handle -> [String] -> IO ()
addCommand handle [x,y] = do
hPutStrLn handle $ show $ read x + read y
addCommand handle _ = do
hPutStrLn handle "usage: add Int Int"
```
I'm noticing some quirks in it's behavior, but the one I want to address for the moment is what happens when a client disconnects with the server. When that happens, the server throws the following exception endlessly, and will not respond to further client connections.
```none
strawboss: : hGetLine: end of file
```
I've tried flushing the handle, and closing the handle. I think that closing the handle is the right thing to do, but I cannot figure out where te correct place to close the handle is. So my first question is: Is the solution to this problem a judicious hClose placement in the code? If not, where does the problem lie? |
You should install your custom module:
go install project/lesson/students.go |