Can't reference my Entity Model for Sql-to-Linq query Posted: 15 Apr 2021 08:58 AM PDT I've made an entity model in a folder called "Entity" that contains my only entitymodel. project.Entity.ListModel.edmx Within my main program.cs, I'm trying to call upon it to navigate some of the tables: var query = ListModel.TableName.Where(x => x.name.. But it keeps saying ListModel does not exist in current context. I've even tried the full path like: project.Entity.ListModel.TableName.Where..... But no luck. This seems like a simple fix, though I'm not well aquainted with Entity Frameworks or Linq for that matter. Any guidence would be welcome. Thanks |
python scale irregular multidimensional dataframe Posted: 15 Apr 2021 08:58 AM PDT I have a dataframe like the one in the example below: import pandas as pd data = {'a1': [40, 0, 40, 100, 80], 'a2': [[0, 2], [4, 5], [10, 2], [3, 8], [0, 0]], 'a3': [[10, 2], [10, 0, 4], [1, 0, 1, 1], [-10, 6], [0, 2]], 'a4': [-1, -0.08, 0.4, 1, 0.2], } df = pd.DataFrame(data) print(df) a1 a2 a3 a4 0 40 [0, 2] [10, 2] -1.00 1 0 [4, 5] [10, 0, 4] -0.08 2 40 [10, 2] [1, 0, 1, 1] 0.40 3 100 [3, 8] [-10, 6] 1.00 4 80 [0, 0] [0, 2] 0.20 and I would like to scale it to [0, 1] and also save the scalers, so that I can apply them on another dataset. With dataframes without nested lists, I've been using MinMaxScaler this way: from sklearn.preprocessing import MinMaxScaler df1 = df[['a1', 'a4']] scaler = MinMaxScaler() scaler.fit(df1) scaled_df = scaler.transform(df1) dump(scaler, open('scaler.pkl', 'wb')) scaler = load(open('scaler.pkl', 'rb')) scaled_df2 = scaler.transform(df2) but this is not working on the whole original df with nested lists. I can think about some "hacky" approaches such as for each column, concatenate its rows in one array, calculate the scalar, store it in an array of scalars and apply it to the second dataframe, but I was wondering if there is a better, cleaner approach to do this. Any ideas? |
How to stop horizontal stretching of a Image using Xamarin Posted: 15 Apr 2021 08:58 AM PDT I have a horizontal <ScrollView/> . When I put <Image/> in every <StackLayout/> . When you press the load button, each frame is stretched. If you press the button 5 times, the frame stretches 5 times. <ScrollView BackgroundColor="Transparent" Orientation="Horizontal" HorizontalOptions="FillAndExpand"> <StackLayout HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand"> <Grid BackgroundColor="Transparent"> <Grid.RowDefinitions> <RowDefinition Height="*" /> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="*" /> <ColumnDefinition Width="*" /> <ColumnDefinition Width="*" /> <ColumnDefinition Width="*" /> <ColumnDefinition Width="*" /> </Grid.ColumnDefinitions> <Frame Grid.Column="0" BorderColor="White" Margin="10,0,5,0" CornerRadius="10" BackgroundColor="Transparent"> <RelativeLayout> <Image x:Name="ImageDescriptionForecastTest" Aspect="AspectFill" RelativeLayout.HeightConstraint="{ConstraintExpression Type=RelativeToParent, Property=Height, Factor=1}" RelativeLayout.WidthConstraint="{ConstraintExpression Type=RelativeToParent, Property=Width, Factor=1}"/> <StackLayout> ..... ..... </StackLayout> </RelativeLayout> </Frame> When I remove this line of the code: <Image x:Name="ImageDescriptionForecastTest" Aspect="AspectFill" RelativeLayout.HeightConstraint="{ConstraintExpression Type=RelativeToParent, Property=Height, Factor=1}" RelativeLayout.WidthConstraint="{ConstraintExpression Type=RelativeToParent, Property=Width, Factor=1}"/> When I press the button, nothing stretches and everything works normally. In the very logic of the button I check weather condition and change the backgrounds: if (descriptionForecast1 == "clear sky") { ImageDescriptionForecastTest.Source = "Images/ClearSky.jpg"; } else if (descriptionForecast1 == "few clouds") { ImageDescriptionForecastTest.Source = "Images/FewClouds.jpg"; } else if (descriptionForecast1 == "scattered clouds") { ImageDescriptionForecastTest.Source = "Images/Scattering.jpg"; } else if (descriptionForecast1 == "broken clouds") { ImageDescriptionForecastTest.Source = "Images/BrokenClouds.jpg"; } else if (descriptionForecast1 == "light rain") { ImageDescriptionForecastTest.Source = "Images/LightRain.jpg"; } else if (descriptionForecast1 == "rain") { ImageDescriptionForecastTest.Source = "Images/Rain.jpg"; } else if (descriptionForecast1 == "thunderstorm") { ImageDescriptionForecastTest.Source = "Images/Thunderstorm.jpg"; } else if (descriptionForecast1 == "snow") { ImageDescriptionForecastTest.Source = "Images/Snow.jpg"; } else if (descriptionForecast1 == "mist") { ImageDescriptionForecastTest.Source = "Images/Mist.jpg"; } else if (descriptionForecast1 == "overcast clouds") { ImageDescriptionForecastTest.Source = "Images/OverCastClouds.jpg"; } else if (descriptionForecast1 == "moderate rain") { ImageDescriptionForecastTest.Source = "Images/ModerateRain.jpg"; } What should I change in this code so that the frames are not stretched ? <Image x:Name="ImageDescriptionForecastTest" Aspect="AspectFill" RelativeLayout.HeightConstraint="{ConstraintExpression Type=RelativeToParent, Property=Height, Factor=1}" RelativeLayout.WidthConstraint="{ConstraintExpression Type=RelativeToParent, Property=Width, Factor=1}"/> I will attach a screenshot from simulator: |
(Tensorflow) TypeError: create_estimator_and_inputs() missing 1 required positional argument: 'hparams' Posted: 15 Apr 2021 08:58 AM PDT I try to train a model object detection and I follow this tutorial: https://tensorflow-object-detection-api-tutorial.readthedocs.io/en/tensorflow-1.14/training.html But at the end I execute the command in the cmd : python model_main.py --alsologtostderr --model_dir=training/ --pipeline_config_path=training/ssd_inception_v2_coco.config and it return the following lines: Traceback (most recent call last): File "model_main.py", line 108, in <module> tf.app.run() File "D:\anaconda\envs\py36\lib\site-packages\tensorflow\python\platform\app.py", line 40, in run _run(main=main, argv=argv, flags_parser=_parse_flags_tolerate_undef) File "D:\anaconda\envs\py36\lib\site-packages\absl\app.py", line 303, in run _run_main(main, args) File "D:\anaconda\envs\py36\lib\site-packages\absl\app.py", line 251, in _run_main sys.exit(main(argv)) File "model_main.py", line 70, in main FLAGS.sample_1_of_n_eval_on_train_examples)) TypeError: create_estimator_and_inputs() missing 1 required positional argument: 'hparams' Did someone had this issue and know how to resolve it ? |
Github creating a DB file discord.py Posted: 15 Apr 2021 08:57 AM PDT I have this code for a XP system for my discord.py bot: import discord from discord.ext import commands import asyncio intents = discord.Intents.all() intents.members = True from discord.ext import tasks import math import aiosqlite bot = commands.Bot(command_prefix=['!', 'pg!', '-'], intents=intents) @bot.event async def on_ready(): activity = discord.Game(name="DM's being sent", type=3) await bot.change_presence( activity=discord.Activity( type=discord.ActivityType.watching, name="Pokemon Go Discord Server!")) print("Ready.") member = await bot.fetch_user(MY_USER_ID) await member.send("The bot is online") bot.multiplier = 1 async def initialize(): await bot.wait_until_ready() bot.db = await aiosqlite.connect("expData.db") await bot.db.execute("CREATE TABLE IF NOT EXISTS guildData (guild_id int, user_id int, exp int, PRIMARY KEY (guild_id, user_id))") @bot.event async def on_message(message): if not message.author.bot: cursor = await bot.db.execute("INSERT OR IGNORE INTO guildData (guild_id, user_id, exp) VALUES (?,?,?)", (message.guild.id, message.author.id, 1)) if cursor.rowcount == 0: await bot.db.execute("UPDATE guildData SET exp = exp + 1 WHERE guild_id = ? AND user_id = ?", (message.guild.id, message.author.id)) cur = await bot.db.execute("SELECT exp FROM guildData WHERE guild_id = ? AND user_id = ?", (message.guild.id, message.author.id)) data = await cur.fetchone() exp = data[0] lvl = math.sqrt(exp) / bot.multiplier if lvl.is_integer(): rankup = bot.get_channel(CHANNEL_ID) await rankup.send(f"{message.author.mention} well done! You're now level: {int(lvl)}.") await bot.db.commit() await bot.process_commands(message) @bot.command() async def stats(ctx, member: discord.Member=None): if member is None: member = ctx.author # get user exp async with bot.db.execute("SELECT exp FROM guildData WHERE guild_id = ? AND user_id = ?", (ctx.guild.id, member.id)) as cursor: data = await cursor.fetchone() exp = data[0] # calculate rank async with bot.db.execute("SELECT exp FROM guildData WHERE guild_id = ?", (ctx.guild.id,)) as cursor: rank = 1 async for value in cursor: if exp < value[0]: rank += 1 lvl = int(math.sqrt(exp)//bot.multiplier) current_lvl_exp = (bot.multiplier*(lvl))**2 next_lvl_exp = (bot.multiplier*((lvl+1)))**2 lvl_percentage = ((exp-current_lvl_exp) / (next_lvl_exp-current_lvl_exp)) * 100 embed = discord.Embed(title=f"Stats for {member.name}", colour=discord.Colour.gold()) embed.add_field(name="Level", value=str(lvl)) embed.add_field(name="Exp", value=f"{exp}/{next_lvl_exp}") embed.add_field(name="Rank", value=f"{rank}/{ctx.guild.member_count}") embed.add_field(name="Level Progress", value=f"{round(lvl_percentage, 2)}%") await ctx.send(embed=embed) @bot.command() async def leaderboard(ctx): buttons = {} for i in range(1, 6): buttons[f"{i}\N{COMBINING ENCLOSING KEYCAP}"] = i # only show first 5 pages previous_page = 0 current = 1 index = 1 entries_per_page = 10 embed = discord.Embed(title=f"Leaderboard Page {current}", description="", colour=discord.Colour.gold()) msg = await ctx.send(embed=embed) for button in buttons: await msg.add_reaction(button) while True: if current != previous_page: embed.title = f"Leaderboard Page {current}" embed.description = "" async with bot.db.execute(f"SELECT user_id, exp FROM guildData WHERE guild_id = ? ORDER BY exp DESC LIMIT ? OFFSET ? ", (ctx.guild.id, entries_per_page, entries_per_page*(current-1),)) as cursor: index = entries_per_page*(current-1) async for entry in cursor: index += 1 member_id, exp = entry member = ctx.guild.get_member(member_id) embed.description += f"{index}) {member.mention} : {exp}\n" await msg.edit(embed=embed) try: reaction, user = await bot.wait_for("reaction_add", check=lambda reaction, user: user == ctx.author and reaction.emoji in buttons, timeout=60.0) except asyncio.TimeoutError: return await msg.clear_reactions() else: previous_page = current await msg.remove_reaction(reaction.emoji, ctx.author) current = buttons[reaction.emoji] bot.loop.create_task(initialize()) bot.run("BOT_TOKEN") asyncio.run(bot.db.close()) When I run it locally, it works fine, as it creates a DB file on the first run, which then allows it to obtain your current xp and level, even if I stop the bot for a while. However, I host my bots by uploading the files to GitHub, and then using Heroku. When I run it like that, no file is created in my github repository, and when the bot gets turned off and on again, the levels reset, as it hasn't got any database. How can I make it so it backs up to a Database file when using GitHub and Heroku, like it does when I host it locally? Thanks! |
Cannot get torch.jit.script to work correctly with pytorch RNN Posted: 15 Apr 2021 08:57 AM PDT Ok, I need to script pytorch LSTM as when I do tracing it gets different answers with different inputs. But when I do: script_module=torch.jit.script(torch.nn.modules.rnn.LSTM(768, 256, num_layers=2, batch_first=True, bidirectional=True)) the resulting script_module prints as: RecursiveScriptModule(original_name=LSTM), but unlike other recursivescriptmodules (for example, as produced here: https://pytorch.org/tutorials/beginner/Intro_to_TorchScript_tutorial.html, and successfully replicated by me) it has no .code or .graph attribute, and it cannot be called. So what am I doing wrong? It obviously "thinks" it has produced a correct script. |
get parent or previous element based on child or sibling class Posted: 15 Apr 2021 08:57 AM PDT Imagine I have three different types of product HTML and I want to select the product-block element for only those that have a child or sibling with an input element that has a class mySelector . - Type A has the element with 'mySelector' within.
- Type B doesn't have an element 'mySelector' within or below it, so we don't want to select it.
- Type C has the element 'mySelector' right after it.
Product block type A <div class="A B C"> <a href="#"></a> <input type="hidden" class="mySelector"> </div> Product block type B <div class="MM NN OO"> <a href="#"></a> </div> Product block type C <div class="X Y Z"> <a href="#"></a> </div> <input type="hidden" class="mySelector"> The goal is to select product block types A and C, which have no child or sibling with mySelector . I imagine a filter could work, but I only can select one type of product-block with a filter like this: jQuery('.mySelector') .filter(function () { if (jQuery(this).prev().hasClass('wc-block-grid__products')) { return jQuery(this).prev(); } }) Another approach is using jQuery('.mySelector').parent() . But then I would not be able to select type C where mySelector is a sibling. |
In python with selenium, how do you rotate IP addresses? Posted: 15 Apr 2021 08:57 AM PDT I am trying to scrape information off of a website (on Chrome) where I need to click on each subpage to get the information I need. After about 7, I get blocked by the website. I think if I was able to switch IPs either each time or once I get blocked, that would work. I am using Selenium to open the site and navigate to the subpages. I have tried using a try-catch block so far and a while loop but I am getting errors I do not know how to address. Does anyone have an alternative approach or previous success doing this? |
Add ArrayList to another ArrayList dynamically is treading values Posted: 15 Apr 2021 08:57 AM PDT { "clientes":[ { "codigo":"1341", "empresa":0, "nombre":"asd", "e_mail":"cli@cli.com" }, { "codigo":"5435", "empresa":0, "nombre":"asd", "e_mail":"cli@cli.com" } ] } I am trying to extract the keys and values from a json then in an array I put all the keys and in another array all the values. The problem now is that more than 1 client can come, so I have to make a list of arrays of keys, and a list of arrays of values As you can see, in the output the values of position [0] are stepped on with that of position [1] and it shouldn't be like that, because in the "codigo" field I send different values .. ArrayList listArrayKeys = new ArrayList(); ArrayList listArrayValues = new ArrayList(); ArrayList<String> arrayKeys = new ArrayList<>(); ArrayList<String> arrayValues = new ArrayList<>(); DatabaseHelper databaseHelper = new DatabaseHelper(this); JSONObject jsonObject; String tableName; void getKeysAndValues() throws JSONException { try { Iterator<String> keys = jsonObject.keys(); while(keys.hasNext()) { String key = keys.next(); System.out.println(key); if(jsonObject.get(key) instanceof JSONArray) { JSONArray array = (JSONArray) jsonObject.get(key); for(int i = 0; i < array.length(); i++){ JSONObject object = (JSONObject) array.get(i); Iterator<String> innerKeys = object.keys(); arrayValues.clear(); while(innerKeys.hasNext()) { String innerKey = innerKeys.next(); String innerValue = object.getString(innerKey); arrayKeys.add(innerKey); arrayValues.add(innerValue); System.out.println(innerKey); } listArrayKeys.add(arrayKeys); listArrayValues.add(arrayValues); } Log.d("ARRAYVALUES", String.valueOf(listArrayValues)); } } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } output: [[5435, 0, asd, cli@cli.com], [5435, 0, asd, cli@cli.com] should be: [[1341, 0, asd, cli@cli.com], [5435, 0, asd, cli@cli.com] |
How to load files based on condition, and then iteratively add them to a Spark dataframe? Posted: 15 Apr 2021 08:57 AM PDT I am conditionally loading in files and was wondering what is the best way to do the following: - If the file exists, read it in.
- Iteratively do this such that each existing file gets added to a Spark dataframe.
- Result will be one large Spark dataframe containing all existing files from the list of paths provide.
This is what I have but it does not work correctly. for path in list_of_paths: if s3.exists(path): sdf = spark.read.format("com.databricks.spark.avro").load(path) final_sdf = sdf.union(sdf) |
How to validate UK postcode using jQuery? [duplicate] Posted: 15 Apr 2021 08:57 AM PDT I want to validate the UK postcode. The validation I required is, 5/6 characters, no space, at least 2 numbers, and 3 letters, with no special characters. Currently I am using this regex /[A-Z]{1,2}[0-9]{1,2}[]{0,1}[0-9][A-Z]{2}/i . This is allows only 6 character and above 6 character. I want only 5/6 character without space and special character. Does any solution please? |
Swift: variable not updated? Posted: 15 Apr 2021 08:58 AM PDT My SwiftUI app has a class which parses JSON Data. As you can see from the comments near the print, I do not understand while the line print("return: " + self.productName) print the variable still empty (basically the initialized one). Why is the variable updated inside the "if" but not outside? Any idea? Thanks class ProductDecoer: ObservableObject { @Published var productName: String = "" func checkBarCode(barcode: String) -> String { let api = <url> let barcode = barcode let format = ".json" let url = URL(string: api + barcode + format) URLSession.shared.dataTask(with: url!) { [self] data, response, error in if let data = data { if let jsonString = String(data: data, encoding: .utf8) { productName = self.getProductInfo(json: jsonString) print("checkBarCode: " + self.productName) // --> print correctly } } }.resume() self.productName = productName print("return: " + self.productName) // --> is empty return self.productName } func getProductInfo(json: String) -> String { let jsonData = json.data(using: .utf8)! let productInfo: ProductInfo = try! JSONDecoder().decode(ProductInfo.self, from: jsonData) self.productName = productInfo.product_name print("AAA: " + self.productName) print("Prodotto: " + productInfo.product_name) productName = productInfo.product_name print("CC: " + productName) return productName } struct ProductInfo: Codable { var code: String var product_name: String enum CodingKeys: String, CodingKey { case code case product enum ProductCodingKeys: String, CodingKey { case product_name } } init(from decoder: Decoder) throws { let rootContainer = try decoder.container(keyedBy: CodingKeys.self) let productContainer = try rootContainer.nestedContainer(keyedBy: CodingKeys.ProductCodingKeys.self, forKey: .product) code = try rootContainer.decode(String.self, forKey: .code) product_name = try productContainer.decode(String.self, forKey: .product_name) print("BB: " + product_name) } func encode(to encoder: Encoder) throws { var rootContainer = encoder.container(keyedBy: CodingKeys.self) var productContainer = rootContainer.nestedContainer(keyedBy: CodingKeys.ProductCodingKeys.self, forKey: .product) try rootContainer.encode(code, forKey: .code) try productContainer.encode(product_name, forKey: .product_name) } } } |
Python, Pandas: check each element in list values of column to exist in other dataframe Posted: 15 Apr 2021 08:58 AM PDT I have dataframe column with values in lists, want to add new column with filtered values from list if they are in other dataframe. df: df = pd.DataFrame({'a':[1,2,5,7,9],'b':[[10,1,100],[],[1,2,3],[5],[25,27]]}) **a**|**b** :-----:|:-----: 1|[10, 1, 100] 2|[] 5|[1, 2, 3] 7|[5] 9|[25, 27] df2: df2 = pd.DataFrame({'d':[324,21,4353,345,4535],'e':[5,1,23,25,25]}) I need to add new column with filtered column b in df so that it contains lists with only elements which are in df2 column e . Result: **a**|**b**|**c** :-----:|:-----:|:-----: 1|[10, 1, 100]|[1] 2|[]|[] 5|[1, 2, 3]|[1] 7|[5]|[5] Speed is crucial, as there is a huge amount of records. What I did for now: - created a set of possible values
l = list(df2['e'].unique()) - Try to use
df.assign with comprehensive lists, but it's not quite working and too slow. df.assign(mapped=[[x for x in row if x in l] for row in df.b]) Appreciate any help. |
Passing files from a rocker container to a latex container within a gitlab-ci job Posted: 15 Apr 2021 08:57 AM PDT I would like to use Gitlab CI to compile a Latex article as explained in this answer on tex.stackexchange (a similar pdf generation example is show in the gitlab documentation for artifacts). My Latex article contains figures made with the R statistical language. R and Latex are two large installation with a lot of dependencies so I decided to use two separate containers for the build, one for R stuff and one for the Latex stuff. Here is the content of my .gitlab-ci.yml : knit_rnw_to_tex: image: rocker/verse:4.0.0 script: - Rscript -e "knitr::knit('article.Rnw')" artifacts: paths: - figure/ compile_pdf: image: aergus/latex script: - ls figure - latexmk -pdf -bibtex -use-make article.tex artifacts: paths: - article.pdf The knit_rnw_to_tex job executed in the R "rocker" container is successful and I can download the figure artifacts from the gitlab "jobs" page. The issue in the second job compile_pdf is that ls figure shows me an empty folder and the Latex article compilation fails because of missing figures. How can I pass the artifacts from one job to the other? Should I use cache as explained in docs.gitlab.com / caching? |
Share variables between different projects in Azure DevOps Posted: 15 Apr 2021 08:58 AM PDT I hope you are all well! I need to ask a question about azure devops, I already read the documentation, but I did not find a way to resolve these doubts I have the X, Y and Z projects and in the X project create in the Pipeline >> Libray a group of variables called general that I would like to be shared with the Y and Z pipelines, when configuring this group I enabled the option "Allow Access to all pipelines" . In the YAML of the Y and Z pipelines I made the following configuration: **variables: When running the pipeline he returns an authorization request and even clicking authorize it, according to the print below: Print Authorization error My question is, is there any way to share variables between pipelines of different purposes, if there is, can you please send me some documentation that can help me to configure this? |
How do you respond to a thread in Google Chat from an incoming webhook? Posted: 15 Apr 2021 08:58 AM PDT There's a thread that my webhook has previously created that it wants to reply to. Is this possible using a webhook? It seems to be possible with a bot, see this answer: https://stackoverflow.com/a/58657945/3832377 But I can't find any documentation on doing it from a webhook. As I've created the original message in the thread, I can guarentee a consistent threadId. I tried to send a body that looked like: { "cards": [/* a card */] "thread": { "name": "some_thread_name" } } But received a 500 error. |
The argument type 'Iterable<Future<SubwayStation>>' can't be assigned to the parameter type 'List<SubwayStation>' Posted: 15 Apr 2021 08:58 AM PDT class Stations extends ChangeNotifier { StationListState state = StationListState(loading: false, stations: []); Future<void> getMachedStations() async { state = state.copyWith(loading: true); notifyListeners(); List<Map<String, dynamic>> aroundStations = await FindNearStation().getLocation(); print(aroundStations.length); var subwaysRef = FirebaseFirestore.instance.collection('subways'); var stations = aroundStations.map((searchedElement) async { String subwayStationName = yuk(searchedElement['subwayStationName']); try { print(' ::::: ${searchedElement['line']}'); var lineRef = await subwaysRef .doc(searchedElement['line']) .collection(subwayStationName) .get(); return SubwayStation.fromDoc(lineRef.docs[0]); } catch (e) { state = state.copyWith(loading: false); } }); state = state.copyWith(loading: false, stations: stations); // <-- Error (stations : stations) } } I try to get the returned list I get the error: The argument type 'Iterable<Future>' can't be assigned to the parameter type 'List'. How can I solve it? |
big data and spring boot Posted: 15 Apr 2021 08:58 AM PDT I want to use spring-boot to build an application linked to big data. The data provides me with a file, with several available formats (RDF, Json-ld, ...). I started with Jena and the RDF format. So I want to be able to use the file provided for big data and be able to use spring-boot, but I'm not sure how to go about it. Basically I want to download the file (rdf, json-ld or other), have the spring-boot project load the file and I can manipulate the data. I wish to be able to make requests on this resource What do you advise me to use? thank you |
How can I round time to hours and minutes instead of hours, minutes and seconds? Posted: 15 Apr 2021 08:57 AM PDT My function returns the time like this 10:43:22 for example. How can I round the time to the closest minute so 10:43:22 becomes 10:43 and 10:43:44 becomes 10:44 . function time (){ let date = new Date() let time = date.toLocaleTimeString("it-IT"); } |
Chrome is Changing the Session Cookie when Calling cart/edit in Opencart 3.0.3.6 Posted: 15 Apr 2021 08:58 AM PDT I'm running Opencart 3.0.3.6 as an intranet supply ordering site on a 2019 server running iis 10 and php 7.3.13. I'm having one hiccup I cannot wrap my head around. The site works fine in every place except when users try to adjust item quantity in their carts. From what I can see, when opencart calls /cart/edit, sometimes chrome will change the session cookie value of OCSESSID, dropping that users session and logging them out. Sometimes the user can make 3-4 changes, sometimes the user needs to log back in a dozen times before they can make a successful change without being logged out. The site works fine with Firefox (staff use chromebooks, otherwise I'd just make them use firefox for the time being). EDIT: I've found samesite settings in Google Admin that allow me to use legacy cookie settings for specific sites. This practically solves my issue, but I would be interested to know the right way to set Opencart to use secure samesite settings that Chrome doesn't hate. I've found some solutions involving "samesite" settings, but nothing has quite worked out for me yet. I've tried applying someone's vqmod: <?xml version="1.0"?> -<modification> <id>Framework and catalog session samesite cookie</id> <vqmver>2.5.0</vqmver> <version>1.0</version> <author>J.J. van de Merwe</author> -<file error="log" name="system/framework.php"> -<operation> -<search position="replace"> -<![CDATA[ setcookie($config->get('session_name'), $session->getId(), ini_get('session.cookie_lifetime'), ini_get('session.cookie_path'), ini_get('session.cookie_domain')); ]]> </search> -<add action="after"> -<![CDATA[ // ### Modified code: your-filename.xml ### setcookie( $config->get('session_name'), $session->getId(), [ 'expires' => ini_get('session.cookie_lifetime'), 'path' => ini_get('session.cookie_path'), 'domain' => ini_get('session.cookie_domain'), 'secure' => true, 'httponly' => true, 'samesite' => 'None' ] ); // ### (End) Modified code ### ]]> </add> </operation> </file> -<file error="log" name="catalog/controller/startup/session.php"> -<operation> -<search position="replace"> -<![CDATA[ setcookie($this->config->get('session_name'), $this->session->getId(), ini_get('session.cookie_lifetime'), ini_get('session.cookie_path'), ini_get('session.cookie_domain')); ]]> </search> -<add action="after"> -<![CDATA[ // ### Modified code: your-filename.xml ### setcookie( $this->config->get('session_name'), $this->session->getId(), [ 'expires' => ini_get('session.cookie_lifetime'), 'path' => ini_get('session.cookie_path'), 'domain' => ini_get('session.cookie_domain'), 'secure' => true, 'httponly' => true, 'samesite' => 'None' ] ); // ### (End) Modified code ### ]]> </add> </operation> </file> </modification> for some reason this resolves my issue on my local test server, but accessing the server from a remote machine causes Chrome to continuously drop the cookie altogether. I'm just totally lost on why the problem is so intermittent, and I'm not sure where to go from here. |
How to get element from HTML (Angular) Posted: 15 Apr 2021 08:58 AM PDT I have a little problem, I want to create a form using Angular : here is my HTML : <form [formGroup]="requeteForm" (ngSubmit)="ajouter()" *ngIf=" tables!= null"> <div class="form-group" *ngFor="let col of colonne; let i=index"> <label for="{{col}}">{{col}}</label> <input type="text" class="form-control" id="{{col}}" formControlName="{{col}}"> </div> </form> As you can see the formControlName take a variable, the problem is how can I get the variable to init the formGroup ? For exemple : this.requeteForm = this.formBuilder.group( { {{col}}: ['', Validators.required], //It's just an exemple about what I want to do } ); Hope you can help me ^^ Thank you |
Microsoft Access Progress Bar Aggregation Posted: 15 Apr 2021 08:57 AM PDT I am after some advice relating to progress bars in ms access. I currently have a database which has a code to run a number of queries. There is a status bar which displays the progress of each query in the bottom right corner of the screen- Is there a way of feeding this info into a form? I want to display 2 progress bars in effect: 1st bar to display the status bar progress 2nd bar to display the overall progress of the code Can this be done? I did a bit of research and the closest thing that I can see is to customise the status bar itself: https://docs.microsoft.com/en-us/office/vba/access/concepts/miscellaneous/use-the-status-bar-progress-meter thanks |
Post using modRestController Class at MODX Posted: 15 Apr 2021 08:57 AM PDT I am developing a modx RESTful API. I would like to ask, if anyone knows how to post directly from browser to modRestController class and finally with this post I can save the information to the database. |
Is there a way to limit the number of features in IML package Shapley values? Posted: 15 Apr 2021 08:57 AM PDT I have an automl model created with the H2O package. Currently, H2O only calculates Shapley values on tree-based models. I've used the IML package to calculate the values on the AML model. However, because I have a large number of features, the plot is too jumbled to read. I'm looking for a way to select/show only the top X number of features. I can't find anything in the IML CRAN PDF nor in other documentation I've found by Googling. #initiate h2o h2o.init() h2o.no_progress() #create automl model (data cleaning and train/test split not shown) set.seed(1911) num_models <- 10 aml <- h2o.automl(y = label, x = features, training_frame = train.hex, nfolds = 5, balance_classes = TRUE, leaderboard_frame = test.hex, sort_metric = 'AUCPR', max_models = num_models, verbosity = 'info', exclude_algos = "DeepLearning", #exclude for reproducibility seed = 27) # 1. create a data frame with just the features features_eval <- as.data.frame(test) %>% dplyr::select(-target) # 2. Create a vector with the actual responses response <- as.numeric(as.vector(test$target)) # 3. Create custom predict function that returns the predicted values as a # vector (probability of purchasing in our example) pred <- function(model, newdata) { results <- as.data.frame(h2o.predict(model, as.h2o(newdata))) return(results[[3L]]) } # example of prediction output pred(aml, features_eval) %>% head() #create predictor needed predictor.aml <- Predictor$new( model = aml, data = features_eval, y = response, predict.fun = pred, class = "classification" ) high <- predict(aml, test.hex) %>% .[,3] %>% as.vector() %>% which.max() high_prob_ob <- features_eval[high, ] shapley <- Shapley$new(predictor.aml, x.interest = high_prob_ob, sample.size = 200) plot(shapley, sort = TRUE) Any suggestions/help appreciated. Thank you, Brian |
undefined is not an object (this.props.navigation.getParam) Posted: 15 Apr 2021 08:57 AM PDT FoodCreate.js export class FoodCreate extends Component { state = { food: null, foodList: [], }; submitFood = (food) => { this.setState({ foodList: [ ...this.state.foodList, { key: Math.random(), name: food, }, ], }); this.props.navigation.navigate("FoodList", { foodList: this.state.foodList, deleteFood: this.deleteFood, }); }; deleteFood = (key) => { this.setState({ foodList: [...this.state.foodList.filter((item) => item.key != key)], }); }; render() { return ( <Container> <Header> <Left> <Button transparent> <Icon name="arrow-back" onPress={() => this.props.navigation.goBack()} style={{ fontSize: 25, color: "red" }} /> </Button> </Left> <Body> <Title>Add Food</Title> </Body> <Right> <Button transparent> <Icon name="checkmark" style={{ fontSize: 25, color: "red" }} onPress={() => { this.submitFood(this.state.food); }} /> </Button> </Right> </Header> <View style={{ alignItems: "center", top: hp("3%") }}> <TextInput placeholder="Food Name" placeholderTextColor="white" style={styles.inptFood} value={this.state.food} onChangeText={(food) => this.setState({ food })} /> </View> </Container> ); } } export default FoodCreate; FoodList.js export class FoodList extends Component { constructor(props) { super(props); this.state = { foodList: [], }; } render() { return ( <Button onPress={() => this.props.navigation.navigate("FoodCreate")}> Press to insert food </Button> <FlatList data={this.props.navigation.getParam("foodList")} <------- keyExtractor={(item, index) => item.key.toString()} renderItem={(data) => <ListItem itemDivider title={data.item.name} />} /> ); } } export default FoodList; Hey everyone, I'm building a Diet App, the food gets created in FoodCreate.js by typing a food and pressing the checkmark Icon, and this will create the food and display it in the FoodList.js, keep it in mind that the first Screen to be displayed is FoodList.js. When I run the code I get the following error: undefined is not an object (this.props.navigation.getParam) |
Flutter null safety conditional widget Posted: 15 Apr 2021 08:57 AM PDT Before Flutter introduced the null-safety feature, I was able to conditionally add Widgets within a list like so: actions: <Widget>[ canCancel ? CupertinoDialogAction( child: Text(cancelActionText), onPressed: () { Navigator.pop(context); }, ) : null, ].where(notNull).toList() notNull being a homemade filter that filters off the null objects... Now with null-safety it's impossible because the list of Widgets strictly has to be non-null. What would be a better approach? |
Get last position known in foreground Android Posted: 15 Apr 2021 08:57 AM PDT After several (unsuccessful) attempts to make my applications compliant about the background access to the location, I decided to re-structure my code in order to remove the ACCESS_BACKGROUND_LOCATION permission from the manifest . My application necessarily needs to get the location of the device at certain times (specifically I need the coordinates), what I'm interested in knowing is: without using the permission mentioned above, how do I get the location of the device? is it possible to do it with a one-time call without using services etc? I thought about using this code, do you think it could be enough? LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); Location lastKnownLocation = locationManager.getLastKnownLocation(locationProvider); mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this); mFusedLocationClient.getLastLocation() .addOnSuccessListener(this, new OnSuccessListener<Location>() { @Override public void onSuccess(Location location) { if (location != null) { // Logic to handle location object } } }); or something like this: LocationManager mLocationManager = (LocationManager) context.getSystemService(LOCATION_SERVICE); List<String> providers = mLocationManager.getProviders(true); Location bestLocation = null; for (String provider : providers) { Location location = mLocationManager.getLastKnownLocation(provider); if (location == null) { continue; } if (bestLocation == null || location.getAccuracy() < bestLocation.getAccuracy()) { bestLocation = location; } } is there a better way to do this? |
Flutter firestore - Check if document ID already exists Posted: 15 Apr 2021 08:58 AM PDT I want to add data into the firestore database if the document ID doesn't already exists. What I've tried so far: // varuId == the ID that is set to the document when created var firestore = Firestore.instance; if (firestore.collection("posts").document().documentID == varuId) { return AlertDialog( content: Text("Object already exist"), actions: <Widget>[ FlatButton( child: Text("OK"), onPressed: () {} ) ], ); } else { Navigator.of(context).pop(); //Adds data to the function creating the document crudObj.addData({ 'Vara': this.vara, 'Utgångsdatum': this.bastFore, }, this.varuId).catchError((e) { print(e); }); } The goal is to check all the documents ID in the database and see in any matches with the "varuId" variable. If it matches, the document won't be created. If it doesn't match, It should create a new document |
Bean definition is overriden by AutoConfiguration Posted: 15 Apr 2021 08:57 AM PDT In my Spring application I have defined a bean of type AuditListener . @Component public class AuditListener { } My project also contains a dependency to spring-boot-starter-actuator which also defines a bean of type AuditListener via AuditAutoConfiguration . When I try to start my application it fails because my own AuditListener is not available. // successful beanFactory.getBean(org.springframework.boot.actuate.audit.listener.AuditListener.class); // fails with NoSuchBeanDefinitionException beanFactory.getBean(demo.AuditListener.class); Exception: java.lang.IllegalStateException: Failed to execute ApplicationRunner at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:791) at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:778) at org.springframework.boot.SpringApplication.run(SpringApplication.java:335) at org.springframework.boot.SpringApplication.run(SpringApplication.java:1255) at org.springframework.boot.SpringApplication.run(SpringApplication.java:1243) at demo.DemoApplication.main(DemoApplication.java:14) Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'demo.AuditListener' available at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:347) at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:334) at demo.DemoApplication.run(DemoApplication.java:27) at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:788) ... 11 more The DefaultListableBeanFactory logs INFO 10140 --- [ main] o.s.b.f.s.DefaultListableBeanFactory : Overriding bean definition for bean 'auditListener' with a different definition: replacing [Generic bean: class [demo.AuditListener]; scope=singleton; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in file [C:\workspace\spring-autoconfiguration-conflict-demo\target\classes\demo\AuditListener.class]] with [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.actuate.autoconfigure.audit.AuditAutoConfiguration; factoryMethodName=auditListener; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/actuate/autoconfigure/audit/AuditAutoConfiguration.class]] How can I get both AuditListener beans into my context without renaming my own? edit: If I define two beans with same class name in different packages I get a ConflictingBeanDefinitionException, so the ApplicationContext won't even start. |
Order a MySQL table by two columns Posted: 15 Apr 2021 08:58 AM PDT How do I sort a MySQL table by two columns? What I want are articles sorted by highest ratings first, then most recent date. As an example, this would be a sample output (left # is the rating, then the article title, then the article date) +================+=============================+==============+ | article_rating | article | article_time | +================+=============================+==============+ | 50 | This article rocks | Feb 4, 2009 | +----------------+-----------------------------+--------------+ | 35 | This article is pretty good | Feb 1, 2009 | +----------------+-----------------------------+--------------+ | 5 | This Article isn't so hot | Jan 25, 2009 | +================+=============================+==============+ The relevant SQL I'm using is: ORDER BY article_rating, article_time DESC I can sort by one or the other, but not both. |
No comments:
Post a Comment