instruction stringlengths 0 30k ⌀ |
|---|
null |
I have been asked in one of the Top company below question and I was not able to answer.
Just replied : I need to update myself on this topic
**Question :**
**If you create a composite indexing on 3 columns (eid , ename , esal ) ?**
- If i mention only eid=10 after where clause will the indexing be called ?
`select * from emp where eid=10`;
- If I mention only eid=10 and ename='Raj' will the indexing be called ?
`select * from emp where eid=10 and ename='Raj';`
- If I mention in different order like esal=1000 and eid=10 will the indexing be called ?
`select * from emp where esal=1000 and eid=10;`
- If I mention in reverse order like esal = 1000 and ename = 'Raj' and eid = 10 will the indexing be called ?
`select * from emp where esal=1000 and enam='Raj' and eid=10;`
Need a solution for this need with detail table representation with data how it does?
|
I want to implement a feature where when I click on a specific sentence within this paragraph, the background color of that sentence changes.
I've tried looking into gesture detection and text selection features within Jetpack Compose, but couldn't find a straightforward way to achieve this effect. Can someone please guide me on how to implement this functionality? |
Change background color of clicked sentence in Text |
|android|android-jetpack-compose|android-jetpack-compose-material3|android-compose-textfield| |
null |
`[userList.jsx]`(https://i.stack.imgur.com/19EbJ.png),
`[EditUser.jsx]`(https://i.stack.imgur.com/6GyU8.png),
`[backend.js]`(https://i.stack.imgur.com/Dsx38.png)
I want to update the data in my database using a form called user List. I want to Update data of that row that's Edit button I click, my current problem is when I click Edit and fill the details to update, it gets update all rows of database |
I want to edit a specific row in database |
|database|windows|jsx| |
null |
{"Voters":[{"Id":4722345,"DisplayName":"JBallin"},{"Id":13302,"DisplayName":"marc_s"},{"Id":839601,"DisplayName":"gnat"}],"SiteSpecificCloseReasonIds":[]} |
{"Voters":[{"Id":3404097,"DisplayName":"philipxy"},{"Id":13302,"DisplayName":"marc_s"},{"Id":839601,"DisplayName":"gnat"}],"SiteSpecificCloseReasonIds":[19]} |
I was trying to build a webpage and for some reason when i test my page to be responsive, the width of the page goes beyond the device's width.
I tried removing various parts of the code and the only thing that makes the webpage go back to the normal width is removing the "introduction" div as i found out that was the problem in inspect. What is wrong with my code?
Here is my html and css regarding the introduction div:
html:
`<div class="introduction row align-items-start">
<div class="gap row">
<!--gap in between a id and text and image-->
</div>
<div class="row">
<div class="intro-text col">
Over the past few years, information technology has exploded, becoming a major force driving innovation and change. But here's the thing: even though women and folks of color have been rocking it in IT, there's still a big lack of diversity in many areas.
</div>
<div class="col">
<img src="/img/women-in-tech.png" alt="Women In IT">
</div>
</div>
</div>`
css:
`.introduction { position:relative; }
.intro-text {
font-family: "Noto Sans", sans-serif;
font-optical-sizing: auto;
font-weight: 300;
font-style: normal;
font-variation-settings:
"wdth" 100;
font-size:2.5vw ;
color:white;
margin-left:3vw;
}
.col img {
margin-top:1.5vw;
max-width: 100%;
height: auto;
margin-left:7vw;
}
/**when width of device is less than 1150px change the image height and with to 70%**/
@media screen and (max-width: 1150px) {
.col img {
height:70%;
}
}
.gap {
height:100px;
}
` |
I was trying to write a table with some entries being multi-line using altair, but seem to get into trouble with fixing line spacing. For example:
```
text_df = pd.DataFrame({"a":["very very very very long thing", "very very very very very long thing"]})
text_chart_base = alt.Chart(text_df).transform_window(row_number="row_number()").transform_calculate(
y=f"split(datum.a, ' ')"
).mark_text(align="left", baseline="top"
).encode(y=alt.Y("row_number:N", axis=None, scale=alt.Scale(reverse=True)))
col1 = text_chart_base.encode(text=f"y:N")
col2= text_chart_base.encode(text=f"row_number:N")
col1 | col2
```
gives me overlapping multi-line strings
[![enter image description here][1]][1]
Instead when I make the `row_number` Quantitative with `encode(y=alt.Y("row_number:Q", axis=None, scale=alt.Scale(reverse=True)))`, I get too much space between the strings
[![enter image description here][2]][2]
Is there a way I can get `mark_text` to give the right row spacing between rows?
[1]: https://i.stack.imgur.com/HHs64.png
[2]: https://i.stack.imgur.com/pOB0f.png |
Table with multi-line strings in Altair |
|vega-lite|altair| |
FQDN means domain name without any addition. Maps.google.com is FQDN is google.com.
Amass has ony 3 main commands. Those are intel , db and enum. Each main command have multiple sub commands. You can visit the github page from: https://github.com/owasp-amass/amass/blob/master/doc%2Fuser_guide.md
I wish it helps. |
day_of_week feb_23 mar_23 apr_23 may_23 jun_23
<chr> <int> <int> <int> <int> <int>
sunday 24575 48314 83366 84074 116821
monday 32208 46043 78434 85285 122528
tuesday 41347 56317 101060 76440 101694
wednesday 25792 51056 61445 98910 94837
thursday 21852 46027 71823 83957 117189
friday 38517 69504 75012 131155 104023
saturday 24284 24948 73140 84078 130631
I am trying to do a line graph with theses informations, but I can't do it. I would like to use each day of week in a line to represent each month.
I've tried several ways but I deleted the previous ones. The last one was:
ggplot(trip_id, aes(y=day_of_week))+
geom_line(aes(x=feb_23))+
geom_line(aes(x=mar_23))+
geom_line(aes(x=apr_23))
|
Seems that some URLs have whitespace character at the end that needs to be stripped:
```py
import requests
from bs4 import BeautifulSoup
from tqdm import tqdm
headers = {
"User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:124.0) Gecko/20100101 Firefox/124.0"
}
def save_url(url, path):
response = requests.get(url, headers=headers, stream=True)
total_size = int(response.headers.get("content-length", 0))
with tqdm(total=total_size, unit="B", unit_scale=True) as progress_bar:
with open(path, "wb") as file:
for data in response.iter_content(1024):
progress_bar.update(len(data))
file.write(data)
url = "https://www.nyc.gov/site/tlc/about/tlc-trip-record-data.page"
soup = BeautifulSoup(requests.get(url).content, "html.parser")
for a in soup.select("table a"):
month = a.find_previous("strong").get_text(strip=True)
year = a.find_previous(attrs={"data-answer": True}).get_text(strip=True)
u = a["href"].strip() # <-- important part!
path = f'{year}_{month}_{u.split("/")[-1]}'
print(year, month, u, f"Saving to {path}...")
save_url(u, path)
print("\n", "-" * 80)
```
Prints:
```none
...
100%|█████████████| 50.0M/50.0M [00:01<00:00, 37.1MB/s]
--------------------------------------------------------------------------------
2024 January https://d37ci6vzurychx.cloudfront.net/trip-data/green_tripdata_2024-01.parquet Saving to 2024_January_green_tripdata_2024-01.parquet...
100%|█████████████| 1.36M/1.36M [00:00<00:00, 5.32MB/s]
--------------------------------------------------------------------------------
2024 January https://d37ci6vzurychx.cloudfront.net/trip-data/fhv_tripdata_2024-01.parquet Saving to 2024_January_fhv_tripdata_2024-01.parquet...
100%|█████████████| 15.0M/15.0M [00:00<00:00, 42.1MB/s]
--------------------------------------------------------------------------------
2024 January https://d37ci6vzurychx.cloudfront.net/trip-data/fhvhv_tripdata_2024-01.parquet Saving to 2024_January_fhvhv_tripdata_2024-01.parquet...
100%|█████████████| 473M/473M [00:15<00:00, 31.0MB/s]
--------------------------------------------------------------------------------
2023 January https://d37ci6vzurychx.cloudfront.net/trip-data/yellow_tripdata_2023-01.parquet Saving to 2023_January_yellow_tripdata_2023-01.parquet...
100%|█████████████| 47.7M/47.7M [00:01<00:00, 42.4MB/s]
--------------------------------------------------------------------------------
2023 January https://d37ci6vzurychx.cloudfront.net/trip-data/green_tripdata_2023-01.parquet Saving to 2023_January_green_tripdata_2023-01.parquet...
100%|█████████████| 1.43M/1.43M [00:00<00:00, 46.7MB/s]
--------------------------------------------------------------------------------
...
``` |
so i am new at coding and im trying to create a Clicker game. To sum it up its supposed to be like Cookie Clicker. Click something to get a point and with those points buy upgrades. But i ran into a little Problem, i want to create Infinite Upgrades. So that i can buy a Click upgrader a infinite amount of times. But I dont know how i can code that.
I havent yet tried anything BUT i have researched. I read allot about Loops but i dont think it would fit because The upgrade part of my Code needs to go up in numbers with the Price of points and the amount of upgrades. Also i would need to somehow Fittingly change the Button Click of the "Cookie" ( cant really explain it well but i basically need to change the code of the thing i click as well ) For now i just did a Max level.
Here is my code
```
using System.Linq.Expressions;
using System.Printing;
using System.Text;
using System.Windows;
using System.Windows.Automation.Peers;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace wieso
{
public partial class MainWindow : Window
{
long Score = 0;
long Upgrade1 = 1;
public MainWindow()
{
InitializeComponent();
ClickAnzahl.Content = Score.ToString();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
ClickAnzahlTEXT.Content = "du hast so viele Clicks :";
ClickAnzahl.Content = Score.ToString();
if (Upgrade1 == 1)
{
Score = Score + 1;
ClickAnzahl.Content = Score.ToString();
}
if (Upgrade1 == 2)
{
Score = Score + 2;
ClickAnzahl.Content = Score.ToString();
}
if (Upgrade1 == 3)
{
Score = Score + 3;
ClickAnzahl.Content = Score.ToString();
}
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
if (Upgrade1 == 1 && Score >= 10)
{
Score -= 10;
Upgrade1++;
ClickAnzahl.Content = Score.ToString();
knopfding.Content = "50 CLICKS FÜR EIN CLICK UPGRADE!";
}
if (Upgrade1 == 2 && Score >= 50)
{
Score -= 50;
Upgrade1++;
ClickAnzahl.Content = Score.ToString();
knopfding.Content = "Max Level!";
}
}
}
}
```
a |
I'm trying to integrate PyDeequ with PySpark in my Streamlit application to perform comprehensive data quality checks on a CSV file. I want to use PyDeequ's functionalities to perform various tests including completeness, correctness, uniqueness, outlier detection, and date format correctness. However, I'm encountering an error that says the 'JavaPackage' object is not callable. Here's the relevant code snippet, the specific tests I'm trying to perform, and the error message:
```lang-py
import streamlit as st
from pyspark.sql import SparkSession
from pydeequ import AnalysisRunner
from pydeequ.analyzers import Completeness
def create_spark_session():
return SparkSession.builder.appName("DataQualityCheck").getOrCreate()
def read_csv_data(spark, uploaded_file):
df = spark.read.csv(uploaded_file, header=True, inferSchema=True)
return df
def main():
st.title("Data Quality Checker")
uploaded_file = st.file_uploader("Choose a CSV file:", key="csv_uploader", type="csv")
if uploaded_file is not None:
spark = create_spark_session()
df = read_csv_data(spark, uploaded_file)
analysis_runner = AnalysisRunner(spark)
analysis_result = analysis_runner.onData(df).addAnalyzer(Completeness("MRN")).run()
completeness_results = analysis_result['Completeness']
completeness_mrn = completeness_results['MRN']
completeness_percent_mrn = completeness_mrn['completeness']
missing_count_mrn = completeness_mrn['count']
if __name__ == "__main__":
main()
```
```
TypeError: 'JavaPackage' object is not callable
Traceback:
File "E:\Deequ\pydeequ_env\lib\site-packages\streamlit\runtime\scriptrunner\script_runner.py", line 542, in _run_script
exec(code, module.__dict__)
File "E:\data_quality.py", line 43, in <module>
completeness_mrn = completeness_results['MRN']
File "E:\Deequ\pydeequ_env\lib\site-packages\pydeequ\analyzers.py", line 52, in onData
return AnalysisRunBuilder(self._spark_session, df)
File "E:\Deequ\pydeequ_env\lib\site-packages\pydeequ\analyzers.py", line 124, in __init__
self._AnalysisRunBuilder = self._jvm.com.amazon.deequ.analyzers.runners.AnalysisRunBu
```
Data Quality Tests:
1. **Completeness**: Ensure that certain columns (e.g., "MRN" and "Date of Admission") have complete data.
2. **Correctness**: Verify that data in specific columns adhere to certain format or correctness rules (e.g., "MRN" format correctness).
3. **Uniqueness**: Check if certain columns contain unique values (e.g., "MRN" uniqueness).
4. **Outlier Detection**: Identify any outliers in numerical columns (e.g., "Billing Amount").
5. **Date Future Format**: Ensure that dates in a certain column (e.g., "Date of Admission") are not in the future.
I have installed PyDeequ version 1.2.0 and PySpark downgraded version 3.3.1 in my environment. Could someone please help me understand why I'm encountering this error and how to resolve it?
|
|python|docker|kubernetes|cron| |
We declare the variable `b` and initialize it to `3`.
Then we have this line, `b += b++`;
Let's dissect it.
You are correct that `b++` deals with the postfix increment operator. However, note that `b` gets incremented after we take the value of `b` (this is the case in which we are dealing with the postfix increment operator!).
So, the right hand side is really `3` because the value of `b` is `3` and we increment `b` after ("post") getting this value.
So, the whole expression is really just `b += 3`.
We are incrementing the value of `b` by `3`, so `b = 6`.
Then, remembering that since we have the postfix increment operator, we will then have to increase `b` by `1`, only on the right hand side (not on the whole expression).
However, we will not again do `b += 1` on the whole expression, so `b = 6` at the end of this program.
*If you want to continue writing this program such that we will increment b again, please feel free to do so. Since the prefix increment operator can be contrasted with the postfix increment operator, why don't you try a sample program with that (if you haven't already) and understand it?*
If anything I said confused you, please comment on this! |
How do I remove the gaps between the subplots on a mosaic? The traditional way does not work with mosaics:
plt.subplots_adjust(wspace=0, hspace=0)
I tried using the grid spec kw, but no luck.
import matplotlib.pyplot as plt
import numpy as np
ax = plt.figure(layout="constrained").subplot_mosaic(
"""
abcde
fghiX
jklXX
mnXXX
oXXXX
""",
empty_sentinel="X",
gridspec_kw={
"wspace": 0,
"hspace": 0,
},
)
for k,ax in ax.items():
print(ax)
#ax.text(0.5, 0.5, k, transform=ax.transAxes, ha="center", va="center", fontsize=8, color="darkgrey")
ax.set_xticklabels([])
ax.set_yticklabels([])
ax.tick_params(length = 0)
The code generates:
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/TxaYQ.jpg |
Remove gaps between subplots_mosaic in matplotlib |
|python|matplotlib| |
I found this code: https://github.com/pixegami/langchain-rag-tutorial/blob/main/create_database.py
It takes the document, splits it into chunks, creates vector embeddings for each chunk, and saves those into Chroma Database. However, the source code uses OpenAI key to create embeddings. Since I don't have access to OpenAI I tried to use free alternative, - SentenceTransformers. But I wasn't able to rewrite the code properly.
Here is my curent attempt:
```
from langchain_community.document_loaders import DirectoryLoader
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain.schema import Document
from sentence_transformers import SentenceTransformer
from langchain.vectorstores.chroma import Chroma
import os
import shutil
CHROMA_PATH = "chroma"
DATA_PATH = "data/books"
embedder = SentenceTransformer("all-MiniLM-L6-v2")
def main():
generate_data_store()
def generate_data_store():
documents = load_documents()
chunks = split_text(documents)
save_to_chroma(chunks)
def load_documents():
loader = DirectoryLoader(DATA_PATH, glob="*.md")
documents = loader.load()
return documents
def split_text(documents: list[Document]):
text_splitter = RecursiveCharacterTextSplitter(
chunk_size=300,
chunk_overlap=100,
length_function=len,
add_start_index=True,
)
chunks = text_splitter.split_documents(documents)
print(f"Split {len(documents)} documents into {len(chunks)} chunks.")
document = chunks[10]
print(document.page_content)
print(document.metadata)
return chunks
def save_to_chroma(chunks: list[Document]):
# Clear out the database first.
if os.path.exists(CHROMA_PATH):
shutil.rmtree(CHROMA_PATH)
# Create a new DB from the documents.
db = Chroma.from_documents(
chunks, embedder.encode, persist_directory=CHROMA_PATH
)
db.persist()
print(f"Saved {len(chunks)} chunks to {CHROMA_PATH}.")
if __name__ == "__main__":
main()
```
This is the error that I get:
```
Traceback (most recent call last):
File "/media/andrew/Simple Tom/Robotics/Crew_AI/langchain-rag-tutorial/create_database.py", line 56, in <module>
main()
File "/media/andrew/Simple Tom/Robotics/Crew_AI/langchain-rag-tutorial/create_database.py", line 15, in main
generate_data_store()
File "/media/andrew/Simple Tom/Robotics/Crew_AI/langchain-rag-tutorial/create_database.py", line 20, in generate_data_store
save_to_chroma(chunks)
File "/media/andrew/Simple Tom/Robotics/Crew_AI/langchain-rag-tutorial/create_database.py", line 49, in save_to_chroma
db = Chroma.from_documents(
File "/home/andrew/.local/lib/python3.10/site-packages/langchain_community/vectorstores/chroma.py", line 778, in from_documents
return cls.from_texts(
File "/home/andrew/.local/lib/python3.10/site-packages/langchain_community/vectorstores/chroma.py", line 736, in from_texts
chroma_collection.add_texts(
File "/home/andrew/.local/lib/python3.10/site-packages/langchain_community/vectorstores/chroma.py", line 275, in add_texts
embeddings = self._embedding_function.embed_documents(texts)
AttributeError: 'function' object has no attribute 'embed_documents'
```
I'm not a programmer. If someone could point out if it's at all possible to achive this without OpenAI key and if yes, then where my mistake is, that'd be great. |
164b: f3 0f 1e fa endbr64
164f: 55 push %rbp
1650: 53 push %rbx
1651: 48 83 ec 28 sub $0x28,%rsp
1655: 64 48 8b 04 25 28 00 mov %fs:0x28,%rax
165c: 00 00
165e: 48 89 44 24 18 mov %rax,0x18(%rsp)
1663: 31 c0 xor %eax,%eax
1665: 48 89 e6 mov %rsp,%rsi
1668: e8 18 08 00 00 call 1e85 <read_six_numbers>
166d: 83 3c 24 01 cmpl $0x1,(%rsp)
1671: 75 0a jne 167d <phase_2+0x32>
1673: 48 89 e5 mov %rsp,%rbp
1676: bb 02 00 00 00 mov $0x2,%ebx
167b: eb 13 jmp 1690 <phase_2+0x45>
167d: e8 c1 07 00 00 call 1e43 <explode_bomb>
1682: eb ef jmp 1673 <phase_2+0x28>
1684: 83 c3 01 add $0x1,%ebx
1687: 48 83 c5 04 add $0x4,%rbp
168b: 83 fb 07 cmp $0x7,%ebx
168e: 74 12 je 16a2 <phase_2+0x57>
1690: 89 d8 mov %ebx,%eax
1692: 0f af 45 00 imul 0x0(%rbp),%eax
1696: 39 45 04 cmp %eax,0x4(%rbp)
1699: 74 e9 je 1684 <phase_2+0x39>
169b: e8 a3 07 00 00 call 1e43 <explode_bomb>
16a0: eb e2 jmp 1684 <phase_2+0x39>
16a2: 48 8b 44 24 18 mov 0x18(%rsp),%rax
16a7: 64 48 2b 04 25 28 00 sub %fs:0x28,%rax
16ae: 00 00
16b0: 75 07 jne 16b9 <phase_2+0x6e>
16b2: 48 83 c4 28 add $0x28,%rsp
16b6: 5b pop %rbx
16b7: 5d pop %rbp
16b8: c3 ret
16b9: e8 c2 fb ff ff call 1280 <__stack_chk_fail@plt>
Given the code above I speculated that %rbp would be equal to a decimal value of -40 but I know this is incorrect and I dont know enough about assembly to figure out where my logic went wrong.
Im not entirely sure what the output is supposed to be but I am not sure if the answer I came up with makes sense because line 1690 compares if %eax is equal to %rbp + 4 but if %rbp is -40 this statement will never execute resulting in an infinite loop |
Why would %rbp not be equal to the value of %rsp which is 0x28 |
|assembly| |
null |
{"Voters":[{"Id":6752050,"DisplayName":"273K"},{"Id":5910058,"DisplayName":"Jesper Juhl"},{"Id":7582247,"DisplayName":"Ted Lyngmo"}],"SiteSpecificCloseReasonIds":[13]} |
|c++|qt-creator|sdl-2|qmake| |
I'm trying to find a way to get a signal-point on the chart everytime the bar is a new 15-days low.
Thanks for help!
```
//@version=5
indicator('15-Days-Low', overlay=true)
bars_back = input(15)
ll = ta.lowest(bars_back) //15-d-low
tl = ta.lowest(source=low, length=1) //todays low
lb = ta.lowestbars(bars_back) //lowest bar since when? (negative number)
plotchar(tl < ll, char='•', color=color.fuchsia, size=size.tiny, location=location.belowbar)
```
I tried to find the lowest low of the last 15 days, compare it to the low of today, and plot a char if the todays low is the lowest of the last 15 days. |
I want to download a.com with all its subdmains and not other domains
for example, I want to include x.a.com in the download and excldues others like b.com
I need to have all subdomains form a.com like x.a.com included in the downlaod but nothing from other domains.
Any idea?
wget https://a.com --domain=*.a.com |
Download a website using wget command to include any subdomain |
|subdomain|wildcard|wget| |
null |
I fix it by adding a setup file. Add a setup file in `jest.conf.js`:
setupFiles: ['<rootDir>/test/unit/setup']
Create `setup.js` and create the div.
createAppDiv();
function createAppDiv() {
var app = document.createElement('div');
app.setAttribute('id', 'app');
document.body.appendChild(app);
}
Now Run the test, the error will disappear. |
"*Why do the results pull multiple fields of the data frame when I remove the numeric_only parameter?*"
[`groupby.median`](https://pandas.pydata.org/docs/reference/api/pandas.core.groupby.DataFrameGroupBy.median.html) only accepts one parameter: `numeric_only`.
By running:
```
df.groupby('author_ban_status').median(['video_share_count'])
```
You're actually still using the `numeric_only` parameter, it's equivalent to:
```
df.groupby('author_ban_status').median(numeric_only=['video_share_count'])
```
And since `bool(['video_share_count'])` evaluates to `True`, you're essentially running:
```
df.groupby('author_ban_status').median(numeric_only=True)
```
So not filtering any column.
You might just want:
```
df.groupby('author_ban_status')[['video_share_count']].median(numeric_only=True)
``` |
I have two arrays containing file names
files_ref=( $(find . -name '*.fasta') )
files_fq=( $(find . -name '*.fastq') )
I understand that if I want to iterate over pairs of items I would do something like this:
for i in "${!files_ref[@]}"; do
printf "%s is in %s\n" "${files_ref[i]}" "${files_fq[i]}"
done
However, my second arrays looks like this
file_ref=(
DI1.fasta
DI2.fasta
WT1.fasta
)
files_fq=(
DI1_P1.fastq
DI1_P2.fastq
DI1_P3.fastq
DI2_P1.fastq
DI2_P2.fastq
DI2_P3.fastq
WT1_P1.fastq
WT1_P2.fastq
WT1_P3.fastq
)
I would have to iterate over files_ref with all its correspoding items in the same group:
DI1.fasta with DI1_P1.fastq DI1_P2.fastq DI1_P3.fastq
DI2.fasta with DI2_P1.fastq DI2_P2.fastq DI2_P3.fastq
WT1.fasta with WT1_P1.fastq WT1_P2.fastq WT1_P3.fastq
Any suggestions?
...to be more clear
I would need iterations like this:
DI1.fasta DI1_P1.fastq
DI1.fasta DI1_P2.fastq
DI1.fasta DI1_P3.fastq
DI2.fasta DI2_P1.fastq
DI2.fasta DI2_P2.fastq
DI2.fasta DI2_P3.fastq
WT1.fasta WT1_P1.fastq
WT1.fasta WT1_P2.fastq
WT1.fasta WT1_P3.fastq
|
I have a SQL Server database with a table named `Users`.
This table has 2 columns: `XP` (int32) and `Name` (nvarchar).
I need a SQL query or Linq (this is better because I'm using Entity Framework in C#) that gets the `Name` and ranks everyone based on `XP` and display the rank of this name + the rank of the previous 1 people + the rank of the next 1 people.
Something like this :
[](https://i.stack.imgur.com/PHI5S.jpg) |
I need to get Kea (DHCP server) running automatically at startup in my Yocto-based project. The Yocto recipe already includes an init.d script to start Kea automatically, however Kea requires a directory /var/run/kea to exist in order to run, so the startup script fails. Since directories under /var/run do not persist, this directory needs to be created at each startup. How can I accomplish this? |
Create kea runtime directory at startup in Yocto image |
|linux|yocto|bitbake|init.d| |
so i am new at coding and im trying to create a Clicker game. To sum it up its supposed to be like Cookie Clicker. Click something to get a point and with those points buy upgrades. But i ran into a little Problem, i want to create Infinite Upgrades. So that i can buy a Click upgrader a infinite amount of times. But I dont know how i can code that.
I havent yet tried anything BUT i have researched. I read allot about Loops but i dont think it would fit because The upgrade part of my Code needs to go up in numbers with the Price of points and the amount of upgrades. Also i would need to somehow Fittingly change the Button Click of the "Cookie" ( cant really explain it well but i basically need to change the code of the thing i click as well ) For now i just did a Max level.
Here is my code
```
using System.Linq.Expressions;
using System.Printing;
using System.Text;
using System.Windows;
using System.Windows.Automation.Peers;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace wieso
{
public partial class MainWindow : Window
{
long Score = 0;
long Upgrade1 = 1;
public MainWindow()
{
InitializeComponent();
ClickAnzahl.Content = Score.ToString();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
ClickAnzahlTEXT.Content = "du hast so viele Clicks :";
ClickAnzahl.Content = Score.ToString();
if (Upgrade1 == 1)
{
Score = Score + 1;
ClickAnzahl.Content = Score.ToString();
}
if (Upgrade1 == 2)
{
Score = Score + 2;
ClickAnzahl.Content = Score.ToString();
}
if (Upgrade1 == 3)
{
Score = Score + 3;
ClickAnzahl.Content = Score.ToString();
}
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
if (Upgrade1 == 1 && Score >= 10)
{
Score -= 10;
Upgrade1++;
ClickAnzahl.Content = Score.ToString();
knopfding.Content = "50 CLICKS FÜR EIN CLICK UPGRADE!";
}
if (Upgrade1 == 2 && Score >= 50)
{
Score -= 50;
Upgrade1++;
ClickAnzahl.Content = Score.ToString();
knopfding.Content = "Max Level!";
}
}
}
}
```
|
`math.gcd()` is certainly a Python shim over a library function that is running as machine code (i.e. compiled from "C" code), not a function being run by the Python interpreter. See also: [Where are math.py and sys.py?](https://stackoverflow.com/questions/18857355/where-are-math-py-and-sys-py) |
docker-compose can't reset postgresql database |
|postgresql|docker|docker-compose| |
null |
|excel|excel-formula|sequence|countif| |
Just Add this code to controller:
ViewData("SomeRole") = "hidden"/"visible"
To your html <li style="visibility:
@ViewBag.SomeRole'>@Html.ActionLink("Tenant", "Index", "{controller}", New With {.area = ""}, Nothing)</li> |
I'm reasonable new for JSOUP, I believe most of JSOUP user is using JSOUP to parse html content (load from Internet URL) into text or some other JOPO.
But I'm trying to use JSOUP to create html elements to create dynamic html email content in rich text.
I don't find lots of examples to create dynamic html elements (for example, graphics, logo etc.) which load from database that stored as byte array format.
If any one has experience in this sub, please share me some example.
Plenty appreciation. |
How to create an JSOUP element from byte array image (Load from Database) |
|java|image|email|jsoup| |
In my Case INPUT will be like Binary number and the output will the most consecutive '1' count.
Input :10101010101111001
Output:4
Case 2:
Input:101010101010
Output:-1
It works for me:
class HelloWorld
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
String s=sc.nextLine();
int max=1,curcount=0;
for(int i=0;i<s.length();i++)
{
if(s.charAt(i)=='1')
curcount++;
else
curcount=0;
if(max<curcount)
max=curcount;
}
if(max==1)
System.out.println("-1");
else
System.out.println(max); }
}
|
The data structure for this is a [Trie][1] (Prefix Tree):
```php
<?php
class TrieNode {
public $childNode = []; // Associative array to store child nodes
public $endOfString = false; // Flag to indicate end of a string
}
class Trie {
private $root;
public function __construct() {
$this->root = new TrieNode();
}
public function insert($string) {
if (!empty($string)) {
$this->insertRecursive($this->root, $string);
}
}
private function insertRecursive(&$node, $string) {
if (empty($string)) {
$node->endOfString = true;
return;
}
$firstChar = $string[0];
$remainingString = substr($string, 1);
if (!isset($node->childNode[$firstChar])) {
$node->childNode[$firstChar] = new TrieNode();
}
$this->insertRecursive($node->childNode[$firstChar], $remainingString);
}
public function commonPrefix() {
$commonPrefix = '';
$this->commonPrefixRecursive($this->root, $commonPrefix);
return $commonPrefix;
}
private function commonPrefixRecursive($node, &$commonPrefix) {
if (count($node->childNode) !== 1 || $node->endOfString) {
return;
}
$firstChar = array_key_first($node->childNode);
$commonPrefix .= $firstChar;
$this->commonPrefixRecursive($node->childNode[$firstChar], $commonPrefix);
}
}
// Example usage
$trie = new Trie();
$trie->insert("/home/texai/www/app/application/cron/logCron.log");
$trie->insert("/home/texai/www/app/application/jobs/logCron.log");
$trie->insert("/home/texai/www/app/var/log/application.log");
$trie->insert("/home/texai/www/app/public/imagick.log");
$trie->insert("/home/texai/www/app/public/status.log");
echo "Common prefix: " . $trie->commonPrefix() . PHP_EOL;
?>
```
[Demo][2]
[1]: https://en.wikipedia.org/wiki/Trie
[2]: https://onecompiler.com/php/428ve5e2h |
Прошу помочь уже несколько дней не понимаю в чем дело.
Я написал онлайн редактор кода на основе monaco editor.Начал делать функции вкладок и теперь моем коде либо не правильно работает удаления одного монако эдитора или что то не так делаю. В общем вкладки у меня построены так
```
[все линии
[ линия
[ таб
{} и обьекты которые хранят модель для эдитора и еще данные
],
],
]
```
проблема в том что когда я удаляю tab который не является последним должен по идеи просто удалиться.
```
[
[
[
{}
],
[ удаляю вот этот например
{}
],
[
{}
],
],
]
```
то консоль выдает ошибку model disposed хотя я же просто должен был удалить массив.
Body от него все идет
```
import { useSelector } from "react-redux";
import Tab from "./Tab";
import { useEffect, useState } from "react";
import {tabs} from './getItems'
const Body = () => {
const themeValue = useSelector(state => state.options.theme);
const plan = useSelector(state => state.editorAll.tabs)
const check = useSelector(state => state.editorAll.check)
useEffect(() => {
if(plan[0][0].length > 0){
localStorage.setItem('tabs', JSON.stringify(plan.map(tab => tab.map(innerArray => innerArray.map(obj => ({ ...obj, model: null }))))));
}
},[plan])
return (
<div className={`body ${themeValue}`}>
{
plan.map((line,i) => (
<div className="body_line" key={i}>
{
line.map((e,tabI) => (
<Tab key={tabI} plan={tabs} index={{line:i,tab:tabI}}/>
))
}
</div>
))
}
<div className={"body_check "+check}>
<div className="body_check_right"></div>
<div className="body_check_bottom"></div>
</div>
</div>
);
};
export default Body;
```
```
import { useEffect, useRef, useState} from 'react';
import Editor from '@monaco-editor/react';
import jsonpath from 'jsonpath';
import { useDispatch, useSelector } from 'react-redux';
import { addRefAction } from '../../store/reducers/ref';
import { changeAllBoolean } from '../../store/reducers/boolean/allBoolean';
import { changeCursorInfo } from '../../store/reducers/components/editorCursorLine';
import { changeEditorAll } from '../../store/reducers/components/editorAll';
import Inset from './Inset';
export default function Tab({plan,index}) {
const editRef = useRef(null);
const monacoRef = useRef(null);
const dispatch = useDispatch();
const themeValue = useSelector(state => state.options.theme);
const autoSaveValue = useSelector(state => state.options.saveBoolean);
const minimapValue = useSelector(state => state.options.minimap);
const indentationValue = useSelector(state => state.options.indentation);
const wrapTextValue = useSelector(state => state.options.wrapText);
const showIndentationValue = useSelector(state => state.options.showIndent)
const fontSizeValue = useSelector(state => state.options.fontSize);
const tabSizeValue = useSelector(state => state.options.tabSize);
const insertSpaceValue = useSelector(state => state.options.insertSpace);
const tabs = useSelector(state => state.editorAll.tabs[index.line][index.tab])
const allTabs = useSelector(state => state.editorAll.tabs)
const ownId = index
const id = useSelector(state => state.editorAll.activeInset)
const languageValue = useSelector(state => state.editorAll.tabs[id.line][id.tab][id.inset]?.lang)
const ref = useSelector(state => state.ref.ref)
const [actualIndex, setactualIndex] = useState(0)
const [actualObj, setactualObj] = useState({name: 'untilted', lang: 'json', model: null, code:'',cursor:{column:0,lineNumber:0}})
const [insetObj, setinsetObj] = useState(null)
function handleEditorDidMount(editor, monaco) {
editRef.current = editor;
monacoRef.current = monaco;
}
editor.onDidChangeModelContent(() => {
if(editor.getModel()){
dispatch(changeAllBoolean('CAN_UNDO',editor.getModel().canUndo()))
dispatch(changeAllBoolean('CAN_REDO',editor.getModel().canRedo()))
}
});
editor.onDidChangeModel(() => {
if(editor.getModel()){
dispatch(changeAllBoolean('CAN_UNDO',editor.getModel().canUndo()))
dispatch(changeAllBoolean('CAN_REDO',editor.getModel().canRedo()))
}
});
if (monaco && tabs.length === 0) {
if(plan && autoSaveValue){
createSaveInsets(plan[index.line][index.tab])
} else{
dispatch(changeEditorAll('ADD_OBJECT',{newId:ownId,newObj:{...actualObj,model:editor.getModel()}}))
}
}
if(tabs.length>0){
const newModel = monacoRef.current.editor.createModel(tabs[0].code, tabs[0].lang)
dispatch(changeEditorAll('REPLACE',{id:{...index,inset:0},obj:{...tabs[0],model: newModel}}))
setinsetObj({...tabs[0],model: newModel});
}
}
const changeEditor = () => {
if (editRef.current) {
if (editRef.current.getValue().trim() === '') {
dispatch(changeEditorAll('EMPTY',false));
} else{
dispatch(changeEditorAll('EMPTY',true));
}
}
};
const createInset = () => {
let newName = 'untilted'
const untitledObject = tabs.find(obj => obj.name === 'untilted');
if(untitledObject){
let numbers = tabs
.filter(obj => obj.name.startsWith('untilted'))
.map(obj => {
const match = obj.name.match(/untilted \((\d+)\)/);
return match?parseInt(match[1]):0;
});
let number = 1;
while (numbers.includes(number)) {
number++;
}
newName = `untilted (${number})`;
}
const newModel = monacoRef.current.editor.createModel('', 'json')
dispatch(changeEditorAll('ADD_OBJECT',{newId:ownId,newObj:{ name: newName, lang: 'json', model: newModel, code:'',cursor:{column:0,lineNumber:0}}}))
}
const deleteInset = (name,boolean) => {
const lineLength = allTabs[index.line].length
if (tabs.length == 1 && lineLength > 1){
monacoRef.current.editor.getModels().forEach(e => {
if (e.id === tabs[0]?.model?.id) {
e.dispose();
}
});
dispatch(changeEditorAll('REMOVE_TAB',index))
console.log(monacoRef.current.editor.getModels())
} else if (tabs.length > 1 ) {
const modelId = tabs.find(e => e.name === name)?.model?.id
monacoRef.current.editor.getModels().forEach(e => {
if(e.id == modelId) {
e.dispose()
}
})
dispatch(changeEditorAll('REMOVE_OBJECT',{oldId:id,oldName:name}))
if (boolean) {
if(actualIndex!==0){
setactualIndex(actualIndex-1);
}
} else{
setactualIndex(tabs.findIndex(e => e.name == name)>actualIndex?actualIndex:actualIndex-1);
}
}
}
const changeRef = () => {
console.log(editRef.current.getModel().id)
dispatch(addRefAction({ref:editRef,monaco:monacoRef}));
dispatch(changeAllBoolean('ACTIVE_INSET_CHANGE', {line:index.line,tab:index.tab,inset:actualIndex}));
}
const createSaveInsets = (plan) => {
plan.forEach((e) => {
const newModel = monacoRef.current.editor.createModel(e.code, e.lang)
dispatch(changeEditorAll('ADD_OBJECT',{newId:ownId,newObj:{ name: e.name, lang: e.lang, model: newModel, code:e.code,cursor:e.cursor}}))
})
}
useEffect(() => {
if(id.tab === index.tab && editRef.current){
dispatch(addRefAction({ref:editRef,monaco:monacoRef}));
console.log(monacoRef.current.editor.getModels())
}
});
useEffect(() => {
if (tabs.length > 0) {
const names = tabs.map(e => e?.model?.id == insetObj?.model?.id)
if(insetObj == null || !names[0]){
// setinsetObj({...tabs[0]});
}
}
}, [tabs]);
useEffect(() => {
if(editRef.current){
const name = editRef.current?.getModel()?.id
if(insetObj && name !== insetObj?.model?.id){
editRef.current.setModel(insetObj.model)
}
}
}, [insetObj]);
useEffect(() => {
if (languageValue && editRef && id.tab == index.tab && id.line == index.line ) {
const model = editRef.current.getModel();
monacoRef.current.editor.setModelLanguage(model,languageValue)
}
}, [languageValue]);
useEffect(() => {
if(id.tab == index.tab && editRef.current){
if(editRef.current.getModel()){
dispatch(changeAllBoolean('CAN_UNDO',editRef.current.getModel().canUndo()))
dispatch(changeAllBoolean('CAN_REDO',editRef.current.getModel().canRedo()))
}
}
},[id])
return (
<div className='body_tab' onClick={changeRef}>
<div className='body_tab_insets'>
{
tabs.map((e,i) => (
<Inset inset={insetObj} setInset={setinsetObj} tabIndex={ownId} editRef={editRef.current} object={e} ownIndex={i} actual={actualIndex} setIndex={setactualIndex} deleting={deleteInset} key={i}/>
))
}
<div className='body_tab_insets_add'>
<svg onClick={() => createInset()} xmlns="http://www.w3.org/2000/svg" height="22" viewBox="0 -960 960 960" width="22"><path d="M464-464H280v-32h184v-184h32v184h184v32H496v184h-32v-184Z"/></svg>
</div>
</div>
<div className="body_tab_editor">
<Editor
className="editor"
width={'100%'}
height={'100%'}
theme={themeValue === 'black' ? 'customTheme' : ''}
onMount={handleEditorDidMount}
onChange={changeEditor}
options={{
renderWhitespace: indentationValue ? 'all' : '',
automaticLayout: true,
minimap: { enabled: minimapValue },
guides: {
indentation: showIndentationValue,
}
}}
/>
</div>
</div>
)
}
```
```
import { useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { useDrag } from 'react-dnd';
import { changeAllBoolean } from "../../store/reducers/boolean/allBoolean";
import { changeEditorAll } from "../../store/reducers/components/editorAll";
export default function Inset({inset,setInset,tabIndex,editRef,object,ownIndex,actual,setIndex,deleting}) {
const [menuShow, setmenuShow] = useState(false)
const tabs = useSelector(state => state.editorAll.tabs[tabIndex.line][tabIndex.tab])
const id = useSelector(state => state.editorAll.activeInset)
const check = useSelector(state => state.editorAll.check)
const allTabs = useSelector(state => state.editorAll.tabs)
const dispatch = useDispatch()
const changeMenuShow = (event) => {
event.preventDefault();
if (!menuShow) {
setmenuShow(true)
}
}
const setModel = () => {
setIndex(ownIndex);
}
const remove = (e) => {
e.stopPropagation();
setmenuShow(false)
const lineLength = allTabs[tabIndex.line].length
if(tabs.length == 1 && lineLength > 1){
let newTab = tabIndex.tab+1==lineLength?(lineLength-2):tabIndex.tab
dispatch(changeAllBoolean('ACTIVE_INSET_CHANGE', {line:tabIndex.line,tab:newTab,inset:0}));
}
deleting(object.name,actual==ownIndex?true:false);
}
const removeAll = (e) => {
e.stopPropagation();
setmenuShow(false)
dispatch(changeEditorAll('REMOVE_ALL_OBJECT',{RMid:tabIndex,RMobj:object}))
setIndex(0);
editRef.setModel(object.model)
dispatch(changeAllBoolean('ACTIVE_INSET_CHANGE',{...tabIndex,inset:ownIndex}))
}
const removeRight = (e,side) => {
if(ownIndex !== tabs.length) {
e.stopPropagation();
setmenuShow(false)
dispatch(changeEditorAll('REMOVE_ALL_SIDES_OBJECT', { RSid: tabIndex, RSown: ownIndex, side: side }));
}
if(ownIndex<actual && side == 'right'){
setIndex(ownIndex);
editRef.setModel(object.model)
dispatch(changeAllBoolean('ACTIVE_INSET_CHANGE',{...tabIndex,inset:ownIndex}))
}
if(ownIndex>=actual && side == 'left'){
setIndex(0);
editRef.setModel(object.model)
dispatch(changeAllBoolean('ACTIVE_INSET_CHANGE',{...tabIndex,inset:ownIndex}))
}
if (ownIndex < actual && side === 'left') {
setIndex(actual-ownIndex);
editRef.setModel(object.model);
dispatch(changeAllBoolean('ACTIVE_INSET_CHANGE', { ...tabIndex, inset: ownIndex }));
}
}
const handleDragEnd = (item, monitor) => {
const clientOffset = monitor.getClientOffset();
const clickedElement = document.elementFromPoint(clientOffset.x, clientOffset.y);
if(clickedElement.classList[0] == 'body_check_right'){
if(tabs.length > 1){
dispatch(changeEditorAll('ADD_TAB',{tabObj:object,tabId:tabIndex.line}))
setmenuShow(false)
deleting(object.name,actual==ownIndex?true:false);
}
} else if(clickedElement.classList[0] == 'body_check_bottom') {
console.log(1)
}
dispatch(changeEditorAll('CHANGE_CHECK', false));
};
const [{ isDragging }, drag] = useDrag({
type:'box',
item: () => {
dispatch(changeEditorAll('CHANGE_CHECK',true))
return { type: 'box'.BOX, id }
},
collect: (monitor) => ({
isDragging: monitor.isDragging(),
}),
end:handleDragEnd,
});
useEffect(() => {
if (menuShow) {
const handleOutsideClick = (event) => {
const div = document.querySelector('.body_tab_insets_inset_menu')
const array = event.composedPath().includes(div)
if (!array) {
setmenuShow(false);
document.removeEventListener("click", handleOutsideClick)
}
};
// const handleContextMenu = (event) => {
// if (event.button === 2 && menuShow) {
// const div = document.querySelector('.body_tab_insets_inset_menu')
// const array = event.composedPath().includes(div)
// if (!array) {
// setmenuShow(false);
// document.removeEventListener("contextmenu", handleContextMenu)
// }
// }
// };
document.addEventListener("click", handleOutsideClick);
// document.addEventListener("contextmenu", handleContextMenu);
}
}, [menuShow]);
useEffect(() => {
if(editRef){
const modelChangeListener = editRef.onDidChangeModelContent(() => {
const newCursorPos = editRef.getPosition();
if(actual === ownIndex && id.tab == tabIndex.tab){
dispatch(changeEditorAll('REPLACE',{id:{...id,inset:actual},obj:{...tabs[id.inset],cursor:newCursorPos,code:editRef.getValue()}}))
}
});
return () => {
modelChangeListener.dispose();
};
}
}, [editRef, actual, ownIndex, id, tabs]);
useEffect(() => {
if (actual === ownIndex && id.tab == tabIndex.tab && inset?.model?.id !== object.model.id) {
setInset(object)
editRef.focus()
editRef.setPosition(tabs[actual].cursor);
dispatch(changeAllBoolean('ACTIVE_INSET_CHANGE', {line:tabIndex.line,tab:tabIndex.tab, inset: ownIndex}));
}
}, [actual]);
return (
<div
ref={drag}
style={{opacity: isDragging ? 0.5 : 1}}
className={`body_tab_insets_inset ${actual==ownIndex?'active':''}`}
onClick={() => setModel()}
onContextMenu={(e) => changeMenuShow(e)}
>
<div className='body_tab_insets_inset_line'></div>
<h5>{object.lang ? object.lang.toUpperCase() : ''}</h5>
<h4>{object.name}</h4>
<svg onClick={(event) => remove(event)} xmlns="http://www.w3.org/2000/svg" height="18" viewBox="0 -960 960 960" width="18"><path d="M291-267.692 267.692-291l189-189-189-189L291-692.308l189 189 189-189L692.308-669l-189 189 189 189L669-267.692l-189-189-189 189Z"/></svg>
<div className={"body_tab_insets_inset_menu "+menuShow}>
<h3 onClick={(event) => remove(event)}>Close Tab</h3>
<h3 onClick={(event) => removeAll(event)}>Close Other Tab</h3>
<h3 onClick={(event) => removeRight(event,'right')}>Close Tabs to the Right</h3>
<h3 onClick={(event) => removeRight(event,'left')}>Close Tabs to the Left</h3>
<div className="body_tab_insets_inset_menu_line"></div>
<h3>Split Up</h3>
<h3>Split Down</h3>
<h3>Split Left</h3>
<h3>Split Right</h3>
</div>
</div>
)
}
```
также так выглядит мой redux
state
```
activeInset:{line:0,tab:0,inset:0},
tabs:[
[
[
],
],
],
```
actions
```
case 'REMOVE_TAB':
return {
...state,
tabs: state.tabs.map((tabLine, lineIndex) => {
if (lineIndex === action.payload.line) {
return tabLine.filter((_, tabIndex) => tabIndex !== action.payload.tab);
}
return [...tabLine];
})
};
```
Это мой код на данный момент но раньше я использовал не useState и не хранил там текущий обьект с данными а просто при клике на саму вкладку менял модель внутри эдитора своего таба. Мне хотя бы найти причину ошибок |
Monaco editor remove tab |
|javascript|reactjs|redux|monaco-editor| |
null |
Let's assume you have those 2 files :
layout.html
```
PHP DOM
*
```
content.htm
```
<h1>DOM content</h1>
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
```
Here is the code for index.php that will insert content.htm in layout.html
```
loadHTMLFile('layout.html');
// loads the content of the document
$content = new DOMDocument();
$content->loadHTMLFile('content.htm');
// imports a copy of the content into the main document
$import = $layout->importNode($content->getElementById('content'), true);
$body = $layout->getElementById("body");
$body->appendChild($import);
echo $layout->saveHTML();
```
A few thoughts and notes :
- even if you only load a partial html document, DOMDocument::loadHTMLFile will create a complete HTML document and insert your file inside.
- for instance, this is what's inside the $content object :
```
<h1>DOM content</h1>
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
```
- you cannot move nodes from one document from another, you need to import those
- once imported, the nodes will not show as they are not attached to any other nodes in the document : you have to do it manually (appendChild here). |
null |
I have a resource in a php Filament App called LoadResource. The standard out of the box Edit action on this resource is working fine - it however does not respond to any lifecycle hooks that I place in the Edit action statement.
My Edit Action is listed below:
```
->actions([
Tables\Actions\ActionGroup::make([
Tables\Actions\ViewAction::make(),
EditAction::make()
->before(function () {
dd('test');
}),
Tables\Actions\DeleteAction::make(),
])
])
```
I am using the following:
`use Filament\Actions\EditAction;`
I however never get to the function within the beforeFormFilled() closure. Any ideas to assist would be greatly appreciated.
Was expecting the function in the beforeFormFilled() to run.
I tried to place the lifecycle hook on the Edit page of the Resource - that worked. However, I dont know how to reference the model from the Edit page `$this->` references the Edit page, not the form or the model. When I try to pass the model to the Edit page, I get an error.
For reference, the following does work - with the hassles mentioned above:
```
protected function beforeSave (array $data): void
{
dd($data);
}
```
|
Lifecycle hooks not working in Edit function, Filament resource |
|action|edit|laravel-filament|before-save| |
null |
To enable SharedArrayBuffer inside a loaded iframe, append `allow="cross-origin-isolated"` to the `<iframe>`. |
Why is the width of my webpage exceeding the device width |
|html|css|width| |
null |
I am using the MockMvcResultMathchers to test my async function but it not work properly.
Here is my function :
```
@GetMapping(
value = "/v1.0/sms-booking/async-handle",
produces = {"text/plain"})
@Async
public CompletableFuture<ResponseEntity<String>> smsAsyncHandle(@RequestParam("moLogID ") Integer moLogID ) {
CompletableFuture.runAsync(...);
return CompletableFuture.completedFuture(
ResponseEntity.ok("New Message Received with moLogID " + moLogID + " !"));
}
```
and the test function
```
@ExtendWith(SpringExtension.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureObservability
@AutoConfigureMockMvc
@EnableAsync
class SmsAsyncControllerTest {
@Test
void smsAsyncHandle_returnMoLogID_whenValidParam() throws Exception {
MvcResult mvcResult = mockMvc.perform(get(SMS_ASYNC_HANDLE_PATH)
.param("moLogID","1")
.andDo(print()).andExpect(request().asyncStarted())
.andReturn();
mockMvc.perform(asyncDispatch(mvcResult))
.andDo(print())
.andExpect(request().asyncResult(instanceOf(ResponseEntity.class)))
.andExpect(content().string(containsString("1")));
}
}
```
and when I run test, this is the result.
[enter image description here](https://i.stack.imgur.com/YcQph.png)
I want my test function run successfully. I have tried many different ways I found on internet but nothing works. Pls help me to overcome this.
Thanks |
Adding my own take here because none of the answers were acceptable to me:
```kotlin
import kotlin.contracts.ExperimentalContracts
import kotlin.contracts.InvocationKind
import kotlin.contracts.contract
private fun closeChain(items: List<AutoCloseable>) {
try {
items.last().close()
} finally {
closeChain(items.dropLast(1))
}
}
class ResourceInitializationScope {
private val itemsToCloseLater = mutableListOf<AutoCloseable>()
fun closeLater(item: AutoCloseable) {
itemsToCloseLater.add(item)
}
fun closeNow() = closeChain(itemsToCloseLater)
}
/**
* Begins a block to initialize multiple resources.
*
* This is done safely. If any failure occurs, all previously-initialized resources are closed.
*
* @param block the block of code to run.
* @return an object which should be closed later to close all resources opened during the block.
*/
@OptIn(ExperimentalContracts::class)
inline fun initializingResources(block: ResourceInitializationScope.() -> Unit): AutoCloseable {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
val scope = ResourceInitializationScope()
var success = false
try {
scope.apply(block)
success = true
return AutoCloseable { scope.closeNow() }
} finally {
if (!success) scope.closeNow()
}
}
```
Example usage: (maybe don't trust the code, other than an example of how to use it, I don't trust it yet)
```kotlin
// ... omitting surrounding code ...
private val buffers: Array<AudioBuffer>
private val device: AudioDevice
private val context: AudioContext
private val source: AudioSource
private val resourcesToClose: AutoCloseable
init {
resourcesToClose = initializingResources {
buffers = Array(BUFFER_COUNT) { AudioBuffer.generate().also(::closeLater) }
device = AudioDevice.openDefaultDevice().also(::closeLater)
context = AudioContext.create(device, intArrayOf(0)).also(::closeLater)
context.makeCurrent()
device.createCapabilities()
source = AudioSource.generate().also(::closeLater)
for (i in 0 until BUFFER_COUNT) {
bufferSamples(ShortArray(0))
}
source.play()
device.detectInternalExceptions()
}
}
override fun close() {
resourcesToClose.close()
}
// ... omitting surrounding code ...
```
|
In order of creating my website, I'm getting following warning in Firefox browser:
> When rendering the <html> element, the used values of CSS properties “writing-mode”, “direction”, and “text-orientation” on the <html> element are taken from the computed values of the <body> element, not from the <html> element’s own values. Consider setting these properties on the :root CSS pseudo-class. For more information see “The Principal Writing Mode” in https://www.w3.org/TR/css-writing-modes-3/#principal-flow
I don't know what's wrong with it and what should I do.
Is there anyone who can figure this out?
I have already tried
```css
:root{
direction:initial;
text-orientation:initial;
writing-mode:initial;
}
```
---
```css
body,html,:root{
direction:initial;
text-orientation:initial;
writing-mode:initial;
}
```
But still the warning is there. I'm using material UI. |
I'm developing a game where my main activity (GameActivity) is hide-and-seek. Then there's a second activity (InventoryActivity) where players can use items that affect their characteristics (number of hit points, for example). I'm able to retrieve the current player's hit points in the second activity, and modify them if he uses an item from his inventory. The problem comes when I finish the 2nd activity: the hit points are not sent to the main activity.
I think it's a problem of intent not being properly returned to the main activity.
To retrieve the information for my second activity, I did the following in my main activity:
```@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1001 && resultCode == RESULT_OK && data != null) {
ArrayList<Item> itemsFound = data.getParcelableArrayListExtra("ITEMS_FOUND");
ArrayList<Item> playerInventory = data.getParcelableArrayListExtra("PLAYER_INVENTORY");
int updatedHearts = data.getIntExtra("CURRENT_PLAYER_HEARTS", 0);
currentPlayerIndex = data.getIntExtra("CURRENT_PLAYER_INDEX", 0);
Player modifiedPlayer = data.getParcelableExtra("CURRENT_PLAYER");
if (modifiedPlayer != null) {
for (int i = 0; i < allPlayers.size(); i++) {
Player currentPlayer = allPlayers.get(i);
if (currentPlayer.getName().equals(modifiedPlayer.getName())) {
allPlayers.set(i, modifiedPlayer);
updateHeartsDisplay(modifiedPlayer.getHearts());
Log.d("GameActivity", "Joueur mis à jour : " + modifiedPlayer.getName() + ", Points de vie : " + modifiedPlayer.getHearts());
break;
}
}
}
}
} ```
To launch the inventory activity using intents, I used the following:
```private void launchInventoryActivity(Player currentPlayer) { // Prepare data for inventory activity ArrayList<Item> itemsFound = new ArrayList<>(); Item lastItemAdded = currentPlayer.getLastItemAdded(); if (lastItemAdded != null) { itemsFound.add(lastItemAdded); } ArrayList<Item> playerInventory = new ArrayList<>(); playerInventory.addAll(currentPlayer.getItems()); Intent inventoryIntent = new Intent(GameActivity.this, InventoryActivity.class); inventoryIntent.putParcelableArrayListExtra("ITEMS_FOUND", itemsFound); inventoryIntent.putParcelableArrayListExtra("PLAYER_INVENTORY", playerInventory); inventoryIntent.putExtra("CURRENT_PLAYER", currentPlayer); inventoryLauncher.launch(inventoryIntent); }```
Finally, in my secondary activity, I return the player's information ( with his modified hit points ) to my main activity with this;
```private void finishTurn() {
int currentPlayerIndex = getIntent().getIntExtra("CURRENT_PLAYER_INDEX", 0);
Intent intent = new Intent();
intent.putExtra("CURRENT_PLAYER_HEARTS", currentPlayer.getHearts());
intent.putExtra("CURRENT_PLAYER_INDEX", currentPlayerIndex + 1);
intent.putExtra("CURRENT_PLAYER", currentPlayer);
setResult(RESULT_OK, intent);
finish();
}
```
Thank you for your help.
I saw the new method because of the deprecated api and i did this, but i still have the same problem.
```inventoryActivityResultLauncher = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
// Vérifiez si les données de point de vie sont renvoyées
Intent data = result.getData();
if (data != null) {
int currentPlayerHealth = data.getIntExtra("CURRENT_PLAYER_HEARTS", -1);
if (currentPlayerHealth != -1) {
Player currentPlayer = data.getParcelableExtra("CURRENT_PLAYER");
if (currentPlayer != null) {
currentPlayer.setHearts(currentPlayerHealth);
updateTurnInfo();
}```
this is my private void launchInventoryActivity method now :
```private void launchInventoryActivity(Player currentPlayer) {
ArrayList<Item> itemsFound = new ArrayList<>();
Item lastItemAdded = currentPlayer.getLastItemAdded();
if (lastItemAdded != null) {
itemsFound.add(lastItemAdded);
}
ArrayList<Item> playerInventory = new ArrayList<>();
playerInventory.addAll(currentPlayer.getItems());
Intent intent = new Intent(GameActivity.this, InventoryActivity.class);
intent.putParcelableArrayListExtra("ITEMS_FOUND", itemsFound);
intent.putParcelableArrayListExtra("PLAYER_INVENTORY", playerInventory);
intent.putExtra("CURRENT_PLAYER", currentPlayer);
inventoryActivityResultLauncher.launch(intent);
}```
So in my main activity, when i need to call this activity i use launchInventoryActivity(currentPlayer); Finally, in my 2nd activity, when it's time to send back info to my first activity, i use this with, i guess, the correct intents we need to get :
```private void finishTurn() { int currentPlayerIndex = getIntent().getIntExtra("CURRENT_PLAYER_INDEX", 0); Intent intent = new Intent(); intent.putExtra("CURRENT_PLAYER_HEARTS", currentPlayer.getHearts()); intent.putExtra("CURRENT_PLAYER_INDEX", currentPlayerIndex + 1); intent.putExtra("CURRENT_PLAYER", currentPlayer); // Ajoutez le joueur actuel ici setResult(RESULT_OK, intent); finish(); }``` |
For example, if I have
```c
/* <…> */
int main(void)
{
int status;
pid_t pid;
char* arg[] = {"ls", "-l", "/usr/include", (char *)0};
if ((pid=fork()) == 0)
{
/* CODICE ESEGUITO DAL FIGLIO - CODE EXECUTED BY THE SON */
execv("/bin/ls", arg);
/* Si torna solo in caso di errore - Returns only in case of error */
exit(/* <…> */
```
Why in the line defining `char* arg[]` there is an element `(char *)0`? What is it? |
execv: What is (char *)0 in C? |
null |
I checked the docs:
> Snapshotting is effectively **“recording after the fact”**. Rather than starting recording at a specific point, snapshotting allows you to convert requests already received by WireMock into stub mappings.
If I'm reading it right, this should pass:
```java
package com.example.gatewaydemo.misc;
import java.util.List;
import com.github.tomakehurst.wiremock.junit5.WireMockRuntimeInfo;
import com.github.tomakehurst.wiremock.junit5.WireMockTest;
import com.github.tomakehurst.wiremock.stubbing.StubMapping;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.reactive.function.client.WebClient;
import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.ok;
import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
import static org.assertj.core.api.Assertions.assertThat;
@WireMockTest
public class GenericTest {
int port;
@BeforeEach
void setUp(WireMockRuntimeInfo info) {
port = info.getHttpPort();
}
@Test
void test(WireMockRuntimeInfo info) {
stubFor(get("/test").willReturn(ok()));
Mono<ResponseEntity<Void>> response = WebClient.builder()
.baseUrl("http://localhost:%d".formatted(port))
.build()
.get()
.uri("/test")
.retrieve()
.toBodilessEntity();
// passses
StepVerifier.create(response.map(ResponseEntity::getStatusCode))
.expectNext(HttpStatus.OK)
.verifyComplete();
// fails
List<StubMapping> stubMappings = info.getWireMock().takeSnapshotRecording();
assertThat(stubMappings).isNotEmpty();
}
}
```
But it doesn't
In the actual test, I need to assert on the request received by my "wire-mocked" endpoint. I hoped once I have a list of recorded endpoint calls, I could do something like this:
```java
String actualBody = (String) stubMappings.get(0).getRequest().getBodyPatterns().get(0).getValue();
assertThat(actualBody).isEqualTo(expectedBody);
```
I know about "startRecording", "stopRecording", but I prefer my tests short (as long as they stay well readable). So every line counts
Though, it doesn't work too so I figure it has nothing to do with snapshot recordings specifically
```java
@Test
void test(WireMockRuntimeInfo info) {
stubFor(get("/test").willReturn(ok()));
WireMock wireMock = info.getWireMock();
wireMock.startStubRecording();
Mono<ResponseEntity<Void>> response = WebClient.builder()
.baseUrl("http://localhost:%d".formatted(port))
.build()
.get()
.uri("/test")
.retrieve()
.toBodilessEntity();
// passses
StepVerifier.create(response.map(ResponseEntity::getStatusCode))
.expectNext(HttpStatus.OK)
.verifyComplete();
// fails
SnapshotRecordResult snapshotRecordResult = wireMock.stopStubRecording();
assertThat(snapshotRecordResult.getStubMappings()).isNotEmpty();
}
```
I searched through existing SO questions and found this [answer][1]. It demonstrates a completely different approach that involves `ServeEvent`s and assigning IDs to stubbings. Is it the only way to capture requests? If so, what is the recording feature for?
[1]: https://stackoverflow.com/a/75144784/23539854 |
{"Voters":[{"Id":213269,"DisplayName":"Jonas"},{"Id":16217248,"DisplayName":"CPlus"},{"Id":1940850,"DisplayName":"karel"}]} |
I'm studying about postfix increment operator in JAVA, and curious about why the result is `6` when coding like this.
```java
int b = 3;
b += b++;
System.out.println(b);
```
I think that due to the `+=` operator, `3` is added to `b`, making it `6`,
and then due to the `++` operator, `1` is added to `6`, resulting in `b` being `7`.
But the compile result showed me `6`.
Can someone explain why my understanding is incorrect? |
{"Voters":[{"Id":3689450,"DisplayName":"VLAZ"},{"Id":2756409,"DisplayName":"TylerH"},{"Id":1940850,"DisplayName":"karel"}],"SiteSpecificCloseReasonIds":[16]} |
Query (or LINQ in Entity Framework) for getting user's rank |
I've just installed Wordpress 6.4.3 & MAMP and managed to edit functions.php and save my changes.
When I tried to make more changes Wordpress started displaying the following error message:
> Something went wrong. Your change may not have been saved. Please try again. There is also a chance that you may need to manually fix and upload the file over FTP.
What I have done:
- I've checked permissions of the file and gave read and write access to everyone on my localhost.
- Restarted the server
but I am still running into the same error message. |
Cannot edit functions.php anymore on localhost |
|wordpress|mamp| |
null |
I've just installed Wordpress 6.4.3 & MAMP and managed to edit functions.php and saved my changes.
When I tried to make more changes to the file, Wordpress started displaying the following error message:
> Something went wrong. Your change may not have been saved. Please try again. There is also a chance that you may need to manually fix and upload the file over FTP.
What I have done:
- I've checked permissions of the file and gave read and write access to everyone on my localhost.
- Restarted the server
but I am still running into the same error message. |
Not sure how you connect your ```mutate``` line to your dataset, given that it already has a column called ```gender_final``` but it seems to work just like you expected. In my suggestion, I have just called the new column ```gender_final2``` because I didn't want to change your original data.
```
library(dplyr)
# Use df and conditional mutate to create gender_final2
df <- df %>%
mutate(gender_final2 = ifelse(is_hoh == "yes", hoh_gender, resp_gender))
df
id resp_gender hoh_gender is_hoh gender_final gender_final2
<dbl> <chr> <chr> <chr> <chr> <chr>
1 1 female male no male female
2 2 male male no male male
3 3 female male no male female
4 4 female male yes female male
5 5 male female no female male
6 6 female male no male female
7 7 male female yes male female
8 8 male female no female male
9 9 female male no male female
10 10 female male yes female male
``` |
I am currently working on implementing a JavaScript code that aims to read and parse .npz files generated from Python's numpy, specified by a JSON file. These .npz files contain arrays of floating values (a ML model weights and biases as arrays). However, I am encountering errors while running the script. What is causing the issues in my implementation? How to resolve them?
Here is the code I have written so far:
```
import * as npz from 'npyz';
import fs from 'fs';
import * as np from 'numjs';
async function printWeightsAndBiases() {
// Load .npz file
const loadedData = await npz.load('weights_biases.npz');
const raw_data = loadedData.data;
// Load indices from .json (assuming the file is named 'model_weights.json')
const jsonContent = fs.readFileSync('model_weights.json', 'utf8');
const indices = JSON.parse(jsonContent);
// Loop through each layer name in the indices
for (const layerName in indices) {
if (layerName.endsWith('weight')) {
const shape = indices[layerName]['shape'];
const weightData = np
.array(
raw_data.slice(
indices[layerName]['offset'],
indices[layerName]['offset'] + shape.reduce((a, b) => a * b)
)
)
.reshape(shape);
console.log(`**Weights for layer: ${layerName.slice(0, -7)}**`);
console.log(weightData);
} else if (layerName.endsWith('bias')) {
const shape = indices[layerName]['shape'];
const biasData = np
.array(
raw_data.slice(
indices[layerName]['offset'],
indices[layerName]['offset'] + shape[0]
)
);
console.log(`**Biases for layer: ${layerName.slice(0, -4)}**`);
console.log(biasData);
}
}
}
printWeightsAndBiases().then(() => console.log('Weights and biases printed!'));
```
And here is a sample JSON file:
```
{
"conv_mid.0": {
"weight": "conv_mid.0_weight.npy",
"bias": "conv_mid.0_bias.npy"
},
"conv_mid.1": {
"weight": "conv_mid.1_weight.npy",
"bias": "conv_mid.1_bias.npy"
},
"conv_mid.2": {
"weight": "conv_mid.2_weight.npy",
"bias": "conv_mid.2_bias.npy"
},
"conv_mid.3": {
"weight": "conv_mid.3_weight.npy",
"bias": "conv_mid.3_bias.npy"
}
}
```
And here is the error I get:
```
retrieve-file.mjs:20
raw_data.slice(
^
TypeError: Cannot read properties of undefined (reading 'slice')
at printWeightsAndBiases (file:///C:/retrieve-file.mjs:20:20)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
```
For context, here is how I generate the .npy files:
```
import torch
import json
import numpy as np
state_dict = torch.load('network.pth')
# Extract the 'params' OrderedDict from the state_dict
params_dict = state_dict['params']
indices = {}
for name, param in params_dict.items():
layer_name, param_type = name.rsplit('.', 1)
if layer_name not in indices:
indices[layer_name] = {}
if param_type == 'weight':
# Store the weight data as a numpy array
data = np.array(param.tolist(), dtype=np.float32)
np.save(f"{layer_name}_weight.npy", data)
indices[layer_name]['weight'] = f"{layer_name}_weight.npy"
elif param_type == 'bias':
# Store the bias data as a numpy array
data = np.array(param.tolist(), dtype=np.float32)
np.save(f"{layer_name}_bias.npy", data)
indices[layer_name]['bias'] = f"{layer_name}_bias.npy"
json_data = json.dumps(indices, indent=4)
with open('model_weights.json', 'w') as f:
f.write(json_data)
print("JSON data and weights/biases saved to model_weights.json and .npy files")
print(json_data)
```
UPDATE: when I print `loadedData` this is the output:
{
'conv_head.bias': [
-0.00030437775421887636,
0.0042824335396289825,
0.0022352728992700577,
-0.0019111455185338855,
0.00017375686729792506,
0.0017428217688575387,
0.005364884156733751,
0.0028239202219992876
],
'conv_mid.1.bias': [
-0.002030380303040147,
0.009842530824244022,
-0.0008345193928107619,
-0.007043828722089529,
-0.00633968273177743,
-0.006188599392771721,
-0.0018206692766398191,
0.0037471423856914043
],
'conv_head.weight': [
[ [Array], [Array], [Array] ],
[ [Array], [Array], [Array] ],
[ [Array], [Array], [Array] ],
[ [Array], [Array], [Array] ],
[ [Array], [Array], [Array] ],
[ [Array], [Array], [Array] ],
[ [Array], [Array], [Array] ],
[ [Array], [Array], [Array] ]
],
'conv_mid.0.weight': [
[
[Array], [Array], [Array],
[Array], [Array], [Array],
[Array], [Array], [Array],
[Array], [Array], [Array],
[Array], [Array], [Array],
[Array]
],
[
[Array], [Array], [Array],
[Array], [Array], [Array],
[Array], [Array], [Array],
[Array], [Array], [Array],
[Array], [Array], [Array],
[Array]
], ...
|
The easiest way is to use the index of the rows you need:
ids=which(df$Hospital %in% c('Other', 'Missing', 'Total') #which rows should be at the bottom of a dataframe
df2=df[ids,] # create temporaty dataframe with this rows only;
df=df[-c(ids),] #remove them from your dataframe
df=rbind(df,df2) # append this rows to the bottom.
#Or,probably, easier:
ids=which(df$Hospital %in% c('Other', 'Missing', 'Total')
df=rbind(df[-c(ids),],df[ids,]) |
I have cretaed a django app, which uses weasyprint to convert html to pdf. This needed GTK3 to be installed on my local system. Now I'm not able to deploy on FL0. I checked the docs which said problems with deployment might be because the code couldn't be run properly. When I first used weasyprint, I was not able to run the app until I installed GTK3 on my laptop. So, I guess this is the issue. Is there any way to do this other than using docker. Or are there any libraries that does not use GTK3.
I'll provide any details required. If anyone needs.
Thanks.
I'm getting a CrashLoopBackoff error ( Back-off restarting failed ) on flow while deploying. It builds properly. But while deploying, I'm getting this error.
I have an option of containerizing the application. But I'm not able to do so at the moment for some other reasons. That's why I'm asking this |
`jax.linear_util` was [deprecated in JAX v0.4.16](https://jax.readthedocs.io/en/latest/changelog.html#jax-0-4-16-sept-18-2023) and [removed in JAX v0.4.24](https://jax.readthedocs.io/en/latest/changelog.html#jax-0-4-24-feb-6-2024).
It appears that `flax` is the source of the `linear_util` import, meaning that you are using an older flax version with a newer jax version.
To fix your issue, you'll either need to install an older version of JAX which still has `jax.linear_util`, or update to a newer version of `flax` which is compatible with more recent JAX versions. |
I'm going to recover my Facebook account but I just forget my email address, can anyone telling me how can I show this full email address. I'm attaching an screenshot please have a looks
Can I show my full email address was |
How can I look this email address |
|facebook|email|recovery| |
null |
```
<?php
if ($_SERVER['REQUEST_METHOD']== "POST") {
if(isset($_POST['submit']){
echo $_POST['vid'];
}}
```
// This part of the code recieves data from the form on the $_POST variable which i dont want in the post variable but i need in the $_FILES variable
```
if ($_SERVER['REQUEST_METHOD']== "POST") {
if(isset($_POST['submit']){
echo $_FILES['vid']['tmp_name'];
}}
```
// but here i get the Undefined index in the $_FILES variable and is null
?>
```
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" enctype="mutlipart/form-data">
<div class="row">
<div class="col-6">
<div class="form-group">
<label for="formGroupExampleInput" >عنوان الدرس </label>
<input type="text" class="form-control" id="formGroupExampleInput" placeholder="عنوان الدرس" name="lsn">
</div>
</div>
<div class="col-6">
<div class="form-group">
<label for="formGroupExampleInput">رقم الدرس </label>
<input type="text" class="form-control" id="formGroupExampleInput" placeholder="رقم الدرس " name="no">
</div>
</div>
</div>
<div class="row">
<div class="col-6">
<input type="file" id="uploadbtn" name="vid" value=""/> // this uploads video in to the file variable
<label for="basic-url" class="form-labe4" > ملخص الدرس </label>
<label class="lbtn" for="uploadbtn">
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="currentColor" class="bi ii bi-upload" viewBox="0 0 16 16">
<path d="M.5 9.9a.5.5 0 0 1 .5.5v2.5a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-2.5a.5.5 0 0 1 1 0v2.5a2 2 0 0 1-2 2H2a2 2 0 0 1-2-2v-2.5a.5.5 0 0 1 .5-.5"/>
<path d="M7.646 1.146a.5.5 0 0 1 .708 0l3 3a.5.5 0 0 1-.708.708L8.5 2.707V11.5a.5.5 0 0 1-1 0V2.707L5.354 4.854a.5.5 0 1 1-.708-.708z"/>
</svg><span></span></label>
</div>
<div class="col-6">
<input type="file" id="uploadbt" name="book" value=""> this file uploads a book of pdf
<label for="basic-url" class="form-labe4" > الكتاب الدرس </label>
<label class="lbtn" for="uploadbt">
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="currentColor" class="bi ii bi-upload" viewBox="0 0 16 16">
<path d="M.5 9.9a.5.5 0 0 1 .5.5v2.5a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-2.5a.5.5 0 0 1 1 0v2.5a2 2 0 0 1-2 2H2a2 2 0 0 1-2-2v-2.5a.5.5 0 0 1 .5-.5"/>
<path d="M7.646 1.146a.5.5 0 0 1 .708 0l3 3a.5.5 0 0 1-.708.708L8.5 2.707V11.5a.5.5 0 0 1-1 0V2.707L5.354 4.854a.5.5 0 1 1-.708-.708z"/>
</svg><span></span></label>
</div></div>
<input class="bttn-n" type="submit" name="submit"> رفع الدرس // this is the submit button the uploads
</input>
</form>
</div>
</div></div>
</div>
```
This is the form HTML code
To be assure that its not a php problem i tried the same idea in a simple form in a different page without any css or javascript and it worked fine, What could be the problem in the html? |
Good Day to the readers.
I have a website for url//link shortening, that uses Google Spreadsheets and Google App Scripts,
I have been trying to find a way to redirect the users when they type my link, but app scripts either tries to load the redirection URL in an iframe which gets rejected by most sites these days or I have to open up a new tab using window.open(url, _blank); which acts as a pop up that has to require permission from the user to open up the first time.
Now i'm aware that I can create an html button which will then redirect them, but thats a really slow and tedious process for a url shortener.
So if anybody is aware on how I can redirect the user automatically instead of making a click button or opening a new tab with popup please do share.
Help is appreciated!
Here is the link to my website that shortens links and then redirects:
>https://surl.jayeshrocks.com/
Heres the doGet function for the Code.gs script
```
function doGet(e) {
var slug = e.queryString;
if (slug == '') {
var title = 'Dashboard | ' + serviceName;
return HtmlService.createHtmlOutputFromFile('Dashboard').setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL).setTitle(title);
} else {
var notFound = false;
var redirectsData = getRedirects();
for (var i = 0; i < redirectsData.length; i++) {
if (slug == redirectsData[i].slug) {
var redirectURL = redirectsData[i].longURL;
var html = "<body>Redirected! You can now close this tab.</body><script>window.open('" + redirectURL + "','_blank');</script>";
return HtmlService.createHtmlOutput(html).setTitle('Redirected!');
break;
} else {
notFound = true;
}
}
if (notFound) {
var html = "<body>No redirections found! Redirected to Link Loom. You can now close this tab.</body><script>alert('No redirects found!');window.open('" + customDomain + "','_blank');</script>";
return HtmlService.createHtmlOutput(html).setTitle('Error 404');
}
}
}
```
If you would like to check out my full script, here is the link:
>https://script.google.com/d/1lAwOw4Os0bZI5Ze1orJd-Crjg_MkKt0WUavO87VCME07C6QdgN7kxxQQ/edit?usp=sharing |