instruction stringlengths 0 30k ⌀ |
|---|
I currently have an issue with a client's website that uses Twitter Bootstrap 3.2 with LESS. The technical lead at my client has flagged that Google Pagespeed Insights is showing a red flag against several of the CSS files in the site causing render blocking issues:
https://developers.google.com/speed/pagespeed/insights/?url=http%3A%2F%2Fwww.ukessays.com%2Fservices%2Fessay-writing-service.php&tab=mobile
However, the above the fold content on the majority of pages contains almost all of the CSS elements used in the site so the idea of "in-lining" all of the CSS to render the above the fold content seems completely ridiculous. To make things worse the most important pages in the site have the lowest speed scores:
`http://www.ukessays.com/services/essay-writing-service.php : 71/100`
vs
`http://www.ukessays.com/essay-help/referencing/ : 77/100`
As the website was re-built using Twitter Bootstrap to make it more responsive I'm left looking a bit of an idiot that it now scores less than the previous non-responsive website. The fact that the CSS is compiled using LESS has effective prevented us from implementing any dynamic solution to the problem server-side
Has anyone come across this problem and if so can anyone recommend a simple fix / plugin that could solve this issue?
The only solution we have so far is to take the entire of the above the fold content, from the H! tag of "essay writing service" down to the first call to action and save this is a completely isolated div structure that doesn't flow with the rest of the page.
|
Brand new to programming. Following a tutorial on C, where the creator uses these 3 commands in the terminal: <br>
code hello.c
make hello
./hello
The `make hello` command doesn't work on my end for some reason. Giving me this error instead:
make : The term 'make' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and
try again.
At line:1 char:1
<br>
make hello
+ CategoryInfo : ObjectNotFound: (make:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
EDIT: I managed to get through the first error. I didn't have make installed, and now I have this error:<br>
cc hello.c -o hello
process_begin: CreateProcess(NULL, cc hello.c -o hello, ...) failed.
make (e=2): The system cannot find the file specified.
make: *** [<builtin>: hello] Error 2
I tried looking this up online, but since I just got started I have no idea what any of this means.
I was expecting the command to work. |
Invalid or unexpected token
at internalCompileFunction (node:internal/vm:73:18)
at wrapSafe (node:internal/modules/cjs/loader:1178:20)
at Module._compile (node:internal/modules/cjs/loader:1220:27)
at Module._extensions..js (node:internal/modules/cjs/loader:1310:10)
at Module.load (node:internal/modules/cjs/loader:1119:32)
at Module._load (node:internal/modules/cjs/loader:960:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:86:12)
at node:internal/main/run_main_module:23:47
iinstall packages figlet and requires that but when i am trying to run in shownig error |
For someone looking for a solution with Ionic v7, this is what you can do to apply custom CSS for toastController.
1. Specify `cssClass` property in `toastController.create()`.
const toast = await this.toastController.create({
message: 'Your Toast Message',
duration: 2000,
cssClass: 'toast-success'
});
2. In your `global.scss`, specify your styles.
ion-toast.toast-success {
&::part(container) {
background: #24a148;
color: #fff;
border-color: #24a148;
border-radius: 4px;
}
} |
I would increase range and use additional value as exception:
```cs
var index = Random.Next(2, 11);
if (index == 10)
index = 15;
``` |
This is the column part which i have declared.
`
{
title: 'Tags',
key: 'tags',
dataIndex: 'tags',
render: (_,{tags})=>{
<>
{tags.map((tag)=>{
return(
<Tag key={tag}>{tag}</Tag>
);
})}
</>
}
}
`
I have tried the code too that is given in antd official site. why this way doesn't work? |
Creating a module for this purpose is inevitable and not a strenuous task at all. All u need is a `package.json` with an `exports` field to limit which submodules can be loaded from within the package. From the [official Node.js docs](https://nodejs.org/api/packages.html#exports):
> The "exports" field allows defining the entry points of a package when imported by name loaded via a node_modules lookup. It is an alternative to the "main" that can support defining subpath exports and conditional exports while encapsulating internal unexported modules
⚠️ Note that all paths defined in the `"exports"` must be relative file URLs starting with `./` except for the default one `.` (as mentioned in the official doc).
So in your case, the `package.json` inside your `facade` folder would be:
```json
{
"name": "@facade",
"private": true,
"version": "0.0.0",
"exports": {
"./B.tsx": "./B.tsx"
}
}
```
Now the external code outside of the `facade` folder (a.k.a the `@facade` package) can only `import {B} from "@facade/B.tsx";`. Both `@facade/A.tsx` and `"@facade/C.tsx"` are completely inaccessible to the external code.
[Another example from AWS](https://github.com/aws-amplify/amplify-ui/blob/d0b13796ad5490a4381009b32c76c8c65e7e0c16/packages/react/package.json#L16)
See [my bonus tip](https://stackoverflow.com/a/78251743/8138591) for additional ways to clearly communicate this intention. |
Try this regex `^$|(?!.*googlebot)(bot|crawl|spider)` |
When i run my app on FireFox, the console returns me an error : (in promise) TypeError: NetworkError when attempting to fetch resource.
I understand what's that mean but i have no clue how to fix it. Besides everythings run well on the others browsers...( chrome, Edge ..)
anyone has an idea?
here my code :
`export function fetchManager(url, data) {
// Objet littéral des paramètres
const options= {
mode: 'no-cors',
method:'POST',
header: {
'Content-Type': 'application/json'},
body: JSON.stringify(data)
}
// Appel et récupère le retour de fetch
let reponseData = fetch(url, options)
return reponseData;
}`
and here the return of the firefox's console :
Uncaught (in promise) TypeError: NetworkError when attempting to fetch resource.
Thank you all.
I try to check firefox's setting but without success.. |
{"OriginalQuestionIds":[129677],"Voters":[{"Id":285587,"DisplayName":"Your Common Sense","BindingReason":{"GoldTagBadge":"php"}}]} |
I'm encountering an issue with building a responsive webpage. When testing the page's responsiveness, the width extends beyond the device's width for some reason.
I've tried removing various parts of the code, and I've found that the "introduction" div seems to be causing the problem. When I remove it, the webpage returns to the normal width. Can anyone help me identify what's wrong with my code?
Here's the relevant HTML and CSS for the introduction div :-
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-css -->
.introduction {
position: relative;
background: grey;
}
.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 width to 70% */
@media screen and (max-width: 1150px) {
.col img {
height: 70%;
}
}
.gap {
height: 100px;
}
<!-- language: lang-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="https://mrwallpaper.com/images/hd/advanced-information-technology-engineering-system-degars3km1qclrsn.jpg" alt="Women In IT">
</div>
</div>
</div>
<!-- end snippet -->
|
void excelsave()
{
try
{
ApplicationClass app = new ApplicationClass(); // the Excel application.
Workbook book = null;
Worksheet sheet = null;
Range range = null;
// the range object is used to hold the data
app.Visible = false;
app.ScreenUpdating = false;
app.DisplayAlerts = false;
string execPath =
Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase);
book = app.Workbooks.Open(@"E:\SSIS\ABC\Book1.xls",
Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value, Missing.Value);
sheet = (Worksheet)book.Worksheets[1];
range = sheet.get_Range("A1", Missing.Value);
range.Columns.ColumnWidth = 22.34;
range = sheet.get_Range("B1", Missing.Value);
range.Columns.ColumnWidth = 22.34;
book.SaveAs(@"E:\SSIS\ABC\Book1.xls", Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, XlSaveAsAccessMode.xlExclusive,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
}
catch (Exception ex)
{
}
}
Here I am opening an Excel sheet trying to increase the column width and need to make the column headers as bold and save the document. Right now, the document is not getting saved. I am using VS 2008 and C# 3.5.
Is there anything that I am doing wrong here?
|
JavaFX SwingNode instantiation fails with exception |
|javafx| |
null |
I am using model = 'filipealmeida/Mistral-7B-Instruct-v0.1-sharded' and quantize it in 4_bit
with the following function.
```
def load_quantized_model(model_name: str):
"""
:param model_name: Name or path of the model to be loaded.
:return: Loaded quantized model.
"""
bnb_config = BitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_use_double_quant=True,
bnb_4bit_quant_type="nf4",
bnb_4bit_compute_dtype=torch.bfloat16
)
model = AutoModelForCausalLM.from_pretrained(
model_name,
load_in_4bit=True,
torch_dtype=torch.bfloat16,
quantization_config=bnb_config
)
return model
```
When I load the file I get the following error message:
```
ValueError Traceback (most recent call last)
Cell In[12], line 1
----> 1 model = load_quantized_model(model_name)
Cell In[10], line 13
2 """
3 :param model_name: Name or path of the model to be loaded.
4 :return: Loaded quantized model.
5 """
6 bnb_config = BitsAndBytesConfig(
7 load_in_4bit=True,
8 bnb_4bit_use_double_quant=True,
9 bnb_4bit_quant_type="nf4",
10 bnb_4bit_compute_dtype=torch.bfloat16
11 )
---> 13 model = AutoModelForCausalLM.from_pretrained(
14 model_name,
15 load_in_4bit=True,
16 torch_dtype=torch.bfloat16,
17 quantization_config=bnb_config
18 )
20 return model
File ~/miniconda3/envs/peft/lib/python3.11/site-packages/transformers/models/auto/auto_factory.py:563, in _BaseAutoModelClass.from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs)
...
2981 )
2983 # preparing BitsAndBytesConfig from kwargs
2984 config_dict = {k: v for k, v in kwargs.items() if k in inspect.signature(BitsAndBytesConfig).parameters}
ValueError: You can't pass `load_in_4bit`or `load_in_8bit` as a kwarg when passing `quantization_config` argument at the same time.
Output is truncated. View as a scrollable element or open in a text editor. Adjust cell output settings...
```
I checked the Class _BaseAutoModelClass.from_pretrained but I cannot find where '8_bit ' is set. What am I expected to do to have the model loaded correctly in 4-bit ?
I tried to change the bnb_config to adapt it to 8_bit but I could not solve the problem. |
Quantization 4 bit and 8 bit - error in 'quantization_config' |
|gpu|local|large-language-model|quantization|8-bit| |
null |
im new to nodejs and i was just wants to update integer in mongodb but i con't do so.
i dont understand what im doing wrong here.no matter what i try findAndUpdate only returning original document without updating it. I also tried typecasting integer value but still didn't work.
```const id = "6606ff9e1a5c69a06612219b"
// const objid = new mongoose.Types.ObjectId(id)
export const UpdateMoisture = async (req, res) => {
try {
const moist = req.body.moisture
const update = {$set:{"moisture":parseInt(moist)}}
const result = await Sensor_data.findOneAndUpdate(
{_id:id},
update,
{
new:true
}
)
console.log(result)
// Return the updated data
return res.status(200).json({ result, success: true });
} catch (error) {
// Log and return error response
console.error('Error while updating moisture:', error);
return res.status(500).json({ msg: 'Error while updating moisture data', error: error, success: false });
}
}```
|
Registration to be configured in ASP.NET Core 8 |
|c#|asp.net-core|.net-8.0| |
Finally found a solution.
The problem was coming from the the next.js SSR.
I needed to add `"use-client;"` in the top of every of my library components.
I did this with `rollup-plugin-banner2` package:
```
banner((chunck) => {
if(!bannedUseClientFiles.includes(chunck.fileName)){
return "'use client';\n";
}
return undefined
})
``` |
I suspect you are getting an uncaught `Exception` from your code:
config.write(config_file)
The `write()` method takes no arguments as it writes to the last read file.
Try changing that line to:
config.write() |
{"OriginalQuestionIds":[6339057],"Voters":[{"Id":5577765,"DisplayName":"Rabbid76","BindingReason":{"GoldTagBadge":"pygame"}}]} |
|javascript|jquery|asp-classic| |
I use segmented picker in iOS which contains few items. When user tap on not selected item this item becomes selected. Some of items can contain sub items. So when user tap on already selected type I need to show modal window with subitems for choosing one of them.
But taps on already selected items of segmented picker are not handling. I tried to use "long press" but it not works as well.
I would like to use native iOS design that's why I don't want use "buttons" instead segmented picker.
So the question is how I can handle tap on already selected item of segmented picker for showing sub items to choosing one of them? It can be "long press" or other alternative which will be intuitive for user.
```
import SwiftUI
struct CustomSegmentedPicker: View {
@State private var showModalSelectD: Bool = false
enum periods {
case A, B, C, D, All
}
@State var predefinedPeriod: periods = periods.All
@State var predefinedPeriodC: String = "C1"
@State var predefinedPeriodD: String = "D1"
func predefinedPeriodSelected(predefinedPeriod: periods) {
if predefinedPeriod == .D {
showModalSelectD.toggle()
}
}
var body: some View {
ZStack {
Color.clear
.sheet(isPresented: $showModalSelectD, content: {
List {
Picker("D", selection: $predefinedPeriodD) {
Text("D1").tag("D1")
Text("D2").tag("D2")
Text("D3").tag("D3")
}
.pickerStyle(.inline)
}
})
VStack {
HStack {
Picker("Please choose a currency", selection: $predefinedPeriod) {
Text("A").tag(periods.A)
Text("B").tag(periods.B)
Text("C").tag(periods.C)
Text("D (\(predefinedPeriodD))").tag(periods.D)
.contentShape(Rectangle())
.simultaneousGesture(LongPressGesture().onEnded { _ in
print("Got Long Press")
showModalSelectD.toggle()
})
.simultaneousGesture(TapGesture().onEnded{
print("Got Tap")
showModalSelectD.toggle()
})
Text("All").tag(periods.All)
}.pickerStyle(SegmentedPickerStyle())
.onChange(of: predefinedPeriod, perform: { (value) in
predefinedPeriodSelected(predefinedPeriod: value)
})
}
}
}
}
}
``` |
There is a free API you can use with JavaScript to do this. I wear it and it works like a glove.
Basically you create a key (namespace) and each post for this route it increments 1. Then you can restore this count for display.
https://javascript.plainenglish.io/how-to-count-page-views-with-the-count-api-afc9369c1f8f
https://countapi.xyz/ |
{"OriginalQuestionIds":[27852613],"Voters":[{"Id":7884305,"DisplayName":"Chayim Friedman","BindingReason":{"GoldTagBadge":"rust"}}]} |
I have 2 SQL queries.
Query #1:
SELECT
SUM(PrincipalBalance)
FROM (
SELECT
lt.AccountId,
SUM(CASE
WHEN TransactionTypeId IN (1)
THEN PrincipalPortionAmount
ELSE 0
END)
- SUM(CASE
WHEN TransactionTypeId NOT IN (1, 2)
THEN PrincipalPortionAmount
ELSE 0
END) AS PrincipalBalance
FROM
program.LoanTransaction lt
INNER JOIN
program.LoanAccount la ON lt.AccountId = la.Id
WHERE
BranchId = 301
AND TransactionDate <= 20231231000000
AND la.STATUS <> - 1
GROUP BY
lt.AccountId
HAVING
SUM(Debit - Credit) > 1
) T
Query #2:
SELECT
ISNULL(SUM(CASE
WHEN TransactionTypeId IN (1)
THEN PrincipalPortionAmount
ELSE 0
END), 0)
- ISNULL(SUM(CASE
WHEN TransactionTypeId IN (43, 38, 4, 12, 7, 10)
THEN PrincipalPortionAmount
ELSE 0
END), 0)
FROM
program.LoanTransaction lt
INNER JOIN
program.LoanAccount la ON lt.AccountId = la.Id
WHERE
BranchId = 301
AND TransactionDate <= 20231231000000
AND la.Status <> -1
Query #1 result is<br> `80773498.0599999`
Query #2 result is<br> `81060946.8400006`
But both results should be the same. I don't get it, why the differences? How can I find out what is causing the differences?
|
|java|multithreading|concurrency|java-21|structured-concurrency| |
{"Voters":[{"Id":476,"DisplayName":"deceze"}],"SiteSpecificCloseReasonIds":[11]} |
You should place .sql file inside the resource folder, so that H2 database will be initialized as per your requirement |
Full source code: https://github.com/remoteworkerid/backendgolang/blob/feature/RWIDPF-13/server.go
My code works for DEV_MODE==true. But it doesn't for DEV_MODE==false.
PrecompileTemplate:
```
func precompileTemplate() {
// Menggunakan template.ParseGlob untuk memuat semua file template
templates = template.Must(template.ParseGlob("static/*.html"))
templateNames := templates.Templates()
fmt.Println("Nama-nama template yang terdaftar:")
for _, t := range templateNames {
fmt.Println(t.Name())
}
}
```
HomeHandler:
```
if devMode {
tmpl, err := template.ParseFiles("static/base.html", "static/daftar.html")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
err = tmpl.ExecuteTemplate(w, "base.html", data)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
} else {
log.Println("Production code daftar")
err = templates.ExecuteTemplate(w, "base.html", data)
if err != nil {
log.Println("Ada error di daftar")
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
```
My base.html excerpt:
```
<div id="content" class="p-5">
{{block "content" .}}
</div>
```
My daftar.html (full):
```
{{ define "content" }}
<h1>Daftar RWID</h1>
{{ end }}
```
How do you render a precompiled template for subtemplate case? I kinda expecting the ExecuteTemplate will accept three parameter: base, sub and data. But as its' only one.. I am guessing `daftar.html` (a subtemplate). But, in daftar.html I didn't mention the superclass.. |
Are there any advanced books or tutorials on programming the Arm64?
Most of the books out there spend the first five chapters explaining what a register is and what memory is. I’ve written code in 5 other assembly languages, so I really don’t need that.
The official Arm documentation seems more like an encyclopedia article for each instruction rather than a practical guide to writing code. The FP and Neon documentation is particular awful.
Is there something in between? |
Advanced Arm64 books or tutorials? |
|arm64| |
To be honest, I'm not entirely clear on your question. If I understand correctly, you're looking to categorize values into intervals of 50, such as 1-50, 51-100, 101-150, and so on. After that, you want to group the IDs based on these intervals and sort them according to the "sort_me" column. Beside this, you want to count the number of ids in each group and discard those with 1 or less. If this is what you are looking for then you may try the following query,
WITH Intervals AS (
SELECT
id,
CASE
WHEN value BETWEEN 1 AND 50 THEN '1-50'
WHEN value BETWEEN 51 AND 100 THEN '51-100'
WHEN value BETWEEN 101 AND 150 THEN '101-150'
-- Add more intervals as needed
ELSE 'Unknown'
END AS value_interval,
sort_me
FROM
your_table
)
SELECT
value_interval,
GROUP_CONCAT(id ORDER BY sort_me) AS grouped_ids,
COUNT(*) AS num_ids
FROM
Intervals
GROUP BY
value_interval
HAVING
num_ids > 1
ORDER BY
value_interval;
There is no straight answer for your query as far as I know. Well as I said, I might be interpreting your question wrong.
|
My problem is given as follows:
[![][1]][1]
```python
import sympy as sp
p = sp.symbols('p')
I_p = sp.Identity(p)
C = sp.BlockMatrix([[I_p, I_p], [I_p, -I_p]])
Sigma_1 = sp.MatrixSymbol('Sigma_1', p, p)
Sigma_2 = sp.MatrixSymbol('Sigma_2', p, p)
Sigma = sp.BlockMatrix([[Sigma_1, Sigma_2], [Sigma_2, Sigma_1]])
C_Sigma_C_transpose = C * Sigma * C.T
print(C_Sigma_C_transpose)
## Matrix([
## [I, I],
## [I, -I]])*Matrix([
## [Sigma_1, Sigma_2],
## [Sigma_2, Sigma_1]])*Matrix([
## [I, I],
## [I, -I]])
```
The result does not match the expected output. How can I correct it?
[1]: https://i.stack.imgur.com/XlrcJ.png |
Using the sympy module to compute the matrix multiplication involving symbols |
|python|matrix|sympy|matrix-multiplication| |
You cannot write a function definition within JSX. You can only write expressions.
This is not allowed within JSX:
<pre><code>{async function fetchURL(){/*••• Function definition •••*/}}</code></pre>
But this is:
<pre><code>{fetchURL()}</code></pre> |
I had the same problem and I solve adding "withXSRFToken: true" to axios create. |
I'm try to install OHS, but there's an error: INST-07551: Not all dependent featuresets for install type "Collocated HTTP Server (Managed through WebLogic server)" could be found. The following prerequisites were found t
o be missing:
wls_server - 12.2.1.4.0em_fmc - 12.2.1.4.0
My version of weblogic is 14.1.1 and I install the plugisng for this version (mod_wl_24.so, libdms2.so and libonssys.so)
I install the plugisng for this version (mod_wl_24.so, libdms2.so and libonssys.so) |
Save an Excel file in C# |
In main you have (with some other stuff)
bool ID;
std::cin >> ID;
So `ID` is declared as a boolean (true or false), and you read into, but you enter `151`, which is not a valid boolean. Depending on your flags, `1` might be, but that will leave `51` to still be input. Regardless, when you then call idcheck, it will either have `cin` in a fail state, or will have some data to read, so the `cin >> checkC` will return immediately.
Always make sure that your data input is in the form expected, and check cin to make sure there hasn't been an input failure. |
` * What went wrong:
A problem occuremphasized textred configuring project ':cloud_firestore'.
> Could not resolve all files for configuration ':cloud_firestore:classpath'.
> Could not download builder-7.0.2.jar (com.android.tools.build:builder:7.0.2)
> Could not get resource 'https://dl.google.com/dl/android/maven2/com/android/tools/build/builder/7.0.2/builder-7.0.2.jar'.
> Could not GET 'https://dl.google.com/dl/android/maven2/com/android/tools/build/builder/7.0.2/builder-7.0.2.jar'.
> The server may not support the client's requested TLS protocol versions: (TLSv1.2, TLSv1.3). You may need to configure the client to allow other protocols to be used. See: https://docs.gradle.org/7.4/userguide/build_environment.html#gradle_system_properties
> Remote host terminated the handshake
> Failed to notify project evaluation listener.
> Could not get unknown property 'android' for project ':cloud_firestore' of type org.gradle.api.Project.
> Could not find method implementation() for arguments [project ':firebase_core'] on object of type org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler.
> Could not get unknown property 'android' for project ':cloud_firestore' of type org.gradle.api.Project.`
I try to upgrade the dependencies
flutter pub upgrade
|
I'm trying to install "Sparkpost" package with pip. The installation is finished, im import it and then I get this error: No module named 'sparkpost'
from sparkpost import SparkPost
My virtual enviroment is working totally fine....
I follow this guide: https://pypi.org/project/sparkpost/ |
No module named 'sparkpost' |
|python|api|sparkpost| |
I am using Keycloak (`24.0.2`) as a standalone self-registration app (with some custom fields) for a small non-profit organization. Keycloak runs as docker behind nginx and is served under `keycloak.myorganization.com`. I have two realms: `master` (the default one) and `members` (where members will login/register).
Now, I would like to have users automatically forwarded to the "members" login/registration upon entering the base path. I set `Frontend URL` for the master realm to `keycloak.myorganization.com` and to `members.myorganization.com` for the members realm.
I also modified the docker environment variables:
```
KC_HOSTNAME=members.myorganization.com
KC_HOSTNAME_ADMIN=keycloak.myorganization.com
```
Nginx does the SSL termination and uses `proxy_pass` to forward everything to localhost/docker for both `members.myorganization.com` and `keycloak.myorganization.com`.
However, when I open [https://members.myorganization.com](https://members.myorganization.com), I get forwarded to the admin/root console, not the members realm login, which is available under [https://members.myorganization.com/realms/members/account/](https://members.myorganization.com/realms/members/account/).
How can I directly forward [https://members.myorganization.com](https://members.myorganization.com) to [https://members.myorganization.com/realms/members/account/](https://members.myorganization.com/realms/members/account/) ?
In the [Migration Guide](https://www.keycloak.org/docs/latest/upgrading/index.html), it says:
> If the Admin Console is enabled, the welcome page will automatically redirect to it if the administrative user already exists. This behavior can be modified by setting the `redirectToAdmin` in your `theme.properties` file. By default, the property is set to `false`, unless you are extending the built-in theme, in which case, the property is set to `true`.
Does this mean I will have to create/override the theme to modify the redirect behavior? |
(in promise) TypeError: NetworkError when attempting to fetch resource |
|javascript|firefox|browser|module|fetch| |
null |
If you're writing something that does "the same thing, with just one thing changing at each step", that's a loop. You don't use separate `if` statements. Not even "when you're lazy": being lazy is an _excellent_ property to have when you're a programmer, because it means you want to do as little work as possible. Of course, in this case that means "why am I even doing this, [`npm install marked`](https://www.npmjs.com/package/marked), oh look I'm done", but even if you insist on implementing a markdown parser yourself (sometimes, just writing code to see if you can is all the justification you need) you don't use a sequence of `if` statements, it takes more time to write, and takes more time to maintain/update.
However, even if you _do_ use `if` statements, resolve them either such that you handle "the largest thing first", to ensure there's no fall-through, _or_ with if-else statements, so there's no fall-though. (And based on your question about whether to use a switch: why stop there? Why not just use a mapping object with `#` sequences as keys instead so the lookup runs in O(1)?)
However, you don't need any of this, because what you're really doing is simple text matching, so you can use the best tool in the toolset for that: you can trivially get both the `#` sequence and "remaining text" with a dead simple regex, and then generate the replacement HTML using the captured data:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
function convert(doc) {
let lines = doc.split(`\n`);
lines = convertInlineMD(lines);
lines = convertMultiLineMD(lines);
return lines.join(`\n`);
}
function convertInlineMD(lines) {
lines.forEach((line, i) => {
// convert headings
line = line.replace(/^(#+)\s+(.+)/, (_, {
length: h
}, text) => `<h${h}>${text.trim()}</h${h}>`);
// then convert bold, then italic, then... etc. etc.
lines[i] = line;
});
return lines;
}
function convertMultiLineMD(lines) {
// convert tables, etc. etc.
return lines;
}
// And a simple test based on what you indicated:
const docs = [`## he#llo\nthere\n# yooo`, `# he#llo\nthere\n## yooo`];
docs.forEach((doc, i) => console.log(`[doc ${i + 1}]\n`, convert(doc)));
<!-- end snippet -->
However, this is also a naive approach to writing a transpiler, and will have dismal runtime performance compared to writing a DFA based on the markdown grammar (the "markup language specification" grammar, i.e. the rules that say which tokens can follow which other tokens), where you run through your document by tracking what kind of token we're dealing with, and convert on the fly as we pass token terminations.
That's wildly beyond the scope of this answer, but worth digging into if you're doing this just to see if you can do it: anyone can write code "that works" but is extremely inefficient, so that's not an exercise that's going to improve your skill at programming. |
{"Voters":[{"Id":529282,"DisplayName":"Martheen"},{"Id":272109,"DisplayName":"David Makogon"},{"Id":408390,"DisplayName":"Warren Burton"}]} |
Extract the processing of the nc files: IndexError IndexError index 10933172 is out of bounds for axis 0 with size 9098798 |
|python-3.x| |
null |
|spring-boot|cross-browser| |
Here' my error message:
```
* What went wrong:
A problem occurred configuring root project 'map'.
> Could not determine the dependencies of null.
> Could not resolve all task dependencies for configuration ':classpath'.
> Could not find com.google.gms.google-services:4.4.1:.
Required by:
project :
```
And here's my android/build.gradle
```
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
ext {
buildToolsVersion = "33.0.0"
minSdkVersion = 21
compileSdkVersion = 33
targetSdkVersion = 33
// We use NDK 23 which has both M1 support and is the side-by-side NDK version from AGP.
ndkVersion = "23.1.7779620"
}
repositories {
google()
mavenCentral()
}
dependencies {
classpath("com.android.tools.build:gradle")
classpath("com.facebook.react:react-native-gradle-plugin")
classpath("com.google.gms.google-services:4.4.1")
}
}
```
At first, I did't change anything about the code, and the emulator showed a error "API key not found", but I thought my AndroidManifest.xml file doesn't have question.
Here's my AndroidManifest.xml:
```
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<application
android:name=".MainApplication"
android:label="@string/app_name"
android:icon="@mipmap/ic_launcher"
android:roundIcon="@mipmap/ic_launcher_round"
android:allowBackup="false"
android:theme="@style/AppTheme">
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="MY-API-KEY"/>
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|screenSize|smallestScreenSize|uiMode"
android:launchMode="singleTask"
android:windowSoftInputMode="adjustResize"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
``` |
Couldn't import Google Map API |
|android|react-native|google-maps| |
null |
) CREATE TABLE ahli(
nama VARCHAR(6),
nokp VARCHAR(12),
id_kelas INT(2),
tahap VARCHAR(20),
katalaluan VARCHAR(20),
PRIMARY KEY(nokp),
FOREIGN KEY(id_kelas) REFERENCES kelas(id_kelas) ON UPDATE CASCADE ON DELETE CASCADE
I try to change it with another words, symbol, numbers and backspace.
|
I got unexpected of beginning near 'nama' |
I want to perform multiple Identity-related actions in a transaction. There is [some guidance](https://learn.microsoft.com/en-us/ef/core/saving/transactions) in the docs for EF in general, but not for Identity in particular.
This approach is used in many SO posts:
```cs
using var transaction = await _context.Database.BeginTransactionAsync();
try
{
var result1 = await _userManager.Foo();
if (!result1.Succeeded) throw new Exception("Could not foo.");
var result2 = await _userManager.Bar();
if (!result2.Succeeded) throw new Exception("Could not bar.");
await transaction.CommitAsync();
}
catch (Exception e)
{
_logger.LogError(e, "Something bad happened, but changes were rolled back.");
// ...handle error
}
```
Ordinarily, without Identity, if execution enters the catch block then the transaction is not committed and is disposed (and thus automatically rolled back).
But:
- Identity calls `SaveChanges` after every action, so at face value it seems like the rollback would accomplish nothing.
- I don't know whether `_context` is the same one used internally by `_userManager`? I think the context is registered by default as scoped (per request), so I assume that within an ASP.NET Core HTTP request, the same context will be used by both Identity and my code.
*Is that correct?*
### UPDATE:
I can't find definitive documentation for these issues, and am uncomfortable relying on internal implementation details for something so critical. <strike>So I opened a [docs issue](https://github.com/dotnet/AspNetCore.Docs/issues/32143) on the repo, asking for official guidance. Please upvote it if this concerns you too.</strike>
Update: they closed that docs request without proper consideration. So I opened another on the [main repo](https://github.com/dotnet/aspnetcore/issues/54855). Please upvote that.
|
I recently upgraded my laravel application to bootstrap 5 and I cannot (for the life of me) get bootstrap's tooltips working. My application is running Laravel Framework 9.52.16 with bootstrap 5.3.3 and popper.js 1.16.1.
My default html tooltips work but I would like to use bootstrap 5's tooltips as they are cleaner with better functionality and positioning. However, they do not appear now matter how I try to instantiate them or use them. There are no errors in my console, the tooltips simply do not appear.
My site uses a structure where I have a layout.blade.php file which loads all of my dependencies and provides a basic structure for the site. It then uses a series of @include or @yield statements to include content appropriate for the page the user is on at any given time.
Initially I tried included the suggested bootstrap instantiation code in the <script> tag at the bottom of layout.blade.php:
`
/** Instantiate all BS5 Tooltips */
var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'))
var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
return new bootstrap.Tooltip(tooltipTriggerEl)
})
`
I've tried placing this in my $(function() {}); tag as well as in $(document).ready(function(){}); but neither corrected the issue. I've also tried adding defer to the script tag, that also did not resolve the issue. I've copied a few other various shorthand solutions from codepen in the same locations and they also did not work. Finally, I've also tried including the above code directly in the lowest-level page (the blade file that actually has the tooltips) but that ALSO did not resolve the issue.
If I stick an alert before the return statement, I can clearly see that the code is identifying each tooltip, but the fact doesn't change that the tooltips do not appear when I hover over their container.
Here is an example tooltip from my HTML as well (I am only adding title; popper is adding the data-bs-original-title tag - so I know it is doing SOMETHING, just not making the tooltip appear.)
`
<i class="fas fa-question-circle help-icon" data-bs-toggle="tooltip" data-bs-placement="top" container="body" aria-label="Sample Text" data-bs-original-title="Sample Text"></i>
`
I am a hobby developer and I am at my wits end on this. I spent days figuring out how to use mix properly so I could use all of BS5's new functionality only to hit this very silly wall over tooltips of all things. Any help is appreciated! |
Keycloak: How to override Welcome Screen redirect behavior (to custom realm, instead of master realn/admin) |
|nginx|realm|keycloak| |
I am using a ```UIBezierPath``` to draw a curved line. The curve works however, I am unable to curve the edges of the line.
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/xFcoV.jpg
If you look at the top/bottom end of the curve, you can see that the edges are flattened out, thats not what I want. Is there a way to curve the edges?
I am using a simple ```UIBezierPath``` to draw an (almost) semi circle. This creates the curved line shape that I want:
CAShapeLayer *circle = [CAShapeLayer layer];
circle.path = [UIBezierPath bezierPathWithArcCenter:CGPointMake(0, 0) radius:70 startAngle:1.0472 endAngle:5.23599 clockwise:NO].CGPath;
circle.fillColor = [UIColor clearColor].CGColor;
circle.strokeColor = [UIColor colorWithWhite:1.0 alpha:0.2].CGColor;
circle.lineWidth = 18.0;
circle.cornerRadius = 10.0;
circle.position = CGPointMake(100, 100);
circle.anchorPoint = CGPointMake(0.5, 0.5);
[mainView.layer addSublayer:circle];
Despite setting the ```cornerRadius``` property, the corners are not curved. What am I doing wrong?
|
How can I configure settings.gradle to accommodate different setups based on the flavours of my app?
In my settings.gradle, I have several modules defined, such as:
include ':SubModule1'
include ':SubModule2'
.....
include ':SubModule8'
include ':SubModule10'
Now, I have two flavour dimensions defined: marketOne and marketTwo. Depending on the market, I would like settings.gradle to distinguish between the two markets, for example:
include ':SubModule1'
if(selectedMarket == marketOne) {
include ':SubModule2'
}
.....
if(selectedMarket == marketTwo) {
include ':SubModule8'
}
include ':SubModule10'
Essentially, I need to set the market or some sort of flag in selectedMarket. However, I'm encountering difficulties obtaining the current buildVariant selected in Android Studio during Gradle sync and build.
Do you have any suggestions on how to accomplish this? |
Android Configuring settings.gradle for different app flavours |
|android|gradle| |
When I try to fetch from a query on a single table I get an associated array where Key is a name of column. But when I try to `JOIN` another table's columns on a query I get an array which only contains a key 'row' and a string value which looks like
`(value1,value2,value3,...,valueN)`, without column names.
I need to get associated array (I use `fetch(PDO::FETCH_ASSOC)` for that) as an output, but I get a string
example of my query:
```
SELECT (item.id, item.category_id, item_category.letter, item_category.name_eng)
FROM item
LEFT JOIN item_category ON item_category.letter = item.category_id
WHERE item.id = :id
```
I get this from that query:
```
Array
(
[row] => (2314,"B","B","Name")
)
```
I would like to get:
```
Array
(
[id] => 2314,
[category_id] => "B",
[letter] => "B",
[name_eng] => "Name"
)
```
I've tried to explode an output string with ',' separator, but it's a dumb idea cuz if i got ',' in table data I split it into different array elements
How do I get an assoc array from that?
|
I want to add a worker and then his id and name go to another table to work with
this doesnt work I tried it
`router.post('/add_employee', (req, res) => {
// Insert into puntoretuji table
const sql = "INSERT INTO puntoretuji (name, salary, role) VALUES (?)";
const values = [req.body.name, req.body.salary, req.body.role];
con.query(sql, [values], (err, result) => {
if (err) return res.json({ Status: false, Error: "Query Error" });
return res.json({ Status: true});
});
}
);
router.post('/worker_id', (req, res) => {
const query = `SELECT MAX(id) AS max_id FROM puntoretuji`;
const values = [req.body.id]
const result = con.query(query, values)
const maxId = result[0].max_id;
// Insert into worker_data table
const insertWorkerDataQuery = "INSERT INTO worker_data (worker_id, name) VALUES (?)";
const workerDataValues = [maxId, req.body.name]; // Assuming current date for 'date'
con.query(insertWorkerDataQuery, workerDataValues);
}` |
Express Mysql getting max ID from table not working cought in a promise |
|javascript|mysql| |
null |
Initially there is no open or close and the style
```
.mobile-nav ul {
transform: translateY(-200%);
}
```
in applied. When the style is either open or close the transition will play.
I moved the SVG to the CSS background -- I don't know if that will work for you?
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
document.addEventListener("DOMContentLoaded", function() {
const hamburgerMenu = document.getElementById("hamburger-menu");
const mobileNav = document.querySelector(".mobile-nav");
hamburgerMenu.addEventListener("click", function() {
mobileNav.classList.toggle("open");
if (mobileNav.classList.contains("open")) {
mobileNav.classList.remove("close");
}else{
mobileNav.classList.add("close");
}
});
});
<!-- language: lang-css -->
#hamburger-menu {
width: 48px;
height: 48px;
background-image: url('data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz4KPHN2ZyB2aWV3Qm94PSIwIDAgMTAwIDEwMCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KICA8cGF0aCBkPSJNIDUgMTUgaCA5MCBNIDUgNTAgaCA5MCBNIDUgODUgaCA5MCIgc3Ryb2tlPSJibGFjayIgc3Ryb2tlLXdpZHRoPSIyMCIgZmlsbD0ibm9uZSIgLz4KPC9zdmc+');
background-repeat: no-repeat;
}
.open #hamburger-menu {
width: 48px;
height: 48px;
background-image: url('data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz4KPHN2ZyB2aWV3Qm94PSIwIDAgMTAwIDEwMCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KICA8cGF0aCBkPSJNIDEwIDEwIEwgOTAgOTAgTSAxMCA5MCBMIDkwIDEwIiBzdHJva2U9ImJsYWNrIiBzdHJva2Utd2lkdGg9IjIwIiBmaWxsPSJub25lIiAvPgo8L3N2Zz4=');
background-repeat: no-repeat;
}
.mobile-nav {
display: block;
width: 100%;
background-color: var(--neutral-1000);
z-index: 1000;
position: absolute;
top: 0;
left: 0;
}
.mobile-nav ul {
transform: translateY(-200%);
}
.mobile-nav.open ul {
animation: slideDown 0.3s ease forwards;
}
.mobile-nav.close ul {
animation: slideUp 0.3s ease forwards;
}
@keyframes slideDown {
from {
transform: translateY(-200%);
}
to {
transform: translateY(0);
}
}
@keyframes slideUp {
from {
transform: translateY(0);
}
to {
transform: translateY(-200%);
}
}
<!-- language: lang-html -->
<header class="mobile">
<div class="logo">
<img src="/media/yogism_logo_header.svg" alt="Logo" />
</div>
<nav class="mobile-nav">
<div class="hamburger-menu" id="hamburger-menu"></div>
<ul>
<li><a href="#">Features</a></li>
<li><a href="#">About Us</a></li>
<li><a href="#">Testimonial</a></li>
<li><a href="#">Pricing</a></li>
<li><a href="#">Blog</a></li>
</ul>
</nav>
</header>
<!-- end snippet -->
|
Apologies in advance for the incompleteness/unprofessional terms as I do not have a CS background and Thank you so much for your help!
I am making a Simple Multicast Receiver through Python, the receiver receives singlecast/multicast/broadcast packets through ethernet connection from a Elevator Control Server. And I encountered a strange problem:
When my computer is connected to Wifi, the multicast packets stops being received, while singlecast/broadcast packets are fine. I used wireshark to monitor the ethernet connection and found that the multicast packets are still being transmitted, just not received and printed on my receiver.
I used wireshark to monitor the wifi connection when wifi is turned on and found that there is packets sent from my device to the router, in IGMPv2 protocol, source ip being my device ip and destination ip being the multicast ip address specified in my receiver code.
So I wonder does the transmission between my device and the router when wifi is connected affect my receiver from receiving multicast packets?
For the receiver I just basically used the code from this solution:
https://stackoverflow.com/questions/603852/how-do-you-udp-multicast-in-python
```
import socket
import struct
MCAST_GRP = '239.64.0.2'
MCAST_PORT = 52000
IS_ALL_GROUPS = True
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
if IS_ALL_GROUPS:
# on this port, receives ALL multicast groups
sock.bind(('', MCAST_PORT))
else:
# on this port, listen ONLY to MCAST_GRP
sock.bind((MCAST_GRP, MCAST_PORT))
mreq = struct.pack("4sl", socket.inet_aton(MCAST_GRP), socket.INADDR_ANY)
sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
while True:
# For Python 3, change next line to "print(sock.recv(10240))"
print sock.recv(10240)
```
I tried using Wireshark to monitor the packets transmission of both the ethernet and wifi connections, I speculate the connection to wifi blocks the binding of port and multicast address. However I am shooting in the dark here and please correct and enlighten me. |
Python Multicast packet receiver stops receiving multicast packets when computer is connected to WiFi |
|python|sockets|wireshark|multicastsocket| |
null |
```
import { NextResponse } from "next/server";
import User from "../../models/post";
const POST = async (req, res) => {
try {
const body = req.json();
console.log(req);
const userData = {
Title: body.title,
content: body.content,
tag: body.tag,
time: new Date()
};
//make corrections here
return NextResponse.json({ message: "User posted successfully" }, { status: 200 });
} catch (error) {
console.error("Error occurred while saving user data:", error);
return NextResponse.json({ error: "Internal Server Error" }, { status: 500 });
}
};
export default POST;
```
here is the frontend fetch api-
const response = await fetch('/api/write', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
title: title,
content: value,
tag: "reactjs"
}),
});
if (!response.ok) {
throw new Error('no network response');
}
console.log('Post successfully published');
} catch (error) {
console.error('Error publishing post:', error);
}
Error: Only plain objects, and a few built-ins, can be passed to Client Components from Server Components. Classes or null prototypes are not supported.
at stringify (<anonymous>)
as well as req.json is not a function error
getting this error in nextjs14 using app router
so what I understand from these errors is that I cannot pass certain objects from server components to client components but I am not sending anything from my server api where I am just creating a post for a blog ,just simply passing a message back to the react frontend. I just want to know why is this happening? |
Invalid or unexpected token in window terminal |
|node.js|quick-install-package| |
null |
|mysql|mysql-8.0| |
I'm trying to simulate a two neuron network in Python. It's simple enough to do writing separate equations for each neuron, but since I would like to generalize the code a bit more so that it's easy to increase the number of neurons without rewriting the equations over and over. The two neural network equations are the following:
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/ET9Ls.png
Basically, I have two Hodgkin-Huxley neurons that are coupled together through the last term in the voltage equations. So what I would like to do is to write a code in such a way so that I can expand the network easily. To do so, I created a vector V for the neuron voltages: [V1, V2], and create a vector X where X models the gating variables m,h, and n. So I would have X = [[m1, h1, n1], [m2, h2, n2]]. However, currently the code is not producing spiking but rather appears the voltage just blows up to infinity. That suggests there's a problem with the gating variables X. The gating variables m, h, and n should always be between 0 and 1, so it looks as if the gating variables are just reaching 1 and staying there which would cause the voltage the blow up. I'm not sure what's causing them to just stay at 1. The code is running and not producing any errors.
import scipy as sp
import numpy as np
import pylab as plt
NN=2 #Number of Neurons in Model
dt=0.01
T = sp.arange(0.0, 1000.0, dt)
nt = len(T) # total number of time steps
# Constants
gNa = 120.0 # maximum conducances, in mS/cm^2
gK = 36.0
gL = 0.3
ENa = 50.0 # Nernst reversal potentials, in mV
EK = -77
EL = -54.387
#Coupling Terms
Vr = 20
w = 1
e11 = e22 = 0
e12 = e21 = 0.1
E = np.array([[e11, e12], [e21, e22]])
#Gating Variable Transition Rates
def alpham(V): return (0.1*V+4.0)/(1.0 - sp.exp(-0.1*V-4.0))
def betam(V): return 4.0*sp.exp(-(V+65.0) / 18.0)
def alphah(V): return 0.07*sp.exp(-(V+65.0) / 20.0)
def betah(V): return 1.0/(1.0 + sp.exp(-0.1*V-3.5))
def alphan(V): return (0.01*V+0.55)/(1.0 - sp.exp(-0.1*V-5.5))
def betan(V): return 0.125*sp.exp(-(V+65.0) / 80.0)
def psp(V,s): return ((5*(1-s))/(1+sp.exp(-(V+3)/8)))-s
#Current Terms
def I_Na(V,x): return gNa * (x[:,0]**3) * x[:,1] * (V - ENa) #x0=m, x1=h, x2=n
def I_K(V,x): return gK * (x[:,2]**4) * (V - EK)
def I_L(V): return gL * (V - EL)
def I_inj(t): return 10.0
#Initial Conditions
V = np.zeros((nt,NN)) #Voltage vector
X = np.zeros((nt,NN,3)) #Gating Variables m,h,n (NN neurons x 3 gating variables)
S = np.zeros((nt,NN)) #Coupling term
dmdt = np.zeros((nt,NN))
dhdt = np.zeros((nt,NN))
dndt = np.zeros((nt,NN))
V[0,:] = -65.0
X[0,:,0] = alpham(V[0,:])/(alpham(V[0,:])+betam(V[0,:])) #m
X[0,:,1] = alphah(V[0,:])/(alphah(V[0,:])+betah(V[0,:])) #h
X[0,:,2] = alphan(V[0,:])/(alphan(V[0,:])+betan(V[0,:])) #n
alef = 5.0/(1+sp.exp(-(V[0,:]+3)/8.0))
S[0,:] = alef/(alef+1)
dmdt[0,:] = alpham(V[0,:])*(1-X[0,:,0])-betam(V[0,:])*X[0,:,0]
dhdt[0,:] = alphah(V[0,:])*(1-X[0,:,1])-betah(V[0,:])*X[0,:,1]
dndt[0,:] = alphan(V[0,:])*(1-X[0,:,2])-betan(V[0,:])*X[0,:,2]
#Euler-Maruyama Integration
for i in xrange(1,nt):
V[i,:]= V[i-1,:]+dt*(I_inj(i-1)-I_Na(V[i-1,:],X[i-1,:])-I_K(V[i-1,:],X[i-1,:])-I_L(V[i-1,:]))+dt*((Vr-V[i-1,:])/w * np.dot(E,S[i-1,:]))
#Gating Variable
dmdt[i,:] = dmdt[i-1,:] + alpham(V[i-1,:])*(1-X[i-1,:,0])-betam(V[i-1,:])*X[i-1,:,0]
dhdt[i,:] = dhdt[i-1,:] + alphah(V[i-1,:])*(1-X[i-1,:,1])-betah(V[i-1,:])*X[i-1,:,1]
dndt[i,:] = dndt[i-1,:] + alphan(V[i-1,:])*(1-X[i-1,:,2])-betan(V[i-1,:])*X[i-1,:,2]
z = np.array([dmdt[i-1,:],dhdt[i-1,:],dndt[i-1,:]]).T
#Gating Variable Constraints (0<m,h,n<1)
X[i,:,0] = max(0,min(X[i,:,0].all(),1))
X[i,:,1] = max(0,min(X[i,:,1].all(),1))
X[i,:,2] = max(0,min(X[i,:,2].all(),1))
#Update Gating Variables
X[i,:,:]= X[i-1,:,:]+dt*(z)
#Coupling Term
S[i,:] = S[i-1,:]+dt*psp(V[i-i,:],S[i-1,:])
V1 = V[:,0]
V2 = V[:,1]
plt.plot(T,V1, 'red')
plt.plot(T,V2, 'blue')
plt.show()
I purposefully am not using odeint to integrate my ODEs because I would like to add stochasticity to the equations later and therefore want to use the Euler method above. Anyway, if anyone can help me figure out how to fix this code so that the expected spiking behavior occurs, that would be fantastic. |
Writing a small neural network with matrices |
|python|ode| |
Have you tried changing your function to:
def cos_func(times, amplitude, frequency, offset):
return amplitude * np.cos(frequency * times) + offset |
The website works fine only for 1-2 requests, after which it starts loading endlessly and if I wait for some time I get an Internal Server Error.
After this I reload the server `sudo systemctl reload apache2`, website works for 1 request and I got same problem again
(When i use `runserver 0.0.0.0:8000` it works fine)
I use Django application on Ubuntu 22.04
Using `apache2` and `libapache2-mod-wsgi-py3`
Libapache version is:
`
libapache2-mod-wsgi-py3/jammy-updates,jammy-security,now 4.9.0-1ubuntu0.1 amd64 [installed]
`
Python version 3.10.12
My Apache file conf `etc/apache2/apache.conf` (I added here only `Servername` and `LimitRequestFieldSize`)
```
ServerName caspian-bavarians.com
DefaultRuntimeDir ${APACHE_RUN_DIR}
PidFile ${APACHE_PID_FILE}
Timeout 300
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 5
User ${APACHE_RUN_USER}
Group ${APACHE_RUN_GROUP}
HostnameLookups Off
ErrorLog ${APACHE_LOG_DIR}/error.log
LogLevel warn
IncludeOptional mods-enabled/*.load
IncludeOptional mods-enabled/*.conf
Include ports.conf
<Directory />
Options FollowSymLinks
AllowOverride None
Require all denied
</Directory>
<Directory /usr/share>
AllowOverride None
Require all granted
</Directory>
<Directory /var/www/>
Options Indexes FollowSymLinks
AllowOverride None
Require all granted
</Directory>
AccessFileName .htaccess
<FilesMatch "^\.ht">
Require all denied
</FilesMatch>
LogFormat "%v:%p %h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" vhost_combined
LogFormat "%h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" combined
LogFormat "%h %l %u %t \"%r\" %>s %O" common
LogFormat "%{Referer}i -> %U" referer
LogFormat "%{User-agent}i" agent
IncludeOptional conf-enabled/*.conf
IncludeOptional sites-enabled/*.conf
LimitRequestFieldSize 32768
```
My website conf file
```
<VirtualHost *:80>
# The ServerName directive sets the request scheme, hostname and port that
# the server uses to identify itself. This is used when creating
# redirection URLs. In the context of virtual hosts, the ServerName
# specifies what hostname must appear in the request's Host: header to
# match this virtual host. For the default virtual host (this file) this
# value is not decisive as it is used as a last resort host regardless.
# However, you must set it for any further virtual host explicitly.
ServerName caspian-bavarians.com
ServerAdmin webmaster@localhost
DocumentRoot /var/www/html
# Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
# error, crit, alert, emerg.
# It is also possible to configure the loglevel for particular
# modules, e.g.
#LogLevel info ssl:warn
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
# For most configuration files from conf-available/, which are
# enabled or disabled at a global level, it is possible to
# include a line for only one particular virtual host. For example the
# following line enables the CGI configuration for this host only
# after it has been globally disabled with "a2disconf".
#Include conf-available/serve-cgi-bin.conf
Alias /static /home/ftpuser/caspi/static
<Directory /home/ftpuser/caspi/static>
Require all granted
</Directory>
Alias /media /home/ftpuser/caspi/media
<Directory /home/ftpuser/caspi/media>
Require all granted
</Directory>
<Directory /home/ftpuser/caspi/main>
<Files wsgi.py>
Require all granted
</Files>
</Directory>
WSGIScriptAlias / /home/ftpuser/caspi/main/wsgi.py
WSGIDaemonProcess django_app python-path=/home/ftpuser/caspi/ python-home=/home/ftpuser/venv
WSGIProcessGroup django_app
</VirtualHost>
```
Apache error log
`
[Fri Sep 22 05:38:30.466675 2023] [wsgi:error] [pid 6140:tid 140592497751616] (70007)The timeout specified has expired: [client 82.194.20.184:60468] mod_wsgi (pid=6140): Failed to proxy response from daemon., referer: http://www.caspian-bavarians.com/az/cars/
[Fri Sep 22 05:38:34.918090 2023] [wsgi:error] [pid 6139:tid 140592497751616] [client 82.194.20.184:57353] Truncated or oversized response headers received from daemon process 'django_app': /home/ftpuser/caspi/main/wsgi.py, referer: http://www.caspian-bavarians.com/az/car/mercedes-benz-e220-7/
[Fri Sep 22 05:38:34.918108 2023] [wsgi:error] [pid 6139:tid 140592480966208] [client 82.194.20.184:57024] Truncated or oversized response headers received from daemon process 'django_app': /home/ftpuser/caspi/main/wsgi.py, referer: http://www.caspian-bavarians.com/az/cars/
[Fri Sep 22 05:50:33.804640 2023] [wsgi:error] [pid 6139:tid 140592298276416] (70007)The timeout specified has expired: [client 82.194.20.184:63960] mod_wsgi (pid=6139): Failed to proxy response from daemon., referer: http://www.caspian-bavarians.com/az/cars/
[Fri Sep 22 05:50:37.371732 2023] [wsgi:error] [pid 6139:tid 140592506144320] [client 82.194.20.184:58025] Timeout when reading response headers from daemon process 'django_app': /home/ftpuser/caspi/main/wsgi.py, referer: http://www.caspian-bavarians.com/az/car/mercedes-benz-e220-7/
[Fri Sep 22 05:50:38.194056 2023] [wsgi:error] [pid 6140:tid 140592323454528] [client 82.194.20.184:63962] Timeout when reading response headers from daemon process 'django_app': /home/ftpuser/caspi/main/wsgi.py, referer: http://www.caspian-bavarians.com/az/car/mercedes-benz-e220-7/
[Fri Sep 22 05:50:38.742344 2023] [wsgi:error] [pid 6139:tid 140592357025344] [client 159.203.17.7:44390] Truncated or oversized response headers received from daemon process 'django_app': /home/ftpuser/caspi/main/wsgi.py
`
My wsgi.py
```
"""
WSGI config for main project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/4.2/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'main.settings')
application = get_wsgi_application()
```
This version of my application works fine on heroku
- I tried `apt-get update` and `upgrade`
- Checked the version of `libapache-mod-wsqi-py3`
- Tried reboot the system
- Disable and then Enable the website
|
I'm facing an issue with comparing a hashed email value stored as a BLOB in an SQLite database with a hash generated from an email address in my Android application. Here's a simplified version of my code:
```
@SuppressLint("Range")
public UserCredentials findUserCredentials(String email) throws DBFindException {
SQLiteDatabase db = null;
Cursor cursor = null;
UserCredentials userCredentials = null;
try {
db = open();
byte[] emailHash = SecurityService.hash(SerializationUtils.serialize(email));
String selection = EMAIL_HASH + "=?";
String[] selectionArgs = {new String(emailHash, StandardCharsets.UTF_8)};
cursor = db.query(TABLE_NAME, null, selection, selectionArgs, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
byte[] passwordBytes = cursor.getBlob(cursor.getColumnIndex(PASSWORD));
byte[] salt = cursor.getBlob(cursor.getColumnIndex(PASSWORD_SALT));
if (passwordBytes != null && salt != null) {
HashData hashData = new HashData(passwordBytes, salt);
userCredentials = new UserCredentials(cursor.getLong(cursor.getColumnIndex(ID)), hashData);
}
}
} catch (SQLiteException | SerializationException | HashException exception) {
throw new DBFindException("Failed to findUserCredentials from user with email (" + email + ")", exception);
} finally {
if (cursor != null)
cursor.close();
close(db);
}
return userCredentials;
}
```
Despite ensuring that the hash generated from the email address matches the value stored in the database, the query doesn't return any results. I suspect the issue might be related to how I'm passing the hashed value as an argument in the selectionArgs. However, even after converting the hash to hexadecimal format for comparison, the problem persists.
Could someone please advise on what might be causing this issue or suggest any potential solutions?
PS: This is the code snippet I'm using for 'getContentValues during the insert operation, where EMAIL_HASH is a column in the database and user.getEmail() returns a String:
contentValues.put(EMAIL_HASH, SecurityService.hash(SerializationUtils.serialize(user.getEmail()))); |
How to put in selectionArgs from a query in SQLite Android Studio byte[] value |
Oracle Http server ISNT-07551 |
|oracle|apache|weblogic14c| |
null |
The spring boot plugin generates a unique structure by default: See [the Spring docs](https://docs.spring.io/spring-boot/docs/current/reference/html/executable-jar.html) for more details.
You will need
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-loader</artifactId>
</dependency>
```
Then you can use the Spring tooling to do something like this
```java
File myJarFile = new File("./myspringbootdep.jar");
NestedJarFile jarFile = new NestedJarFile(myJarFile, "BOOT-INF/classes/");
Enumeration<JarEntry> e = jarFile.entries();
ArrayList<JarEntry> jarEntries = Collections.list(e);
//This is required to make URLs with `nested:` work
org.springframework.boot.loader.net.protocol.Handlers.register();
URL[] urls = { JarUrl.create(myJarFile, "BOOT-INF/classes/") };
LaunchedClassLoader launchedClassLoader = new LaunchedClassLoader(false, urls, this.getClass().getClassLoader());
for(JarEntry je : jarEntries) {
System.out.println(je.getName());
if(je.isDirectory() || !je.getName().endsWith(".class") || !je.getName().contains("example")){
continue;
}
//Replaces slashes with dots and remove .class
Class c = launchedClassLoader.loadClass(je.getName().replaceAll("/", ".").replaceFirst("\\.class$", ""));
System.out.println(c);
}
```
|