text
stringlengths 15
59.8k
| meta
dict |
|---|---|
Q: How to export event in a DLL? I have the following two classes:
public class DLLClass {
public delegate void dllDelegate(Object sender, EventArgs e);
public event dllDelegate dllEvent;
.....
}
class AppClass {
DLLClass dll;
public AppClass() {
dll.dllEvent += new DLLClass.dllDelegate(dllEventHandler);
}
public void dllEventHandler(Object sender, EventArgs e){
}
}
Each one is a part of the same solution, but refer to different projects.
The problem is that the compiler says that there is no dllEvent member in the DLLClass.
EDIT:
The error:
error CS1061: 'AppNamespace.DLLClass ' does not contain a definition for 'dllEvent ' and no extension method 'dllEvent ' accepting a first argument of type 'AppNamespace.DLLClass ' could be found (are you missing a using directive or an assembly reference?)
error CS0426: The type name 'dllDelegate' does not exist in the type 'AppNamespace.DLLClass.ParametersPanel'
Also when I try to see the definition of the DLLClass from the code of AppClass, MSVS shows me class definition from metadata with no delegates in it.
A: If your reference is not a Project Reference, but a file reference, you may need to build the first project first. Form the Build menu, select Rebuild All.
If that doesn't help, you may have referenced to the wrong file. Remove the reference to the first project, and add a Project reference to it.
A: Found this one link.
The problem was in the .csproject file.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/15500205",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Python socket chat issue I have client and server sample codes. I can send message from client to server and I cant receive message from server to client. what is the issue ?
Server.py file
#server
import socket;
import time;
HOST = "localhost";
PORT = 5454;
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM);
s.bind((HOST,PORT));
while True:
print "Client says: " + s.recv(1024);
data = raw_input("Enter..... ") ;
s.sendto(data,(HOST, PORT));
if data=="bye" or s.recv(1024)=="bye":
print "Exiting..................";
time.sleep(1);
break;
Client.py file
#client
import socket;
import time;
HOST = "localhost";
PORT = 5454;
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM);
s.connect((HOST,PORT));
while True:
data = raw_input("Enter..... ")
s.sendto(data,(HOST,PORT)) ;
print "Server says: " + s.recv(1024);
if data=="bye" or s.recv(1024)=="bye":
print "Exiting...........";
time.sleep(1);
break;
What is the issue of above code....
First time i can send mesage from client to server. can not send message server to clint. have to wait more time.... but no responce. help me
A: You expect to receive twice as much data as you send.
print "Server says: " + s.recv(1024);
if data=="bye" or s.recv(1024)=="bye":
Calling receive each time will wait for data on the socket. Store the message received first, then manipulate that message.
msg = s.recv(1024)
print "Server says: " + msg
if data=="bye" or msg=="bye":
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/34263453",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Append an elements HTML into newly appended textarea I'm building a website designer and have gotten stuck at a little annoying problem. I made a small example of what I'm trying to accomplish here - http://codepen.io/mikethedj4/pen/KqyaH
The code below grabs the html in my canvas, puts it in a textarea when query is added, and I can see that html when I click on the already added media query.
$(".list-of-media-queries").append("<div class='list-of-media-queries-container'><a href='javascript:void(0)' class='del-media-query'><span class='fa fa-times'></span></a> <button>"+ $(".cwidth").val() +"px</button>"+ "<pre style='text-align:left; padding-top:5px; overflow:auto;'>"+ "@media all and (max-width:"+ $(".cwidth").val() +"px) { \n\n" + $(".dadammediaquery").val() +" }</pre>" +"</div><textarea class='"+ $(".cwidth").val() +"'>"+ $(".canves").html() +"</textarea>");
When a global style is added into div.list-of-css-selectors I append the following tags Textarea, DIV, Anchor, Button, and Pre.
Here's an example of what is appended
<textarea class="custom-css-sheet hide" style="cursor:text!important; width:100%; resize:vertical; border:0; border-radius:0; min-height:200px;" placeholder="Your Custom CSS is added here"></textarea><div class="list-of-css-selectors-container"><a href="javascript:void(0)" class="del-global-css-style"><span class="fa fa-times"></span></a> <button>body</button><pre style="text-align:left; padding-top:5px; overflow:auto;">body {
background-color: rgb(0, 224, 97);}</pre>
</div>
Now this is what I'm trying to backup aka the global/custom styles. I have all that stored in a div.list-of-css-selectors so I updated my code (2nd seen below) to where I wanted that backed up to. Now the code inside of div.list-of-css-selectors is suppose to go into the newly added textbox that has the class of the media queries location upon add. However the code is not encased in the textarea. Here's what I get instead.
<textarea class="custom-css-sheet hide" style="cursor:text!important; width:100%; resize:vertical; border:0; border-radius:0; min-height:200px;" placeholder="Your Custom CSS is added here">
I'm not sure why it's reacting this way. If anybody can help it'd be greatly appreciated.
$(".list-of-media-queries").append("<div class='list-of-media-queries-container'><a href='javascript:void(0)' class='del-media-query'><span class='fa fa-times'></span></a> <button>"+ $(".cwidth").val() +"px</button>"+ "<pre style='text-align:left; padding-top:5px; overflow:auto;'>"+ "@media all and (max-width:"+ $(".cwidth").val() +"px) { \n\n" + $(".dadammediaquery").val() +" }</pre>" +"</div><textarea class='"+ $(".cwidth").val() +"'>"+ $(".list-of-css-selectors").html() +"</textarea>");
A: use val() to set textarea's value
var string = "your html content";
var textarea=$('<textarea>').val( string).appendTo( containerSelector);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/24717055",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Using FXCop in your project Are there a lot of IT shops utilizing FxCop for writing production code? If so, what was/is your overall experience implementing it in terms of culture shift, pain points, and tangible benefits?
I am in an environment that is somewhat chaotic and looking for tools to help us standardize our development efforts and get us home at a decent hour. I want to avoid egg on my face for pushing a static analysis tool only to have it fail because it’s
“not practical”. <- (Anticipated management response)
A: I'd say there aren't that many places really using FxCop. We have it turned on, but most of the dev staff ignores the warnings produced.
Also, Dev Management here hasn't been interested in really pushing cleaning up the warnings, in part because FxCop really dislikes the conventions (variable names, etc) that management wants us to follow...
On projects where I've been the lead, I've mandated its use because I think it helps us be better programmers. But you have to have by in at the top in order to get all the dev's to follow it.
A: Note that FxCop is very customisable with regards to the rules you wish to apply. You may find it works best by incrementally introducing it; only for a certain set of rules for a certain set of files, or even excluding all legacy files initially.
There are bound to be rules that you may never activate because they just do not suit your problem domain. And remember that if a piece of code 'breaks a rule' for a specific purpose, there is an attribute to mark such code as acceptable, although I would instate a rule that all such overrides must use the Justification property on the attribute to indicate why.
Finally, as much as the built-in rules will help a lot with improving code quality, the really big wins are to be had in custom rules that will allow you to check for company conventions. If you do not automate your 'peer review' in this fashion, then you cannot really guarantee compliance.
I use FxCop as an integrated part of the build system at work, and our common libraries currently get released with all rules enabled with minimal attribute overrides, and it has been worthwhile in more than a few places.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/1018013",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: How to cast an process instance into it's fitting object maybe my question sounds very strange, but I want to do the following:
I have some instances of the Internet Explorer opened (iexplore.exe).
When I start my program, it should refresh all the instances of iexplore.exe without opening another instance of it.
In the beginning I thought it must be easy to refresh the Internet Explorer with help of a Visual Basic exe. But this thought was wrong.
No I was thinking about it and my thoughts where the following:
*
*At runtime I have to find out all the processes iexplore.exe
*I declare a variable Dim Browsers() as WebBrowser
*Now I have to cast all processes iexplore.exe to the object list named Browsers.
*With help of Browsers.Refresh it is easy to solve the Problem.
I have no idea how to do this and even not if this can work at all.
I appreciate your help.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/46849885",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Gunicorn "error: unrecognized arguments --log-file-" I started a Django project and it was working fine in local computer. I deployed it to Heroku and I getting this error:
2019-07-06T10:32:11.836364+00:00 app[web.1]: gunicorn: error:
unrecognized argum ents: --log-file-
2019-07-06T10:32:19.185756+00:00 app[web.1]: gunicorn: error:
unrecognized argum ents: --log-file-
My Procfile contains
web: gunicorn tutorial_two.wsgi
A: Gunicorn doesn't recognize the argument --log-file-. The Procfile you shared with us doesn't contain anything like that, but I'm going to assume that it actually contains something like
web: gunicorn tutorial_two.wsgi --log-file-
since the error message specifically mentions that argument and this is almost a correct Procfile for Gunicorn. The problem is that --log-file should get an argument -. Those things shouldn't be attached together.
Modify your Procfile to add a space, e.g.
web: gunicorn tutorial_two.wsgi --log-file -
A: Well, this is rather implied. The gunicorn program takes the --log-file - argument given in the Procfile. May be something like this is the right solution.
web: gunicorn tutorial_two.wsgi; --log-file -
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/56920284",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Error deploying Ruby On Rails over CentOS with Apache2 and Passenger I am new on Ruby on Rails and after i have finished my first project and trying to deploy it i found a bunch of error that I do not understand.
0 /usr/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb 31 in `gem_original_require'
1 /usr/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb 31 in `require'
2 /var/www/fabiolaalvaradoservices.com/public_html/config/application.rb 3
3 /usr/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb 31 in `gem_original_require'
4 /usr/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb 31 in `require'
5 /var/www/fabiolaalvaradoservices.com/public_html/config/environment.rb 2
6 /usr/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb 31 in `gem_original_require'
7 /usr/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb 31 in `require'
8 /usr/lib/ruby/gems/1.8/gems/passenger-3.0.19/lib/phusion_passenger/classic_rails/application_spawner.rb 222 in `preload_application'
9 /usr/lib/ruby/gems/1.8/gems/passenger-3.0.19/lib/phusion_passenger/classic_rails/application_spawner.rb 181 in `initialize_server'
10 /usr/lib/ruby/gems/1.8/gems/passenger-3.0.19/lib/phusion_passenger/utils.rb 563 in `report_app_init_status'
11 /usr/lib/ruby/gems/1.8/gems/passenger-3.0.19/lib/phusion_passenger/classic_rails/application_spawner.rb 174 in `initialize_server'
12 /usr/lib/ruby/gems/1.8/gems/passenger-3.0.19/lib/phusion_passenger/abstract_server.rb 204 in `start_synchronously'
13 /usr/lib/ruby/gems/1.8/gems/passenger-3.0.19/lib/phusion_passenger/abstract_server.rb 180 in `start'
14 /usr/lib/ruby/gems/1.8/gems/passenger-3.0.19/lib/phusion_passenger/classic_rails/application_spawner.rb 149 in `start'
15 /usr/lib/ruby/gems/1.8/gems/passenger-3.0.19/lib/phusion_passenger/spawn_manager.rb 219 in `spawn_rails_application'
16 /usr/lib/ruby/gems/1.8/gems/passenger-3.0.19/lib/phusion_passenger/abstract_server_collection.rb 132 in `lookup_or_add'
17 /usr/lib/ruby/gems/1.8/gems/passenger-3.0.19/lib/phusion_passenger/spawn_manager.rb 214 in `spawn_rails_application'
18 /usr/lib/ruby/gems/1.8/gems/passenger-3.0.19/lib/phusion_passenger/abstract_server_collection.rb 82 in `synchronize'
19 /usr/lib/ruby/gems/1.8/gems/passenger-3.0.19/lib/phusion_passenger/abstract_server_collection.rb 79 in `synchronize'
20 /usr/lib/ruby/gems/1.8/gems/passenger-3.0.19/lib/phusion_passenger/spawn_manager.rb 213 in `spawn_rails_application'
21 /usr/lib/ruby/gems/1.8/gems/passenger-3.0.19/lib/phusion_passenger/spawn_manager.rb 132 in `spawn_application'
22 /usr/lib/ruby/gems/1.8/gems/passenger-3.0.19/lib/phusion_passenger/spawn_manager.rb 275 in `handle_spawn_application'
23 /usr/lib/ruby/gems/1.8/gems/passenger-3.0.19/lib/phusion_passenger/abstract_server.rb 357 in `__send__'
24 /usr/lib/ruby/gems/1.8/gems/passenger-3.0.19/lib/phusion_passenger/abstract_server.rb 357 in `server_main_loop'
25 /usr/lib/ruby/gems/1.8/gems/passenger-3.0.19/lib/phusion_passenger/abstract_server.rb 206 in `start_synchronously'
26 /usr/lib/ruby/gems/1.8/gems/passenger-3.0.19/helper-scripts/passenger-spawn-server 99
Please, I need some one who can give me a hint what do I need to fix.
By the way I am using CentOS + Apache2 + Passenger.
config/application.rb file
require File.expand_path('../boot', __FILE__)
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(:default, Rails.env)
module Demo
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
# config.i18n.default_locale = :de
end
end
Configuration for Development and Production
Development Settings
Ruby version: 1.9.3p392
Rails version: 4.0.0.rc2
Production Settings
Ruby version: 1.9.3p484
Rails version: 4.0.2
Here my gemfile
source 'https://rubygems.org'
# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '4.0.0.rc2'
# Use sqlite3 as the database for Active Record
gem 'sqlite3'
# Use SCSS for stylesheets
gem 'sass-rails', '~> 4.0.0.rc2'
# Use Uglifier as compressor for JavaScript assets
gem 'uglifier', '>= 1.3.0'
# Use CoffeeScript for .js.coffee assets and views
gem 'coffee-rails', '~> 4.0.0'
# See https://github.com/sstephenson/execjs#readme for more supported runtimes
# gem 'therubyracer', platforms: :ruby
# Use jquery as the JavaScript library
gem 'jquery-rails'
# Turbolinks makes following links in your web application faster. Read more: https://github.com/rails/turbolinks
gem 'turbolinks'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 1.2'
group :doc do
# bundle exec rake doc:rails generates the API under doc/api.
gem 'sdoc', require: false
end
# Use ActiveModel has_secure_password
# gem 'bcrypt-ruby', '~> 3.0.0'
# Use unicorn as the app server
# gem 'unicorn'
# Use Capistrano for deployment
# gem 'capistrano', group: :development
# Use debugger
# gem 'debugger', group: [:development, :test]
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/20387174",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: setting the value of a checkbox programmatically in c# (wpf) I'm working on a small wpf project using c#. I have 2 windows. When I go from one window to the next, i need to have some items preselected on the 2nd window. I have a checkbox that I need to set the value based on information that I pull from the registry. On the 1st window, i have a reference to the 2nd window. How can I set the checkbox to checked so that when the other window opens it's already checked?
private void btnGoToNextWindow_Click(object sender, RoutedEventArgs e)
{
Window2 w2 = new Window2();
//This doesn't work
w2.Checked = true;
w2.Show();
this.Close();
}
A: You can use the IsChecked property.
I hope this helps.
Damian
A: Using this:
Window2 w2 = new Window2();
//This doesn't work
w2.Checked = true;
You're setting the Checked property of the window not the control. It should be somehting like this:
Window2 w2 = new Window2();
w2.MyCheckBox.IsChecked = true;
A: I'd say that you should move towards pushing the view model into the view via IoC or some other fashion. Tie the value to a property and let the framework make your life easier via binding, instead of having to hard code values all over the place.
http://msdn.microsoft.com/en-us/library/ms752347.aspx
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/3789773",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
}
|
Q: Checking Image size using jQuery validation not working I am uploading an image to the folder but before uploading, I am checking the image extension and size. I am using jQuery validation.
I checked on SO before uploading the question and I found the code. But the issue is when I am uploading an image which is less than 100kb(actual image size is 98kb) then I am getting the error "File size must be less than 5". I tried another image which is 3.8MB but still getting the same error.
Would you help me out what size of the image I have to use here? and what is the filesize: 5?
Can any one help me out in this issue?
$.validator.addMethod('filesize', function(value, element, param) {
return this.optional(element) || (element.files[0].size <= param)
}, 'File size must be less than {0}');
$(function($) {
"use strict";
$('#form').validate({
rules: {
image: {
//required: true,
extension: "jpg,jpeg,png",
filesize: 5,
}
},
});
});
<form id="form" method="post" action="">
<input type="file" name="image" />
<input type="submit" value="Upload" />
</form>
<script type="text/javascript" src="//code.jquery.com/jquery-1.11.3.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.13.1/jquery.validate.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.13.1/additional-methods.js"></script>
A: Your parameter is only set to 5
$('#form').validate({
rules: {
image: {
....
filesize: 5, ...
That is 5 BYTES, so of course you would be getting the error message for any file that is 98 kB or 3.8 MB. Since these are both larger than 5 bytes, they fail your custom rule, which only allows files smaller than 5 bytes.
Try 5242880 if you want to allow files under 5 MB.
filesize: 5242880 // <- 5 MB
$.validator.addMethod('filesize', function(value, element, param) {
return this.optional(element) || (element.files[0].size <= param)
}, 'File size must be less than {0} bytes');
$(function($) {
"use strict";
$('#form').validate({
rules: {
image: {
//required: true,
extension: "jpg,jpeg,png",
filesize: 5242880 // <- 5 MB
}
},
});
});
<form id="form" method="post" action="">
<input type="file" name="image" />
<input type="submit" value="Upload" />
</form>
<script type="text/javascript" src="//code.jquery.com/jquery-1.11.3.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.13.1/jquery.validate.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.13.1/additional-methods.js"></script>
A: Usually in these types, file sizes are specified in bytes. So you have to multiply it by 1024 multipliers accordingly.
For example if you want to check if the file size is less than 5MB, you should use
image: {
extension: "jpg,jpeg,png",
filesize: 5*1024*1024,
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/54455000",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Property 'double' does not exist on type 'MyComponent' in vuex-smart-module I have a vue application with typescript. I also use vuex-smart-module.
In my component I get typescript error:
Property 'double' does not exist on type 'MyComponent'.
In the vuex module I defined a getter:
class MyModuleGetters extends Getters<MyModuleState> {
// You can declare both getter properties or methods
get double() {
// Getters instance has 'state' property
return this.state.count * 2
}
}
And I add the getter by:
@Component({
computed: {
...MyModule.mapGetters(['double'])
}
})
export default class MyComponent extends Vue {
someFunction() {
console.log(this.double); // <-- the error is here typescript typo.
If I use Vue.extend({ … }) its solved the problem BUT I need for every component to do Vue.extend so basically I create for 2 components each time. which is seems wrong.
Any idea how to make it work without extend?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/57757339",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Change filename after upload Laravel Stapler I'm using the Stapler Lib to make the image uploads.
The image's filename is generated by image description field.
After the upload, the user can change the image description and after that, I need to update the image filename.
Is there a way to do this using the Stapler Lib?
A: Yes You can do like this
if($request->hasFile('image')) {
$file = Input::file('image');
//getting timestamp
$timestamp = str_replace([' ', ':'], '-', Carbon::now()->toDateTimeString());
$name = $timestamp. '-' .$file->getClientOriginalName();
$blog->image = $name;
$file->move(public_path().'/../public_html/img/blog/', $name);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/38413206",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: MAC VSCode remote ssh extension failed to connect to Linux server I am trying to use VSCode remote ssh extension to access a folder on my school machine. I think initially the connection was established since it prompted me to enter the password. But then the window is stuck, and here is the output:
[16:27:58.275] > Warning: no access to tty (Inappropriate ioctl for device).
> Thus no job control in this shell.
[16:27:58.340] > ready: 4b31ee9ef295
[16:27:58.410] > Linux 4.19.0-13-amd64 #1 SMP Debian 4.19.160-2 (2020-11-28)
[16:27:58.410] Platform: linux
[16:27:58.552] stderr> bash: line 360: syntax error near unexpected token `('
[16:27:58.552] stderr> bash: line 360: `echo "* as described in the license (https://go.microsoft.com/fwlink/?linkid=2077057)"'
[16:27:58.552] stderr> function: Command not found.
[16:27:58.552] stderr> Bad : modifier in $ '-'.
[16:27:58.553] > 4b31ee9ef295: running
> *
>
[16:27:58.553] stderr> VSCH_LOGFILE: Undefined variable.
[16:27:58.553] stderr> LISTENING_ON=: Command not found.
[16:27:58.554] stderr> VSCH_LOGFILE: Undefined variable.
[16:27:58.554] stderr> WEBUITOKEN=: Command not found.
[16:27:58.554] stderr> LISTENING_ON: Undefined variable.
The problem should not be on my school's server side because I used the ssh command in zsh and it successfully connects. So can anyone tell me where the problem is? Thank you in advance!
A: Open command palette, run "Remote-SSH: Settings", then config "Remote.SSH: Remote Server Listen On Socket" to true. This did the trick for me.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/66217477",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: is it convenient to urlencode all next parameters? - django While writing code, it is pretty common to request a page with an appended "next" query string argument.
For instance, in the following template code next points back to the page the user is on:
<a href="{%url some_view%}?next={{request.get_full_path}}
Here I am following a convention: if next features something that I'm not in control of, such as search keywords a user has typed, I urlencode it. Otherwise I don't.
<a href="{%url some_view%}?next={{request.get_full_path|urlencode}}
Instead of judging for each next argument whether it would be user provided or not, would it be convenient if I urlencode all next strings? Will there be side effects I don't see at the moment?
A: To the best of my knowledge anything that's inside of a url should always be urlencoded.
The only gotcha is that you need to make sure to reverse the encoding when you read in the arguments. It's very possible that django already does this for you. I'd need to consult the documentation and/or code to confirm though.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/1702035",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: spring boot use file path both in eclipse and after build I'm developing spring boot program using json input.
when I build spring boot from build.gradle file, I copy resources from src/main/resources to deploy/config.
Now, I want to use my json file in Eclipse and after build, but file path is different.
In eclipse, file path is src/main/resources/input/a.json and After build, file path is deploy/config/input/a.json
this is my build.gradle
task deploy() {
doLast{
delete ('deploy')
copy {
from "src/main/resources"
into "deploy/config"
include "*/"
}
copy {
from "build/libs/${rootProject.name}-${version}.jar"
into "deploy/"
}
}
}
And my java source code is like this.
String path1="config/input/"+fileName;
String path2="src/main/resources/input"+fileName;
How can I write file path just one way? I can't modify all the time when I build.
Thank you! :D
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/50385591",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: asmx WebMethod caching on POST request in asp.net I am using jQuery to get back some JSON data from the server. I am using a POST verb, but even after setting the WebMethod CacheDuration attribute, the JSON doesn't get cached.
I checked the response headers with firebug and the Cache-Control is still set to no-cache.
How can i cache these request on the client and avoid the server to be hit every time.
UPDATE
After reading this post from scottGu I thought it would have been safe to go on to use a POST request. Does his post not apply to the kind of operation i would be trying to do ? (getting data from the server without modifying it). In fact after changing the verb to GET, i am not even getting to the web service ...
A: You should be using a get request. Post does not cache by default. You can try to get a post to cache by using .ajax() and setting cache to true and type to post. I cannot say that this will work as typically you would not expect a post to cache. I suggest using get.
E.g
$.ajax( { url: '/bla',
type : 'post',
data : dataObj,
cache : true } );
A: Use the GET keyword instead if you want to use caching. There is a similar question on SO.
A: I've noticed differences in the way ASP.NET caches responses depending upon whether the caching parameters are query string parameters or (in my case with ASP.NET MVC) route parameters.
I never completely figured out exactly what the conditions were, but this may help someone.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/1235652",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to redirect an asp page to 2 other pages? I have a web page with checkbox list to choose multiple crystal reports to view. I want to open these reports in new tabs or windows.
I tried this :
This is the show report button:
<asp:Button ID="Button2" runat="server" Text="Show Report" OnClick="ButtonShowReport_Click"
CssClass="button" OnClientClick="aspnetForm.target ='_blank';"/>
And this is my gridview control:
<asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333"
RowStyle-HorizontalAlign="Center" AutoGenerateColumns="False"
DataKeyNames="AccountID">
<RowStyle BackColor="#>
<Columns>
<asp:TemplateField HeaderText="Choose Client's Accounts">
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server"/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField Visible="false">
<ItemTemplate>
<asp:Label id="lblAccountId" runat ="server" text='<%# Eval("AccountID")%>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="AccountID" HeaderText="AccountID" Visible="false"/>
<asp:BoundField DataField="AccountName" HeaderText="Account Name" />
<asp:BoundField DataField="Name" HeaderText="Client Name" />
</Columns>
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<EditRowStyle BackColor="#2461BF" />
<AlternatingRowStyle BackColor="White" />
</asp:GridView>
My c# code looks like:
protected void ButtonShowReport_Click(object sender, EventArgs e)
{
string accountID;
int Rows = GridView1.Rows.Count;
for (int i = 0; i < Rows; i++)
{
//CheckBoxField cb = ((CheckBoxField)gvASH.Rows[i].Cells[1]).;
CheckBox cb = (CheckBox)GridView1.Rows[i].Cells[0].FindControl("CheckBox1");
if (cb.Checked == true)
{
accountID = ((Label)GridView1.Rows[i].FindControl("lblAccountID")).Text;//GridView1.DataKeys[i].Value.ToString();//GridView1.Rows[i].Cells[1].Text;
//Button2.Enabled = true;
openReport(accountID);
}
}
}
protected void openReport(string accountID)
{
//some code for setting parameters of the crystal report
//and for creating report key
Response.Redirect(string.Format("~/Report.aspx?ReportKey={0}",
ReportKey.ToString()),false);
}
So if the user checked 2 reports and clicked on the ShowReport button, it'll do the loop but opens only one new tab with the last report chosen ...
Any Suggestions please ??
A: Add this to the control which triggers the redirect. I know this works for Buttons/LinkButtons, not sure if it will work on a checkbox though.
OnClientClick="aspnetForm.target ='_blank';"
A: One method you might consider:
Instead of doing the Redirect to each report inside the code behind - dynamically generate some JavaScript that has uses window.open for each report. The javascript would look similar to this:
<script type="text/javascript">
window.open("<report1URL>", "_blank");
window.open("<report2URL>", "_blank");
...
window.open("<reportNURL>", "_blank");
</script>
Then, instead of doing a Response.Redirect, you should be able to do a Respone.Write() to get the browser to execute the code.
string myJavaScript= <dynamicallyGenerateJavascript>;
Response.Write(myJavaScript);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7322041",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How can I store recorded data from the NEST simulator in a binary format? I am trying to write spikedetector data into .gdf files in binary format, but I cannot.
I am setting the binary param of the spikedetector to True (I checked it using nest.GetStatus) but files are written in ASCII:
neurons = nest.Create('iaf_psc_alpha', 5)
sr = nest.Create('spike_recorder')
nest.Connect(neurons, sr)
sr.SetStatus({'binary': True})
I am using NEST 2.18
A: The documentation for NEST 2.18 and 2.20 is misleading in this respect. The binary option has no effect (it sets the ios::binary flag when opening the file, but that has no significant consequences).
If you want to write spikes in binary format, you need to switch to NEST 3.0 and use the sionlib recording backend by setting the recorder's record_to property:
neurons = nest.Create('iaf_psc_alpha', 5)
sr = nest.Create('spike_recorder')
nest.Connect(neurons, sr)
sr.SetStatus({'record_to': 'sionlib'})
A guide for recording from simulations is available in the docs.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/67054916",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Failed pushing Python Flask App to Heroku New to Flask and deploying on Heroku, trying to push to Heroku and I get this error when installing dependencies:
The pipenv version looks funny not sure if that is correct or how to correct it if that is the error
Enumerating objects: 38, done.
Counting objects: 100% (38/38), done.
Delta compression using up to 8 threads
Compressing objects: 100% (30/30), done.
Writing objects: 100% (38/38), 83.94 KiB | 10.49 MiB/s, done.
Total 38 (delta 8), reused 0 (delta 0), pack-reused 0
remote: Compressing source files... done.
remote: Building source:
remote:
remote: -----> Python app detected
remote: -----> Installing python-3.8.5
remote: -----> Installing pip
remote: -----> Installing dependencies with Pipenv 2018.5.18
remote: Traceback (most recent call last):
remote: File "/tmp/build_9fedd330/.heroku/python/lib/python3.8/site-packages/pipenv/patched/prettytoml/elements/abstracttable.py", line 27, in _enumerate_items
remote: yield next(non_metadata), next(non_metadata)
remote: StopIteration
remote:
remote: return toml.loads(contents)
remote: File "/tmp/build_9fedd330/.heroku/python/lib/python3.8/site-packages/pipenv/vendor/toml.py", line 307, in loads
remote: raise TomlDecodeError("Key group not on a line by itself.")
remote: toml.TomlDecodeError: Key group not on a line by itself.
remote: ! Push rejected, failed to compile Python app.
remote:
remote: ! Push failed
remote: Verifying deploy...
remote:
Not sure what the error is! Any help would be appreciated. I have removed some of the error list due to asking me for more details as to much code
A: If you have not yet done it, create a file with dependencies for your code and specify versions explicitly (example):
Flask==0.8
Jinja2==2.6
Werkzeug==0.8.3
certifi==0.0.8
chardet==1.0.1
distribute==0.6.24
gunicorn==0.14.2
requests==0.11.1
Then (if you didn't create it yet), set up a new virtual environment, install all the requirements and check that your code is running by using the python from this environment.
*
*Install virtualenv:
python3 -m pip install --user virtualenv
*Create a virtual environment: python3 -m venv env
*Activate the virtual environment source env/bin/activate
*Install all the requirements pip install -r requirements.txt
*Run your application in the same console where you activated the virtual environment.
The Heroku uses the following command for installing dependencies pip install -r requirements.txt. So if it gives you error on your local machine you would know what's the problem.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/63132290",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to make babel compile null coalescing operator? A dependency of mine uses the null coalescing operator. Babel can't handle it. Is there any way to make Babel work here?
babel.config.js
module.exports = {
presets: ['@babel/preset-env', '@babel/preset-react'],
plugins: [
'@babel/transform-runtime',
'@babel/plugin-proposal-nullish-coalescing-operator'
],
};
Compile error:
./node_modules/test/dist/test.js 26:10
Module parse failed: Unexpected token (26:10)
File was processed with these loaders:
* ./node_modules/react-scripts/node_modules/babel-loader/lib/index.js
You may need an additional loader to handle the result of these loaders.
| export class Test {
| constructor() {
> null ?? 0;
| }
|
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/70398728",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: .attachClickHandler() does not work on page refresh/redirect I'm trying to implement a custom google login button in index.html which works perfectly on page load but does not when the page is reloaded or redirected from another page. On page load, console statements 1,2 and 3 are printed sequentially automatically and 4 is printed on sign-in. When redirected from another page or refreshed the console only prints 1 and 2 and the button is not clickable. The script to include gapi is included by
<script src="https://apis.google.com/js/api:client.js"></script>
in index.html. I'm using AngularJS if that has something to do with this.
var googleUser = {};
var startApp = function() {
console.log("1");
gapi.load('auth2', function(){
// Retrieve the singleton for the GoogleAuth library and set up the client.
console.log("2");
auth2 = gapi.auth2.init({
client_id: '*************.apps.googleusercontent.com',
cookiepolicy: 'single_host_origin',
// Request scopes in addition to 'profile' and 'email'
scope: 'profile email'
});
setTimeout(function(){
attachSignin(document.getElementById('g_login'));
}, 1000);
// attachSignin(document.getElementById('g_login'));
});
};
function attachSignin(element) {
console.log("3");
auth2.attachClickHandler(element, {},
function(googleUser) {
console.log("4");
document.getElementById('name').innerText = "Signed in: " +
googleUser.getBasicProfile().getName();
angular.element(document.getElementById('status')).scope().googleLogin(googleUser.getAuthResponse().id_token);
}, function(error) {
alert(JSON.stringify(error, undefined, 2));
});
}
startApp();
</script>
A: Solved.
Global variable 'auth2' is automatically initialised each time the page is loaded and can be used to sign users in.
The script is called as:
<script src="https://apis.google.com/js/api:client.js?onload=onLoadCallback" async defer></script>
<script>
var auth2;
var googleUser = {};
var auth3;
window.onLoadCallback = function(){
gapi.load('auth2', function () {
auth2 = gapi.auth2.init({
client_id: '**********.apps.googleusercontent.com',
cookiepolicy: 'single_host_origin',
// Request scopes in addition to 'profile' and 'email'
scope: 'profile email'
});
auth3 = true;
startApp();
})
}
var startApp = function() {
element = document.getElementById('g_login');
auth2.attachClickHandler(element, {},
function(googleUser) {
console.log("4");
document.getElementById('name').innerText = "Signed in: " +
googleUser.getBasicProfile().getName();
angular.element(document.getElementById('status')).scope().googleLogin(googleUser.getAuthResponse().id_token);
}, function(error) {
console.log("5");
alert(JSON.stringify(error, undefined, 2));
});
};
if (auth3)
startApp();
</script>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/38178520",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Remove Paste option from MenuItems in iOS 16 I have a custom menu options written in
override func tableView(_ tableView: UITableView, canPerformAction action: Selector, forRowAt indexPath: IndexPath, withSender sender: Any?) -> Bool { }
in iOS 16 I see now a Paste option in the context option. I tried to hide it via
if action.description == "paste:" { return false } //FAILED
return action != #selector(UIResponderStandardEditActions.paste(_:)) // FAILED
but did not help. I see Paste option now everywhere.
How to get rid of it ?
A: To remove the paste option from the default context menu, use this:
func tableView(_ tableView: UITableView, canPerformAction action: Selector, forRowAt indexPath: IndexPath, withSender sender: Any?) -> Bool {
if action != #selector(UIResponderStandardEditActions.paste(_:)) {
return true
}
return false
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73727326",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Javascript Mapping Nested Arrays I have an array of objects ("array"), each containing other arrays of objects.
[
{
name: "Object 1",
question: [{value: "This", type: "text"}, {value: "is", type: "text"}, {value: "1", type: "number".]
answer: [{value: "Answer", type: "text"}, {value: "is", type: "text"}, {value: "1", type: "number".]
},
{
name: "Object 2",
question: [{value: "This", type: "text"}, {value: "is", type: "text"}, {value: "2", type: "number".]
answer: [{value: "Answer", type: "text"}, {value: "is", type: "text"}, {value: "2", type: "number".]
},
]
In React, I'd like to render out the below:
<Typography>This</Typography><Typography>is</Typography><Number>1</Number>
<Typography>Answer</Typography><Typography>is</Typography><Number>1</Number
<Typography>This</Typography><Typography>is</Typography><Number>2</Number>
<Typography>Answer</Typography><Typography>is</Typography><Number>2</Number
I have tried the below, but can't work out why some of it won't map correctly.
array.map(snippet => {
snippet.question.map(question => {
return something here;
})
EDITED AS FORGOT A LEVEL OF OBJECTS
A: Try some thing like this.
array.map(snippet => (
<>
{snippet.question.map(que => {
if (que.type === "text") {
return <Typography>{que.value}</Typography>;
} else if (que.type === "number") {
return <Number>{que.value}</Number>;
}
return null;
})}
{snippet.answer.map(ans => {
if (ans.type === "text") {
return <Typography>{ans.value}</Typography>;
} else if (ans.type === "number") {
return <Number>{ans.value}</Number>;
}
return null;
})}
</>
));
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/60987262",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: issue with adding a method in object I have this object:
var Point = {
step: function () {
alert("hello");
}
};
This works:Point.step();.
How to make it work with the [ ] notation? Meaning Point["property_name"].
A: It is Point["step"]();. Here is the snippet:
var Point = {
step: function () {
alert("hello");
}
};
Point["step"]();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/29386067",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: JQuery UI - .resizable not working I have looked around and although I have found similar questions to this one, none of them had any solutions that worked for me.
Here is a link to another question similar.
Draggable and resizable in JqueryUI for an image is not working?
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
</head>
<body>
<div id="draggableHelper" style="display:inline-block">
<img id="image" src="http://www.google.com.br/images/srpr/logo3w.png" />
</div>
<script type="text/javascript">
$(document).ready(function(){
$('#draggableHelper').draggable();
$('#image').resizable();
});
</script>
</body>
</html>
This is just a very basic example but when I run this the image is movable but is not resizable. Although as far as I can tell, it should definitely work.
In the link above at the bottom of the question there is a link to a working example.
http://jsfiddle.net/8VY52/
The example is using jfiddle with this exact same HTML and javascript.
Is there something I am missing about Jquery UI, why does this work through Jfiddle but does not seem to work within the code above.
Thanks.
A: You are missing the jquery-ui CSS file in your code
<link rel="stylesheet" type="text/css" href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css"/>
Demo: Plunker
A: Complete working code would be.
</head>
<body>
<div id="draggableHelper" style="display:inline-block">
<div id="image"><img src="http://www.google.com.br/images/srpr/logo3w.png" /></div>
</div>
<script type="text/javascript">
$(document).ready(function(){
$('#image').resizable();
$('#image').draggable();
$('#image').resize(function(){
$(this).find("img").css("width","100%");
$(this).find("img").css("height","100%");
});
});
</script>
</body>
</html>
A: This will work for you.
<div id="draggableHelper" style="display:inline-block">
<div id="image"><img src="http://www.google.com.br/images/srpr/logo3w.png" /></div>
</div>
A: As the resizable property only works on right side and bottom side so find the image borders find that by selecting a image in css and border to it then see the output it will work perfectly
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/16692919",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
}
|
Q: Flutter How to make two columns in Container? There is a Container, inside you need to make two columns. In one column there will be icons with texts, and in another there will be one icon in the center.
More details on the photo
enter image description here
A: I made an example of what you are trying to achieve:
class SO extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Container(
height: 200,
width: 300,
decoration: BoxDecoration(
color: Colors.orange,
borderRadius: BorderRadius.circular(10),
),
padding: EdgeInsets.only(left: 25),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Row(
children: <Widget>[
Icon(
Icons.mail_outline,
color: Colors.white,
size: 30,
),
Text('title'),
],
),
Row(
children: <Widget>[
Icon(
Icons.mail_outline,
color: Colors.white,
size: 30,
),
Text('title'),
],
),
Row(
children: <Widget>[
Icon(
Icons.mail_outline,
color: Colors.white,
size: 30,
),
Text('title'),
],
),
Row(
children: <Widget>[
Icon(
Icons.mail_outline,
color: Colors.white,
size: 30,
),
Text('title'),
],
),
],
),
Spacer(),
Container(
height: 60,
width: 60,
decoration: BoxDecoration(
shape: BoxShape.circle,
border: Border.all(
color: Colors.white,
width: 2,
),
),
child: Center(
child: Text('Photo'),
),
),
Spacer(),
],
)),
),
);
}
}
OUTPUT :
A: This is the code, which will help you attain what you want to achieve. Also, I have replaced the photo with the real image, to give you a feel about how the image works. However, it is NetworkImage(), it uses web images, if you want to use the local image, then do use AssetImage()
Container(
height: 200.0,
width: 350.0,
padding: EdgeInsets.all(20.0),
decoration: BoxDecoration(
color: Colors.orange,
borderRadius: BorderRadius.circular(10.0)
),
child: Row(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Row(
children: <Widget>[
Icon(
Icons.mail_outline,
color: Colors.white,
size: 30,
),
SizedBox(width: 10.0),
Text('title', style: TextStyle(fontSize: 17.0, fontWeight: FontWeight.bold)),
]
),
Row(
children: <Widget>[
Icon(
Icons.mail_outline,
color: Colors.white,
size: 30,
),
SizedBox(width: 10.0),
Text('title', style: TextStyle(fontSize: 17.0, fontWeight: FontWeight.bold)),
]
),
Row(
children: <Widget>[
Icon(
Icons.mail_outline,
color: Colors.white,
size: 30,
),
SizedBox(width: 10.0),
Text('title', style: TextStyle(fontSize: 17.0, fontWeight: FontWeight.bold)),
]
)
]
),
Expanded(
flex: 1,
child: Align(
alignment: Alignment.center,
child: Container(
height: 80.0,
width: 80.0,
decoration: BoxDecoration(
border: Border.all(color: Colors.white, width: 3.0),
borderRadius: BorderRadius.all(Radius.circular(40.0)),
image: DecorationImage(
fit: BoxFit.cover,
image: NetworkImage('https://image.shutterstock.com/image-photo/beautiful-pink-flower-anemones-fresh-260nw-1028135845.jpg')
)
)
)
)
)
]
)
)
RESULT
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/62910293",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: kickme discord.js command, kicks before can dm Im having some issues getting the command to wait for the bot to dm the user before it kicks them, ive put in a wait 5 second function but it kicks well before 5 seconds is up Below is my code and error.
its saying 'wait' isnt defined but ive looked here and used one of those, with a slight modification.
also i have another not so important question, how would i make it so whoever runs the !kickme command gets logged into a .txt file or something similar?
Edit: i figured id clarify. Yes im trying to kick the user who sent the !kickme command. its meant to be a completely useless command for people to mess around with. it should send them a dm with the server invite(so they can rejoin) and then kick them.
as of now it isnt sending the dm to them, its just kicking them
const Discord = require('discord.js')
module.exports.run = async (bot, message, args) => {
const user = message.author
const member = message.guild.member(user);
message.author.send(`Here is an invite so you can join back! https://discord.gg/FBXSduget2 `)
const timew = async (bot, message, args) => {
wait(5000);
console.log("Waited 5s");
wait(5000);
console.log("Waited an additional 5s");
};
timew();
if (member) {
member
.kick('User was kicked')
.then(() => {
console.log(`${user.tag} Kicked themself`);
message.channel.send(`${user.tag} kicked themself`)
})
.catch(err => {
message.reply('Unable');
console.error(err);
});
}
}
module.exports.help = {
name: "kickme"
}
(node:13216) UnhandledPromiseRejectionWarning: ReferenceError: wait is not defined
at timew (C:\Users\8fwbu\Desktop\CodeTProj\-Tux V2\commands\kickme.js:12:9)
at Object.module.exports.run (C:\Users\8fwbu\Desktop\CodeTProj\-Tux V2\commands\kickme.js:19:7)
at Client.<anonymous> (C:\Users\8fwbu\Desktop\CodeTProj\-Tux V2\main.js:42:31)
at Client.emit (events.js:315:20)
at MessageCreateAction.handle (C:\Users\8fwbu\node_modules\discord.js\src\client\actions\MessageCreate.js:31:14)
at Object.module.exports [as MESSAGE_CREATE] (C:\Users\8fwbu\node_modules\discord.js\src\client\websocket\handlers\MESSAGE_CREATE.js:4:32)
at WebSocketManager.handlePacket (C:\Users\8fwbu\node_modules\discord.js\src\client\websocket\WebSocketManager.js:384:31)
at WebSocketShard.onPacket (C:\Users\8fwbu\node_modules\discord.js\src\client\websocket\WebSocketShard.js:444:22)
at WebSocketShard.onMessage (C:\Users\8fwbu\node_modules\discord.js\src\client\websocket\WebSocketShard.js:301:10)
at WebSocket.onMessage (C:\Users\8fwbu\node_modules\ws\lib\event-target.js:132:16)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:13216) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled
with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:13216) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
(node:13216) UnhandledPromiseRejectionWarning: DiscordAPIError: Cannot send messages to this user
at RequestHandler.execute (C:\Users\8fwbu\node_modules\discord.js\src\rest\RequestHandler.js:154:13)
at processTicksAndRejections (internal/process/task_queues.js:93:5)
at async RequestHandler.push (C:\Users\8fwbu\node_modules\discord.js\src\rest\RequestHandler.js:39:14)
(node:13216) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled
with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)
Unicorn-Barf#9255 Kicked themself
A: Your error comes from using wait(5000); as this is not defined.
You can use await when sending messages to ensure they are sent.
await message.author.send(`Here is an invite`)
message.member.kick('they kicked themself')
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/66480486",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Spring MVC: Testing particular annotated method gets invoked In Spring MVC 3.0, how do I test that a particular method gets invoked?
For example, I have this controller method:
public class myController {
@RequestMapping(value = "/create", method = RequestMethod.GET)
public ModelAndView create(ModelMap map) {
map.put("category", new Category());
return new ModelAndView("views/someView", map);
}
}
How do I test that this create() method gets called when somebody requests http://example.com/create url.
A: In Unit Tests, you should only test your controller's Java code, without using any Servlet technology.
In integration tests you can do one of several things:
Use the org.springframework.mock.web package in the spring-test artifact, which contains Mock Objects for request, response, servletContext to fire fake requests at your controllers and read the data from the fake responses.
Or use a web testing framework like Selenium that works against a deployed webapp.
A:
How do I test that this create() method gets called when somebody requests http://example.com/create url.
Looks really like a integration test. Sean Patrick Floyd already mentioned some ways how to test that, but to my understanding none of this options really tests that a request to an url really invokes the method. -- The mocking way simulates the request and the selenium test tests only the return value, but not the Invocation. -- Don't get my wrong, I believe that this two other tests are in most cases better (easyer to test and even more valid test results), but if you really want to test the invokation I would come up with this solution.
Use a web testing framework like Selenium (or Selenium 2/Webdriver) or only a simple one that only generates HTTP requests. -- To do that tests you will need of curse the deployed application. -- so it is realy an integration test.
To check that the method is invoked. I would recommend to use a logging tool (Log4J). Then use a Tool like AspectJ or Spring AOP Support to add logging statements to your controller method. The logging should be written to some logger that writes to an other destination then the other loggers you use.
At the end the last step is, that you need to verify that the expected logging statement is is the logfile after the test sends the http request. (Pay attention to the fact, that the logging may is asynchronous.)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7690425",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Updating to Marionette Driver C# Ok so as many of you fellow webdriver testers know the release of Firefox 47 has broken the Webdriver.FirefoxDriver. All the documentation I can find tells me that the new FirefoxDriver is Marionette.
So I have downloaded the latest executable from https://github.com/mozilla/geckodriver/releases
renamed to wires.exe and moved into my test directory.
Here is my setup method
[TestFixture("chrome")]
[TestFixture("firefox")]
//[TestFixture("internet explorer")]
[Category("ExistingUser")]
public class ExistingUserTestSuite
{
public string browser;
public IWebDriver Driver { get; set; }
public UserInfo User { get; set; }
private static readonly log4net.ILog log = log4net.LogManager.GetLogger("ExistingUserTest");
public ExistingUserTestSuite(string browser)
{
this.browser = browser;
}
[OneTimeSetUp]
public void SetUp()
{
switch (browser)
{
case "chrome":
Driver = new ChromeDriver();
break;
case "firefox":
FirefoxOptions op1 = new FirefoxOptions();
op1.IsMarionette = true;
op1.AddAdditionalCapability("marionette", true);
Driver = new FirefoxDriver(op1);
break;
When I try to run I get the following exception. I can see that the wire.exe process is running in process explorer when I start the tests.
Test Name: ChangePlan
Test FullName: POMAuctivaTest.TestSuite.ExistingUserTestSuite("firefox").ChangePlan
Test Source: c:\git\POMAuctivaTest\POMAuctivaTest.TestSuite\ExistingUserTestSuite.cs : line 359
Test Outcome: Failed
Test Duration: 0:00:00.0000001
Result Message: OneTimeSetUp: System.InvalidOperationException : entity not found
Here is the stack trace generating the exception
at OpenQA.Selenium.Remote.RemoteWebDriver.UnpackAndThrowOnError(Response errorResponse)
at OpenQA.Selenium.Remote.RemoteWebDriver.Execute(String driverCommandToExecute, Dictionary`2 parameters)
at OpenQA.Selenium.Remote.RemoteWebDriver.StartSession(ICapabilities desiredCapabilities)
at OpenQA.Selenium.Remote.RemoteWebDriver..ctor(ICommandExecutor commandExecutor, ICapabilities desiredCapabilities)
at OpenQA.Selenium.Firefox.FirefoxDriver..ctor(FirefoxDriverService service, FirefoxOptions options, TimeSpan commandTimeout)
at OpenQA.Selenium.Firefox.FirefoxDriver..ctor(FirefoxOptions options)
at POMAuctivaTest.TestSuite.ExistingUserTestSuite.SetUp() in c:\git\POMAuctivaTest\POMAuctivaTest.TestSuite\ExistingUserTestSuite.cs:line 56
Most advice I see is regarding making sure your system path is updated. I feel this is not the case here as if I remove the wire.exe from my test/bin/debug folder I get the following exception.
Test Name: ChangePlan
Test FullName: POMAuctivaTest.TestSuite.ExistingUserTestSuite("firefox").ChangePlan
Test Source: c:\git\POMAuctivaTest\POMAuctivaTest.TestSuite\ExistingUserTestSuite.cs : line 359
Test Outcome: Failed
Test Duration: 0:00:00.0000001
Result Message: OneTimeSetUp: OpenQA.Selenium.DriverServiceNotFoundException : The wires.exe file does not exist in the current directory or in a directory on the PATH environment variable. The driver can be downloaded at https://github.com/jgraham/wires/releases.
This tells me that I am finding the driver but for some reason cannot create an instance of FirefoxDriver().
Not sure what to do here, any help would be nice.
A: Well after what felt like a wild goose hunt I found this little gem in an open issue on the geckodriver github page. I have confirmed that this has fixed my issue and now I am able to create an instance of firefox driver and successfully open Firefox 47. https://github.com/mozilla/geckodriver/issues/91
Here is a snippet of the code from the above URL in case the link goes dead
FirefoxDriverService service = FirefoxDriverService.CreateDefaultService();
service.FirefoxBinaryPath = @"C:\Program Files (x86)\Mozilla Firefox\firefox.exe";
IWebDriver driver = new FirefoxDriver(service);
Hope this helps others. But there is a bug which is currently a blocking issue for all my tests. All of my tests access our internal test environments which have self signed certs and there is a bug with marionette where you cannot handle these.
https://bugzilla.mozilla.org/show_bug.cgi?id=1103196
=(
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/37890982",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Two COUNT and a GROUP BY I'm stuck with this query and I would like to have a hand.
So I have two tables : Course and Absence.
The purpose of my query is to count, for a student, all his courses and absences for each months of the year.
With just the courses, I have this query :
SELECT DATE_FORMAT(c.date, "%M") AS month,
COUNT(*) AS courses
FROM Course c
GROUP BY month
ORDER BY MONTH(c.date);
The result looks like this :
+-----------+--------+
| month | courses|
+-----------+--------+
| January | 24 |
| February | 20 |
| March | 20 |
| April | 22 |
| May | 23 |
| June | 20 |
| July | 23 |
| August | 22 |
| September | 20 |
| October | 23 |
| November | 23 |
| December | 21 |
+-----------+--------+
I would like to have a new column, exactly like the courses one, but for the absences.
My Absence columns are : id, user_id, course_id, reason, justified
So, is this possible to use the courses group by with an absence count ?
If yes, how ?
Thanks in advance,
EDIT :
I have now this query :
SELECT a.month, a.courses, b.absences
FROM (SELECT DATE_FORMAT(c.DATE, "%M") AS month,
COUNT(*) AS courses
FROM Course c
GROUP BY month) a
INNER JOIN (SELECT DATE_FORMAT(c.date, "%M") AS month,
COUNT(*) AS absences
FROM Absence a
LEFT JOIN Course c
ON a.course_id = c.id
GROUP BY month) b
ON a.month = b.month;
And the result is :
+----------+---------+----------+
| month | courses | absences |
+----------+---------+----------+
| November | 23 | 2 |
| October | 23 | 1 |
+----------+---------+----------+
The numbers are good, but when there are no absences, the courses are not shown.
Is there a way to have a 0 on the absences ?
EDIT 2 :
This is the working query :
SELECT a.month, a.courses, b.absences
FROM (SELECT DATE_FORMAT(c.DATE, "%M") AS month,
COUNT(*) AS courses
FROM Course c
GROUP BY month) a
LEFT JOIN (SELECT DATE_FORMAT(c.date, "%M") AS month,
COUNT(*) AS absences
FROM Absence a
LEFT JOIN Course c
ON a.course_id = c.id
GROUP BY month) b
ON a.month = b.month;
A: Try this:
SELECT a.month, a.courses, b.absences
FROM (SELECT DATE_FORMAT(c.DATE, "%M") AS month,
COUNT(*) AS courses
FROM Course c
GROUP BY month) a
LEFT JOIN (SELECT DATE_FORMAT(c.date, "%M") AS month,
COUNT(*) AS absences
FROM Absence a
LEFT JOIN Course c
ON a.course_id = c.id
GROUP BY month) b
ON a.month = b.month;
This does two subqueries, one to find the count of courses and one for absences. Then you join them by the month.
It should give you what you are looking for.
A: You should be able to do this with inline views:
SELECT c.month, c.courses, a.absences
FROM (
SELECT DATE_FORMAT(date, "%M") AS month,
COUNT(*) AS courses
FROM Course
GROUP BY month
) AS c
JOIN (
SELECT DATE_FORMAT(date, "%M") AS month,
COUNT(*) AS absences
FROM Absence
GROUP BY month
) AS a
ON a.month = c.month
ORDER BY c.month
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/20129105",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Google Sheet Formula: Preventing the serial number of duplicates below to go up I'm currently struggling to assign serial number to a series of dynamic data in google spreadsheet.
for example, i have this table below
Product
Serial Number
Apple
1
Orange
1
Lemon
1
Banana
1
Apple
2
Melon
1
Lemon
2
Orange
2
Banana
2
Apple
3
currently on column B i'm using the formula =COUNTIF($A$1:A1,A1)
But the problem is, when i change the product on column A to another, the serial number of the duplicates below will automatically go up. for instance, if i change the 2nd Apple to Orange, the serial number of the 3rd Apple will automatically go up to 2.
I'd like the serial number of duplicates below to not be changed because it will be sent to the customer (i hope i'm making sense).
is there a way for me to do this?
any help will be much appreciated.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/74858761",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Batch hostednetwork IF ELSE not working I would like to write a batch script, but i'm not very good at it.
I want to start my hostednetwork if it isn't running. If it is already running, I want to stop it. Could somebody help me please?
This is what I have:
@echo off
netsh wlan show hostednetwork
if not (hostednetwork==started) goto start
else goto stop
:start
netsh wlan start hostednetwork
goto end
:stop
A: The string "hostednetwork" will never be the same as the string "started"
Also, you have a syntax error with your elsestatement. Nevertheless, you don't need it:
netsh wlan show hostednetwork|find "Status"|find "started">nul && goto stop || goto start
A: For anyone who would like to use this method, here is the complete working code
@ECHO OFF
netsh wlan show hostednetwork|find "Status"|find "Started">nul && goto stop || goto start
:start
netsh wlan start hostednetwork
goto end
:stop
netsh wlan stop hostednetwork
goto end
:end
PAUSE
Thanks to those who put into the creation of this method
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/22640167",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: remote_ip is returning an ip different from whatismyip.com in some cases I am trying to set up some IP whitelisting for a specific controller and I'm relying on the value returned by request.remote_ip
def country_whitelist
request_country = Custom::BackofficeLibrary.get_country_by_ip(request.remote_ip)
head 404 unless ['PE'].include? request_country
end
My problem is that for certain devices/networks, the IP address returned by request.remote_ip is wrong.
Using my phone's mobile network for example, I'm getting an IP for the US when I'm located in Peru. However, if I browse on my phone to http://www.whatismyip.com or to http://freegeoip.net I do get the correct Peru IP address.
So in some cases (1 in 10), remote_ip is failing to get the correct ip when free internet services get it right.
My setup is AWS EC2 -> Nginx -> Puma -> Rails 5.0.0.1
I have tried AWS with and without a load balancer in front and it makes no difference.
Any ideas?
EDIT:
Adding Ngnix partial config in case it's relevant:
server {
listen 80;
server_name localhost;
root /home/deploy/backoffice/current/public;
try_files $uri/index.html $uri @app;
location / {
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Host $host;
proxy_redirect off;
proxy_http_version 1.1;
proxy_set_header Connection '';
proxy_pass http://app;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/42964904",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: java.lang.NoClassDefFoundError when trying to run tasks-android-sample I have been trying to run the sample code available at http://samples.google-api-java-client.googlecode.com/hg/tasks-android-sample/instructions.html
I have included all jar file needed to resolve the dependencies. My project doesn't contain any error but when i try to the program it give me following error:
java.lang.NoClassDefFoundError:
com.google.api.client.googleapis.auth.oauth2.GoogleCredential
I can see that the above class file is present in my reference libraries still the code is not running. Trying to solve this from 2 days. Please help
A: I think you should drop these jars in a folder named /libs at the root of your project. See this SO question: How can I use external JARs in an Android project?
A: Have you included your libs in the java build path and checked it in the Order and Export Tab?
i.e
Project > Properties > Java Build Path > Order and Export > and finally, checkmark your imported library.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/13063485",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Screenshots not found in HTML Publisher report after Jenkins build In my index.html file the embedded screenshots are not displayed when using Jenkins with HTML Publisher plugin. The screenshots are shown only when running my tests locally.
In the index.html file shown in the HTML Publisher plugin when I click on one of the embedded empty screenshots I'm getting:
HTTP ERROR 404
Problem accessing /var/lib/jenkins/workspace/my_test/target/surefire-reports/Wed_Jan_23_14_33_19_UTC_2019.png. Reason:
Not Found
I have verified the screenshots get generated every time in this exact path. This is my code to set the screenshot location:
public void takeScreenshotMyOwn() {
File scrFile = ((TakesScreenshot)getDriver()).getScreenshotAs(OutputType.FILE);
try {
String reportDirectory = new File(System.getProperty("user.dir")).getAbsolutePath() + "/target/surefire-reports/";
File destFile = new File( reportDirectory + screenshotFileName());
FileUtils.copyFile(scrFile, destFile);
Reporter.log( htmlNewLine + htmlNewLine + "<a href='" + reportDirectory + destFile.getName() + "'> <img src='" + reportDirectory + destFile.getName() + "' height='200' width='340'/> </a>"+htmlNewLine);
} catch (IOException e) {
e.printStackTrace();
Reporter.log("Failed to create screenshot");
Reporter.log(e.getMessage());
}
}
What am I doing wrong? I have searched all over and haven't found a solution that works.
A: I'm still looking for a more elegant answer but with the help of a developer I was able to create an external folder on our Apache server to store the images and link to them. Then I added parameters to our Jenkins server to alter the security policy and restarted. The screenshots are now showing up.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/54330073",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: why does Scala function accepts case class type for a function argument? Consider the code block.
class Evaluation {
def evaluate= {
println("Charlie...")
}
}
case class Dept(name:String) extends Evaluation
def depEval(name:String,f:(String) => Evaluation) ={
println(name)
f(name).evaluate
}
depEval("abc", Dept)
Why does Dept can be passed as a Funtion1 type? Is it that, Scala does not checks for the type before resolving the arguments.
Consider other snippet
def matchingCase(f: String => Evaluation)= {
println(f.toString())
f match {
case Dept => println("function type matched")
}
}
matchingCase((x: String)=> Dept(x))
Whereas in the above code scala gives a match error, as expected.
A: The companion object of a case class extends FunctionX[T1, T2, <CaseClass>] so that you can use it to construct instances of the case class.
So, for example, if you have a case class
case class Foo(i: Int, s: String)
the compiler will generate a companion object
object Foo extends (Int, String) ⇒ Foo with Product2[Int, String] {
def apply(i: Int, s: String) = new Foo(i, s)
// and some other stuff such as equals, hashCode, copy
}
This allows you to construct an instance of Foo like this:
Foo(42, "Hello")
instead of
new Foo(42, "Hello")
So, to conclude: the reason, why you can pass the Dept companion object as a function is because it is a function.
A: Dept is not a "case class type", it's the companion object for the case class. It extends Function1 (and has .apply method, that's part of the interface), so you can use it wherever a function is expected.
The second snipped fails because { x => Dept(x) } is it's own anonymous function, not Dept object.
A: It has a lot of sense, because if you just give as paramenter Dept it will behave ass a function that takes a String as parameter, and return an instance of the class Dept, meaning a Dept object (It is like give the new or apply function as parameter), look that the following code is valid also:
val c: Dept.type = Dept
val dep = c("Name1")
dep
res1: Dept = Dept(Name1)
dep.evaluate
Charlie...
res2: Unit = ()
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/47982061",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Sender address rejected I'm trying to use PHPMAILER, but I keep getting:
SMTP -> FROM SERVER:220 smart6.bol.com.br ESMTP
SMTP -> FROM SERVER: 250-smart6.bol.com.br 250-PIPELINING 250-SIZE 13312000 250-VRFY 250-ETRN 250-AUTH LOGIN PLAIN 250-AUTH=LOGIN PLAIN 250 8BITMIME
SMTP -> FROM SERVER:250 Ok
SMTP -> FROM SERVER:553 : Sender address rejected: not owned by user X
SMTP -> ERROR: RCPT not accepted from server: 553 : Sender address rejected: not owned by user deltrem1984@bol.com.br
SMTP Error: The following recipients failed: deltrem1984@bol.com.br
What should I do?
A: Often for anti-spam purposes, "$mail->From" is required to be the same address as you use for login to your SMTP server.
If that is your case, you can use the "$mail->AddReplyTo" field for the senders address instead. Only a suggestion.
If it is not the solution, some extra debugging information can be enabled by setting
$mail->SMTPDebug = true;
A: You should also be careful about email address aliases, because your SMTP server may be rejecting your mails for that reason (it depends on server configuration).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/1022472",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: How this space generate in this flex layout I want to use flex layout to do a navigation.I have 4 li in a ul tag. I want them side by side.But when I use flex layout.There are some place not use.
How can I delete the green part.
this is my html code.
<nav class="nav active" id="nav">
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">Works</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Contact</a></li>
</ul>
<button>
<div class="line line1"></div>
<div class="line line2"></div>
</button>
</nav>
this is my css code
nav {
background-color: #fff;
padding: 10px;
display: flex;
align-items: center;
border-radius: 3px;
-webkit-border-radius: 3px;
-moz-border-radius: 3px;
-ms-border-radius: 3px;
-o-border-radius: 3px;
box-shadow: 1px 2px 4px rgba(0, 0, 0, 0.1);
}
nav ul {
list-style: none;
display: flex;
flex-direction: row;
align-items: center;
justify-content: center;
width: 0;
opacity: 0;
font-size: 1.2rem;
margin: 10px;
}
nav.active ul {
opacity: 1;
width: 100%;
}
nav ul li a {
text-decoration: none;
color: #000;
margin: 0px 10px;
}
A: This happens because the ul has a default padding-inline-start of 40px.
Adding a padding: 0px to the nav ul selector would fix the issue.
You can see that default value in Chrome Dev Tools, as you can see in the bottom right of this screenshoot
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73837370",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Consuming JSON-RPC web services in .NET A business partner has suggested building a web services library with JSON-RPC rather that SOAP. (note they are not building in .NET necessarily, but I am)
I am a potential consumer of this data.
I've used JSON for client-based Ajax calls in the past, but this web services library will be used primarily for server-side calls and syncing large amounts of data.
I don't have much experience with JSON-RPC.
Questions:
*
*Can I easily build a JSON-RPC
consumer in .NET?
*Are JSON-RPC web services self
documenting and discoverable, like a
SOAP WSDL?
*Can I easily add a Web Reference in
Visual Studio to a JSON-RPC web service?
Thanks
A:
Can I easily build a JSON-RPC consumer
in .NET?
Yes. JSON-RPC services are simple to consume as long as you have a robust JSON parser or formatter. Jayrock provides a simple client implementation JsonRpcClicnet that you can use to build a consumer. There is also a small demo sample included.
Are JSON-RPC web services self
documenting and discoverable, like a
SOAP WSDL?
No, there is nothing standardized but there are ideas being floated around like Service Mapping Description Proposal.
Can I easily add a Web Reference in
Visual Studio to a JSON-RPC web
service?
This can work if the server-side implementation provides a WSDL-based description of the JSON-RPC service but none are known to provide this to date.
A: Check out Jayrock.
Jayrock is a modest and an open source
(LGPL) implementation of JSON and
JSON-RPC for the Microsoft .NET
Framework, including ASP.NET. What can
you do with Jayrock? In a few words,
Jayrock allows clients, typically
JavaScript in web pages, to be able to
call into server-side methods using
JSON as the wire format and JSON-RPC
as the procedure invocation protocol.
The methods can be called
synchronously or asynchronously.
A:
Can I easily build a JSON-RPC consumer in .NET?
Shouldn't be difficult as long as you know what you're doing.
Are JSON-RPC web services self documenting and discoverable, like a SOAP WSDL?
Discoverable yes, documenting in as much as you can get function names and parameter lists. (not entirely sure what you're asking for as far as documentation goes).
Can I easily add a Web Reference in Visual Studio to a JSON-RPC web service?
I don't think so, no. (Though, I have no idea, it's possible. My experience with JSON-RPC is in PHP/JS mostly)
Relevant links:
*
*http://json-rpc.org/wiki/specification
*http://json.org/
*http://techblog.procurios.nl/k/618/news/view/14605/14863/How-do-I-write-my-own-parser-for-JSON.html
A: Maybe you could have a look at json-wsp which is much like json-rpc but with a discription specification. It is implemented as an interface in Ladon for python.
http://pypi.python.org/pypi/ladon
A: I have some sample Json-Rpc 2.0 clients for .net and windows phone 7 in the Json-RPC.NET sources.
Check them out: .Net Client and WP7 Client
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/1061788",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: SQL syntax error manual check For the code below I get the error
You have an error with your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Name','Score') VALUES('cain','0') at line 1
private void btnSubmitScore_Click(object sender, EventArgs e)
{
string connStr = "server=bel.sunderland.ac.uk; " +
"database=bg30xw; " +
"uid=USERNAME; " +
"pwd=PASSWORD;";
string query = "INSERT INTO highscore('Name','Score') VALUES (@Name, @Score);";
using(MySqlConnection myconn = new MySqlConnection(connStr))
{
Console.WriteLine(query);
MySqlCommand insertCommand = new MySqlCommand(query,myconn);
insertCommand.Parameters.AddWithValue("@Name",sName);
insertCommand.Parameters.AddWithValue("@Score",iTotalScore);
try
{
myconn.Open();
insertCommand.ExecuteNonQuery();
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message);
}
myconn.Close();
}
The error showed up in the 'messagebox.show(ex.message);' when I ran the program. I looked on google but most of the suggestions was for quotation marks, I have changed and re-changed them but to no avail.
Thanks
A: Use backticks to escape column (and table) names, not quotes
INSERT INTO highscore(`Name`,`Score`) VALUES (@Name, @Score)
A: Single-word column names don't need to be escaped (I don't think MySQL allows it, but I may be wrong);therefore, this should work:
INSERT INTO highscore(Name,Score) VALUES (@Name, @Score);
You may give an alias to a column, using spaces when you run a select statement, but I simply avoid them in general.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/15417590",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Integrations skype and facebook messenger not responding with fulfillmenttext except for google assistant app, all of my integrations are responding with static default response instead of custom fulfillment that i hosted on my server.
i already checked request and response json from dialogflow to my server, they are fine... when i make request from skype, the response from my server does have the custom fulfillment message but instead the skype is showing static response for skype that i wrote i the default text message tab for my intent. please let me know what i need to do. thanks
Expected Conversation through (Skype)
User: some words in english
Agent(From Fulfillment): English, this is response is for english
Actual Conversation i am getting:
User: some words in english
Agent(from dialogflow static text response): Hello.. i am default response from skype
Note this is only happening in facebook messenger, skype(these are the only integrations i've enabled) but not on dialogflow simulator and actions on google simulator.
I think this problem is from dialogflow end because both facebook messenger and skype produce the same behavior
const express = require('express')
const bodyParser = require('body-parser')
const {dialogflow,
Permission,
Suggestions,
Carousel,
BrowseCarouselItem,
BrowseCarousel,
Image,}= require('actions-on-google')
const request = require('request')
const dialogflowapp = dialogflow()
const app = express()
app.use(bodyParser.json())
app.set('port', (process.env.PORT || 5000))
const LANGUAGE_INTENT = 'Languages';
const LANGUAGE_TYPE_ENTITY = 'LanguageType';
dialogflowapp.intent(LANGUAGE_INTENT, (conv) => {
const quote_type = conv.parameters[LANGUAGE_TYPE_ENTITY].toLowerCase();
if (quote_type === "telugu") {
conv.ask("Telugu, This response is for telugu");
} else if (quote_type === "english") {
conv.ask("English, this is response is for english");
} else if (quote_type === "hindi") {
conv.ask("Hindi, this response is for Hindi");
} else {
conv.ask("Cann't understand bro");
}
});
dialogflowapp.catch((conv, error) => {
console.error(error);
conv.ask('Something went wrong!');
});
app.post('/webhook',(req,res, next)=>{
console.log(req.body);
next();
}, dialogflowapp);
app.listen(app.get('port'), function () {
console.log('* Webhook service is listening on port:' + app.get('port'))
A: The issue is that you're using the actions-on-google library for fulfillment, which only creates results that are valid on the Google Assistant.
If you want to send back a reply that is valid for other Dialogflow integrations, you will need to use the dialogflow-fulfillment library.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/54107434",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: javaOptions with sbt docker:publishLocal and docker run If I was running my application sans Docker, I would do something like this:
./myapp -Dconfig.file=conf/application.prod.conf -Dlogger.resource=logback.prod.xml
In fact, I can do even better and put them into by build.sbt file:
// Production Mode
javaOptions in Production ++= Seq(
"-Dconfig.file=conf/application.prod.conf",
"-Dlogger.resource=logback.prod.xml"
)
and then they will be applied when I run my app:
./myapp # options now applied via build.sbt
When I build my app with sbt docker:publishLocal, then run it with docker run, the javaOptions do not take effect.
How can I get these javaOptions to take effect when I docker run ?
A: Found a work-around answer. You can set the dockerEntrypoint like so:
// build.sbt
dockerEntrypoint := Seq("bin/myapp", "-Dconfig.file=conf/application.prod.conf", "-Dlogger.resource=logback.prod.xml")
A: javaOptions can be supplied to sbt-native-packager with
javaOptions in Universal ++= Seq(
// -J params will be added as jvm parameters
"-J-Xmx2048m",
"-J-Xms256m"
)
Note that these options will be applied to all generated packages (Debian, Rpm, etc.), not just Docker. See the discussion here.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/39401111",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Importance of filenames when issuing CSR & key file for X.509 certificate I have one confusion while generating CSR and key file.
My domain name is like www.abc.example
I have to run command like that on terminal:
openssl req -new -newkey rsa:2048 -nodes -keyout abc.key -out abc.csr
or
openssl req -new -newkey rsa:2048 -nodes -keyout abc.example.key -out abc.example.csr
?
A: The filenames have no consequences on the result, you can name them whatever you want.
Even the extensions are just conventions to make human life simpler.
You just need to make sure of course that all applications using them will use their proper name.
My personal advice would be to use the full domain name in the filename, especially if you have to maintain many different certificates (in which case you may need to handle certificates for both example.com and example.net at the same time if they are two different certificates, you will need the TLD in the filename to discriminate between them).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/52074886",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: vault helm chart: Enable prometheus metrics How does one enable prometheus metric collection in Hashicorp Vault when deployed via the helm chart?
A: Figured it out. You need to add things like 'telemetry' (and other configuration stanzas) to the server.ha.config data structure in your values.yaml. This will push changes to vault's configmap. You then bounce all vault nodes and you're good-to-go!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/60715117",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Kernel compilation fails due to PF_MAX > 44 I have a QEMU VM running an image of the Linux kernel 4.14.78.
On the host machine (a server with 96 cores), I am trying to compile a new update for the kernel with some changes I have made.
To make this process faster, I was using the host machine to compile for the target VM.
To do that I follow these steps:
*
*copy the /boot/config-4.14.78 file from VM to host
*put the copied file into the kernel source-code root directory, renaming it to .config in my
*run make clean to clean it
*run make menuconfig just to update the configs
*run make -j$(nproc)
However, I am getting this error:
AS arch/x86/purgatory/setup-x86_64.o
CC arch/x86/purgatory/sha256.o
AS arch/x86/purgatory/entry64.o
CC arch/x86/purgatory/string.o
In file included from scripts/selinux/mdp/mdp.c:49:
./security/selinux/include/classmap.h:245:2: error: #error New address family defined, please update secclass_map.
245 | #error New address family defined, please update secclass_map.
| ^~~~~
make[3]: *** [scripts/Makefile.host:102: scripts/selinux/mdp/mdp] Error 1
make[2]: *** [scripts/Makefile.build:587: scripts/selinux/mdp] Error 2
make[2]: *** Waiting for unfinished jobs....
In file included from scripts/selinux/genheaders/genheaders.c:19:
./security/selinux/include/classmap.h:245:2: error: #error New address family defined, please update secclass_map.
245 | #error New address family defined, please update secclass_map.
| ^~~~~
CHK scripts/mod/devicetable-offsets.h
make[3]: *** [scripts/Makefile.host:102: scripts/selinux/genheaders/genheaders] Error 1
make[2]: *** [scripts/Makefile.build:587: scripts/selinux/genheaders] Error 2
make[1]: *** [scripts/Makefile.build:587: scripts/selinux] Error 2
make[1]: *** Waiting for unfinished jobs....
I have checked what causes this, and turns out that it is because of the:
include/linux/socket.h:211:#define AF_MAX 44 /* For now.. */
include/linux/socket.h:260:#define PF_MAX AF_MAX
Then, I followed this solution to print out the definition of PF_MAX at preprocessing time, and turns out that the PF_MAX is 45:
In file included from scripts/selinux/mdp/mdp.c:49:
./security/selinux/include/classmap.h:247:9: note: #pragma message: 45
247 | #pragma message(STRING(PF_MAX))
| ^~~~~~~
./security/selinux/include/classmap.h:250:2: error: #error New address family defined, please update secclass_map.
250 | #error New address family defined, please update secclass_map.
| ^~~~~
This 45 makes no sense for me, because I just checked that it is supposed to be 44.
I wonder if the build is considering the host machine instead of the target?
P.S.: These steps works fine on my local machine, which is a 8-cores machine, look the kernel version:
uname -a
Linux campes-note 5.4.86 #1 SMP Fri Jan 1 16:26:25 -03 2021 x86_64 x86_64 x86_64 GNU/Linux
UPDATE 1:
I tried to compile the kernel without any of my changes, following th above steps mentioned, and it did not compile as well, I get the same error.
UPDATE 2:
I found out that somehow, the compilation is looking at the host /usr/src/linux-headers-x.x.x files.
Instead, it should point to the same version as the target.
For that, I tried to follow this tutorial but I did not success. I am having a problem in one of the steps stated on this tutorial.
A: (Gathered from the now removed comments)
I have tried myself to build myself v4.14.78 followed by the latest available v4.14.214. I have found that former fails while the latter builds. So, I have bisected down to v4.14.116 that first builds correctly. Then I simple looked into the changes and found commit 760f8522ce08 ("selinux: use kernel linux/socket.h for genheaders and mdp") in the Linux stable tree which fixes the issue.
You may try to cherry-pick it to your branch and compile again.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/65672033",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Selecting multiple objects using the hitbox when drawing a box in konvajs I'm currently trying to select multiple objects (specifically lines) and adding them to a Group/Transformer by drawing a box. To do this, I followed this very helpful stackoverflow question.
After implementing it, I wasn't really happy with the results because I needed to check the entire list of shapes every time I drew the box even if I didn't pass through a shape.
In an attempt to find a solution to this problem, I thought that there might be a way for a line to know it had collided with the box being drawn. However, I have not been lucky to find out something similar to what I'm trying to reproduce. Is there an example or a way for me to draw a box to select multiple objects when they collide with the box?
A: Checking every shape in the stage is the only way to check intersections.
If you need some optimizations you can try debouncing or throttle strategies.
E.g. check interactions every 100ms instead of every mousemove or touchmove events.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/62908440",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: TypeScript types based on capitalization of a key Trying to add types to an existing JS library I'm using. The library unfortunately has a rule that the type of the value in an object is somewhat determined by the capitalization of the first letter of its associated key. I thought something like the below might work, but it does not.
type UppercaseLetters = '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';
type LowercaseLetters = Lowercase<UppercaseLetters>;
type RefKey = `${UppercaseLetters}${string}`
type PropKey = `${LowercaseLetters}${string}`
// Define these types just so it compiles
type SomeRefType = number;
type SomePropType = boolean;
type Spec = {
type: string
} & {
[s in RefKey]: SomeRefType
} & {
[s in PropKey]: SomePropType
};
This compiles, but the actual type that Spec becomes is:
type Spec = {
type: string;
} & {} & {}
Any ideas out there? Perhaps this case is just too out of the left field for TypeScript to handle.
Example object:
const specObj: Spec = {
type: 'Some string',
Apple: 3,
Orange: 6,
lowerCaseKey: false,
anotherOne: true
}
A: As noted by Alateros in the comments, since typescript@4.4 you can use index signatures for template literals.
Though you still have to ensure type field must be required and may have the type that is not compatible with lowercased keys type. So you may write Spec type like that:
type Spec = {
[K in RefKey | PropKey]: 'type' extends K
? string
: K extends RefKey
? SomeRefType
: K extends PropKey
? SomePropType
: never
} & {
type: string
}
playground link
A: I removed
type RefKey = `${UppercaseLetters}${string}`
type PropKey = `${LowercaseLetters}${string}`
and replaced with UppercaseLetters and LowercaseLetters types
Is it what are you looking for?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/68165564",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Html, auth. Getting cookies I'm not quite sure how it works but what I need to do is authenticate with JSON-RPC and then request a page. I have this code to find out if the username and password is right but I don't know how to use this information to request a page..
List<Cookie> cook;
public void postData(String method, Object ... params) throws JSONException {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.examp;e.com/json-rpc/");
try {
// Add your data
String methodandp = "{id:3, method:" + method + ", params:[" + params[0].toString()+ ", " + params[1].toString() + "]}";
StringEntity a = new StringEntity(methodandp);
httppost.setEntity(a);
Log.i("ClientActivity: request", httppost.getMethod().toString());
Log.i("ClientActivity: request", nameValuePairs.toString());
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
Header[] head = response.getAllHeaders();
Log.i("ClientActivity", response.getStatusLine().toString());
String responseString = EntityUtils.toString(response.getEntity());
responseString = responseString.trim();
JSONObject jsonResponse = new JSONObject(responseString);
Log.i("ClientActivity", jsonResponse.toString());
String cookie = "";
for(int i = 0; i < head.length; i++){
Log.i("ClientActivity: response", head[i].toString());
if(head[i].toString().contains("Set-Cookie")){
cookie = (head[i].toString()).replace("Set-Cookie: ", "");
cook = ((AbstractHttpClient) httpclient).getCookieStore().getCookies();
if (cook.isEmpty()) {
System.out.println("None");
} else {
for (int x = 0; x < cook.size(); x++) {
Log.i("ClientActivity", "-" + cook.get(x).toString());
}
}
Log.i("ClientActivity: Cookie", cookie);
}
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
It comes back with successful and with all the right data but I dont know how to use it.
A: This was actually really simple now that I look at it, once I have verified that I was authenticated I could use the same HttpClient (that holds the cookies) to request other files and push files to the web server using MultipartEntity
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/10150268",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Javascript ArrayBuffer equivalent in Swift or iOS I want to know what is the Javascript ArrayBuffer equivalent in Swift or ios.
Basically I have a Swift struct that I want to store as a blob (data stored based on memory layout) and pass this blob to Javascript ArrayBuffer where I can , based on defined set layout extract data from ArrayBuffer
I havent yet managed to save the struct from Swift as a binary/memory blob. Struggling to understand the memory layout configuration. I thought it would be similar to structs in C but they are not.
Any help or pointers would be appreciated. Thanks.
A: I'm not an expert in Javascript, so I may be talking nonsense.
It seems like you can achieve what you want if your struct S implements the Codable protocol. Then you can transform it to a Data blob using an encoder, like this:
let encoder = JSONEncoder()
do {
let data = try encoder.encode(s)
// do what you want with the blob
} catch {
// handle error
}
And back to S, like this:
let decoder = JSONDecoder()
do {
let s = try decoder.decode(S.self, from: data)
} catch {
// handle error
}
If S is Codable, [S] (an Array<S>) will also be Codable.
You can probably pass the data to your scriptas a String, then you'll have to transform your data do string with JSONSerialization
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/54751766",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Django One-Click Install Image on Digital Ocean So i am trying to follow this tutorial about How To Use the Django One-Click Install Image to deploy my Django 1.7 project in a Digital Ocean Droplet but i am running into some problems.
Basically if i do python manage.py runserver 0.0.0.0:9000 everything works fine, but when trying to use it with Gunicorn i get a
ImproperlyConfigured: Requested setting CACHES, but settings are not
configured. You must either define the environment variable
DJANGO_SETTINGS_MODULE or call settings.configure() before accessing
settings.
my gunicorn.conf is:
description "Gunicorn daemon for Django project"
start on (local-filesystems and net-device-up IFACE=eth0)
stop on runlevel [!12345]
# If the process quits unexpectadly trigger a respawn
respawn
setuid django
setgid django
chdir /home/django
exec gunicorn \
--name=bla \
--pythonpath=bla \
--bind=127.0.0.1:9000 \
--config /etc/gunicorn.d/gunicorn.py \
bla_api.wsgi:application
my wsgi is:
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "bla_api.settings.production")
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
Any ideas?? i tried export DJANGO_SETTINGS_MODULE=bla_api.settings.production with no luck
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/29560364",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to set include_directories from a CMakeLists.txt file? I seem to be having trouble setting the include path (-I) using the include_directories() command in CMake. My project directory is as follows:
Root
| - CMakeLists.txt
| - libs
| - | - CMakeLists.txt
| - | - inc
| - | - | - // lib specific includes
| - | - src
| - | - | - // lib specific sources
| - proj1
| - | - CMakeLists.txt
| - | - inc
| - | - | - // proj1 specific includes
| - | - src
| - | - | - // proj1 specific sources
The root CMakeLists.txt file looks like so:
project(ROOT)
add_subdirectory(libs)
add_subdirectory(proj1)
The CMakeLists.txt file under libs:
project(lib)
add_library(lib STATIC ${lib_hdrs} ${lib_srcs}) // for conciseness, omitted set()
And lastly, the CMakeLists.txt file under proj1:
project(proj1)
include_directories("${ROOT_SOURCE_DIR}/lib/inc") # <- problem line?
add_executable(proj1 ${proj1_srcs})
target_link_libraries(proj1 lib)
The goal is to create the library from the source and header files in libs, then link against the executable generated under proj1. Proj1 has some files that #include stuff in libs include, so I need to add the directories to be used with -I. Based on the documentation, that's what include_directories() is supposed to do. However despite explicitly setting that and following it with a debug message(${INCLUDE_DIRECTORIES}), the INCLUDE_DIRECTORIES variable is an empty string, and no directories are specified for the include path, so my compilation of proj1 fails.
I've also attempted removing the quotes around ${ROOT_SOURCE_DIR}/inc to see if that helped but no luck.
A: include_directories() populates a directory property called INCLUDE_DIRECTORIES:
http://www.cmake.org/cmake/help/v2.8.12/cmake.html#prop_dir:INCLUDE_DIRECTORIES
Note that CMake 2.8.11 learned the target_include_directories command, which populates the INCLUDE_DIRECTORIES target property.
http://www.cmake.org/cmake/help/v2.8.12/cmake.html#command:target_include_directories
Note also that you can encode the fact that 'to compile against the headers of the lib target, the include directory lib/inc is needed' into the lib target itself by using target_include_directories with the PUBLIC keyword.
add_library(lib STATIC ${lib_hdrs} ${lib_srcs}) # Why do you list the headers?
target_include_directories(lib PUBLIC "${ROOT_SOURCE_DIR}/lib/inc")
Note also I am assuming you don't install the lib library for others to use. In that case you would need to specify different header directories for the build location and for the installed location.
target_include_directories(lib
PUBLIC
# Headers used from source/build location:
"$<BUILD_INTERFACE:${ROOT_SOURCE_DIR}/lib/inc>"
# Headers used from installed location:
"$<INSTALL_INTERFACE:include>"
)
Anyway, that's only important if you are installing lib for others to use.
After the target_include_directories(lib ...) above you don't need the other include_directories() call. The lib target 'tells' proj1 the include directories it needs to use.
See also target_compile_defintions() and target_compile_options().
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/19460707",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
}
|
Q: Can't import an eclipse project into android studio? I am trying to learn android in android studio.Now i imported an eclipse project in android studio and now while trying to run it it is not building.Some problems in gradle may be..
Error:Execution failed for task ':app:processDebugManifest'.
Manifest merger failed : uses-sdk:minSdkVersion 8 cannot be smaller than version L declared in library com.android.support:support-v4:21.0.0-rc1
my build.gradle
apply plugin: 'android'
android {
compileSdkVersion 19
buildToolsVersion "19.1.0"
defaultConfig {
applicationId "com.example.practise"
minSdkVersion 8
targetSdkVersion 19
}
buildTypes {
release {
runProguard false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
}
}
}
dependencies {
compile 'com.android.support:support-v4:+'
compile 'com.android.support:gridlayout-v7:+'
}
Can anyone help me to find out the problem??
A: Change your dependencies
dependencies {
compile 'com.android.support:support-v4:19.1.0'
compile 'com.android.support:gridlayout-v7:19.1.0'
}
Using the +, you are getting the last release.
Currently the last release is the compile 'com.android.support:support-v4:21 and it has a minSdk='L' because it is a preview release.
Use it only to test the android 'L' preview.
A: Try editing the following line to your Android Manifest file, like so:
dependencies {
compile 'com.android.support:support-v4:21+'
}
Then your project should build.
A: Change your dependencies in app/build.gradle to lower version
apply plugin: 'com.android.application'
android {
compileSdkVersion 20
buildToolsVersion "20.0.0"
defaultConfig {
applicationId "com.eusecom.snowsmsden"
minSdkVersion 16
targetSdkVersion 20
}
buildTypes {
release {
runProguard false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
}
}
}
dependencies {
compile 'com.android.support:support-v4:20.+'
compile 'com.android.support:appcompat-v7:20.+'
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/25813712",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Environment Variables for storing instance data I think that this is a dumb question about Env Variables in node js.
My question is, is it ok to dynamically set env variables , for example when the user starts a session. Let's say that I want to store a user's email which will be stored in a env variable and will be used in other parts of the website (Let's say the application can't access the user's email using any other method) .
Will this interfere with the way node works and mess up my users experience
Any help is appreciated
A: I figured it out. The answer is no.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/50665416",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to set this css only works for specified class? Given the following markup:
<div class="my_class"></div>
and and the following css:
.sidebar .nav { width: 95%; }
.sidebar-nav{ left: -200px; }
.sidebar-nav.active{ left: 0; }
How can I make the above styles apply only for children on the my-class class?
A: It is my understanding that you want the following css to only apply to children of .my_class.
If so, please change your css to this:
.my-class .sidebar .nav { width: 95%; }
.my-class .sidebar-nav{ left: -200px; }
.my-class .sidebar-nav.active{ left: 0; }
Note that if you have any sidebar or sidebar-nav outside your my-class they won't be getting the above styles.
Check out Specificity on MDN.
A: .my-class .sidebar .nav { width: 95%; }
.my-class .sidebar-nav{ left: -200px; }
.my-class .sidebar-nav.active{ left: 0; }
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/42154407",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Flurl and untrusted certificates Currently I worked on Flurl and I tried to contact an API in https (I am in my lab).
So the certificate is not valid and Flurl can't continue to work :/
Here is my error message:
Unhandled Exception: System.AggregateException: One or more errors occurred. (Call failed. The SSL connection could not be established, see inner exception. POST https://IP/api/aaaLogin.json) ---> Flurl.Http.FlurlHttpException: Call failed. The SSL connection could not be established, see inner exception. POST https://IP/api/aaaLogin.json ---> System.Net.Http.HttpRequestException: The SSL connection could not be established, see inner exception. ---> System.Security.Authentication.AuthenticationException: The remote certificate is invalid according to the validation procedure.
In Flurl documentation we can use using Flurl.Http.Configuration; and modify the DefaultHttpClientFactory However I do not understand the elements specified to say of jumped over the errors.
On the web I can see the same case: https://github.com/tmenier/Flurl/issues/365
Do you have an issue for this problem?
Thank you!
A: Here is my setup for Flurl, which works with untrusted certificates:
HttpClientHandler httpClientHandler = new HttpClientHandler();
httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain,
errors) => true;
HttpClient httpClient = new HttpClient(httpClientHandler);
httpClient.BaseAddress = new Uri("https://myaddress.com");
var flurlClient = new FlurlClient(httpClient);
var apiInfo = await flurlClient.Request("apiInfo").GetJsonAsync<ApiInfoDto>();
I have created custom HttpClientHandler which accepts every certificate in ServerCertificateCustomValidationCallback. Of course, you can use other logic in this handler.
Update:
With this setup, you cannot use Flurl extensions for URL (you cannot write "http://myadress.com/apiInfo".GetJsonAsync<ApiInfoDto>().
You have to create Flurl client as seen above and use Flurl client for your calls as demonstrated also in mine code. The usage is the same as Flurl extensions for URL.
A: An inline solution to accept any certificate is:
var myString = await "https://some-server-with-an-invalid-cert.net"
.AppendPathSegment("/some-file.txt")
.WithClient(new FlurlClient(new HttpClient(new HttpClientHandler
{
ServerCertificateCustomValidationCallback = (message, cert, chain,
errors) => true
})))
.GetStringAsync();
With WithClient() you can pass a client configured different than the default client. In some cases you would not want to change the default client, but apply properties, e.g. the certificate validation only to this specific case.
A: The most typical way to do this is to create a custom factory:
public class UntrustedCertClientFactory : DefaultHttpClientFactory
{
public override HttpMessageHandler CreateMessageHandler() {
return new HttpClientHandler {
ServerCertificateCustomValidationCallback = (_, _, _, _) => true
};
}
}
Then register it somewhere in your app startup:
FlurlHttp.ConfigureClient("https://theapi.com", cli =>
cli.Settings.HttpClientFactory = new UntrustedCertClientFactory());
Flurl reuses the same HttpClient instance per host by default, so configuring this way means that every call to theapi.com will allow the use of the untrusted cert. The advantage of this over passing an HttpClient to a FlurlClient constructor is that it keeps this configuration "off to the side" and works when you use Flurl in the more typical/less verbose way:
await "https://theapi.com/endpoint".GetJsonAsync();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/53853081",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
}
|
Q: Visual Studio Team Services creates commit on pull request I have three branches master, dev and feature1 (gitflow process). dev and master have branch policies applied (minimum of 2 reviews) so cannot be committed to directly or merged to. Standard setup right? I make some commits to the feature1 branch. I create and complete a pull request to get the commits from feature1 into dev. I then create and complete a pull request to get the changes from dev into master. VSTS now tells me that dev is behind master. I can't merge master into dev due to the policies.
This is the state of my branchesafter four pull requests from dev into master.
What can I do?
As suggested by Tim Biegeleisen, I have attempted to merge dev into master but am unable to do so due to the branch policies.
Merge dev into master
Commits are ready to be pushed to dev
Sync fails due to policies
Error encountered while pushing to the remote repository: rejected dev -> dev (TF402455: Pushes to this branch are not permitted; you must use a pull request to update this branch.)
A: Nothing you described struck me as anything out of the ordinary. You could easily end up in this situation if, for example, others had made some commits to master since the last time dev had synched with that branch.
The two typical ways to resolve this are merging and rebasing. Let's consider merging, because it is probably the strategy you are already using, and it is more succinct to describe. You could resolve this situation by first merging master into your dev branch. Then, open a pull request back into master from dev, if one does not already remain open. Have your reviewers sign off on it, and then the pull request should go through.
The key step here is merging master into your dev branch. After this operation, Git should not longer be telling you that dev is behind master.
A side note: Technically speaking, master itself was also behind dev. Actually, both branches were mutually behind the other party, because each has new commits since the last time they both synched.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/47938940",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Calling notes URL from a web page with query string parameters in URL We have a web page with links to Notes client. We can open existing document easily or create a new one with syntax: notes://localhost/__A92574C800517FC7.nsf/company?OpenForm Is there a way how to, in notes client, ready query string parameters provided in URL like this: notes://localhost/__A92574C800517FC7.nsf/company?OpenForm¶m1=value . We tried a common ways like using @UrlQueryString("param1") in the form but no luck. Is there any otheroption for doing this?
A: Could you see what happens (not sure here...) when you add a text-field xyz to the form and use a notes-url like notes://localhost/__A92574C800517FC7.nsf/company?OpenForm&xyz=something ?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72085767",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: save disabled on sitecore page editor I'm been working with Sitecore for a while, but this is my first time on the page editor.
So, I go to my sublayout and I place a sitecore tag instead a .net tag
<sc:Text ID="txtContent" Field="Content" runat="server"/>
Content is the normal content field on the sitecore page.
When I go to the page editor, I'm able to see the correct content and do some editing but the save button is disabled and my changes are not saved at all
I'm I missing something very basic here?
this is a screen cast on what I'm doing
http://screencast.com/t/0itqgjGVQx8
Update: After including jquery.noconflict constructs, the execution moves to the handler function in the ribbon correctly. BUT it seems that the button itself is disabled. Is it possible to enable/disable the button? is it disable on specific situations? if so how can I enable it.
A: There might be invalid html appearing. Check you hints for buttons, etc. There might be non-escaped texts on the page.
A: I've resolve this some time ago... in the sublayout definition on sitecore there was a redundant/wrong compatible rendering definition. Once I removed that, the save button appeared and the sublayout started to work as expected
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/14899659",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: What does cmp %eax,0x80498d4(,%ebx,4) mean? I know there are some other questions similar to this, but I'm still having trouble understanding the () part of it. Could someone spell this syntax out for me? Thanks.
A: cmp %eax,0x80498d4(,%ebx,4)
cmp is the comparison assembly instruction. It performs a comparison between two arguments by signed subtracting the right argument from the left and sets a CPU EFLAGS register. This EFLAGS register can then be used to do conditional branching / moving, etc.
First argument: `%eax (the value in the %eax register)
Second argument: 0x80498d4(,%ebx,4). This is read as offset ( base, index, scale ) In your example, the value of the second argument is the memory location offset 0x80498d4 + base (which I believe defaults to zero if not included) + value in %ebx register * 4 (scaling factor).
Note: I believe base here is empty and defaults to the value 0.
You can take a look at http://docs.oracle.com/cd/E19120-01/open.solaris/817-5477/ennby/index.html for more information on the syntax for Intel x86 assembly instructions.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/28801983",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: __WFI() will not sleep even with all interrupts disabled and pending cleared - LPC18XX Series Background: I am trying to make my embedded application go to sleep when there is no CAN activity with the __WFI() and then wake up whenever a CAN interrupt is received. Before enterring sleep mode, I disable all interrupts and clear their pending states in the NVIC registers.
To start, right now I'm just trying to make sure that I can sleep forever when I have all interrupts disabled.
for(int i = 0; i < IRQ_MAX; i++)
{
IRQ_ClearPending((IRQ)i);
IRQ_Disable((IRQ)i);
}
__DSB();
__ISB();
__WFI();
MCU_Reset();
I checked the NVIC registers, and they are all set to 0, which should mean that all interrupts are disabled and there are no pending interrupts. However, everytime I execture the WFI (Wait for interrupt) instruction, it will just NOP on me.
Why can I not enter sleep mode? Do I actually have to somehow disable all of my peripherals and disable the interrupts at their source or is there a way to just mask all interrupts minus the CAN?
Thank you for your time. Let me know if there is anything I can do to clarify the question.
A: Check for imprecise external abort, which does not cause exception immediately.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/53242217",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Setting Mouse Cursor in WinformsHost I am working on a WPF application that has a WinformsHost element. I try to set the cursor
for the winforms host element, but this does not have any effect. I tried to use the ForceCursor property of the window, but this seems to be ignored completely.
In my sample window I have a WPF Textblock on the left with a Hand cursor which is used properly, but on the right side where I have a WinForms PropertyGrid, I get the same behavior.
<Window x:Class="WpfWinformsCursor.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:wf="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"
Title="MainWindow" Height="350" Width="525"
Cursor="ScrollAll"
ForceCursor="False"
>
<Grid Cursor="Pen">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid Grid.Column="0" Cursor="Help">
<TextBlock Cursor="Hand" />
</Grid>
<WindowsFormsHost Grid.Column="1" Cursor="ScrollNW">
<wf:PropertyGrid Cursor="Hand" />
</WindowsFormsHost>
</Grid>
</Window>
Can somebody help me how to do this correctly?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/18490782",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Visual studio and xamarin using c# releasing on mobile? I am making an android application using visual studio and xamarin using the c# language but when i copy the apk file to the mobile and after installing it doesn't open and give me the message: " unfortunately your app has been stopped " what can i do please i need to open it on mobile?
A: Most likely, you also need the mono runtime and all the support libraries that are needed.
Run your app once from the debugger (or at least deploy from within Visual Studio/Xamarin Studio), and you will
a) get a notice (in deploy output) about all the libraries/frameworks being installed before the app launches, this can actually take a minute before first launch
b) you have those supports installed for the future, so as long as you target the same framework version, you can simply directly install the .apks
Normally, you don't use .apks directly, since most often your first shot is not perfect anyway, so the debugging helps a lot. :)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/29680656",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Execute a form after System.exit (0); I'm trying to close all open forms with System.exit (0); And then call the loggin but I close the execution of the program.
Is there any way to close everything and then call the loggin?
Pd: translated with google translator xD
regards
private void cerrarSesion() {
JOptionPane.showMessageDialog(null, "Se cerrara el sistema", "Advertencia", JOptionPane.PLAIN_MESSAGE, warning);
System.exit(0);
frmLoggin lo = new frmLoggin();
lo.setVisible(true);
}
A: You should manually keep track of all "forms" in a list somewhere, then just iterate over that list and close them.
If for whatever reason this is not possible you could use JFrame.getWindows() which accesses all Windows in the application
for (Window each : JFrame.getWindows()) {
each.setVisible(false);
}
Note: This may not properly shutdown the forms, e.g. remove listeners/stop threads the forms may be using...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/45657153",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Rails 7 Adding an Other text field to a group of checkboxes for the same attribute to save as an array I am developing a Rails 7 application where I need to have an "Other" text field in addition to a group of checkboxes or radio buttons.
Right now I have the following for an array for the interests attribute:
%fieldset.border.border-dark.ps-4.pe-4.pt-4.mb-4
%legend What are your interests? You can select more than one. If one is not listed, please feel free to add others to the "Other interests" text field.
.row.mb-4
- camp_interests.each do |interest|
.col-md-4.d-grid.d-block.mb-2
= f.check_box :interests, { multiple: true, class: "btn-check" }, interest, false
= f.label :interests, interest, value: interest, class: "btn btn-outline-dark btn-lg text-start"
.form-floating.mb-4
= f.text_area :interests, placeholder: "Other interests", class: "border border-dark form-control", height: "100px", data:{controller: "textarea-autogrow"}
= f.label :interests, "Other interests"
The referenced method is in the helper:
def camp_interests
[
"Walking / hiking",
"Camping",
"Swimming",
"Socializing",
"Teambuilding",
"Tactile crafts",
"Boating",
"Yoga",
"Workshops",
"Special interest groups",
"Bingo",
"Adaptive biking"
]
end
Scenario 1: When you click on "Walking / hiking" and "Camping", but leave "Other interests" blank, and submit the form, you expect the interests attribute to have an array of ["Walking / hiking", "Camping"]. Actual result: interests attribute is saved as nil.
Scenario 2: When you leave all checkboxes options unchecked, and type into the Other Interests field, the interests attribute should have an array with the content from that field. So if Other Interests had "Dancing", you'd have an array of ["Dancing"]. Actual result, same as expected.
Now if I comment out the Other Interests block, and just have a group of checkboxes, if I click on "Walking / Hiking" and "Camping" and submit, the interests attribute has an array of ["Walking / hiking", "Camping"].
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/71490159",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: search with 2 field in generic api view Do you know how can I search with 2 fields with 'and' conditions?
I mean in the below code I need to search'search_fields' with symbol name and time_frame,(both conditions together not only one of them)
class RegisterSymbolViewSet(mixins.ListModelMixin, viewsets.GenericViewSet):
serializer_class = SymbolValidationSerializer
filter_backends = [filters.SearchFilter]
search_fields = ['^symbol','^time_frame']
queryset = RegisterSymbol.objects.all()
A: First of all DRF docs say that only text-based fields can be used as search field so if timeframe is DateField it will most likely not work.
The SearchFilter class will only be applied if the view has a
search_fields attribute set. The search_fields attribute should
be a list of names of text type fields on the model,
such as CharField or TextField.
You can try creating custom SearchFilter class and override filter_querysetmethod to use and instead of or operator.
See DRF source code
https://github.com/encode/django-rest-framework/blob/86673a337a4fe8861c090b4532379b97e3921fef/rest_framework/filters.py#L123
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/71935480",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Converting Long If/Then Formula into Excel Macro I have a macro that relies on a lot of variables. The way I have it set up (because I know formulas better than macros) is a string of =if(and((etc etc)) statements, and it works, but when I run it, it takes ~20 seconds. I know there's a faster way, but I'm stuck on converting the formulas into If/Then to make it faster.
The way it's set up is that if all certain criteria are met, the color populates in column N. Then, it uses an ISNUMBER(SEARCH(""Red"",$N1))=TRUE formula to apply conditional formatting for highlighting based on color.
All of my conditional formulas are as follows. I know there's probably a way to string them all into one, I just don't know it.
Column F - Sum Product: =SUMPRODUCT((A:A=A20)*(E:E=*"N/A"*))
VBA: "=SUMPRODUCT((C[-5]=RC[-5])*(C[-1]=""N/A""))"
(It actually shows the text "N/A" - it's not returning an error)
Column G - Lookup Dollar Amount from Column P:
=LOOKUP(A20,O:O,P:P)
VBA: "=LOOKUP(RC[-6],C[8],C[9])"
Column K - Determine if Column E begins with a 5:
=IF(LEFT(C20,1)="5","Yes","No")
VBA: "=IF(LEFT(RC[-8],1)=""5"",""Yes"",""No"")"
Column M - (Count occurances in column A) * (Count Column F > 1) * (Dollar amount in D > 0)):
=SUMPRODUCT((A:A=A20)*(F:F>1)*(D:D>0))
VBA: "=SUMPRODUCT((C[-12]=RC[-12])*(C[-7]>1)*(C[-9]>0))"
Column N - Assigns color value for each conditional and applies to Column N:
=IF(AND((F20>1),(M20=1),(G20>0)),"Yellow",IF(AND((F20>1),(M20=1),(G20=0)),"Red",IF(AND((F20>1),(M20>1),(G20>0)),"Blue",IF(AND((K20="Yes"),(G20>0)),"Blue",IF(AND((K20="No"),(G20>0)),"Red",IF(G20<0,"Orange",IF(G20=0,"Red","Next")))))))
VBA:
"=IF(AND((RC[-8]>1),(RC[-1]=1),(RC[-7]>0)),""Yellow""," & _
"IF(AND((RC[-8]>1),(RC[-1]=1),(RC[-7]=0)),""Red""," & _
"IF(AND((RC[-8]>1),(RC[-1]>1),(RC[-7]>0)),""Blue""," & _
"IF(AND((RC[-3]=""Yes""),(RC[-7]>0)),""Blue""," & _
"IF(AND((RC[-3]=""No""),(RC[-7]>0)),""Red""," & _
"IF(RC[-7]<0,""Orange""," & _
"IF(RC[-7]=0,""Red"",""Next"")))))))"
Then for applying highlighting, I have:
Columns("A:E").Select
Selection.FormatConditions.Add Type:=xlExpression, Formula1:= _
"=ISNUMBER(SEARCH(""Blue"",$N1))=TRUE"
Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
With Selection.FormatConditions(1).Interior
.Color = 15773696
End With
I know there's a way to string it all together... I'm just not sure how. There don't even have to be multiple columns... That's just how I knew how to get it to work.
A: You're on the right track with your VBA, but you're trying to use formula syntax in VBA code, and that's not going to work.
Change this:
"=IF(AND((RC[-8]>1),(RC[-1]=1),(RC[-7]>0)),""Yellow""," & _
"IF(AND((RC[-8]>1),(RC[-1]=1),(RC[-7]=0)),""Red""," & _
"IF(AND((RC[-8]>1),(RC[-1]>1),(RC[-7]>0)),""Blue""," & _
"IF(AND((RC[-3]=""Yes""),(RC[-7]>0)),""Blue""," & _
"IF(AND((RC[-3]=""No""),(RC[-7]>0)),""Red""," & _
"IF(RC[-7]<0,""Orange""," & _
"IF(RC[-7]=0,""Red"",""Next"")))))))"
To this:
Dim cel as range
offset(row,col)
set cel = ActiveCell
if cel.offset(0,-8) > 1 and cel.offset(0,-1) = 1 and cel.offset(0,-7) > 0 then
cel.interior.color = vbYellow
elseif cel.offset(0,-8) > 1 and cel.offset(0,-1) = 1 and cel.offset(0,-7) = 0 then
cel.interior.color = vbRed
elseif cel.offset(0,-8) > 1 and cel.offset(0,-1) > 1 and cel.offset(0,-7) > 0 then
cel.interior.color = vbBlue
elseif ucase(cel.offset(0,-3)) = "YES" and cel.offset(0,-7) > 0 then
cel.interior.color = vbBlue
elseif ucase(cel.offset(0,-3)) = "NO" and cel.offset(0,-7) > 0 then
cel.interior.color = vbRed
elseif cel.offset(0,-7) < 0 then
cel.interior.color = vbOrange
elseif cel.offset(0,-7) = 0 then
cel.interior.color = vb.Red
End If
Note:
*
*vbOrange may not be a predefined color. You may have to specify the RGB you want to get there. This was done to get you going.
*set cel = ActiveCell is most likely not what you really want, but you didn't specify any code around it, so you'll have to figure out how to assign this properly yourself.
*Using this code, I think you should be able to eliminate the use of multiple columns now that you have the proper syntax for VBA instead of a formula.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/29212780",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Has “SLComposeViewController” stopped pre-filling the initial text for Facebook share? I have social share in my app implemented using Apples Social framework.
Now Facebook share does bring sharing view controller up on screen but initial text missing.
Has something changed?
Not only that cancelling call back is coming back as done
A: This is a duplicate of SLComposeViewController setInitialText not showing up in View.
This behaviour is by design; prefilling was not allowed by policy, and now it's also enforced.
About the cancel button; this is a known issue and will be fixed. See bug report: https://developers.facebook.com/bugs/962985360399542/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/29999182",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How i can cut java stacktrace for selenium test? Same actions for java
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Lol {
public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();
driver.get("http://suninjuly.github.io/simple_form_find_task.html");
WebElement button = driver.findElement(By.id("submit"));
}
}
and python
from selenium import webdriver
driver = webdriver.Firefox()
driver.get("http://suninjuly.github.io/simple_form_find_task.html")
button = driver.find_element_by_id("submit")
but stacktraces are very different it terms of information value:
*
*java 35 lines
*python 14 lines
i didnt paste stacktraces due to security reasons, but you can check blurred screenshots: https://imgur.com/a/hlyJ6AK
java stacktrace even does not fit in macbook 13' screen :c
How i can restrict printing unwanted information except actual trace?
A: The problem with Firefox and Geckodriver is that it produces so many log entries which are not relevant for most users. To reduce the log entries in your Java program you have following options:
*
*Use a different Browser e.g. Chrome which produces less log entries.
*Redirect the Geckodriver log entries.
You can redirect the log entries of Geckodriver with following line to a file:
System.setProperty(FirefoxDriver.SystemProperty.BROWSER_LOGFILE,"C:\\temp\\logs.txt");
For more information see this link.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/58342649",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Two questions, 1. On express router 2.request, response [environment]
node.js,
express,
react,
nginx
[ 1st question ]
if i have reloaded the website except of root url, i got an error "cannot get /... "
[ 2nd question ]
Website is stopped and no respond, when i request to server side over 6 times by ajax. If i restart my server, i can get response from server again 5 times ...
This error is so critical for me.
My codes..!
[ client ]
// request to server
fetchInfo = async () => {
const { id } = this.props.params;
const room = await webster.get("/api/v1/conference/"+id);
this.setState({
info: room
});
}
//webster.get - ajax
function get(url, data) {
const get = $.ajax({
url,
data,
type: "get",
dataType: "json",
});
const error = get.fail(() => {
throw new Error("Error occured in request");
});
const info = get.done(info => {
return info;
});
return info || error;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
[ backend ]
//app.js
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// Attach database pool for req object
app.use((req, res, next) => {
req.db = pool;
allowCrossDomain;
next();
});
var allowCrossDomain = function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header('Access-Control-Allow-Headers', 'Content-Type'); next();
} ;
//set route for prod
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname + '/../public/dist'+ 'index.html'));
});
app.use('/', express.static(path.join(__dirname + '/../public')));
app.use('/api/v1/user', user);
app.use('/api/v1/conference', conference);
module.exports = {
app
};
//api/conference/index.js
const router = require('express').Router();
const _get = require('./get');
router.get('/', (req, res) => {
_get.searchConferenceRoom(req, res);
});
router.get('/:id', (req, res) => {
_get.getRoomInfo(req, res); //request query to db
});
module.exports = router;
//www.js - exec file
const { app } = require('../app');
const port = require('../settings.json').http.port;
const httpServer = require('http').Server(app);
app.set('port', process.env.PORT || port);
//set port
httpServer.listen(app.get('port'), () => {
console.log('Express started on http://localhost:' + app.get('port'));
});
A: regarding your first question
if i have reloaded the website except of root url, i got an error "cannot get /... "
this is expected since when you navigate through the router links then Javascript runs and manipulates the URL in the address bar, without causing a page refresh, which in turn does a page transition
the solution is to do a "catch-all" route
just set up a catch-all on the server that sends all request to the index index.html
something like this
app.get('/*', function (req, res) {
res.sendFile(path.join(__dirname, '/../../client/build', 'index.html'));
});
but make sure to do this route after your rest api
regarding the second question it quite unclear and if i want to take a guess i think the handler of the request get stuck and does not respond to the client until you end it
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/51452044",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: Should the system be an actor in Use case diagram of a social network app i was wondering if the system should be included as an actor in my use case diagram , my app is about a social network for developers, so the system is prompted to generate notifications to send to the user who gets a new friend request, and also the system send a notification to a user when he receieves a chat message ... does the system plays the role of an actor or not???
thank you in advance
A: No. The system is actually the system under consideration. It's not an actor but defines the border for actors. That's why you see a boundary grouping use cases and the actors outside that border attached to the use cases inside.
p. 637 of UML 2.5:
UseCases are a means to capture the requirements of systems, i.e., what systems are supposed to do. The key concepts specified in this clause are Actors, UseCases, and subjects. Each UseCase’s subject represents a system under consideration to which the UseCase applies. Users and any other systems that may interact with a subject are represented as Actors.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/63087392",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to add class on scroll ReactJS Firstly i know theres many questions like this but i tried their answers too....
So lets get to the point: I want to add a class when i scroll in React... I tried to research some answers but none of them worked...
this is my app.js:
import React from "react";
import "./styles.css";
import { BrowserRouter as Router } from "react-router-dom";
export default class App extends React.Component {
componentDidMount() {
window.addEventListener("scroll", () => {
let activeClass = "";
if (window.scrollY === 0) {
activeClass = "top";
}
this.setState({ activeClass });
});
}
render() {
return (
<>
<Router>
<div className="something">
<div class="box"></div>
<div class={`box-menu ${this.activeClass}`}>something here</div>
<div class="content">
SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br />
SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br />
SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br />
SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br />
SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br />
SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br />
SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br />
SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br />
SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br />
SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br />
SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br />
SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br />
SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br />
SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br />
SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br />
</div>
</div>
</Router>
</>
);
}
}
and this is my styles.css:
body {
margin: 0;
padding: 0;
}
.box {
height: 100px;
background-color: violet;
}
.box-menu {
position: fixed;
top: 100px;
bottom: 0;
left: 0;
width: 200px;
z-index: 5;
overflow-y: scroll;
}
/* THE MENU SHOULD GO TO THE TOP AND HAVE RED BACKGROUND COLOR */
.box-menu.top {
top: 0;
background: red;
}
.content {
margin-left: 200px;
padding-left: 28px;
background-color: aqua;
height: 100%;
}
I dont know why its not working... also i dont have any errors.
This is my code sandbox: https://codesandbox.io/s/inspiring-cloud-s27uv?file=/src/styles.css:0-430
Lastly if you guys need more details pls tell on the comments and ill do my best to provide it to you... Thank you in advance!!!
A: Two things are missing:
First set the initial state (to make the component stateful)
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {activeClass: 'top'};
}
...
}
and then access the state from the state object:
<div className={`box-menu ${this.state.activeClass}`}>something here</div>
A: It doesn't update because you mislead local scoped variable with state. In the scope of event listener you set component state, but in your render function you try to refer to global variable which doesn't exist. In your case 'activeClass' is accessible in the scope of event listener only.
Other thing is that you should unlisten the scroll event listener in the componentWillUnmount() lifecycle method to prevent memory leaks.
You should also you className attribute instead of class - this is one of the differences between standard HTML and JSX.
If you want to access your state in a way like you did you could destructure the activeClass from the this.state object:
render() {
const { activeClass } = this.state;
return (
...
);
}
Working example:
import React from "react";
import "./styles.css";
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = { activeClass: "" };
}
componentDidMount() {
window.addEventListener("scroll", () => {
let activeClass = "";
if (window.scrollY === 0) {
activeClass = "top";
}
this.setState({ activeClass });
});
}
componentWillUnmount() {
}
render() {
return (
<>
<div className="something">
<div className="box"></div>
<div className={`box-menu ${this.state.activeClass}`}>something here</div>
<div className="content">
SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br />
SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br />
SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br />
SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br />
SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br />
SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br />
SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br />
SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br />
SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br />
SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br />
SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br />
SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br />
SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br />
SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br />
SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br /> SCROLLING
<br />
</div>
</div>
</>
);
}
}
A: There are couple of issues in your code.
You need to set a initial state
constructor(props) {
super(props);
this.state = {activeClass: 'top'};
}
In the jsx you need to use
<div className={`box-menu ${this.state.activeClass}`}>
Also you are missing a space in your css
.box-menu .top {
top: 0;
background: red;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/68699921",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Failure sending mail. - System.IO.IOException: Unable to read data from the transport connection: net_io_connectionclosed I have used below code bit to send email from my web service
var emailMessage = new MailMessage(fromaAdress, toAdress)
{
Subject = subject,
IsBodyHtml = true,
Body = body
};
var smtp = new SmtpClient()
{
Host = "smtp.sendgrid.net",
Port = 25,
EnableSsl = false,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential("xxxxx", "xxxxxx"),
Timeout = 10000
};
smtp.Send(emailMessage);
*
*Web service is work perfectly fine with staging server and Test server.
*doesn't work and throw error on prod server(wen i use as a service form other
web applications).
*But it dose work when i use application in same domain(xxx.com/sendmailTest app with xxx.com/sendmailservice).Environment difference is prod has SSL installed.I have changed the ssl enable 587 ports. still the same error.
Can some one help me to find the issue please.
Thanks in advance.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/44759358",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Android: ExpandableListActivity icons overlapping text I'm trying to build a very simple ExpandableListActivity based on the API Demos Sample Code:
Unfortunately, even though the demo just uses the default layout, the layout doesn't look right. It seems the text isn't indented enough, such that the expand/collapse icons overlap the list item text, as the screenshot demonstrates.
Why is this happening and how can I fix it?
Thanks!
A: The problem lies in the getGenericTextView() method of the sample code:
// Set the text starting position
textView.setPadding(36, 0, 0, 0);
setPadding(...) sets the padding (intrinsic space) in pixels, meaning the result of this indenting approach will differ per device. You seem to be using an hdpi device with a relatively large horizontal screen resolution, resulting in visually too little space on the lefthand side of the TextView. For some more explanation on this issue, please read the documentation here.
That being said, you can easily overcome the problem by setting a density independent pixel (d(i)p) value, such that the visually indented space will be identical across different resolutions. You can use the TypedValue utility class for this:
int dips = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 36, getResources().getDisplayMetrics());
Alternatively you could inflate a TextView from xml, on which you can set the density independent properties at design time, in stead of doing it on the fly at runtime.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/8674470",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: get 404 error by batch file upload via google-api-javascript-client library I'm trying to upload whole folder to google drive.
I could successfully upload one file by one request.
But I met rateLimitExceed error while upload whole files.
So, I tried to use batch request.
Creating folders with batch request are successfully done.
but when I trying to upload file by batch request, it returns 404 error. ( Not Found )
Is this google drive's bug?
If so, should I do time delay for upload many files?
var boundary = '--314159265358979323846';
var delimiter = "\r\n--" + boundary + "\r\n";
var close_delim = "\r\n--" + boundary + "--";
var contentType = 'text/plain';
var metadata = {
'title': 'test1.txt',
'mimeType': contentType
};
var base64Data = btoa('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa');
var multipartRequestBody =
delimiter +
'Content-Type: application/json\r\n\r\n' +
JSON.stringify(metadata) +
delimiter +
'Content-Type: ' + contentType + '\r\n' +
'Content-Transfer-Encoding: base64\r\n' +
'\r\n' +
base64Data +
close_delim;
var request = gapi.client.request({
'path': '/upload/drive/v2/files',
'method': 'POST',
'params': {'uploadType': 'multipart'},
'headers': {
'Content-Type': 'multipart/mixed; boundary="' + boundary + '"'
},
'body': multipartRequestBody});
var httpBatch = gapi.client.newHttpBatch();
httpBatch.add(request, {
callback: function(resp, rawResp){
console.log(rawResp);
}
});
httpBatch.execute(function(resp, rawResp){
console.log(rawResp)
});
error is here:
{"id":"1171148984","result":false}
{"gapiRequest":{"data":{"body":"--batch_YZmy6yr9vIk=_ABqi-xumfFQ=\r\nContent-Type: application/http\r\nContent-ID: <response-1171148984>\r\n\r\nHTTP/1.1 404 Not Found\r\nContent-Type: text/html; charset=UTF-8\r\nDate: Mon, 21 Oct 2013 07:53:20 GMT\r\nExpires: Mon, 21 Oct 2013 07:53:20 GMT\r\nCache-Control: private, max-age=0\r\nContent-Length: 9\r\n\r\nNot Found\r\n--batch_YZmy6yr9vIk=_ABqi-xumfFQ=--\r\n","headers":{"pragma":"no-cache","date":"Mon, 21 Oct 2013 07:53:20 GMT","server":"GSE","content-type":"multipart/mixed; boundary=batch_YZmy6yr9vIk=_ABqi-xumfFQ=","cache-control":"no-cache, no-store, max-age=0, must-revalidate","content-length":"349","expires":"Fri, 01 Jan 1990 00:00:00 GMT"},"status":200,"statusText":"OK"}}}
A: Uploading cannot be batched, please run the upload requests individually.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/19489623",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: value was changed by using "
A: Your input field has not rendered and the script is looking for an element with it's id. A simple solution is to move your script to end of the html file. like this:
<p><input type="text" placeholder="Results" name="idn" id="idn_id"></p>
<script>
var idn_text = "123"
document.getElementById("idn_id").value = idn_text
</script>
A: Switch the order of your elements and call the script afterwards.
<p><input type="text" placeholder="Results" name="idn" id="idn_id"></p>
<script>
var idn_text = "123"
document.getElementById("idn_id").value = idn_text
</script>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73267502",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Open a Document in IE and be able to store it as a variable in vbs I am trying to write a vbs program where I navigate to a web page, click on a link that opens a file in excel, then run a macro in the excel file. I know how to navigate to a web page and click on a link. I need help figuring out how I store the excel file in a way that the vbs program can manipulate it.
Set IE = WScript.CreateObject("InternetExplorer.Application", "IE_")
IE.Visible = True
IE.Navigate ("https://www.whateverWebsite.com/")
Dim LinkHref
LinkHref = "analyze" 'the key word that will be in the link to click
Dim a
For Each a In IE.Document.GetElementsByTagName("a") ' for every element whose tag name starts with 'a' for "a href" pull out its contents
If InStr((a.GetAttribute("href")), LinkHref)>0 Then 'checks to see if the link that is set contains the string stored in LinkHref
a.Click 'click the link
End If
Next
Dim objExcel
Set objExcel = CreateObject("Excel.Application")
Now how do I attach the excel file, that I opened with the link, to objExcel?
A: You can attach to a running Excel instance via GetObject:
Set xl = GetObject(, "Excel.Application")
If you have several instances launched, that will only get you the first one, though. You'd have to terminate the first instance to get to the second one.
With that said, a better approach would be to have Excel open the URL directly:
Set xl = CreateObject("Excel.Application")
For Each a In IE.Document.GetElementsByTagName("a")
If InStr(a.href, LinkHref) > 0 Then
Set wb = xl.Workbooks.Open(a.href)
Exit For
End If
Next
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/30241939",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How should I pass a String argument to clojure.core/apply I have the following piece of code:
(condp apply "string argument"
predicate1? "Result1"
predicate2? "Result2"
predicate3? "Result3"
"Else")
Currently, "string argument", when passed to apply gets interpreted as a seq, therefore each character becomes a parameter to the predicate:
(apply predicate1? \s \t \r \i \n ...)
A simple solution would be to wrap the argument in a vector:
(condp apply ["string argument"] ...)
I'm not sure this is very idiomatic. Is there a better solution?
A: I don't think there is a more idiomatic way than using cond directly, binding "string argument" to a symbol and passing it to each predicate. Everything else looks confusing to people reading your code and involves extra function calls.
Extra magic could be achieved with the following helper macro:
(defmacro pcond
"Translates clauses [pred result-expr] to a cond form:
(cond
(pred expr) result-expr
...)
A single result-expr can follow the clauses, and it will be appended
to the cond form under a generated test expression that returns logical
true."
[expr & clauses]
(let [expr-sym (gensym "expr")
else-kw (keyword (gensym "else"))
step (fn [[pred-form clause-form]]
(if (= else-kw clause-form)
[else-kw pred-form]
[(list pred-form expr-sym) clause-form]))
body (->> clauses
(partition 2 2 [else-kw])
(mapcat step))]
`(let [~expr-sym ~expr]
(cond ~@body))))
You can use it so
(pcond "String argument"
predicate1 "Result1"
predicate2 "Result2"
"Else")
It macroexpands directly to cond:
(clojure.core/let [expr13755 "String argument"]
(clojure.core/cond
(predicate1 expr13755) "Result1"
(predicate2 expr13755) "Result2"
:else13756 "Else"))
A: You can use the anonymous function #(%1 %2) for what you are trying to do. IMO it's better than wrapping the condp expression in a vector, but either way works, neither is really straigthforward.
(condp #(%1 %2) "string argument"
string? "string"
map? "map"
vector? "vector"
"something else")
;= Result1
EDIT (copied from the comments)
I'm no expert on macros, but what I've heard over and over is that you shouldn't write a macro if a function will do and condp provides all the elements to use the power of Clojure functions. An approach that doesn't involve macros and improves readability could be defining a function (def apply-pred #(%1 %2)) and use it with condp.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/21033770",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: bypassing javascript to get page source 1)I am building an app for downloading all my pictures from my instagram profile.
2)I don't want to use instagram api so i searched and i find Selenium Webdriver and i add this package to my project
3)I am using c# to build android app (Xamarin) check below Code.
string url = "https://www.instagram.com/" + _theUsername;
IWebDriver driver = new FirefoxDriver();
driver.Url = url;
string source = driver.PageSource;
4)By Using above code i am getting below error :-
OpenQA.Selenium.DriverServiceNotFoundException: The geckodriver file does not exist in the current directory or in a directory on the PATH environment variable
5)Is it possible to use this in xamarin? i need to find a way to do this
any help will be greatly appreciated
A: I am not familiar with Selenium, but getting the page source for a url is easy with HttpClient:
string url = "https://www.instagram.com/" + _theUsername;
using (var httpClient = new HttpClient()){
var response = await httpClient.GetStringAsync(url);
Debug.WriteLine(response);
}
and response will have your page source. And if you do not want to show the web page then there is no need for a WebView anyway.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/41806527",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: An Azure function works from Postman but not from web browser and javascript I have a C# Azure function that manipulates an image file and returns a . Following is the complete code.
[FunctionName("ImageHandler")]
public static async Task<IActionResult> GetHandledImage([HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req, ILogger log)
{
int CaseID = Convert.ToInt32(req.Query["CaseID"]);
int ImageID = Convert.ToInt32(req.Query["ImageID"]);
int ApplyAngle = Convert.ToInt32(req.Query["RotationAngle"]);
string ImagePath = req.Query["ImagePath"].ToString();
string ImageServer = "https://localhost:44331/training/Images";
string FullImagePath = string.Format("{0}{1}", ImageServer, ImagePath);
string Format = "";
MemoryStream ms;
using (WebClient wc = new WebClient())
{
var imageData = await wc.DownloadDataTaskAsync(new Uri(FullImagePath));
using (var BitmapStream = new MemoryStream(imageData))
{
Bitmap b = new Bitmap(BitmapStream);
ImageFormat ImageFormat = b.RawFormat;
b = RotateImage(b, ApplyAngle, true);
using (ms = new MemoryStream())
{
if (ImageFormat.Equals(ImageFormat.Png))
{
Format = "image/png";
b.Save(ms, ImageFormat.Png);
}
if (ImageFormat.Equals(ImageFormat.Jpeg))
{
Format = "image/jpg";
b.Save(ms, ImageFormat.Jpeg);
}
}
}
}
return new FileContentResult(ms.ToArray(), Format);
}
The problem I am facing is that this function works ok when invoked from Postman but not from my own code. Also, I am hosting the function on http://localhost:7001/api/
Following is my local.settings.json file:
{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "UseDevelopmentStorage=true",
"EmailScheduleTriggerTime": "0 0 */6 * * *",
"FUNCTIONS_WORKER_RUNTIME": "dotnet",
"SqlConnectionString": "***",
"URL": "*****"
},
"Host": {
"LocalHttpPort": 7071,
"CORS": "*",
"CORSCredentials": false
}
}
Can someone please help me understand what I could do so I can this function from my browser too.
I am getting HTTP 404 error when accessing from my browser.
Thanks.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/68446837",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Linkify hashtags based on match.group(1) I am trying to Linkify hashtags in a TextView.
Thats is working as sample code I provided but I need to underline found hashtags based on match.group(1).
Linkify seems to underline based on match.group(0).
With TransformFilter I can only change hashtag click destination not the preview of underline link.
As a summary, Linkify creates underlines on match.group(0) but I want underlines on match.group(1)
TextView tv_body = (TextView) view.findViewById(R.id.tv_body);
final Pattern pattern = Pattern.compile(
"(?:^|\\W)#([A-Za-z\\d\u00E7\u011F\u0131\u015F\u00F6\u00FC\u00C7\u011E\u0130\u015E\u00D6\u00DC]+)");
String scheme = "search://";
TransformFilter filter = new TransformFilter()
{
public final String transformUrl(final Matcher match, String url)
{
Log.d(Constants.TAG, "transformUrl - match.group(0):" +
match.group(0) + " - match.group(1):" + match.group(1));
return match.group(1);
}
};
Linkify.addLinks(tv_body, pattern, scheme, null, filter);
transformUrl - match.group(0):##dene - match.group(1):dene
transformUrl - match.group(0):#hashreal - match.group(1):hashreal
transformUrl - match.group(0):+#arti - match.group(1):arti
transformUrl - match.group(0):(#de - match.group(1):de
transformUrl - match.group(0):#feriştah - match.group(1):feriştah
/*
tv_body text content:
nb#dnkjd
##dene
#hashreal
1#2
+#arti
%d(#de
#feriştah
şah#in
*/
A: If you want to exclude the text matched by (?:^|\\W)#, enclose it in a look-behind:
(?<=(?:^|\\W)#)
Then you can drop the capturing group, and the main match will contain only the content after the #.
Before, I'd suggest this:
(?<=\B#)
However, after looking at this bug report and this question about inconsistency between \w and \b in Java, I'd say you need to be careful when using the shorter one, since \b and \B's definition in default mode is not synced with \w.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/26572462",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How make div not scrolling, fixed and keeps there width base on parent container I have page that contains three elements: a header, an article, and a aside.
I want the scroll to only affect the article, and I’d like the header and aside to stay fixed.
I can make header fixed by using position: fixed; and it works.
But when I do the same to aside, its width swaps from being 30% of the width of the container to 30% of the browser width.
So I need the aside to be fixed (not scroll), but at the same time have a width of 30% of its container.
Snippet below, JSFiddle Link
.body-header {
background: blue;
height: 50px;
position: fixed;
width: 100%;
top: 0px;
}
.body-content {
width: 60%;
margin: auto;
}
article {
width: 70%;
display: inline-block;
float: left;
margin-top: 60px;
}
aside {
width: 30%;
background: black;
height: calc(100vh - 50px);
display: inline-block;
float: left;
margin-top: 45px;
}
<body>
<header class="body-header">
header
</header>
<div class="body-content">
<article>
<h1>Introduction t ththth tht</h1>
<p>Etiam non nulla id risus finibus laoreet. Vestibulum vel placerat quam. Suspendisse risus, lacinia sit amet aliquet sit amet, ultricies nec ligula. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris scelerisque vestibulum facilisis. Curabitur hendrerit a libero id ullamcorper. Nam scelerisque felis non nunc tempus fringilla. Proin ullamcorper, massa vitae elementum aliquam, lectus velit imperdiet mauris, nec blandit justo leo ut nisl. Etiam sollicitudin, urna eget malesuada convallis, augue nunc molestie erat, fringilla fringilla augue purus ac lacus. Donec sagittis nisl quis rhoncus fermentum. Sed a velit sem. Suspendisse tempor tempus dolor, ac porta velit porta at. Integer mi est, commodo non aliquam et, venenatis id felis.Sed venenatis diam est, ut volutpat nisl laoreet sed. Sed ut quam sed nibh pharetra congue. Donec ullamcorper, arcu vel finibus dictum, urna purus congue libero, quis fringilla erat ante maximus mauris. Suspendisse odio sem, mollis ac mauris non, viverra bibendum elit. Phasellus malesuada augue nulla, vitae eleifend sapien vehicula et. Aliquam pharetra imperdiet mauris non scelerisque. Donec dictum fringilla ante ac accumsan. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Ut id tempus nisi, ut aliquet justo. Duis a pretium ligula. Morbi facilisis urna sed lacus feugiat, nec laoreet purus fermentum. Proin semper nisi nec sapien porta, quis dapibus tellus auctor Etiam non nulla id risus finibus laoreet. Vestibulum vel placerat quam. Suspendisse lacus risus, Etiam non nulla id risus finibus laoreet. Vestibulum vel placerat quam. Suspendisse lacus risus, Etiam non nulla id risus finibus laoreet. Vestibulum vel placerat quam. Suspendisse lacus risus, Etiam non nulla id risus finibus laoreet. Vestibulum vel placerat quam. Suspendisse lacus risus, Etiam non nulla id risus finibus laoreet. Vestibulum vel placerat quam. Suspendisse lacus risus, Etiam non nulla id risus finibus laoreet. Vestibulum vel placerat quam. Suspendisse lacus risus, Etiam non nulla id risus finibus laoreet. Vestibulum vel placerat quam. Suspendisse lacus risus, Etiam non nulla id risus finibus laoreet. Vestibulum vel placerat quam. Suspendisse lacus risus, Etiam non nulla id risus finibus laoreet. Vestibulum vel placerat quam. Suspendisse lacus risus.</p>
</article>
<aside>
g
</aside>
</div>
</body>
A: I'd think the easiest way to achieve this would be to use some JavaScript.
Using the example code below should do the trick:
var aside = document.getElementsByTagName("aside")[0],
parent = document.getElementsByClassName("body-content")[0];
aside.style.width = ((parent.offsetWidth / 10) * 3) + "px";
Using this code and having the position set to fixed should give the desired effect.
A: So you want aside to be 30% of body-content which is also a percentage?
With a bit of maths, you can do the following:
You want 30% of 60%, which works out at 18%.
60 divided by (10/3) = 18
So change your aside to this (add position: fixed and change width to width: 18%):
aside {
width: 18%;
background: black;
height: calc(100vh - 50px);
display: inline-block;
float: left;
margin-top: 45px;
position: fixed;
}
And you will have the result you wanted.
.body-header {
background: blue;
height: 50px;
position: fixed;
width: 100%;
top: 0px;
}
.body-content {
width: 60%;
margin: auto;
}
article {
width: 70%;
display: inline-block;
float: left;
margin-top: 60px;
}
aside {
width: 18%;
background: black;
height: calc(100vh - 50px);
display: inline-block;
float: left;
margin-top: 45px;
position: fixed;
}
<body>
<header class="body-header">
header
</header>
<div class="body-content">
<article>
<h1>Introduction t ththth tht</h1>
<p>Etiam non nulla id risus finibus laoreet. Vestibulum vel placerat quam. Suspendisse risus, lacinia sit amet aliquet sit amet, ultricies nec ligula. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris scelerisque vestibulum facilisis. Curabitur hendrerit a libero id ullamcorper. Nam scelerisque felis non nunc tempus fringilla. Proin ullamcorper, massa vitae elementum aliquam, lectus velit imperdiet mauris, nec blandit justo leo ut nisl. Etiam sollicitudin, urna eget malesuada convallis, augue nunc molestie erat, fringilla fringilla augue purus ac lacus. Donec sagittis nisl quis rhoncus fermentum. Sed a velit sem. Suspendisse tempor tempus dolor, ac porta velit porta at. Integer mi est, commodo non aliquam et, venenatis id felis.Sed venenatis diam est, ut volutpat nisl laoreet sed. Sed ut quam sed nibh pharetra congue. Donec ullamcorper, arcu vel finibus dictum, urna purus congue libero, quis fringilla erat ante maximus mauris. Suspendisse odio sem, mollis ac mauris non, viverra bibendum elit. Phasellus malesuada augue nulla, vitae eleifend sapien vehicula et. Aliquam pharetra imperdiet mauris non scelerisque. Donec dictum fringilla ante ac accumsan. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Ut id tempus nisi, ut aliquet justo. Duis a pretium ligula. Morbi facilisis urna sed lacus feugiat, nec laoreet purus fermentum. Proin semper nisi nec sapien porta, quis dapibus tellus auctor Etiam non nulla id risus finibus laoreet. Vestibulum vel placerat quam. Suspendisse lacus risus, Etiam non nulla id risus finibus laoreet. Vestibulum vel placerat quam. Suspendisse lacus risus, Etiam non nulla id risus finibus laoreet. Vestibulum vel placerat quam. Suspendisse lacus risus, Etiam non nulla id risus finibus laoreet. Vestibulum vel placerat quam. Suspendisse lacus risus, Etiam non nulla id risus finibus laoreet. Vestibulum vel placerat quam. Suspendisse lacus risus, Etiam non nulla id risus finibus laoreet. Vestibulum vel placerat quam. Suspendisse lacus risus, Etiam non nulla id risus finibus laoreet. Vestibulum vel placerat quam. Suspendisse lacus risus, Etiam non nulla id risus finibus laoreet. Vestibulum vel placerat quam. Suspendisse lacus risus, Etiam non nulla id risus finibus laoreet. Vestibulum vel placerat quam. Suspendisse lacus risus.</p>
</article>
<aside>
g
</aside>
</div>
</body>
|
{
"language": "la",
"url": "https://stackoverflow.com/questions/44050035",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: read data from excel in perl I am trying to read data from excel, i have below code.
#!/usr/bin/perl
use strict;
use warnings;
use 5.010;
use feature 'say';
use Spreadsheet::XLSX;
use Spreadsheet::Read qw(ReadData);
my $book = ReadData ('/tmp/simple.xlsx');
say 'A1: ' . $book->[1]{A1};
my @row = Spreadsheet::Read::row($book->[1], 1);
for my $i (0 .. $#row) {
say 'A' . ($i+1) . ' ' . ($row[$i] // '');
}
my @rows = Spreadsheet::Read::rows($book->[1]);
foreach my $i (1 .. scalar @rows) {
foreach my $j (1 .. scalar @{$rows[$i-1]}) {
say chr(64+$i) . " $j " . ($rows[$i-1][$j-1] // '');
}
}
getting the error as:
Can't locate OLE/Storage_Lite.pm in @INC (@INC contains: /usr/local/lib64/perl5 /usr/local/share/perl5 /usr/lib64/perl5/vendor_perl /usr/share/perl5/vendor_perl /usr/lib64/perl5 /usr/share/perl5 .) at /usr/local/share/perl5/Spreadsheet/ParseExcel.pm line 21.
BEGIN failed--compilation aborted at /usr/local/share/perl5/Spreadsheet/ParseExcel.pm line 21.
Compilation failed in require at /usr/local/share/perl5/Spreadsheet/XLSX.pm line 14.
BEGIN failed--compilation aborted at /usr/local/share/perl5/Spreadsheet/XLSX.pm line 14.
Compilation failed in require at read_excel.pl line 6.
BEGIN failed--compilation aborted at read_excel.pl line 6.
I have every related module. but as per error when i am going to download OLE/Storage_Lite.pm from the CPAN, page is going blank, and from metacpan below error is coming.
https://cpan.metacpan.org/authors/id/M/MS/MSCHWARTZ/OLE-Storage-0.386.tar.gz
Resolving cpan.metacpan.org... 151.101.128.249, 151.101.192.249, 151.101.64.249, ...
Connecting to cpan.metacpan.org|151.101.128.249|:443... connected.
ERROR: certificate common name “a.ssl.fastly.net” doesn’t match requested host name “cpan.metacpan.org”.
To connect to cpan.metacpan.org insecurely, use ‘--no-check-certificate’.
A: Try downloading the module tar zip from cpan or metacpan. Then build the module locally using any make utility(e.g.dmake). You can find more info for building module locally from here.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/42107656",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: DialogFlow error when launching Google Assistant Console I'm using DialogFlow to build a Action for Google Assistant. I want to build this for pt-BR language, but when I am going to test the actions on Actions on Google console I'm getting the following error "Request contains an invalid argument. Locale pt-br selected but the language pt-BR has not been selected." as in the following image:
The steps for reproduce this issue:
*
*Create a agent pt-BR language
*Click on "See how it works on Google Assistant"
And the error appers at bottom of the browser window.
So guys, do anyone know the solution for this issue or a workaround?
A: The Google Issue haven't closed yet, but the problem was fix by the Google Team.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/54421046",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: how to define in svelte.js a global variable over several pages using svelte-router-spa I'm trying to learn svelte and build a card-solution with routing through svelte-router-spa. On each view (index and productdetails) i import my variable basket. This should contain my card-array over the different pages. Unfortunately on every page my array is empty again. How can I define a global var through every page?
thanks for your help.
A: This sounds like a problem that can be solved using a writable store. Stores (if you don't know) are essentially storage for things such as variables and other data which apply across all your components (if imported from your stores file).
The documentation can be found here: https://svelte.dev/tutorial/writable-stores
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/66280344",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: Right Approach to Call Web Service(API) from Fragment in Android I have an activity which has a fragment and a dialog. And I am calling an API from the fragment in the onCreateView method. And when I am on the fragment and opens the dialog then fragment again hits the API. I want to prevent it.I want that my app do not hit when I am opening a dialog.
// code
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_news, container, false);
callApi()
}
A: call your api in onViewCreated like this.
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
callApi(); //here call your function.
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/46561332",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to add Background color for JOptionPane Completely? I am not getting a complete background color for JOptionPane.
Below there is one of my output screen:
http://i.stack.imgur.com/i4tvh.png
And my code:
JFrame frame1 = new JFrame("Showing Error Message");
UIManager UI=new UIManager();
UI.put("OptionPane.background", Color.BLUE);
UI.put("OptionPane.messagebackground", Color.BLUE);
UI.put("Panel.background", Color.BLUE);
JOptionPane.showMessageDialog(frame1,errorMessage1);
A: First of all, the public methods of UIManager are static. It is incorrect, misleading, and pointless to create an instance of UIManager. The correct way to invoke those methods is:
UIManager.put("OptionPane.background", Color.BLUE);
UIManager.put("OptionPane.messagebackground", Color.BLUE);
UIManager.put("Panel.background", Color.BLUE);
This is the whole sample.
import javax.swing.event.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
public class Main extends JFrame
{
public static void main(String []args) {
UIManager.put("OptionPane.background", Color.blue);
UIManager.put("Panel.background", Color.blue);
UIManager.put("Button.background", Color.white);
String value = JOptionPane.showInputDialog("Enter your name");
System.out.println("Hello " + value);
// exit awt thread
System.exit(1);
}
}
A: In nimbus look and feel these all codes are not usable.
So solution is,
UIManager.put("control", new Color(0, 0, 0));
This is also call "Dark Nimbus" add this top of your main frame's main method.
So it will automatically change All JOptionPane's background.
And also you can't change button background with
UIManager.put("OptionPane.buttonBackground", BLACK);
So you should use,
UIManager.put("nimbusBase", new Color(0, 0, 0));
Remember - but unfortunately, this code will change all your buttons etcs' background. So you have to add *.setBackground(...); to all other objects.
If you want to change foreground of JOptionPane you should use
UIManager.put("text", new Color(255, 255, 255));
Again unfortunately this will change your all of text's foreground.
These all codes are called Dark Nimbus.
If you're using nimbus you can try these UIManager codes to customize nimbus look and feel.
UIManager.put("control", new Color(0, 0, 0));
UIManager.put("info", new Color(0, 0, 0));
UIManager.put("nimbusBase", new Color(0, 0, 0));
UIManager.put("nimbusAlertYellow", new Color(248, 187, 0));
UIManager.put("nimbusDisabledText", new Color(255, 255, 255));
UIManager.put("nimbusFocus", new Color(115, 164, 209));
UIManager.put("nimbusGreen", new Color(176, 179, 50));
UIManager.put("nimbusInfoBlue", new Color(66, 139, 221));
UIManager.put("nimbusLightBackground", new Color(0, 0, 0));
UIManager.put("nimbusOrange", new Color(191, 98, 4));
UIManager.put("nimbusRed", new Color(169, 46, 34));
UIManager.put("nimbusSelectedText", new Color(255, 255, 255));
UIManager.put("nimbusSelectionBackground", new Color(18, 134, 175));
UIManager.put("text", new Color(255, 255, 255));
You can try these codes. In my project the nimbus seem as
But I always recommend using "Flatleaf" (Search google "FlatLafLookAndFeel" or go to jar.download.com"). It is a professional and you can change all to your own.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/37021667",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Extracting trees from image without picking up background vegetation? I do not have a background in image recognition/feature extraction, but I am in need of a way to extract trees from an image without the background vegetation.
Seen above is a small example of the kind of imagery I'm working with. I have access to multi-spectral imagery as well (though I haven't seen it yet) including NDVI, NIR, Red-edge.
From researching the problem at hand, I am aware that feature extraction is an active area of research and it seems that often supervised and unsupervised machine learning is employed in combination with statistical voodoo such as "PCA". Being able to differentiate between trees and background vegetation has been noted as an area of difficulty in some papers I skimmed over in my research.
There are notable features about the imagery I am working with. First of all, the palm trees have a very distinctive shape. Not only this, but there are obvious differences in the texture of the trees vs the texture of the background vegetation.
I am not an academic, and as such I only have access to publicly available papers for my research. I am looking for relevant algorithms that could help me extract the features of interest to me (trees) that either have an implementation (ideally in C or bindings to C, though I'm aware that it is not a commonly used language in this field) or with publicly available papers/tutorials/sites/etc. detailing the algorithm so that I could implement it myself.
Thanks in advance for any help!
A: Look into OpenCV, It has a lot of options for supervised/semi supervised Learning methods. As you have mentioned there is a visible texture difference between the tress and background vegetation, a good place for you would be to start would be color based segmentation and evolving it to use textures as well. OpenCV ML tutorial is a good starting point. Moreover you can also combine the NDVI data to create a stronger feature set.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/32258480",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How do I create a #define mapping to the spacebar character in C? I'm looking for the equivalent of this, without the surrounding single quotes:
#define SPACEBAR ' '
How do I do this? For any other character I would use either the character itself or its corresponding escape character. To my knowledge, however, there's no escape character for the spacebar. Is there some sort of hex code I can use? Please help.
A:
Is there some sort of hex code I can use?
The ASCII code for Space is 32 or 0x20. If you want to use SPACEBAR like a constant, you can #define it to be:
#define SPACEBAR 32
or
#define SPACEBAR 0x20
Caveat
The above encoding will work for systems that use ASCII and UTF-8 encoding. For systems that use EBCDIC encoding, the decimal value to encode Space is 64 (Thanks are due to @BasileStarynkevitch for pointing that out).
A: #define SPACEBAR 32
OR
char ch = 0x20
Hope it helps
A: Depending of what you exactly want to do, you may be able to use:
#define SPACEBAR \040
It is the octal value of the space char, like it may appear in a string.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/29374863",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Google Sheets: Sheets as filtered views of data I'm creating a financial spreadsheet that has an All Transactions sheet, which contains entries from multiple people. I would like to also have have dedicated sheets for each person (John's Transactions, Jane's Transactions), where they can see and edit the categories for their own expenses.
I know I can use a filter to accomplish this but only one filter can be applied at a time.
Is there any way to create a duplicate view of a sheet where I can show a subset of entries, but changes made to one will also change the other?
Here is my example sheet
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/62627508",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How can Excel file and website server interact?
I have a working excel calculator and a website server. My goal is to present the result generated by the calculator on the website. And to feed input received by the website My question is that how should I implement this because excel and website server can not seem to interact directly.
I am looking for some language that the excel can be converted to and the language can also be interactive with a website.
Any help would be appreciated!
A: You can embed excel documents on a website using one drive or google docs.
Sync your doc to your one drive, then embed the doc on the page.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73769716",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: React Native CLI uses autolinking for native dependencies, but the following modules are linked manually I am getting Error while running my project using react-native run-ios
error React Native CLI uses autolinking for native dependencies, but the following modules are linked manually:
*
*react-native-document-picker (to unlink run: "react-native unlink react-native-document-picker")
*react-native-fast-image (to unlink run: "react-native unlink react-native-fast-image")
*react-native-image-picker (to unlink run: "react-native unlink react-native-image-picker")
*react-native-maps (to unlink run: "react-native unlink react-native-maps")
*react-native-navigation (to unlink run: "react-native unlink react-native-navigation")
*react-native-permissions (to unlink run: "react-native unlink react-native-permissions")
*react-native-vector-icons (to unlink run: "react-native unlink react-native-vector-icons")
This is likely happening when upgrading React Native from below 0.60 to 0.60 or above. Going forward, you can unlink this dependency via "react-native unlink " and it will be included in your app automatically. If a library isn't compatible with autolinking, disregard this message and notify the library maintainers.
Read more about autolinking: https://github.com/react-native-community/cli/blob/master/docs/autolinking.md
info Found Xcode workspace "JustHelper.xcworkspace"
info Building (using "xcodebuild -workspace JustHelper.xcworkspace -configuration Debug -scheme JustHelper -destination id=BB2D702A-3FF7-4C11-863C-445B97ACFB83 -derivedDataPath build/JustHelper")
..
.. error Failed to build iOS project. We ran "xcodebuild" command but it exited with error code null. To debug build logs further, consider building your app with Xcode.app, by opening JustHelper.xcworkspace***
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/57175614",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: element implicitly has an 'any' type error in vue 3 app I am trying to use lucidev icons in my component but I am really new in typescript
Here is lucidev: https://github.com/lucide-icons/lucide
<template>
<component :is="icon" />
</template>
<script lang="ts">
import * as icons from 'lucide-vue-next';
import { defineComponent } from 'vue';
export default defineComponent({
props: {
name: {
type: String,
required: true,
},
size
},
computed: {
icon() {
return icons[this.name];
},
},
});
</script>
But I am getting element implicitly has an 'any' type because expression of type 'string' can't be used to index type in icons[this.name]
How can I fix this?
icons:
A: This error usually means that the icons variable is not the type that you expect it to be.
Often it's because it's an array. In that case, a string can't be used to index the type of the array because a number is needed to do that. e.g. icons[2].
I would try console logging the icons variable and seeing what comes out, from there you can figure out what you need to use to index it :)
I hope this helps!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75172096",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to show MQ client list by Java? Is it possible to show all clients of a MQ server (or MQ queue manager, or channel) by Java? Because there are too many connections sometimes and I need to monitor it.
I checked the API of com.ibm.mq.MQQueueManager
(https://www.ibm.com/support/knowledgecenter/en/SSFKSJ_7.5.0/com.ibm.mq.javadoc.doc/WMQJavaClasses/com/ibm/mq/MQQueueManager.html)
I can use it to get queue depth, but I cannot get the client connection information (ex: IP address) of it.
If it's impossible to get IP address, could we get "connection count" only?
A: You need to use MQ PCF via Java.
request = new PCFMessage(CMQCFC.MQCMD_INQUIRE_CHANNEL_STATUS);
request.addParameter(CMQCFC.MQCACH_CHANNEL_NAME, "TEST.CHL");
request.addParameter(CMQCFC.MQIACH_CHANNEL_INSTANCE_TYPE, CMQC.MQOT_CURRENT_CHANNEL);
request.addParameter(CMQCFC.MQIACH_CHANNEL_INSTANCE_ATTRS,
new int []
{
CMQCFC.MQCACH_CHANNEL_NAME,
CMQCFC.MQCACH_CONNECTION_NAME,
CMQCFC.MQIACH_CHANNEL_STATUS,
CMQCFC.MQIACH_CHANNEL_SUBSTATE,
CMQCFC.MQIACH_MSGS,
CMQCFC.MQCACH_LAST_MSG_DATE,
CMQCFC.MQCACH_LAST_MSG_TIME,
CMQCFC.MQCACH_CHANNEL_START_DATE,
CMQCFC.MQCACH_CHANNEL_START_TIME,
CMQCFC.MQIACH_BYTES_SENT,
CMQCFC.MQIACH_BYTES_RECEIVED,
CMQCFC.MQIACH_BUFFERS_SENT,
CMQCFC.MQIACH_BUFFERS_RECEIVED,
CMQCFC.MQIACH_MCA_STATUS,
CMQCFC.MQCACH_MCA_JOB_NAME,
CMQCFC.MQCACH_MCA_USER_ID
} );
responses = agent.send(request);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/42757786",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: No exception with SqlDataReader.ExecuteReader while SQL Server returns converstion error When I execute the following statement in SQL Server Management Studio
exec sp_executesql N'select 1 where 1 = @p1',N'@p1 nvarchar(3)',@p1=N'a'
go
I get the below error
Msg 245, Level 16, State 1, Line 1
Conversion failed when converting the nvarchar value 'a' to data type int.
But when I use ExecuteReader, I don't get any exception
Why?
How can I get and handle this error as exception in app
Imports System.Data.SqlClient
Module Module1
Sub Main()
Dim TestSqlConnection As SqlConnection = Nothing
Dim TestSqlCommand As SqlCommand = Nothing
Dim TestReader As SqlDataReader = Nothing
Dim TestGetSchemaTable As DataTable = Nothing
TestSqlConnection = New SqlConnection
TestSqlConnection.ConnectionString = "Data Source=(local);Database=master;Integrated Security=true"
TestSqlConnection.Open()
TestSqlCommand = New SqlCommand()
TestSqlCommand.Connection = TestSqlConnection
TestSqlCommand.CommandType = CommandType.Text
TestSqlCommand.CommandText = "select 1 where 1 = @p1"
Dim TestSqlParameter As SqlParameter = New SqlParameter
TestSqlParameter.ParameterName = "@p1"
TestSqlParameter.SqlDbType = SqlDbType.NVarChar
TestSqlParameter.Size = 3
TestSqlParameter.Direction = ParameterDirection.Input
TestSqlParameter.Value = "a"
TestSqlCommand.Parameters.Add(TestSqlParameter)
Try
TestReader = TestSqlCommand.ExecuteReader()
Catch ex As Exception
Console.WriteLine("Exception")
Finally
Console.WriteLine("Finally")
End Try
End Sub
End Module
A: ExecuteReader doesn't actually perform the query. The first call to .Read() will throw the error.
If you want to only catch the SqlException you can do the following:
Try
TestReader = TestSqlCommand.ExecuteReader()
TestReader.Read()
Catch ex As SqlException
Console.WriteLine("SQL error.")
Catch ex As Exception
Console.WriteLine("Exception")
Finally
Console.WriteLine("Finally")
End Try
A: For me this fixes the SSMS
exec sp_executesql N'select 1 where N''a'' = @p1',N'@p1 nvarchar(3)',@p1=N'a'
exec sp_executesql N'select 1 where N''1'' = @p1',N'@p1 nvarchar(3)',@p1=N'a'
I totally disagree with Rene Reader.
On my system it executes on ExecuteReader.
ExecuteReader would be a real bad name if it did not actually execute.
Did you consider that it is not catching and exception because it is not throwing an exception.
I know you see an error in SQL Profiler but if I introduce a syntax error it is caught.
This is C# but is is not throwing an exception for me.
And if I change it to:
"select 1 where N'a' = @p1";
Then it returns a row.
If I introduce a syntax error:
"select 1 whereX 1 = @p1";
Then it does throw an exception and it throws it on the ExecuteReader line.
If you want 1 to be a literal you should use:
"select 1 where '1' = @p1";
SQLcmd.CommandType = CommandType.Text;
SQLcmd.CommandText = "select 1 where N'1' = @p1";
SqlParameter TestSqlParameter = new SqlParameter();
TestSqlParameter.ParameterName = "@p1";
TestSqlParameter.SqlDbType = SqlDbType.NChar;
TestSqlParameter.Value = "a";
SQLcmd.Parameters.Add(TestSqlParameter);
try
{
rdr = SQLcmd.ExecuteReader();
Int32 waste;
if (rdr.HasRows)
{
while (rdr.Read())
{
waste = rdr.GetInt32(0);
}
}
}
catch (Exception Ex)
{
Debug.WriteLine(Ex.Message);
}
A: I solved this problem if the sql string passed used EXEC sp_executesql by ensuring I read every result and result set... like so:
....
using (var conn = new SqlConnection(_connectionString))
{
try
{
conn.Open();
using (var cmd = new SqlCommand(sql, conn))
{
cmd.CommandTimeout = 0;
using (var rdr = cmd.ExecuteReader())
{
// TODO: Do stuff with the rdr here.
FlushReader(rdr);
}
}
}
catch (Exception ex)
{
_logger.Fatal("Exception: {0}\r\nSQL:\r\n{1}", ex.Message, sql);
throw;
}
finally
{
conn.Close();
}
}
...
/// <summary>
/// Continue trying to read in case the server threw an exception.
/// </summary>
private static void FlushReader(IDataReader rdr)
{
while (rdr.Read())
{
}
while (rdr.NextResult())
{
while (rdr.Read())
{
}
}
}
Without calling the FlushReader method the application continues without throwing an exception of any kind. Even if I use a SQL THROW statement. Running the same sql in SQL management studio will show the error.
Hope this helps.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/19634521",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to silently provide initial settings for Visual Studio I'm looking for a way to provide initial settings for Visual Studio 2017 through a script. Copying a *.vssettings file to the %USERPROFILE%\Documents\Visual Studio 2017\Settings path doesn't work since Visual Studio will rewrite the file on startup while creating a user profile.
There is the /resetsetting switch vor devenv.exe which can be used to reset the settings to a specified .vssettings file, but this will also open Visual Studio IDE.
Is there a way to silently provide initial settings for Visual Studio from a PowerShell script? Or any safe way to detect at which time Visual Studio has created the profile and imported the settings when using /resetsetting, so that the devenv process can be killed?
A: When using /resetsettings, you could:
*
*Check whether default settings file exists. Get modified date if it does.
*Run devenv.exe /resetsettings <filepath> The modified date on the default settings file will be changed to match the file specified.
*Check modified date has changed, or file now exists.
*Close devenv.exe
I've given this a go; the settings file after step 3 isn't identical to the one specified in /resetsettings, although it's clearly different from the previous default one. I don't know the criteria for which tags are kept.
Related, not a PowerShell solution: A team settings file can be specified by going to Tools > Options > Environment > Import and Export Settings. More info on Enviornment Options.
Note from link: "When applied, these team settings would not override any category not specified in the .vssettings file"
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/45670925",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to compare 2 List objects to get the missing value from the List How do I use the "NOT IN" to get the missing data, to be added to "foo" List.
var accessories = new List<string>();
var foo = new List<string>();
accessories.Add("Engine");
accessories.Add("Tranny");
accessories.Add("Drivetrain");
accessories.Add("Power Window");
foo.Add("Engine");
foo.Add("Tranny");
foo.Add("Power Window");
foreach(var v in foo.Where(x => x??).???)
{
foo.Add(v); //Add the missing "Drivetrain" to it...
}
A: You can use .Except() to get the difference between two sets:
var difference = accessories.Except(foo);
// difference is now a collection containing elements in accessories that are not in foo
If you then want to add those items to foo:
foo = foo.Concat(difference).ToList();
A: Use List.Except:
foo.AddRange(accessories.Except(foo));
From MSDN:
Except Produces the set difference of two sequences.
A: There's a LINQ method to do this for you, it looks like this; accessories.Except(foo);
A: You can combine Concat and Distinct to do this:
foo = foo.Concat(accessories).Distinct().ToList();
Edit: Or Except as others have pointed out, which seems to be the superior choice for this case.
A: If you just want foo to be the distinct combination of all elements in foo and accessories (i.e., the union of the two lists),
List<string> foo = foo.Union(accessories).ToList();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/33763942",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Default seeds in Stata I gather from the Stata manual on the RNG seed that the value for the seed is 123456789 every time Stata is launched. My questions are
*
*Was it always this way or was the default seed different in older versions (I'm particularly concerned with version 8)
*Is the default sortseed also 123456789?
A: To answer my own questions:
Going back to at least version 8 the default seed was 123456789 but as Nick Cox points out in comments above this doesn't mean all versions of Stata would produce the same sequence of random numbers based on that seed because the random number generator has changed over time.
The default sortseed seems to be 1001:
. query sortseed
. di r(sortseed)
1001
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/21591731",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Application in CloudFoundry is able to access Redis even when Redis service is un-binded from that app I have deployed an application in CloudFoundry with Redis service binded to it. In this app I have autowired StringRedisTemplate and have provided couple of endpoints for inserting, deleting and listing data from Redis.
Now when I am un-binding Redis service from my app , I am still able to perform all the operations to Redis. Whenever a service is un-binded its credentials ( Ip/port/username/password ) will not be there in the environment variables of that app. So my question is how still my app is able to access redis DB when redis service is un-binded from it ?
A: Did you restage the app after un-binding? Changes to bindings don't take affect until after an app has been restaged. You can verify by running cf env app-name and seeing of the VCAP_SERVICES environment variable is still set.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/34631486",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Is there a way to set a score range (or a max score) for a query I have a very simple query :
match: {
field => {
boost: 4,
query: term,
fuzziness: 'AUTO',
}
}
Composed with several (about 10) others queries most of them using constant_score. The problem is that on specific terms, my query has a too big score that cancel all others queries results.
Here is a part of the explain :
"details" => [
[0] {
"value" => 63.656006,
"description" => "sum of:",
"details" => [
[0] {
"value" => 63.656006,
"description" => "weight(title.de:kandinsky in 1694239) [PerFieldSimilarity], result of:",
"details" => [
[0] {
"value" => 63.656006,
"description" => "score(doc=1694239,freq=1.0 = termFreq=1.0\n), product of:",
"details" => [
[0] {
"value" => 4.0,
"description" => "boost",
"details" => []
},
[1] {
"value" => 11.3820715,
"description" => "idf, computed as log(1 + (docCount - docFreq + 0.5) / (docFreq + 0.5)) from:",
[...]
Has you can see, I have a score of 11.38 due to the IDF.
My others queries (with scores between 1 and 3) are totally useless.
My question is :
How can I set a max possible score for a query ?
Or, even better, can I set a range of score for my query ?
I would like to avoid a constant_score query for this field, I need a few TF/IDF and score notion for this field but not that strong.
I tried this :
function_score: {
query: { match: {
field => term,
}},
score_mode: :avg,
script_score: {
script: {
inline: "4 * (1 + Math.log(2 + _score))",
}
},
}
It's better but it can still perform a very high score on certain cases.
A: Finaly I used a function score with a script score using a 1 - (1/x) function in script_score
GET _search
{
"query": {
"function_score": {
"query": {
"match": {
"postgresql.log.message": "alter"
}
},
"script_score" : {
"script" : {
"params": {
"max_score": 5
},
"source": "params.max_score * (1 - 1 / _score)"
}
}
}
}
}
This way, I will have a score between 0 and nearly 5 (max_score).
You can try it here with the word alter (score 3.9150627) or alter table pgbench_branches add primary key (bid) (score 4.8539715).
You can adapt the 1 - (1/x) function to approach the asymptote faster.
A: have u tried using Function score query ?
Here is the link for the same
https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-function-score-query.html
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/44965601",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Initialize integer value while declaration vb6 How should I initialize variable value during the declaration.
I am using VB6,
I tried
public i as integer = 0
but i got error
Expected: End of statement, and "=" is highlighted
I want to set initial value to 0.
Edit from comments:
I want to create a login form without the help of the database..
Module: So i created a user_name(1 to 10)-- array and password(1 to 10) array
form1 I want to register upto 10 users each time the value of i increments //form// i=1 register_user(i)=uname register_pass(i)=upass i=i+1 //end// but each time I go to that form value is set again to 1 what should I do.
A: In VBA and VB6 you can't initialize variables. You must use an executable statement.
However, each variable does have a default initialization value.
From the VB6 documentation:
When variables are initialized, a numeric variable is initialized to
0, a variable-length string is initialized to a zero-length string
(""), and a fixed-length string is filled with zeros. Variant
variables are initialized to Empty. Each element of a user-defined
type variable is initialized as if it were a separate variable.
So actually, in your case,
public i as integer = 0
doesn't work, but the next stement does work, and does just that:
public i as integer
A: I think the issue is that you are attempting to instantiate a public variable at declaration...Dim i As Integer: i = 1 works, but is not public. You can either do this or declare the public variable then instantiate it in the first line of of the sub.
A: Vacip answered it in terms of setting it to 0 like you asked, but to build on it... If you need a public variable to start as something other than the default value you would set it to that value the first time it is called in a sub.
If you have multiple subs that might call it for the first time and then it gets passed back and forth, you need to check to ensure that it hasn't already been set. you can do that with a public boolean.
If you turn on your locals and step through this you can see one way to do it.
Public iTesti As Integer 'defaults to 0
Public bTesti As Boolean 'defaults to FALSE
Public Sub testi()
If bTesti = False Then 'btesti is false and iteseti is 0
iTesti = 1
bTesti = True
End If
iTesti = 2
testi2
End Sub
Public Sub testi2()
If bTesti = False Then 'btesti is true and itesti is 2
iTesti = 1
bTesti = True
End If
iTesti = 3
End Sub
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/35960661",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Clojure thread-first macro (->) vs thread-last macro (->>) What are the practical differences? I still do not fully understand the difference between the two Clojure arrow macros thread-first -> and thread-last macro ->>.
While reading through https://clojure.org/guides/threading_macros I understand that thread first -> is an alternative expression for nested operations on a single object, each datastep using the object as input argument, performing an independent operation.
(defn transformation [object]
(transform2 (transform1 object)))
becomes
(defn transformation [object]
(-> object
(transform1) ;; object as implicit argument
(transform2))) ;; object as implicit argument
When using threat-last ->> operator, each tranformation uses output of the preceding transformation as implicit argument:
(defn transformation [object]
(->> object
(transform1) ;; object as implicit argument
(transform2))) ;; (transform1 object) as implicit argument
What are the practical implicantions of these differences? I understand that it makes sense to use threat -first -> for operations on maps and dictionaries, where each transformation creates a new copy of the original instance, which has to be supplied for the next operation.
However, in many cases, both operators actually behave the same:
(->> [2 5 4 1 3 6] (reverse) (rest) (sort) (count)) ;; => 5
(-> [2 5 4 1 3 6] (reverse) (rest) (sort) (count)) ;; => 5
A: The practical difference is where the macro "inserts" the variable (and the subsequent results) into the expressions:
(ns so.example)
(defn example-1 [s]
(-> s
(str "foo")))
(defn example-2 [s]
(->> s
(str "foo")))
(example-1 "bar")
;=> "barfoo"
(example-2 "bar")
;=> "foobar"
So (-> "bar" (str "foo")) is the same as (str "bar" "foo") and (->> "bar" (str "foo")) is the same as (str "foo" "bar"). With unary functions -> and ->> do the same thing.
When you need more flexibility as to where these results should be inserted, you would use as->:
(ns so.example)
(defn example-3 [s]
(as-> s v
(str "foo" v "foo")))
(example-3 "bar")
;=> "foobarfoo"
A: Following up on as-> as an answer purely because I can't format code in a comment.
Here's a usage of as-> from our codebase at work:
(-> date
(.getTime)
(as-> millis
(/ (- (.getTime (java.util.Date.)) millis)
1000 60 60 24))
(long)
(min days))
That computation could be unrolled, and ->> used to place the threaded value at the end of the - expression, but would probably be harder to read. It would also be possible to unroll it in such a way that -> alone would be enough (by negating the threaded value and then adding it to (.getTime (java.util.Date.))) but that would make it even harder to read I think.
A: I think there is a misunderstanding on your part on how -> works.
You say
*
*-> is an alternative expression for nested operations on a single object, each datastep using the object as input argument, performing an independent operation.
and then about ->> you say
*When using threat-last ->> operator, each tranformation uses output of the preceding transformation as implicit argument
but statement 1 is not true, and statement 2 is true for both, -> and ->>.
This is very easy to test, like this:
cljs.user=> (-> [2 5 4 1 3 6] reverse rest)
(3 1 4 5 2)
cljs.user=> (-> [2 5 4 1 3 6] rest reverse)
(6 3 1 4 5)
If you add sort to the end of the call chain, like in your example, you wouldn't notice this difference, because both results would be sorted.
Like cfrik said, when you are passing only one argument to a function, then the first argument and the last argument are the same (because there's just one), so that's why it's easy to get confused when all the functions in your call chain accept only one argument, which is the case with your example where you have used count, sort, rest, and reverse.
Another thing you might have missed from the documentation in https://clojure.org/guides/threading_macros is the fact that many functions that work with sequences, like filter, map, and reduce, take the sequence as the last argument as a convention, and that makes it possible to chain calls to them using ->>, like
(->> (range 10)
(filter even?)
(map #(+ 3 %))
(reduce +))
which becomes
(reduce + (map #(+ 3 %) (filter even? (range 10))))
whereas -> is more suitable for functions like assoc and update, which (like you said) work with single objects and take the object as their first argument (and "transformations/update" on that object as the rest of the arguments), so then you can do the following
(-> person
(assoc :hair-color :gray)
(update :age inc))
which becomes
(update (assoc person :hair-color :gray) :age inc)
To better understand how macros work, try using macroexpand-1, like this
user> (macroexpand-1 '(->> (range 10)
(filter even?)
(map #(+ 3 %))
(reduce +)))
(reduce + (map (fn* [p1__21582#] (+ 3 p1__21582#)) (filter even? (range 10))))
The argument macroexpand-1 should be a quoted version of the function call, and the result will be the expanded function call.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/65629918",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.