text
stringlengths 15
59.8k
| meta
dict |
---|---|
Q: Error when trying to create a facetgrid of pointplots I have sequencing data of micro-RNAs (miR) under different conditions ('Comparisons'), and I want to create a point-plot which will show me on different graphs the fold-change for each miR. the data looks like this (and is a pandas data_frame)
mir_Names Comparison Fold_Change
9 9 mmu-miR-100-4373160\n15 m... YAD-YC 508539.390000
15 9 mmu-miR-100-4373160\n15 m... YAD-YC 26.816000
17 9 mmu-miR-100-4373160\n15 m... YAD-YC 728.608000
18 9 mmu-miR-100-4373160\n15 m... YAD-YC 11483029.706000
'upregulated' is a subset of the dataframe and i tried to visualize it using:
g = sns.FacetGrid(upregulated, col='Comparison', sharex=True, sharey=True, size=0.75, aspect=12./8, despine=True, margin_titles=True)
g.map(sns.pointplot, 'mir_Names', 'Fold_Change', data=upregulated)
**
*
*but it gives me the error which I couldn't find any solution to it:
**
ValueError Traceback (most recent call last) <ipython-input-180-a1cf1b282869> in <module>()
1 g = sns.FacetGrid(upregulated, col='Comparison', sharex=True, sharey=True, size=0.75, aspect=12./8, despine=True, margin_titles=True)
----> 2 g.map(sns.pointplot, 'mir_Names', 'Fold_Change', data=upregulated) #maybe with .count
c:\pyzo2014a\lib\site-packages\seaborn\axisgrid.py in map(self, func,
*args, **kwargs)
446
447 # Finalize the annotations and layout
--> 448 self._finalize_grid(args[:2])
449
450 return self
c:\pyzo2014a\lib\site-packages\seaborn\axisgrid.py in
_finalize_grid(self, axlabels)
537 self.set_axis_labels(*axlabels)
538 self.set_titles()
--> 539 self.fig.tight_layout()
540
541 def facet_axis(self, row_i, col_j):
c:\pyzo2014a\lib\site-packages\matplotlib\figure.py in tight_layout(self, renderer, pad, h_pad, w_pad, rect) 1663 rect=rect) 1664
-> 1665 self.subplots_adjust(**kwargs) 1666 1667
c:\pyzo2014a\lib\site-packages\matplotlib\figure.py in subplots_adjust(self, *args, **kwargs) 1520 1521 """
-> 1522 self.subplotpars.update(*args, **kwargs) 1523 for ax in self.axes: 1524 if not isinstance(ax, SubplotBase):
c:\pyzo2014a\lib\site-packages\matplotlib\figure.py in update(self, left, bottom, right, top, wspace, hspace)
223 if self.bottom >= self.top:
224 reset()
--> 225 raise ValueError('bottom cannot be >= top')
226
227 def _update_this(self, s, val):
**ValueError: bottom cannot be >= top**
What causes this error?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/30527294",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Multiprocess Python 3 I have a script that loops over an array of numbers, those numbers are passed to a function which calls and API. It returns JSON data which is then written to a CSV.
for label_number in label_array:
call_api(domain, api_call_1, api_call_2, label_number, api_key)
The list can be up to 7000 elements big, as the API takes a few seconds to respond this can take hours to run the entire script. Multiprocessing seems the way to go with this. I can't quite working out how to do this with the above loop. The documentation I am looking at is
https://docs.python.org/3.5/library/multiprocessing.html
I found a similar article at
Python Multiprocessing a for loop
But manipulating it doesn't seem to work, I think I am buggering it up when it comes to passing all the variables into the function.
Any help would be appreciated.
A: Multiprocessing could help but this sounds more like a threading problem. Any IO implementation should be made asynchronous, which is what threading does. Better, in python3.4 onwards, you could do asyncio.
https://docs.python.org/3.4/library/asyncio.html
If you have python3.5, this will be useful: https://docs.python.org/3.5/library/asyncio-task.html#example-hello-world-coroutine
You can mix asyncio with multiprocessing to get the optimized result. I use in addition joblib.
import multiprocessing
from joblib import Parallel, delayed
def parallelProcess(i):
for index, label_number in enumerate(label_array):
if index % i == 0:
call_api_async(domain, api_call_1, api_call_2, label_number, api_key)
if __name__=="__main__":
num_cores_to_use = multiprocessing.cpu_count()
inputs = range(num_cores_to_use)
Parallel(n_jobs=num_cores_to_use)(delayed(parallelProcess)(i) for i in inputs)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/33162690",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to compare two lists with multiple objects and set values? I have two lists. Each list has a Name object and and a Value object. I want to loop through list1 and check if each list1 Name object is the same as the list2 Name object (the linq code below does this).
If they match, then I want the List1 Value to be set with the list2 Value How can this be done?
list1 list2
Name Value Name Value
john apple John orange
peter null Peter grape
I need it to look like this:
list1 list2
Name Value Name Value
john orange john orange
peter grape peter grape
Linq code:
var x = list1.Where(n => list2.Select(n1 => n1.Name).Contains(n.Name));
A: For filtering you can use LINQ, to set the values use a loop:
var commonItems = from x in list1
join y in list2
on x.Name equals y.Name
select new { Item = x, NewValue = y.Value };
foreach(var x in commonItems)
{
x.Item.Value = x.NewValue;
}
A: In one result, you can get the objects joined together:
var output= from l1 in list1
join l2 in list2
on l1.Name equals l2.Name
select new { List1 = l1, List2 = l2};
And then manipulate the objects on the returned results. by looping through each and setting:
foreach (var result in output)
result.List1.Value = result.List2.Value;
A: You are looking for a left join
var x = from l1 in list1
join l2 in list2 on l1.Name equals l2.Name into l3
from l2 in l3.DefaultIfEmpty()
select new { Name = l1.Name, Value = (l2 == null ? l1.Value : l2.Value) };
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/25532364",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Discord JS function returning undefined I'm building a Discord bot using a collector and am trying to collect votes for rounds of a game. However, the bot keeps returning the wrong values. It will usually return either undefined or [object Object]. The stringifier() function should be returning the name of a round but it's instead returning undefined. e.g. if I input "spleef" on Discord it should output "Spleef" to console and in Discord, but it returns undefined in both or just errors.
UPDATE: i found that the variables were returning boolean values (the variables are battleBoxVotes to cTFVotes).
UPDATE A LOT LATER: so I fixed the problem but my new problem now is that I can't get variables bbv to ctfv to not return an error if they don't have a value. Console logs this: (node:8700) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'content' of undefined
const filter = m => (m.author.id != client.user.id);
const channel = message.channel;
const collector = channel.createMessageCollector(filter, { time: 5000 });
collector.on('collect', m => console.log(`Collected ${m.content}`));
collector.on('end', async collected => {
var bb = collected.find(collected => collected.content === 'battle box');
var pw = collected.find(collected => collected.content === 'spleef');
var s = collected.find(collected => collected.content === 'spleef');
var sw = collected.find(collected => collected.content === 'skywars');
var ctf = collected.find(collected => collected.content === 'capture the flag');
const bbv = bb.content || null;
const pwv = pw.content || null;
const sv = s.content || null;
const swv = sw.content || null;
const ctfv = ctf.content || null;
const stringifier = function(a, b, c, d, e) {
let results;
if (a>b&&a>c&&a>d&&a>e) {results = "Battle Box"}
else if (b>a&&b>c&&b>d&&b>e) {results = "Parkour Warrior"}
else if (c>a&&c>b&&c>d&&c>e) {results = "Spleef"}
else if (d>a&&d>b&&d>c&&d>e) {results = "SkyWars"}
else if (e>a&&e>b&&e>c&&e>c) {results = "Capture the Flag"}
return results;
}
message.channel.send(`And the winner is... ${stringifier(bbv, pwv, sv, swv, ctfv)}!`),
console.log(stringifier(bbv, pwv, sv, swv, ctfv))
});
A: The logic of that comparison absolutely breaks my brain and is a pain to read in the first place. Here's an adapted version that should work a bit better.
This solution iterates through the recieved messages and increments a counter for each gamemode depending on a switch-case expression. (bear in mind this doesn't stop a user from simply spamming whichever gamemode they want...)
Credit for the getAllIndexes function (used to determine ties)
const filter = m => (m.author.id != client.user.id);
const channel = message.channel;
const collector = channel.createMessageCollector(filter, { time: 5000 });
collector.on('collect', m => console.log(`Collected ${m.content}`));
collector.on('end', async collected => {
let msgs = Array.from(collected.keys()).map(m=>m?.content.toLowerCase().trim());
let modes = [ "Battle Box", "Parkour Warrior", "Spleef", "SkyWars", "Capture the Flag" ] // Define the names of the GameModes
let scores = [ 0, 0, 0, 0, 0 ] // Set up the default scores
msgs.forEach(m => {
switch(m) {
case "bb": // Fallthrough case for aliases
case "battlebox":
case "battle box":
scores[0]++; // Increment BattleBox (0) Counter
break;
case "pw":
case "parkour":
case "parkour warrior":
scores[1]++; // Increment ParkourWarrior (1) counter
break;
case "spleef":
scores[2]++; // Increment Spleef (2) counter
break;
case "sw":
case "sky":
case "skywars":
scores[3]++; // Increment SkyWars (3) counter
break;
case "ctf":
case "capture the flag":
scores[4]++; // Increment CaptureTheFlag (4) counter
break;
});
// Now to find who won...
let winningCount = Math.max(scores);
let winningIndexes = getAllIndexes(scores, winningCount);
if(winningIndexes.length = 1) { // Single Winner
message.channel.send(`And the winner is... ${modes[winningIndexes[0]]}!`);
} else { // tie!
message.channel.send(`It's a tie! There were ${winningIndexes.length} winners. (${winningIndexes.map(i=>modes[i]).join(", ")})`);
}
j});
// Get All Indexes function...
function getAllIndexes(arr, val) {
var indexes = [], i;
for(i = 0; i < arr.length; i++)
if (arr[i] === val) indexes.push(i);
return indexes;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/67801752",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How would offline_access work after deprecation after May 1st? I did some test, the result I found contradicts Facebook's documentation. https://developers.facebook.com/roadmap/offline-access-removal/
If we enable the "Deprecate offline access:" and ask for offline_access, at mobile client, we automatically get a token valid for 60 days, without upgrading the SDK. It seems Facebook made it easier for clients, no upgrade is needed. This is what is said on Facebook. "Apps migrating to this feature will no longer be asked for offline_access. They will be issued long lived access tokens which will expire if the user has not used the app in a while. " How long is the "a while" is not documented.
If I upgrade the SDK, extendingToken method is not triggered, because the token is valid for 60 days. If we force to extend the token, we got the following error from Facebook, which I have no clue what it means.
Error Domain=facebookErrDomain Code=10 "The operation couldn’t be completed. (facebookErrDomain error 10.)" UserInfo=0x1404bb70 {request_args=(
{
key = method;
value = "auth.extendSSOAccessToken";
},
{
key = sdk;
value = ios;
},
{
key = "sdk_version";
value = 2;
},
{
key = "access_token";
value = AAACiLiBjLHABAOo3NZCSSLlRddFZCQUsky0q9sogtzHIFGpNNoeYUqtt2X2QUvxMg8AwsQqSLP3oe0cxUoLIXwVZC3xDGuBC3QOvFgELwZDZD;
},
{
key = format;
value = json;
}
), error_code=10, error_msg=The access token was not obtained using single sign-on}
If we don't request "offline_access", the token expires in 2 hours.
What is your observation? Any thought? Any insight from Facebook?
A: The section marked 'If you were NOT previously asking for offline_access' in that document explains how to exchange that 2 hour token for a 60 day token: (note that the 2 hours and 60 days values could change in future)
https://developers.facebook.com/roadmap/offline-access-removal/#extend_token
Just access
https://graph.facebook.com/oauth/access_token?
client_id=APP_ID&
client_secret=APP_SECRET&
grant_type=fb_exchange_token&
fb_exchange_token=EXISTING_ACCESS_TOKEN
And the token returned will have a longer expiry (it may be the same token with a longer expiry or a new token, you should handle both cases)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/9930311",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to add variable in other class static Dictionary without calling a function? Desired outcome:
Implement a class structure, for testing API without altering the base class.
Current situation:
When I write each test for a website, then I'm trying to reuse currently implemented functions to prevent code duplication. Test are called by custom script language (if it can be called like that).
Problem:
Since each line of script can only be applied to 1 function, then I can't use polymorthism. Test implementation looks ugly and I want to change that.
My solution:
I separated each base testing methods and added a map to each of them to define specific cases.
Public static Dictionary <string, dynamic> TestCases
This works well, but I always have to add new cases to that dictionary in main class which I don't really like.
The main question:
Can I add new cases to this variable without editing main class and calling a function in runtime. Something like:
MainTest.TestCases.Add("specific case", ...);
But it should be done during compilation.
Notes:
Maybe my implementation is not very right so I will accept other suggestions as well.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/49599882",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Authenticate OneDrive API with client-credentials-flow We have a requirement to expose an API which can talk to OneDrive storage to download the files which is in shared directory.
Can i have OAuth Client Credential flow using Azure AD ?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73012490",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Replacing string after match I'm new to perl and was wondering how I could replace some text after a matched pattern.
For example I have a string:
my $string = 'startDate="2014-06-10"';
$string =~ s/startDate="2014-06-10"/startDate=""\g;
This code replaces what I want but I want to be able to have any date and for it replace the date with a blank string. So I want to replace any text after startDate=" and stop replacing after 10 characters. What is the best way to do this?
Thanks
A: Assuming your date is always in that format, you can use a more general regular expression to replace the date:
my $string = 'startDate="2014-06-10"';
$string =~ s/startDate="\d{4}-\d{1,2}-\d{1,2}"/startDate=""/g;
and since startDate="" stays the same you really just need to replace the date itself:
my $string = 'startDate="2014-06-10"';
$string =~ s/\d{4}-\d{1,2}-\d{1,2}//g;
A: Assuming perl >5.10:
s/startDate="\K[^"]{10}//g;
Replaces 10 characters which aren't " following startDate=". Using \K means you don't need to replace the bit you wanted to retain:
\K , which causes the regex engine to "keep" everything it had matched
prior to the \K and not include it in $&
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/24166349",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to handle exceptions that occur in let bindings or body How does one deal with exceptions that could occur in the bindings or body of a let statement using the same finally block? Ex:
(let [connections (create-connections)]
(dostuff)
(close connections))
If (create-connections) or (dostuff) fails, I want to (close connections). Some options:
Option 1:
(try
(let [connections (create-connections)]
(dostuff))
(finally (close connections))
This obviously doesn't work though since connections is not in scope in the finally block.
Option 2:
(let [connections (create-connections)]
(try
(dostuff)
(finally (close connections)))
This option only catches exceptions that occur in the (destuff) call though and not those that occur in (create-connections).
Option 3:
(let [connections (try
(create-connections)
(finally (close connections)))]
(try
(dostuff)
(finally (close connections)))
This also doesn't work since connections is not in scope for the finally statement inside the let binding.
So what's the best way of dealing with this?
A: The built in with-open works on anything you can call .close on, so the normal approach is to use something like:
(with-open [connections (create-connections)]
(do-stuff connections))
and handle errors opening connections within the code that failed to open them. If create-connections fails to open one of the connections then perhaps a try ... finally block within create-connections is a cleaner place to handle that sort of error condition.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/20335760",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
}
|
Q: Does JavaScript Promise.allSettled have a callback? Does JavaScript Promise.allSettled have a callback when all settled?
I need to call a function after promise.allSettled.
A: Calling Promise.allSettled returns a Promise, so just like any other Promise, call .then on it:
Promise.allSettled(arrOfPromises)
.then((result) => {
// all Promises are settled
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/58969834",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to scrape a URL on a page only once? I'm not sure how I can count a URL on a page just once.
For example, this page https://www.ig.com/uk/news-and-trade-ideas/ includes the article https://www.ig.com/uk/news-and-trade-ideas/early-morning-call--221103 4 times in different sections.
How can I record it just once.
from cgitb import text
import requests
from bs4 import BeautifulSoup
import gspread
import datetime
import urllib
from urllib.parse import urlparse
# Connect to Google Sheet and select sheet
gc = gspread.service_account(filename='creds.json')
sh = gc.open('scrapetosheets').sheet1
# Add URLs to inspect
urls = ["https://www.ig.com/uk/trading-strategies",
"https://www.ig.com/uk/news-and-trade-ideas",
"https://www.ig.com/us/trading-strategies",
"https://www.ig.com/us/news-and-trade-ideas",
"https://www.ig.com/en/trading-strategies",
"https://www.ig.com/en/news-and-trade-ideas",
"https://www.ig.com/za/trading-strategies",
"https://www.ig.com/za/news-and-trade-ideas",
"https://www.ig.com/au/trading-strategies",
"https://www.ig.com/au/news-and-trade-ideas",
"https://www.ig.com/fr/strategies-de-trading",
"https://www.ig.com/fr/marche-actualites-et-idees-de-trading",
"https://www.ig.com/de/trading-strategien",
"https://www.ig.com/de/nachrichten-und-trading-ideen",
"https://www.ig.com/it/strategie-di-trading",
"https://www.ig.com/it/news-e-idee-di-trading",
"https://www.ig.com/es/estrategias-de-trading",
"https://www.ig.com/es/ideas-de-trading-y-noticias",
"https://www.ig.com/en-ch/trading-strategies",
"https://www.ig.com/en-ch/news-and-trade-ideas",
"https://www.ig.com/cn/trading-strategies",
"https://www.ig.com/cn/news-and-trade-ideas",
"https://www.ig.com/se/tradingstrategier",
"https://www.ig.com/se/nyheter-och-trading-ideer",
"https://www.ig.com/nl/nieuws-en-trading-ideeen",
"https://www.ig.com/nl/trading-strategieen",
"https://www.ig.com/jp/trading-strategies",
"https://www.ig.com/jp/news-and-trade-ideas"]
# Add array
obj = {r[2]: True for r in sh.get_all_values()}
ar = []
for url in urls:
my_url = requests.get(url)
html = my_url.content
soup = BeautifulSoup(html, "html.parser")
for item in soup.find_all("h3", class_="article-category-section-title"):
date = datetime.date.today()
title = item.find("a", class_="primary js_target").text.strip()
url = item.find("a", class_="primary js_target").get("href")
abs = "https://www.ig.com"
rel = url
pub = rel[-6:]
datestring = f"{pub[4:6]} {pub[2:4]} {pub[0:2]}"
info = {"date": date, "title": title, "url":urllib.parse.urljoin(abs, rel), "published":datestring}
url = str(info["url"].replace("https://",""))
if url not in obj:
ar.append([str(info["date"]), str(info["title"]), url, str(info["published"])])
if ar != []:
sh.append_rows(ar, value_input_option="USER_ENTERED")sHH"
A: There are several approaches:
*
*Append urls to list and lookup while iterating if actual url is not in list else skip scraping it.
*Or as mentioned use set and operate from the links:
articles = []
for e in set(soup.select('h3>a')):
e = e.find_parent('div')
articles.append({
'url':e.a.get('href'),
'title':e.get_text(strip=True),
'date':e.select_one('.article-category-section-date').get_text(strip=True) if e.select_one('.article-category-section-date') else None
})
articles
*Or collect your information in list of dicts and iterate over values to get unique one:
list({v['url']:v for v in articles}.values())
*...
Example
import requests
from bs4 import BeautifulSoup
r = requests.get('https://www.ig.com/uk/news-and-trade-ideas/')
soup = BeautifulSoup(r.content)
articles = []
for e in soup.select('h3:has(>a)'):
articles.append({
'url':e.a.get('href'),
'title':e.get_text(strip=True)
})
print('Whit duplicates: ',len(articles))
print('Whitout duplicates: ', len(list({v['url']:v for v in articles}.values())))
list({v['url']:v for v in articles}.values())
Output
With duplicates: 36
Without duplicates: 29
[{'url': '/uk/news-and-trade-ideas/_brent-crude-oil--gold-and-us-natural-gas-rallies-pause-amid-us--221108',
'title': '\u200bBrent crude oil, gold and US natural gas ral...'},
{'url': '/uk/news-and-trade-ideas/early-morning-call--gloomy-festive-season-ahead-amid-consumer-we-221108',
'title': 'Early Morning Call: dollar basket steady ahead of ...'},
{'url': '/uk/news-and-trade-ideas/nasdaq-listed-ryanair-posts-record-h1-results-221107',
'title': 'Ryanair shares up after record H1 result...'},...]
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/74357989",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Inflating Custom Views - Layout File Inconsistencies No, no one answered that question, and the problem still remains... This question here is about another symptom to the same problem (please see comments below):
In Monodroid atleast, when inflating a custom view from a layout, sometimes it needs to be wrapped in a ViewGroup (ie, LinearLayout) in order to not get an exception, and other times does not.
I was wondering if anyone is familiar with this situation, and if it happens in "raw" Android as well (ie, no Monodroid) ?
I always first try without, as in
TextView1.axml
<?xml version="1.0" encoding="utf-8"?>
<Monodroid.Activity1.TextView1
android:id="@+id/text_view1"
android:layout_width="300dp"
android:layout_height="50dp"/>
but if I get an inflation exception, then I'll have to wrap it up
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/ll_container"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<Monodroid.Activity1.TextView1
android:id="@+id/text_view1"
android:layout_width="300dp"
android:layout_height="50dp"/>
</LinearLayout>
where
public class TextView1 : TextView
{
public TextView1 (Context context) : base(context) { }
public TextView1 (Context context, IAttributeSet attributes) : base(context, attributes) { }
public TextView1 (Context context, IAttributeSet attributes, int defStyle) : base(context, attributes, defStyle) { }
}
Thank you.
This layout file inflates with no containing viewgroup:
<?xml version="1.0" encoding="utf-8"?>
<fieldinspection.droid.views.custom.FieldInput
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/RecordDataFieldInput"
style="@style/FieldInput"
android:layout_marginRight="0dip"/>
and this one (inner class PagedFragmentFieldInput) does not (it needs to be within a LinearLayout or else inflation exception):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/ll_record_data_field_input2_container"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<FieldInspection.Droid.Views.ComplaintView.PagedFragmentRecordDataFieldBox.PagedFragmentFieldInput
android:id="@+id/RecordDataFieldInput"
style="@style/FieldInput"
android:layout_marginRight="0dip"/>
</LinearLayout>
Its read as PagedFragment-RecordDataFieldBox, its a RecordDataFieldBox thats within a Fragment thats within a ViewPager.
A: I took your first sample and tried it out here. I get no error wrapping it or not.
TextViewInherit.cs:
using Android.Content;
using Android.Util;
using Android.Widget;
namespace InflationShiz
{
public class TextViewInherit : TextView
{
public TextViewInherit(Context context, IAttributeSet attrs) :
this(context, attrs, 0)
{
}
public TextViewInherit(Context context, IAttributeSet attrs, int defStyle) :
base(context, attrs, defStyle)
{
}
}
}
One.axml:
<?xml version="1.0" encoding="utf-8"?>
<inflationshiz.TextViewInherit
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
Two.axml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<inflationshiz.TextViewInherit
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>
Both work when I inflate in my Activity like so:
var one = LayoutInflater.Inflate(Resource.Layout.One, null);
var two = LayoutInflater.Inflate(Resource.Layout.Two, null);
I find it hard to reproduce your issue; Your code is scattered over 3 different SO questions and even more scattered because you have created answers to your own question where you try to elaborate on your initial questions.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/17394374",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: why am getting null value for the $mail->body =$message? I have tried to add text in message finally it works but after adding $message from the form showing null with error message.
I am using an ajax call for form submission. Everything working fine but mail is not working throwing an error
"message":"Mailer Error: Message body empty"
<?php
header('Content-Type: application/json');
require("phpmailer/class.phpmailer.php");
$c_name = $_POST['name'];
$c_email = $_POST['email'];
$c_message = $_POST['message'];
$message = '<ul><li>' . $c_name . "</li>";
$message .= '<li>' . $c_email . "</li>";
$message .= '<li>' . $c_message . "</li></ul>";
$mail = new PHPMailer();
$mail->IsSMTP(); // set mailer to use SMTP
$mail->Host = "smtp.gmail.com"; // specify main and backup server
$mail->SMTPAuth = true; // turn on SMTP authentication
$mail->Username = "jswan"; // SMTP username
$mail->Password = "secret"; // SMTP password
$mail->From = "[email protected]";
$mail->FromName = "Mailer";
$mail->AddAddress("[email protected]", "Josh Adams");
$mail->Port = 587;
$mail->SMTPSecure = 'tls';
$mail->WordWrap = 50; // set word wrap to 50 // add attachments
$mail->IsHTML(true); // set email format to HTML
$mail->Subject = "Enquiry";
$mail->Body = preg_replace('/\[\]/','',$message);
//$mail->Body = $message; //var_dump($message) showing null
$mail->AltBody = $message;
//$mail->AltBody = "This is the body in plain text for non-HTML mail clients";
if (!$mail->send()) {
$result = array('status'=>"error", 'message'=>"Mailer Error: ".$mail->ErrorInfo);//
echo json_encode($result);
} else {
$result = array('status'=>"success", 'message'=>"Message sent.");
echo json_encode($result);
}
exit;
?>
form.js
$(document).ready(function()
{
$('#reused_form').submit(function(e)
{
e.preventDefault();
var formData = $(this).serialize();
debugger;
$.ajax({
type: "POST",
url: 'form/index.php',
dataType: "json",
data: formData,
processData: false,
contentType: false,
cache: false ,
success: function(result) {
console.log(result);
if(result.status=="success"){
$('#success_message').show();
}else if(result.status=="error"){
$('#error_message').show();
}
},
});
});
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/51843710",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Confirmation dialog will not show when submitting form I am trying to throw up a confirmation dialog before a user clicks delete.
@using (Html.BeginForm("Delete", "Controller", new { viewModel.Id }, FormMethod.Post, null, new { onsubmit= "return confirm('Do you really want to submit the form?');", @style = "text-align: center" }))
{
<input type="submit" value="X" class="form-control btn btn-danger" />
}
The form seems to be rendering as you would expect:
<form action="/admin/RiskProfile/Delete/24" method="post" onsubmit="return confirm('Do you really want to submit the form?');" style="text-align: center">
<input type="submit" value="X" class="form-control btn btn-danger">
<input name="__RequestVerificationToken" type="hidden" value="CfDJ8O5vcsGUmyZOqz2RSFC3UgK8ICB1W1Ov79zW2-IkboTHIL_LvzQMkjy9s4JsbrA9fEXtE4YfWy1pULXxUk4VhKJc2V53WUuVYJwTB0gbBlxRmM8flrHnFvmtJ8Dr_6zPXmDkZW31Tga5pEiCPw1ebTQMbCLmbhzLKKf9jLErmbajbpUSpYUtZG5H_bMaXw3ptg">
</form>
When I click the button it simply submits the form without throwing up the confirmation dialog.
A: My knowledge of .net is limited, but it seems like you just need to prevent the default action from the form submission event. Here's some code to get you rolling, though it may not be perfect:
@using (Html.BeginForm("Delete", "Controller", new { viewModel.Id }, FormMethod.Post, null, new { onsubmit= "onFormSubmit", @style = "text-align: center" }))
{
<input type="submit" value="X" class="form-control btn btn-danger" />
}
function onFormSubmit (e) {
e.preventDefault() // The default event action should be ignored
return confirm('Do you really want to submit the form?');
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/70603196",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Amazon Pinpoint - send a scheduled message to a specific user I am using Amazon Pinpoint to send push notification to my users' devices and I'm looking for a way to send a message to a specific user/device at a specified time (e.g. 15 minutes from now). Is there a way to accomplish this using Pinpoint?
A: Yes, that is possible with Amazon Pinpoint. Please see documentation regarding setting up and executing a scheduled campaign. https://docs.aws.amazon.com/pinpoint/latest/userguide/campaigns.html
thanks
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/48177904",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: LTE internet during WIFI connection? Is it possible to programmatically force iphone to download LTE internet during WIFI connection?
I am connected via WIFI to a device with no internet connection. But I need to use MapKit (via LTE)
Best regards.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/60248050",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Android: Get 64mp image from Xiaomi Mi 10T I'm trying to get the largest picture from Xiaomi device. When requesting supported resolutions
CameraManager manager = (CameraManager) getContext().getSystemService(Context.CAMERA_SERVICE);
CameraCharacteristics characteristics = manager.getCameraCharacteristics(manager.getCameraIdList()[0]);
StreamConfigurationMap map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
Size[] sizes = map.getOutputSizes(ImageReader.class);
the highest resolutions I get there is 4624x3472
however when using android camera app, there is 64mp mode for taking picture.
When using this mode, I'm getting image with 6944x9248
How can I get such resolution in my app?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72058862",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to make AjaxForm work with several forms loaded using jquery load()? I have a page with a div that is dynamically filled using a paginator ;-) At page init I load the first 10 forms in it using jquery .load() method.
What I'd like to do is to make all the forms dynamically updatable using AjaxForm plugin. I know about server side, let's call it update.asp. It works.
But there are several questions:
*
*How to make plugin work in the first place as the AjaxForm seems not to work to the firms inside a dynamically loaded div?
*How do I ID and name the forms? Now I used ID and name myForm to all of them (maybe that is why it doesn't work). Because if I use name myForm1, myForm2 etc... I have to write 10 ajaxForm functions that I use:
$('#myForm').ajaxForm({
beforeSubmit: showLoader,
success: hideLoader
});
I would then need to make this 10 times using myForm1 to myForm10? There must be another way...
*How do I make AjaxForm work with the pages that are not loaded yet? I think this is the same problem as 1). Because even page 1 is loaded dynamically somehow the ajaxForm doesn't get bind to the form.
Sorry, I am quite new to jquery, I am trying hard to study it, I tried this quite some time before I wrote here. If you can help me, I'd be very gratefull.
Yours
Jerry
EDIT: Here is my loader now... It is not working OK, as the loader is never shown, it dissapears so fast I can see it only if I put alert in the hideLoader :-(((
function load(num){
showLoader2();
var link='/obdelaneslike.asp?ID=<%=request.QueryString("IDRecept") %>&offset='+ num
$('#content').load(link, function(){
hideLoader2();
$('.ajax-loader').hide();
$('.myForm').bind("submit", function(event) {
$(this).ajaxForm({
beforeSubmit: showLoader($(this).find('img.ajax-loader').attr('id')),
success: hideLoader($(this).find('img.ajax-loader').attr('id'))
});
return false;
});
});
}
A: I'll try and address these one at a time to better match the question:
1) You can re-bind when you .load() (or whatever jQuery ajax method you're using) or use a plugin like livequery(), for example here's re-binding (do this in your success handler):
$("#myDynamicDiv .myForm").ajaxForm({ ...options... });
Or using livequery():
$(".myForm").livequery(function() { $(this).ajaxForm({ ...options... }); });
2) Use a class instead of IDs here, like this: class="myForm", whenever you want to handle batches of elements like this class is a pretty safe route. The examples above work with class and not IDs per form (they can have IDs, they're just not used). Your form tags would look like this:
<form class="myForm">
3) The same solutions in answer #1 account for this :)
A: ID values are unique to a single DOM element. So you'd need to give each form a new ID, so if you had three forms, you could name them like so:
<form name="formone" id="formone"...
<form name="formtwo" id="formtwo"...
<form name="formthree" id="formthree"...
Now you'd create instances of your ajax request like so:
$('#formone, #formtwo, #formthree').ajaxForm({
beforeSubmit: showLoader,
success: hideLoader
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/3467894",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Add Qlabels in PyQt5 on runtime I want to add Qlabels on runtime by clicking the pushbutton.
For example, I want to add "Helloworld" text label each time the button is clicked.
I have written code but it replaces not add Qlabel in scrollArea, I want to add "Helloworld" in the scrollArea each time the pushbutton is pressed. Secondly, I have created the Qlabel label_99 on runtime, But I think this will not work. As
multiple Qlabels must be created on runtime, as I want to add Qlabel each time I click a pushbutton.
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'test.ui'
#
# Created by: PyQt5 UI code generator 5.9.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(800, 600)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.scrollArea = QtWidgets.QScrollArea(self.centralwidget)
self.scrollArea.setGeometry(QtCore.QRect(130, 80, 221, 301))
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.scrollArea.sizePolicy().hasHeightForWidth())
self.scrollArea.setSizePolicy(sizePolicy)
self.scrollArea.setWidgetResizable(True)
self.scrollArea.setObjectName("scrollArea")
self.scrollAreaWidgetContents = QtWidgets.QWidget()
self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 219, 299))
self.scrollAreaWidgetContents.setObjectName("scrollAreaWidgetContents")
self.verticalLayout = QtWidgets.QVBoxLayout(self.scrollAreaWidgetContents)
self.verticalLayout.setObjectName("verticalLayout")
self.label = QtWidgets.QLabel(self.scrollAreaWidgetContents)
self.label.setObjectName("label")
self.verticalLayout.addWidget(self.label)
self.label_2 = QtWidgets.QLabel(self.scrollAreaWidgetContents)
self.label_2.setObjectName("label_2")
self.verticalLayout.addWidget(self.label_2)
self.label_3 = QtWidgets.QLabel(self.scrollAreaWidgetContents)
self.label_3.setObjectName("label_3")
self.verticalLayout.addWidget(self.label_3)
self.label_4 = QtWidgets.QLabel(self.scrollAreaWidgetContents)
self.label_4.setObjectName("label_4")
self.verticalLayout.addWidget(self.label_4)
self.scrollArea.setWidget(self.scrollAreaWidgetContents)
self.pushButton = QtWidgets.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(390, 110, 89, 25))
self.pushButton.setObjectName("pushButton")
self.pushButton.clicked.connect(self.button_pressed)
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 22))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.label.setText(_translate("MainWindow", "TextLabel"))
self.label_2.setText(_translate("MainWindow", "TextLabel"))
self.label_3.setText(_translate("MainWindow", "TextLabel"))
self.label_4.setText(_translate("MainWindow", "TextLabel"))
self.pushButton.setText(_translate("MainWindow", "PushButton"))
def button_pressed(self):
print("button pressed")
self.add_new_label()
def add_new_label(self):
self.label_99 = QtWidgets.QLabel()
label_99=QtWidgets.QLabel()
label_99.setText("HelloWorld")
self.scrollArea.setWidget(label_99)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
A: setWidget sets the widget for the scroll are, and that is why the code you have doesn't work since it removes the previous widget from the scroll area, and sets the new label as the scroll area widget.
You need to create a new instance of QLabel, and add it to the layout of the scroll area widget, which is self.verticalLayout for the above class.
def add_new_label(self):
newLabel = QtWidgets.QLabel('Hello World')
self.verticalLayout.addWidget(newLabel)
The code to create new label and assign it class instance attribute as self.label_99 = QtWidgets.QLabel() is useless in your case. You just need to create a local variable to hold the label, and finally add it to the scroll area's widget's layout.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/69082882",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Sockets in Pascal How do you use network sockets in Pascal?
A: Here's an example taken from http://www.bastisoft.de/programmierung/pascal/pasinet.html
program daytime;
{ Simple client program }
uses
sockets, inetaux, myerror;
const
RemotePort : Word = 13;
var
Sock : LongInt;
sAddr : TInetSockAddr;
sin, sout : Text;
Line : String;
begin
if ParamCount = 0 then GenError('Supply IP address as parameter.');
with sAddr do
begin
Family := af_inet;
Port := htons(RemotePort);
Addr := StrToAddr(ParamStr(1));
if Addr = 0 then GenError('Not a valid IP address.');
end;
Sock := Socket(af_inet, sock_stream, 0);
if Sock = -1 then SockError('Socket: ');
if not Connect(Sock, sAddr, sizeof(sAddr)) then SockError('Connect: ');
Sock2Text(Sock, sin, sout);
Reset(sin);
Rewrite(sout);
while not eof(sin) do
begin
Readln(sin, Line);
Writeln(Line);
end;
Close(sin);
Close(sout);
Shutdown(Sock, 2);
end.
A: If you're using FPC or Lazarus(which is basically a rad IDE for FPC and a clone of delphi) you could use the Synapse socket library. It's amazing.
A: If you are using Delphi, I highly recommend Indy sockets, a set of classes for easy manipulation of sockets and many other internet protocols (HTTP, FTP, NTP, POP3 etc.)
A: You cannot use OpenSSL with Indy version 10.5 that shippes with Delphi 2007. You have to download version 10,6 from http://www.indyproject.org/ and install it into the IDE.
Note that other packages might use Indy, like RemObjects, and therefore they have to be re-compiled too and this can be tricky due to cross-references.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/17054",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Google Cloud Instance Groups - There is no backend service attached to the instance group I am getting an error on an instance group after updating the autoscaler min and max values.
This is running from Google Cloud Functions
var url = `https://www.googleapis.com/compute/v1/projects/${projectId}/regions/${groupRegion}/autoscalers/`;
{
url: url,
method: 'POST',
data: {
"name": "${groupName}",
"target": `https://www.googleapis.com/compute/v1/projects/${projectId}/regions/${groupRegion}/instanceGroupManagers/${groupName}`,
"autoscalingPolicy": {
"minNumReplicas": `${groupSizeMin}`,
"maxNumReplicas": `${groupSizeMax}`,
"loadBalancingUtilization": {
"utilizationTarget": 0.8
},
"coolDownPeriodSec": 90
}
}
}
The above is successful in setting the min and max values, however an error comes up on the Instance Group.
This is the status that comes up on the instance group page on Google Cloud Console
"There is no backend service attached to the instance group"
If I go into cloud console and remove the Auto Scaling by setting it to "Off", Save, and then turn it back on in the console, then the error is not there.
What am I missing during this update?
A: From the autoscalers documentation, the property autoscalingPolicy.loadBalancingUtilization.utilizationTarget is only for setting an HTTP(S) load balancer.
If this is not the case, you should remove it from your query and the error will disappear.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/54870088",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to rescale widgets in a layout? I have a widget (lets call it a main widget), which should display another two widgets. I am using QGridLayout to position these two widgets in the main widget. (This is just simplified. I really got 5 widgets in the main window)
Initially, these two widgets are of the same size, but they can rescale. For example, the 2nd widget should be displayed 2, 3 or 4 times bigger as the 1st widget, but both should be displayed.
Something like this :
I tried using addWidget, with stretching the 2nd widget over rows and columns, but that didn't work as expected (the widget's sizes remained the same)
So, how would you suggest me to achieve as requested?
If QGridLayout is not the right class, what should I use?
EDIT:
Some types:
...
struct info
{
int item;
int row;
int column;
int rowSpan;
int columnSpan;
}
typedef std::vector< info > LayoutDefinition;
...
The class WindowsContainer contains this :
vector< QWidget* > containers;
Here is the method that updates the layout:
void WindowsContainer::SetNewLayout( const LayoutDefinition & newLayoutDef )
{
// hide all containers
for ( std::vector< QWidget* >::iterator it = containers.begin(); containers.end() != it; ++ it )
{
(*it)->hide();
}
// remove all items in the layout, and release the layout
QLayout * currentLayout( layout() );
if ( 0 != currentLayout )
{
// remove all items in the layout
// (this code is taken from the reference page for the QLayout::takeAt() function)
QLayoutItem *child;
while ( ( child = currentLayout->takeAt( 0 ) ) != 0 )
{
delete child;
}
}
delete( currentLayout );
// form the new layout
QGridLayout *newLayout = new QGridLayout( this );
newLayout->setSpacing( 0 );
newLayout->setContentsMargins( 0, 0, 0, 0 );
for ( LayoutDefinition::const_iterator it = newLayoutDef.begin(); newLayoutDef.end() != it; ++ it )
{
QWidget * w( containers.at( it->item ) );
newLayout->addWidget( w,
it->row,
it->column,
it->rowSpan,
it->columnSpan
);
w->show();
}
// update the layout of this object
setLayout( newLayout );
}
It all works, until I try to set rowSpan and columnSpan. Both images still occupy the same area size.
I also tried with spacers, and that didn't work (not sure if I did it correctly).
A: Yes, this can be accomplished with layouts, spacers and size policies. Here is a screen shot from QtCreator that reproduces the effect you are looking for:
The "TopWidget" will occupy as little space as necessary as dictated by the widgets it contains and the "BottomWidget" will expand to occupy all remaining space when the application window is resized.
The "BottomWidget" has both horizontal and vertical size policies set to "expanding".
A: I figured out how to do it : it is enough to set the stretch factors.
In the above example :
for ( LayoutDefinition::const_iterator it = newLayoutDef.begin(); newLayoutDef.end() != it; ++ it )
{
QWidget * w( containers.at( it->item ) );
newLayout->addWidget( w, it->row, it->column );
w->show();
}
newLayout->setRowStretch( 0, 1 );
newLayout->setRowStretch( 1, 2 );
This will cause the 2nd row to be two times bigger then the 1st row.
A: It's impossible. Layout is a thingy that is supposed to automatically manage layout and size of widgets. Write your own layout.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7598178",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Migrate base odoo12 I want to migrate the database from one computer to another. I downloaded the backup and transferred all installed modules to this computer. But when I enter the database, I get an error:
raise QWebException("Error to render compiling AST", e, path, node and etree.tostring(node[0], encoding='unicode'), name) odoo.addons.base.models.qweb.QWebException: 'res.users' object has no attribute 'sidebar_type' Traceback (most recent call last): File "c:\program files (x86)\odoo
12.0\server\odoo\addons\base\models\qweb.py", line 346, in compiled_fn
return compiled(self, append, new, options, log) File "", line 1, in template_178_234 File "", line 2, in body_call_content_233 AttributeError: 'res.users' object has no attribute 'sidebar_type' Error to render compiling AST AttributeError: 'res.users' object has no attribute 'sidebar_type' Template: 178 Path: /templates/t/t/t[4]
Node:< t t-set="body_classname" t-value="'o_web_client mk_sidebar_type' + request.env.user.sidebar_type or 'large'"/> - - -
I looked at this place. This muk_web_theme module:
<?xml version="1.0" encoding="UTF-8"?>
<odoo>
<template id="webclient_bootstrap" name="Web Client" inherit_id="web.webclient_bootstrap">
<xpath expr="//t[@t-set='body_classname']" position="after">
<t t-set="body_classname" t-value="'o_web_client mk_sidebar_type_' + request.env.user.sidebar_type or 'large'"/>
</xpath>
<xpath expr="//*[hasclass('o_main')]" position="attributes">
<attribute name="t-attf-class">o_main mk_chatter_position_#{request.env.user.chatter_position or 'normal'}</attribute>
</xpath>
</template>
</odoo>
from odoo import models, fields, api
class ResUsers(models.Model):
_inherit = 'res.users'
#----------------------------------------------------------
# Defaults
#----------------------------------------------------------
@api.model
def _default_sidebar_type(self):
return self.env.user.company_id.default_sidebar_preference or 'small'
@api.model
def _default_chatter_position(self):
return self.env.user.company_id.default_chatter_preference or 'sided'
#----------------------------------------------------------
# Database
#----------------------------------------------------------
sidebar_type = fields.Selection(
selection=[
('invisible', 'Invisible'),
('small', 'Small'),
('large', 'Large')
],
required=True,
string="Sidebar Type",
default=lambda self: self._default_sidebar_type())
chatter_position = fields.Selection(
selection=[
('normal', 'Normal'),
('sided', 'Sided'),
],
required=True,
string="Chatter Position",
default=lambda self: self._default_chatter_position())
#----------------------------------------------------------
# Setup
#----------------------------------------------------------
def __init__(self, pool, cr):
init_res = super(ResUsers, self).__init__(pool, cr)
type(self).SELF_WRITEABLE_FIELDS = list(self.SELF_WRITEABLE_FIELDS)
type(self).SELF_WRITEABLE_FIELDS.extend(['sidebar_type'])
type(self).SELF_WRITEABLE_FIELDS.extend(['chatter_position'])
type(self).SELF_READABLE_FIELDS = list(self.SELF_READABLE_FIELDS)
type(self).SELF_READABLE_FIELDS.extend(['sidebar_type'])
type(self).SELF_READABLE_FIELDS.extend(['chatter_position'])
return init_res
What could be the problem?
A: Check if modules are visible to odoo. Module versions should stay the same when you are migrating.
Try with empty base and see if there are any errors after initializing your database.
Try to install your modules to empty base.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/63132450",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: undefined symbol: rb_thread_select Hi I have working with rbenv and using rails application it is working good, when I switched application to another computer , After bundle install
When I run "rails s" or "bundle exec rails s"
This is error come
/home/{user}/.rbenv/versions/2.2.2/bin/ruby: symbol lookup error: /home/{user}/.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/extensions/x86_64-linux/2.2.0-static/pg-0.13.2/pg_ext.so: undefined symbol: rb_thread_select
can anyone guide how to overcome this solution
A: The pg gem you are using 0.13.2 is referencing to a ruby method rb_thread_select, which is not present in 2.2.0+. It was there in the older version of ruby. So you can't use that version of pg in ruby 2.2.0+.
Upgrade to a version 0.15.0 +, which doesn't use rb_thread_select
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/32372487",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Not all Nintex workflow steps occuring I have a "visit notification" workflow which is triggered when "visit required?"=Yes and "Sales email sent? "=No.
The workflow steps are
*
*Send email
*Change "visit date" to "Date to be confirmed"
*Change "visit email sent? "=Yes (to ensure the workflow does not
trigger more than once.)
The workflow triggered at the correct time and completed with no errors.
*
*Send email --> email was sent
*"visit date" --> was changed to "Date to be confirmed"
*"visit email sent? " --> stayed at No
Consequently when the item was edited again the workflow was triggered a second time.
Why would one of the update field steps work correctly and one not?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/43897113",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Eclipse with Jython doesn't understand Java Imports I have set up Eclipse to use Jython as documented here:
http://www.jython.org/jythonbook/en/1.0/JythonIDE.html (Under Minimal Configuration)
I am following this tutorial as best I can, but for some reason the IDE does not understand Java imports. The line javax.swing import JFrame, JLabel underlines JFrame and JLabel as unresolved.
Code in entirety:
# -*- coding: utf-8 -*-
import sys
from optparse import OptionParser
greetings = dict(en=u'Hello %s!',
es=u'Hola %s!',
fr=u'Bonjour %s!',
pt=u'Al %s!')
uis = {}
def register_ui(ui_name):
def decorator(f):
uis[ui_name] = f
return f
return decorator
def message(ui, msg):
if ui in uis:
uis[ui](msg)
else:
raise ValueError("No greeter named %s" % ui)
def list_uis():
return uis.keys()
@register_ui('console')
def print_message(msg):
print msg
@register_ui('window')
def show_message_as_window(msg):
from javax.swing import JFrame, JLabel
frame = JFrame(msg,
defaultCloseOperation=JFrame.EXIT_ON_CLOSE,
size=(100, 100),
visible=True)
frame.contentPane.add(JLabel(msg))
if __name__ == "__main__":
parser = OptionParser()
parser.add_option('--ui', dest='ui', default='console',
help="Sets the UI to use to greet the user. One of: %s" %
", ".join("'%s'" % ui for ui in list_uis()))
parser.add_option('--lang', dest='lang', default='en',
help="Sets the language to use")
options, args = parser.parse_args(sys.argv)
if len(args) < 2:
print "Sorry, I can't greet you if you don't say your name"
sys.exit(1)
if options.lang not in greetings:
print "Sorry, I don't speak '%s'" % options.lang
sys.exit(1)
msg = greetings[options.lang] % args[1]
try:
message(options.ui, msg)
except ValueError, e:
print "Invalid UI name\n"
print "Valid UIs:\n\n" + "\n".join(' * ' + ui for ui in list_uis())
sys.exit(1)
When I run it I selected Jython. So I don't understand why Eclipse doesn't understand. Do I need to include Jython JAR files in every Jython project...?
Thanks in advance.
A: Have you created a new PyDev project for this? Without that, Eclipse won't be able to find your full Jython installation, which could explain the underlinings. In my environment (Eclipse Kepler, PyDev, and Jython 2.5.2) it works correctly.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/18275332",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Graphviz compacting graph I'm generating a graph with graphviz and the circo tool it provides.
The graph generated is a nice shape, but the lengths of the edges between the nodes are a lot larger than they need to be, which makes the text of the nodes be small (relative to the output image) and so hard to read.
How can I make the node be bigger (relatively) in the output image, so that the text inside the nodes is easier to read,
Output image:
Source graph file:
digraph G {
FoundUrlToFollow [shape=box];
"Fetch the URL" [shape=circle];
FoundUrlToFollow -> "Fetch the URL";
ResponseReceived [shape=box];
"Fetch the URL" [shape=circle, label=<Fetch the URL>];
"Fetch the URL" -> ResponseReceived;
ResponseError [shape=box];
"Fetch the URL" [shape=circle, label=<Fetch the URL>];
"Fetch the URL" -> ResponseError;
ResponseReceived [shape=box];
"Log response" [shape=circle];
ResponseReceived -> "Log response";
ResponseReceived [shape=box];
"Is the response OK?" [shape=circle];
ResponseReceived -> "Is the response OK?";
ResponseOk [shape=box];
"Is the response OK?" [shape=circle, label=<Is the response<br/>OK?>];
"Is the response OK?" -> ResponseOk;
ResponseOk [shape=box];
"Is the response HTML?" [shape=circle];
ResponseOk -> "Is the response HTML?";
HtmlToParse [shape=box];
"Is the response HTML?" [shape=circle, label=<Is the response<br/>HTML?>];
"Is the response HTML?" -> HtmlToParse;
HtmlToParse [shape=box];
"Parse the HTML to find links" [shape=circle];
HtmlToParse -> "Parse the HTML to find links";
FoundUrl [shape=box];
"Parse the HTML to find links" [shape=circle, label=<Parse the HTML<br/>to find links>];
"Parse the HTML to find links" -> FoundUrl;
FoundUrl [shape=box];
"Should we follow this URL?" [shape=circle];
FoundUrl -> "Should we follow this URL?";
FoundUrlToSkip [shape=box];
"Should we follow this URL?" [shape=circle, label=<Should we<br/>follow this<br/>URL?>];
"Should we follow this URL?" -> FoundUrlToSkip;
FoundUrlToFollow [shape=box];
"Should we follow this URL?" [shape=circle, label=<Should we<br/>follow this<br/>URL?>];
"Should we follow this URL?" -> FoundUrlToFollow;
FoundUrlToSkip [shape=box];
"Log skipped links" [shape=circle];
FoundUrlToSkip -> "Log skipped links";
graph [label="Switches are circles. Events are boxes.", fontsize="12", overlap=scale];
edge [splines=curved];
}
Command:
circo -Tpng -ograph_so.png graph.dot
A: I would try to add mindist (less than 1) to graph:
graph [..., overlap=scale, mindist=.6];
[edit]
maybe the renderer version make a difference: here is the outcome on my machine
A: Try varying -Gsize (units of inches) and -Gdpi. You'll find that if you change them both together, you get different outputs with the same pixel size, but with different spacing between the nodes relative to the size of the nodes themselves. -Gnodesep and -Nfontsize might also be useful to tweak. You might also have better luck by rendering to EPS or PDF or SVG and then converting that to PNG, instead of using Graphviz's PNG renderer. Getting pleasing output from Graphviz is, in my experience, a very inexact science.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/41494943",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: PHP SELECT Query in FOR LOOP not executing I have a SELECT query in the FOR loop that will just not return a value, I have echoed the parameters and also run the SQL and they appear fine.
Any ideas as to where I am going wrong?
I am posting values from a multi row form that has the following text fields:
F1,
Grade_system_id
Grade
Grade_System_id
I want to look up the Grade_Points using Grade and Grade_System_id, but not able to.
The error checks dont suggest any errors.
foreach ($_POST['F1'] as $Lesson_Class_id => $Response) {
$Grade_System_id = $_POST['Grade_System_id'][$Lesson_Class_id];
$G1 = $_POST['G1'][$Lesson_Class_id];
$Lesson_Class_id=trim($_POST['Lesson_Class_id']);
$I1 = $_POST['I1'][$Lesson_Class_id];
$stmt = $conn -> prepare('SELECT Grade_Points FROM Grades WHERE Grade=? AND Grade_System_id=?');
$stmt -> bind_param('si', $G1, $Grade_System_id);
$stmt -> execute();
$stmt -> store_result();
$stmt -> bind_result($Grade_Points);
$stmt -> fetch();
echo $G1;
echo $Grade_System_id;
echo $Response;
echo $Grade_Points;
if ($Response=="Completed") {
$T_Points=$Grade_Points;
}
if ($Response!="Completed") {
$T_Points="";
}
$stmt = $conn -> prepare('UPDATE Lesson_CLass SET I1 = ?, F1=?, T_Points=? WHERE Lesson_Class_id= ?');
//echo 'Student ID: ' . $Lesson_Class_id . ' Outcome: ' . $Response . "<br>";
$stmt -> bind_param('ssss', $I1,$Response, $T_Points, $Lesson_Class_id);
$stmt -> execute();
}
?>
The query is unable to return 'Grade Points'
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/74338847",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to prepare Pandas df for Venn diagram I have a Pandas dataframe as follows:
+-----+-----------+
| ID | VALUE |
+-----+-----------+
| A | Today |
+-----+-----------+
| A | Yesterday |
+-----+-----------+
| B | Tomorrow |
+-----+-----------+
| C | Tomorrow |
+-----+-----------+
| D | Today |
+-----+-----------+
| D | Tomorrow |
+-----+-----------+
| E | Today |
+-----+-----------+
| E | Yesterday |
+-----+-----------+
| E | Tomorrow |
+-----+-----------+
I want to get counts of each ID's "overlap", as I want to construct a Venn diagram from this data.
E.g. in this case, 2 IDs are in 'Today' as well as in 'Tomorrow'. 2 IDs are also in both 'Today' and 'Yesterday'.
How do I go about doing this? I've tried various combinations of value_counts and group_by, but I've had no luck coming up with something intelligent.
A: You can use crosstab to get the dummies, then matrix product to see cooccurrences:
s = pd.crosstab(df['ID'],df['VALUE'])
pair_intersection = s.T @ s
all_three = s.ne(0).all(1)
Then, pair_intersection looks like:
VALUE Today Tomorrow Yesterday
VALUE
Today 3 2 2
Tomorrow 2 4 1
Yesterday 2 1 2
Then counts of two overlapping groups can be extracted using pair_intersection.at['Today', 'Tomorrow'].
all_three is
ID
A False
B False
C False
D False
E True
dtype: bool
And thus the number of instances that fall in all three groups is sum(all_three)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/65038097",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Lua why is 'require' unsafe to use in a sandbox environment? Via this page: http://lua-users.org/wiki/SandBoxes require is marked as unsafe and it's because:
*
*modifies globals (e.g. package.loaded)
*provides access to environments outside the sandbox
*and accesses the file system
Pretty much all pure Lua libraries use 'require' so not having this be safe is a huge pain because you can't use any pure Lua libraries. I don't understand these unsafe reasons. It loads other Lua files in a library. Why is that unsafe?
A: Require loads and executes code in the global environment.
For example, lets create a simple sandbox (Lua >= 5.2):
-- example.lua
my_global = 42
local sandbox
do
local _ENV = { require = require, print = print }
function sandbox()
print('<sandbox> my_global =', my_global)
require 'example_module'
end
end
print('<global> my_global =', my_global)
sandbox()
print('<global> my_global =', my_global)
Now, lets create a module that changes my_global:
-- example_module.lua
print('<module> my_global =', my_global)
my_global = nil
The expectation is that inside the sandbox the only functions available are require and print. Code inside the sandbox should not be able to access the global my_global.
Run the example and you will see:
$ lua example.lua
<global> my_global = 42 -- The global environment, Ok.
<sandbox> my_global = nil -- Inside the sandbox, Ok.
<module> my_global = 42 -- Inside the sandbox, but loaded with require. Whoops, we have access to the global environment.
<global> my_global = nil -- The module changed the value and it is reflected in the global environment.
The module has broken out of the sandbox.
A: Since it has access to the file system and the global environment, it can execute code and modify values it's not supposed to modify.
You can implement and make available your own require method that satisfies your sandbox requirements. For example, you can preload those libraries you verified and have "require" only return preloaded results.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/38596386",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Django: AttributeError: 'NoneType' object has no attribute 'username' I am trying to create a chat app and got stuck with this error.
I am getting this error though I'm logged in as a superuser.
My models.py
class Message(models.Model):
author = models.ForeignKey(User, null=True, related_name='author_messages', on_delete=models.CASCADE)
content = models.TextField()
timestamp = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.author.username
def last_10_messages():
return Message.objects.order_by('-timestamp').all()[:10]
Where I try to access it:
for message in messages:
print("message printing")
result.append(self.message_to_json(message))
then
def message_to_json(self, message):
print("message.id=",message.id)
print(message.author.username)
return {
'id': message.id,
'author': message.author.username,
'content': message.content,
'timestamp': str(message.timestamp)
}
When i print the length of the object i notice it says 2..idk why coz i haven't added any messages yet.
As the loop goes twice i noticed that the username got printed the first time but raised an error for the second loop(though idk why it loops coz i dont even have messages to load yet)
like here
The error also appears to be in the return function in my models class as in here
I've read other posts but their errors were different...
Would be really grateful if sum1 cud help out!!
or how do i define and access author variables the correct way
A: If you allow the author to not be set then you need to make sure it has been set before you try to use it.
Be a little defensive like this;
class Message(models.Model):
author = models.ForeignKey(User, null=True, related_name='author_messages', on_delete=models.CASCADE)
content = models.TextField()
timestamp = models.DateTimeField(auto_now_add=True)
def __str__(self):
if not self.author:
return "Anonymous"
return self.author.username
def last_10_messages():
return Message.objects.order_by('-timestamp').all()[:10]
def message_to_json(self, message):
if message.author:
author = message.author.username
else:
author = "Anonymous"
return {
'id': message.id,
'author': author,
'content': message.content,
'timestamp': str(message.timestamp)
}
A: It seems that you have more the one message even if you said you did not create any. At least you must have created one with the username aysha. The message with the id=1 seems to have no user attached ... so you get the error when trying to access message.author.username.
To add the if not self.author in the __str__ of Message does not change anything as you access or print message.author.username and not message. It would help if you print(message) and message has no author.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/65376523",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Office Analysis Prompts Value Macro I have a vba code to open prompts window in excel:
Application.Run("SAPExecuteCommand", "ShowPrompts")
But my problem is I dont know how to put value in Prompts window through Macro. Can anyone help about that? Any code sample?
For instance in this picture I want to put 1000 in 0BUCHUNG field. I would like to do this through Macro code and click ok. I cant record a Macro while doing these steps I dont know why, that is why I am asking maybe there is kind of code to perform it in Macro. Prompts Window
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/71378493",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: ECMA in Datapower anybody know how to access XML data using xpath expression in ECMA Script(datapower)?
IBM infocenter doesn't have this information on how to access XML data
Please provide if you have any sample script for accessing XML data
Thanks
A: GatewayScript doesn't support any XML Dom in the ECMA (Node.js) implemented.
I have however used the modules XPATH and DOM with great success.
Download XMLDom (https://github.com/jindw/xmldom) and Xpath (https://github.com/goto100/xpath) Node.js modules and add the following scripts to your DP directory:
*
*dom-parser.js
*dom.js
*sax.js
*xpath.js
To use it in DataPower GWS you first need to get the XML data from INPUT:
// This is where we start, grab the INPUT as a buffer
session.input.readAsBuffers(function(readAsBuffersError, data) {
if (readAsBuffersError) {
console.error('Error on readAsBuffers: ' + readAsBuffersError);
session.reject('Error on readAsBuffers: ' + readAsBuffersError);
} else {
if (data.slice(0,5).toString() === '<?xml') {
console.log('It is XML!');
parseXML(data);
}
} //end read as buffers error
}); //end read as buffer function
function parseXML(xml) {
// Load XML Dom and XPath modules
var select = require('local:///xpath.js');
var dom = require('local:///dom-parser.js');
var doc = new dom.DOMParser().parseFromString(xml.toString(), 'text/xml');
// Get attribute
var nodes = select(doc, "//root/element1/@protocol");
try {
var val = nodes[0].value.toString();
console.log('found xml attribute as ['+val+']');
} catch(e) {
// throw error here
}
// Get an element
nodes = select(doc, "//root/element1/child1");
try {
var val = nodes[0].firstChild.data;
console.log('elemnt found as ['+val+']');
} catch(e) {
//throw error here
}
}
That should be a working sample... You need to change the path for the modules if you move them.
I have a directory in store:/// where I add my GWS modules.
Hope you'll get it to fly!
A: At least from 7.0.0 firmware version Gatewayscript is able to work with XPATH and DOM easily. Snippet from the DP store:
//reading body from the rule input
session.input.readAsXML(function (error, nodeList) {
if (error) {
//error behaviour
} else {
var domTree;
try {
domTree = XML.parse(nodeList);
} catch (error) {
//error behaviour
}
var transform = require('transform'); //native gatewayscript module
transform.xpath('/someNode/anotherNode/text()', domTree, function(error, result){
if(error){
//error behaviour
}
//some use of result, for example putting it to output
session.output.write(result);
}
});
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/26582051",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Pass list of arguments to a command for each line In a bash script:
I have this list of arguments (or directories in this case):
Directories=(
/Dir1/
/Dir2/
/Dir3/
)
And I want every item (or line) of this list, to be passed as a argument to a command.
Like this:
cd /Dir1/
cd /Dir2/
cd /Dir3/
(Replace "cd" with any command)
I tried this:
cd ${Directories[@]}
But that results in this:
cd /Dir1/ /Dir2/ /Dir3/
How I can make the script run the command each time with a new line, until it reaches the end?
A: For loop can be used as well
#!/bin/bash
Directories=( /dir1 /dir2 /dir3)
for dir in "${Directories[@]}"
do
cd "${dir}"
done
A: Update: In fact, the solution below is not suitable for commands meant to alter the current shell's environment, such as cd. It is suitable for commands that invoke external utilities.
For commands designed to alter the current shell's environment, see Balaji Sukumaran's answer.
xargs is the right tool for the job:
printf '%s\n' "${Directories[@]}" | xargs -I % <externalUtility> %
*
*printf '%s\n' "${Directories[@]}" prints each array element on its own line.
*xargs -I % <externalUtility> % invokes external command <externalUtility> for each input line, passing the line as a single argument; % is a freely chosen placeholder.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/34376428",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: moving laravel public folder gives ' looks like something went wrong ' it worked fine when the file structure was:
/bin
....
....
/public_ftp
/public_html/app
/public_html/bootstrap
...
/public_html/public
....
....
/www
but when i changed it to:
/bin
/laravel/app
/laravel/bootstrap
....
....
/public_ftp
...
/public_html/css
/public_html/js
/public_html/index.php
....
....
/www
and i also changed index.php to:
$app = require_once __DIR__.'/../laravel/bootstrap/app.php';
require __DIR__.'/../laravel/bootstrap/autoload.php';
but when i opened index.php it shows
Whoops, looks like something went wrong.
laravel log
production.ERROR: exception 'RuntimeException' with message 'The only supported ciphers are AES-128-CBC and AES-256-CBC with the correct key lengths.' in /home/fabitzza/laravel/vendor/laravel/framework/src/Illuminate/Encryption/Encrypter.php:43
this error was not there before when every this was in public_html
A: Run this command
php artisan key:generate
and the clear config cache using
php artisan config:cache
Hope this will work!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/41228202",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: IndexError: tuple index out of range when using Datasets with tensorflow 2.1 Generating my own TFRecords and I can't seem to properly use datasets in my models. Just to test if it was my current files or something in the model code I used tfds with MNIST and am having the same error.
The error is: IndexError: tuple index out of range
The full output is below. I'm doing this from a jupyter notebook if it changes anything.
1/Unknown - 0s 47ms/step
--------------------------------------------------------------------------- IndexError Traceback (most recent call last) <ipython-input-302-f8e9089d7285> in <module>
----> 1 model.fit(dataset['train'].batch(4096))
~/miniconda3/envs/keras/lib/python3.7/site-packages/tensorflow_core/python/keras/engine/training.py in fit(self, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, validation_freq, max_queue_size, workers, use_multiprocessing,
**kwargs)
817 max_queue_size=max_queue_size,
818 workers=workers,
--> 819 use_multiprocessing=use_multiprocessing)
820
821 def evaluate(self,
~/miniconda3/envs/keras/lib/python3.7/site-packages/tensorflow_core/python/keras/engine/training_v2.py in fit(self, model, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, validation_freq, max_queue_size, workers, use_multiprocessing,
**kwargs)
340 mode=ModeKeys.TRAIN,
341 training_context=training_context,
--> 342 total_epochs=epochs)
343 cbks.make_logs(model, epoch_logs, training_result, ModeKeys.TRAIN)
344
~/miniconda3/envs/keras/lib/python3.7/site-packages/tensorflow_core/python/keras/engine/training_v2.py in run_one_epoch(model, iterator, execution_function, dataset_size, batch_size, strategy, steps_per_epoch, num_samples, mode, training_context, total_epochs)
126 step=step, mode=mode, size=current_batch_size) as batch_logs:
127 try:
--> 128 batch_outs = execution_function(iterator)
129 except (StopIteration, errors.OutOfRangeError):
130 # TODO(kaftan): File bug about tf function and errors.OutOfRangeError?
~/miniconda3/envs/keras/lib/python3.7/site-packages/tensorflow_core/python/keras/engine/training_v2_utils.py in execution_function(input_fn)
96 # `numpy` translates Tensors to values in Eager mode.
97 return nest.map_structure(_non_none_constant_value,
---> 98 distributed_function(input_fn))
99
100 return execution_function
~/miniconda3/envs/keras/lib/python3.7/site-packages/tensorflow_core/python/eager/def_function.py in __call__(self, *args, **kwds)
566 xla_context.Exit()
567 else:
--> 568 result = self._call(*args, **kwds)
569
570 if tracing_count == self._get_tracing_count():
~/miniconda3/envs/keras/lib/python3.7/site-packages/tensorflow_core/python/eager/def_function.py in _call(self, *args, **kwds)
613 # This is the first call of __call__, so we have to initialize.
614 initializers = []
--> 615 self._initialize(args, kwds, add_initializers_to=initializers)
616 finally:
617 # At this point we know that the initialization is complete (or less
~/miniconda3/envs/keras/lib/python3.7/site-packages/tensorflow_core/python/eager/def_function.py in _initialize(self, args, kwds, add_initializers_to)
495 self._concrete_stateful_fn = (
496 self._stateful_fn._get_concrete_function_internal_garbage_collected(
# pylint: disable=protected-access
--> 497 *args, **kwds))
498
499 def invalid_creator_scope(*unused_args, **unused_kwds):
~/miniconda3/envs/keras/lib/python3.7/site-packages/tensorflow_core/python/eager/function.py in _get_concrete_function_internal_garbage_collected(self, *args,
**kwargs) 2387 args, kwargs = None, None 2388 with self._lock:
-> 2389 graph_function, _, _ = self._maybe_define_function(args, kwargs) 2390 return graph_function 2391
~/miniconda3/envs/keras/lib/python3.7/site-packages/tensorflow_core/python/eager/function.py in _maybe_define_function(self, args, kwargs) 2701 2702 self._function_cache.missed.add(call_context_key)
-> 2703 graph_function = self._create_graph_function(args, kwargs) 2704 self._function_cache.primary[cache_key] = graph_function 2705 return graph_function, args, kwargs
~/miniconda3/envs/keras/lib/python3.7/site-packages/tensorflow_core/python/eager/function.py in _create_graph_function(self, args, kwargs, override_flat_arg_shapes) 2591 arg_names=arg_names, 2592 override_flat_arg_shapes=override_flat_arg_shapes,
-> 2593 capture_by_value=self._capture_by_value), 2594 self._function_attributes, 2595 # Tell the ConcreteFunction to clean up its graph once it goes out of
~/miniconda3/envs/keras/lib/python3.7/site-packages/tensorflow_core/python/framework/func_graph.py in func_graph_from_py_func(name, python_func, args, kwargs, signature, func_graph, autograph, autograph_options, add_control_dependencies, arg_names, op_return_value, collections, capture_by_value, override_flat_arg_shapes)
976 converted_func)
977
--> 978 func_outputs = python_func(*func_args, **func_kwargs)
979
980 # invariant: `func_outputs` contains only Tensors, CompositeTensors,
~/miniconda3/envs/keras/lib/python3.7/site-packages/tensorflow_core/python/eager/def_function.py in wrapped_fn(*args, **kwds)
437 # __wrapped__ allows AutoGraph to swap in a converted function. We give
438 # the function a weak reference to itself to avoid a reference cycle.
--> 439 return weak_wrapped_fn().__wrapped__(*args, **kwds)
440 weak_wrapped_fn = weakref.ref(wrapped_fn)
441
~/miniconda3/envs/keras/lib/python3.7/site-packages/tensorflow_core/python/keras/engine/training_v2_utils.py in distributed_function(input_iterator)
83 args = _prepare_feed_values(model, input_iterator, mode, strategy)
84 outputs = strategy.experimental_run_v2(
---> 85 per_replica_function, args=args)
86 # Out of PerReplica outputs reduce or pick values to return.
87 all_outputs = dist_utils.unwrap_output_dict(
~/miniconda3/envs/keras/lib/python3.7/site-packages/tensorflow_core/python/distribute/distribute_lib.py in experimental_run_v2(self, fn, args, kwargs)
761 fn = autograph.tf_convert(fn, ag_ctx.control_status_ctx(),
762 convert_by_default=False)
--> 763 return self._extended.call_for_each_replica(fn, args=args, kwargs=kwargs)
764
765 def reduce(self, reduce_op, value, axis):
~/miniconda3/envs/keras/lib/python3.7/site-packages/tensorflow_core/python/distribute/distribute_lib.py in call_for_each_replica(self, fn, args, kwargs) 1817 kwargs
= {} 1818 with self._container_strategy().scope():
-> 1819 return self._call_for_each_replica(fn, args, kwargs) 1820 1821 def _call_for_each_replica(self, fn, args, kwargs):
~/miniconda3/envs/keras/lib/python3.7/site-packages/tensorflow_core/python/distribute/distribute_lib.py in _call_for_each_replica(self, fn, args, kwargs) 2162 self._container_strategy(), 2163 replica_id_in_sync_group=constant_op.constant(0, dtypes.int32)):
-> 2164 return fn(*args, **kwargs) 2165 2166 def _reduce_to(self, reduce_op, value, destinations):
~/miniconda3/envs/keras/lib/python3.7/site-packages/tensorflow_core/python/autograph/impl/api.py in wrapper(*args, **kwargs)
290 def wrapper(*args, **kwargs):
291 with ag_ctx.ControlStatusCtx(status=ag_ctx.Status.DISABLED):
--> 292 return func(*args, **kwargs)
293
294 if inspect.isfunction(func) or inspect.ismethod(func):
~/miniconda3/envs/keras/lib/python3.7/site-packages/tensorflow_core/python/keras/engine/training_v2_utils.py in train_on_batch(model, x, y, sample_weight, class_weight, reset_metrics, standalone)
414 x, y, sample_weights = model._standardize_user_data(
415 x, y, sample_weight=sample_weight, class_weight=class_weight,
--> 416 extract_tensors_from_dataset=True)
417 batch_size = array_ops.shape(nest.flatten(x, expand_composites=True)[0])[0]
418 # If `model._distribution_strategy` is True, then we are in a replica context
~/miniconda3/envs/keras/lib/python3.7/site-packages/tensorflow_core/python/keras/engine/training.py in _standardize_user_data(self, x, y, sample_weight, class_weight, batch_size, check_steps, steps_name, steps, validation_split, shuffle, extract_tensors_from_dataset) 2381 is_dataset=is_dataset, 2382 class_weight=class_weight,
-> 2383 batch_size=batch_size) 2384 2385 def _standardize_tensors(self, x, y, sample_weight, run_eagerly, dict_inputs,
~/miniconda3/envs/keras/lib/python3.7/site-packages/tensorflow_core/python/keras/engine/training.py in _standardize_tensors(self, x, y, sample_weight, run_eagerly, dict_inputs, is_dataset, class_weight, batch_size) 2467 shapes=None, 2468 check_batch_axis=False, # Don't enforce the batch size.
-> 2469 exception_prefix='target') 2470 2471 # Generate sample-wise weight values given the `sample_weight` and
~/miniconda3/envs/keras/lib/python3.7/site-packages/tensorflow_core/python/keras/engine/training_utils.py in standardize_input_data(data, names, shapes, check_batch_axis, exception_prefix)
510 'for each key in: ' + str(names))
511 elif isinstance(data, (list, tuple)):
--> 512 if isinstance(data[0], (list, tuple)):
513 data = [np.asarray(d) for d in data]
514 elif len(names) == 1 and isinstance(data[0], (float, int)):
IndexError: tuple index out of range
Minimal code to reproduce this:
from tensorflow.keras.layers import Dense, Embedding, Flatten, Lambda, Subtract, Input, Concatenate, Average, Reshape, GlobalAveragePooling1D, Dot, Dropout
from tensorflow.keras.models import Model, Sequential
from tensorflow.keras.utils import Sequence
from tensorflow.keras import initializers
import tensorflow_datasets as tfds
tfds.list_builders()
dataset, info = tfds.load("mnist", with_info=True)
inputs = Input((28, 28, 1), name="image")
First = Dense(128, activation="relu")
Second = Dropout(0.2)
Third = Dense(10, activation="softmax", name="label")
first = First(inputs)
second = Second(first)
third = Third(second)
model = Model(inputs=[inputs], outputs=[third])
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
model.fit(dataset['train'].batch(4096))
I bet I'm missing something in the docs, but I can't figure it out and have been hammering away at it for a few hours. The model trains fine from a generator but as the datasets get larger I'd like to switch over.
A: Adding as_supervised=True to tfds.load() will solve the problem. Another question is why this problem occurs in the first place, probably a bug in TF.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/59761890",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to migrate a table using Business Intelligence Dev Studio? I am trying to migrate a table from a remote server into my local database. However, I do not want to create an intermediate csv or tab-delimited file because of the content of the columns inside this table. Some columns are huge and I don't really want to remember all the data types. I was wondering if there is an intermediate format that I can just dump the table into and then re-import it back into my local database.
I was suggested to use Business Intelligence Development Studio for this purpose but am clueless on how to actually use this tool. Maybe I am using the wrong set of keywords but Google is of no help either.
Can someone point me in the right direction?
A: I don't believe you need Business Intelligence Development Studio for this. You should be able to link to the remote server, run an external query and then do an SELECT INTO statement to insert the table data directly into your database.
A: (i am assuming that you are running SQL Server 2005+)
If you have access to both SQL Servers, simply use the Data Import / Export wizard.
*
*Open Management Studio and connect to source database server.
*Right click the source database and click Export Data.
*Follow the wizard. It will ask to target database and table. You can create a new database / table at the target system with this wizard.
You can also use SQL Script Generator, a free & great tool which allows you to script both database, table with it's data. See http://sqlscriptgenerator.com/ for more information about the tool.
And yes, you don't need Business Intelligence Development Studio.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7492900",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Jump to 'git add -i' patch command (5) directly How can I get "git add -i" to start up in patch mode directly without having to type "5" + Enter?
I know about "git add -p", but it's not the same as it doesn't show me a list of files to select from first.
This is very annoying because I'd like to jump between "git add -i" and "git commit" very quickly to turn my dirty tree into some nice looking commits.
A: It's a fairly easy change on a perl file to make this happen. I would only recommend doing this if you don't like the default git-add -p behavior of patching all files.
Find your copy of git-add--interactive and open with your favorite editor. Go to the patch_update_cmd subroutine. In there, there is an if statement which tests $patch_mode. Remove the top part of the if statement or set it so that the conditional always evaluates to false. Save and test.
An example of what I did to make this work follows.
if (0) {
@them = @mods;
}
else {
@them = list_and_choose({ PROMPT => 'Patch update',
HEADER => $status_head, },
@mods);
}
Another possible point of change would be at the very bottom of the file. You can change $patch_mode to some false value after the if statement, the effect should be the same.
Note you may have some issues if you're using a package manager or something else similar which tracks installed packages, I'm not sure.
A: What you could do, is 'git add -p' and add the filenames as commandline arguments.
with good tab completion (which only completes dirty files) it's about as effective as picking them from the menu.
A: If you don't mind bringing up a gui, just use git gui.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/2948414",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to create torrent files from magnet link or infohash I am trying to create a torrent search engine. yet I found a way to collect torrent infohashes from DHT network. My question is how can I extract .torrent files from them?
I have a MongoDB collection contains 1M-1.5M(Growing Very Quickly) torrent info hash.
A: I solved the problem myself.
I used webtorrent npm package and also created an algorithm to loop through the whole database and added the magnet link in the download task. once the client gets metadata, I just saved it to the torrent file and canceled the download.
Well, The code is not yet fully production ready. I'll Post The Code Snippet here afterward. Thank You!
UPDATE: I am using this class to download Torrent file from magnet
const Discovery = require('torrent-discovery');
const Protocol = require('bittorrent-protocol');
const ut_metadata = require('ut_metadata');
const addrToIPPort = require('addr-to-ip-port');
const net = require('net');
class TorrentDownloader {
constructor(port, trackers, timeout) {
this.SELF_HASH = '4290a5ff50130a90f1de64b1d9cc7822799affd5';
this.port = port | 6881;
this.trackers = trackers;
this.timeout = timeout | 80000;
}
downloadTorrent(infoHash) {
let self = this;
return new Promise((resolve, reject) => {
let dis = new Discovery({infoHash: infoHash, peerId: this.SELF_HASH, port: this.port, dht: true, announce: this.trackers})
.on('peer', function (peer) {
const peerAddress = {address: addrToIPPort(peer)[0], port: addrToIPPort(peer)[1]};
// console.log(`download metadata from peer ${peerAddress.address}:${peerAddress.port}`);
self.getMetadata(peerAddress, infoHash, resolve);
});
setTimeout(() => {
dis.destroy();
reject(new Error("Torrent Timeout"))
}, this.timeout)
})
}
getMetadata(peerAddress, infoHash, resolve) {
const socket = new net.Socket();
socket.setTimeout(this.timeout);
socket.connect(peerAddress.port, peerAddress.address, () => {
const wire = new Protocol();
socket.pipe(wire).pipe(socket);
wire.use(ut_metadata());
wire.handshake(infoHash, this.SELF_HASH, {dht: true});
wire.on('handshake', function (infoHash, peerId) {
wire.ut_metadata.fetch();
});
wire.ut_metadata.on('metadata', function (rawMetadata) {
resolve(rawMetadata);
wire.destroy();
socket.destroy()
})
});
socket.on('error', err => {
socket.destroy();
});
}
}
module.exports = TorrentDownloader;
A: Given just an infohash, e.g.:
*
*463e408429535139a0bbb5dd676db10d5963bf05
you can use:
BEP: 9 - Extension for Peers to Send Metadata Files
The purpose of this extension is to allow clients to join a swarm and complete a download without the need of downloading a .torrent file first. This extension instead allows clients to download the metadata from peers. It makes it possible to support magnet links, a link on a web page only containing enough information to join the swarm (the info hash).
You use DHT to find the distributed trackers.
Then you use the distributed trackers to find the peers who have the torrent.
Then you can download the torrent metadata from a peer.
You send the bencoded metadata request to the peer:
{
"msg_type": 0, ; 0==>request
"piece": 0
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/52873382",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: No Persistence provider for EntityManager named defaultPersistenceUnit I am trying to use JPA in my Play app and when I try to load my app I receive a PersistenceException: No Persistence provider for EntityManager named defaultPersistenceUnit
These are my settings:
build.sbt
libraryDependencies ++= Seq(
....
"mysql" % "mysql-connector-java" % "5.1.28",
javaJpa,
"org.hibernate" % "hibernate-entitymanager" % "3.6.9.Final"
)
conf/META-INF/persistance.xml
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<persistence-unit name="defaultPersistenceUnit" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<non-jta-data-source>DefaultDS</non-jta-data-source>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLInnoDBDialect"/>
</properties>
</persistence-unit>
</persistence>
application.conf
db.default.driver=com.mysql.jdbc.Driver
db.default.url="jdbc:mysql://localhost/testDB"
db.default.user="root"
db.default.password="root"
db.default.jndiName=DefaultDS
jpa.default=defaultPersistenceUnit
Can please someone tell me what I am doing wrong...
Thank you.
A: When your information above are correct, I assume a filename typo: rename conf/META-INF/persistance.xml to conf/META-INF/persistence.xml.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/24346537",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Spring Security, secured and none secured access I'm doing a little application that requires to login first. But for some 3rd party tool, I want to provide an API that doesn't require login. The login itself works fine, the API itself works, but I can't figure out how to tell Spring Security, that the API can be accessed without the need of authentication. I checked several topics here and on other websites and tried different versions, but none worked. Everytime I try to access the API, I get forwarded to the login form and have to login first.
My Code Looks like this so far, inside my Spring Security config:
/**
* configuration of spring security, defining access to the website
*
* @param http
* @throws Exception
*/
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/rest/open**").permitAll()
.antMatchers("/login**").permitAll()
.and()
.authorizeRequests()
.anyRequest()
.authenticated()
.and()
.formLogin()
.loginPage("/login")
.failureUrl("/login?error")
.defaultSuccessUrl("/dashboard")
.loginProcessingUrl("/j_spring_security_check")
.usernameParameter("username")
.passwordParameter("password")
.and()
.logout()
.logoutUrl("/j_spring_security_logout")
.logoutSuccessUrl("/login?logout")
.and()
.csrf();
}
And my controller:
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class PredictionOpenRestController {
@RequestMapping("/rest/open/prediction")
public String getPrediction() {
return "First Try!";
}
}
Somehow I have to feeling to miss something.
A: See Spring Security Reference:
Our examples have only required users to be authenticated and have done so for every URL in our application. We can specify custom requirements for our URLs by adding multiple children to our http.authorizeRequests() method. For example:
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/resources/**", "/signup", "/about").permitAll()
.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/db/**").access("hasRole('ADMIN') and hasRole('DBA')")
.anyRequest().authenticated()
.and()
// ...
.formLogin();
}
1 There are multiple children to the http.authorizeRequests() method each matcher is considered in the order they were declared.
2
We specified multiple URL patterns that any user can access. Specifically, any user can access a request if the URL starts with "/resources/", equals "/signup", or equals "/about".
3
Any URL that starts with "/admin/" will be resticted to users who have the role "ROLE_ADMIN". You will notice that since we are invoking the hasRole method we do not need to specify the "ROLE_" prefix.
4
Any URL that starts with "/db/" requires the user to have both "ROLE_ADMIN" and "ROLE_DBA". You will notice that since we are using the hasRole expression we do not need to specify the "ROLE_" prefix.
5
Any URL that has not already been matched on only requires that the user be authenticated
Your second use of .authorizeRequests() overrides the first one.
Also see AntPathMatcher:
The mapping matches URLs using the following rules:
? matches one character
* matches zero or more characters
** matches zero or more directories in a path
Examples
com/t?st.jsp — matches com/test.jsp but also com/tast.jsp or com/txst.jsp
com/*.jsp — matches all .jsp files in the com directory
com/**/test.jsp — matches all test.jsp files underneath the com path
org/springframework/**/*.jsp — matches all .jsp files underneath the org/springframework path
org/**/servlet/bla.jsp — matches org/springframework/servlet/bla.jsp but also org/springframework/testing/servlet/bla.jsp and org/servlet/bla.jsp
Your modified code:
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/rest/open/**").permitAll()
.antMatchers("/login/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.failureUrl("/login?error")
.defaultSuccessUrl("/dashboard")
.loginProcessingUrl("/j_spring_security_check")
.usernameParameter("username")
.passwordParameter("password")
.and()
.logout()
.logoutUrl("/j_spring_security_logout")
.logoutSuccessUrl("/login?logout")
.and()
.csrf();
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/39052457",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to make sure all files uploaded via SFTP in watched directory are ok to use via Java7? I'm using WatchService to monitor a directory. Another third party will upload large CSV files to that directory via SFTP. I have to wait until all the files are finished to start processing the files.
My trouble right now is that SFTP creates the file as soon as the uploading starts I get ENTRY_CREATE and continuously get ENTRY_MODIFY until the file is done. Is there anyway to tell if the file is actually done.
This is the code I use which I got it from Java Documentation
public class WatchDir {
private final WatchService watcher;
private final Map<WatchKey, Path> keys;
private final boolean recursive;
private boolean trace = false;
@SuppressWarnings("unchecked")
static <T> WatchEvent<T> cast(WatchEvent<?> event) {
return (WatchEvent<T>) event;
}
/**
* Register the given directory with the WatchService
*/
private void register(Path dir) throws IOException {
WatchKey key = dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
if (trace) {
Path prev = keys.get(key);
if (prev == null) {
System.out.format("register: %s\n", dir);
} else {
if (!dir.equals(prev)) {
System.out.format("update: %s -> %s\n", prev, dir);
}
}
}
keys.put(key, dir);
}
/**
* Register the given directory, and all its sub-directories, with the
* WatchService.
*/
private void registerAll(final Path start) throws IOException {
// register directory and sub-directories
Files.walkFileTree(start, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
throws IOException {
register(dir);
return FileVisitResult.CONTINUE;
}
});
}
/**
* Creates a WatchService and registers the given directory
*/
WatchDir(Path dir, boolean recursive) throws IOException {
this.watcher = FileSystems.getDefault().newWatchService();
this.keys = new HashMap<WatchKey, Path>();
this.recursive = recursive;
if (recursive) {
System.out.format("Scanning %s ...\n", dir);
registerAll(dir);
System.out.println("Done.");
} else {
register(dir);
}
// enable trace after initial registration
this.trace = true;
}
/**
* Process all events for keys queued to the watcher
*/
void processEvents() {
for (; ; ) {
// wait for key to be signalled
WatchKey key;
try {
key = watcher.take();
} catch (InterruptedException x) {
return;
}
Path dir = keys.get(key);
if (dir == null) {
System.err.println("WatchKey not recognized!!");
continue;
}
for (WatchEvent<?> event : key.pollEvents()) {
WatchEvent.Kind kind = event.kind();
// TBD - provide example of how OVERFLOW event is handled
if (kind == OVERFLOW) {
continue;
}
// Context for directory entry event is the file name of entry
WatchEvent<Path> ev = cast(event);
Path name = ev.context();
Path child = dir.resolve(name);
// print out event
System.out.format("%s: %s\n", event.kind().name(), child);
// if directory is created, and watching recursively, then
// register it and its sub-directories
if (recursive && (kind == ENTRY_CREATE)) {
try {
if (Files.isDirectory(child, NOFOLLOW_LINKS)) {
registerAll(child);
}
} catch (IOException x) {
// ignore to keep sample readbale
}
}
}
// reset key and remove from set if directory no longer accessible
boolean valid = key.reset();
if (!valid) {
keys.remove(key);
// all directories are inaccessible
if (keys.isEmpty()) {
break;
}
}
}
}
static void usage() {
System.err.println("usage: java WatchDir [-r] dir");
System.exit(-1);
}
public static void main(String[] args) throws IOException {
// parse arguments
if (args.length == 0 || args.length > 2)
usage();
boolean recursive = false;
int dirArg = 0;
if (args[0].equals("-r")) {
if (args.length < 2)
usage();
recursive = true;
dirArg++;
}
// register directory and process its events
Path dir = Paths.get(args[dirArg]);
new WatchDir(dir, recursive).processEvents();
}
}
A: Under Linux, you can use the "inotify" tools. they probably arrive with all major destributions. here is wiki for it : wiki - Inotify
Note in the supported events list you have:
IN_CLOSE_WRITE - sent when a file opened for writing is closed
IN_CLOSE_NOWRITE - sent when a file opened not for writing is closed
these are what you look for. I did not manage to see something similar on windows.
Now as for using them, there can be various ways. I used a java library jnotify
Note that the library is cross platform, so you don't want to use the main class as windows does not support events for close file. you will want to use the linux API which exposes the full linux capabilities. just read the description page and you know its what you request : jnotify - linux
Note that in my case, I had to download the library source because I needed compile the shared object file "libjnotify.so" for 64 bit. the one provided worked only under 32 bit. Maybe they provide it now you can check.
check the examples for code and how to add and remove watches. just remember to use the "JNotify_linux" class instead of "JNotify" and then you can use a mask with your operation, for example.
private final int MASK = JNotify_linux.IN_CLOSE_WRITE;
I hope it will work for you.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/20631045",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Swagger Ui forcing input as File upload type instead of Text I have an endpoint to save some data. I mapped the input json to a class with name File.
@PutMapping(path = "/file")
public boolean save(@RequestBody File file) {
// logic
}
When hooked up with swagger, the swagger ui considers this as a file type input.
How can I force the value on swagger ui to consider it as a regular text instead of a file upload?
Expected:
I tried :
@PutMapping(path = "/file", consumes = "application/json")
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/54023569",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Passing array of strings as an input argument in a function I'm new to C and I'm not to sure if the title of the question is correct with what I'm about to ask here. Basically I have written a bit of code to:
*
*Ask for the user input for a string each time and fill up the array of string.
*Sort the array of string alphetically.
char ch_arr[nV][MAX_WORD_LENGTH];
for (int i = 0; i < nV; i++) {
printf("Enter a word: ");
scanf(FORMAT_STRING, ch_arr[i]);
}
//sort array of string alphabetically
char temp[MAX_WORD_LENGTH];
for (int i = 0; i < nV; i++) {
for (int j = i+1; j < nV; j++) {
if (strcmp(ch_arr[i], ch_arr[j]) > 0) {
for (int c = 0; c < MAX_WORD_LENGTH; c++) {
temp[c] = ch_arr[i][c];
ch_arr[i][c] = ch_arr[j][c];
ch_arr[j][c] = temp[c];
}
}
}
}
Now I want to make the sorting part to become a seperate function for reuseability. The example I've read are all using double pointer to a character, but I'm not too sure how to apply it in here?
Thank you very much for reading. And any help would be greatly appreciated!
A: There are two ways you can allocate an array of strings in C.
*
*Either as a true 2D array with fixed string lengths - this is what you have currently. char strings [x][y];.
*Or as an array of pointers to strings. char* strings[x]. An item in this pointer array can be accessed through a char**, unlike the 2D array version.
The advantage of the 2D array version is faster access, but means you are stuck with pre-allocated fixed sizes. The pointer table version is typically slower but allows individual memory allocation of each string.
It's important to realise that these two forms are not directly compatible with each other. If you wish to declare a function taking these as parameters, it would typically be:
void func (size_t x, size_t y, char strings[x][y]); // accepts 2D array
void func (size_t x, size_t y, char (*strings)[y]); // equivalent, accepts 2D array
or
void func (size_t x, char* strings[x]); // accepts pointer array
void func (size_t x, char** strings); // equivalent - accepts pointer array
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/71643193",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Algorithm to get items from nested array structure structured around powers of 2 I have some constraints on how an array would be implemented under the hood. There can only be power-of-two contiguous elements up to 32 elements (1, 2, 4, 8, 16, 32). Therefore, this puts some constraints on how to optimally store the array elements of like 7 or 15 elements, etc.. The full list of examples from 1 to 32 is here, but some examples are next:
base-3
a
b
c
null
base-5
a
b
c
tree
d
e
base-6
a
b
c
d
e
f
null
null
...
base-10
a
b
c
d
e
f
g
tree
h
i
j
null
...
base-13
tree
a
b
c
d
tree
e
f
g
h
tree
i
j
k
l
tree
m
...
base-16
a
b
c
d
e
f
g
h
i
j
k
l
m
n
o
p
base-17
a
b
c
d
e
f
g
h
i
j
k
l
m
n
o
tree
p
q
Null is chosen in a few cases because it would take up less space to just have a null value than to make it into an appropriate tree (or using null would mean less traversal steps).
At 32, it should nest the pattern, like this:
base-33
tree
a
b
c
d
e
f
g
h
i
j
k
l
m
n
o
p
q
r
s
t
u
v
w
x
y
z
aa
ab
ac
ad
ae
af
tree
ag
The tree key just shows it is an address linking out to another array.
I started to implement an algorithm to fetch all the values from this tree system below. I didn't find a way of generically making it so I didn't have to write each of 32 functions. If you know of an abstract/generic way to write this, that would be cool to know (doesn't need to exactly match how I divided up the arrays, but it should be close to the same idea). But that is not the main question. The main question is simply how you would make this function repeat for arrays larger than 32. How do you make this algorithm (a loop/iterative algorithm, not using recursion) so that it can fetch up to billions of items from such a tree, and know how to traverse the custom array structure?
const map = [
get1,
get2,
get3,
get4,
get5,
get6,
get7,
get8,
get9,
get10,
get11,
get12,
get13,
get14,
get15,
get16,
get17,
get18,
get19,
get20,
get21,
get22,
get23,
get24,
get25,
get26,
get27,
get28,
get29,
get30,
get31,
get32,
]
// how to make getItems handle arrays larger than 32 in length?
function getItems(array) {
return map[array.length](array)
}
function get1(array) {
return [
array[0]
]
}
function get2(array) {
return [
array[0],
array[1],
]
}
function get3(array) {
return [
array[0],
array[1],
array[2],
]
}
function get4(array) {
return [
array[0],
array[1],
array[2],
array[3],
]
}
function get5(array) {
return [
array[0],
array[1],
array[2],
array[3][0],
array[3][1],
]
}
function get6(array) {
return [
array[0],
array[1],
array[2],
array[3],
array[4],
array[5],
]
}
function get7(array) {
return [
array[0],
array[1],
array[2],
array[3],
array[4],
array[5],
array[6],
]
}
function get8(array) {
return [
array[0],
array[1],
array[2],
array[3],
array[4],
array[5],
array[6],
array[7],
]
}
function get9(array) {
return [
array[0],
array[1],
array[2],
array[3],
array[4],
array[5],
array[6],
array[7][0],
array[7][1],
]
}
function get10(array) {
return [
array[0],
array[1],
array[2],
array[3],
array[4],
array[5],
array[6],
array[7][0],
array[7][1],
array[7][2],
]
}
function get11(array) {
return [
array[0],
array[1],
array[2],
array[3],
array[4],
array[5],
array[6],
array[7][0],
array[7][1],
array[7][2],
array[7][3],
]
}
function get12(array) {
return [
array[0][0],
array[1][1],
array[2][2],
array[3][3],
array[4][4],
array[5][5],
array[6][6],
array[6][7],
array[7][0],
array[7][1],
array[7][2],
array[7][3],
]
}
I am lost right at the beginning. It could be implemented with recursion, and perhaps from that I can figure it out as an imperative form.
function getItemsRecursive(tree) {
if (tree.size <= 32) {
return map[tree.size](tree)
}
// ... I am lost right at the beginning.
if (tree.size === 33) {
return [
...getItemsRecursive(tree[0]),
tree[1][0]
]
} else if (tree.size === 34) {
// ....?
}
}
The tree.size is just pseudocode. You can just do pseudocode if you'd like, but I am doing this in JavaScript.
A: In JavaScript you would of course call .flat(Infinity), which would return the completely flattened array. But I'll assume these constraints:
*
*No use of array methods besides push and pop (as you target a custom, simpler language)
*No use of recursion
*No use of a generator or iterator
I hope the use of a stack is acceptable. I would then think of a stack where each stacked element consists of an array reference and an index in that array. But to avoid "complex" stack elements, we can also use two stacks: one for array references, another for the indices in those arrays.
To implement "iteration", I will use a callback system, so that you can specify what should happen in each iteration. The callback can be console.log, so that the iterated value is just output.
Here is an implementation:
function iterate(arr, callback) {
let arrayStack = [];
let indexStack = [];
let i = 0;
while (true) {
if (i >= arr.length || arr[i] === null) {
if (arrayStack.length == 0) return; // all done
arr = arrayStack.pop();
i = indexStack.pop();
} else if (Array.isArray(arr[i])) {
arrayStack.push(arr);
indexStack.push(i + 1);
arr = arr[i];
i = 0;
} else {
callback(arr[i]);
i++;
}
}
}
let arr = [1, 2, 3, [4, 5]];
iterate(arr, console.log);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/71089072",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to get inputs from user and save them in a list(Python Kivy)? I'm beginner in kivy module. I want to put 8 textboxes in screen to get input from user and then, save this inputs in a list in order to use them later!
I searched in the internet but a didn't find any thing useful.
I think I should do sth like this code:
Save text input to a variable in a kivy app
But don't want to show the inputs in shell, I wanna save them in a list!
A: You need to give your text inputs ids, then reference the id of them and get their text using .text. self.root in the TestApp class refers to the root widget of your kv file, which is the one that doesn't have brackets (< >) around it, in this case the GridLayout.
main.py
from kivy.app import App
class MainApp(App):
def get_text_inputs(self):
my_list = [self.root.ids.first_input_id.text, self.root.ids.second_input_id.text]
print(my_list)
pass
MainApp().run()
main.kv
GridLayout:
cols: 1
TextInput:
id: first_input_id
TextInput:
id: second_input_id
Button:
text: "Get the inputs"
on_release:
app.get_text_inputs()
A: Py file
*
*Use a for loop to traverse through a container of all widgets e.g. TextInput.
Snippets
for child in reversed(self.container.children):
if isinstance(child, TextInput):
self.data_list.append(child.text)
kv file
*
*Use a container e.g. GridLayout
*Add an id for the container
*Add all those Label and TextInput widgets as child of GridLayout
Snippets
GridLayout:
id: container
cols: 2
Label:
text: "Last Name:"
TextInput:
id: last_name
Example
main.py
from kivy.app import App
from kivy.uix.screenmanager import Screen
from kivy.uix.textinput import TextInput
from kivy.properties import ObjectProperty, ListProperty
from kivy.lang import Builder
Builder.load_file('main.kv')
class MyScreen(Screen):
container = ObjectProperty(None)
data_list = ListProperty([])
def save_data(self):
for child in reversed(self.container.children):
if isinstance(child, TextInput):
self.data_list.append(child.text)
print(self.data_list)
class TestApp(App):
def build(self):
return MyScreen()
if __name__ == "__main__":
TestApp().run()
main.kv
#:kivy 1.11.0
<MyScreen>:
container: container
BoxLayout:
orientation: 'vertical'
GridLayout:
id: container
cols: 2
row_force_default: True
row_default_height: 30
col_force_default: True
col_default_width: dp(100)
Label:
text: "Last Name:"
TextInput:
id: last_name
Label:
text: "First Name:"
TextInput:
id: first_name
Label:
text: "Age:"
TextInput:
id: age
Label:
text: "City:"
TextInput:
id: city
Label:
text: "Country:"
TextInput:
id: country
Button:
text: "Save Data"
size_hint_y: None
height: '48dp'
on_release: root.save_data()
Output
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/55402450",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Run H2 database before log4j initialization in OSGI when using Equinox Launcher I am using log4j to store the logs in H2 database in OSGI using Equinox Launcher. The problem is log4j is initialized before the plugin responsible for starting the H2 database. Is there any way to initialize log4j only after a plugin has started or somehow run the plugin before log4j initialization? Also I don't actually want to run H2 outside the OSGI.
Thanks,
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/74318944",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: how to change newtonsoft.json code to system.text.json I want to move completely to .NET Core so I need to use System.Text.Json instead of Newtonsoft.Json.
How can I write this code in the System.Text.Json?
private readonly JsonSerializer _serializer;
_serializer = JsonSerializer.Create(new JsonSerializerSettings
{
DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate
});
private JObject _jsonSettings;
protected override void LoadSection(string sectionName, object section)
{
var jsonSection = _jsonSettings[sectionName];
if (jsonSection != null)
{
using (var reader = jsonSection.CreateReader())
{
_serializer.Populate(reader, section);
}
}
}
protected override void SaveSection(string sectionName, object section)
{
var settings = _jsonSettings ?? new JObject();
settings[sectionName] = JObject.FromObject(section);
_jsonSettings = settings;
}
protected override void LoadDefaults()
{
_jsonSettings = new JObject();
}
private void LoadFromJson(string json)
{
_jsonSettings = JObject.Parse(json);
}
A: Please refer to the official How to migrate from Newtonsoft.Json to System.Text.Json.
There are 3.1 and 5 versions provided. Please note that in 3.1 you can install the 5.0 package to get the new features (for example deserializing fields).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/67225752",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: ANR due to jacocoInit() method I'm getting ANR with below logs,
main (runnable): tid=1 systid=5585
at com.myapp.datamodels.chatgroup.Data.$jacocoInit(Data.java)
at com.myapp.datamodels.chatgroup.Data.getOpenfireId(Data.java)
at com.myapp.utils.UtilityMethods.getGroupById(UtilityMethods.java:314)
Data.java is a model class which have getter method getOpenfireId() which returns string. Can anyone help me to fix this ANR or what is jacocoInit() method?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/71575777",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How can I let html table borders merge into each other in css In a current project I have a three-columned table.
<table>
<tr>
<th>Datum</th>
<th>Entschuldigt?</th>
<th>Vermerkt von</th>
</tr>
</table>
My current stylesheet for the table looks as following:
th {
border-bottom: 1px solid black;
}
td + td {
border-left: 1px solid black;
border-right: 1px solid black;
}
Now the table looks like this
Now I would like to have those little spaces removed so the column separators and the header separator are solid and not that kind of dashed. Every help is very much appreciated
A: You need to use border-collapse: collapse on the table:
th {
border-bottom: 1px solid black;
}
td+td {
border-left: 1px solid black;
border-right: 1px solid black;
}
table {
border-collapse: collapse;
}
<table>
<tr>
<th>Datum</th>
<th>Entschuldigt?</th>
<th>Vermerkt von</th>
</tr>
<tr>
<td>item 1</td>
<td>item 2</td>
<td>item 3</td>
</tr>
<tr>
<td>item 1</td>
<td>item 2</td>
<td>item 3</td>
</tr>
</table>
A: Another Approach:
<table cellspacing="0">
A:
table {
border-collapse: collapse;
}
th, td {
padding: 5px;
text-align: center;
font-size: 20px;
border-left: 1px solid black;
}
th:nth-child(1), td:nth-child(1) {
border-left: none;
}
tr:nth-child(2){
border-top: 1px solid black;
}
<table>
<tr>
<th>Datum</th>
<th>Entschuldigt?</th>
<th>Vermerkt von</th>
</tr>
<tr>
<td>item 1</td>
<td>item 2</td>
<td>item 3</td>
</tr>
<tr>
<td>item 1</td>
<td>item 2</td>
<td>item 3</td>
</tr>
</table>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/59999227",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: what are the attributes in Cals table mean I've working on CALS tables and was stuck in a step. I've the below table.
<?xml version="1.0" encoding="UTF-8"?>
<table frame="all">
<tgroup cols="2">
<colspec colnum="1" colname="col1" colwidth="2*"/>
<colspec colnum="2" colname="col2" colwidth="16*"/>
<tbody>
<row>
<entry align="center" valign="top" colname="col1" colsep="1" rowsep="1"><para><content-style font-style="bold">A</content-style></para></entry>
<entry align="left" valign="top" colname="col2" colsep="1" rowsep="1"><para><content-style font-style="bold">Board Matters</content-style></para></entry>
</row>
<row>
<entry align="center" valign="top" colname="col1" colsep="1" rowsep="1"><para></para></entry>
<entry align="left" valign="top" colname="col2" colsep="1" rowsep="1"><para></para></entry>
</row>
<row>
<entry align="center" valign="top" colname="col1" colsep="1" rowsep="1"><para><content-style font-style="bold">2</content-style></para></entry>
<entry align="left" valign="top" colname="col2" colsep="1" rowsep="1"><para><content-style font-style="bold">Board composition and balance</content-style> <content-style font-style="bolditalic">(strong and independent board with no dominant</content-style><content-style font-style="bolditalic" format="strikethrough">e</content-style> <content-style font-style="bolditalic">individual(s))</content-style></para></entry>
</row>
</tbody>
</tgroup>
</table>
and the below XSLT.
<xsl:template name="table" match="table">
<xsl:if test="./title/page">
<xsl:apply-templates select="./title/page"/>
</xsl:if>
<div class="figure">
<div class="figure-title">
<xsl:value-of select="./title"/>
</div>
</div>
<table class="frame-{current()/@frame}">
<xsl:apply-templates select="child::node()[not(self::title)]"/>
</table>
</xsl:template>
<xsl:template match="tgroup">
<xsl:if test="not(preceding-sibling::tgroup)">
<xsl:if test="@colsep|@rowsep|@align|cols">
</xsl:if>
</xsl:if>
<colgroup>
<xsl:apply-templates select=".//colspec" />
</colgroup>
<xsl:apply-templates select="child::node()[not(self::colspec|self::tfoot/*)]" />
</xsl:template>
<xsl:template name="tbody" match="tgroup/tbody">
<tbody>
<xsl:for-each select="current()/row">
<xsl:call-template name="row" />
</xsl:for-each>
</tbody>
<xsl:if test="preceding-sibling::tfoot">
<tfoot class="foot">
<xsl:apply-templates select="preceding-sibling::tfoot"/>
</tfoot>
</xsl:if>
</xsl:template>
<xsl:template name="thead" match="tgroup/thead">
<thead>
<xsl:for-each select="current()/row">
<tr>
<xsl:for-each select="current()/entry">
<xsl:call-template name="headentry" />
</xsl:for-each>
</tr>
</xsl:for-each>
</thead>
</xsl:template>
<xsl:template match="box">
<div class="box">
<div class="title">
<xsl:value-of select="./title"/>
</div>
<xsl:apply-templates select="child::node()[not(self::title)]"/>
</div>
</xsl:template>
<xsl:template name="colspec" match="colspec">
<xsl:variable name="b">
<xsl:value-of select="sum(../colspec/number(substring-before(@colwidth,'*')))"/>
</xsl:variable>
<col class="colname-{current()/@colname} colwidth-{concat(format-number( number(substring-before(@colwidth,'*')) div $b * 100,'##'),'%')}" />
<xsl:text disable-output-escaping="yes"><![CDATA[</col>]]></xsl:text>
</xsl:template>
<xsl:template name="row" match="row">
<xsl:if test="./entry/*/page">
<xsl:apply-templates select="./entry/*/page"/>
</xsl:if>
<xsl:choose>
<xsl:when test="parent::tfoot">
<tr>
<xsl:for-each select="current()/entry">
<xsl:call-template name="entry" />
</xsl:for-each>
</tr>
</xsl:when>
<xsl:otherwise>
<tr>
<xsl:for-each select="current()/entry">
<xsl:call-template name="entry" />
</xsl:for-each>
</tr>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
<xsl:template match="entry" name="entry">
<xsl:choose>
<xsl:when test="./@namest">
<xsl:variable name="namest" select="@namest"/>
<xsl:variable name="nameend" select="@nameend"/>
<xsl:variable name="namestPos" select="count(ancestor::tgroup/colspec[@colname=$namest]/preceding-sibling::colspec)"/>
<xsl:variable name="nameendPos" select="count(ancestor::tgroup/colspec[@colname=$nameend]/preceding-sibling::colspec)"/>
<td colspan="{$nameendPos - $namestPos + 1}" align="{@align}">
<xsl:apply-templates select="child::node()[not(self::page)]"/>
</td>
</xsl:when>
<xsl:when test="@align and ./@morerows">
<td align="{@align}" rowspan="{number(./@morerows)+1}">
<xsl:for-each select="para">
<div class="para">
<xsl:apply-templates select="child::node()[not(self::page)]"/>
</div>
</xsl:for-each>
</td>
</xsl:when>
<xsl:when test="./@morerows and not(./@align)">
<td rowspan="{number(./@morerows)+1}">
<xsl:for-each select="para">
<div class="para">
<xsl:apply-templates select="child::node()[not(self::page)]"/>
</div>
</xsl:for-each>
</td>
</xsl:when>
<xsl:when test="not(./@morerows) and ./@align">
<td align="{@align}">
<xsl:for-each select="para">
<div class="para">
<xsl:apply-templates select="child::node()[not(self::page)]"/>
</div>
</xsl:for-each>
</td>
</xsl:when>
<xsl:otherwise>
<td>
<xsl:for-each select="para">
<div class="para">
<xsl:apply-templates select="child::node()[not(self::page)]"/>
</div>
</xsl:for-each>
</td>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
<xsl:template name="headentry">
<xsl:choose>
<xsl:when test="@align">
<td class="align-{@align}">
<xsl:if test="translate(current()/@namest,'col','') != translate(current()/@nameend,'col','')">
<xsl:variable name="colspan">
<xsl:value-of select="xs:integer(translate(current()/@nameend,'col','')) - xs:integer(translate(current()/@namest,'col','')) + 1" />
</xsl:variable>
<xsl:attribute name="colspan">
<xsl:value-of select="$colspan">
</xsl:value-of>
</xsl:attribute>
</xsl:if>
<xsl:for-each select="para">
<div class="para">
<xsl:apply-templates></xsl:apply-templates>
</div>
</xsl:for-each>
</td>
</xsl:when>
<xsl:otherwise>
<td>
<xsl:if test="translate(current()/@namest,'col','') != translate(current()/@nameend,'col','')">
<xsl:variable name="colspan">
<!-- <xsl:value-of select="translate(current()/@nameend,'col','') - translate(current()/@namest,'col','') + 1" />-->
</xsl:variable>
<xsl:attribute name="colspan">
<xsl:value-of select="$colspan">
</xsl:value-of>
</xsl:attribute>
</xsl:if>
<xsl:for-each select="para">
<div class="para">
<xsl:apply-templates></xsl:apply-templates>
</div>
</xsl:for-each>
</td>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
here when i run the XSLT everything is fine but i was having a problem with the below XML part.
<row>
<entry align="center" valign="top" colname="col1" colsep="1" rowsep="1"><para></para></entry>
<entry align="left" valign="top" colname="col2" colsep="1" rowsep="1"><para></para></entry>
</row>
In the output i need a blank row, and it is getting generated, but it looks more like two lines on one another with no gap. as shown below.
But i actually i need some gap between these lines like below.
please let me know how can i get this done, I want to know how i can make use of the colsep and rowsep in my XSLT.
Thanks
A: Add a non-breaking space as a content in your empty para. More like
<row>
<entry align="center" valign="top" colname="col1" colsep="1" rowsep="1"><para> </para></entry>
<entry align="left" valign="top" colname="col2" colsep="1" rowsep="1"><para> </para></entry>
</row>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/23781914",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: NULL not being counted in aggregate SQL Could use a little help with this SQL query.
Let's say I have a table, called StudentGrades, containing a list of students and a flag indicating whether they have passed a class or not. Assuming there are a large portion of students who have not yet been given a grade, how do I calculate the current percentage of those students that have passed/failed or have not been given a grade.
ID LastName GradeGiven
-------------------------------
1 Bueller PASS
2 Smith FAIL
3 Carter FAIL
4 Howell NULL
5 Clinton PASS
6 Brown FAIL
.
.
.
48 Jones NULL
49 Frank NULL
50 Jenkins NULL
I would like to be able create a query that would display the number of students who passed, failed, and don't have a grade assigned yet. To do this I create this query ...
SELECT
COUNT(GradeGiven) AS "Count of each Grade",
GradeGiven,
COUNT(GradeGiven * 100.0/(SELECT COUNT(*) from StudentGrades) AS "Percentage"
FROM
StudentGrades
GROUP BY
GradeGiven
My question is that NULL shows up as having a count of 0, even though it is present. Shouldn't it have a count even if it represents no value? I would have expected it to have a count of 45 and a large percentage if most of the grades has not been filled out. Yet it is 0.000
Count GradeGiven Percentage
------------------------------------------
0 NULL 0.000
2 PASS 4.000
3 FAIL 6.000
A: Use count(*) or count(1):
SELECT COUNT(*) AS "Count of each Grade",
GradeGiven,
COUNT(*) * 100.0/(SELECT COUNT(*) from StudentGrades) AS "Percentage"
FROM StudentGrades
GROUP BY GradeGiven;
Confusion over count(<column name>) is why I don't think it should be used, at least by beginners in SQL. You can read more about my opinion in this matter here.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/22665693",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Entity framework update change I have an entity model with a self relation (parent/child). My entity named Article has a property called parent. This parent is in fact the relation, and ParentID which is the field in the relation. In ef 4 i did this:
using (var dbContext= new DataBaseModel())
{
ArticleTable newEntity= new ArticleTable();
newEntity.name="childArt";
newEntity.ParentID = 1;
dbContext.ArticleTable.Add(newEntity);
dbContext.SaveChanges();
//after calling save I can do this
var parentName = newEntity.Parent.Name;
}
With entity framework 6, this doesn't work any more, I have get the entity from the database again in order to get the related parent entity. Is this because of changes to lazyloading? what should i do different.
A: The difference is that in EF 4 entities were generated with piles of code that took care of change notification and lazy loading. Since then, the DbContext API with POCOs has become the standard.
If you want the same behavior as with the old 'enriched' entities you must make sure that lazy loading can occur by a number of conditions:
*
*The context must allow lazy loading. It does this by default, but you can turn it off.
*The navigation properties you want to lazy load must have the virtual modifier, because
*EF must create dynamic proxies. These proxies somewhat resemble the old generated entities in that they are able to execute lazy loading, because they override virtual members of the original classes.
The last (and maybe second) point is probably the only thing for you to pay attention to. If you create a new object by new, it's just a POCO object that can't do lazy loading. However, if you'd create a proxy instead, lazy loading would occur. Fortunately, there is an easy way to create a proxy:
ArticleTable newEntity= dbContext.ArticleTables.Create();
DbSet<T>.Create() creates dynamic proxies -
if the underlying context is configured to create proxies and the entity type meets the requirements for creating a proxy.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/21944553",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: .htaccess redirect to subdirectory for Ruby application deployed by passenger My Ruby on Rails project is on justhost server. When I am creating there ruby project, it is creating this in folder rails_apps by default.
For my project, I have created symlinks.
ln -s ~/rails_apps/webworth/public ~/public_html/webworth
And
ln -s ~/rails_apps/webworth ~/public_html/webworth_app [Purpose of this symlink just for browsing files by ftp client]
I created .htaccess file in ~/rails_apps/webworth/public directory. Below is the .htaccess code
Options -MultiViews
PassengerResolveSymlinksInDocumentRoot on
RailsEnv development
RailsBaseURI /webworth
SetEnv GEM_HOME /home5/worthgur/ruby/gems
and one .htaccess file in ~/public_html. Below is the code:
# Use PHP5 Single php.ini as default
AddHandler application/x-httpd-php5s .php
RewriteEngine on
Options +SymLinksIfOwnerMatch
RewriteBase /
RewriteCond %{HTTP_HOST} ^(www\.)?webworth.com [NC]
RewriteCond %{REQUEST_URI} !webworth/ [NC]
RewriteRule ^(.*)$ "webworth\/$1" [L]
Everything is working proper with these structure of .htaccess files except one problem. Extra text is appending to all urls in my project i.e "webworth" for all links generated by routes.rb file. And I want to remove this extra text "webworth" from all URL's.
Now urls are generating for example in this manner.
http://webworth.com/webworth/tags/smartphones
while it should be http://webworth.com/tags/smartphones.
This extra text i.e "webworth" was added previously for the folder that has to be accessed since it was not in the document root for the site and because of this extra text, extra text is appending to all URL's generated by routes.rb file thru ~/rails_apps/webworth/public/.htaccess file [Reason: RailsBaseURI /webworth]
I guess this can be fixed by changing RailsBaseURI /webworth to RailsBaseURI / in ~/rails_apps/webworth/public/.htaccess file.
I did that and I am sure I could not write proper commands in ~/public_html/.htaccess file so that I can redirect the traffic from the public_html to the symlink (webworth) for my site. I used many options but couldn't figure out how it will work. Please help to write ~/public_html/.htaccess file properly to redirect the traffic from public_html folder to my symlink(webworth).
Justhost suggested this link: How to host the Primary Domain from a subfolder. But still I could not figure out the issue. Thanks
A: I had the same problem with justhost and I solved it without adding any redirect.
I set my rails app public folder to be the main site public folder.
*
*I renamed the original "public_html" to "public_html_backup", just in case.
*Added a symlink ln -s ~/myRailsApp/public ~/public_html
*in my htaccess I changed RailsBaseURI /myRailsApp to RailsBaseURI /, resulting in:
<IfModule mod_passenger.c>
Options -MultiViews
PassengerResolveSymlinksInDocumentRoot on
RailsEnv production
RackBaseURI /
SetEnv GEM_HOME /yourUserPath.../ruby/gems
</IfModule>
I hope this can help you.
Cheers
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/18546792",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: No mole class for NativeMethods.cs? I have a class named NativeMethods.cs which contains all extern methods:
internal static class NativeMethods
{
[DllImport("kernel32.dll", SetLastError = true, CallingConvention = CallingConvention.Winapi)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool IsWow64Process([In] IntPtr hProcess, [Out] out bool wow64Process);
[DllImport("advapi32.dll", CharSet = CharSet.Auto)]
internal static extern int RegOpenKeyEx(
IntPtr hKey,
string subKey,
int ulOptions,
int samDesired,
out int hkResult);
}
The assembly containing this class has a corresponding .Moles file. All other classes included in the assembly can be moled and stubbed properly, except this one.
There is no MNativeMethods that we can use for detouring. Is there a special case against the class name "NativeMethods" (Highly unlikely)? Or a special case against extern methods?
A: Moles is capable of detouring calls to managed code. This class is clearly not dealing with managed code. Try creating a stub for this class, manually. This means crating an INativeMethods interface, have NativeMethods implement INativeMethods, and then use the interface as the stub, as usual. Moles will then generate stub type SINativeMethods from the interface, for use in test projects.
A: "Thus, if a method has no body (such as an abstract method), we cannot detour it." - Moles Dev
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/9188937",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: adb I/O Error, possible corruption I am struggling to fix an issue I have. Basically my Galaxy S3 has just up and decided that Google Calendar will now crash whenever I open it. After examining the system log, stack trace, etc... it appears to be stemming from the app trying to access /data/data/com.google.android.calendar/databases/<database>.db, of course with a specific database name.
When I cd into the folder by using adb in root mode I find the folder lib, cache and a file named databases. The other two folders perform normally but databases is weird, it does not auto-complete with tab and using any form of file operation on it (such as less, rm, etc...) results in an I/O Error.
I think this is an oddly corrupted file that is causing the problem, particularly as it appears to stay even when I uninstall Google Calendar. Any help would be most appreciated in getting this sorted as I could really do with getting my calendar back.
Long display of results:
root@m0:/data/data/com.google.android.calendar # ls
databases
root@m0:/data/data/com.google.android.calendar # rm databases
rm failed for databases, I/O error
255|root@m0:/data/data/com.google.android.calendar # rm -rf databases
rm failed for databases, I/O error
1|root@m0:/data/data/com.google.android.calendar # cd databases
/system/bin/sh: cd: /data/data/com.google.android.calendar/databases: I/O error
2|root@m0:/data/data/com.google.android.calendar #
2|root@m0:/data/data/com.google.android.calendar # sqlite3 databases
SQLite version 3.7.11 2012-03-20 11:35:50
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> .databases
Error: unable to open database "databases": unable to open database file
1|root@m0:/data/data/com.google.android.calendar #
Regards,
Ybrad
A: It happened to a friend on his Moto X Force, Instagram kept crashing. He was using LineageOS 7.1, we wiped everything and installed the original firmware (through TRWP) and when we was installing the package, it returned IO Error on "data/data/com.instagram.android/analytics/xxxxxxxx.pending". We formatted the /data partition but the problem persisted.
We installed the original firmware along with Magisk, installed Root Explorer and renamed the "com.instagram.android" folder to "insta.broken", uninstalled and reinstalled the app and voilá, working again.
A: Huh,
Turns out that if you uninstall the app, rename the folder containing the corrupted file and then re-install everything goes swimmingly.
No idea what caused it or even what is wrong but hey, I have my calendar back.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/27974193",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: geting maximu value in a table column I am trying to get maximum value of id column
$taskid = (new Query())->select('MAX(id)')->from('member');
echo $taskid;
unfortunate I got the below text
O:12:"yii\db\Query":20:{s:6:"select";a:1:{i:0;s:7:"MAX(id)";}s:12:"selectOption";N;s:8:"distinct";N;s:4:"from";a:1:{i:0;s:21:"member";}s:7:"groupBy";N;s:4:"join";N;s:6:"having";N;s:5:"union";N;s:6:"params";a:0:{}s:18:"queryCacheDuration";N;s:20:"queryCacheDependency";N;s:27:"yii\base\Component_events";a:0:{}s:35:"yii\base\Component_eventWildcards";a:0:{}s:30:"yii\base\Component_behaviors";N;s:5:"where";N;s:5:"limit";N;s:6:"offset";N;s:7:"orderBy";N;s:7:"indexBy";N;s:16:"emulateExecution";b:0;}
please help me out
A: Maximum id value of Member model:
use app\models\Member;
// ...
echo Member::find()->max('id');
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/52809037",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Testing RegEx against Null When calling RegEx.prototype.test() on null, JS runtimes appear to convert null into its string form ("null") and then test the regex against that. A few examples:
/[a-z]+/.test(null)
true
/null/.test(null)
true
/[0-9]+/.test(null)
false
/nnull/.test(null)
false
My questions are:
*
*Why?
*Is this correct behavior according to current specifications?
This behavior is horribly unintuitive. Since null conceptually represents the absence of any object, it conceptually makes sense that a RegEx test against it would fail, because there should be nothing to test against. It doesn't help that a lot of basic RegEx will succeed on testing against "null".
I have confirmed this behavior in Node.js and Firefox Nightly.
A: 21.2.5.13 RegExp.prototype.test( S )
The following steps are taken:
*
*Let R be the this value.
*If Type(R) is not Object, throw a TypeError exception.
*Let string be ToString(S).
*ReturnIfAbrupt(string).
*Let match be RegExpExec(R, string).
*ReturnIfAbrupt(match).
*If match is not null, return true; else return false.
And look at the ToString(S) you will see null = "null" and you get what you see.
A: Yes, this is as specified.
Per §21.2.5.13 "RegExp.prototype.test( S )" in the 2015 version (6th Edition), one of the first few steps is to apply the "ToString" operation to the argument S, and use its result. The "ToString" operation converts various non-string values to string values; null, in particular, is converted to "null".
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/35473255",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How can I use matcaffe in Windows? To use caffe in MATLAB, i need matcaffe.
The manual tells me to run "make all matcaffe"
But it does not tell where to command.
I command "run make all" matcaffe by running cmd from the cafe root folder where caffe.exe exists.
But there is an error saying "There is nothing to do for matcaffe"
Is there a clear, specific, and accurate description of how matcaffe can be run?
Thank you.
A: There is an official branch for caffe on Windows. BVLC/caffe
Follow the steps in that repository, like the below
C:\Projects> git clone https://github.com/BVLC/caffe.git
C:\Projects> cd caffe
C:\Projects\caffe> git checkout windows
:: Edit any of the options inside build_win.cmd to suit your needs
C:\Projects\caffe> scripts\build_win.cmd
If you got all the tools successfully installed, you will be able to build it successfully. Then you could find a .mex64 file under the caffe/matlab folder.
Simply add that directory into matlab, you can use matcaffe then.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/51762579",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Issues with macros and formulas in Excel I'm having problems when inserting a formula from a macro in Excel. I managed to insert exactly the same value that I have on another cell where the formula is working perfectly. It always says #¿NAME? unless I press F2 and Enter. I checked and rechecked the calculation mode and is not Manual, is set to automatic but this formulas doesn't work at all. The method SendKeys "{f2}" SendKeys "{enter}" seems to work but it's horrible and not "seamless".
I've tried with different formulas (from simpler to more complex) and every time a tried any function inside my formula just doesn't work. The only way I insert a working formula is just using numbers (ex. "=1+1" and stuff like that) but when using any function for ex. "=SUM(A1:A5)" just don't work (unless pressing F2 and Enter).
I don't understand why having exactly the same "text" inserted as Formula it just don't work.
What can I do to solve this???
Thanx in advance
A: Thanks for your replies!!!
Using FormulaLocal works great!!! What I did was to "translate" the functions names and done!
Cells(LastRow + 1, 3).Formula = "=IFERROR(VLOOKUP(" & "B" & laststr & " , Datos!A2:E52, 3), """")"
A: Please refer to the answer by Monster for the correct solution to the problem.
I have to leave this answer here until it is "unaccepted", and then I will be able to delete it.
To enter locale-dependent formulas, you need to use FormulaLocal:
Cells(LastRow + 1, 3).FormulaLocal = "=SI.ERROR(BUSCARV(B" & laststr & " , Datos!A2:E52, 3), """")"
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/43374910",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Eclipse not recognizing my "Main" method I'm trying to write a "Hello, World" variant program in Eclipse, and I can't seem to be able to run my program.
Here's the code:
/**
*
*/
package GreeterPackage;
/**
* @author Raven Dreamer
* Prints out "Hello, World" in three languages:
* English, French, and Spanish.
*/
public class GreeterProg {
/**
* returns "Hello, World" three times, once
* in English, once in French, and once in
* Spanish.
*/
public static void Main(String[] args){
/** instances of the three greeter
* classes so the non-static methods
* can be called.
*/
EnglishGreeter eng = new EnglishGreeter();
FrenchGreeter fre = new FrenchGreeter();
SpanishGreeter spa = new SpanishGreeter();
System.out.println(eng.greet());
System.out.println(fre.greet());
System.out.println(spa.greet());
}
}
And here's my code for SpanishGreeter (French and English greeter are identical, currently)
/**
*
*/
package GreeterPackage;
/**
* @author Raven Dreamer
* Returns "Hello, World!" but in Spanish!
*/
public class SpanishGreeter extends greeter {
/**Spanish string of "Hello, World!"
*/
private String GREET = "¡Hola, World!";
/**
* returns "Hello, World" in Spanish
*/
public String greet() {
return GREET;
}
}
The code compiles fine with no errors, but when I try to run the program as a java application, I get the following error:
So I am left baffled as to what, exactly, the problem is. Am I missing something salient in terms of how I set the project up in the first place?
A: The problem is that you have Main with a capital letter. Java is case-sensitive.
The full method signature is: public static void main(String [] args)
A: Your main method needs to be a lowercase "main".
A: "main" must be in lowercase only. Java method names are case-sensitive.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/4784564",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Infinite scrolling I am trying to add some "Infinite Scrolling" to my product pages. However, i can't get it working at all, so i have nothing.
The page currently works, but it just outputs all of the products. I can't get the infinite scrolling scripts i found working, as my query is not always the same.
This is the code that builds my query, using GETs:
$kategori_q = "";
if ($kategori !== "") {
if ($hkat !== "") {
$ukator = "";
$underkategorier = sqlSelect("SELECT * FROM underkategorier WHERE fk_hkategori = '$kategori'");
while ($row = sqlFetch($underkategorier)) {
$ukator .= " fk_ukategori = '".$row['underkategori_id']."' OR";
}
$kategori_q = rtrim($ukator, "OR");
$kategori_q = "WHERE ($kategori_q)";
}
else {
$kategori_q = "WHERE fk_ukategori = '$kategori'";
}
}
$query = "SELECT * FROM annoncer $kategori_q ORDER BY annonce_id DESC";
$soeg = "";
if (isset($_GET['soeg'])) {
$soeg = $_GET['soeg'];
if (substr_count($query, "WHERE") == 1) {
$soeg = " AND (overskrift LIKE '%$soeg%' OR beskrivelse LIKE '%$soeg%')";
}
else {
$soeg = " WHERE (overskrift LIKE '%$soeg%' OR beskrivelse LIKE '%$soeg%')";
}
}
$query = "SELECT * FROM annoncer $kategori_q $soeg ORDER BY annonce_id DESC";
$q = sqlSelect($query);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/12144277",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: JavaScript function not retrieving string from HTML textarea I am learning JavaScript and I am not understanding why my message is not being retrieved by a word count function. When I click the button with a message of multiple words, I am receiving '1' as the word count, which is incorrect. I have tested the calWords function which works correctly when using console.log(calWords(some message));.
This code is written using requirements and I cannot use .split() or regex. Here is a link to the code:
https://jsbin.com/rucicol/edit?html,js,console,output
<form class="userform">
<label id="labeltxt">Enter a Message to Display Statistics</label><br>
<textarea type="text" name="message" id='userInput'></textarea><br>
<button type="button" onclick="showStats()">Submit</button>
</form>
// global variables
var numWords = 0;
var displayStats = document.getElementById('userInput').value;
// display stats
function showStats() {
alert(calWords(displayStats));
}
// calculate words
function calWords(str) {
for(var i = 0; i < str.length; i++) {
if (str[i] === ' ') {
numWords ++;
}
}
return numWords + 1;
}
A: This is because, when you create displayStats you take the value of the textarea at the moment of the creation (e.g. nothing).
To make your script working, you can "store" the reference to the textarea in displayStatsand access his value when needed.
This is the corrected script:
// global variables
var numWords = 0;
var displayStats = document.getElementById('userInput');
// display stats
function showStats()
alert(calWords(displayStats.value));
}
// calculate words
function calWords(str) {
for(var i = 0; i < str.length; i++) {
if (str[i] === ' ') {
numWords ++;
}
}
return numWords + 1;
}
A: Add the code to get the text area content inside the function.
// global variables
var numWords = 0;
// display stats
function showStats() {
var displayStats = document.getElementById('userInput').value;
alert(calWords(displayStats));
}
// calculate words
function calWords(str) {
for(var i = 0; i < str.length; i++) {
if (str[i] === ' ') {
numWords ++;
}
}
return numWords + 1;
}
A: The reason being you have initialised the displayStats globally which will be initialised once the page when load will happen. It would be better if you move displayStats inside click handler.
Also, if you are interested in knowing the number of words in the textarea, you should move your numWords inside the calWords, that way you will get the number of words which is present in the textarea.
// display stats
function showStats() {
var displayStats = document.getElementById('userInput').value;
alert(calWords(displayStats));
}
// calculate words
function calWords(str) {
var numWords = 0;
for(var i = 0; i < str.length; i++) {
if (str[i] === ' ') {
numWords ++;
}
}
return numWords + 1;
}
<form class="userform">
<label id="labeltxt">Enter a Message to Display Statistics</label><br>
<textarea type="text" name="message" id='userInput'></textarea><br>
<button type="button" onclick="showStats()">Submit</button>
</form>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/45230002",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Wordpress: register_my_menus / creating a new menu does not work I have prepared a positioning of my own menus. So far the menu only reacts to the styling. Wordpress simply selects any menu. For example, if I create a new footer menu, the actual top menu is replaced. The current solution without further menus:
<?php wp_nav_menu( [ 'container_id' => 'main-nav','menu_id' => 'menu-top-menu', 'menu_class' => 'dropdown'] ); ?>
The code in the function.php I have used so far:
function register_my_menus() {
register_nav_menus(
array( 'top_menu' => __( 'Top Menu', 'test' ),
'footer_menu' => __( 'Footer Menu', 'test' ))
'blog_menu' => __( 'Blog Menu', 'test' ))
);
}
add_action ('init', 'register_my_menus');
The code in the header.php that I have tried so far for positioning:
<?php wp_nav_menu( array( 'theme_location' => 'top_menu', 'container_id' => 'main-nav','menu_id' => 'menu-top-menu', 'menu_class' => 'dropdown' ) ); ?>
A: I love the object-oriented approach:
class Menu_init {
public function __construct() {
add_action( 'init', array($this, 'register_menus'));
}
public function register_menus() {
register_nav_menus(
array(
'top_menu' => __( 'Top Menu', 'test' ),
'footer_menu' => __( 'Footer Menu', 'test' )
'blog_menu' => __( 'Blog Menu', 'test' )
)
);
}
}
new Menu_init();
and for your header of course:
<?php
wp_nav_menu( [
'theme_location' => 'primary',
'container_id' => 'main-nav',
'menu_id' => 'menu-top-menu',
'menu_class' => 'dropdown'
] );
?>
It is true, you have an extra bracket ( ) ).
A: function register_my_menus() {
$locations = array(
'primary' => __( 'Top Menu', 'test' ),
'blog' => __( 'Blog Menu', 'test' ),
'footer' => __( 'Footer Menu', 'test' ),
);
register_nav_menus( $locations );
}
add_action( 'init', 'register_my_menus' );
<?php wp_nav_menu( [ 'theme_location' => 'primary', 'container_id' => 'main-nav','menu_id' => 'menu-top-menu', 'menu_class' => 'dropdown'] ); ?>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72744283",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Matlab: Creating contour maps/images similiar to SigmaPlot If a = columns, b = rows and c = intensity. How can I create an image of dimensions a by b and for each pixel to have intensity c:
In SigmaPlot, to create a 29x4 image, a , b and c are formatted as follows, how can the data be formatted in Matlab to achieve similar results:
[a, b, c] =
1 1 0
2 1 0
3 1 0
4 1 0
5 1 0
6 1 360.389854270598
7 1 524.553377941978
8 1 587.550618428821
9 1 535.164504523392
10 1 494.350943153525
11 1 509.366595359498
12 1 541.550829317582
13 1 714.122144025010
14 1 807.904727901154
15 1 634.059149684754
16 1 406.202488197581
17 1 338.349519959103
18 1 348.757723417053
19 1 334.118680593247
20 1 375.846361889047
21 1 507.518116274100
22 1 422.583478997748
23 1 0
24 1 0
25 1 0
26 1 0
27 1 0
28 1 0
29 1 0
1 2 0
2 2 0
3 2 0
4 2 0
5 2 0
6 2 222.769016959765
7 2 426.141970064050
8 2 481.453912764027
9 2 517.069153954465
10 2 487.414455654141
11 2 506.604099604784
12 2 514.770604062499
13 2 460.590220686965
14 2 376.241099616609
15 2 337.728227490832
16 2 394.310238250583
17 2 644.982641646965
18 2 856.664806333676
19 2 1040.69617779231
20 2 1128.07830809176
21 2 1070.24104109274
22 2 850.891638429000
23 2 489.144965506451
24 2 0
25 2 0
26 2 0
27 2 0
28 2 0
29 2 0
1 3 0
2 3 0
3 3 0
4 3 0
5 3 0
6 3 0
7 3 337.875341290982
8 3 446.387817855576
9 3 505.667919278579
10 3 474.666874694826
11 3 404.395323496310
12 3 345.514890319901
13 3 367.942209080407
14 3 450.883569030291
15 3 507.808892555292
16 3 498.203471996257
17 3 501.711478584646
18 3 518.354642382383
19 3 596.694216569632
20 3 591.347390565249
21 3 622.610680837716
22 3 667.944336239558
23 3 445.858691175108
24 3 0
25 3 0
26 3 0
27 3 0
28 3 0
29 3 0
1 4 0
2 4 0
3 4 0
4 4 0
5 4 0
6 4 0
7 4 216.608353008468
8 4 375.475770667960
9 4 425.565743597413
10 4 380.722854551759
11 4 317.194831801482
12 4 337.830175882681
13 4 352.530658493000
14 4 352.286503054898
15 4 323.117595263304
16 4 289.104540650745
17 4 259.229945714487
18 4 233.527214821773
19 4 137.305656551259
20 4 1418.69232849777
21 4 1055.72415597513
22 4 818.007236956091
23 4 595.146860875435
24 4 363.440841935283
25 4 0
26 4 0
27 4 0
28 4 0
29 4 0
A: It seems there is an inconsistency in the data definition: you define
*
*a as the columns (ranging from 1 to 29)
*b as the rows (ranging from 1 to 4)
*nevertheless, then you refer to a 29 x 4 matrix, while it should be 4 x 29
A part from that, you have to first re-arrange the definition of the input data as follow:
abc=[
1 1 0
2 1 0
3 1 0
4 1 0
5 1 0
6 1 360.389854270598
7 1 524.553377941978
8 1 587.550618428821
...
all the other data
...
]
that is to include them into [].
Then you can:
*
*extract the intensity data (which are in the third column of the abc matrix
*use the reshape function to convert the intensity array into a matrix
*"automatically" the x and y data by using the unique function
*get the number of row and column using the length function
*use the meshgrid function to generate the XY grid over which to plot the surface
At this point you can:
*
*use the surf function to plot a 3D surface (the z values will be the intensity data)
*create flat surface and use the intensity data as "colour"
*use the contour function to plot a 2D contour plot
*use the contour3 function to plot a 3D contour plot
This solution can be implemented as follows (where abc is your complete data set):
% Get the intensity data
intensity=abc(:,3);
% Get the x and y data
row_data=unique(abc(:,1));
col_data=unique(abc(:,2));
n_row=length(row_data);
n_col=length(col_data);
% Reshape the intensity data to get a 29x4 matrix
z=reshape(intensity,n_row,n_col);
% Create the grid to plot the surface
[X,Y]=meshgrid([1:n_col],[1:n_row])
% Plot a 3D surface
figure
surf(X,Y,z)
shading interp
colorbar
% Plot a flat surface with
figure
% Create a "dummy" zeros matrix to plot a flat surface
Z=zeros(size(X));
surf(X,Y,Z,z)
shading interp
colorbar
% Plot a 2D contour
figure
[c,h] = contour(z);
clabel(c,h)
colorbar
% Plot a 3D contour
figure
[c,h] = contour3(z);
clabel(c,h)
colorbar
Hope this helps.
Qapla'
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/37765000",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: When do I see "404" in the page? I'm a rookie in nodejs, and I'm learning Koa. I got some problem about this code.
const Koa = require('koa');
const app = new Koa();
app.use(async function(ctx, next) {
await next();
if (ctx.body || !ctx.idempotent) return ;
ctx.status = 404;
});
What is the meaning of await next() and if statement after that ?
A: This works like a "catch all" statement, reading in plain English:
*
*wait for the request to be processed by other parts of the app
(await next())
*when done, check if the app responded with a body or the request does not require a response body
*if none is true, return HTTP code 404 "Not Found"
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/58939103",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: How to make clipping geometry scale with the target? In the following example whenever Grid size is changed, the clipping region size remains as it is expressed in absolute coordinates.
<Grid Clip="M10,10 L10,150 L150,150 L150,10 Z">
<Rectangle Fill="Red"/>
</Grid>
Is is possible somehow to clip the region such that the clipping geometry is scaled along with the clipped object?
Code behind solutions are not accepted, because this is to be used in the control template. Also, the region in the example is a simple shape for clarity sake. The actual used region is a complex and asymmetric shape.
EDIT:
It looks like I have to be more specific. This is the snipped that is part of custom control template for ProgressBar. When scaling the outer grid, the PART_Indicator rectangle does not scale its clipping region. The correct composition is when grid is sized 200x200.
<Grid>
<Path Name="PART_Track"
Data="M100,0 A100,100 0 1 0 100,200 A100,100 0 1 0 100,0 Z"
Fill="AliceBlue" Stretch="Fill"/>
<Rectangle Clip="M100,0 A100,100 0 1 0 100,200 A100,100 0 1 0 100,0 Z"
Stretch="Fill"
Name="PART_Indicator" Fill="Red"
Height="100" VerticalAlignment="Top"/>
<Path Name="Border" Data="M100,0 A100,100 0 1 0 100,200 A100,100 0 1 0 100,0 Z"
Stretch="Fill" StrokeThickness="3" Stroke="Black"/>
</Grid>
UPDATE:
Rick provided excellent suggestion, though it took time for me to understand how to use it.
Here is the final code.
<Viewbox StretchDirection="Both" Stretch="Fill" >
<Grid>
<Path Name="PART_Track"
Data="M100,0 A100,100 0 1 0 100,200 A100,100 0 1 0 100,0 Z"
Fill="AliceBlue" Stretch="Fill"/>
<Border Clip="M100,0 A100,100 0 1 0 100,200 A100,100 0 1 0 100,0 Z"
Height="200" VerticalAlignment="Bottom">
<Rectangle Name="PART_Indicator" Fill="Red" VerticalAlignment="Bottom"
Height="40"/>
</Border>
<Path Name="Border"
Data="M100,0 A100,100 0 1 0 100,200 A100,100 0 1 0 100,0 Z"
StrokeThickness="3"
Stretch="Fill" Stroke="Black"/>
</Grid>
</Viewbox>
A: Put the Grid inside of a Viewbox and change the size of the Viewbox instead of the Grid.
<Viewbox>
<Grid Clip="M10,10 L10,150 L150,150 L150,10 Z" Width="200" Height="200">
<Rectangle Fill="Red"/>
</Grid>
</Viewbox>
A: An alternative approach to this is to define the clipping path using element rather than attribute syntax, and then use the same transformation on the clip as you apply to the element as a whole, e.g.:
<Grid.Clip>
<PathGeometry FillRule="Nonzero" Transform="{Binding Path=MatrixTransform, RelativeSource={RelativeSource TemplatedParent}, Mode=OneWay}">
<PathFigure StartPoint="715, 96.3333" IsClosed="True" IsFilled="True">
<PolyLineSegment IsStroked="False">
<PolyLineSegment.Points>
<Point X="1255.2526" Y="540" />
<Point X="426.3333" Y="1342.3333" />
<Point X="64.66666" Y="7356.6666" />
</PolyLineSegment.Points>
</PolyLineSegment>
</PathFigure>
</PathGeometry>
</Grid.Clip>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/5956093",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Which version of angular-notify is compatible with angular version 15? I use angular version 15.0.0 and tried to install angular-notify version 12, but I got an error while installing process. How can I fix the error and install notify successfully?
Best regards.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/74642078",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How can I return the sum of things counted in xpath for $b in doc ("courses.xml") //Course_Catalog/Department/Course
where count($b/Instructors/Lecturer)=0
return count($b)
This code returns the result: 1 1 1 1 1 1 1 1 1 1. What I acutally want is all the ones to be added up to return the figure 10.
I would be grateful if somebody can tell me how to achieve this. Thank you in advance for any help offered.
A: Use sum:
sum(
for $b in doc ("courses.xml") //Course_Catalog/Department/Course
where count($b/Instructors/Lecturer)=0
return count($b)
)
A: You actually need the count of all such elements.
Use:
count(doc ("courses.xml")//Course_Catalog/Department/Course[not(Instructors/Lecturer)])
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/15460753",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Exit protractor spec without failure Is there a way I can stop protractor from executing more tests in a spec even if there was no failure in the previous tests?
> describe('tests', function () {
> it('should exit', function () {
> protractor.stop(); <---- is there a way to prevent executing more tests?
> });
> it('should not run', function () {
> expect(something).toBeTruthy();
> });
> });
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/36230427",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Rbenv permission denied issue I have trouble getting my Rails app running after I deployed this to my DO droplet.
I deployed (and installed everything including rbenv) following this guide. Rbenv seems to be installed properly but app is not running and nginx error log says "cannot execute /root/.rbenv/shims/ruby permission denied (13)"
I can not get the sense of this error, hope anyone can help with that.
A: Looks like rbenv's installed under root. It should probably be installed under your (or your app user's) home directory, in this case for the user named 'deploy.'
This Passenger configuration line from nginx.conf shows where it's expected to live:
/home/deploy/.rbenv/shims/ruby
So you should probably (re)install rbenv as/under 'deploy.'
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/27213078",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to catch mouse moves outside of screen boundaries My application catpures mouse on down event and relies on mouse movements not directly related to current mouse pointer position (visible pointer). So the math is based on initial point and the relative point of the mouse and has the visual feedback visually not linked to the visible mouse pointer so the pointer might as well be hidden completely. But when I reach the screen boundaries, the incoming coordinates are clipped. It looks reasonable since the pointer don't move either, but I would like to continue getting information about relative mouse movements even if the visible pointer reached the screen boundary. Is this possible? Maybe with access to raw mouse information from the driver?
A: Basically Raw Input Api serves my goal. One needs to register the window with RegisterRawInputDevices and get WM_INPUT message. The incoming data passes relative mouse movements not limited by the screen boundaries.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/13891180",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Why java.util.Optional is not Serializable, how to serialize the object with such fields The Enum class is Serializable so there is no problem to serialize object with enums. The other case is where class has fields of java.util.Optional class. In this case the following exception is thrown: java.io.NotSerializableException: java.util.Optional
How to deal with such classes, how to serialize them? Is it possible to send such objects to Remote EJB or through RMI?
This is the example:
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Optional;
import org.junit.Test;
public class SerializationTest {
static class My implements Serializable {
private static final long serialVersionUID = 1L;
Optional<Integer> value = Optional.empty();
public void setValue(Integer i) {
this.i = Optional.of(i);
}
public Optional<Integer> getValue() {
return value;
}
}
//java.io.NotSerializableException is thrown
@Test
public void serialize() {
My my = new My();
byte[] bytes = toBytes(my);
}
public static <T extends Serializable> byte[] toBytes(T reportInfo) {
try (ByteArrayOutputStream bstream = new ByteArrayOutputStream()) {
try (ObjectOutputStream ostream = new ObjectOutputStream(bstream)) {
ostream.writeObject(reportInfo);
}
return bstream.toByteArray();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
A: The Vavr.io library (former Javaslang) also have the Option class which is serializable:
public interface Option<T> extends Value<T>, Serializable { ... }
A: It's a curious omission.
You would have to mark the field as transient and provide your own custom writeObject() method that wrote the get() result itself, and a readObject() method that restored the Optional by reading that result from the stream. Not forgetting to call defaultWriteObject() and defaultReadObject() respectively.
A: This answer is in response to the question in the title, "Shouldn't Optional be Serializable?" The short answer is that the Java Lambda (JSR-335) expert group considered and rejected it. That note, and this one and this one indicate that the primary design goal for Optional is to be used as the return value of functions when a return value might be absent. The intent is that the caller immediately check the Optional and extract the actual value if it's present. If the value is absent, the caller can substitute a default value, throw an exception, or apply some other policy. This is typically done by chaining fluent method calls off the end of a stream pipeline (or other methods) that return Optional values.
It was never intended for Optional to be used other ways, such as for optional method arguments or to be stored as a field in an object. And by extension, making Optional serializable would enable it to be stored persistently or transmitted across a network, both of which encourage uses far beyond its original design goal.
Usually there are better ways to organize the data than to store an Optional in a field. If a getter (such as the getValue method in the question) returns the actual Optional from the field, it forces every caller to implement some policy for dealing with an empty value. This will likely lead to inconsisent behavior across callers. It's often better to have whatever code sets that field apply some policy at the time it's set.
Sometimes people want to put Optional into collections, like List<Optional<X>> or Map<Key,Optional<Value>>. This too is usually a bad idea. It's often better to replace these usages of Optional with Null-Object values (not actual null references), or simply to omit these entries from the collection entirely.
A: A lot of Serialization related problems can be solved by decoupling the persistent serialized form from the actual runtime implementation you operate on.
/** The class you work with in your runtime */
public class My implements Serializable {
private static final long serialVersionUID = 1L;
Optional<Integer> value = Optional.empty();
public void setValue(Integer i) {
this.value = Optional.ofNullable(i);
}
public Optional<Integer> getValue() {
return value;
}
private Object writeReplace() throws ObjectStreamException
{
return new MySerialized(this);
}
}
/** The persistent representation which exists in bytestreams only */
final class MySerialized implements Serializable {
private final Integer value;
MySerialized(My my) {
value=my.getValue().orElse(null);
}
private Object readResolve() throws ObjectStreamException {
My my=new My();
my.setValue(value);
return my;
}
}
The class Optional implements behavior which allows to write good code when dealing with possibly absent values (compared to the use of null). But it does not add any benefit to a persistent representation of your data. It would just make your serialized data bigger…
The sketch above might look complicated but that’s because it demonstrates the pattern with one property only. The more properties your class has the more its simplicity should be revealed.
And not to forget, the possibility to change the implementation of My completely without any need to adapt the persistent form…
A: If you would like a serializable optional, consider instead using guava's optional which is serializable.
A: If you want to maintain a more consistent type list and avoid using null there's one kooky alternative.
You can store the value using an intersection of types. Coupled with a lambda, this allows something like:
private final Supplier<Optional<Integer>> suppValue;
....
List<Integer> temp = value
.map(v -> v.map(Arrays::asList).orElseGet(ArrayList::new))
.orElse(null);
this.suppValue = (Supplier<Optional<Integer>> & Serializable)() -> temp==null ? Optional.empty() : temp.stream().findFirst();
Having the temp variable separate avoids closing over the owner of the value member and thus serialising too much.
A: Just copy Optional class to your project and create your own custom Optional that implements Serializable. I am doing it because I just realized this sh*t too late.
A: the problem is you have used variables with optional. the basic solution to avoid this, provide the variable without optional and get them as optional when you call the getter like below. Optional<Integer> value = Optional.empty(); to Integer value = null;
public class My implements Serializable {
private static final long serialVersionUID = 1L;
//Optional<Integer> value = Optional.empty(); //old code
Integer value = null; //solution code without optional.
public void setValue(Integer value ) {
//this.value = Optional.of(value); //old code with Optional
this.value = value ; //solution code without optional.
}
public Optional<Integer> getValue() {
//solution code - return the value by using Optional.
return Optional.ofNullable(value);
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/24547673",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "125"
}
|
Q: Coldfusion Parse URLs in text Can anyone help with a function that will parse all urls into valid html links in a text string?
For example:
"Welcome to www.nerds4life.com. View our articles at nerds4life.com or at http://nerds4life.com or also http://www.nerds4life.com"
would become:
"Welcome to www.nerds4life.com. View our articles at nerds4life.com or at http://nerds4life.com or also http://www.nerds4life.com"
What would be the best way to approach this. Regex (and if so, how?) or loop through each word in the text (would think that's less efficient)
Thanks
A: Again... there may be a more elegant regex...
Certainly feel free to google for "good" regex's for finding URLs if this one falls short.
<cfset myText = "Welcome to www.nerds4life.com. View our articles at nerds4life.com or at http://nerds4life.com or also http://www.nerds4life.com or at https://foo.com or http://123.com" />
<cfset myNewText = rereplaceNoCase( myText, '((http(s)?://)?((www\.)?\w+\.\w{2,6}))', '<a href="http://\4">\1</a>', 'all' ) />
A: This will parse URL in string that starts with http or www and terminated by a space
<cfset myString = "Welcome to www.nerds4life.com. View our articles at nerds4life.com or at http://nerds4life.com or also http://www.nerds4life.com">
<cfset URLinString = rereplaceNoCase(myString, '(((http(s)?://)|(www))\.?(\S+))', '<a href="http://\1">\1</a>', 'all')>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/5184737",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: TypeError: userAgent.toLowerCase is not a function While running Angular-unit test, using chrome browser, ended up with the error as
TypeError: userAgent.toLowerCase is not a function
at _isAndroid (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/forms/fesm2015/forms.mjs:176:43)
at new DefaultValueAccessor (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/forms/fesm2015/forms.mjs:227:38)
at NodeInjectorFactory.factory (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/forms/fesm2015/forms.mjs:254:1)
at getNodeInjectable (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/fesm2015/core.mjs:3565:44)
at instantiateAllDirectives (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/fesm2015/core.mjs:10318:27)
at createDirectivesInstances (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/fesm2015/core.mjs:9647:5)
at ɵɵelementStart (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/fesm2015/core.mjs:14561:9)
at templateFn (ng:///TodaysMarketMoversComponent.js:397:66)
at executeTemplate (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/fesm2015/core.mjs:9618:9)
at renderView (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/fesm2015/core.mjs:9421:13)
Most wondering/confusing part to me- toLowerCase function has never been used through out the component/spec file.
A: It looks like the userAgent is being checked by the @angular/forms lib and has been deleted or not provided at all for some reason.
If it's not your code that's changing the userAgent then it's probably some third-party script.
If I were you I'd start with the latest additions in terms of libraries and dependencies and peel them back until I get a unit test running. That will give the clue.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73620887",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How can I change the CheckBox focus color on Android? I want to change the checkbox "outline" color, which is visible when focusing the checkbox in order to improve the visibility of the currently focused item when using the app with a keyboard or directional pad. How can I do that?
Image of what I mean:
Focused CheckBox on Android
Edit: After finding the correct wording ("ripple color") for what I mean, I managed to change it with:
<item name="colorControlHighlight">#00f</item>
But this only applies to unchecked checkboxes. Does anybody know how to apply it to all (also checked) checkboxes?
Image of colorControlHighlight effect on checked and unchecked checkboxes
A: Thanks to @special N9NE
This works: define an own ripple ripple_bg.xml:
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
android:color="@color/accent_26" />
And set it as background (globally):
<resources>
<style name="AppTheme" parent="Theme.AppCompat.DayNight">
<!-- ... -->
<!-- custom checkbox style to improve visibility on special (TV) devices -->
<item name="android:checkboxStyle">@style/MyCheckBoxStyle</item>
</style>
<style name="MyCheckBoxStyle" parent="Widget.AppCompat.CompoundButton.CheckBox">
<item name="android:background">@drawable/ripple_bg</item>
</style>
</resources>
A: You can check this blog: AppCompat themes
colorControlHighlight is for ripple color
So try to create a ThemeOverlay.AppCompat theme where you will set the value of the color that you want and that will allow you to change the ripple color for that view and its children.
To target ripple in theme use this attribute:
android:colorControlHighlight
A: you can use the theme attribute:
app:theme="@style/MyCheckboxStyle"
then add this in your style.xml file :
<style name="MyCheckboxStyle" parent="AppTheme">
<item name="colorAccent">@color/colorAccent</item> // color when checkbox is checked
<item name="android:textColorSecondary">@color/colorSecondary</item> // when it is unchecked
</style>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/70580021",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Go: How can I "unpack" a struct? I have a struct:
type mystruct struct {
Foo string
Bar int
}
I'd like to create SQL insert statements from the struct which have the following form:
m := mystruct{ "Hello" , 1 }
query := "INSERT INTO mytbl ( foo, bar ) VALUES ( ?,? )"
res,err := db.Exec(query, m.Foo, m.Bar)
Now my question is: how can I make the last line dynamically from the struct (or m) itself? I am able to get the struct names using reflect, but I don't know how to create the []interface{} slice for the db.Exec() call. This is what I have tried: (http://play.golang.org/p/GR1Bb61NFH)
package main
import (
"fmt"
"reflect"
)
type mystruct struct {
Foo string
Bar int
}
func main() {
m := mystruct{"Foo", 1}
fmt.Println(readNames(m))
x := unpackStruct(m)
fmt.Printf("%#v\n", x)
}
func unpackStruct(a interface{}) []interface{} {
// "convert" a to m t
// doesn't work, from 'laws of reflection'
s := reflect.ValueOf(&t).Elem()
typeOfT := s.Type()
for i := 0; i < s.NumField(); i++ {
f := s.Field(i)
fmt.Printf("%d: %s %s = %v\n", i,
typeOfT.Field(i).Name, f.Type(), f.Interface())
}
// this is in principle what I want:
m := mystruct{"Hello", 2}
var ret []interface{}
ret = make([]interface{}, s.NumField())
ret[0] = m.Foo
ret[1] = m.Bar
return ret
}
// works fine:
func readNames(a interface{}) []string {
s := reflect.TypeOf(a)
lenStruct := s.NumField()
ret := make([]string, lenStruct)
for i := 0; i < lenStruct; i++ {
ret[i] = s.Field(i).Name
}
return ret
}
A: If getting the values of the fields is your issue, this code snippet should help:
s := reflect.ValueOf(a)
ret := make([]interface{}, s.NumField())
for i := 0; i < s.NumField(); i++ {
ret[i] = s.Field(i).Interface()
}
A: If creating the []interface{} value is your problem, using reflect's slice creation mechanisms should work nicely:
slc := reflect.MakeSlice(InterfaceType, len, cap) // See the link below for creating InterfaceType
slc.Index(0).Set(TargetValue)
return slc.Interface()
(Here's the above-mentioned link).
Modifying the above code to loop over the values in the struct instead of just the 0th index shouldn't be too bad.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/18628852",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Python mysql.connector select without locked rows from transactions I'm currently working on a Project with MySQL-based Jobworkers. In order for them to fetch a new Job i ran into a problem with row locking:
On Native MySQL (ran 2 terminals and executed following):
SELECT id FROM `data` WHERE `status`=0 ORDER BY `created_at` LIMIT 20 FOR UPDATE SKIP LOCKED;
The Select does not lock the rows what so ever (intended to be this way & what I want)
But running the exact same in Python:
import mysql.connector
class DB:
def __init__(self):
self.conn = mysql.connector.MySQLConnection(
host = "localhost",
database = "test"
)
-------------------------
db = DB()
cursor = db.conn.cursor()
cursor.execute("SELECT id FROM `data` WHERE `status`=0 ORDER BY `created_at` LIMIT 20 FOR UPDATE SKIP LOCKED")
Locks all selected Rows even tho no Transaction was ever started for all other Python connections + Native selects in Terminal.
What am I missing here?
Basically all I want is a select to skip locked rows from Python.
Cheers.
Tried enabling autocommit with:
db = DB()
db.autocommit = True
Also tried:
mysql.connector.MySQLConnection
mysql.connector.connect
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/74824541",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to call static func by passing $_GET params? i have got a static function> which is called
regenerateThumbnailsCron()
And I would like to execute this function by GET params, for example>
if($_GET["pass"]=="password")
self::regenerateThumbnailsCron();
But if I tryied to call this function in constructor>
class AdminImages extends AdminTab
...
public function __construct()
{
if($_GET["pass"]=="password")
self::regenerateThumbnailsCron();
}
I cannot execute this function.
Is any way, how to call this function before __construct to correctly execute?
Thanks very much for any advice.
EDIT>
I tried also with public function>
<?php
include 'AdminImages.php';
$images = new AdminImages();
$images->regenerateThumbnailsCron();
?>
But i got error>
Fatal error: Class 'AdminTab' not found
A: You need to do a include 'AdminTab.php'; as well, since your class extends that
A: Not completely sure I understand your question, are you saying that you have static class "B" which extends class "A", "A" having your regenerateThumbnailsCron() method which you want to call before anything else?
If so then try this:
<?php
class A {
private function regenerate() {
.... do something ....
}
}
class B extends A {
function __construct() {
if ($_GET["pass"] == "password") {
parent::regenerate();
}
}
function regenerateThunbnailsCron() {
.... do somethinig ....
}
}
$images = new B();
$images->regenerateThumbnailsCron();
?>
This way, your parent's "regenerate()" function would get called during the constructor. You can switch this around to be a static class if you want, which if your goal is to compartmentalise any variables and functions away from the global scope would be a better way.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/4596980",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: SetProperty of "SelectedItem is not supported on control type: Window while trying to select an item from combo box in windows application error message showing
"SetProperty of "SelectedItem" is not supported on control type: Window"
A: The problem is that you are calling an instance of class Window but not ComboBox. I see to possible reasons why this happens. Either you are referring to the wrong ui property from UIMap or Coded UI Test Builder recorded wrong element or not the whole hierarchy of your wanted test control.
Moreover, if you are trying to select an item in combobox, then just use
comboBox.SelectedIndex = 3; // to select an item by its zero-based index
comboBox.SelectedItem = "Item Text"; // to select an item by its text
If it does not help, provide additional information on the problem, particularly on the technology of your Windows Application (UIA/WPF or MSAA/WinForms).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/33541457",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Java 8 how to check null values and get List of object? I've a below code written in Java and I wanted to use in Java 8. How can I do that?
Below code is within method:
Query query = new Query();
query.fields().include("address");
query.fields().exclude("_id");
List<User> users = mongoTemplate.find(query, User.class);
List<Address> addresses = new ArrayList<>();
if(!users.isEmpty()) {
for (Address address : addresses) {
addresses.addAll(country.getSubaddress());
}
}
return address;
in Java 8
List<List<Address>> values = countries.stream().filter(Objects::nonNull).map(x -> x.getAddresses()).collect(Collectors.toList());
I only want List of Address. How can I do that ?
A: This is one way of solving the problem:
List<Address> addresses = Optional.ofNullable(users)
.orElseGet(Collections::emptyList)
.stream()
.filter(Objects::nonNull)
.flatMap(x -> x.getAddress().stream())
.collect(Collectors.toList());
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/55521274",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: How to continously deploy a feature to karaf? I want to continously deploy a feature to ServiceMix 6.0, which is based on Karaf 3.0.4.
I first tried this using the karaf console. However there are some problems. It is for a standard karaf installation not possible to determine on the karaf console if a feature is already installed (see my other question on this). The other problem with the karaf console is that it doesn't support exit codes. So it is not possible to determine reliably if a feature installation was successfully finished.
I then installed hawtio and tried to use the exposed JMX beans via jolokia/REST that is bundled with hawtio. The problem here is that karaf 3.0.x is unable to update a feature. Therefore features must be uninstalled first. However the FeatureService only offers the possibility to uninstall an explicitly specified feature. But when a previous version of the feature was installed, subfeatures were installed with it. They also need an upgrade and therefore be uninstalled first. So I would need a way to iterate over the subfeatures of a feature, which I do not have.
So how can continous deployment of features to karaf 3.0.x be done?
A: The first try we have implemented is a bash script. The biggest problem is uninstalling the old version. Therefore we have set up a convention for the names of the feature and it's subfeatures. So we can use the following to find already installed features:
features=$(echo "feature:list" | ssh -p $smx_ssh_port $smx_user@$smx_host | grep -h "<feature-name-convention-regex>.*|.*x.*|" | cut -f1 -d" " | tr '\n' ' ')
This can then be passed to feature:uninstall and can also be used for detecting if features were installed after the call to feature:repo-add -i.
The remaining problem is that we are unable to reference 3rd-party subfeatures because they won't be uninstalled when an updated version needs to be installed and we can't be sure if all of the subfeatures have been successfully installed.
A: For karaf 3 there is no good way to update features.
This is already a little better for karaf 4. It allows to update a feature repo and you can then simply install the feature again. It will detect that the feature has changed and do the necessary changes in bundles.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/32117888",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Using cuda thrust::max_element to find max element in array returns incorrect sometimes I have a 2^20 element array being filled on the device; these numbers should be the same every time.
I then move that array over to the host and then search for the max element in the array, this technique works with 2^10 element array but once I begin to get any larger than that I begin to get random answers not sure if thrust is messing up or the device calculations.
The answer max_element should return is 0.094479 usually the first time the program is run the code will output the correct answer then the answer will randomly show up every few times
GPU is tesla k20 running 5.0 also tested on 780GTX; same issue both times
//Host Code
int main( void ) {
float h_c[TOTAL];
float *d_c;
cudaMalloc((void**)&d_c, sizeof(float)*TOTAL);
cudaEvent_t start, stop;
cudaEventCreate(&start);
cudaEventCreate(&stop);
cudaEventRecord(start);
//Number of threads
kernel<<<BLOCKS,THREADS>>>(d_c);
cudaEventRecord(stop);
cudaEventSynchronize(stop);
float mil = 0;
cudaEventElapsedTime(&mil, start, stop);
cudaMemcpy(h_c, d_c, sizeof(float)*TOTAL, cudaMemcpyDeviceToHost);
for(int y = 0; y < TOTAL; y++){
printf(" %d: Host C: %f \n",y, h_c[y]);
}
float *result = thrust::max_element(h_c, h_c + TOTAL);
printf("Max is: %f \n", *result);
printf("Time: %f \n", mil/1000);
printf("THREADS: %d \n", THREADS);
printf("BLOCKS: %d \n", BLOCKS);
printf("TOTAL: %d \n", TOTAL);
cudaFree(d_c);
cudaDeviceReset() ;
return 0;
}
Device Code
#include <thrust/extrema.h>
#include <math.h>
#include <stdio.h>
#define ARRAYSIZE 15
#define THREADS 1024
#define BLOCKS 32
#define TOTAL THREADS * BLOCKS
__global__ void kernel(float *cc){
//Get thread for summing all elements
int threadId = threadIdx.x + blockDim.x * blockIdx.x;
int decimalNumber,quotient;
//Size of the array
//const int size = 10;
//Holds the binary number in an array
int binaryNumber[ARRAYSIZE];
int i = 0;
int a[ARRAYSIZE] = {1192, 1315, 1462, 1484, 1476, 1443, 1508, 1489, 1470, 1573, 1633, 1539, 1600, 1707, 1701};//, 1682, 1688, 1681, 1694, 1728};
int b[ARRAYSIZE] = {1162, 1337, 1282, 1491, 1508, 1517, 1488, 1513, 1539, 1576, 1626 ,1634, 1573, 1786, 1741};//, 1782, 1755, 1669, 1700, 1826};
//Holds Product from the dot product
int c[ARRAYSIZE];
//Arrays to hold integers to be summed
int aSumArr[ARRAYSIZE];
int bSumArr[ARRAYSIZE];
for(int i = 0; i < ARRAYSIZE; i++){
c[i] = 0;
aSumArr[i] = 0;
bSumArr[i] = 0;
}
//Holds the value for the dot product
int dotSum = 0;
//Holds sum of valid array positions for array a
int aSum = 0;
//Holds sum of valid array positions for array b
int bSum = 0;
//Holds the Value of the arcCos of the dot product / sqrt(array a) * sqrt(array b)
float finalValue = 0;
//printf("ThreadID: %d \n", threadId);
//ALL 1's 1048575 = Threads
decimalNumber = threadId;
//printf("decimal number: %d \n", decimalNumber);
quotient = decimalNumber;
//Loop to convert decimal into binary and store in array
while(quotient!=0){
binaryNumber[i++]= quotient % 2;
quotient = quotient / 2;
}
//Test if conversion from decimal to binary is complete and correct
//printf("Equivalent binary value of decimal number %d: \n",decimalNumber);
//for(int in = size-1; in >= 0;in--){
//printf("Index: %d | binary number: %d ---- a:%d || b: %d\n",in,binaryNumber[in],a[in],b[in]);
//}
//printf(" \n ");
//Loop through binaryNumber array
for(int x = ARRAYSIZE-1 ; x >= 0; x--){
//If index is == 1 Perform calculation
if(binaryNumber[x] == 1){
//Multiply numbers at good index
c[x] = a[x] * b[x];
//Fill sum arrays at correct index
aSumArr[x] = a[x];
bSumArr[x] = b[x];
//Checks if the loop is executing correctly
//sumArray[x] = 1;
//printf("Multiplied - %d * %d = %f\n", a[x], b[x], c[x]);
//printf("--This should not be run --\n");
}else{
// printf("SKIPPED - %d * %d = %f\n", a[x], b[x], c[x]);
}
}
//Sums up the product array to complete dot product
for(int j = 0; j < ARRAYSIZE; ++j){
dotSum += c[j];
//printf("aSumArr %d \n", aSumArr[j]);
//printf("bSumArr %d \n", bSumArr[j]);
aSum += powf( aSumArr[j], 2 );
bSum += powf( bSumArr[j], 2 );
// printf("aSum: %d + aSumArr %d \n", aSum, aSumArr[j]);
// printf("bSum: %d + bSumArr %d \n", bSum, bSumArr[j]);
}
//printf("\n");
//Print out the dot prudct
//printf("Dot product is: %d \n", dotSum);
//printf("aSum is: %d \n", aSum);
//printf("bSum is: %d \n", bSum);
float sqSum1 = sqrtf(aSum);
float sqSum2 = sqrtf(bSum);
// printf("sqSum1: %f \n", sqSum1);
// printf("sqSum2: %f \n", sqSum2);
float sqSum = sqSum1 * sqSum2;
// printf("sqSum %f \n", sqSum);
float div = dotSum / sqSum ;
// printf("div: %f \n", div);
finalValue = acosf( div ) ;
//Stores the threads final value in array cc, in the respected index
if(finalValue == finalValue){
cc[threadId] = finalValue;
}else{
cc[threadId] = -2;
}
//printf("final value is: %f for number %d \n", finalValue, threadId);
}
A: It seems to be a case of using improperly initiialized/uninitialized variables.
After I added the following line:
for(int i = 0; i < ARRAYSIZE; i++){
c[i] = 0;
aSumArr[i] = 0;
bSumArr[i] = 0;
binaryNumber[i] = 0; // add this line
}
I was no longer able to reproduce the issue.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/27238084",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Set background color of NSWindow with appearance set I am using the following code on my NSWindow so that all my buttons, pop ups, etc. are in a dark mode tint:
[self.window setAppearance:[NSAppearance appearanceNamed:NSAppearanceNameVibrantDark]];
But I want to set a custom window background color instead of the black color which is set as default for the Vibrant Dark Appearance. Calling this line without the appearance works otherwise fails to set:
self.window.backgroundColor = [NSColor colorWithPatternImage:[NSImage imageNamed:@"backgroundColor"]];
Any ideas?
A: Just add a view with a background color and use It as your window's background.
Take a look at this sample app.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/33595674",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to run angular test using Cloud Build? I use out-of-the-box Angular testing framework: Jasmine and karma for Unit Test and GCP Cloud Build to deploy the app. However, there is a problem in testing because there is no Chrome installed for the node Docker image.
What is the best way to handle that? Create a customized docker image? Or is there any well-known docker image I can leverage for build and test Angular app in Cloud Build?
cloudbuild.yaml
steps:
# Install
- name: node:14
entrypoint: npm
args: ["install"]
#Build
- name: node:14
entrypoint: npm
args: ["run", "build", "--", "--aot"]
# Test <- This step fails. See the error message below
- name: node:14
entrypoint: npm
args: ["run", "test", "--", "--watch=false"]
# Deploy to Firebase
- name: gcr.io/$PROJECT_ID/firebase
args: ["deploy", "--project=$PROJECT_ID", "--only=hosting"]
Error
Already have image: node:14
> [email protected] test /workspace
> ng test "--watch=false"
- Generating browser application bundles (phase: setup)...
18 01 2022 19:22:45.740:INFO [karma-server]: Karma v6.3.11 server started at http://localhost:9876/
18 01 2022 19:22:45.744:INFO [launcher]: Launching browsers Chrome with concurrency unlimited
18 01 2022 19:22:45.749:INFO [launcher]: Starting browser Chrome
18 01 2022 19:22:45.756:ERROR [launcher]: No binary for Chrome browser on your platform.
Please, set "CHROME_BIN" env variable.
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] test: `ng test "--watch=false"`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] test script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! /builder/home/.npm/_logs/2022-01-18T19_22_45_880Z-debug.log
A: If you need headless chrome in your container, choose a container with node14 and headless chrome installed. I found this one with Chrome 89 and released 10 months ago. You could find better source I guess
Else, you can use your node:14 container and, if it's possible, install headless Google Chrome on it (something like that, install work, but I haven't node file to test on it to validate completely that example)
- name: node:14
entrypoint: bash
args:
- -c
- |
wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb
apt update && apt install -y libappindicator1 fonts-liberation ./google-chrome-stable_current_amd64.deb
npm run test -- --watch=false
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/70789800",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: What is on my heap? C linux So I called malloc(1024) today to just play around with the heap. I for the most part understand the structure of the heap, so when I printed out what was in memory, I wasn't surprised to see "00000000 00000409 00000000 00000000 ...."
however 1032 bytes later, I expected to find the top chunk of the heap. Instead I found another chunk as if another call of malloc(1024) had happened after my initial one.
In this chunk is the following:
00000000 00000409 30387830 65336234
30203a30 30303030 20303030 30303030
30303030 30303020 30303030 30302030
34303030 33203930 33303330 20303330
30333033 30333032 33343320 33303330
33332030 39333032 000a3233 00000000
which translates to:
08x0e3b40 :00000 00000000000000 000000 040003 903030 03003030302343 303033#09302
23
Does anyone know why this exists? I am sure I am only calling malloc once. And it always seems to be there no matter what size I malloc.
A: malloc reservers a particular amount of memory on the heap and gives back a pointer to this memory block (or NULL, if it was not able to allocate the desired memory block). Note, however, that malloc will not initialise the memory block in any way. It will not fill it with 0 or any other value; it will simply keep it's content as is.
So the question is actually "what is the initial content of the heap when a program starts?". And the answer is: it depends on the operating system, which portion of memory it assigns to a program when executed, and the content of this memory block is very likely to be just "something undefined", not even random. This can be some recurring patterns of values, it can be zeros, it can be everything.
When you look into different portions of a program's heap, you will probably see this "something undefined" content, regardless of whether you have used malloc before or not. You may see recurring patterns as in your case. Note, however, that "looking into" portions of the heap that have not been allocated before is actually undefined behaviour.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/43530173",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Recursively update a State Monad this question is related to this question
I have a state monad. An object provides an update function as in the OOD strategy pattern.
*
*The choice of having a object is that in real, production code, the
class provides an array of operations, all sharing state through the
monad. Inheritance helped me extend the basic functionality and
further customizing the class providing the operations.
*The choice of having a monad instead of a mutable property within the class is that the monad, through proper use of generics, is helping me abstracting and being more flexible on what variables/information must be carried along the computation as "state".
I have a simple toy example:
/////////////////////////////////////////////////////////////////////////////////////
// Definition of the state
/////////////////////////////////////////////////////////////////////////////////////
type StateFunc<'State, 'T> = 'State -> 'T * 'State
/////////////////////////////////////////////////////////////////////////////////////
// Definition of the State monad type
/////////////////////////////////////////////////////////////////////////////////////
type StateMonadBuilder<'State>() =
// M<'T> -> M<'T>
member b.ReturnFrom a : StateFunc<'State, 'T> = a
// 'T -> M<'T>
member b.Return a : StateFunc<'State, 'T> = ( fun s -> a, s)
// M<'T> * ('T -> M<'U>) -> M<'U>
member b.Bind(p : StateFunc<_, 'T>, rest : 'T -> StateFunc<_,_>) : StateFunc<'State, 'U> =
(fun s ->
let a, s' = p s
rest a s')
// Getter for the whole state, this type signature is because it passes along the state & returns the state
member b.getState : StateFunc<'State, _> = (fun s -> s, s)
// Setter for the state
member b.putState (s:'State) : StateFunc<'State, _> = (fun _ -> (), s)
let runState f init = f init
/////////////////////////////////////////////////////////////////////////////////////
// STRATEGY PATTERN
/////////////////////////////////////////////////////////////////////////////////////
let state = StateMonadBuilder<int> ()
// DoubleFunctOne defines standard operations that remain always the same
type Strategy (aFunction) =
member this.Update (x: int) = state {
let! currState = state.getState
let processedx = aFunction x
do! state.putState (currState + x) }
// Create a function that customizes the strategy
let myFunction x =
2 * x
// Customize the strategy with the desired function:
let strategy = Strategy (myFunction)
/////////////////////////////////////////////////////////////////////////////////////////////////////////
// Update recursively
/////////////////////////////////////////////////////////////////////////////////////////////////////////
// ?? How to run update recursively ??
let result initialCondition =
initialCondition
|> (for i = 10 to 100 do
yield state { do! strategy.Update i } )
My goal is to apply the initial conditions, fetch data and launch recursively (within a for or a while loop or even some functional operation) the functions provided by strategy. Working with the monad, I am not sure how to do this.
Thank you.
Computational Expression For
Inspired by @kvb answer, I have added a for method to the computational expression.
// Loops through seqnc of numbers that constitute an input to func
member b.For (seqnc:_ List, func) =
seqnc
|> List.map (fun item -> func item)
|> List.reduce (fun acc item ->
(fun s ->
let _, s' = acc s
item s' ) )
I run a few tests and I have the impression that this one works.
Thanks.
A: Something like this?
let result initialCondition =
let rec loop = function
| 101 -> state { return () }
| i ->
state {
do! strategy.Update i
do! loop (i+1)
}
initialCondition
|> runState (loop 10)
Alternatively, define a For member on your builder and write it the more imperative way:
let result initialCondition =
let f = state {
for i in 10 to 100 do
do! strategy.Update i
}
initialCondition
|> runState f
Also, note that there is likely a bug in your definition of Strategy.Update: processedx is bound but unused.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/20357643",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Linq to sql Distinct after join I have a join query and i want to filter the result of this query by using distinct. I want to get only one of the shoes which has same brand, model, primary color and secondary color. How can i make this ? Here is my join query.
var query = from b in db.BrandTbls.AsQueryable()
join m in db.ShoeModelTbls on b.BrandID equals m.BrandID
join s in db.ShoeTbls on m.ModelID equals s.ModelID
join i in db.ShoeImageTbls on s.ShoeID equals i.ShoeID
where s.Quantity > 0
orderby m.ModelName
select new
{
s.ShoeID,
m.ModelName,
m.Price,
b.BrandName,
i.ImagePath
};
A: I found the solution. This query does approximately what i want to do
var query = from b in db.BrandTbls.AsQueryable()
join m in db.ShoeModelTbls on b.BrandID equals m.BrandID
join s in db.ShoeTbls on m.ModelID equals s.ModelID
join i in db.ShoeImageTbls on s.ShoeID equals i.ShoeID
group new {b,m,s,i} by new {b.BrandName,m.ModelName,m.Price,s.ShoeID,s.PrimaryColor,s.SecondaryColor,i.ImagePath} into g
select new {g.Key.ShoeID,g.Key.BrandName,g.Key.ModelName,g.Key.ImagePath,g.Key.Price};
A: Remove price from the output and use Distinct() like this:
var query = (from b in db.BrandTbls.AsQueryable()
join m in db.ShoeModelTbls on b.BrandID equals m.BrandID
join s in db.ShoeTbls on m.ModelID equals s.ModelID
join i in db.ShoeImageTbls on s.ShoeID equals i.ShoeID
where s.Quantity > 0
orderby m.ModelName
select new
{
s.ShoeID,
m.ModelName,
b.BrandName,
i.ImagePath
}).Distinct();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/23895647",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: API call in ReactJS and setting response to state I have an array with ids like
[123,345,212,232.....]
I have a Rest API that responds the particular product with respect to an id .
So in ReactJS, how would I loop through the array and get the products and store in state
I tried doing this in useEffect{running once as in componentDidMount} but it only stores the first product in array.
Are there better ways to accomplish this?
My Actual Code that has the problem is
useEffect(() => {
const getBought = async () => {
user.bought.map(async (boughtID) => {
let bought = await get(`/bought/${boughtID}`, {}, true);
let boughtDate = bought.createdAt.slice(0, 10);
bought.products.map(async (pr) => {
let product = await get(`product/${pr.product}`);
let quantityBought = pr.quantity;
setAllBoughts({
...allBoughts,
[boughtDate]: [
...(allBoughts.boughtDate || []),
{
product,
quantityBought,
},
],
});
});
});
};
getBought();
}, []);
So I have a user which has arrays of boughtIds in bought key...
so I am looping throughout those bought keys
A bought schema has products which has product id and number of product bought (pr.product and pr.quantity).. So I am hitting the API , and save all the products in a state object.
so allBoughts is state which is an object that has keys as (dates) as in the code .createdAt.slice(0,10) which gives me date removing rest of stuffs mongodb added.
But everytime I do it, there are few things that happen.
Either only the first item is saved, and rest are not
Either the same item gets overwritten
or the page reloads infinitely(especially whrn I try to remove dependency array from useEffect)
A: setAllBoughts({
...allBoughts,
[boughtDate]: [
...(allBoughts.boughtDate || []),
{
product,
quantityBought,
},
],
});
allBoughts is the state that existed when this effect ran. Ie, it's the empty state, with no results in it yet. So every time a result comes back, you are copying the empty state, and adding one entry to it. This erases any results you have.
Instead, you need to use the most recent version of the state, which you can do with the function version of set state:
setAllBoughts(prevState => {
return {
...prevState,
[boughtDate]: [
...(prevState.boughtDate || []),
{
product,
quantityBought,
},
],
};
})
A: From what you're saying, it seems to me that you're erasing the previous stored result in the state (You get result for id 123, store it, then result of 345, store it and erase the previous value). Or you're just not looping through the array.
Here is an example of how to GET multiple times in a useEffect and assign all the results in the state.
Fully working example at Codesandbox
export default function App() {
const ids = useRef([1, 3, 5]);
const [items, setItems] = useState([]);
useEffect(() => {
const promises = ids.current.map((id) => fetchData(id));
Promise.all(promises).then((responses) => {
setItems(responses);
});
}, []);
async function fetchData(id) {
const response = await fetch(
`https://jsonplaceholder.typicode.com/posts/${id}`
);
return response.json();
}
return (
<div className="App">
{items.map((item) => (
<div key={item.id}>
{item.id} - {item.title}
</div>
))}
</div>
);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/66702031",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do I prefix my log messages with the current date and time? I'm using Python 3.9 and Django 3.2. I have logging configured in my settings.py file
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'console': {
'class': 'logging.StreamHandler',
},
},
'root': {
'handlers': ['console'],
'level': 'INFO',
},
}
When I do logging in one of my classes, I do it like so
import logging
...
class TransactionService:
def __init__(self):
self._logger = logging.getLogger(__name__)
def my_method(self, arg1, arg2):
...
self._logger.info("Doing some logging here.")
How do I configure my logger such that when the message is printed out, it is prefixed by the current date and time?
A: This worked for me (adapted from thorndeux's answer):
import logging.config
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'prepend_date': {
'format': '{asctime} {levelname}: {message}',
'style': '{',
},
},
'handlers': {
'console': {
'class': 'logging.StreamHandler',
'formatter': 'prepend_date',
},
},
'root': {
'handlers': ['console'],
'level': 'INFO',
},
}
logging.config.dictConfig(LOGGING)
logging.info('foo')
logging.warning('bar')
prints
2021-11-28 16:05:13,469 INFO: foo
2021-11-28 16:05:13,469 WARNING: bar
A: Add a formatter to your logger. For example:
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'prepend_date': {
'format': '{asctime} {message}',
'style': '{',
},
},
'handlers': {
'console': {
'class': 'logging.StreamHandler',
'formatter': 'prepend_date',
},
},
'root': {
'handlers': ['console'],
'level': 'INFO',
},
}
A: The answer to your question can be found in the official documentation, please read the full article.
import logging
FORMAT = '%(asctime)s %(message)s'
logging.basicConfig(format=FORMAT)
logger = logging.getLogger()
logger.setLevel(logging.INFO)
logger.info("Doing some logging here.")
This would print:
2021-11-29 14:06:59,825 Doing some logging here.
A: What is missing in your example is formatters (add to LOGGING dict following):
LOGGING = {
...
"formatters": {"console": {"format": "%(asctime)s %(message)s"}},
# and add it to handlers
"handlers": {"console": {"class": "logging.StreamHandler", "formatter": "console"}},
...
}
Another thing that you may want to change logging setup in classes to something like
import logging
logger = logging.getLogger(__name__)
...
class TransactionService:
def my_method(self, arg1, arg2):
...
logger.info("Doing some logging here.")
You can also find full example in official Django documentation (last of examples in that subsection):
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'verbose': {
'format': '{levelname} {asctime} {module} {process:d} {thread:d} {message}',
'style': '{',
},
'simple': {
'format': '{levelname} {message}',
'style': '{',
},
},
'filters': {
'special': {
'()': 'project.logging.SpecialFilter',
'foo': 'bar',
},
'require_debug_true': {
'()': 'django.utils.log.RequireDebugTrue',
},
},
'handlers': {
'console': {
'level': 'INFO',
'filters': ['require_debug_true'],
'class': 'logging.StreamHandler',
'formatter': 'simple'
},
'mail_admins': {
'level': 'ERROR',
'class': 'django.utils.log.AdminEmailHandler',
'filters': ['special']
}
},
'loggers': {
'django': {
'handlers': ['console'],
'propagate': True,
},
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': False,
},
'myproject.custom': {
'handlers': ['console', 'mail_admins'],
'level': 'INFO',
'filters': ['special']
}
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/70059001",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: jQuery FullCalendar Plugin not Showing Events I'm using the FullCalendar plugin in a CodeIgniter application. I'm retrieving event objects with a GET request server side and the events do not show on the calendar using a similar approach to the events as a function example with a callback. I have verified that the GET request returns json properly.
Here is the json returned by my request...
[{"id":"1","title":"2011 Acura Integra (1)","start":1313996400,"color":"red"}, {"id":"15","title":"2011 Acura Integra (1)","start":1314774000,"color":"red"}]
My call is as follows...
var year = $("#year").text();
var month = $("#month").text();
$maintenance_schedule_calendar_table = $("#vehicles_maintenance_schedule_calendar").fullCalendar({
year: year,
month: month -1,
header: {
left: 'prev,next today',
center: 'title',
right: ''
},
editable: true,
disableResizing: true,
events: function(start, end, callback) {
var start_timestamp = Math.round(start.getTime() / 1000);
var end_timestamp = Math.round(end.getTime() / 1000);
var url = "/tripsys/new_admin/vehicles/get_maintenance_schedule_data/" + start_timestamp + "/" + end_timestamp;
$.get(url, function(events) {
callback(events);
});
}
});
The strange thing is that the previous call fetches the json properly and the callback seems to process the events because if I call the .fullCalendar('clientEvents') it shows the json that I passed into the events method, but they do not render.
However if I pass this same json into my initial FullCalendar call directly the events do render...
var year = $("#year").text();
var month = $("#month").text();
$maintenance_schedule_calendar_table = $("#vehicles_maintenance_schedule_calendar").fullCalendar({
year: year,
month: month -1,
header: {
left: 'prev,next today',
center: 'title',
right: ''
},
editable: true,
disableResizing: true,
events: [
{"id":"1","title":"2011 Acura Integra (1)","start":1313996400,"color":"red"},
{"id":"15","title":"2011 Acura Integra (1)","start":1314774000,"color":"red"}
]
});
Does anyone have any idea why the first example is not rendering the events on my calendar?
A: Turns out that the problem was caused by me requesting the data with $.get instead of with $.getJSON
This is the correct call...
var year = $("#year").text();
var month = $("#month").text();
$maintenance_schedule_calendar_table = $("#vehicles_maintenance_schedule_calendar").fullCalendar({
year: year,
month: month -1,
header: {
left: 'prev,next today',
center: 'title',
right: ''
},
editable: true,
disableResizing: true,
events: function(start, end, callback) {
var start_timestamp = Math.round(start.getTime() / 1000);
var end_timestamp = Math.round(end.getTime() / 1000);
var url = "/tripsys/new_admin/vehicles/get_maintenance_schedule_data/" + start_timestamp + "/" + end_timestamp;
$.getJSON(url, function(events) {
callback(events);
});
}
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7165585",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Bootstrap MultiSelect Options list need to hide while scroll the window
<!DOCTYPE html>
<html>
<head>
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.15/js/bootstrap-multiselect.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.15/css/bootstrap-multiselect.css" rel="stylesheet"/>
</head>
<body>
<div class="container">
<div class="example">
<script type="text/javascript">
$(document).ready(function() {
$('#multi-select-demo').multiselect();
});
</script>
<select id="multi-select-demo" multiple="multiple">
<option value="jQuery">jQuery tutorial</option>
<option value="Bootstrap">Bootstrap Tips</option>
<option value="HTML">HTML</option>
<option value="CSS">CSS tricks</option>
<option value="angular">Angular JS</option>
</select>
</div>
</div>
</body>
</html>
In multiselect, we have a bunch of options. These options need to hide while user scrolls the window. The list is contained in a ul with class name "multiselect-container".
A: Triggering a click outside the element should do the trick.
$(document).click();
There is no official way to 'close' the bootstrap dropdown, however, the above one is a workaround to handle that. It basically triggers a fake click outside the dropdown, therefore, closing it.
If you want it to close every time user starts scrolling, then:
$(window).on('scroll',function(){
$(document).click();
});
A:
var prev = 0;
var $window = $(window);
var nav = $('.nav');
$window.on('scroll', function(){
var scrollTop = $window.scrollTop();
nav.toggleClass('hidden', scrollTop > prev);
prev = scrollTop;
});
@import bourbon
body
font-family: helvetica neue, helvetica, arial, sans-serif
height: 8000px
.nav
background: #111
text-align: center
color: #fff
+padding(20px null)
+position(fixed, null 0px 0px 0px)
+transition(transform 1s $ease-in-out-quint)
.nav.hidden
+transform(translateY(100%))
p
margin: 0
+padding(20px)
<div class="nav">Scroll to show/hide this bar!</div>
<p>They see me scrolling...</p>
A: <!DOCTYPE html>
<html>
<head>
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.15/js/bootstrap-multiselect.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.15/css/bootstrap-multiselect.css"
rel="stylesheet"/>
</head>
<body>
<div class="container">
<div class="example">
<script type="text/javascript">
$(document).ready(function () {
$('#multi-select-demo').multiselect();
});
window.addEventListener("wheel", myScript);
function myScript() {
$("#multi-select-demo").dropdown('toggle');
}
</script>
<select id="multi-select-demo" multiple="multiple">
<option value="jQuery">jQuery tutorial</option>
<option value="Bootstrap">Bootstrap Tips</option>
<option value="HTML">HTML</option>
<option value="CSS">CSS tricks</option>
<option value="angular">Angular JS</option>
</select>
</div>
</div>
</body>
</html>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/57685229",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Bootstrap responsive: How to fix a non-responsive element? I've enabled the responsive feature in twitter bootstrap, using nested fluid grid. When viewed on small mobile, every single spans are stacked. However, I'd like to keep the "maincontent" unstacked and shown in horizontal layout. I've tried display:inline-block; and min-width but both didn't work. Any recommendations? Thank you.
<div class="container-fluid">
<div class="row-fluid">
<div class="span9" id="maincontent">
<div class="container-fluid">
<div class="row-fluid">
<div class="span2">2</div>
<div class="span8">8</div>
<div class="span2">2</div>
</div>
</div>
</div>
<div class="span3" id="sidebar">
<!-- sidebar elements go here -->
</div>
</div>
</div>
A: Give something like this a shot:
<div class="container-fluid">
<div class="row-fluid">
<div class="span9" id="maincontent">
<div class="row">
<div class="span2" style="float: left; width: 15%;">2</div>
<div class="span8" style="float: left; width: 65%;">8</div>
<div class="span2" style="float: left; width: 15%;">2</div>
</div>
</div>
<div class="span3" id="sidebar">
<!-- sidebar elements go here -->
sidebar
</div>
</div>
</div>
You'll want to tweak and play with the % to fit your needs, and eventually move those inline styles out into a stylesheet. You may need to slap !important on them to keep them from being overriden by the fluid twitter bootstrap classes. The reason they were stacking with your setup is that the fluid styles took over despite the non-fluid container/row classes you used, and changed them to float: none, width: 100%; display: block divs.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/16885799",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: YouTubeAPI v3 - "Daily Limit Exceeded" error before my app reaches API quota limit Daily, between 11:00PM and 2:00AM EDT, my requests to the YouTube v3 API start failing the "dailyLimitExceeded" error, status code 403. The error always stops at 3:00AM EDT. My app hasn't actually yet reached the 50,000,000 units limit. Any idea why this could be happening?
{
"error": {
"errors": [
{
"domain": "usageLimits",
"reason": "dailyLimitExceeded",
"message": "Daily Limit Exceeded"
}
],
"code": 403,
"message": "Daily Limit Exceeded"
}
}
This started occurring on May 19th, though my app's API usage hasn't really changed since a few weeks before the 19th. Since the issue started, the most API units my app has used is 44,995,660 out of the allowed 50,000,000. The app usually ends each day between 42,000,000 and 45,000,000 units used. My per-user-limit is 3,000 requests/second/user (I highly doubt the API calls from my users are that dense this late at night).
Any ideas on why this could be happening would be greatly appreciated.
EDIT: I should note that this doesn't affect all of my users when it happens (I believe less than half), many are able to continue using the app without issue while others are receiving the error.
A: YouTube Data API Errors -> Global Domain Errors
dailyLimitExceeded402 A daily budget limit set by the developer has
been reached.
Billing status
This API is limited by the free quota shown below. Apply for higher quota
Quota summary
Daily quota resets at midnight Pacific Time (PT).
Free quota 50,000,000 units/day
Remaining 50,000,000 units/day 100% of total
Per-user limit 3,000 requests/second/user
The current quota displayed to you in the Google Developer console is a estimate it is not 100% accurate. If you are getting the error dailyLimitExceeded it means that you have reached your limit for the day and will have to wait until midnight PT time to run again. This is something you can test by running the request again and seeing that suddenly you have access again.
You need to either extend your quota or reduce the number of requests you make.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/30565612",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Exception in thread "main" cucumber.runtime.CucumberException I am getting Exception in thread:
Exception in thread "main" cucumber.runtime.CucumberException: No back ends were found. Please make sure you have a backend module on your CLASS PATH.
I am new for Cucumber BDD framework ,running following feature file.
Feature: feature to test login scenario
Scenario: Check login is successful with valid credentials
Given User is on login page
When User enters login and password
And Clicks on login button
Then User navigated to home page
I have added following dependencies, tried with different adding version, but still not working.
Kindly provide your help.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73089345",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: how to find draggable product related values name, price I have tried drag and drop using jquery UI , i have updated this into fiddle
JSFIDDLE:
http://jsfiddle.net/GPBUn/
JQUERY CODE:
//draggable start
$(function () {
// jQuery UI Draggable
$(".products-grid .item a img").draggable({
// brings the item back to its place when dragging is over
revert:true,
// once the dragging starts, we decrease the opactiy of other items
// Appending a class as we do that with CSS
drag:function () {
$(this).addClass("active");
$(this).closest(".products-grid .item a img").addClass("active");
// $('.hover').css("display","none");
},
// removing the CSS classes once dragging is over.
stop:function () {
$(this).removeClass("active").closest(".products-grid .item a img").removeClass("active");
}
});
// jQuery Ui Droppable
$(".basket").droppable({
// The class that will be appended to the to-be-dropped-element (basket)
activeClass:"active",
// The class that will be appended once we are hovering the to-be-dropped-element (basket)
hoverClass:"hover",
// The acceptance of the item once it touches the to-be-dropped-element basket
// For different values http://api.jqueryui.com/droppable/#option-tolerance
tolerance:"touch",
drop:function (event, ui) {
var basket = $(this),
move = ui.draggable,
itemId = basket.find("ul li[data-id='" + move.attr("data-id") + "']");
var param = $(ui.draggable).attr('id');
// To increase the value by +1 if the same item is already in the basket
if (itemId.html() != null) {
itemId.find("input").val(parseInt(itemId.find("input").val()) + 1);
var price=move.find(".itemprices").html();
}
else {
// Add the dragged item to the basket
//alert(p);
addBasket(basket, move);
// Updating the quantity by +1" rather than adding it to the basket
move.find("input").val(parseInt(move.find("input").val()) + 1);
}
}
});
// This function runs onc ean item is added to the basket
//+ '<span class="sno">1</span>'
function addBasket(basket, move) {
var val=move.find(".product-name").html();
//alert(val);
basket.find("ul").append('<li data-id="' + move.attr("data-id") + '">'
+ '<span class="name">' + move.find(".product-name").html() + '</span>'
+ '<span class="price">' + move.find(".itemprices").html() + '</span>'
+ '<input class="count" value="1" type="text" id="count">'
+ '<button class="total">'+ (move.find(".itemprices").html())*($(".count").val())+'</button>'
+ '<button class="delete">✕</button>');
}
$("#count").on('change', function(){
var v=$("#count").val();
// alert(v);
});
// The function that is triggered once delete button is pressed
$(".basket ul li button.delete").live("click", function () {
$(this).closest("li").remove();
});
});
//draggable ends
here drag and drop functionality is working fine , but how do i get the product title and price ,any help ?
A: For price =>
$(".itemprices").text();
For title =>
$(".product-name").prop('title');
//NEW CODE
See if you have multiple products ,Assign separate ID to every Product DIV (you already have class assigned to it).Then use # instead of '.' (DOT) . So use
var idStored=$(this).attr('id');
idStored.text();
idStored.text().prop('title');
And then Call these Manipulation on Hover of the div ,Or onClick
A: Try the following:
In your addBasket(basket, move) function add the following line:
var currentLIelement = $(move).parents('li');
So, currentLIelement will be your parent <li> element of dragged element.
Now, to get the title you need to call this:
$(currentLIelement).find('.product-name').prop('title')
And to get the price you need to call this:
$(currentLIelement).find('.itemprices').text()
NOTE: In your code I found live() method - As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/22147269",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to validate AzureAD accessToken in the backend API I just wanted to know how can we validate the azure ad access token in a backend API in my case i.e. Django rest framework.
Consider that I have a single page app or a native app and a backend API (django rest framework) completely independen of each other. In my case if my single page app/native app wants to access certain data from the backend API, and inorder to access the API, user should be logged in the backend API.
So what my approch is to make use of MSAL library to get the access token from the SPA/native app and then once token is acquired, pass that token to backend API, validate it, get the user info from graph api. If user exists in the DB then login the user and pass the required info. If user info doesn't exist then create the user, login and pass the info from the API.
So my question is when I pass the access token to my backend api, how can I validate that the token that a user/SPA/native app has passed to backend API is valid token or not?
Is it just we need to make an API call to graph API endpoint with accessToken that user/SPA/native passed and if it is able to get the user data with the accessToken then then token is valid or if it fails then the accessToken is invalid.
Is it the general way to validate the token or some better approach is there? Please help
A: Good day sir, I wanna share some of my ideas here and I know it's not a solution but it's too long for a comment.
I created a SPA before which used msal.js to make users sign in and generate access token to call graph api, you must know here that when you generate the access token you need to set the scope of the target api, for example, you wanna call 'graph.microsoft.com/v1.0/me', you need a token with the scope 'User.Read, User.ReadWrite' and you also need to add delegated api permission to the azure app.
So as the custom api of your own backend program. I created a springboot api which will return 'hello world' if I call 'localhost:8080/hello', if I wanna my api protected by azure ad, I need to add a filter to validate all the request if has a valid access token. So I need to find a jwt library to decode the token in request head and check if it has a token, if the token has expired and whether the token has the correct scope. So here, which scope is the correct scope? It's decided by the api you exposed in azure ad. You can set the scope named like 'AA_Custom_Impression', and then you can add this delegate api permission to the client azure ad app, then you that app to generate an access token with the scope of 'AA_Custom_Impression'. After appending the Bearer token in calling request, it will be filtered by backend code.
I don't know about python, so I can just recommend you this sample, you may try it, it's provided by microsoft.
A: I've solved the similar issue. I don't found how to directly validate access token, but you can just call graph API on backend with token you've got on client side with MSAL.
Node.js example:
class Microsoft {
get baseUrl() {
return 'https://graph.microsoft.com/v1.0'
}
async getUserProfile(accessToken) {
const response = await got(`${this.baseUrl}/me`, {
headers: {
'x-li-format': 'json',
Authorization: `Bearer ${accessToken}`,
},
json: true,
})
return response.body
}
// `acessToken` - passed from client
async authorize(accessToken) {
try {
const userProfile = await this.getUserProfile(accessToken)
const email = userProfile.userPrincipalName
// Note: not every MS account has email, so additional validation may be required
const user = await db.users.findOne({ email })
if (user) {
// login logic
} else {
// create user logic
}
} catch (error) {
// If request to graph API fails we know that token wrong or not enough permissions. `error` object may be additionally parsed to get relevant error message. See https://learn.microsoft.com/en-us/graph/errors
throw new Error('401 (Unauthorized)')
}
}
}
A: Yes we can validate the Azure AD Bearer token.
You can fellow up below link,
https://github.com/odwyersoftware/azure-ad-verify-token
https://pypi.org/project/azure-ad-verify-token/
We can use this for both Django and flask.
You can directly install using pip
but I'm not sure in Django. If Django install working failed then try to copy paste the code from GitHub
Validation steps this library makes:
1. Accepts an Azure AD B2C JWT.
Bearer token
2. Extracts `kid` from unverified headers.
kid from **Bearer token**
3. Finds `kid` within Azure JWKS.
KID from list of kid from this link `https://login.microsoftonline.com/{tenantid}/discovery/v2.0/keys`
4. Obtains RSA key from JWK.
5. Calls `jwt.decode` with necessary parameters, which inturn validates:
- Signature
- Expiration
- Audience
- Issuer
- Key
- Algorithm
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/66720526",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: Unity shadows ignoring shader's transparency but only in build I've made a custom shader that adds a pass to the surface shader to achieve an outline around the object. The object is a quad with the characters sprite on it to achieve a 2d character in a 3d game. The object should be casting a shadow in the same shape as its sprite.
In the editor's play mode the shadows work perfectly:
However when I build the game in either windows or android platform the shadows completely ignore the object's transparency and only show the shadow of the quad.
I'm not sure if the problem is caused by my shader or something in the settings. I've reset the quality settings to the default values and still have the problem even when it is set to ultra quality. The only light in the scene is a directional light with soft shadows turned on.
This is the code in my shader.
Shader "Custom/MultiPassOutlineShader" {
Properties {
_Color ("Color", Color) = (1,1,1,1)
_MainTex ("Albedo (RGB)", 2D) = "white" {}
_Glossiness ("Smoothness", Range(0,1)) = 0.5
_Metallic ("Metallic", Range(0,1)) = 0.0
_OutlineColor ("Outline Color",Color) = (1,1,1,1)
_OutlineThickness ("Outline Thickness",float) = 0.05
}
SubShader {
Tags {"RenderType"="Transparent" "Queue"="Transparent" "IgnoreProjector"="True"}
LOD 100
Pass
{
ZWrite Off
Blend SrcAlpha OneMinusSrcAlpha
CGPROGRAM
#pragma vertex vert
#pragma fragment frag alpha
// make fog work
#pragma multi_compile_fog
#include "UnityCG.cginc"
struct appdata
{
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
};
struct v2f
{
float2 uv : TEXCOORD0;
UNITY_FOG_COORDS(1)
float4 vertex : SV_POSITION;
};
sampler2D _MainTex;
float4 _MainTex_ST;
float _OutlineThickness;
fixed4 _OutlineColor;
v2f vert (appdata v)
{
v2f o;
v.vertex = normalize(v.vertex) * _OutlineThickness + v.vertex;
o.vertex = UnityObjectToClipPos(v.vertex);
o.uv = TRANSFORM_TEX(v.uv, _MainTex);
UNITY_TRANSFER_FOG(o,o.vertex);
return o;
}
fixed4 frag (v2f i) : SV_Target
{
UNITY_APPLY_FOG(i.fogCoord, col);
fixed4 c = tex2D (_MainTex, i.uv);
fixed4 col = _OutlineColor;
col.a *= c.a;
clip(c.a-0.1);
return col;
}
ENDCG
}
ZWrite On
Blend Off
CGPROGRAM
#pragma surface surf Standard fullforwardshadows alpha
#pragma target 3.0
sampler2D _MainTex;
struct Input {
float2 uv_MainTex;
};
half _Glossiness;
half _Metallic;
fixed4 _Color;
// Add instancing support for this shader. You need to check 'Enable Instancing' on materials that use the shader.
// See https://docs.unity3d.com/Manual/GPUInstancing.html for more information about instancing.
#pragma instancing_options assumeuniformscaling
UNITY_INSTANCING_CBUFFER_START(Props)
// put more per-instance properties here
UNITY_INSTANCING_CBUFFER_END
void surf (Input IN, inout SurfaceOutputStandard o) {
fixed4 c = tex2D (_MainTex, IN.uv_MainTex) * _Color;
clip(c.a - 0.9);
o.Albedo = c.rgb;
o.Metallic = _Metallic;
o.Smoothness = _Glossiness;
o.Alpha = c.a;
}
ENDCG
}
FallBack "Standard"
}
A: I fixed the problem by adding a shadow casting pass. (for some reason unity has no documentation on these.) I also changed the fallback to "VertexLit" but I don't know if that had any effect. I still don't know why the shadow shapes were different in the editor than in the build though.
//From https://answers.unity.com/questions/1003169/shadow-caster-shader.html
Pass{
Name "ShadowCaster"
Tags { "LightMode" = "ShadowCaster" }
Fog {Mode Off}
ZWrite On ZTest Less Cull Off
Offset 1, 1
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#pragma fragmentoption ARB_precision_hint_fastest
#pragma multi_compile_shadowcaster
#include "UnityCG.cginc"
sampler2D _MainTex;
struct v2f
{
V2F_SHADOW_CASTER;
float2 uv : TEXCOORD1;
};
v2f vert(appdata_full v )
{
v2f o;
o.uv = v.texcoord;
TRANSFER_SHADOW_CASTER(o)
return o;
}
float4 frag( v2f i ) : COLOR
{
fixed4 c = tex2D (_MainTex, i.uv);
clip(c.a - 0.9);
SHADOW_CASTER_FRAGMENT(i)
}
ENDCG
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/52751343",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: What is the difference between doc_values and fielddata.doc_values mapping settings? Question is about Elasticsearch 1.x
The documentation says that setting "doc_values": true should suffice to use disk-based fielddata. Like this:
"string_field": {
"doc_values": true,
"type": "string",
"index": "not_analyzed"
}
However, there is also a possibility to set doc_values as a fielddata format:
"string_field": {
"type": "string",
"index": "not_analyzed",
"fielddata": {
"format": "doc_values"
}
}
So my questions are:
Are these two approaches essentially the same thing?
If not, what is the difference and should they be used together at the same time (I checked, they can, but I don't know if there is any actual benefit from that)?
A: "fields don't need to be indexed to enable doc values" means you can have "index": "no", for example:
"my_field": {
"type": "string",
"index": "no",
"fielddata": {
"format": "doc_values"
}
}
If you want to change format to doc_values, you need to update mapping and reindex your data.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/39253770",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Using Different elements for Laptop and Mobile? Framework: Meteor
I am using Handlebars to send information to the client.
I have this layout defined named post.html:
<div class="card">
<div class="card-image waves-effect waves-block waves-light">
<img class="activator" src="{{image}}">
</div>
<div class="card-content">
<span class="card-title activator grey-text text-darken-4"><a href="/{{slug}}">{{title}}</a><i class="mdi-navigation-more-vert right"></i></span>
<div class="card-reveal">
<span class="card-title grey-text text-darken-4">{{title}}<i class="mdi-navigation-close right"></i></span>
<p class="tobeappeded">{{body}}</p>
</div>
</div>
Notice the Card layout.
Now this is responsive and works and I dont have a problem that How to make it responsive? It works.
I want to completely change this layout, and use other elements in the layout.
I know this can be done using JS by manipulating the DOM, and appending HTML, but can that be attained without JS?
Like maybe, the JS is only used to find the screen size, or something, and if it is, it renders layout number 1, otherwise, it renders layout number 2.
[ Think of it as Media Queries, but for HTML/JS]
You could also think about how Fragments work in Android.
A: You can do this using window.matchMedia(), which is basically media queries in javascript. And if it matches your condition load your templates accordingly.
https://developer.mozilla.org/en-US/docs/Web/API/Window/matchMedia
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/31030654",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.