instruction stringlengths 0 30k ⌀ |
|---|
As the title says, if I change the number of hidden layers in my pytorch neural network to be anything different from the amount of input nodes it returns the error below.
> RuntimeError: mat1 and mat2 shapes cannot be multiplied (380x10 and 2x10)
I think that the architecture is incorrectly coded but I am relatively new to pytorch and neural networks so I can't spot the mistake. Any help is greatly appreciated, I've included the code below
class FCN(nn.Module):
def __init__(self, N_INPUT, N_OUTPUT, N_HIDDEN, N_LAYERS):
super().__init__()
activation = nn.Tanh
self.fcs = nn.Sequential(*[
nn.Linear(N_INPUT, N_HIDDEN),
activation()])
self.fch = nn.Sequential(*[
nn.Sequential(*[
nn.Linear(N_INPUT, N_HIDDEN),
activation()]) for _ in range(N_LAYERS-1)])
self.fce = nn.Linear(N_INPUT, N_HIDDEN)
def forward(self, x):
x = self.fcs(x)
x = self.fch(x)
x = self.fce(x)
return x
torch.manual_seed(123)
pinn = FCN(2, 2, 10, 8)
If the pinn architecture is defined as `pinn = FCN(2, 2, 2, 8)` no errors are returned but neural network does not perform well.
Other information:
- the input is a matrix tensor with a batch size of 380
Please let me know if you need anymore information and thank you! |
I am trying to open a file from the Finder app with my Flutter app. However, the method that is expected to be called when opening a file is never being invoked.
---
I've created a custom file extension for my flutter app and already registered it in the ```Info.plist``` for MacOS. Files of the custom type are already being recognized by the operating system and are displayed with the correct icon. Double clicking one of them opens or focuses my Flutter app.
I have read online that the correct way to listen to opened files on MacOS is to override the ```application(_ application: NSApplication, open urls: [URL])```method of ```FlutterAppDelegate``` in ```AppDelegate.swift```. So far my code looks like this:
```
@NSApplicationMain
class AppDelegate: FlutterAppDelegate {
...
override func application(_ application: NSApplication, open urls: [URL]) {
ApplicationService.shared?.methodChannel.invokeMethod("print", arguments: "Hello World!")
}
...
}
```
But as it seems, the method is never being called. It can't be methodChannel, as it successfully sends a print, when initialized.
I even tried removing all pub libraries from my project in order to see if any of them have an impact on the problem. Is it still possible that there is a Flutter plugin that is consuming the "OpenUrl" Event?
Any help is appreciated! Thanks :) |
The conversion is a bit trickier if you need to convert a null-terminated C character array (a C "string") returned by a legacy C function, to a Go string (which is what I needed to do). Since C arrays do not inherently have a length (C buffer overflows are notorious sources of security issues and bugs), you must manually find the actual 'end' of the C array by finding the location of the first 0 (null) after the C function returns:
bLength = 256 // should be >= the length C function expects
buffer = make([]byte, bLength) // make fixed length byte buffer to pass to C function
someCFunctionThatPutsCharactersIntoBuffer(&buffer[0]) // call the C function, passing address of first byte in buffer
lastPos int = bLength // or lastPos int = len(buffer) - assume buffer is full, possibly without null terminator
for i := range lastPos // C bug may mean buffer is NOT null terminated
if buffer[i] == 0 {
lastPos = i // get true last position
break
}
goStringFromC = string(buffer[:lastPos] // an empty string if lastPos is 0
**NOTE** that if the C function returns, say, a 32-bit float, you would need to import the **binary/encoding** and **math** packages, and after calling the C function use something like:
bits := binary.LittleEndian.Uint32(buffer) // get first first 4 bytes of buffer, assuming x86/x64 architecture
var f float32 = math.Float32frombits(bits) // convert raw bits to float32
The same approach works for other numeric values. |
Render emoji flags on windows |
|flutter|google-fonts| |
I have a ViewPager 2 inside a plannerFragment, which calls 2 fragments: one (localeChoosingFragment) contains a recyclerview for the user to choose a locale, and another to choose places within that locale (localeExploringFragment). A ViewModel (japanGuideViewModel) stores the data (as MutableLiveData), including the int currentLocaleBeingViewed. When the user chooses a locale, this is updated, and an observer in the plannerFragment causes one of the tabs in the PlannerFragment to update with the name of that locale. Clicking that tab the loads the localeExploringFragment for that locale.
When the observer in the plannerFragment is triggered, the tab is updated. This causes the recyclerview in the localeChoosingFragment to reset to the first position. As a workaround I have tried using a Handler to automatically scroll the recyclerview to the correct place (according to the ViewModel) but I am confused and concerned about why this is happening. Before using the ViewPager2, I added both (localeChoosingFragment and localeExploringFragment) to a framelayout manually, and tried show/hide and attach/detach, but had the same problem (the recyclerview resetting to the first position).
Does anyone know why this could be? It seems a small thing, but I am concerned that there is something going on I don't and should know about, especially this early in the project.
The recyclerview is not recreated, and nor is notifyDataSet changed.
That ViewPager 2 is actually part of a fragment that is selected from another ViewPager 2, but I don't think that's what's causing the problem.
I will attach a cleaned up version of my code.
Here is the plannerFragment:
public class PlannerFragment extends Fragment {
Context mContext;
JapanGuideViewModel japanGuideViewModel;
View plannerFragmentView;
ViewPager2 plannerFragmentViewPager2;
TabLayout tabLayout;
public static final String TAG = "JapanGuideTAG";
public PlannerFragment() {
Toast.makeText(mContext, "New Planner Fragment, empty constructor", Toast.LENGTH_SHORT).show();
}
public PlannerFragment(Context mContext, JapanGuideViewModel japanGuideViewModel) {
this.japanGuideViewModel = japanGuideViewModel;
this.mContext = mContext;
Log.d(TAG, "New Planner Fragment, arguments passed");
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "oncreate in planner fragment");
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Log.d(TAG, "oncreateview in planner fragment");
plannerFragmentView = inflater.inflate(R.layout.fragment_planner, container, false);
return plannerFragmentView;
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Log.d(TAG, "onViewCreated in PlannerFragment");
plannerFragmentViewPager2 = plannerFragmentView.findViewById(R.id.plannerFragmentViewPager2);
tabLayout = plannerFragmentView.findViewById(R.id.plannerFragmentTabLayout);
PlannerFragmentViewPager2Adaptor plannerFragmentViewPager2Adaptor = new PlannerFragmentViewPager2Adaptor(getChildFragmentManager(), getLifecycle(), mContext, japanGuideViewModel);
plannerFragmentViewPager2.setAdapter(plannerFragmentViewPager2Adaptor);
plannerFragmentViewPager2.setUserInputEnabled(false);
TabLayoutMediator.TabConfigurationStrategy tabConfigurationStrategy = new TabLayoutMediator.TabConfigurationStrategy() {
@Override
public void onConfigureTab(@NonNull TabLayout.Tab tab, int position) {
Log.d(TAG, "onConfigure in tabConfigurationStrategy");
if (position == 0) {
Log.d(TAG, "Chooser");
tab.setText("Explore Prefectures");
} else if (position == 1) {
tab.setText("Explore Chosen Prefecture");
}
}
};
Log.d(TAG, "attachingTabLayoutMediator");
new TabLayoutMediator(tabLayout, plannerFragmentViewPager2, tabConfigurationStrategy).attach();
Observer dataDownloadedObserver = new Observer() {
@Override
public void onChanged(Object o) {
if (japanGuideViewModel.getDataDownloaded().getValue() > 0) {
Log.d(TAG, "onChanged called in data downloaded observer. Value is " + japanGuideViewModel.getDataDownloaded().getValue());
japanGuideViewModel.getCurrentLocaleBeingViewed().setValue(0);
}
}
};
Observer localeToExploreChangedObserver = new Observer() {
@Override
public void onChanged(Object o) {
Log.d(TAG, "localeChangedObserver in planner fragment");
TabLayout.Tab tab = tabLayout.getTabAt(1);
if (tab != null) {
Log.d(TAG, "the tab is" + tab.getPosition());
// THIS IS WHERE THE PROBLEM OCCURS.
// If this line (setting the text) is removed, the recyclerview in
// localeChoosingFragment does not reset to the first position.
tab.setText(japanGuideViewModel.getLocaleNamesArray().getValue().get(japanGuideViewModel.getCurrentLocaleBeingViewed().getValue()));
}
}
};
japanGuideViewModel.getCurrentLocaleBeingViewed().observe(getViewLifecycleOwner(), localeToExploreChangedObserver);
japanGuideViewModel.getDataDownloaded().observe(getViewLifecycleOwner(), dataDownloadedObserver);
} //onViewCreated
public class PlannerFragmentViewPager2Adaptor extends FragmentStateAdapter {
Context mContext;
JapanGuideViewModel japanGuideViewModel;
public PlannerFragmentViewPager2Adaptor(FragmentManager fragmentManager, Lifecycle lifecycle, Context mContext, JapanGuideViewModel japanGuideViewModel) {
super(fragmentManager, lifecycle);
this.japanGuideViewModel = japanGuideViewModel;
this.mContext = mContext;
Log.d(TAG, "full constructor in planner fragment");
}
@NonNull
@Override
public Fragment createFragment(int position) {
Log.d(TAG, "createFragment called in plannerFragment. Position is ");
switch (position) {
case 0:
Log.d(TAG, "planner fragment, case 0, localechoosingfragment");
LocaleChoosingFragment localeChoosingFragment = new LocaleChoosingFragment(mContext, japanGuideViewModel);
return localeChoosingFragment;
case 1:
Log.d("planner fragment localeExploringFragmentTAG", "case 1");
LocaleExploringFragment localeExploringFragment = new LocaleExploringFragment(mContext, japanGuideViewModel);
return localeExploringFragment;
default:
Log.d(TAG, "default constructor so returning localeChoosingFragment");
localeChoosingFragment = new LocaleChoosingFragment(mContext, japanGuideViewModel);
return localeChoosingFragment;
}
}
@Override
public int getItemCount() {
return 2;
}
}
}
And here is the localeChoosingFragment:
public class LocaleChoosingFragment extends Fragment {
JapanGuideViewModel japanGuideViewModel;
Context mContext;
View localeChoosingFragmentView;
public static final String TAG = "JapanGuideTAG";
RecyclerView localeChoosingRecyclerView;
LinearLayoutManager recyclerViewLayoutManager;
LocaleChoosingRecyclerViewAdaptor localeChoosingAdaptor;
SnapHelperOneByOne SnapHelper;
public LocaleChoosingFragment() {
Log.d(TAG, "EMPTY constructor called for localeChoosingFragment");
}
public LocaleChoosingFragment(Context mContext, JapanGuideViewModel japanGuideViewModel) {
this.japanGuideViewModel = japanGuideViewModel;
this.mContext = mContext;
Log.d(TAG, "constructor called for localeChoosingFragment");
Toast.makeText(mContext, "Creating a new localeChoosingFragment", Toast.LENGTH_SHORT).show();
}
@Override
public void onCreate(Bundle savedInstanceState) {
Log.d(TAG, "onCreate in localeChoosingFragment");
super.onCreate(savedInstanceState);
Log.d(TAG, "creating a NEW LOCALECHOOSING RECYCLERVIEW");
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
Log.d(TAG, "onCreateView called in LocalChoosingFragment");
localeChoosingFragmentView = inflater.inflate(R.layout.fragment_locale_choosing, container, false);
localeChoosingRecyclerView = localeChoosingFragmentView.findViewById(R.id.localeChoosingRecyclerView);
return localeChoosingFragmentView;
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Log.d(TAG, "onviewcreated in locale choosing fragment.");
localeChoosingAdaptor = new LocaleChoosingRecyclerViewAdaptor(mContext, japanGuideViewModel);
SnapHelper = new SnapHelperOneByOne();
recyclerViewLayoutManager = new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false);
localeChoosingRecyclerView.setLayoutManager(recyclerViewLayoutManager);
localeChoosingRecyclerView.setAdapter(localeChoosingAdaptor);
SnapHelper.attachToRecyclerView(localeChoosingRecyclerView);
// localeChoosingRecyclerView.scrollToPosition(japanGuideViewModel.getCurrentLocaleBeingViewed().getValue());
}
public class LocaleChoosingRecyclerViewAdaptor extends RecyclerView.Adapter {
Context mContext;
JapanGuideViewModel japanGuideViewModel;
Button exploreNowButton;
Button wontGoHereButton;
TextView localeNameTextView;
TextView localeDescriptionTextView;
ImageView localePhotoImageView;
TextView localePhotoCaptionTextView;
public LocaleChoosingRecyclerViewAdaptor() {
Log.d(TAG, "localeChoosingAdaptor created with empty constructor");
}
public LocaleChoosingRecyclerViewAdaptor(Context mContext, JapanGuideViewModel japanGuideViewModel) {
this.mContext = mContext;
this.japanGuideViewModel = japanGuideViewModel;
Log.d(TAG, "localeChoosingAdaptor created with full constructor");
}
@NonNull
@Override
public LocaleChoosingAdaptorHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
Log.d(TAG, "oncreateviewholder in localechoosingfragment");
View view = LayoutInflater.from(mContext).inflate(R.layout.locale_recyclerview_holder, parent, false);
return new LocaleChoosingAdaptorHolder(view);
}
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
Log.d(TAG, "onBindViewHolder called in localeChoosingFragment. The position is " + position + " and the total size is " + getItemCount());
localeNameTextView = holder.itemView.findViewById(R.id.localeRecyclerviewHolderHeadingTextview);
localeNameTextView.setText(japanGuideViewModel.getLocalesDetailsArray().getValue().get(position).getLocaleName());
localeDescriptionTextView = holder.itemView.findViewById(R.id.localeRecyclerviewHolderDescriptionTextView);
if (japanGuideViewModel.getLocalesDetailsArray().getValue().get(holder.getAdapterPosition()).getLocaleDescription() != null) {
localeDescriptionTextView.setText(japanGuideViewModel.getLocalesDetailsArray().getValue().get(holder.getAdapterPosition()).getLocaleDescription());
}
localePhotoImageView = holder.itemView.findViewById(R.id.localeRecyclerviewHolderImageView);
if ((japanGuideViewModel.getLocalesDetailsArray().getValue().get(holder.getAdapterPosition()).getPhotoSet().size() != 0)) {
if ((japanGuideViewModel.getLocalesDetailsArray().getValue().get(holder.getAdapterPosition()).getPhotoSet().get(0).getURL() != null) && (!(japanGuideViewModel.getLocalesDetailsArray().getValue().get(holder.getAdapterPosition()).getPhotoSet().get(0).getURL().equals("")))) {
Glide.with(mContext).load(japanGuideViewModel.getLocalesDetailsArray().getValue().get(holder.getAdapterPosition()).getPhotoSet().get(0).getURL()).into(localePhotoImageView);
}
localePhotoCaptionTextView = holder.itemView.findViewById(R.id.localeRecyclerviewHolderPhotoCaptionTextView);
if ((japanGuideViewModel.getLocalesDetailsArray().getValue().get(holder.getAdapterPosition()).getPhotoSet().get(0).getCaption() != null) && (japanGuideViewModel.getLocalesDetailsArray().getValue().get(holder.getAdapterPosition()).getPhotoSet().get(0).getCaption() != "")) {
localePhotoCaptionTextView.setText(japanGuideViewModel.getLocalesDetailsArray().getValue().get(holder.getAdapterPosition()).getPhotoSet().get(0).getCaption());
}
}
exploreNowButton = holder.itemView.findViewById(R.id.LocaleRecyclerviewHolderExploreNowButton);
wontGoHereButton = holder.itemView.findViewById(R.id.LocaleRecyclerviewHolderWontGoHereButton);
exploreNowButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.d(TAG, "Explore now button clicked. Setting the locale to explore to " + japanGuideViewModel.getCurrentLocaleBeingViewed().getValue());
japanGuideViewModel.getCurrentLocaleBeingViewed().setValue(holder.getAdapterPosition());
}
});
} //bind
@Override
public int getItemCount() {
return japanGuideViewModel.getLocalesDetailsArray().getValue().size();
}
} //recyclerview adaptor
public class LocaleChoosingAdaptorHolder extends RecyclerView.ViewHolder {
TextView localeNameTextView;
TextView localeDescriptionTextView;
Button exploreNowButton;
Button wontGoHereButton;
public LocaleChoosingAdaptorHolder(@NonNull View itemView) {
super(itemView);
Log.d(TAG, "localechoosing recyclerview holder constructor called");
localeNameTextView = itemView.findViewById(R.id.localeRecyclerviewHolderHeadingTextview);
localeDescriptionTextView = itemView.findViewById(R.id.localeRecyclerviewHolderDescriptionTextView);
exploreNowButton = itemView.findViewById(R.id.LocaleRecyclerviewHolderExploreNowButton);
wontGoHereButton = itemView.findViewById(R.id.LocaleRecyclerviewHolderWontGoHereButton);
}
}
}
I was not expecting the RecyclerView in LocaleChoosingFragment to reset to the first position when the observer in the plannerFragment is triggered by the observer in the plannerFragment of currentLocaleBeingViewed in the Viewmodel. Everything else works as expected.
|
I have a column in my Bigq\Query table that is filled by C# Ticks:
DateUtc = DateTime.UtcNow.Ticks;
This is some thing like:638148714773184690
I want to convert it to Bigquery DateTime.
|
Conver C# DateTime.Ticks to Bigquery DateTime Format |
|c#|sql|.net|google-bigquery| |
I have stuck with a pretty simple problem - I can't communicate with process' stdout.
The process is a simple stopwatch, so I'd be able to start it, stop and get current time.
The code of stopwatch is:
```python
import argparse
import time
def main() -> None:
parser = argparse.ArgumentParser()
parser.add_argument('start', type=int, default=0)
start = parser.parse_args().start
while True:
print(start)
start += 1
time.sleep(1)
if __name__ == "__main__":
main()
```
And its manager is:
```python
import time
import asyncio
class RobotManager:
def __init__(self):
self.cmd = ["python", "stopwatch.py", "10"]
self.robot = None
async def start(self):
self.robot = await asyncio.create_subprocess_exec(
*self.cmd,
stdout=asyncio.subprocess.PIPE,
)
async def stop(self):
if self.robot:
self.robot.terminate()
await self.robot.wait()
async def state(self):
print("communicating...")
stdout, stderr = await self.robot.communicate()
print(stdout, stderr)
async def main():
robot = RobotManager()
await robot.start()
time.sleep(5)
await robot.state()
time.sleep(5)
await robot.stop()
asyncio.run(main())
```
After running python manager.py it hangs when getting state of robot.
I tried to replace `proc.communicate()` with `proc.stdout.readline()` but nothing changed.
EDIT:
I moved from idea with state() to just output last printed time
the RobotManager now is:
import asyncio
class RobotManager:
def __init__(self):
self.cmd = ["python", "stopwatch.py", "10"]
self.robot = None
async def start(self):
self.robot = await asyncio.create_subprocess_exec(
*self.cmd,
stdout=asyncio.subprocess.PIPE,
)
async def stop(self):
if self.robot:
self.robot.kill()
stdout = await self.robot.stdout.readline()
print(stdout)
await self.robot.wait()
self.robot = None
async def main():
robot = RobotManager()
await robot.start()
await asyncio.sleep(3)
await robot.stop()
await robot.start()
await asyncio.sleep(3)
await robot.stop()
asyncio.run(main())
but stdout.readline returns an empty byte string every time :( |
I developed this website- https://snotes00.vercel.app
but I am facing an issue while sending request to vercel backend- POST https://snotes00.vercel.app/server/login net::ERR_ABORTED 405 (Method Not Allowed)
I was sending the request from- https://snotes00.vercel.app/login
While running in local server, it works alright., it causes this issue only in vercel.
I am running the front end on https://snotes00.vercel.app and backend on https://snotes00.vercel.app/server
Github repo- https://github.com/sayanbose-0000/snotes
Please help me fix it
[NOTE: I don't think there is an error in my code, cause it works fine in local server... Is there a problem in how I set up the env variables?]
|
{"Voters":[{"Id":6782707,"DisplayName":"Edric"},{"Id":115145,"DisplayName":"CommonsWare"},{"Id":295004,"DisplayName":"Morrison Chang"}],"SiteSpecificCloseReasonIds":[18]} |
I have an expo app that i had to run `expo prebuild` and then `expo run:android` on. I am using Clerk for auth and expo router. This app is based on the tabs template. My root _layout.tsx looks like this:
```javascript
export function InitialLayout() {
const [loaded, error] = useFonts({
SpaceMono: require("../assets/fonts/SpaceMono-Regular.ttf"),
...FontAwesome.font,
});
const segments = useSegments();
const router = useRouter();
const { isLoaded, isSignedIn } = useAuth();
useEffect(() => {
if (!loaded || !isLoaded) return;
const inProtectedGroup = segments[0] === "(tabs)";
if (isSignedIn && !inProtectedGroup) {
return router.push("/(tabs)");
} else if (!isSignedIn) {
return router.push("/(auth)/login");
}
}, [isSignedIn]);
// Expo Router uses Error Boundaries to catch errors in the navigation tree.
useEffect(() => {
if (error) throw error;
}, [error]);
useEffect(() => {
if (loaded) {
SplashScreen.hideAsync();
}
}, [loaded]);
if (!isLoaded || !loaded) {
return (
<SafeAreaView>
<View style={tw`flex justify-center items-center h-full`}>
<ActivityIndicator size="large" color={Colors.brandColor} />
</View>
</SafeAreaView>
);
}
return <Slot />;
}
export default function RootLayout() {
const colorScheme = useColorScheme();
return (
<ClerkProvider publishableKey={CLERK_KEY} tokenCache={tokenCache}>
<GestureHandlerRootView>
<ThemeProvider
value={colorScheme === "dark" ? DarkTheme : DefaultTheme}
>
<SafeAreaView>
<InitialLayout />
</SafeAreaView>
</ThemeProvider>
</GestureHandlerRootView>
</ClerkProvider>
);
}
```
Inside the (tabs) folder, the _layout.tsx looks like this:
```javascript
export default function TabLayout() {
const colorScheme = useColorScheme();
return (
<Tabs
screenOptions={{
tabBarActiveTintColor: Colors[colorScheme ?? "light"].tint,
}}
>
<Tabs.Screen
name="index"
options={{
tabBarLabel: "Home",
title: "Tab One",
tabBarIcon: ({ color }) => <TabBarIcon name="home" color={color} />,
}}
/>
<Tabs.Screen
name="two"
options={{
tabBarLabel: "Away",
title: "Tab Two",
tabBarIcon: ({ color }) => <TabBarIcon name="code" color={color} />,
}}
/>
</Tabs>
);
}
```
Then I have index.tsx and two.tsx (these came with the template). Before adding clerk routing worked fine. I added clerk and the routing works fine when user is not logged in (they are sent to (auth)/login). But once I login to the app, I see the two tab button on the very top of the screen and don't see any component being rendered when in fact i have index.tsx. I have attached a screenshot too.[![Screenshot of the app][1]][1]
[1]: https://i.stack.imgur.com/rPJWn.jpg |
Expo Router does not render the child components but renders the tabs |
|expo|expo-router|clerk| |
In JavaScript, there are fundamentally two types of entities: primitives and objects. Primitives can be reassigned, but they cannot be *altered*.
Primitives include things like numbers and strings.
Objects are things like, well, `Objects` (written like `{key: value}`), arrays (`[1, 2, 3, ...]`).
For example, some primitives:
```javascript
let a = "hello";
let b = a; // b is now "hello"
a = "bye"; // a is now "bye", but
// b is is still "hello"
```
Objects, on the other hand, *can* be altered, and that change is reflected across all variables that reference that object:
```javascript
let a = {
phrase: "hello"
};
let b = a;
a.phrase = "bye"; // b.phrase is now "bye"
```
It also means that this doesn't work the way you might expect:
```javascript
let obj = {
token: "hello"
}
let token = obj.token;
token = "bye"; // obj.token is still "hello"
``` |
{"Voters":[{"Id":10289265,"DisplayName":"Hao Wu"},{"Id":16540390,"DisplayName":"jabaa"},{"Id":269970,"DisplayName":"esqew"}]} |
So I'm trying to run this command to turn files into a .chd file:
`for i in *.cue; do chdman createcd -i "$i" -o "${i%.*}.chd"; done`
But I get this error:
`fish: ${ is not a valid variable in fish.
for i in *.cue; do chdman createcd -i "$i" -o "${i%.*}.chd"; done`
Which is boggling to me cuz I run this command to convert flac to ogg and it works just fine:
`find . -name "*flac" -exec sh -c 'oggenc -q 7 "$1" -o ~/vorbis/"${1%.*}".ogg' _ {} \;`
The second line uses ${ and works fine. So why is the first command giving me that error for ${? I've searched around and can't find much on the subject. I'd really like to understand so if I use a similar string in the future I'll know what to do. I don't really know much about coding, so this really has my interest. And frustration at the same time.
Thank you for reading, and any and all help
What I have tried is replacing ${ with $(, and other variants. But nothing has worked. The command works fine in zsh, so it's something with Fish.
I did find this:
`https://stackoverflow.com/questions/57882337/resolving-is-not-a-valid-variable-in-fish-error-when-installing-ghc-the-h`
Looks like someone having a similar problem, but...do I really have to install something(ghc) to get this working? Seems like there would be a different work around. |
Error: fish: ${ is not a valid variable in fish |
|linux| |
null |
To embed YouTube videos in your web app while safeguarding the direct video links, you can use the YouTube Player API provided by YouTube. This allows you to embed YouTube videos on your website without exposing the direct video links.
Here's a general approach to achieve this using the YouTube Player API:
Include the YouTube Player API script: First, include the YouTube Player API script in your HTML. You can do this by adding the following script tag to your HTML file:
```
<script src="https://www.youtube.com/iframe_api"></script>
```
Create a placeholder for the video: Create a placeholder element (e.g., a div) where you want to embed the YouTube video.
```
<div id="player"></div>
```
Initialize the YouTube player: In your JavaScript code, initialize the YouTube player by specifying the video ID and other options. This code should be executed after the YouTube Player API script has loaded.
```
let player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '360',
width: '640',
videoId: 'VIDEO_ID_HERE', // Replace VIDEO_ID_HERE with the ID of your YouTube video
playerVars: {
// Add any additional player options here
},
events: {
// Add event handlers if needed
}
});
}
```
Replace the placeholder with the video player: When the YouTube Player API is ready, it will call the onYouTubeIframeAPIReady function. This function creates a new instance of the YouTube player and replaces the placeholder with the actual video player.
Access control: By using the YouTube Player API, you can control the playback of the video, such as starting, pausing, stopping, and adjusting volume, without exposing the direct video links.
This approach ensures that the direct video links are not exposed to users, as the video is embedded using an iframe generated by the YouTube Player API. Additionally, it provides you with control over the video playback and other features.
|
Why am I getting 'Method Not Allowed Error' in vercel |
|backend|mern|vercel| |
Trying to add an AD user account to a AD group using python with ldap3 using the following script:
```
# Import necessary modules and libraries
import requests
from flask import json
from ldap3 import Server, Connection, ALL_ATTRIBUTES, SUBTREE, NTLM
from ldap3.extend.microsoft.addMembersToGroups import ad_add_members_to_groups
# Test API data
testuser = r"TS\testuser"
# Define LDAP server details
Server_ip = '192.168.2.3'
# Define bind user credentials
#BIND_Username = 'CN=Automation,CN=Users,DC=testnetwerk,DC=com'
BIND_Username = 'TESTNETWERK\\Automation'
BIND_Password = 'Welkom123!'
# Define LDAP paths
Base_DN = "dc=testnetwerk,dc=com"
Filter = "(sAMAccountName={0}*)" # LDAP filter to search for users based on sAMAccountName
Group_DN = "CN=testgroup,CN=Users,DC=testnetwerk,DC=com" # DN of the group to which users will be added
# Function to create an LDAP Server object
def server_ldap():
return Server(Server_ip)
# Function to establish connection to LDAP server
def connect_ldap():
server = server_ldap()
# return Connection(server, user=BIND_Username, password=BIND_Password, auto_bind=True)
return Connection(server, user=BIND_Username, password=BIND_Password, authentication=NTLM)
# Function to search for a user in LDAP directory based on sAMAccountName
def find_user(username):
with connect_ldap() as c:
print("Connected to LDAP server")
# Perform LDAP search operation
c.search(search_base=Base_DN, search_filter=Filter.format(username[3:]), search_scope=SUBTREE,
attributes=ALL_ATTRIBUTES, get_operational_attributes=True)
# Return search results in JSON format
print(json.loads(c.response_to_json()))
return json.loads(c.response_to_json())
# Function to add the found user to the specified LDAP group
def add_user_to_group(username):
# Retrieve the DN (Distinguished Name) of the user from search results
user = find_user(username)["entries"][0]["dn"]
print(user)
# Add user to the specified group
ad_add_members_to_groups(connect_ldap(), user, Group_DN)
# Return confirmation message
return "Added " + user + " to the group!"
print(find_user(testuser))
try:
# Attempt to add test user to the group and print confirmation
print(add_user_to_group(testuser))
except Exception as e:
# Print error message if an exception occurs
print("ai ai ai")
print(e)
```
However printing out the value that should be returned using `print(json.loads(c.response_to_json()))` it responds, when returning it it does not and gives me the following error: `TypeError: the JSON object must be str, bytes or bytearray, not NoneType`
Uncommenting `#BIND_Username = 'CN=Automation,CN=Users,DC=testnetwerk,DC=com'` and `# return Connection(server, user=BIND_Username, password=BIND_Password, auto_bind=True)`
and commenting the other it works.
Response from the print when the return does not work:
```
{'entries': [{'attributes': {'accountExpires': '9999-12-31 23:59:59.999999+00:00', 'badPasswordTime': '1601-01-01 00:00:00+00:00', 'badPwdCount': 0, 'cn': 'Test User', 'codePage': 0, 'countryCode': 0, 'dSCorePropagationData': ['1601-01-01 00:00:00+00:00'], 'displayName': 'Test User', 'distinguishedName': 'CN=Test User,CN=Users,DC=testnetwerk,DC=com', 'givenName': 'Test', 'instanceType': 4, 'lastLogoff': '1601-01-01 00:00:00+00:00', 'lastLogon': '1601-01-01 00:00:00+00:00', 'logonCount': 0, 'name': 'Test User', 'objectCategory': 'CN=Person,CN=Schema,CN=Configuration,DC=testnetwerk,DC=com', 'objectClass': ['top', 'person', 'organizationalPerson', 'user'], 'objectGUID': '{bdfd2aa0-2fcf-46df-9417-2396360fb83f}', 'objectSid': 'S-1-5-21-813124840-2969614714-1384511549-1106', 'primaryGroupID': 513, 'pwdLastSet': '2024-03-29 12:50:26.547474+00:00', 'sAMAccountName': 'testuser', 'sAMAccountType': 805306368, 'sn': 'User', 'uSNChanged': 12835, 'uSNCreated': 12830, 'userAccountControl': 66048, 'userPrincipalName': 'testuser@testnetwerk.com', 'whenChanged': '2024-03-29 12:50:26+00:00', 'whenCreated': '2024-03-29 12:50:26+00:00'}, 'dn': 'CN=Test User,CN=Users,DC=testnetwerk,DC=com'}]}
```
Response from the print when it does work:
```
{'entries': [{'attributes': {'accountExpires': '9999-12-31 23:59:59.999999+00:00', 'badPasswordTime': '1601-01-01 00:00:00+00:00', 'badPwdCount': 0, 'cn': 'Test User', 'codePage': 0, 'countryCode': 0, 'dSCorePropagationData': ['1601-01-01 00:00:00+00:00'], 'displayName': 'Test User', 'distinguishedName': 'CN=Test User,CN=Users,DC=testnetwerk,DC=com', 'givenName': 'Test', 'instanceType': 4, 'lastLogoff': '1601-01-01 00:00:00+00:00', 'lastLogon': '1601-01-01 00:00:00+00:00', 'logonCount': 0, 'name': 'Test User', 'objectCategory': 'CN=Person,CN=Schema,CN=Configuration,DC=testnetwerk,DC=com', 'objectClass': ['top', 'person', 'organizationalPerson', 'user'], 'objectGUID': '{bdfd2aa0-2fcf-46df-9417-2396360fb83f}', 'objectSid': 'S-1-5-21-813124840-2969614714-1384511549-1106', 'primaryGroupID': 513, 'pwdLastSet': '2024-03-29 12:50:26.547474+00:00', 'sAMAccountName': 'testuser', 'sAMAccountType': 805306368, 'sn': 'User', 'uSNChanged': 12835, 'uSNCreated': 12830, 'userAccountControl': 66048, 'userPrincipalName': 'testuser@testnetwerk.com', 'whenChanged': '2024-03-29 12:50:26+00:00', 'whenCreated': '2024-03-29 12:50:26+00:00'}, 'dn': 'CN=Test User,CN=Users,DC=testnetwerk,DC=com'}]}
```
and the returned response when calling `print(find_user(testuser))`
```
{'entries': [{'attributes': {'accountExpires': '9999-12-31 23:59:59.999999+00:00', 'badPasswordTime': '1601-01-01 00:00:00+00:00', 'badPwdCount': 0, 'cn': 'Test User', 'codePage': 0, 'countryCode': 0, 'dSCorePropagationData': ['1601-01-01 00:00:00+00:00'], 'displayName': 'Test User', 'distinguishedName': 'CN=Test User,CN=Users,DC=testnetwerk,DC=com', 'givenName': 'Test', 'instanceType': 4, 'lastLogoff': '1601-01-01 00:00:00+00:00', 'lastLogon': '1601-01-01 00:00:00+00:00', 'logonCount': 0, 'name': 'Test User', 'objectCategory': 'CN=Person,CN=Schema,CN=Configuration,DC=testnetwerk,DC=com', 'objectClass': ['top', 'person', 'organizationalPerson', 'user'], 'objectGUID': '{bdfd2aa0-2fcf-46df-9417-2396360fb83f}', 'objectSid': 'S-1-5-21-813124840-2969614714-1384511549-1106', 'primaryGroupID': 513, 'pwdLastSet': '2024-03-29 12:50:26.547474+00:00', 'sAMAccountName': 'testuser', 'sAMAccountType': 805306368, 'sn': 'User', 'uSNChanged': 12835, 'uSNCreated': 12830, 'userAccountControl': 66048, 'userPrincipalName': 'testuser@testnetwerk.com', 'whenChanged': '2024-03-29 12:50:26+00:00', 'whenCreated': '2024-03-29 12:50:26+00:00'}, 'dn': 'CN=Test User,CN=Users,DC=testnetwerk,DC=com'}]}
```
Any ideas?
|
import tkinter as tk
from tkvideo import tkvideo
root = tk.Tk()
root.geometry("957x555")
root.configure(bg = "#FFFFFF")
root.attributes('-alpha', 0.8)
canvas = tk.Canvas(
root,
bg="#FFFFFF",
height=555,
width=957,
bd=0,
highlightthickness=0,
relief="ridge"
)
canvas.place(x = 0, y = 0)
canvas.create_rectangle(
52.976036673451745,
41.0,
69.0,
512.0,
fill="#FFFFFF",
outline="")
canvas.create_rectangle(
854.9753520069789,
24.0,
871.0,
508.0,
fill="#FFFFFF",
outline="")
canvas.create_text(
247.0,
250.0,
anchor="nw",
text="Test",
fill="#FFFFFF",
font=("Inter Medium", 24 * -1)
)
lbl = tk.Label()
player = tkvideo("Files/0001-1000.mp4", lbl, loop=1, size=(957,555),)
player.play()
lbl.pack()
canvas.pack()
root.resizable(False, False)
root.mainloop()
I've used Tkvideo to create a video playing infinitely in the back. I've tried to make the video both as a part and not a part of the canvas and moving around the elements but it seems they aren't being displayed. I want some text to be visible in the front but Its not working. Can someone help? |
How to get text and other elements to display over the Video in Tkinter? |
|python|python-3.x|tkinter|video|tkinter-canvas| |
I am curently working on an App implemented with REACT. The idea, or the task is to get data from Spotify, filter that data and add those songs to a new playlist which than can be saved to the spotify-profile.
I already setup the main functionalities with mocked data. But now I am trying to connect the login button on my app to the authorization flow and I am really stucked.
Spotify-for Developers provides a [boilerplate](https://github.com/spotify/web-api-examples/blob/master/authorization/authorization_code_pkce/public/app.js), that is stored on github .
Here the boilerplate is linked as script to the index.html and the app is build with javascript. So I need a different approach. I saved the boilerplate in a js file and tried different ways to connect it with the App.js file in my application. Including the boilerplate directly in the App.js file throws errors because of the 'await' statements in the function.
My last Idea was to import the the provided Clickhandlers and use them via props with the button. But of course it does not work as intendet. I get redirected to the Spotify-login-page. But when I click on the login there, i get redirected to my app with no informations. Which makes sense, because the rest of the boilerplate-code cant be executed.
What would be the best approach to make this work? Do I have to extract some of the code and bring it to App.js?
This is my App.js:
```
import {React, useState, useEffect} from "react";
import Navbar from './components/Navbar/Navbar';
import Footer from './components/Footer/Footer';
import Main from './components/Main/Main'
import './assets/global.css';
import {loginWithSpotifyClick, logoutClick, refreshTokenClick} from './data/AuthContext2.js';
const App = () => {
return (
<div className="appLayout">
<Navbar login={loginWithSpotifyClick} />
<Main />
<Footer />
</div>
);
}
export default App;
```
This is my Navbar-Component that includes the login-button:
```
import React from 'react';
import './Navbar.css';
const Navbar = ({login}) => {
return (
<div className="container2">
<h1 className="ja"><span>ja</span><span className="mmm">mmm</span><span className="ing">ing</span></h1>
<button className='login' onClick={login}>Login</button>
</div>
);
}
export default Navbar;
```
This is the boilerplate-file (I already deleted the HTML related code from the original file). I named it AuthContext2.js:
```
/**
* This is an example of a basic node.js script that performs
* the Authorization Code with PKCE oAuth2 flow to authenticate
* against the Spotify Accounts.
*
* For more information, read
* https://developer.spotify.com/documentation/web-api/tutorials/code-pkce-flow
*/
const clientId = "be41c3b888364af48ef3602d44a207a6"; // your clientId
const redirectUrl = 'http://localhost:3000/callback'; // your redirect URL - must be localhost URL and/or HTTPS
const authorizationEndpoint = "https://accounts.spotify.com/authorize";
const tokenEndpoint = "https://accounts.spotify.com/api/token";
const scope = 'user-read-private user-read-email';
// Data structure that manages the current active token, caching it in localStorage
const currentToken = {
get access_token() { return localStorage.getItem('access_token') || null; },
get refresh_token() { return localStorage.getItem('refresh_token') || null; },
get expires_in() { return localStorage.getItem('refresh_in') || null },
get expires() { return localStorage.getItem('expires') || null },
save: function (response) {
const { access_token, refresh_token, expires_in } = response;
localStorage.setItem('access_token', access_token);
localStorage.setItem('refresh_token', refresh_token);
localStorage.setItem('expires_in', expires_in);
const now = new Date();
const expiry = new Date(now.getTime() + (expires_in * 1000));
localStorage.setItem('expires', expiry);
}
};
// On page load, try to fetch auth code from current browser search URL
const args = new URLSearchParams(window.location.search);
const code = args.get('code');
// If we find a code, we're in a callback, do a token exchange
if (code) {
const token = await getToken(code);
currentToken.save(token);
// Remove code from URL so we can refresh correctly.
const url = new URL(window.location.href);
url.searchParams.delete("code");
const updatedUrl = url.search ? url.href : url.href.replace('?', '');
window.history.replaceState({}, document.title, updatedUrl);
}
// If we have a token, we're logged in, so fetch user data and render logged in template
if (currentToken.access_token) {
const userData = await getUserData();
}
// Otherwise we're not logged in, so render the login template
async function redirectToSpotifyAuthorize() {
const possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
const randomValues = crypto.getRandomValues(new Uint8Array(64));
const randomString = randomValues.reduce((acc, x) => acc + possible[x % possible.length], "");
const code_verifier = randomString;
const data = new TextEncoder().encode(code_verifier);
const hashed = await crypto.subtle.digest('SHA-256', data);
const code_challenge_base64 = btoa(String.fromCharCode(...new Uint8Array(hashed)))
.replace(/=/g, '')
.replace(/\+/g, '-')
.replace(/\//g, '_');
window.localStorage.setItem('code_verifier', code_verifier);
const authUrl = new URL(authorizationEndpoint)
const params = {
response_type: 'code',
client_id: clientId,
scope: scope,
code_challenge_method: 'S256',
code_challenge: code_challenge_base64,
redirect_uri: redirectUrl,
};
authUrl.search = new URLSearchParams(params).toString();
window.location.href = authUrl.toString(); // Redirect the user to the authorization server for login
}
// Soptify API Calls
async function getToken(code) {
const code_verifier = localStorage.getItem('code_verifier');
const response = await fetch(tokenEndpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: new URLSearchParams({
client_id: clientId,
grant_type: 'authorization_code',
code: code,
redirect_uri: redirectUrl,
code_verifier: code_verifier,
}),
});
return await response.json();
}
async function refreshToken() {
const response = await fetch(tokenEndpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: new URLSearchParams({
client_id: clientId,
grant_type: 'refresh_token',
refresh_token: currentToken.refresh_token
}),
});
return await response.json();
}
async function getUserData() {
const response = await fetch("https://api.spotify.com/v1/me", {
method: 'GET',
headers: { 'Authorization': 'Bearer ' + currentToken.access_token },
});
return await response.json();
}
// Click handlers
export async function loginWithSpotifyClick() {
await redirectToSpotifyAuthorize();
}
export async function logoutClick() {
localStorage.clear();
window.location.href = redirectUrl;
}
export async function refreshTokenClick() {
const token = await refreshToken();
currentToken.save(token);
}
``` |
How to connect Spotify PKCE Authorization Boilerplate to Login-Button in REACT-APP |
|reactjs|authentication|pkce|spotify-app| |
null |
You can upload your custom model to HuggingFace, create a `Modelfile` (https://github.com/ollama/ollama/blob/main/docs/modelfile.md), then build the model with `ollama`
Here's a reference > https://github.com/ollama/ollama |
I wait until the page is loaded and use the "DOMContentLoaded" method to add eventhandlers on some p tags. This works until I open and close the modal, then the page/js freezes. Why does it freeze?
```
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="div_1">
<p>One</p>
<p>Two</p>
<p>Three</p>
</div>
<p id="open_modal">open the modal</p>
<script>
document.addEventListener("DOMContentLoaded", () => {
let test = document.querySelector("#div_1")
for (let i = 0; i < test.children.length; i++) {
test.children[i].addEventListener("click", () => {
console.log(test.children[i].innerHTML)
});
};
});
document.querySelector("#open_modal").addEventListener("click", () => {
if (!document.querySelector("#modal")) {
document.body.innerHTML += `
<div id="modal" style="display: block; position: fixed; padding-top: 200px; left: 0; top: 0; width: 100%; height: 100%;
background-color: rgba(0,0,0,0.4)">
<div id="modal_content">
<span id="modal_close">×</span>
<p style="color: green;">Some text in the Modal..</p>
</div>
</div>
`;
document.querySelector("#modal_close").addEventListener("click", () => {
document.querySelector("#modal").style.display = "none";
});
} else {
document.querySelector("#modal").style.display = "block";
};
});
</script>
</body>
</html>
``` |
I have an interface
```
interface I1 {
field1: fieldType1;
...
fieldN: fieldTypeN;
}
```
Now, I need an interface that has the same fields, but some of them (say the first 10) are optional.
I can write it as `Omit<I1, field1, ..., field 10> & {field1?: fieldType1 ...}` but wonder if there is a more concise way to do it.
|
Make some of the type's field optional |
|typescript| |
I am writing a program that reads a bmp file, and then outputs the same BMP file but cropped in half. I'm doing this by simply dividing the bmp height in half, and that results in the top half of the BMP image being cropped out. However, I can only crop out the top half. I am trying to find a way to crop out the bottom half of the BMP image, but it seems that the pixels begin writing from the bottom of the file and I am trying to get them to start halfway through the file, or maybe start from the top down.
```
// Update the width and height in the BMP header
header.width = newWidth;
header.height = newHeight;
printf("New header width: %d\n", header.width);
printf("New header height: %d\n", header.height);
// Write the modified BMP header to the output file
fwrite(&header, sizeof(BMPHeader), 1, outputFile);
// Calculate the padding
int padding = (4 - (header.width * (header.bpp / 8)) % 4) % 4;
// Copy the image data
unsigned char pixel[4];
for (int y = 0; y < newHeight; y++) {
for (int x = 0; x < header.width; x++) {
fread(pixel, sizeof(unsigned char), header.bpp / 8, inputFile);
fwrite(pixel, sizeof(unsigned char), header.bpp / 8, outputFile);
}
for (int p = 0; p < padding; p++) {
fputc(0, outputFile); // Write padding for the new image
}
}
// Close the files
fclose(inputFile);
fclose(outputFile);
printf("BMP image cropped successfully\n");
```
This is essentially all the code that does the image cropping. I'm only using stdio.h and stdlib.h libraries and would like to keep it that way. The outputted image is the bottom half of the original image, but I would like to also be able to find a way to keep the top half instead. The original BMP image I am using is 3200x1200, and I am setting the new height to be 600 instead of 1200 so the new image can be cut in half vertically.
EDIT: The `header.height` and `header.width` variables are both positive. `header.height = 1200`, and `header.width = 3200` originally.

 |
This worked for me, try using this :
https://github.com/TooTallNate/proxy-agents
The request formed will be similar to this:
```
fetch('accessUrl', {agent: new HttpsProxyAgent('proxyHost:proxyPort')})
.then(function (res) {
})
```
|
You need to run `updateSelectizeInput` if one of the `SelectizeInput` receives a selection. Therefore you could include the code below: The first `lapply` attaches an `observeEvent` to all `SelectizeInput` and the `lapply` inside contains the updates.
```
lapply(
X = cols_to_filter,
FUN = function(colChanged) {
observeEvent(input[[paste0("filter_", colChanged)]], {
lapply(
X = cols_to_filter,
FUN = function(colToChange) {
updateSelectizeInput(
inputId = paste0("filter_", colToChange),
choices = filtered_data()[[colToChange]],
selected = input[[paste0("filter_", colToChange)]]
)
}
)
}, ignoreNULL = FALSE)
}
)
```
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/fDHvv.gif |
Try using `<ng-template ngFor let-room [ngForOf]="rooms"><mat-tab></mat-tab></ng-template>`
instead of `<mat-tab *ngFor="let room of rooms"></mat-tab>`.<br/>
I hope this help if someone have same issue.<br/>
If it now working, you can try using lazy-loadig: `<ng-template matTabContent>` |
've started working with Svelte and I stumbled upon some unexpected behavior. This is the snippet of my app source
let currentPage = 1;
$: if (currentPage || $selectedOption) {
fetchPage(currentPage, $selectedOption);
}
async function fetchPage(page: number, option: string) {
//...
}
onMount(() => {
fetchPage(currentPage, $selectedOption);
});
When I load the page for the first time `fetchPage()` function is called twice. However, if I'll make this change `let currentPage = 0;` it is properly called only once. The problem is that I need to have `currentPage` value initially set to 1.
I've tried also this change:
let currentChange = 0;
// ... rest the same
onMount(() => {
fetchPage(currentPage, $selectedOption);
currentPage = 1;
});
But this didn't help as well. Similarly any bool flags set in `onMount()` and then checked in if statement didn't help.
Any suggestion what else can I do? |
Unexpected additional function calls in Svelte depending on init variable |
|svelte| |
Using `querySelectorAll` =>
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const dialog = document.querySelector("dialog");
const showButton = document.querySelectorAll("dialog + button");
const closeButton = document.querySelectorAll("dialog button");
// "Show the dialog" button opens the dialog modally
showButton.forEach(k=> k.addEventListener("click", () => {
dialog.showModal();
}));
// "Close" button closes the dialog
closeButton.forEach(l=>l.addEventListener("click", () => {
dialog.close();
}));
<!-- language: lang-html -->
<dialog>
<img src="https://www.w3schools.com/html/img_girl.jpg" height="600">
<button autofocus>Close</button>
</dialog>
<button class="btn">
<img src="https://www.w3schools.com/html/img_girl.jpg" height="200" width="200">
</button>
<dialog>
<img src="https://www.w3schools.com/html/img_girl.jpg" height="600">
<button autofocus>Close</button>
</dialog>
<button class="btn">
<img src="https://www.w3schools.com/html/img_girl.jpg" height="200" width="200">
</button>
<!-- end snippet -->
|
I want to deploy a shiny application composed of files `ui` , `server` and `global` via Docker. All the files are in the folder `deploy_test`
I simulated this dataset
set.seed(123)
dir.create("deploy_test")
setwd("deploy_test")
mydata_<-data.frame(
gender=c(rep("Male",50),rep("Female",25)),
height=c(rnorm(50,1.70,0.05),rnorm(25,1.65,1))
)
saveRDS(mydata_,file = "mydata_.RDS")
Here are the contents of my files:
## 1. **UI**
source("global.R")
dashboardPage(
dashboardHeader(title = "Test of app deployment"),
dashboardSidebar(
selectInput("gender","Gender",as.character(unique(mydata_$gender)))
),
dashboardBody(
fluidRow(
column(6,plotOutput(
"plot1"
)),
column(6,plotOutput(
"plot2"
))
),
fluidRow(
dataTableOutput(
"table"
)
)
)
)
## 2. **SERVER**
source("global.R")
function(input, output, session){
output$plot1<-renderPlot(
{
data_<-mydata_%>%filter(
gender==input$gender
)
boxplot(data_$height)
}
)
output$plot2<-renderPlot(
{
data_<-mydata_%>%filter(
gender==input$gender
)
hist(data_$height)
}
)
output$table<-renderDataTable(
{
data_<-mydata_%>%filter(
gender==input$gender
)
data_
}
)
}
## 3. **GLOBAL**
library(shinydashboard)
library(shiny)
library(tidyverse)
library(DT)
mydata_<-readRDS("mydata_.RDS")
## 4. **DOCKERFILE**
Dockerfile is located in the same folder as the Shiny's:
# Base image
FROM rocker/shiny
#Make a directory in the container
RUN mkdir /home/shiny-app
# Install dependencies
RUN R -e "install.packages(c('tidyverse','shiny','shinydashboard','DT'))"
COPY . /home/shiny-app/
EXPOSE 8180
CMD ["R", "-e", "shiny::runApp('/home/shiny-app')"]
I built my container without any problem:
docker build -t deploy_test .
When I run it:
docker run -p 8180:8180 deploy_test
It generate the links:
Listening on http://xxx.x.x.x:xxxx
But nothing appears when I access the link:
I got: `La connexion a échoué` |
null |
I have created this swiper slider with pagination bullets that have a progress bar pagination. It changes color for the bullet (to #000) on active slides. Is there a way for the bullets for the slide that was visited has their colored changed (to #000) as well - so only the unvisited slide's bullet with the grey #DDD background?
Here's my code:
HTML:
```
<!-- Slider main container -->
<div class="swiper-container">
<!-- Additional required wrapper -->
<div class="swiper-wrapper">
<!-- Slides -->
<div class="swiper-slide">Slide 1</div>
<div class="swiper-slide">Slide 2</div>
<div class="swiper-slide">Slide 3</div>
...
</div>
<!-- If we need pagination -->
<div class="swiper-pagination"></div>
</div>
```
CSS:
```
:root {
--swiper-pagination-bullet-border-radius: 0;
--swiper-pagination-bullet-width: 40px;
--swiper-pagination-bullet-height: 2px;
}
body {
font-family: Helvetica;
color: #000;
}
.swiper-container {
width: 100%; height: 100vh;
}
.swiper-wrapper {
width: 100%; height: 100%;
}
.swiper-slide {
font-size: 100px; text-align: center;
line-height:100vh;
}
.swiper-pagination-bullet {
position: relative;
height: auto;
opacity: 1;
margin-right: 20px;
background-color: transparent;
.progress-bar-bg {
position: absolute;
bottom: 0;
left: 0;
z-index: 1;
width: 100%;
height: 2px;
background-color: #DDD;
}
.progress-bar-cover {
position: absolute;
bottom: 0;
left: 0;
z-index: 2;
width: 0%;
height: 2px;
background-color: #000;
}
}
.swiper-pagination-bullet-active {
background-color: transparent;
b {
animation-name: countingBar;
animation-duration: 3s;
animation-timing-function: ease-in;
animation-iteration-count: 1;
animation-direction: alternate ;
animation-fill-mode:forwards;
}
}
@keyframes countingBar {
0% {width: 0;}
100% {width:100%;}
}
```
JS:
```
var mySwiper = new Swiper('.swiper-container', {
loop: true,
slidesPerView: 1,
autoplay: {
delay: 5000,
},
effect: 'fade',
fadeEffect: {
crossFade: true
},
pagination: {
el: '.swiper-pagination',
clickable: 'true',
type: 'bullets',
renderBullet: function (index, className) {
return '<span class="' + className + '">' + '<i class="progress-bar-bg"></i>' + '<b class="progress-bar-cover"></b>' + '</span>';
},
},
})
```
Any pointers would be an immense help. Thank you so much.
In JavaScript, I tried added an event listener to visited slide through click and added a 'visited-slide' class before. However, it requires a click but won't automatically updating the bullet's color as the slide animation goes on. |
Swiper pagination bullet: styling for visited slides' pagination bullet as well |
|javascript|css|sass|swiper.js| |
null |
As explained in the comments, you can get via JavaScript the total memory usage in your WASM (`WebAssembly.Memory.prototype.buffer.byteLength`). This never shrinks, but if it continuously grows then you probably have a leak. You can get the `WebAssembly.Memory` instance via [`wasm_bindgen::memory()`](https://docs.rs/wasm-bindgen/latest/wasm_bindgen/fn.memory.html), and the rest can be done with `wasm_bindgen`:
```rust
fn get_current_allocated_bytes() -> u64 {
#[wasm_bindgen]
extern "C" {
type Memory;
#[wasm_bindgen(method, getter)]
fn buffer(this: &Memory) -> MaybeSharedArrayBuffer;
type MaybeSharedArrayBuffer;
#[wasm_bindgen(method, getter = byteLength)]
fn byte_length(this: &MaybeSharedArrayBuffer) -> f64;
}
wasm_bindgen::memory()
.unchecked_into::<Memory>()
.buffer()
.byte_length() as u64
}
```
If you want a more performant implementation (this will be quite slow), or if you want a more precise metric (as said, this won't count deallocations), you can implement a global allocator:
```rust
use std::alloc::{GlobalAlloc, Layout, System};
use std::sync::atomic::{AtomicIsize, Ordering};
struct CountingAllocator<A> {
inner: A,
allocated_now: AtomicIsize,
}
impl<A> CountingAllocator<A> {
const fn new(inner: A) -> Self {
Self {
inner,
allocated_now: AtomicIsize::new(0),
}
}
fn allocated_now(&self) -> usize {
self.allocated_now
.load(Ordering::Relaxed)
.try_into()
.unwrap_or(0)
}
}
unsafe impl<A: GlobalAlloc> GlobalAlloc for CountingAllocator<A> {
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
self.allocated_now
.fetch_add(layout.size() as isize, Ordering::Relaxed);
self.inner.alloc(layout)
}
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
self.allocated_now
.fetch_sub(layout.size() as isize, Ordering::Relaxed);
self.inner.dealloc(ptr, layout);
}
unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 {
self.allocated_now
.fetch_add(layout.size() as isize, Ordering::Relaxed);
self.inner.alloc_zeroed(layout)
}
unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
self.allocated_now.fetch_add(
new_size as isize - layout.size() as isize,
Ordering::Relaxed,
);
self.inner.realloc(ptr, layout, new_size)
}
}
#[global_allocator]
static ALLOCATOR: CountingAllocator<System> = CountingAllocator::new(System);
```
Then call `ALLOCATOR.allocated_now()` to retrieve the exact number of currently allocated bytes. |
From a Cloud Functions standpoint, that approach is fine. You have put your API key into the Configuration as an environment variable. It would be safer to put the key into [Google Secret Manager][1], but your approach here is reasonable.
Except....the question is how you are populating the Configuration for your environment variables and how you are storing the "source" of that information.
For example, if you put the API key into some type of shell script and are passing that API key via `firebase functions:config:set ....` then it is the data in the shell script that is a risk. You need to protect that file. Storing it as clear text in your version control system, for example, would be an insecure approach.
[1]: https://cloud.google.com/security/products/secret-manager |
I'm developing a web compiler in TypeScript and I've encountered a small, but still irritating issue.
I have a progress bar inside an iframe element which keeps rendering for a short amount of time.
I want that progress bar to be rendered only when there's a code bundling process.
Here's a piece of that TypeScript code:
`codeCell.tsx` (The `CodeCell` component):
```
const bundle = useTypedSelector((state) => state.bundles[cell.id]);
return (
<>
<Resizable direction="vertical">
<div className="h-100 d-flex flex-row position-relative">
<Resizable direction="horizontal">
<div className="position-relative w-100">
<CodeEditor
initialValue={cell.content}
onChange={handleEditorChange}
/>
</div>
</Resizable>
<div className="progress-wrapper">
{!bundle || bundle.loading ? (
<div className="progress-cover">
<progress hidden={!bundle} max="100"/>
</div>
) : (
<Preview code={bundle.code} err={bundle.err} cell={cell}/>
)}
</div>
</div>
</Resizable>
</>
);
```
`useTypedSelector.ts` (`useTypedSelector` hook):
```
export const useTypedSelector: TypedUseSelectorHook<RootState> = (selector) => {
const result = useSelector(selector, shallowEqual);
return useMemo(() => result, [result]);
};
const shallowEqual = (a: any, b: any) => {
if (a === undefined || b === undefined) {
return false;
}
for (let key in a) {
if(a[key] !== b[key]) {
return false;
}
}
for (let key in b) {
if (!(key in a)) {
return false;
}
}
return true;
};
```
`preview.tsx` (`Preview` component):
```
interface PreviewProps {
code: string;
err: string;
cell: Cell;
}
const Preview: React.FC<PreviewProps> = ({ code, err, cell }) => {
const iframe = useRef<any>();
useEffect(() => {
iframe.current.srcdoc = html;
setTimeout(() => {
iframe.current.contentWindow.postMessage(code, '*'); // Posts the result from the code bundling
}, 10);
}, [code]);
return (
<div className="preview-wrapper">
<iframe
title="code preview"
ref={iframe}
sandbox="allow-scripts"
srcDoc={html}/>
{err && (
<div className="preview-error">
{err}
</div>
)}
<div style={{ display: "none" }}>
<div className="action-bar">
<ActionBar id={cell.id}/>
</div>
</div>
</div>
);
}
export default Preview;
```
One of the approaches I tried is using a ternary operator inside the `Preview` component's props stating that if there's a code bundling process you'll see the progress bar (the same if there's a code error) and if not (there's no code at all), you'll see an empty string (meaning you'll see an empty iframe element). |
There might some cases:
1. Ensure that the font file (Yarndings20Charted-regular.ttf) is
located in the correct directory within your Flutter project.
2. Double-check that the family name specified in your pubspec.yaml
matches the actual family name embedded in the font file.
3. Sometimes, changes to the pubspec.yaml file may not take effect
immediately. Try hot-reloading your app by pressing **r** in the
terminal or restarting your app to see if the font is loaded
correctly.
4. Sometimes, cached assets may cause issues with font loading. You can
try clearing the Flutter build cache by running flutter clean in
your terminal and then rebuilding your app. |
if you use just *.mdb you can build the connection like this: to avoid the error ODBC Driver not found.
db_main = f"C:\Users\jseinfeld\Desktop\Databasetest1.mdb"
conn_string = r"DRIVER={Microsoft Access Driver (*.mdb)};" \
f"DBQ={db_main}" |
I want to set axisItems to a PlotItem useing pyqtgraph, I encountered an error while running my code.
Here is my code:
```
import numpy as np
import pyqtgraph as pg
app = pg.mkQApp("app")
x = np.linspace(0, 10, 1000)
y = np.sin(x)
plot_item = pg.PlotItem()
plot_item.setAxisItems(axisItems={'top':pg.AxisItem('top')}) # error occurs here
plot_item.plot(x, y)
plot_item.setTitle("Sine Wave Plot")
plot_item.setLabel("left", "Amplitude", units="V")
plot_item.setLabel("bottom", "Time", units="s")
plot_item.showGrid(True, True)
win = pg.GraphicsLayoutWidget()
win.setWindowTitle("PlotItem Example")
win.resize(800, 600)
win.addItem(plot_item)
win.show()
app.exec()
```
----------------------------------------------------------------------------------------------------
When I run this code, it shows the error as below:
```
Traceback (most recent call last):
File "E:\Workspace\Python\VNPY-master\examples\candle_chart\tick\item\main.py", line 42, in <module>
plotItem.setAxisItems(axisItems={'top':pg.AxisItem('top')})
File "E:\home\.conda\envs\Python310\lib\site-packages\pyqtgraph\graphicsItems\PlotItem\PlotItem.py", line 312, in setAxisItems
oldAxis.scene().removeItem(oldAxis)
AttributeError: 'NoneType' object has no attribute 'removeItem'
```
I tried to set axises when initialzing PlotItem, it succeeded. but how to set axises after initialized PlotItem?
```
plotItem = pg.PlotItem(axisItems={'top':pg.AxisItem('top')})
```
|
null |
I'm using ```sorl-thumbnail``` and it works as expected except for when I use ```padding``` (which I have to) a white background is added.
I know I can change that color, but I want no color (i.e transparency).
Is there any hack or another library to fix this? |
sorl-thumbnail adds a background color when padding is used |
|python|django|sorl-thumbnail| |
je veux créer une class BottleOfWater () et à l'intérieur une fonction avec pour argument contenant, couleur et liquide |
null |
This is not a question, but a summary of the steps required to address multi tenancy with spring (the partitioned approach where every table will have a tenant id column). I hope this helps others facing issues or looking for sample code ...
Two things to consider here -
1. The tenant id will be set in the header and passed with every http request.
2. I have enabled spring data rest in my application.
Firstly we need an determine the tenant for each http request. We can do that by intercepting the http request before it is processed, determine the tenant and store it until the request is completely processed and clear the tenant before the next http request is processed.
import jakarta.validation.constraints.NotNull;
@FunctionalInterface
public interface TenantResolver<T> {
String resolveTenantId(@NotNull T object);
}
Tenant context is the class which will store the tenant Id once it is identified by intercepting http requests.
public class TenantContext {
private static final ThreadLocal<String> tenantId = new InheritableThreadLocal<>();
public static void setTenantId(String tenant) {
tenantId.set(tenant);
}
public static String getTenantId() {
return tenantId.get();
}
public static void clear() {
tenantId.remove();
}
}
HTTPHeaderTenantResolver implements TenantResolver. X-TenantId is the name of the header which contains the tenant id and passed along with every http request.
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.constraints.NotNull;
import org.springframework.stereotype.Component;
@Component
public class HttpHeaderTenantResolver implements TenantResolver<HttpServletRequest> {
@Override
public String resolveTenantId(@NotNull HttpServletRequest request) {
return request.getHeader("X-TenantId");
}
}
We then need to intercept each request by implementing HandlerInterceptor. In the preHandle() method, we resolve the tenant id and store it in the TenantContext class. In postHandle() and afterCompletion(), we clear the tenant id in TenantContext so we are ready to process new http requests.
@Component
@RequiredArgsConstructor
public class HttpRequestInterceptor implements HandlerInterceptor {
private final HttpHeaderTenantResolver tenantResolver;
@Override
public boolean preHandle(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response,
@NotNull Object handler) throws Exception {
var tenantId = tenantResolver.resolveTenantId(request);
TenantContext.setTenantId(tenantId);
return true;
}
@Override
public void postHandle(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response,
@NotNull Object handler, ModelAndView modelAndView) throws Exception {
TenantContext.clear();
}
@Override
public void afterCompletion(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response,
@NotNull Object handler, Exception ex) throws Exception {
TenantContext.clear();
}
}
We then need to register HttpRequestInterceptor with Spring. We do that by implementing addInterceptors method of WebMvcConfigurer.
@Configuration
@RequiredArgsConstructor
public class WebConfigurer implements WebMvcConfigurer {
private final HttpRequestInterceptor httpRequestInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(httpRequestInterceptor);
}
}
With this, spring starts intercepting every http request and will try to resolve the tenant id. We now have to let hibernate know of the current tenant id so that hibernate can use the tenant id in all sql statements. We can do that by implementing the interfaces CurrentTenantIdentifierResolver and HibernatePropertiesCustomizer.
@Component
public class JPATenantIdentifierResolver implements CurrentTenantIdentifierResolver<String>, HibernatePropertiesCustomizer {
@Override
public String resolveCurrentTenantIdentifier() {
return (TenantContext.getTenantId() == null ? "" : TenantContext.getTenantId());
}
@Override
public boolean validateExistingCurrentSessions() {
return false;
}
@Override
public void customize(Map<String, Object> hibernateProperties) {
hibernateProperties.put(AvailableSettings.MULTI_TENANT_IDENTIFIER_RESOLVER, this);
}
}
Now hibernate is aware of the current tenant and it will add the tenant id in all sql statements.
Lastly, as I have enabled spring data rest, we will require one additional step. Spring does not intercept data rest urls by default. We need to define an addition bean to achieve this step.
@Configuration
public class JPARequestInterceptor {
@Bean
public MappedInterceptor addJPARestHttpInterceptor() {
return new MappedInterceptor(
null, // => maps to any repository
new HttpRequestInterceptor(new HttpHeaderTenantResolver())
);
}
}
We can then define our entities. @TenantId annotation is the hibernate annotation and should be there in all entities.
public class Instance {
@Id
@GeneratedValue(strategy = GenerationType.UUID)
@JdbcTypeCode(SqlTypes.VARCHAR)
private UUID id;
@TenantId
private String tenant;
private String name;
private LocalDate startDate;
private LocalDate validUntil;
private String instanceStatus;
}
Below are some links which will provide more information on multi tenancy -
[https://www.youtube.com/watch?v=pG-NinTx4O4&t=1164s][1]
[https://stackoverflow.com/questions/69816821/mappedinterceptor-bean-vs-webmvcconfigurer-addinterceptors-what-is-the-correct][2]
[https://github.com/spring-projects/spring-data-rest/issues/1522][3]
[1]: https://www.youtube.com/watch?v=pG-NinTx4O4&t=1164s
[2]: https://stackoverflow.com/questions/69816821/mappedinterceptor-bean-vs-webmvcconfigurer-addinterceptors-what-is-the-correct
[3]: https://github.com/spring-projects/spring-data-rest/issues/1522
|
First off: Are you sure that you are picking the right kind of model here? Training a regression model for each patient sounds like you want a linear mixed effects model here (LME), not a neural network. In general, the advantages of neural networks fly out the window if you train them on single individuals, especially if you train a high number of parameters.
LMEs are very common if you want to look at patient data. They will allow you to infer the population mean of an effect, as well as its variance across the population. They replace the constant parameters in a traditional regression model with a parameter distribution. Each individual then has its parameter set, following the common distribution.
There is a Python implementation in `statsmodels`, documented here: https://www.statsmodels.org/stable/mixed_linear.html
Now, **about the number of rows of your .csv files**: I suggest you import them into a `dataframe` with pandas and then use `dataframe.shape` to get the number of rows and columns of each of them. Then you make the number of rows an input to your program.
|
git fetch origin our-team
or
git pull origin our-team
But first you should make sure that you are already on the branch you want to update (featurex).
|
null |
So basically I'm creating a automation that copy a information from a cell and save it in to a var so i can paste in to a app like notepad or wathever
```
import win32com.client as win32
import pyautogui
import global_variables
def copiar():
try:
excel = win32.GetActiveObject("Excel.Application")
except:
print("Excel not found.")
return
# Obter o nome da planilha ativa
workbook_name = excel.ActiveWorkbook.Name
# Se a planilha ativa não for a desejada, você pode abrir a planilha usando o seu caminho
if workbook_name != 'CONEMB_ZLE.xlsx':
# Exibe uma mensagem de aviso
print("Excel not found, open.")
return
# Tornar o Excel visível
excel.Visible = True
# Selecionar a planilha ativa
sheet = excel.ActiveSheet
# Obter o valor da célula selecionada
global_variables.valor_global = sheet.Application.Selection.Text
# Imprimir o valor
#print(global_variables.valor_global)
copiar()
```
It was working until today, I don't know why its doesnt recognize my Excel archive anymore, it prints `excel not found` but the Excel is opened with the same archive
I use it this way because i don't want to have to put the archive location I'm 3 hours tryng to fix that and i use my Excel archives on my Onedrive.
Here is the error message:
Traceback (most recent call last): File "C:\Users\bissojhe\PycharmProjects\pythonProject\.venv\py32.py", line 36, in <module> copiar() File "C:\Users\bissojhe\PycharmProjects\pythonProject\.venv\py32.py", line 8, in copiar excel = win32.GetActiveObject("Excel.Application") ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\bissojhe\PycharmProjects\pythonProject\.venv\Lib\site-packages\win32com\client_init_.py", line 96, in GetActiveObject return __WrapDispatch(dispatch, Class, resultCLSID=resultCLSID, – |
How to deploy my shiny application (with multiple files) via Docker |
|r|docker|shiny|deployment|shinydashboard| |
As per the title, I need to automate unwinding my date 7 days back upon I launch a specific macOS application bundle and putting the timestamp back to normal 45 seconds into its uptime.
What I need to do is:
1. Watch an application bundle with a specific name to be opened (like `FileSystemWatcher` in .NET)
2. Change the date 7 days back between the `Application opened by user` and `First application window appears` events (events written in pseudocode)
3. Wait 40-45 seconds while the application checks the trial period status
4. Wind the date forward to normal state.
It looks like the Automator standard library does not implement a wholly native solution for this part of workflow, and I need to find a workaround. I know it is wrong using non-seamless methods of application integration, like launcher shell scripts, and I don not prefer cracks either, just because they are illegal and also due to the fact of putting a stamp into the application menus, like `K'ed by MacKed team`. This severely damages the eye candy and is too explicit saying the software has indeed been pirated.
I do not endorse nor condone any forms of computer piracy. This question has been asked exclusively for educational purposes. |
How do I react to external program launch inside an Automator workflow? |
|macos|scripting|applescript|automator|sirishortcuts| |
null |
So far, I have the opportunity to choose in the settings which user prefers the theme: system, dark or light. And which navbar is more convenient: compact or full. I can't find anywhere what is the best way to store the user's selection and restore it when logging into the application. In the future, the settings will expand and store everything in sharedpreferences, I think it's not a good idea. Maybe storage in a local database Room or make some kind of DataStore? Can you tell me how to do this correctly and maybe there is a solution to the problem somewhere on github or in the article?
I was thinking of making something like this data class:
```
data class UserData(
val darkThemeConfig: DarkThemeConfig,
val navigationConfig: NavigationViewConfig
)
```
And somehow transfer data via Flow. But how do you save and restore them when you open the application? Please share articles and githabs with a similar implementation.
|
Storing Android user settings |
|android| |
null |
Style your text inputs with a CSS color property. To change the text input colour. Try this code for solve the problem:
input[type=text] {
color : #FFFFFF;
}
|
I have tried to isolate my problem in a very simple (and working) project. Let's say I have a simple model with 2 fields, and I have configured its properties and a `PropertyChanged` event. This is a simplified implementation of my model, please notice the last method just gets a new client object from a list and returns it:
public class Clients : INotifyPropertyChanged
{
private long _Id = 0;
public long Id
{
get { return this._Id; }
set {
this._Id = value;
RaisePropertyChanged("Id");
}
}
private String _Name = string.Empty;
public String Name
{
get { return this._Name; }
set {
if (value is null)
this._Name = string.Empty;
else
this._Name = value;
RaisePropertyChanged("Name");
}
}
public event PropertyChangedEventHandler? PropertyChanged;
internal void RaisePropertyChanged(string name)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
// Let's say this is a populated list with 100 clients with different ids and names
public static List<Clients> clients = new List<Clients>();
// ...method for loading the list with DB data
public static Clients? LoadClient(long id)
{
return clients.FirstOrDefault(x => x.Id == id);
}
}
And I have a simple `.xaml` file in order to display one client data (id and name). Each UI control has a binding with the client property and the trigger for updating. I have also 2 configured buttons that will make changes to the client values:
<TextBox x:Name="txtClientId" Text="{Binding Id, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
</TextBox>
<TextBox x:Name="txtClientName" Text="{Binding Name, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
</TextBox>
<Button Name="btnNext" Click="btnNext_Click">Next</Button>
<Button Name="btnRandom" Click="btnRandom_Click">Random</Button>
Now let's take a look to my `.xaml.cs` code. Here is the initializing and the code for the 2 buttons: one of them just modify the client properties in the `DataContext` object directly, and the other just assigns a new client object to the `DataContext` client:
public partial class ClientsPage : Page
{
private Models.Clients? client = null;
public ClientsPage()
{
InitializeComponent();
// Load all clients data in Models.Clients.clients list...
client = new Models.Clients();
DataContext = client;
}
private void btnNext_Click(object sender, RoutedEventArgs e)
{
client = Models.Clients.LoadClient(client.Id + 1);
}
private void btnRandom_Click(object sender, RoutedEventArgs e)
{
Random random = new Random();
client.Id = random.Next(999);
client.Name = "RANDOM";
}
}
- When I set the DataContext, data is displayed correctly in the UI -> OK
- When I make changes directly in the properties of the client object changes are reflected correctly in the UI -> OK
- But... when I load a new client object, and assign it to the variable set as `DataContext`, UI doesn't change since the `PropertyChanged` event is not raised.
Of course this situation can be solved by assigning property values instead of assigning a new object directly:
private void btnNext_Click(object sender, RoutedEventArgs e)
{
Models.Clients newClient = Models.Clients.LoadClient(client.Id + 1);
this.client.Id = newClient.Id;
this.client.Name = newClient.Name;
}
But it is so tedious in a real project with many models and methods that can load/modify an object with a lot of fields. I'm looking for an easy/scalable way for making the `PropertyChanged` event fire when I assign a new object to the `DataContext` variable. If you need more detail of my code or have any question I'll be happy to ask. |
As per the title, I need to automate unwinding my date 7 days back upon I launch a specific macOS application bundle and putting the timestamp back to normal 45 seconds into its uptime.
What I need to do is:
1. Watch an application bundle with a specific name to be opened (like `FileSystemWatcher` in .NET)
2. Change the date 7 days back between the `Application opened by user` and `First application window appears` events (events written in pseudocode)
3. Wait 40-45 seconds while the application checks the trial period status
4. Wind the date forward to normal state.
It looks like the Automator standard library does not implement a wholly native solution for this part of workflow, and I need to find a workaround. I know it is wrong using non-seamless methods of application integration, like launcher shell scripts, and I do not prefer cracks either, just because they are illegal and also due to the fact of putting a stamp into the application menus, like `K'ed by MacKed team`. This severely damages the eye candy and is too explicit saying the software has indeed been pirated.
I do not endorse nor condone any forms of computer piracy. This question has been asked exclusively for educational purposes. |
I have created this swiper slider with pagination bullets that have a progress bar pagination. It changes color for the bullet (to #000) on active slides. Is there a way for the bullets for the slide that was visited has their colored changed (to #000) as well - so only the unvisited slide's bullet with the grey #DDD background?
Here's my code:
HTML:
```
<!-- Slider main container -->
<div class="swiper-container">
<!-- Additional required wrapper -->
<div class="swiper-wrapper">
<!-- Slides -->
<div class="swiper-slide">Slide 1</div>
<div class="swiper-slide">Slide 2</div>
<div class="swiper-slide">Slide 3</div>
...
</div>
<!-- If we need pagination -->
<div class="swiper-pagination"></div>
</div>
```
CSS:
```
:root {
--swiper-pagination-bullet-border-radius: 0;
--swiper-pagination-bullet-width: 40px;
--swiper-pagination-bullet-height: 2px;
}
body {
font-family: Helvetica;
color: #000;
}
.swiper-container {
width: 100%; height: 100vh;
}
.swiper-wrapper {
width: 100%; height: 100%;
}
.swiper-slide {
font-size: 100px; text-align: center;
line-height:100vh;
}
.swiper-pagination-bullet {
position: relative;
height: auto;
opacity: 1;
margin-right: 20px;
background-color: transparent;
.progress-bar-bg {
position: absolute;
bottom: 0;
left: 0;
z-index: 1;
width: 100%;
height: 2px;
background-color: #DDD;
}
.progress-bar-cover {
position: absolute;
bottom: 0;
left: 0;
z-index: 2;
width: 0%;
height: 2px;
background-color: #000;
}
}
.swiper-pagination-bullet-active {
background-color: transparent;
b {
animation-name: countingBar;
animation-duration: 3s;
animation-timing-function: ease-in;
animation-iteration-count: 1;
animation-direction: alternate ;
animation-fill-mode:forwards;
}
}
@keyframes countingBar {
0% {width: 0;}
100% {width:100%;}
}
```
JS:
```
var mySwiper = new Swiper('.swiper-container', {
loop: true,
slidesPerView: 1,
autoplay: {
delay: 5000,
},
effect: 'fade',
fadeEffect: {
crossFade: true
},
pagination: {
el: '.swiper-pagination',
clickable: 'true',
type: 'bullets',
renderBullet: function (index, className) {
return '<span class="' + className + '">' + '<i class="progress-bar-bg"></i>' + '<b class="progress-bar-cover"></b>' + '</span>';
},
},
})
```
Any pointers would be an immense help. Thank you so much.
In JavaScript, I tried to add an event listener to visited slide through click and added a 'visited-slide' class before. However, it requires a click but won't automatically updating the bullet's color as the slide animation goes on. |
I'm programming a simple 'game' that is just a block that can jump around. I placed a wall, but now the character phases through when moving to the right, but the collision works when going to the right.
Every other part of this is fine. the willImpactMovingLeft function works just fine and should be a mirror of willImpactMovingRight, but right doesn't work.
simple working code for this example:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-html -->
<!DOCTYPE html>
<html>
<body>
<div id="cube" class="cube"></div>
<div id="ground1" class="ground1"></div>
<div id="ground2" class="ground2"></div>
<script>
var runSpeed = 5;var CUBE = document.getElementById("cube");var immovables = ["ground1", "ground2"];let Key = {pressed: {},left: "ArrowLeft",right: "ArrowRight",isDown: function (key){return this.pressed[key];},keydown: function (event){this.pressed[event.key] = true;},keyup: function (event){delete this.pressed[event.key];}}
window.addEventListener("keyup", function(event) {Key.keyup(event);});
window.addEventListener("keydown", function(event) {Key.keydown(event);});
setInterval(()=>{
if (Key.isDown(Key.left)){
if(willImpactMovingLeft("cube", immovables)!=false){
cube.style.left = willImpactMovingLeft("cube", immovables)+"px";
}else{
cube.style.left = CUBE.offsetLeft - runSpeed +"px";
}
}
if (Key.isDown(Key.right)){
if(willImpactMovingRight("cube", immovables)!=false){
cube.style.left = willImpactMovingRight("cube", immovables)+"px";
}else{
cube.style.left = CUBE.offsetLeft + runSpeed +"px";
}
}
}, 10);
function willImpactMovingLeft(a, b){
var docA = document.getElementById(a);
var docB = document.getElementById(b[0]);
for(var i=0;i<b.length;i++){
docB = document.getElementById(b[i]);
if((docA.offsetTop>docB.offsetTop&&docA.offsetTop<docB.offsetTop+docB.offsetHeight)||(docA.offsetTop+docA.offsetHeight>docB.offsetTop&&docA.offsetTop+docA.offsetHeight<docB.offsetTop+docB.offsetHeight)){//vertical check
if(docA.offsetLeft+docA.offsetWidth>docB.offsetLeft+runSpeed){
if(docA.offsetLeft-runSpeed<docB.offsetLeft+docB.offsetWidth){
return docB.offsetLeft+docB.offsetWidth;
}
}
}
}
return false;
}
function willImpactMovingRight(a, b){
var docA = document.getElementById(a);
var docB = document.getElementById(b[0]);
for(var i=0;i<b.length;i++){
docB = document.getElementById(b[i]);
if((docA.offsetTop>docB.offsetTop&&docA.offsetTop<docB.offsetTop+docB.offsetHeight)||(docA.offsetTop+docA.offsetHeight>docB.offsetTop&&docA.offsetTop+docA.offsetHeight<docB.offsetTop+docB.offsetHeight)){//vertical check
if(docA.offsetLeft>docB.offsetWidth+docB.offsetLeft-runSpeed){
if(docA.offsetLeft+docA.offsetWidth+runSpeed<=docB.offsetLeft){
CUBE.textContent = "WIMR";
return docB.offsetLeft-docA.offsetWidth;
}
}
}
}
return false;
}
</script><style>.cube{height:50px;width:50px;background-color:red;position:absolute;top:500px;left:500px;}.ground1{height:10px;width:100%;background-color:black;position:absolute;top:600px;left:0;}.ground2{height:150px;width:10px;background-color:black;position:absolute;top:450px;left:700px;}</style></body></html>
<!-- end snippet -->
it looks like a lot, but the only problem is the last if statement. Even when the condition is true, it still skips the return number and returns false. Any idea why?
Edit: simplified the code as much as I could.
P.S. **I CANNOT USE THE CONSOLE, I AM ON A MANAGED COMPUTER** |
My issue was that I was saved the RDS object with the `save()` function and not the `saveRDS()` function.
```
# Doesn't work
a = 1
save(a, file="test.rds")
b = readRDS("test.rds")
print(b)
```
```
# Works
a = 1
saveRDS(a, file="test.rds")
b = readRDS("test.rds")
print(b)
``` |
|javascript|google-apps-script| |
When it comes to setting initial values, I am usually using a machine factory function:
```typescript
function createInteractiveVideoMachine({
useFullscreen,
}: {
useFullscreen: boolean;
}) {
return createMachine({
id: "interactiveVideoMachine",
states: {
user: {
id: "user",
initial: `${useFullscreen ? "fullscreen" : "menu"}`, // <--here
states: {
menu: {
/*...*/
},
fullscreen: {
/*...*/
},
},
},
},
});
}
```
Then use it like so:
```typescript
let isFullscreenDefault: boolean;
const { state, send } = useMachine(createInteractiveVideoMachine({useFullscreen: isFullscreenDefault}));
``` |
I need to be able to see how much space my bucket is using, but when I followed the online help to add 'total bytes' metric to my dashboard but I cannot find this metric.
I would like to be able to monitor how much storage I am using.
Thanks for any help
|
Hello I just started with google cloud storage, size of bucket online help doesnt |
|google-cloud-datastore| |
null |
I have a large structure.
The size of arrays is known at compile time and I will not use a `Vec<_>`.
This current initialization code trigger a stack overflow:
```rust
use std::sync::atomic::AtomicUsize;
use std::sync::Arc;
#[derive(Debug)]
pub struct OuterStruct {
pub big_array_0: [u32; 108],
pub big_array_1: std::sync::Mutex<[Option<String>; 65536]>,
pub big_array_2: [AtomicUsize; 65536],
}
fn main() {
let manager = Arc::new(OuterStruct {
big_array_0: [0; 108], // Doesn't explode my stack
big_array_1: std::sync::Mutex::new(std::array::from_fn(|_| None)),
big_array_2: std::array::from_fn(|_| 0.into()),
});
}
```
So how do I allocate this structure in it's own heap allocation without triggering a stack overflow ?
I prefer not using unsafe code for this and I have `#![deny(invalid_value)]` so some `std::mem::MaybeUninit` based solutions will error (these would cause warnings anyway). |
|php|laravel|eloquent|permissions| |
I have a web app deployed on Azure. During testing, I found one of my endpoints is not working... sometimes. More specifically, this `POST` endpoint always works in my dev environment, and it randomly works in Prod.
When it fails, my controller endpoint is not hit (discovered by adding logs), and a "successful" 200 is returned but no response content is sent down. My `POST` body is tiny, only 50 or so bytes.
I'm not sure if its a clue or not, but it does seem to work immediately after a browser refresh, then when my auth token is refreshed it fails much more. This is fairly anecdotal though.
From googling, I found this helps some people:
var builder = WebApplication.CreateBuilder(args);
builder.WebHost.ConfigureKestrel(options =>
{
options.Limits.MinRequestBodyDataRate = null;
options.Limits.MinResponseDataRate = null;
});
No such luck here though. Any ideas what else might caused this? OR, any idea how how I can have .NET better tell me what's failing? I have nothing in my logs or anything.
Thanks!
EDIT:
I have two middlewares:
public class ExceptionHandlingMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger<ExceptionHandlingMiddleware> _logger;
private readonly JsonSerializerOptions jsonPolicy = new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase };
public ExceptionHandlingMiddleware(RequestDelegate next, ILogger<ExceptionHandlingMiddleware> logger)
{
_next = next;
_logger = logger;
}
public async Task InvokeAsync(HttpContext httpContext)
{
try
{
await _next(httpContext);
}
catch (Exception ex)
{
await HandleExceptionAsync(httpContext, ex);
}
}
private async Task HandleExceptionAsync(HttpContext context, Exception exception)
{
context.Response.ContentType = "application/json";
var response = context.Response;
string msg;
switch (exception)
{
case ApplicationException ex:
if (ex.Message.Contains("Invalid Token"))
{
response.StatusCode = (int)HttpStatusCode.Forbidden;
msg = ex.Message;
break;
}
response.StatusCode = (int)HttpStatusCode.BadRequest;
msg = ex.Message;
break;
default:
response.StatusCode = (int)HttpStatusCode.InternalServerError;
msg = exception.Message;
break;
}
var errorResponse = new
{
Failed = true,
ErrorMessage = msg
};
_logger.LogError(exception, exception.Message);
var result = JsonSerializer.Serialize(errorResponse, jsonPolicy);
await context.Response.WriteAsync(result);
}
}
and:
public class UserStatusMiddleware
{
private readonly RequestDelegate _next;
private readonly DbContextFactory DbContextFactory;
private readonly ILogger<ExceptionHandlingMiddleware> _logger;
private readonly JsonSerializerOptions jsonPolicy = new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase };
public UserStatusMiddleware(RequestDelegate next, DbContextFactory dbrderMonkeyContextFactory, ILogger<ExceptionHandlingMiddleware> logger)
{
_next = next;
_logger = logger;
DbContextFactory = dbContextFactory;
}
public async Task InvokeAsync(HttpContext httpContext)
{
using (DBContext dbContext = DbContextFactory.CreateDbContext())
{
var user = httpContext.User.FindFirst(ClaimTypes.NameIdentifier);
if (user == null)
{
throw new ArgumentException();
}
AspNetUser dbUser = dbContext.AspNetUsers.FirstOrDefault(x => x.Id == user.Value);
if (dbUser.IsDisabled || !dbUser.IsApproved)
{
httpContext.Response.ContentType = "application/json";
var response = httpContext.Response;
string msg;
var errorResponse = new
{
Failed = true,
IsDisabled = dbUser.IsDisabled,
IsApproved = dbUser.IsApproved,
ErrorMessage = "User is either disabled or not approved"
};
response.StatusCode = (int)HttpStatusCode.Unauthorized;
var result = JsonSerializer.Serialize(errorResponse, jsonPolicy);
await httpContext.Response.WriteAsync(result);
}
else
{
_next(httpContext);
}
}
}
}
public static class UserStatusMiddlewareExtensions
{
public static IApplicationBuilder UseUserStatusCheck(
this IApplicationBuilder builder)
{
return builder.UseMiddleware<UserStatusMiddleware>();
}
}
|
{"Voters":[{"Id":5424988,"DisplayName":"The fourth bird"},{"Id":10871073,"DisplayName":"Adrian Mole"},{"Id":2530121,"DisplayName":"L Tyrone"}]} |
If you need to mock static methods and you cannot use `mockito-inline` you could do something like this with `mockito-core`:
```java
public class MockitoUtil {
public static <T, S> void mockStaticMethod(Class<T> classToMock, String nameOfMethodToMock, S result) {
MockCreationSettings<T> settings = mock(MockCreationSettings.class);
when(settings.isSerializable()).thenReturn(true);
MockHandler<T> handler = new MockHandler<>() {
private static final long serialVersionUID = 1L;
@Override
public Object handle(Invocation invocation) throws Throwable {
String invokedMethodName = invocation.getMethod().getName();
if(!invokedMethodName.equals(nameOfMethodToMock)){
String message = "called %s on class %s, but only %s was implemented";
throw new Exception(String.format(message, invokedMethodName, classToMock.getName(), nameOfMethodToMock));
}
return result;
}
@Override
public MockCreationSettings<T> getMockSettings() { return null; }
@Override
public InvocationContainer getInvocationContainer() { return null; }
};
MockMaker.StaticMockControl<T> classToMockControl = Mockito
.framework()
.getPlugins()
.getInlineMockMaker()
.createStaticMock(classToMock, settings, handler);
classToMockControl.enable();
}
}
```
**N.B.** you should call `classToMockControl.disable()` after the static method invocation if you'd like to mock static methods of other classes in the same test |
**using a by keyword instead of the =. This is a property delegate that saves you from typing .value every time.** |
if you use just *.mdb you can build the connection like this: to avoid the error ODBC Driver not found.
db_main = f"C:\Users\jseinfeld\Desktop\Databasetest1.mdb"
conn_string = r"DRIVER={Microsoft Access Driver (*.mdb)};" \
f"DBQ={db_main}" |
the requirement is to allow to see only granted warehouse view on Snowflake cost management page, and not whole account level ware houses to specific function roles.
is that really possible, cause if I followed [https://docs.snowflake.com/en/user-guide/cost-exploring-overall#label-cost-accessing-data][1] this does not solve the purpose, as privileges granted role can see even other warehouses in "account option" and I want to restrict the role to show only specific Warehouse details.
[1]: https://docs.snowflake.com/en/user-guide/cost-exploring-overall#label-cost-accessing-data |
snowflake cost management page limited warehouse access to role |
|snowflake-cloud-data-platform| |