问:
Run file with terminal commands in Python IDE
I run these commands out of my terminal.

It works perfectly. Since I don't want to type the same commands every time, I made a file with these commands:

However when I run this file from terminal, the commands in the file are now not recognized:

What do i need to modify to make this file work the way it should?


来源: stackexchange

问:
Failure to create identity server tables 4
I have used identity and identity server 4 in my project. But the main identity server tables are not created for me like the client ...
Any help guiding me would be appreciated

Context:

```<code>public class ApplicationDbContext : IdentityDbContext<ApplicationUser>, IApplicationDbContext
    {
        private readonly IMediator _mediator;
        private readonly AuditableEntitySaveChangesInterceptor _auditableEntitySaveChangesInterceptor;

        public ApplicationDbContext(
            DbContextOptions<ApplicationDbContext> options,
            IMediator mediator,
            AuditableEntitySaveChangesInterceptor auditableEntitySaveChangesInterceptor)
            : base(options)
        {
            _mediator = mediator;
            _auditableEntitySaveChangesInterceptor = auditableEntitySaveChangesInterceptor;
        }

        public DbSet<ApplicationUser> Users => Set<ApplicationUser>();

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.AddInterceptors(_auditableEntitySaveChangesInterceptor);
        }
</code>```

list of Packages Identity Server in Infrastructure :

```<code>    <PackageReference Include="IdentityServer4" Version="4.1.2" />
    <PackageReference Include="IdentityServer4.AspNetIdentity" Version="4.1.2" />
    <PackageReference Include="IdentityServer4.EntityFramework" Version="4.1.2" />
    <PackageReference Include="IdentityServer4.Storage" Version="4.1.2" />
   <PackageReference Include="Microsoft.AspNetCore.Authentication.Google" Version="6.0.9" />
    <PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="6.0.9" />
    <PackageReference Include="Microsoft.AspNetCore.Identity.UI" Version="6.0.9" />
</code>```

ConfigureServices in Infrastructure layer :

```<code> public static IServiceCollection AddInfrastructureServices(this IServiceCollection services, IConfiguration configuration)
    {
    services.AddScoped<AuditableEntitySaveChangesInterceptor>();

services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(configuration.GetConnectionString("DefaultConnection"),
               builder => builder.MigrationsAssembly(typeof(ApplicationDbContext).Assembly.FullName)))
            .AddIdentity<ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();

services.AddHangfire(config => config
            .SetDataCompatibilityLevel(CompatibilityLevel.Version_170)
            .UseSimpleAssemblyNameTypeSerializer()
            .UseRecommendedSerializerSettings()
            .UseSqlServerStorage(
                configuration.GetConnectionString("DefaultConnection"),
                new SqlServerStorageOptions()
                {
                    CommandBatchMaxTimeout = TimeSpan.FromMinutes(5),
                    SlidingInvisibilityTimeout = TimeSpan.FromMinutes(5),
                    QueuePollInterval = TimeSpan.Zero,
                    UseRecommendedIsolationLevel = true,
                    DisableGlobalLocks = true
                }));

        services.AddHangfireServer();

        services.AddScoped<IApplicationDbContext>(provider =>
          provider.GetRequiredService<ApplicationDbContext>());

        services.AddScoped<ApplicationDbContextInitialiser>();

        services.AddAuthentication(options =>
        {
            options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            IdentityServerConstants.DefaultCookieAuthenticationScheme;
            options.DefaultChallengeScheme = "oidc";
        })
        .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddOpenIdConnect("oidc", options =>
            {
                options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                options.RequireHttpsMetadata = false;
                options.ClientId = "website";
                options.Authority = "https://localhost:5001/";
                options.ResponseType = "code id-token";
                options.ClientSecret = "secret";
                options.Scope.Add("profile");
                options.Scope.Add("phone");
                options.SaveTokens = true;
                options.GetClaimsFromUserInfoEndpoint = true;
                options.ClaimActions.MapJsonSubKey(
                    "sub",
                    "profile",
                    "profile_id");
            });
     }

        services.AddCors(options =>
        {
            {
                options.AddPolicy("AllowOrigin", cfg =>
                    cfg.AllowAnyMethod()
                        .AllowAnyHeader()
                        .AllowAnyOrigin()
                        //.AllowCredentials()
                        .Build());
            }
        });

       services.AddAuthorization(options =>
            options.AddPolicy(
                "CanPurge",
                policy => policy.RequireRole("Administrator")));

      services.AddIdentityServer()
            .AddDeveloperSigningCredential()
            .AddAspNetIdentity<ApplicationUser>()
            .AddConfigurationStore(options =>
            {
                options.ConfigureDbContext = c => c.UseSqlServer(
                    configuration.GetConnectionString("DefaultConnection"), builder =>

      builder.MigrationsAssembly(typeof(ApplicationDbContext).Assembly.FullName));
            })
            .AddOperationalStore(options =>
            {
                options.ConfigureDbContext = c =>
      c.UseSqlServer(configuration.GetConnectionString("DefaultConnection"), builder =>

       builder.MigrationsAssembly(typeof(ApplicationDbContext).Assembly.FullName));
            })
            .AddInMemoryClients(MyConfig.Clients)
            .AddInMemoryApiScopes(MyConfig.ApiScopes)
            .AddInMemoryIdentityResources(MyConfig.IdentityResources)
            .AddDefaultSecretValidators();

     return services;
</code>```

program.cs important of middleware:

```<code>pp.UseHttpsRedirection();

app.UseRouting();

app.UseCors("AllowOrigin");

app.UseAuthentication();

app.UseAuthorization();

app.UseIdentityServer();

app.UseHealthChecks("/health");

//app.UseDefaultFiles();
app.UseStaticFiles();

app.UseHangfireDashboard();

app.MapControllers();

app.MapHangfireDashboard("/hangfire", new DashboardOptions()
{
    Authorization = new[] { new MyAuthorizationFilter() },
    IsReadOnlyFunc = (DashboardContext context) => true
});

app.Run();

</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have used identity and identity server 4 in my project. But the main identity server tables are not created for me like the client ...
Any help guiding me would be appreciated

Context:

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>, IApplicationDbContext
    {
        private readonly IMediator _mediator;
        private readonly AuditableEntitySaveChangesInterceptor _auditableEntitySaveChangesInterceptor;

        public ApplicationDbContext(
            DbContextOptions<ApplicationDbContext> options,
            IMediator mediator,
            AuditableEntitySaveChangesInterceptor auditableEntitySaveChangesInterceptor)
            : base(options)
        {
            _mediator = mediator;
            _auditableEntitySaveChangesInterceptor = auditableEntitySaveChangesInterceptor;
        }

        public DbSet<ApplicationUser> Users => Set<ApplicationUser>();

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.AddInterceptors(_auditableEntitySaveChangesInterceptor);
        }

list of Packages Identity Server in Infrastructure :

    <PackageReference Include="IdentityServer4" Version="4.1.2" />
    <PackageReference Include="IdentityServer4.AspNetIdentity" Version="4.1.2" />
    <PackageReference Include="IdentityServer4.EntityFramework" Version="4.1.2" />
    <PackageReference Include="IdentityServer4.Storage" Version="4.1.2" />
   <PackageReference Include="Microsoft.AspNetCore.Authentication.Google" Version="6.0.9" />
    <PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="6.0.9" />
    <PackageReference Include="Microsoft.AspNetCore.Identity.UI" Version="6.0.9" />

ConfigureServices in Infrastructure layer :

 public static IServiceCollection AddInfrastructureServices(this IServiceCollection services, IConfiguration configuration)
    {
    services.AddScoped<AuditableEntitySaveChangesInterceptor>();

services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(configuration.GetConnectionString("DefaultConnection"),
               builder => builder.MigrationsAssembly(typeof(ApplicationDbContext).Assembly.FullName)))
            .AddIdentity<ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();

services.AddHangfire(config => config
            .SetDataCompatibilityLevel(CompatibilityLevel.Version_170)
            .UseSimpleAssemblyNameTypeSerializer()
            .UseRecommendedSerializerSettings()
            .UseSqlServerStorage(
                configuration.GetConnectionString("DefaultConnection"),
                new SqlServerStorageOptions()
                {
                    CommandBatchMaxTimeout = TimeSpan.FromMinutes(5),
                    SlidingInvisibilityTimeout = TimeSpan.FromMinutes(5),
                    QueuePollInterval = TimeSpan.Zero,
                    UseRecommendedIsolationLevel = true,
                    DisableGlobalLocks = true
                }));

        services.AddHangfireServer();

        services.AddScoped<IApplicationDbContext>(provider =>
          provider.GetRequiredService<ApplicationDbContext>());

        services.AddScoped<ApplicationDbContextInitialiser>();

        services.AddAuthentication(options =>
        {
            options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            IdentityServerConstants.DefaultCookieAuthenticationScheme;
            options.DefaultChallengeScheme = "oidc";
        })
        .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddOpenIdConnect("oidc", options =>
            {
                options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                options.RequireHttpsMetadata = false;
                options.ClientId = "website";
                options.Authority = "https://localhost:5001/";
                options.ResponseType = "code id-token";
                options.ClientSecret = "secret";
                options.Scope.Add("profile");
                options.Scope.Add("phone");
                options.SaveTokens = true;
                options.GetClaimsFromUserInfoEndpoint = true;
                options.ClaimActions.MapJsonSubKey(
                    "sub",
                    "profile",
                    "profile_id");
            });
     }

        services.AddCors(options =>
        {
            {
                options.AddPolicy("AllowOrigin", cfg =>
                    cfg.AllowAnyMethod()
                        .AllowAnyHeader()
                        .AllowAnyOrigin()
                        //.AllowCredentials()
                        .Build());
            }
        });

       services.AddAuthorization(options =>
            options.AddPolicy(
                "CanPurge",
                policy => policy.RequireRole("Administrator")));

      services.AddIdentityServer()
            .AddDeveloperSigningCredential()
            .AddAspNetIdentity<ApplicationUser>()
            .AddConfigurationStore(options =>
            {
                options.ConfigureDbContext = c => c.UseSqlServer(
                    configuration.GetConnectionString("DefaultConnection"), builder =>

      builder.MigrationsAssembly(typeof(ApplicationDbContext).Assembly.FullName));
            })
            .AddOperationalStore(options =>
            {
                options.ConfigureDbContext = c =>
      c.UseSqlServer(configuration.GetConnectionString("DefaultConnection"), builder =>

       builder.MigrationsAssembly(typeof(ApplicationDbContext).Assembly.FullName));
            })
            .AddInMemoryClients(MyConfig.Clients)
            .AddInMemoryApiScopes(MyConfig.ApiScopes)
            .AddInMemoryIdentityResources(MyConfig.IdentityResources)
            .AddDefaultSecretValidators();

     return services;

program.cs important of middleware:

pp.UseHttpsRedirection();

app.UseRouting();

app.UseCors("AllowOrigin");

app.UseAuthentication();

app.UseAuthorization();

app.UseIdentityServer();

app.UseHealthChecks("/health");

//app.UseDefaultFiles();
app.UseStaticFiles();

app.UseHangfireDashboard();

app.MapControllers();

app.MapHangfireDashboard("/hangfire", new DashboardOptions()
{
    Authorization = new[] { new MyAuthorizationFilter() },
    IsReadOnlyFunc = (DashboardContext context) => true
});

app.Run();


问:
Could not find method classpath() for arguments [androidx.navigation:navigation-safe-args-gradle-plugin:2.5.3]
```<code>
plugins {

    id 'com.android.application'
    id 'org.jetbrains.kotlin.android'
    id 'androidx.navigation.safeargs.kotlin' version '2.5.3' apply(false)
}

dependencies {
    def nav_version='2.5.3'
    classpath("androidx.navigation:navigation-safe-args-gradle-plugin:$nav_version")

    // Feature module Support
    implementation "androidx.navigation:navigation-dynamic-features-fragment:$nav_version"

    // Testing Navigation
    androidTestImplementation "androidx.navigation:navigation-testing:$nav_version"
   // classpath("androidx.navigation:navigation-safe-args-gradle-plugin:$nav_version")
    // Jetpack Compose Integration
    implementation "androidx.navigation:navigation-compose:$nav_version"
    implementation "androidx.navigation:navigation-fragment-ktx:$nav_version"
    implementation "androidx.navigation:navigation-ui-ktx:$nav_version"
    implementation 'androidx.core:core-ktx:1.7.0'
    implementation 'androidx.appcompat:appcompat:1.5.1'
    implementation 'com.google.android.material:material:1.7.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
</code>```

my build.gradle(app) files looks like this, I am getting the error while trying to sync.

was excepting to sync without errors.

Body:
plugins {

    id 'com.android.application'
    id 'org.jetbrains.kotlin.android'
    id 'androidx.navigation.safeargs.kotlin' version '2.5.3' apply(false)
}

dependencies {
    def nav_version='2.5.3'
    classpath("androidx.navigation:navigation-safe-args-gradle-plugin:$nav_version")

    // Feature module Support
    implementation "androidx.navigation:navigation-dynamic-features-fragment:$nav_version"

    // Testing Navigation
    androidTestImplementation "androidx.navigation:navigation-testing:$nav_version"
   // classpath("androidx.navigation:navigation-safe-args-gradle-plugin:$nav_version")
    // Jetpack Compose Integration
    implementation "androidx.navigation:navigation-compose:$nav_version"
    implementation "androidx.navigation:navigation-fragment-ktx:$nav_version"
    implementation "androidx.navigation:navigation-ui-ktx:$nav_version"
    implementation 'androidx.core:core-ktx:1.7.0'
    implementation 'androidx.appcompat:appcompat:1.5.1'
    implementation 'com.google.android.material:material:1.7.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}

my build.gradle(app) files looks like this, I am getting the error while trying to sync.

was excepting to sync without errors.


问:
How to Make Notification System Using React and Firebase?
I'm using React and Firebase to create chat web app.

And I don't know how user can get notofications, when another user sent him a message in the chat.

Can someone tell me how to do it?

If you want to look at the whole project, here is github: https://github.com/PHILLyaHI/diplom-work/tree/main/React-Frontend/frontend

But for now, I’ll show the files below that I think are important for creating a notification system.

Input.js File with sending system

```<code>import React, { useContext, useState } from "react";
import Img from "../../static/chat/add-img.png";
import Attach from "../../static/chat/attach.png";
import { AuthContext } from "./AuthContext";
import { ChatContext } from "./ChatContext";
import {
  arrayUnion,
  doc,
  serverTimestamp,
  Timestamp,
  updateDoc,
} from "firebase/firestore";
import { db, storage } from "../../firebase";
import { v4 as uuid } from "uuid";
import { getDownloadURL, ref, uploadBytesResumable } from "firebase/storage";

const Input = () => {
  const [text, setText] = useState("");
  const [img, setImg] = useState(null);
  const { currentUser } = useContext(AuthContext);
  const { data } = useContext(ChatContext);

  const handleSend = async () => {
    if (img) {
      const storageRef = ref(storage, uuid());

      const uploadTask = uploadBytesResumable(storageRef, img);

      uploadTask.on(
        (error) => {
          //TODO:Handle Error
        },
        () => {
          getDownloadURL(uploadTask.snapshot.ref).then(async (downloadURL) => {
            await updateDoc(doc(db, "chats", data.chatId), {
              messages: arrayUnion({
                id: uuid(),
                text,
                senderId: currentUser.uid,
                date: Timestamp.now(),
                img: downloadURL,
              }),
            });
          });
        }
      );
    } else {
      await updateDoc(doc(db, "chats", data.chatId), {
        messages: arrayUnion({
          id: uuid(),
          text,
          senderId: currentUser.uid,
          date: Timestamp.now(),
        }),
      });
    }

    await updateDoc(doc(db, "userChats", currentUser.uid), {
      [data.chatId + ".lastMessage"]: {
        text,
      },
      [data.chatId + ".date"]: serverTimestamp(),
    });

    await updateDoc(doc(db, "userChats", data.user.uid), {
      [data.chatId + ".lastMessage"]: {
        text,
      },
      [data.chatId + ".date"]: serverTimestamp(),
    });

    setText("");
    setImg(null);
  };

  return (
    <div className="input">
      <input
        type="text"
        placeholder="Type something..."
        onChange={(e) => setText(e.target.value)}
        value={text}
      />
      <div className="send">
        <img src={Attach} alt="" />
        <input
          type="file"
          style={{ display: "none" }}
          id="file"
          onChange={(e) => setImg(e.target.files[0])}
        />
        <label title="IMAGE SUPPOSE TO BE LESS THAN 250KB" htmlFor="file">
          <img src={Img} alt="" />
        </label>
        <button onClick={handleSend}>Send</button>
      </div>
    </div>
  );
};

export default Input;
</code>```

Chats.js The sidebar with users.

```<code>import React, { useContext, useEffect, useState } from "react";
import { doc, onSnapshot } from "firebase/firestore";
import { AuthContext } from "./AuthContext";
import { db } from "../../firebase";
import { ChatContext } from "./ChatContext";
import addNotification from "react-push-notification";

const Chats = () => {

  const [chats, setChats] = useState([]);
  const {currentUser} = useContext(AuthContext);
  const { dispatch } = useContext(ChatContext)

  useEffect(() => {
    const getChats = () => {
      const unsub = onSnapshot(doc(db, "userChats", currentUser.uid), (doc) => {
        setChats(doc.data())
      });

    return () => {
      unsub();
    };
  };
    currentUser.uid && getChats()
  }, [currentUser.uid]);

  const handleSelect = (u) => {
    dispatch({type: "CHANGE_USER", payload: u})
  }

  return (
    <div className="chats">
      {Object.entries(chats)?.map((chat) => (
      <div className="userChat" key={chat[0]} onClick={()=>handleSelect(chat[1].userInfo)}>
      {chats?.unread && (
        <small className="unread">New</small>
      )}
        <img src={chat[1].userInfo.photoURL} alt=""/>
        <div className="userChatInfo">
          <span>{chat[1].userInfo.displayName}</span>
          <p>{chat[1].lastMessage?.text}</p>
        </div>
      </div>
      ))};
    </div>
  );
};

export default Chats;
</code>```

AuthContext.js

```<code>import { createContext, useEffect, useState } from "react";
import { auth } from "../../firebase";
import { onAuthStateChanged } from "firebase/auth";

export const AuthContext = createContext();

export const AuthContextProvider = ({ children }) => {
  const [currentUser, setCurrentUser] = useState({});

  useEffect(() => {
    const unsub = onAuthStateChanged(auth, (user) => {
      setCurrentUser(user);
      console.log(user);
    });

    return () => {
      unsub();
    };
  }, []);

  return (
    <AuthContext.Provider value={{ currentUser }}>
      {children}
    </AuthContext.Provider>
  );
};
</code>```
```<code>import { createContext, useEffect, useState } from "react";
import { auth } from "../../firebase";
import { onAuthStateChanged } from "firebase/auth";

export const AuthContext = createContext();

export const AuthContextProvider = ({ children }) => {
  const [currentUser, setCurrentUser] = useState({});

  useEffect(() => {
    const unsub = onAuthStateChanged(auth, (user) => {
      setCurrentUser(user);
      console.log(user);
    });

    return () => {
      unsub();
    };
  }, []);

  return (
    <AuthContext.Provider value={{ currentUser }}>
      {children}
    </AuthContext.Provider>
  );
};
</code>```

ChatContext.js

```<code>import {
    createContext,
    useContext,
    useReducer,
  } from "react";
  import { AuthContext } from "./AuthContext";

  export const ChatContext = createContext();

  export const ChatContextProvider = ({ children }) => {
    const { currentUser } = useContext(AuthContext);
    const INITIAL_STATE = {
      chatId: "null",
      user: {},
    };

    const chatReducer = (state, action) => {
      switch (action.type) {
        case "CHANGE_USER":
          return {
            user: action.payload,
            chatId:
              currentUser.uid > action.payload.uid
                ? currentUser.uid + action.payload.uid
                : action.payload.uid + currentUser.uid,

          };

        default:
          return state;
      }
    };

    const [state, dispatch] = useReducer(chatReducer, INITIAL_STATE);

    return (
      <ChatContext.Provider value={{ data:state, dispatch }}>
        {children}
      </ChatContext.Provider>
    );
  };
</code>```

Body:
I'm using React and Firebase to create chat web app.

And I don't know how user can get notofications, when another user sent him a message in the chat.

Can someone tell me how to do it?

If you want to look at the whole project, here is github: https://github.com/PHILLyaHI/diplom-work/tree/main/React-Frontend/frontend

But for now, I’ll show the files below that I think are important for creating a notification system.

Input.js File with sending system

import React, { useContext, useState } from "react";
import Img from "../../static/chat/add-img.png";
import Attach from "../../static/chat/attach.png";
import { AuthContext } from "./AuthContext";
import { ChatContext } from "./ChatContext";
import {
  arrayUnion,
  doc,
  serverTimestamp,
  Timestamp,
  updateDoc,
} from "firebase/firestore";
import { db, storage } from "../../firebase";
import { v4 as uuid } from "uuid";
import { getDownloadURL, ref, uploadBytesResumable } from "firebase/storage";

const Input = () => {
  const [text, setText] = useState("");
  const [img, setImg] = useState(null);
  const { currentUser } = useContext(AuthContext);
  const { data } = useContext(ChatContext);

  const handleSend = async () => {
    if (img) {
      const storageRef = ref(storage, uuid());

      const uploadTask = uploadBytesResumable(storageRef, img);

      uploadTask.on(
        (error) => {
          //TODO:Handle Error
        },
        () => {
          getDownloadURL(uploadTask.snapshot.ref).then(async (downloadURL) => {
            await updateDoc(doc(db, "chats", data.chatId), {
              messages: arrayUnion({
                id: uuid(),
                text,
                senderId: currentUser.uid,
                date: Timestamp.now(),
                img: downloadURL,
              }),
            });
          });
        }
      );
    } else {
      await updateDoc(doc(db, "chats", data.chatId), {
        messages: arrayUnion({
          id: uuid(),
          text,
          senderId: currentUser.uid,
          date: Timestamp.now(),
        }),
      });
    }

    await updateDoc(doc(db, "userChats", currentUser.uid), {
      [data.chatId + ".lastMessage"]: {
        text,
      },
      [data.chatId + ".date"]: serverTimestamp(),
    });

    await updateDoc(doc(db, "userChats", data.user.uid), {
      [data.chatId + ".lastMessage"]: {
        text,
      },
      [data.chatId + ".date"]: serverTimestamp(),
    });

    setText("");
    setImg(null);
  };

  return (

      <input
        type="text"
        placeholder="Type something..."
        onChange={(e) => setText(e.target.value)}
        value={text}
      />

        <input
          type="file"
          style={{ display: "none" }}
          id="file"
          onChange={(e) => setImg(e.target.files[0])}
        />

        <button onClick={handleSend}>Send</button>

  );
};

export default Input;

Chats.js The sidebar with users.

import React, { useContext, useEffect, useState } from "react";
import { doc, onSnapshot } from "firebase/firestore";
import { AuthContext } from "./AuthContext";
import { db } from "../../firebase";
import { ChatContext } from "./ChatContext";
import addNotification from "react-push-notification";

const Chats = () => {

  const [chats, setChats] = useState([]);
  const {currentUser} = useContext(AuthContext);
  const { dispatch } = useContext(ChatContext)

  useEffect(() => {
    const getChats = () => {
      const unsub = onSnapshot(doc(db, "userChats", currentUser.uid), (doc) => {
        setChats(doc.data())
      });

    return () => {
      unsub();
    };
  };
    currentUser.uid && getChats()
  }, [currentUser.uid]);

  const handleSelect = (u) => {
    dispatch({type: "CHANGE_USER", payload: u})
  }

  return (

      {Object.entries(chats)?.map((chat) => (

handleSelect(chat[1].userInfo)}>
      {chats?.unread && (
        New
      )}

          {chat[1].userInfo.displayName}

{chat[1].lastMessage?.text}

      ))};

  );
};

export default Chats;

AuthContext.js

import { createContext, useEffect, useState } from "react";
import { auth } from "../../firebase";
import { onAuthStateChanged } from "firebase/auth";

export const AuthContext = createContext();

export const AuthContextProvider = ({ children }) => {
  const [currentUser, setCurrentUser] = useState({});

  useEffect(() => {
    const unsub = onAuthStateChanged(auth, (user) => {
      setCurrentUser(user);
      console.log(user);
    });

    return () => {
      unsub();
    };
  }, []);

  return (
    <AuthContext.Provider value={{ currentUser }}>
      {children}
    </AuthContext.Provider>
  );
};

import { createContext, useEffect, useState } from "react";
import { auth } from "../../firebase";
import { onAuthStateChanged } from "firebase/auth";

export const AuthContext = createContext();

export const AuthContextProvider = ({ children }) => {
  const [currentUser, setCurrentUser] = useState({});

  useEffect(() => {
    const unsub = onAuthStateChanged(auth, (user) => {
      setCurrentUser(user);
      console.log(user);
    });

    return () => {
      unsub();
    };
  }, []);

  return (
    <AuthContext.Provider value={{ currentUser }}>
      {children}
    </AuthContext.Provider>
  );
};

ChatContext.js

import {
    createContext,
    useContext,
    useReducer,
  } from "react";
  import { AuthContext } from "./AuthContext";

  export const ChatContext = createContext();

  export const ChatContextProvider = ({ children }) => {
    const { currentUser } = useContext(AuthContext);
    const INITIAL_STATE = {
      chatId: "null",
      user: {},
    };

    const chatReducer = (state, action) => {
      switch (action.type) {
        case "CHANGE_USER":
          return {
            user: action.payload,
            chatId:
              currentUser.uid > action.payload.uid
                ? currentUser.uid + action.payload.uid
                : action.payload.uid + currentUser.uid,

          };

        default:
          return state;
      }
    };

    const [state, dispatch] = useReducer(chatReducer, INITIAL_STATE);

    return (
      <ChatContext.Provider value={{ data:state, dispatch }}>
        {children}
      </ChatContext.Provider>
    );
  };


问:
How to run multiple cypress test cases in parallel in circle ci
I am trying to run 60 Cypress test cases in parallel in circle Ci but it's running all the 60 test cases on all the 4 machines rather than dividing the test cases and running them in parallel in all the machines to reduce the time say 20 test cases in each machine,, i am stuck and deadline is just tomorrow please help me out

So far I am just able to run the same test cases in parallel in 4 machines but i want to split the test cases in 4 machines so the overy time should be reduced


问:
Fix for `background-attachment: fixed` + `background-size: cover` on iOS
A background-image stretches the height of the div rather than being contained to the dimensions of the viewport. Testing on desktop the desired effect is achieved but on iPhone X (Safari and Chrome) the background stretches the height of the content so the image is 'zoomed in' and blurry.

So my phone is ignoring the combo of:

```<code>background-attachment: fixed;
background-position: top center;
background-repeat: no-repeat;
background-size: cover;
</code>```

I'm aware there has been issues with this in the past on iOS and I have searched SO for threads but I saw this working on https://mrleight.com/clip and I'm wondering how they got this to work - is JS maybe or something else I'm missing as my core CSS seems to more or less match.

I've included an simplified example, I've taken out all the 'real' content and just added a red div with a fixed height to simulate the effect my grid of content has.

I'd rather not resolve this by having a separate div with position: fixed - I see that as a last resort!

html,
body {
  margin: 0;
  padding: 0;
}

.page {
  background: white;
}

.collection {
  background-attachment: fixed;
  background-position: top center;
  background-repeat: no-repeat;
  background-size: cover;
  display: block;
  height: 100%;
  overflow: hidden;
  position: relative;
}

.collection:before {
  background: rgba(0, 0, 0, .48);
  content: "";
  height: 100%;
  position: absolute;
  inset: 0;
  width: 100%;
}

.p-grid {
  display: flex;
  flex-direction: column;
  flex-wrap: nowrap;
  height: 100%;
  position: relative;
}

.product-grid {
  background: rgba(255, 0, 0, .24);
  display: block;
  height: 3000px;
  margin: 0 auto;
  width: 50px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="page">

  <!-- START COLLECTION -->
  <div class="collection" style="background-image: url('https://images.pexels.com/photos/38136/pexels-photo-38136.jpeg')">

    <!-- START GRID -->
    <div class="p-grid">

      <div class="product-grid">

      </div>

    </div>
  </div>

</div></code>```

Body:
A background-image stretches the height of the div rather than being contained to the dimensions of the viewport. Testing on desktop the desired effect is achieved but on iPhone X (Safari and Chrome) the background stretches the height of the content so the image is 'zoomed in' and blurry.

So my phone is ignoring the combo of:

background-attachment: fixed;
background-position: top center;
background-repeat: no-repeat;
background-size: cover;

I'm aware there has been issues with this in the past on iOS and I have searched SO for threads but I saw this working on https://mrleight.com/clip and I'm wondering how they got this to work - is JS maybe or something else I'm missing as my core CSS seems to more or less match.

I've included an simplified example, I've taken out all the 'real' content and just added a red div with a fixed height to simulate the effect my grid of content has.

I'd rather not resolve this by having a separate div with position: fixed - I see that as a last resort!

html,
body {
  margin: 0;
  padding: 0;
}

.page {
  background: white;
}

.collection {
  background-attachment: fixed;
  background-position: top center;
  background-repeat: no-repeat;
  background-size: cover;
  display: block;
  height: 100%;
  overflow: hidden;
  position: relative;
}

.collection:before {
  background: rgba(0, 0, 0, .48);
  content: "";
  height: 100%;
  position: absolute;
  inset: 0;
  width: 100%;
}

.p-grid {
  display: flex;
  flex-direction: column;
  flex-wrap: nowrap;
  height: 100%;
  position: relative;
}

.product-grid {
  background: rgba(255, 0, 0, .24);
  display: block;
  height: 3000px;
  margin: 0 auto;
  width: 50px;
}


问:
Implementing a Basic Neural Network to Perform Classification with Neuroph
I'm very new to neural networks, and decided to try implementing a basic one using Neuroph in Java to perform multiclass classification using Multilayer Perceptron.

```<code>public static void main(String[] args) {
        final MultiLayerPerceptron neuralNetwork = new MultiLayerPerceptron(2, 3, 3, 3);

        final BackPropagation rule = new BackPropagation();
        rule.setLearningRate(0.1);
        rule.setMaxError(0.001);
        rule.setMaxIterations(10000);

        neuralNetwork.setLearningRule(rule);

        final Layer softMaxLayer = neuralNetwork.getLayerAt(neuralNetwork.getLayersCount() - 2);
        final SoftMax max = new SoftMax(softMaxLayer);

        for (Neuron n : softMaxLayer.getNeurons())
            n.setTransferFunction(max);

//      for (Neuron n : this.getOutputNeurons())
//          n.setTransferFunction(new Linear());

        DataSet trainingSet = new DataSet(2, 3);

        // Output contains only one instance of "1" to represent the class it belongs to
        trainingSet.add(new double[]{0, 0}, new double[]{1, 0, 0});
        trainingSet.add(new double[]{0, 0}, new double[]{1, 0, 0});
        trainingSet.add(new double[]{0, 0}, new double[]{1, 0, 0});
        trainingSet.add(new double[]{0, 1}, new double[]{0, 1, 0});
        trainingSet.add(new double[]{0, 1}, new double[]{1, 0, 0});
        trainingSet.add(new double[]{1, 0}, new double[]{0, 0, 1});
        trainingSet.add(new double[]{1, 1}, new double[]{0, 0, 1});
        trainingSet.add(new double[]{1, 1}, new double[]{0, 1, 0});
        trainingSet.add(new double[]{1, 1}, new double[]{0, 1, 0});

        // Train the neural network on the training set
        neuralNetwork.learn(trainingSet);

        // Test the neural network on a new example
        neuralNetwork.setInput(0, 1);
        neuralNetwork.calculate();
        double[] output = neuralNetwork.getOutput();

        System.out.println(output[0]); // prints the probability of class 0
        System.out.println(output[1]); // prints the probability of class 1
        System.out.println(output[2]); // prints the probability of class 2

        System.out.println("\n\nTotal (=1?): " + (output[0] + output[1] + output[2]));
        System.out.println(neuralNetwork.getLearningRule().getTotalNetworkError());
    }
</code>```

The output of the neural network should be a distribution, but the sum of it is slightly greater than or less than 1.

I generally tried to follow this guide, with the idea being I implement a soft max layer before the output layer. I assume I made a basic mistake here, if anyone knows what I did incorrectly please let me know.

EDIT: Example output:

```<code>0.8514345496167552
0.23687369660618554
0.001890247376537854

Total (=1?): 1.0901984935994786
0.17265593270797627
</code>```

(First three lines are the three output neuron values, followed by the sum of them, followed by the total network error).

Body:
I'm very new to neural networks, and decided to try implementing a basic one using Neuroph in Java to perform multiclass classification using Multilayer Perceptron.

public static void main(String[] args) {
        final MultiLayerPerceptron neuralNetwork = new MultiLayerPerceptron(2, 3, 3, 3);

        final BackPropagation rule = new BackPropagation();
        rule.setLearningRate(0.1);
        rule.setMaxError(0.001);
        rule.setMaxIterations(10000);

        neuralNetwork.setLearningRule(rule);

        final Layer softMaxLayer = neuralNetwork.getLayerAt(neuralNetwork.getLayersCount() - 2);
        final SoftMax max = new SoftMax(softMaxLayer);

        for (Neuron n : softMaxLayer.getNeurons())
            n.setTransferFunction(max);

//      for (Neuron n : this.getOutputNeurons())
//          n.setTransferFunction(new Linear());

        DataSet trainingSet = new DataSet(2, 3);

        // Output contains only one instance of "1" to represent the class it belongs to
        trainingSet.add(new double[]{0, 0}, new double[]{1, 0, 0});
        trainingSet.add(new double[]{0, 0}, new double[]{1, 0, 0});
        trainingSet.add(new double[]{0, 0}, new double[]{1, 0, 0});
        trainingSet.add(new double[]{0, 1}, new double[]{0, 1, 0});
        trainingSet.add(new double[]{0, 1}, new double[]{1, 0, 0});
        trainingSet.add(new double[]{1, 0}, new double[]{0, 0, 1});
        trainingSet.add(new double[]{1, 1}, new double[]{0, 0, 1});
        trainingSet.add(new double[]{1, 1}, new double[]{0, 1, 0});
        trainingSet.add(new double[]{1, 1}, new double[]{0, 1, 0});

        // Train the neural network on the training set
        neuralNetwork.learn(trainingSet);

        // Test the neural network on a new example
        neuralNetwork.setInput(0, 1);
        neuralNetwork.calculate();
        double[] output = neuralNetwork.getOutput();

        System.out.println(output[0]); // prints the probability of class 0
        System.out.println(output[1]); // prints the probability of class 1
        System.out.println(output[2]); // prints the probability of class 2

        System.out.println("\n\nTotal (=1?): " + (output[0] + output[1] + output[2]));
        System.out.println(neuralNetwork.getLearningRule().getTotalNetworkError());
    }

The output of the neural network should be a distribution, but the sum of it is slightly greater than or less than 1.

I generally tried to follow this guide, with the idea being I implement a soft max layer before the output layer. I assume I made a basic mistake here, if anyone knows what I did incorrectly please let me know.

EDIT: Example output:

0.8514345496167552
0.23687369660618554
0.001890247376537854

Total (=1?): 1.0901984935994786
0.17265593270797627

(First three lines are the three output neuron values, followed by the sum of them, followed by the total network error).


问:
Power Automate and Shadow Root elements
My colleague is using Power Automate to navigate a site.  The shadow-root elements seem to be skipped.  Any ideas?</p>

Title: Power Automate and Shadow Root elements


问:
Great PDF from single worksheet tab in Google Sheets
So I am working on a project where I am using Google Sheets to create a new sheet for payroll each time I hit "run payroll" the issue now is I want it to have it become a PDF and go into a specific folder and then email it out.

I found the first part then tried to do it with zapier but its not working as its creating the entire sheet as a PDF not the new one.

```<code>
</code>```
```<code>// Add menu items.
function onOpen() {
  var spreadsheet = SpreadsheetApp.getActive();
  var menuItems = [
    {name: 'Run Payroll', functionName: 'runPayroll'},
    {name: 'Delete Paystub', functionName: 'deletePayroll'},
    {name: 'Rebuild YTD from Stubs', functionName: 'rebuildYTD'}
  ];
  spreadsheet.addMenu('Payroll', menuItems);
}

function runPayroll() {
  var spreadsheet = SpreadsheetApp.getActive();
  var templateSheet = spreadsheet.getSheetByName('Template');

  // Validate weekly input
  if(!validateInput()) {
    return;
  }

  // Create new sheet for pay date
  var sheetName = Utilities.formatDate(getNamedValue('TempPayDate'), "PST", "MM/dd/yyyy");
  var paystubSheet = spreadsheet.getSheetByName(sheetName);
  if (paystubSheet) {
    // we already have a paystub for this date. remove that stub's values from YTD before we create a new one.
    removePayrollFromYTD(paystubSheet);
    paystubSheet.clear();
    SpreadsheetApp.flush();  // ran into a race issue here with YTD not getting updated fast enough for the new stub creation -- flush() seems to fix it
  } else {
    paystubSheet = spreadsheet.insertSheet(sheetName, spreadsheet.getNumSheets());
  }

  // Copy pay data from Template to new sheet
  var dataRange = templateSheet.getRange(1, 1, 45, 6);
  dataRange.copyValuesToRange(paystubSheet, 1, 6, 1, 45);
  dataRange.copyFormatToRange(paystubSheet, 1, 6, 1, 45);
  paystubSheet.setRowHeight(1, 10);
  paystubSheet.setRowHeight(2, 10);
  paystubSheet.setRowHeight(43, 10);
  paystubSheet.setRowHeight(44, 10);

  // Update YTD sheet. Grab current values from the template before we clean it up
  updateYTDFromCurrent();

  // Reset template data
  cleanup();

  // Activate new paystub and pre-set selection for printing
  paystubSheet.activate();
  paystubSheet.setActiveSelection(paystubSheet.getRange(1, 1, 45, 6));

//  Logger.log(sheetName);
//  dumpLog();
}

function validateInput() {
  // hours
  var hrsReg = getNamedValue('TempHoursReg');
  var hrsOT = getNamedValue('TempHoursOT');
  if(hrsReg + hrsOT <= 0) {
    Browser.msgBox('Error', 'Work harder. Enter some hours.', Browser.Buttons.OK);
    return 0;
  }

  // taxes
  var taxFed = getNamedValue('TempFedTax');
  var taxCa = getNamedValue('TempCaTax');
  if(taxFed <= 0 || taxCa <= 0) {
    Browser.msgBox('Error', 'Pay your fair share. Enter some taxes.', Browser.Buttons.OK);
    return 0;
  }

  // dates
  // very basic sanity on pay period
  var begin = getNamedValue('TempPeriodBegin');
  var end = getNamedValue('TempPeriodEnd');
  if(end < begin) {
    Browser.msgBox('Error', 'Pay period looks funky.', Browser.Buttons.OK);
    return 0;
  }

  // warn on duplicate payroll
  var payDate = getNamedValue('TempPayDate');
  var sheetName = Utilities.formatDate(payDate, "PST", "MM/dd/yyyy");
  var paystubSheet = SpreadsheetApp.getActive().getSheetByName(sheetName);
  if (paystubSheet) {
    var resp = Browser.msgBox('Do Over?', 'You already have a paycheck for this date -- are you sure you want to overwrite it?', Browser.Buttons.YES_NO);
    if(resp == 'no') {
       return 0;
    }
  }

  return 1;
}

function deletePayroll() {
  // prompt for the date
  var strDel = Browser.inputBox('Delete Payroll', 'Please enter the date of the paystub to remove (mm/dd/yyyy):', Browser.Buttons.OK_CANCEL);
  if (strDel == 'cancel') {
    return;
  }

  // search for sheet and confirm deletion
  var spreadsheet = SpreadsheetApp.getActive();
  var deleteSheet = spreadsheet.getSheetByName(strDel);
  if(deleteSheet) {
    var resp = Browser.msgBox('Are you sure?', Utilities.formatString("Located the payroll for %s -- continue with deletion?", strDel), Browser.Buttons.YES_NO);
    if(resp == 'no') {
       return;
    }
  } else {
    Browser.msgBox('Error', Utilities.formatString("Couldn't find a paystub for %s. Nothing to delete. Hint: make sure you are using the form '01/09/2017' rather than '1/9/17'.", strDel), Browser.Buttons.OK);
    //todo: make this friendier
    return;
  }

  // Subtract from YTD sheet
  removePayrollFromYTD(deleteSheet);

  // Delete tab and return to template
  spreadsheet.deleteSheet(deleteSheet);
  SpreadsheetApp.flush();
  spreadsheet.getSheetByName('Template').activate();

  // todo: is it possible to trap the Delete Sheet action from UI and trigger this function? or at least ask if we should adjust YTD before deleting
}

function rebuildYTD() {
  // todo:
  // copy current YTD to backup column or sheet
  // zero out current YTD values
  // cycle through all paystubs to sum new values
  Browser.msgBox('Payroll', "Haven't gotten around to this feature yet...", Browser.Buttons.OK);
}

function updateYTDFromCurrent() {
  incrementNamedValue('YTDFedTax', getNamedValue('CurFedTax'));
  incrementNamedValue('YTDSocSec', getNamedValue('CurSocSec'));
  incrementNamedValue('YTDMedicare', getNamedValue('CurMedicare'));
  incrementNamedValue('YTDCaTax', getNamedValue('CurCaTax'));
  incrementNamedValue('YTDCaSdi', getNamedValue('CurCaSdi'));
  incrementNamedValue('YTDWagesReg', getNamedValue('CurWagesReg'));
  incrementNamedValue('YTDWagesOT', getNamedValue('CurWagesOT'));
}

function cleanup() {
  clearNamedValue('TempHoursReg');
  clearNamedValue('TempHoursOT');
  clearNamedValue('TempFedTax');
  clearNamedValue('TempCaTax');
/*
  clearNamedValue('TempPeriodBegin');
  clearNamedValue('TempPeriodEnd');
  clearNamedValue('TempPayDate');
*/
}

function getNamedValue(valueName) {
  var nr = SpreadsheetApp.getActiveSpreadsheet().getRangeByName(valueName);
  return nr.getValue();
}

function incrementNamedValue(valueName, valueToAdd) {
  var nr = SpreadsheetApp.getActiveSpreadsheet().getRangeByName(valueName);
  nr.setValue(nr.getValue() + valueToAdd);
}

function clearNamedValue(valueName) {
  var nr = SpreadsheetApp.getActiveSpreadsheet().getRangeByName(valueName);
  if(nr) {
    nr.clearContent();
  }
}

function removePayrollFromYTD(payrollSheet) {
  // note: this will be fragile, we don't have named ranges for the individual payroll sheets so it's using specific cell IDs instead
  var wagesReg = payrollSheet.getRange('E30');
  incrementNamedValue('YTDWagesReg', -wagesReg.getValue());

  var wagesOT = payrollSheet.getRange('E31');
  incrementNamedValue('YTDWagesOT', -wagesOT.getValue());

  var fedTax = payrollSheet.getRange('E38');
  incrementNamedValue('YTDFedTax', -fedTax.getValue());

  var caTax = payrollSheet.getRange('E41');
  incrementNamedValue('YTDCaTax', -caTax.getValue());

  var caSdi = payrollSheet.getRange('E42');
  incrementNamedValue('YTDCaSdi', -caSdi.getValue());

  var socSec = payrollSheet.getRange('E39');
  incrementNamedValue('YTDSocSec', -socSec.getValue());

  var medicare = payrollSheet.getRange('E40');
  incrementNamedValue('YTDMedicare', -medicare.getValue());
}

function dumpLog() {
  var logSheet = SpreadsheetApp.getActive().getSheetByName('devlog');
  if(!logSheet) {
    logSheet = SpreadsheetApp.getActive().insertSheet('devlog', 0);
  }

  var logData = Logger.getLog();
  var a1 = logSheet.getRange(1,1);
  a1.setValue(logData);
}
</code>```
```<code>
</code>```

Body:
So I am working on a project where I am using Google Sheets to create a new sheet for payroll each time I hit "run payroll" the issue now is I want it to have it become a PDF and go into a specific folder and then email it out.

I found the first part then tried to do it with zapier but its not working as its creating the entire sheet as a PDF not the new one.

// Add menu items.
function onOpen() {
  var spreadsheet = SpreadsheetApp.getActive();
  var menuItems = [
    {name: 'Run Payroll', functionName: 'runPayroll'},
    {name: 'Delete Paystub', functionName: 'deletePayroll'},
    {name: 'Rebuild YTD from Stubs', functionName: 'rebuildYTD'}
  ];
  spreadsheet.addMenu('Payroll', menuItems);
}

function runPayroll() {
  var spreadsheet = SpreadsheetApp.getActive();
  var templateSheet = spreadsheet.getSheetByName('Template');

  // Validate weekly input
  if(!validateInput()) {
    return;
  }

  // Create new sheet for pay date
  var sheetName = Utilities.formatDate(getNamedValue('TempPayDate'), "PST", "MM/dd/yyyy");
  var paystubSheet = spreadsheet.getSheetByName(sheetName);
  if (paystubSheet) {
    // we already have a paystub for this date. remove that stub's values from YTD before we create a new one.
    removePayrollFromYTD(paystubSheet);
    paystubSheet.clear();
    SpreadsheetApp.flush();  // ran into a race issue here with YTD not getting updated fast enough for the new stub creation -- flush() seems to fix it
  } else {
    paystubSheet = spreadsheet.insertSheet(sheetName, spreadsheet.getNumSheets());
  }

  // Copy pay data from Template to new sheet
  var dataRange = templateSheet.getRange(1, 1, 45, 6);
  dataRange.copyValuesToRange(paystubSheet, 1, 6, 1, 45);
  dataRange.copyFormatToRange(paystubSheet, 1, 6, 1, 45);
  paystubSheet.setRowHeight(1, 10);
  paystubSheet.setRowHeight(2, 10);
  paystubSheet.setRowHeight(43, 10);
  paystubSheet.setRowHeight(44, 10);

  // Update YTD sheet. Grab current values from the template before we clean it up
  updateYTDFromCurrent();

  // Reset template data
  cleanup();

  // Activate new paystub and pre-set selection for printing
  paystubSheet.activate();
  paystubSheet.setActiveSelection(paystubSheet.getRange(1, 1, 45, 6));

//  Logger.log(sheetName);
//  dumpLog();
}

function validateInput() {
  // hours
  var hrsReg = getNamedValue('TempHoursReg');
  var hrsOT = getNamedValue('TempHoursOT');
  if(hrsReg + hrsOT <= 0) {
    Browser.msgBox('Error', 'Work harder. Enter some hours.', Browser.Buttons.OK);
    return 0;
  }

  // taxes
  var taxFed = getNamedValue('TempFedTax');
  var taxCa = getNamedValue('TempCaTax');
  if(taxFed <= 0 || taxCa <= 0) {
    Browser.msgBox('Error', 'Pay your fair share. Enter some taxes.', Browser.Buttons.OK);
    return 0;
  }

  // dates
  // very basic sanity on pay period
  var begin = getNamedValue('TempPeriodBegin');
  var end = getNamedValue('TempPeriodEnd');
  if(end < begin) {
    Browser.msgBox('Error', 'Pay period looks funky.', Browser.Buttons.OK);
    return 0;
  }

  // warn on duplicate payroll
  var payDate = getNamedValue('TempPayDate');
  var sheetName = Utilities.formatDate(payDate, "PST", "MM/dd/yyyy");
  var paystubSheet = SpreadsheetApp.getActive().getSheetByName(sheetName);
  if (paystubSheet) {
    var resp = Browser.msgBox('Do Over?', 'You already have a paycheck for this date -- are you sure you want to overwrite it?', Browser.Buttons.YES_NO);
    if(resp == 'no') {
       return 0;
    }
  }

  return 1;
}

function deletePayroll() {
  // prompt for the date
  var strDel = Browser.inputBox('Delete Payroll', 'Please enter the date of the paystub to remove (mm/dd/yyyy):', Browser.Buttons.OK_CANCEL);
  if (strDel == 'cancel') {
    return;
  }

  // search for sheet and confirm deletion
  var spreadsheet = SpreadsheetApp.getActive();
  var deleteSheet = spreadsheet.getSheetByName(strDel);
  if(deleteSheet) {
    var resp = Browser.msgBox('Are you sure?', Utilities.formatString("Located the payroll for %s -- continue with deletion?", strDel), Browser.Buttons.YES_NO);
    if(resp == 'no') {
       return;
    }
  } else {
    Browser.msgBox('Error', Utilities.formatString("Couldn't find a paystub for %s. Nothing to delete. Hint: make sure you are using the form '01/09/2017' rather than '1/9/17'.", strDel), Browser.Buttons.OK);
    //todo: make this friendier
    return;
  }

  // Subtract from YTD sheet
  removePayrollFromYTD(deleteSheet);

  // Delete tab and return to template
  spreadsheet.deleteSheet(deleteSheet);
  SpreadsheetApp.flush();
  spreadsheet.getSheetByName('Template').activate();

  // todo: is it possible to trap the Delete Sheet action from UI and trigger this function? or at least ask if we should adjust YTD before deleting
}

function rebuildYTD() {
  // todo:
  // copy current YTD to backup column or sheet
  // zero out current YTD values
  // cycle through all paystubs to sum new values
  Browser.msgBox('Payroll', "Haven't gotten around to this feature yet...", Browser.Buttons.OK);
}

function updateYTDFromCurrent() {
  incrementNamedValue('YTDFedTax', getNamedValue('CurFedTax'));
  incrementNamedValue('YTDSocSec', getNamedValue('CurSocSec'));
  incrementNamedValue('YTDMedicare', getNamedValue('CurMedicare'));
  incrementNamedValue('YTDCaTax', getNamedValue('CurCaTax'));
  incrementNamedValue('YTDCaSdi', getNamedValue('CurCaSdi'));
  incrementNamedValue('YTDWagesReg', getNamedValue('CurWagesReg'));
  incrementNamedValue('YTDWagesOT', getNamedValue('CurWagesOT'));
}

function cleanup() {
  clearNamedValue('TempHoursReg');
  clearNamedValue('TempHoursOT');
  clearNamedValue('TempFedTax');
  clearNamedValue('TempCaTax');
/*
  clearNamedValue('TempPeriodBegin');
  clearNamedValue('TempPeriodEnd');
  clearNamedValue('TempPayDate');
*/
}

function getNamedValue(valueName) {
  var nr = SpreadsheetApp.getActiveSpreadsheet().getRangeByName(valueName);
  return nr.getValue();
}

function incrementNamedValue(valueName, valueToAdd) {
  var nr = SpreadsheetApp.getActiveSpreadsheet().getRangeByName(valueName);
  nr.setValue(nr.getValue() + valueToAdd);
}

function clearNamedValue(valueName) {
  var nr = SpreadsheetApp.getActiveSpreadsheet().getRangeByName(valueName);
  if(nr) {
    nr.clearContent();
  }
}

function removePayrollFromYTD(payrollSheet) {
  // note: this will be fragile, we don't have named ranges for the individual payroll sheets so it's using specific cell IDs instead
  var wagesReg = payrollSheet.getRange('E30');
  incrementNamedValue('YTDWagesReg', -wagesReg.getValue());

  var wagesOT = payrollSheet.getRange('E31');
  incrementNamedValue('YTDWagesOT', -wagesOT.getValue());

  var fedTax = payrollSheet.getRange('E38');
  incrementNamedValue('YTDFedTax', -fedTax.getValue());

  var caTax = payrollSheet.getRange('E41');
  incrementNamedValue('YTDCaTax', -caTax.getValue());

  var caSdi = payrollSheet.getRange('E42');
  incrementNamedValue('YTDCaSdi', -caSdi.getValue());

  var socSec = payrollSheet.getRange('E39');
  incrementNamedValue('YTDSocSec', -socSec.getValue());

  var medicare = payrollSheet.getRange('E40');
  incrementNamedValue('YTDMedicare', -medicare.getValue());
}

function dumpLog() {
  var logSheet = SpreadsheetApp.getActive().getSheetByName('devlog');
  if(!logSheet) {
    logSheet = SpreadsheetApp.getActive().insertSheet('devlog', 0);
  }

  var logData = Logger.getLog();
  var a1 = logSheet.getRange(1,1);
  a1.setValue(logData);
}


问:
Navigate back with Compose in Fragment with NavGraph
I need to go back from RegisterUserScreen to Login

```<code>class RegisterUser : Fragment() {
    private val viewModel: RegistrationViewModel by viewModels()

    @SuppressLint("InflateParams")
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View {

        return ComposeView(requireContext()).apply {
            setContent {
                RegisterScreen(viewModel, this@RegisterUser)
            }
        }
    }
}
</code>```

In RegisterScreen I have Icon with clickable property:

```<code>   Icon(
        painter = painterResource(id = R.drawable.ic_baseline_arrow_back_24),
        modifier = Modifier
            .align(Alignment.Start)
            .width(40.dp)
            .height(30.dp)
            .clickable { findNavController(registerUserFragment).navigate(R.id.action_registerUser_to_logIn) },
        contentDescription = stringResource(id = R.string.register_user_button_back)
    )
</code>```

Problem is when I click on it nothing happens.

EDIT:

Failed to open APK
'/data/app/~~Jg0TKmfn-xZKpM84xgQqlw==/android.tvz.hr.fitnessclienttracker-DRhW5UElzP1jmYnzMDYMpQ==/base.apk':
I/O error 2022-12-22 20:37:16.666   742-742   ndroid.systemu

pid-742                              E  Failed to open APK
'/data/app/~~Jg0TKmfn-xZKpM84xgQqlw==/android.tvz.hr.fitnessclienttracker-DRhW5UElzP1jmYnzMDYMpQ==/base.apk':
I/O error 2022-12-22 20:37:16.667   742-742   ResourcesManager

pid-742                              E  failed to add asset path
'/data/app/~~Jg0TKmfn-xZKpM84xgQqlw==/android.tvz.hr.fitnessclienttracker-DRhW5UElzP1jmYnzMDYMpQ==/base.apk'
java.io.IOException: Failed to load asset path
/data/app/~~Jg0TKmfn-xZKpM84xgQqlw==/android.tvz.hr.fitnessclienttracker-DRhW5UElzP1jmYnzMDYMpQ==/base.apk

Body:
I need to go back from RegisterUserScreen to Login

class RegisterUser : Fragment() {
    private val viewModel: RegistrationViewModel by viewModels()

    @SuppressLint("InflateParams")
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View {

        return ComposeView(requireContext()).apply {
            setContent {
                RegisterScreen(viewModel, this@RegisterUser)
            }
        }
    }
}

In RegisterScreen I have Icon with clickable property:

   Icon(
        painter = painterResource(id = R.drawable.ic_baseline_arrow_back_24),
        modifier = Modifier
            .align(Alignment.Start)
            .width(40.dp)
            .height(30.dp)
            .clickable { findNavController(registerUserFragment).navigate(R.id.action_registerUser_to_logIn) },
        contentDescription = stringResource(id = R.string.register_user_button_back)
    )

Problem is when I click on it nothing happens.

EDIT:

Failed to open APK
'/data/app/~~Jg0TKmfn-xZKpM84xgQqlw==/android.tvz.hr.fitnessclienttracker-DRhW5UElzP1jmYnzMDYMpQ==/base.apk':
I/O error 2022-12-22 20:37:16.666   742-742   ndroid.systemu

pid-742                              E  Failed to open APK
'/data/app/~~Jg0TKmfn-xZKpM84xgQqlw==/android.tvz.hr.fitnessclienttracker-DRhW5UElzP1jmYnzMDYMpQ==/base.apk':
I/O error 2022-12-22 20:37:16.667   742-742   ResourcesManager

pid-742                              E  failed to add asset path
'/data/app/~~Jg0TKmfn-xZKpM84xgQqlw==/android.tvz.hr.fitnessclienttracker-DRhW5UElzP1jmYnzMDYMpQ==/base.apk'
java.io.IOException: Failed to load asset path
/data/app/~~Jg0TKmfn-xZKpM84xgQqlw==/android.tvz.hr.fitnessclienttracker-DRhW5UElzP1jmYnzMDYMpQ==/base.apk


问:
How to reference the initial value of property without being affected by subsequent value changes of said property?
I have a User class with a one-many relationship with two other classes, InterestRate and Loan respectively. I would like for a specific loan to inherit the initial interestRate value of a user when a new loan is created but retain that value even if the user's initial interestRate value changes.

When I try assigning the value of the user's interestRate to a new loan like so,

```<code>    public async Task<LoanRequest> AddLoanRequest(LoanRequestForCreationDto field)
    {
        var data = new LoanRequest
        {
            LoanAmount = field.LoanAmount,
            LoanTenure = field.LoanTenure,
            AppUserId = field.AppUserId,
            InterestRate = AppUser.InterestRate
        };

        await context.LoanRequests.AddAsync(data);
        await context.SaveChangesAsync();
        return data;
    }
</code>```

I get the object reference error.

Although I am able to update the user's interest rate using the following code:

```<code>public async Task<AppUser> UpdateUserInterestRate(UserInterestForUpdateDto field)
{
    var dataFromRepo = await context.Users.Include(x => x.PreviousInterestRates).FirstOrDefaultAsync(i => i.Id == field.AppUserId);

    var data = new InterestRate
    {
        AppUserId = field.AppUserId,
        Rate = dataFromRepo.InterestRate
    };
    await context.InterestRates.AddAsync(data);

    dataFromRepo.InterestRate = field.NewInterestRates;
    await context.SaveChangesAsync();
    return dataFromRepo;
}
</code>```

The interestRate on the loan is not affected. I am aware that I could hardcode the desired interestRate of the user to the loan using

```<code>InterestRate = field.InterestRate
</code>```

but I would like for the system to be dynamic.

Body:
I have a User class with a one-many relationship with two other classes, InterestRate and Loan respectively. I would like for a specific loan to inherit the initial interestRate value of a user when a new loan is created but retain that value even if the user's initial interestRate value changes.

When I try assigning the value of the user's interestRate to a new loan like so,

    public async Task<LoanRequest> AddLoanRequest(LoanRequestForCreationDto field)
    {
        var data = new LoanRequest
        {
            LoanAmount = field.LoanAmount,
            LoanTenure = field.LoanTenure,
            AppUserId = field.AppUserId,
            InterestRate = AppUser.InterestRate
        };

        await context.LoanRequests.AddAsync(data);
        await context.SaveChangesAsync();
        return data;
    }

I get the object reference error.

Although I am able to update the user's interest rate using the following code:

public async Task<AppUser> UpdateUserInterestRate(UserInterestForUpdateDto field)
{
    var dataFromRepo = await context.Users.Include(x => x.PreviousInterestRates).FirstOrDefaultAsync(i => i.Id == field.AppUserId);

    var data = new InterestRate
    {
        AppUserId = field.AppUserId,
        Rate = dataFromRepo.InterestRate
    };
    await context.InterestRates.AddAsync(data);

    dataFromRepo.InterestRate = field.NewInterestRates;
    await context.SaveChangesAsync();
    return dataFromRepo;
}

The interestRate on the loan is not affected. I am aware that I could hardcode the desired interestRate of the user to the loan using

InterestRate = field.InterestRate

but I would like for the system to be dynamic.


问:
Uri from Filepath returns false EncodedPath
I have a Uri of a File that the User can pick with a FilePicker.
I can make an intent with this Uri and Google Sheets opens the file successfully.

I now get the Path of the pickedUri and create a new Uri with it and try to open it. This does not work.

If I compare the paths of the URIs, they are identical but if I compare the encoded Paths then they don't match.

```<code>filepath = pickedUri.getPath();
Uri testUri = Uri.fromFile(new File(filepath));
</code>```

and

```<code>filepath = pickedUri.getPath();
Uri testUri = Uri.parse("file://" + filepath);
</code>```

Body:
I have a Uri of a File that the User can pick with a FilePicker.
I can make an intent with this Uri and Google Sheets opens the file successfully.

I now get the Path of the pickedUri and create a new Uri with it and try to open it. This does not work.

If I compare the paths of the URIs, they are identical but if I compare the encoded Paths then they don't match.

filepath = pickedUri.getPath();
Uri testUri = Uri.fromFile(new File(filepath));

and

filepath = pickedUri.getPath();
Uri testUri = Uri.parse("file://" + filepath);


问:
Auto Filter out Rows as soon as data is entered
I'm trying to create a google sheet where it automatically filters out the row as soon as a specific column has data input.

For example I have 5 columns but as soon as I enter a data in a cell under column #5 it would automatically filter out the entire row where the cell is.

Is this possible with a formula?

Thanks,


问:
How do I fix "object loglik not found" error when using glmmLasso for model selection?
I am using glmmlasso for model selection. I get to a point where I try to implement my tuned lambda only to get the error:

Error in logLik.glmmLasso(y = y, yhelp = yhelp, mu = mu, family = family,  :
object 'loglik' not found

I have searched but found no solution and am honestly not even sure what this error means.

image of what my data looks like before scaling
BB3[,c(6,16,20,24,28,29,32:38)]<-scale(BB3[,c(6,16,20,24,28,29,32:38)],center=T,scale=T)
After centering and scaling

Below is the code I was using:

```<code>BB3<-data.frame(BB3)

lambda <- seq(500,0,by=-5)

family <- inverse.gaussian(link = "1/mu^2")

ID <- as.factor(BB3$ID)

BIC_vec<-rep(Inf,length(lambda))

PQL<-glmmPQL(BBSDI~1,random = ~1|ID,family=family,data=BB3)
Delta.start<-c(as.numeric(PQL$coef$fixed),rep(0,11),as.numeric(t(PQL$coef$random$ID)))
Q.start<-as.numeric(VarCorr(PQL)[1,1])

j<- -1
for(j in 1:length(BIC_vec))
{
  print(paste("Iteration ", j,sep=""))

  glm1 <- try(glmmLasso(BBSDI~AvgTemp
                        + AvgJulianDate + AvgCloud
                        + AvgBeaufort + TreeCover + PropObsBV + as.factor(Quality) + NH + HHSDI + PCNum, rnd = list(ID=~1),
                        family = family, data = BB3, lambda=lambda[j],switch.NR=FALSE,final.re=FALSE), silent=TRUE)

  if(!inherits(glm1, "try-error"))
  {
    BIC_vec[j]<-glm1$bic
    Coeff_ma<-cbind(Coeff_ma,glm1$coefficients)

    #save error (deviance) values
    y.hat<-predict(glm1,BB3)
    Devianz_ma[j]<-sum(family$dev.resids(BB3I$BBSDI,y.hat,wt=rep(1,length(y.hat))))

  }

}
opt<-which.min(BIC_vec)

glm1_Final <- glmmLasso(BBSDI~AvgTemp
                            + AvgJulianDate + AvgCloud
                            + AvgBeaufort + TreeCover + PropObsBV + as.factor(Quality) + NH + HHSDI + PCNum, rnd = list(ID=~1),
                            family = family, data = BB3, lambda=lambda[opt], switch.NR=FALSE,final.re=FALSE,
                            control=list(start=Delta.start,q_start=Q.start))
```
`

Here is where I get the error, which I can't even figure out the meaning of.
```

Body:
I am using glmmlasso for model selection. I get to a point where I try to implement my tuned lambda only to get the error:

Error in logLik.glmmLasso(y = y, yhelp = yhelp, mu = mu, family = family,  :
object 'loglik' not found

I have searched but found no solution and am honestly not even sure what this error means.

image of what my data looks like before scaling
BB3[,c(6,16,20,24,28,29,32:38)]<-scale(BB3[,c(6,16,20,24,28,29,32:38)],center=T,scale=T)
After centering and scaling

Below is the code I was using:

BB3<-data.frame(BB3)

lambda <- seq(500,0,by=-5)

family <- inverse.gaussian(link = "1/mu^2")

ID <- as.factor(BB3$ID)

BIC_vec<-rep(Inf,length(lambda))

PQL<-glmmPQL(BBSDI~1,random = ~1|ID,family=family,data=BB3)
Delta.start<-c(as.numeric(PQL$coef$fixed),rep(0,11),as.numeric(t(PQL$coef$random$ID)))
Q.start<-as.numeric(VarCorr(PQL)[1,1])

j<- -1
for(j in 1:length(BIC_vec))
{
  print(paste("Iteration ", j,sep=""))

  glm1 <- try(glmmLasso(BBSDI~AvgTemp
                        + AvgJulianDate + AvgCloud
                        + AvgBeaufort + TreeCover + PropObsBV + as.factor(Quality) + NH + HHSDI + PCNum, rnd = list(ID=~1),
                        family = family, data = BB3, lambda=lambda[j],switch.NR=FALSE,final.re=FALSE), silent=TRUE)

  if(!inherits(glm1, "try-error"))
  {
    BIC_vec[j]<-glm1$bic
    Coeff_ma<-cbind(Coeff_ma,glm1$coefficients)

    #save error (deviance) values
    y.hat<-predict(glm1,BB3)
    Devianz_ma[j]<-sum(family$dev.resids(BB3I$BBSDI,y.hat,wt=rep(1,length(y.hat))))

  }

}
opt<-which.min(BIC_vec)

glm1_Final <- glmmLasso(BBSDI~AvgTemp
                            + AvgJulianDate + AvgCloud
                            + AvgBeaufort + TreeCover + PropObsBV + as.factor(Quality) + NH + HHSDI + PCNum, rnd = list(ID=~1),
                            family = family, data = BB3, lambda=lambda[opt], switch.NR=FALSE,final.re=FALSE,
                            control=list(start=Delta.start,q_start=Q.start))
```
`

Here is where I get the error, which I can't even figure out the meaning of.


问:
Why is my WebRTC data channel stuck on connecting?
I have been stuck for the past week debugging this problem and it just isn't working. I am currently working on a Firebase and WebRTC project and I can't get my data channel to transmit messages from one peer to another. The readyState of the data channel is always "connecting".

Client code:

```<code>const pc: RTCPeerConnection = new RTCPeerConnection(servers);
let sendChannel = null;
pc.ondatachannel = (e) => {
  console.log("data channel activated");
  sendChannel = e.channel;
  sendChannel.onmessage = handleRecieveMessage;
};
</code>```

Host code:

```<code>const channel = pc.createDataChannel("sendChannel", { ordered: true });

channel.binaryType = "arraybuffer";
channel.addEventListener("open", () => {
  console.log("local channel open");
  channel.send("hello world!")
});
</code>```

Also, I have a function in the host code that checks the readyState of the channel and it always returns "connecting".

I have tried numerous tutorials and also have tried this StackOverflow question that has the same problem that I have but the answers did not fix my problem.

All I want to do is to send a message from one "host" peer to another "client" peer. The "host" peer should NOT recieve messages and the "client" peer should NOT send messages.

Any help?

Thanks in advance!

Body:
I have been stuck for the past week debugging this problem and it just isn't working. I am currently working on a Firebase and WebRTC project and I can't get my data channel to transmit messages from one peer to another. The readyState of the data channel is always "connecting".

Client code:

const pc: RTCPeerConnection = new RTCPeerConnection(servers);
let sendChannel = null;
pc.ondatachannel = (e) => {
  console.log("data channel activated");
  sendChannel = e.channel;
  sendChannel.onmessage = handleRecieveMessage;
};

Host code:

const channel = pc.createDataChannel("sendChannel", { ordered: true });

channel.binaryType = "arraybuffer";
channel.addEventListener("open", () => {
  console.log("local channel open");
  channel.send("hello world!")
});

Also, I have a function in the host code that checks the readyState of the channel and it always returns "connecting".

I have tried numerous tutorials and also have tried this StackOverflow question that has the same problem that I have but the answers did not fix my problem.

All I want to do is to send a message from one "host" peer to another "client" peer. The "host" peer should NOT recieve messages and the "client" peer should NOT send messages.

Any help?

Thanks in advance!


问:
API Rest, MongoDB Atlas, NodeJS, Express: Validator error, data is not send
So when I click Send Request a get this error of 'ValidatorError' 'Path email is required'

Response

So I deleted the { required: true } I have put mongoose.Schema and that error dissapear, but instead of the error I just get _id and __v but not the whole data like name, age and email.

`

```<code>{
  "_id": "63a4acbc992b1000285b629e",
  "__v": 0
}
</code>```

`

I also check my MongoDB Atlas and it also just have _id and __v, nothing else.

index.js

```<code>const express = require('express');
const mongoose = require('mongoose');
require('dotenv').config();

const userRoute = require('./routes/user');

const app = express();
const port = process.env.PORT || 9000;

// middleware
app.use(express.json())
app.use('/api', userRoute)

// routes
app.get('/', (req, res) => {
    res.send('Welcome to my API');
});

// mongodb connection

mongoose
    .connect(process.env.MONGODB_URI)
    .then(() => console.log('Connected to MongoDB Atlas'))
    .catch((error) => console.error(error));

app.listen(port, () => console.log('server listening on port', port));

</code>```

routes\user.js

`

```<code>const express = require("express");
const userSchema = require("../models/user");

const router = express.Router();

// Create user route
router.post("/users", (req, res) => {
  // res.send('create user'); // Si funciona manda este mensaje
  const user = userSchema(req.body); // Crea un nuevo usuario (body: información de nombre, edad y email)
  user
    .save()
    .then((data) => res.json(data))
    .catch((error) => res.json({ message: error }));
});

module.exports = router;

</code>```

`

models\user.js

`

```<code>const mongoose = require('mongoose');

const userSchema = mongoose.Schema({
    name: {
        type: String,
    },
    age: {
        type: Number,
    },
    email: {
        type: String,
    }
});

module.exports = mongoose.model('User', userSchema);
</code>```

`

requests.http

`

```<code>###
POST http://localhost:9000/api/users HTTP/1.1

Content-Type: application/json

{
    "name": "Nikola Tesla",
    "age": 83,
    "email": "nikolatesla@gmail.com"
}
</code>```

`

Body:
So when I click Send Request a get this error of 'ValidatorError' 'Path email is required'

Response

So I deleted the { required: true } I have put mongoose.Schema and that error dissapear, but instead of the error I just get _id and __v but not the whole data like name, age and email.

`

{
  "_id": "63a4acbc992b1000285b629e",
  "__v": 0
}

`

I also check my MongoDB Atlas and it also just have _id and __v, nothing else.

index.js

const express = require('express');
const mongoose = require('mongoose');
require('dotenv').config();

const userRoute = require('./routes/user');

const app = express();
const port = process.env.PORT || 9000;

// middleware
app.use(express.json())
app.use('/api', userRoute)

// routes
app.get('/', (req, res) => {
    res.send('Welcome to my API');
});

// mongodb connection

mongoose
    .connect(process.env.MONGODB_URI)
    .then(() => console.log('Connected to MongoDB Atlas'))
    .catch((error) => console.error(error));

app.listen(port, () => console.log('server listening on port', port));

routes\user.js

`

const express = require("express");
const userSchema = require("../models/user");

const router = express.Router();

// Create user route
router.post("/users", (req, res) => {
  // res.send('create user'); // Si funciona manda este mensaje
  const user = userSchema(req.body); // Crea un nuevo usuario (body: información de nombre, edad y email)
  user
    .save()
    .then((data) => res.json(data))
    .catch((error) => res.json({ message: error }));
});

module.exports = router;

`

models\user.js

`

const mongoose = require('mongoose');

const userSchema = mongoose.Schema({
    name: {
        type: String,
    },
    age: {
        type: Number,
    },
    email: {
        type: String,
    }
});

module.exports = mongoose.model('User', userSchema);

`

requests.http

`

###
POST http://localhost:9000/api/users HTTP/1.1

Content-Type: application/json

{
    "name": "Nikola Tesla",
    "age": 83,
    "email": "nikolatesla@gmail.com"
}

`


问:
Can't use multiple render targets. Falling back to two passes. 36054 "angular-forge-viewer-app" using "adsk-forge-viewer"
I encounter a probleme when intergtaing the angular wrapper "adsk-forge-viewer" to my angular app.

i ve tried using node 14 12.


问:
Add CameraCollisionHandler to my 3rd person controller (Unity)
I'm new to the world of Game Design and Unity and while following a tutorial I ran into this issue where my camera does not stay at the proper height and drops bellow 0 on the y axis.

My guess is it has something to do with when I set its position I'm overwriting the old one (Including the Y Coordinate).

All feedback is greatly appreciated!

    using UnityEngine;

    public class CameraManager : MonoBehaviour
    {
        InputManager inputManager;

        public Transform targetTransform;   //Target Object to be Followed...
        public Transform cameraTransform;   //Transform of the camera object.
        public Transform cameraPivot;       //Object used to pivot.

        private float defaultPosition;
        private Vector3 cameraFollowVelocity = Vector3.zero;
        private Vector3 cameraVectorPosition;

        public LayerMask collisionLayers; //Layers Camera can collide with.

        public float cameraCollisionRadius = 0.2f;
        public float cameraCollisionOffset = 0.2f; //Offset camera should have when colliding with the env...
        public float minCollisionOffSet = 0.2f;

        public float cameraFollowSpeed = 0.2f;
        public float cameraLookSpeed = 2;
        public float cameraPivotSpeed = 2;

        public float lookAngle; // Left + Right
        public float pivotAngle; // Up + Down
        public float minPivotAngle = -35;
        public float maxPivotAngle = 35;

        private void Awake()
        {
            inputManager = FindObjectOfType<InputManager>();
            targetTransform = FindObjectOfType<PlayerManager>().transform;

            cameraTransform = Camera.main.transform;
            defaultPosition = cameraTransform.localPosition.z;
        }

        private void FollowTarget() {
            Vector3 targetPos = Vector3.SmoothDamp
                (transform.position, targetTransform.position, ref cameraFollowVelocity, cameraFollowSpeed);

            transform.position = targetPos;

        }

        private void RotateCamera() {

            Vector3 rotation;
            Quaternion targetRotation;

            lookAngle = lookAngle + (inputManager.cameraInputX * cameraLookSpeed);
            pivotAngle = pivotAngle - (inputManager.cameraInputY * cameraPivotSpeed);
            pivotAngle = Mathf.Clamp(pivotAngle, minPivotAngle, maxPivotAngle);

            rotation = Vector3.zero;
            rotation.y = lookAngle;
            targetRotation = Quaternion.Euler(rotation);
            transform.rotation = targetRotation;

            rotation = Vector3.zero;
            rotation.x = pivotAngle;
            targetRotation = Quaternion.Euler(rotation);
            cameraPivot.localRotation = targetRotation;
        }

        private void HandleCameraCollision()
        {
            float targetPosition = defaultPosition;
            RaycastHit hit;
            Vector3 direction = cameraTransform.position - cameraPivot.position;
            direction.Normalize();

            if (Physics.SphereCast
                    (cameraPivot.transform.position, cameraCollisionRadius, direction, out hit, Mathf.Abs(targetPosition), collisionLayers))
            {
                float distance = Vector3.Distance(cameraPivot.position, hit.point);
                targetPosition = -(distance - cameraCollisionOffset);
            }

            if (Mathf.Abs(targetPosition) < minCollisionOffSet)
            {
                targetPosition = targetPosition - minCollisionOffSet;
            }

            cameraVectorPosition.z = Mathf.Lerp(cameraTransform.localPosition.z, targetPosition, 0.2f);
            cameraTransform.localPosition = cameraVectorPosition;
            //cameraTransform.localPosition.Set(cameraVectorPosition);
        }

        public void HandleAllCameraMovement() {
            FollowTarget();
            RotateCamera();
            HandleCameraCollision();
        }

    }
```


问:
Why can't Typescript find an imported type from a .svelte file?
Typescript reports the following error: Cannot find module './App.svelte' or its corresponding type declarations. ts(2307) when trying to import a type from a .svelte file like:

import type { User } from './App.svelte';
```
<p>My <code>App.svelte</code> file:</p>
<pre class="lang-html prettyprint-override"><code><script context="module" lang="ts">
  export type User = {
    name?: string
    id: string;
  }

...
</script>

<script lang="ts">
...
</script>
</code>```

My tsconfig file is pretty standard:

{
  "extends": "@tsconfig/svelte/tsconfig.json",
  "compilerOptions": {
    "target": "ESNext",
    "useDefineForClassFields": true,
    "module": "ESNext",
    "resolveJsonModule": true,
    /**
     * Typecheck JS in `.svelte` and `.js` files by default.
     * Disable checkJs if you'd like to use dynamic types in JS.
     * Note that setting allowJs false does not prevent the use
     * of JS in `.svelte` files.
     */
    "allowJs": true,
    "checkJs": true,
    "isolatedModules": true,
    "paths": {
      "src/*": ["src/*"],
    }
  },
  "include": ["src/**/*.d.ts", "src/**/*.ts", "src/**/*.js", "src/**/*.svelte"],
  "references": [{ "path": "./tsconfig.node.json" }]
}
```

I would expect to import a type from App.svelte without any error. I've added different variations of "types" in tsconfig without any success: "types": ["svelte"]

I've tried changing vite.config.js and svelte.config.js to no success.

It seems like the TS compiler doesn't recognize .svelte files, but I get the expected linting whenever I edit a .svelte file.

Restarting VS code has no effect.

Body:
Typescript reports the following error: Cannot find module './App.svelte' or its corresponding type declarations. ts(2307) when trying to import a type from a .svelte file like:

import type { User } from './App.svelte';

My App.svelte file:

My tsconfig file is pretty standard:

{
  "extends": "@tsconfig/svelte/tsconfig.json",
  "compilerOptions": {
    "target": "ESNext",
    "useDefineForClassFields": true,
    "module": "ESNext",
    "resolveJsonModule": true,
    /**
     * Typecheck JS in `.svelte` and `.js` files by default.
     * Disable checkJs if you'd like to use dynamic types in JS.
     * Note that setting allowJs false does not prevent the use
     * of JS in `.svelte` files.
     */
    "allowJs": true,
    "checkJs": true,
    "isolatedModules": true,
    "paths": {
      "src/*": ["src/*"],
    }
  },
  "include": ["src/**/*.d.ts", "src/**/*.ts", "src/**/*.js", "src/**/*.svelte"],
  "references": [{ "path": "./tsconfig.node.json" }]
}

I would expect to import a type from App.svelte without any error. I've added different variations of "types" in tsconfig without any success: "types": ["svelte"]

I've tried changing vite.config.js and svelte.config.js to no success.

It seems like the TS compiler doesn't recognize .svelte files, but I get the expected linting whenever I edit a .svelte file.

Restarting VS code has no effect.


问:
Count measure with filters not grouping properly
Background: Here is the data I am using for the Power BI visualization. You may also be able to view this link and download the excel file from replit. https://replit.com/join/tzsvuaqktb-iamyolanda

I am attempting to analyze metrics by date. In this case, the sum of the fruits.

Normally I can use a measure and group it by categories in a visualization. For example, you can have a measure = count([column A])  that you group by fruit type.

```<code>Fruit  | count fruits eaten
———————————————-
Banana | 10
Apple  | 5
Peach  | 21
Total  | 36
</code>```

Now my problem is that when I apply filters, it no longer works…

If I filter my measure like this  =CALCULATE(SUM(["Number of Fruits"]), ["Date Eaten"]=DATE(2022,11,20)

Then the table results like this

```<code>Fruit  | count fruits eaten
———————————————-
Banana | 4
Apple  | 4
Peach  | 4
Total  | 4
</code>```

Where 4 is the sum of everything, instead of what was expected

How do I filter my measure and still get it to group properly???

What I tried:
CALCULATE(COUNT("Number of Fruits]), [Date Eaten]=DATE(2022,11,20))

But this measure will not group in my table visualization.

Body:
Background: Here is the data I am using for the Power BI visualization. You may also be able to view this link and download the excel file from replit. https://replit.com/join/tzsvuaqktb-iamyolanda

I am attempting to analyze metrics by date. In this case, the sum of the fruits.

Normally I can use a measure and group it by categories in a visualization. For example, you can have a measure = count([column A])  that you group by fruit type.

Fruit  | count fruits eaten
———————————————-
Banana | 10
Apple  | 5
Peach  | 21
Total  | 36

Now my problem is that when I apply filters, it no longer works…

If I filter my measure like this  =CALCULATE(SUM(["Number of Fruits"]), ["Date Eaten"]=DATE(2022,11,20)

Then the table results like this

Fruit  | count fruits eaten
———————————————-
Banana | 4
Apple  | 4
Peach  | 4
Total  | 4

Where 4 is the sum of everything, instead of what was expected

How do I filter my measure and still get it to group properly???

What I tried:
CALCULATE(COUNT("Number of Fruits]), [Date Eaten]=DATE(2022,11,20))

But this measure will not group in my table visualization.


问:
Problems with GoRouter deeplink paths when app is not deployt under root
I want to host an Flutter Web App under https://www.someDomain.com/someFolder/otherFolder

and create a deeplink like that https://www.someDomain.com/someFolder/otherFolder/showProducts/1

that should also work for smartphones.

In android I define:

```<code>        <intent-filter android:autoVerify="true">
            <action android:name="android.intent.action.VIEW" />
            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />
            <data android:scheme="https" android:host="www.someDomain.com" android:path="/someFolder/otherFolder" />
        </intent-filter>
</code>```

So the deeplink is working for the webapp and the smartphone - BUT I would have to define a GoRoute like that:

```<code>      GoRoute(
        path: "**someFolder/otherFolder/**showProducts/:productID",
        builder: _showProductsDL,
      ),
</code>```

The problem is that a version of the WebApp could also be deployed under other subfolder structures like
https://www.someDomain.com/
or
https://www.someDomain.com/somewhereElse/V2/
or
https://www.someDomain.com/somewhereElse/v3/

Is it somehow possible to handle all by defininig a GoRoute with the path "showProducts/:productID" and ignore the subfolders / remoe them from the path the GoRouter is working with?

Body:
I want to host an Flutter Web App under https://www.someDomain.com/someFolder/otherFolder

and create a deeplink like that https://www.someDomain.com/someFolder/otherFolder/showProducts/1

that should also work for smartphones.

In android I define:

        <intent-filter android:autoVerify="true">
            <action android:name="android.intent.action.VIEW" />
            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />
            <data android:scheme="https" android:host="www.someDomain.com" android:path="/someFolder/otherFolder" />
        </intent-filter>

So the deeplink is working for the webapp and the smartphone - BUT I would have to define a GoRoute like that:

      GoRoute(
        path: "**someFolder/otherFolder/**showProducts/:productID",
        builder: _showProductsDL,
      ),

The problem is that a version of the WebApp could also be deployed under other subfolder structures like
https://www.someDomain.com/
or
https://www.someDomain.com/somewhereElse/V2/
or
https://www.someDomain.com/somewhereElse/v3/

Is it somehow possible to handle all by defininig a GoRoute with the path "showProducts/:productID" and ignore the subfolders / remoe them from the path the GoRouter is working with?


问:
@JsonSubTypes with Generic classes which are in other projects

I have a JSON structure with an Interface "ActionInterface".
This "ActionInterface" is used for different types of Actions (sendEmail, deleteUser...).

I have different kind of Java (Eclipse) projects.
"Shared Project" is my project which can be used in all other projects (like a lib).
In this project I have general ActionTypes, which will be used in all other projects as well.
In other projects I can implement other types of projects, which implements the interface "ActionInterface". "Shared Project" cannot use classes from "Project1, Project2...".

My problem is now how will I annotate the interface?
The interface is part of "SharedProject", but I cannot add classes, which are not part from "SharedProject".

```<code>@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "entityName", defaultImpl = ActionSendWebhook.class)
@JsonSubTypes({
    @Type(value = ActionSendEmail.class, name = "ActionSendEmail"),
    // I cannot add this here !!!! @Type(value = ActionSendWebhook.class, name = "ActionSendWebhook")
})
public interface ActionComponentInterface {
    String getId();
}
</code>```

[![enter image description here][1]][1]

Here is an image about the structure.
[1]: https://i.stack.imgur.com/MZ2Yp.png

Body:
I have a JSON structure with an Interface "ActionInterface".
This "ActionInterface" is used for different types of Actions (sendEmail, deleteUser...).

I have different kind of Java (Eclipse) projects.
"Shared Project" is my project which can be used in all other projects (like a lib).
In this project I have general ActionTypes, which will be used in all other projects as well.
In other projects I can implement other types of projects, which implements the interface "ActionInterface". "Shared Project" cannot use classes from "Project1, Project2...".

My problem is now how will I annotate the interface?
The interface is part of "SharedProject", but I cannot add classes, which are not part from "SharedProject".

@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "entityName", defaultImpl = ActionSendWebhook.class)
@JsonSubTypes({
    @Type(value = ActionSendEmail.class, name = "ActionSendEmail"),
    // I cannot add this here !!!! @Type(value = ActionSendWebhook.class, name = "ActionSendWebhook")
})
public interface ActionComponentInterface {
    String getId();
}

[![enter image description here][1]][1]

Here is an image about the structure.
[1]: https://i.stack.imgur.com/MZ2Yp.png