text
stringlengths 15
59.8k
| meta
dict |
---|---|
Q: Disable Chrome "plugin not responding" message It is quite annoying that this pop-up window appears every time I debug my GWT code using GWT dev-mode and Chrome's GWT Development plugin. Any ideas how to turn it off?
A: chromium-browser --disable-hang-monitor
| {
"language": "en",
"url": "https://stackoverflow.com/questions/9161926",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: using File().byLine() with fold() I am trying to use the fold operation on a range returned by byLine(). I want the lambda which is passed to fold to be a multi-line function. I have searched google and read the documentation, but cannot find a description as to what the signature of the function should be. I surmize that one of the pair is the accumulated sum and one is the current element. This is what I have but it will not build
auto sum = File( fileName, "r" )
.byLine
.fold!( (a, b)
{
auto len = b.length;
return a + len;
});
The error I get back from dmd is:
main.d(22): Error: no property `fold` for `(File(null, null)).this(fileName, "r").byLine(Flag.no, '\n')` of type `std.stdio.File.ByLineImpl!(char, char)`
So my question is two fold:
*
*Is my use of fold in this case valid?
*How do I pass a curley brace lambda to fold?
I have tried searching google and reading the dlang documentation for fold. All documentation uses the shortcut lambda syntax (a, b) => a + b.
A: So the way fold works is that it accepts a list of function aliases on how to fold the next element in. if you don't provide it with a starting value, it uses the first element as the starting value. Quoting the documentation (emphasis mine):
The call fold!(fun)(range, seed) first assigns seed to an internal
variable result, also called the accumulator. Then, for each element
x in range, result = fun(result, x) gets evaluated. Finally, result
is returned. The one-argument version fold!(fun)(range) works
similarly, but it uses the first element of the range as the seed
(the range must be non-empty).
The reason why your original code didn't work is because you can't add an integer to a string (the seed was the first line of the file).
The reason why your latest version works (although only on 32-bit machines, since you can't reassign a size_t to an int on 64-bit machines) is because you gave it a starting value of 0 to seed the fold. So that is the correct mechanism to use for your use case.
The documentation is a bit odd, because the function is actually not an eponymous template, so it has two parts to the documentation -- one for the template, and one for the fold function. The fold function doc lists the runtime parameters that are accepted by fold, in this case, the input range and the seed. The documentation link for it is here: https://dlang.org/phobos/std_algorithm_iteration.html#.fold.fold
A: I was able to tweak the answer provied by Akshay. The following compiled and ran:
module example;
import std.stdio;
import std.algorithm.iteration : fold;
void main() {
string fileName = "test1.txt";
auto sum = File(fileName, "r")
.byLine
.fold!( (a, b) {
// You can define the lambda function using the `{}` syntax
auto len = b.length;
return a + len;
})(0); // Initialize the fold with a value of 0
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74668853",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Typescript is slower than javascript when using sequelize? I am migrating a web app from javascript to typescript. And I have noticed that the query results are a bit slower sometimes as compared to javascript. It is not consistent though.
I have two tables - User and Team. One user can have many teams. So it is hasMany and belongsTo association between them.
Team Model
import {Model, Table, Column, Default} from 'sequelize-typescript';
@Table
export class Team extends Model {
@Column name!: string;
@Default(true)
@Column isActive!: boolean;
}
User Model
import {Model, Table, Column, Default,DataType} from 'sequelize-typescript';
@Table
export class User extends Model {
@Column firstName!: string;
@Column lastName!: string;
@Column email!: string;
@Default(true)
@Column isActivated!: boolean;
@Column source!: string;
@Column(DataType.JSON)
profileData: string;
@Column(DataType.JSON)
settings: string;
@Column(DataType.JSON)
paymentDetails: string;
}
The association
Team.belongsTo(User, { foreignKey: "fk_ownerId", as: 'Owner' });
User.hasMany(Team, { foreignKey: "fk_ownerId", as: 'OwnedTeams' });
Here are my results
30k records
typescript
user ins query: 2.955s
user query: 2.134s
javascript
user ins query: 3.785s
user query: 1.947s
50k records
typescript
team ins query: 4.621s
team query: 2.601s
javascript
team ins query: 4.352s
team query: 2.340s
tsconfig.json
{
"compilerOptions": {
"module": "commonjs",
"target": "es6",
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"sourceMap": true,
"strictNullChecks": false,
"noUnusedLocals": true,
"pretty": true,
"skipLibCheck": true,
"lib": [
"es2015"
]
}
}
I am running tsc --build to generate the build.
Is there anything that I have been doing wrong ?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/69263121",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Standards or best practices for the content of RESTful requests and responses We may need to provide a RESTful web service interface to our application.
THe RESTFul architecture provides some guiding principles for some parts of the interface but leaves others entirely open - in particular, it doesn't seem to say anything about the format of the data transferred in a request or response.
While this is very open and flexible for implementers, we do need to make a choice!
So this question is to ask if there are any emerging standards for the way RESTful web services are implemented - e..g JSON or XML for the payload? Specified by XML schemas or something else?
If no emerging standards, are there guidelines and best practices for how to make these kinds of choices?
In our case, we're pretty free to choose what works best for our application - we are not (yet) constrained by what the systems that will be invoking these web services can handle.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/8210640",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Converting to a dropdown menu firstly apologies, as I have seen this question asked before, but I'm still none the wiser, so going to have to ask it myself.
I am very new to html5 and css3, so far I have managed to get by, until now.
I would like to convert one of the options in my navigation menu to a drop down menu, I have tried many times using info from here and other sites, but I'm still having problems.
Here is my css for the Nav menu..
/* Site Nav */
#site-nav
{
position: absolute;
top: 0;
right: 50px;
font-family: 'Open Sans Condensed', sans-serif;
text-align: right;
}
#site-nav ul
{
list-style: none;
overflow: hidden;
}
#site-nav ul li
{
display: block;
float: left;
text-decoration: none;
font-size: 1.2em;
height: 90px;
line-height: 110px;
margin: 0 0 0 1.75em;
}
#site-nav ul li a
{
color: #000;
text-decoration: none;
outline: 0;
}
#site-nav ul li a:hover
{
color: #fff;
}
#site-nav ul li.current_page_item
{
background: url('images/nav-arrow.png') center 77px no-repeat;
}
#site-nav ul li.current_page_item a
{
color: #662d91;
}
and here is the html for my menu...
<ul>
<li><a href="index.html">Homepage</a></li>
<li><a href="about.html">About Us</a></li>
<li><a href="products.html">Products</a></li>
<li><a href="bullion.html">Bullion</a></li>
<li class="current_page_item"><a href="#.html">Contact Us</a></li>
</ul>
If this can be done with just HTML5 and CSS3 then that is great, but I'm happy to go down the JavaScript route if needs be.
Thanks in advance for any help, it will be very much appreciated.
EDIT 21/03/2013...
I have tried to implement the code given to me below, and this fiddle shows how far i have got, http://jsfiddle.net/2rgSP/1/
With 2 problems, firstly, links are pushed off edge of website, 2, the drop down menu falls behind the main wrapper.
There is clearly some conflicting css going on, but i am a complete beginner at this, so I'm clueless I'm afraid.
Hopefully someone can see where I am going wrong.
Thanks
Lee
A: Below is what you could use, if javsscript/jquery is an option:
<ul id="cssdropdown">
<li class="headLink">Home
<ul>
<li><a href="#">Home1</a></li>
<li><a href="#">Home4</a></li>
<li><a href="#">Home2</a></li>
<li><a href="#">Home3</a></li>
<li><a href="#">Home5</a></li>
</ul>
</li>
<li class="headLink">About
<ul>
<li><a href="#">About1</a></li>
<li><a href="#">About2</a></li>
<li><a href="#">About</a></li>
<li><a href="#">About3</a></li>
<li><a href="#">About5</a></li>
</ul>
</li>
<li class="headLink">Contact
<ul>
<li><a href="#">Contact1</a></li>
<li><a href="#">Contact2</a></li>
<li><a href="#">Contact3</a></li>
<li><a href="#">Contact4</a></li>
<li><a href="#">Contact5</a></li>
</ul>
</li>
<li class="headLink">Links
<ul>
<li><a href="#">Links1</a></li>
<li><a href="#">Links2</a></li>
<li><a href="#">Links3</a></li>
<li><a href="#">Links4</a></li>
<li><a href="#">Links5</a></li>
</ul>
</li>
</ul>
CSS
body{
padding:0px;
margin:0px;
}
ul li{
list-style-type:none;
}
#cssdropdown{
padding:0px;
margin:0px;
}
a{
text-decoration:none;
padding:0px;
margin:0px;}
.headLink{
display: inline-block;
padding:10px;
margin:10px;
text-align:right;
background-color:#999999;
cursor:pointer;
}
.headLink ul{
display:none;
position: absolute;
margin:10px 0 0 -13px;
padding:0 10px;
text-align:left;
background-color:#CCC;
cursor:pointer;
}
JS:
$(function() {
$(".headLink").hover(function() {
$('ul',this).slideToggle();
});
});
DEMO
| {
"language": "en",
"url": "https://stackoverflow.com/questions/15496826",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to insert an "apply" button in WordPress I am building a job website and I am trying to insert an 'apply' button in a custom post-type single page (called 'vacancy') within WordPress.
I need this button to notify the admin of the new 'application' = meaning someone logged in clicked on the button.
I have thought about using the comment_form() function but I am not sure how to adapt it to register the "button" click. It doesn't show anything at all in fact.
I have got the following code inside the WP_Query( $mypost ) while( have_posts() ) : the_post(); loop:
if ( comments_open() || get_comments_number() ) :
if ( post_password_required() ) {
return;
}
comment_form( array(
'comment_field' => '',
'label_submit' => __( 'Apply' ),
'comment_notes_after' => ''
),
$mypost
);
endif;
I don't want to affect the general comments as I may need them for the normal posts and pages, and preferably if I can separate it from the comments and instead have something else - but I can't think of another way to do it.
Thanks in advance! Really do appreciate any suggestions/help.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/27017941",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: awk: automatically call functions from file I need to perform the absolute value calculation a lot in awk.
But absolute value is not built into awk, so many of my awk commands look like this:
awk 'function abs(x){return ((x < 0.0) ? -x : x)} { ...calls to "abs" .... }' file
Is there a way to store user-defined awk functions in files, and have awk automatically load these functions whenever it is called?
Something like setting an awk "include" path or user-profile, much the same way you do for bash and other programs.
A: You can use @include "file" to import files.
e.g. Create a file named func_lib:
function abs(x){
return ((x < 0.0) ? -x : x)
}
Then include it with awk:
awk '@include "func_lib"; { ...calls to "abs" .... }' file
A: Also try
$ cat function_lib.awk
function abs(x){
return ((x < 0.0) ? -x : x)
}
call function like this
$ awk -f function_lib.awk --source 'BEGIN{ print abs(-1)}'
| {
"language": "en",
"url": "https://stackoverflow.com/questions/26063076",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: how to add listener to java dock icon on osx i have in my applications jframe Hide on close, but when i click the dock icon, i want it
to setVisible(true);
how do i add an action listener to the dock icon?
i tried
Image im = Toolkit.getDefaultToolkit().getImage(this.getClass().getResource("SLogo.png"));
final TrayIcon tri = new TrayIcon(im);
tri.addActionListener(this);
@Override
public void actionPerformed(ActionEvent ae) {
this.setVisible(true);
System.out.print("ok");
}
but its not triggered,
and also, how will it affect the app on windows machine?
A: You need to use an AppForegroundListener and/or AppReOpenedListener. See this example:
public static void main(String[] args)
{
final JFrame frame = new JFrame();
Application app = Application.getApplication();
app.addAppEventListener(new AppForegroundListener() {
@Override
public void appMovedToBackground(AppForegroundEvent arg0)
{
System.out.println("appMovedToBackground");
}
@Override
public void appRaisedToForeground(AppForegroundEvent arg0)
{
System.out.println("appRaisedToForeground");
frame.setVisible(true);
}
});
app.addAppEventListener(new AppReOpenedListener() {
@Override
public void appReOpened(AppReOpenedEvent arg0)
{
System.out.println("app reoponed");
frame.setVisible(true);
}
});
frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
frame.setSize(200, 200);
frame.setVisible(true);
}
If you develop on Windows, you'll need to include stubs of the Mac/Java classes or else you'll get compiler errors. See here.
If you develop on Mac, just make sure the code is not executed when running on Windows.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/16401190",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Javascript click element by X Y not working Hey guys I am working on a script to help me out on soundcloud. On soundcloud, each track has a waveform that you can click on to skip to certain parts of the track. I want to simulate a mouse click on the waveform of a song but I need some help.
I need to be able to click at varying parts of the waveform, not simply on the element's position.
I wrote the following code to find the coordinates of the waveform (just execute it in address bar while on any track):
(function(){ alert(document.getElementsByClassName('g-box-full sceneLayer')[0].getBoundingClientRect().top); })();
For me the coordinates are 678, 296.
If I wanted to, for example, click a few seconds into the track I though I would be able to do:
(function(){ document.elementFromPoint(750, 310).click(); })();
However, this doesn't seem to work. Nothing happens. I want to be able to execute the javascript from the address bar via javascript: <code here>
Any help would be appreciated, thanks!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/43556865",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Search form in two Regions? New to Drupal, trying to wrap my mind around the Blocks concept.
Am I right in concluding that I cannot have the SearchForm on the right side (sidebar second) for one ContentType, and on the left side (sidebar first) for another ContentType?
I'm talking standard 7(.17) with no extra modules or PHP "hacks".
A: Standard Drupal will only allow you to specify the placement of blocks once. To achieve what you're after you'll need to look into using a contributed module like Context or Panels.
Personally used Context a fair bit in the past. It's pretty powerful but relatively simple to use.
A: This module allows you to create several instances of a block, so you can duplicate a block and put the duplicates on other regions.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/13701261",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: CDK pipelines with several application repositories I have successful setup a pipeline for my application with CDK Pipelines construct that was introduced this summer. The application is a microservice (UserService) compiled with CodeBuild and creates a ECS Fargate service. The source of the application is in a GitHub repository.
The project stored in GitHub repository is like this:
.
+-- cdk
+-- Dockerfile_OrderService
+-- Dockerfile_ProductService
+-- Dockerfile_UserService
+-- OrderService
+-- ProductService
+-- UserService
OrderService, ProductService and UserService are folders containing source code of the microservices that needs to be compiled with CodeBuild. I have only implemented UserService so far, and that works fine. When I push a change from the UserService folder, the pipeline is triggered, and the source code are built with CodeBuild, and the service is deployed to ECS Fargate.
When I set up a pipeline for the other two services, a push from any of the services folders will trigger CodePipeline for all three services. I don't want that, I want the pipeline for the specific service is triggered, not the other two, but I am not sure how to do that.
I was thinking about each service to have it's own repository, but I also need the infrastructure code under cdk to be present.
Do anyone have an example of how to do this?
A: My team uses a monorepo with different cdk-pipelines for each product/service that we offer. It does trigger each pipeline when we push to the develop branch, but if there are no changes in 'ProductService' or 'OrderService' then technically I don't think there's no harm letting it update all of them.
But if you do want separate triggers, you would have to use separate branches that trigger each microservice. You are allowed to specify a branch for 'GitHubSourceActionProps.Branch'. For example, the pipeline construct for 'UserService' could look like this: (C#)
var pipeline = new Amazon.CDK.Pipelines.CdkPipeline(this, "My-Cdk-Pipeline", new CdkPipelineProps()
{
SourceAction = new GitHubSourceAction(new GitHubSourceActionProps()
{
ActionName = "GitHubSourceAction",
Branch = user-service,
Repo = "my-cool-repo",
Trigger = GitHubTrigger.WEBHOOK,
}),
};
aws cdk api reference githubsourceactionprops
| {
"language": "en",
"url": "https://stackoverflow.com/questions/65425189",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Authorization issue with python request I am trying to authenticate users and I am getting invalid
{'error': 'invalid_request'}
bellow is my code
I am following the guide on https://developer.sonos.com/build/direct-control/authorize/
import base64
import requests
client_secret = "*******************************"
client_id = "*******************************"
combine_id = f'{client_id}:{client_secret}'
base64_id = base64.b64encode(combine_id.encode("ascii"))
base64_id = base64_id.decode("UTF-8")
code = request.data["code"]
state = request.data["state"]
headers = {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
'Authorization': f'Basic {base64_id}',
}
data = {
'grant_type': 'authorization_code',
'code': code,
'redirect_uri': 'http://localhost:8000/sonos'
}
response = requests.post(
'https://api.sonos.com/login/v3/oauth/access', headers=headers, data=data)
print("response : ", response.json())
| {
"language": "en",
"url": "https://stackoverflow.com/questions/69529233",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: User-Agents are removed by Chinese mobile networks? Kindly confirm the information below.
a. Chinese mobile networks are blocking the useragent strings.
b. The user-agent send to the server are in different encoding for Chinese mobiles.
Please let me know whether a or b is true and also pour in your experiences on the identifying the user agents in Chinese mobiles.
Everywhere the term Chinese mobile means a mobile in China with Chinese mobile network.
Thanks in advance.
[changed]
A: I just tested this with my mobile phone. The user agent that is received by remote servers is both the same when I connect via WLAN and via GPRS (my SIM card is issued by China Mobile). There doesn't seem to be any filtering of user agents.
Specifically, my browser's user agent string is:
Mozilla/5.0 (webOS/2.1.0; U; en-GB) AppleWebKit/532.2 (KHTML, like Gecko) Version/1.0 Safari/532.2 Pre/1.1
I'd say that neither a nor b is true.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/1952598",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to include a jar file into Scala code This is the Scala code that I have written
object Main extends App {
println("Hello World from Scala!")
}
This is my build file
name := "hello-world"
version := "1.0"
scalaVersion := "2.11.5"
mainClass := Some("Main")
This is command that I am using to create the jar file
java -cp "scala-library.jar:target/scala-2.11/hello-world_2.11-1.0.jar" Main
Problem: I want to include the scala-library.jar in my hello-world jar file so that I don't have to reference it in the command line. Is it possible?
A: The way I use it is add all the external jar to the "lib" folder and use "sbt assembly" to create one fat jar.
A: i suggest you bundle the jar file into your applications jar file. you can use jar command for packaging or any such utility offered by the IDE as well.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30596087",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Making installer but used SDKs "Classes not registered" We are trying to make an installer for our application and are using Advanced Installer.
When i add all the files from the release folder of our application and let it install. The application crashes and says that some classes are not registered. I know this is comming from some of the SDKs we are using that uses ActiveX objects. Do i have to add these SDK installers to the Prerequisites or is there another way to register these classes?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/15249815",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Run docker with volume mapping from another docker container I have a Jenkins instance running in a Docker container which can also run docker commands of the host.
The build process of my apps includes running bower and grunt. But to avoid having to install node on the Jenkins container, I wish to run a seperate node-container to perform the node-specific commands.
ie. this works if I run this locally on my machine:
docker run -it -v $(pwd):/usr/src/app 3bdigital/bower-grunt-gulp bower install
I basically mount my project folder to the app folder and the container will run bower install in that folder.
Unfortunately this doesn't seem to work if I run this command from inside the Jenkins container. The docker container runs, but the volume is not being mounted properly.
Is there a way to do this ? Or do I have to install Node in my Jenkins image ?
Another solution is to install node in the image of the app itself and have that docker image do the necessary build steps. The downside is that this image will be much larger than necessary (the node_modules, bower_components, source, ... folders are not needed in production)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/38036835",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: using apply function write multiple append statement Is it possible to write below code using apply function or any other, because iterrows seems not feasible here.
For creating Dataframe:
df = [[['55792', 'TRIM'], 'A', ['55792', 'TRIM']], [['ZQFC', 'DYWH'], 'A', ['MEIL', '1724']]]
df = pd.DataFrame(df, columns=['seg','cod','seg2'])
df
seg cod seg2
[55792, TRIM] A [55792, TRIM]
[ZQFC, DYWH] A [MEIL, 1724]
#output
seg cod seg2
[55792, TRIM] A [55792, TRIM]
[ZQFC, DYWH] A [MEIL, 1724]
[MEIL, 1724] A [MEIL, 1724]
So, I am expanding the rows if the seg column and seg2 column doesn't matches. It there any better way to do that using apply.
Code I have used:
df1 = pd.DataFrame(columns=df.columns)
for index, row in df.iterrows():
#if seg match seg 2
if(row['seg']==row['seg2'])==True:
#append same row
df1 = df1.append(row)
else:
#if not match, then we can create two seg, and append 2 row
#append same row first
df1 = df1.append(row)
#changing existing segment to new segment, and append
row['seg'] = row['seg2']
df1 = df1.append(row)
Thanks a lot.
A: You don't need to use apply you can just use your conditionals as boolean masks and do your operations that way.
mask = df["seg"] == df["seg2"]
true_rows = df.loc[mask]
false_rows = df.loc[~mask]
changed_rows = false_rows.assign(seg=false_rows.seg2)
df1 = pd.concat([true_rows, false_rows, changed_rows], ignore_index=True)
print(df1)
seg cod seg2
0 [55792, TRIM] A [55792, TRIM]
1 [ZQFC, DYWH] A [MEIL, 1724]
2 [MEIL, 1724] A [MEIL, 1724]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/70632807",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Handcoding PHP for daily log style website with mySQL database I only began learning about web development 3 weeks ago and have grasped html, css and js quite quickly and have also had some success in using php to draw values from a mySQL database that I have setup however I have a few questions if that is OK?
I am designing a website that essentially allows users to register and then login and add details to a daily log which is stored in the mySQL database. I also want a forum, content section and a shop. Obviously there is no standard open source package for this so I have been investigating how to handcode the PHP to log users in and have them logged in across all parts of the handcoded website. I initially thought I could do this using sessions but I have read that they are bad for SEO? I understand that you can disable them and use cookies but I fear this is all getting a bit over my head? Would it be easier to try and develop this in ASP.NET?
Apologies if some of this doesn't make sense but as I said I am very new to this but I am eager to learn and really serious about it so I will take any information given to me on board. Thanks for your time
A: This is all very possible in PHP, but what you are asking is for an explanation that requires a book. Speaking of books, there are tons of great books offering help with exactly what you need:
PHP 5 CMS Framework Development: Would teach you about many of the pieces you are trying to assemble by hand including MVC principles.
"Obviously there is no standard open source package.."
Just to name one, WordPress allows users to log in and add stuff to a daily log (it's called a blog), has content sections, and has forum and commerce plugins. Personally, I've been amazed at how customizable WordPress is!
A: I don't understand your comment about using cookies instead of sessions. I recommend you use the PHP $_SESSION superglobal to keep users logged in during their session.
If you have super-sensitive data in these logs, one option might be to verify that the user's IP has not changed between requests.
I see no reason why ASP.net would be preferable. Personally, I like to learn programming by opening up vim and going at it.
P.S. Be sure you are escaping data provided to you by users before writing it to your SQL database.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/8735850",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Set status code on specific path in Nginx There's a particular route in our web app which we wish should always be served with a 404 status code. With Nginx, how do I return a specific route's content just as usual, but with a specific http status code, for example 404?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42419285",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Apache cant change listening port I am trying to install nginx as reverse frontend proxy to apache.
During this process I have to change the listening port for apache to e.g. 7070 instead of 80.
I went to the /etc/httpd/conf/httpd.conf and changed:
Listen 80
to
Listen 7070
I also added a virtualhost
NameVirtualHost *:7070
<VirtualHost *:7070>
//code
</VirtualHost>
at the end of it
However when i restart apache and nginx, nginx complains that port 80 is already in use and cannot be used
if i run
ss -plnt sport eq :80
i see lots of httpd processes/users.
What am i doing wrong, why is apache still on port 80?
If i do
sudo fuser -k 80/tcp
i can start nginx then, but then apache complains about the used port 80...
What am i doing wrong? :|
I am thankful for any help
A: You need a NameVirtualHost directive matching your virtualhosts somewhere in your config.
In your case, you'd need that, before the VirtualHosts declarations:
NameVirtualHost *:7070
As a matter of fact, you must have NameVirtualHost *:80 somewhere already, just change the port there too.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39651602",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: DiscordAPIError: Unknown Interaction after making the /help command So I have this help command but I am getting an error saying "Unknown Interaction". I have been searching on the internet for quite a while now, but could not find a solution for this.
Here is the code:
const { Client, MessageEmbed } = require("discord.js");
const { readdirSync} = require("fs");
module.exports = {
name: "help",
aliases: ["h"],
userPerms: ["SEND_MESSAGES"],
clientPerms: ["SEND_MESSAGES", "EMBED_LINKS"],
description: "Shows all available bot commands.",
execute: async(interaction, args, client, message) => {
const {user} = interaction;
if(!args[0]){
let categories = [];
readdirSync("./Commands/").forEach((dir) => {
const commands = readdirSync(`./Commands/${dir}/`).filter((file) => file.
endsWith(".js"))
const cmds = commands.map((command) => {
let file = require(`../../Commands/${dir}/${command}`)
if(!file.name) return "No command name.";
let name = file.name.replace(".js", "");
return `\`${name}\``;
});
let data = new Object();
data = {
name: dir.toUpperCase(),
value: cmds.length === 0 ? "In progress." : cmds.join(" | "),
};
categories.push(data);
})
const embed = new MessageEmbed()
.setTitle("Commands")
.addFields(categories)
.setDescription(`Use /help followed by a command name to get more additional information on a command. For example: /help afk`)
.setFooter(`Requested by ${user.tag}`, user.displayAvatarURL({dynamic: true}))
.setColor("RANDOM");
return interaction.reply({emebds: [embed]})
} else {
const command = client.commands.get(args[0].toLowerCase()) || client.commands.find((c) => c.aliases && c.aliases.includes(args[0].toLowerCase()));
if(!command){
const embed = new MessageEmbed()
.setTitle("Not Found")
.setDescription("Command not found. Use /help for all commands available")
.setColor("RANDOM");
return interaction.reply({embeds: [embed]})
}
const embed = new MessageEmbed()
.setTitle("Command Details")
.addField("COMMAND:", command.name ? `\`${command.name}\`` : "No name for this command")
.addField("ALIASES:", command.aliases ? `\`${command.aliases.join("` `")}\`` : "No aliases for this command.")
.addField("USAGE:", command.usage ? `\`/${command.name} ${command.usage}\`` : `/\`${command.name}\``)
.addField("DESCRIPTION", command.description ? command.description : "No description for this command.")
.setFooter(`Requested by ${message.author.tag}`, message.author.displayAvatarURL({dnyamic: true}))
.setColor("RANDOM");
return interaction.reply({embeds: [embed]});
}
}
}
And this is the error I am getting after typing /help on discord
/Users/Aplex/Documents/Aplel/node_modules/discord.js/src/rest/RequestHandler.js:350
throw new DiscordAPIError(data, res.status, request);
^
DiscordAPIError: Unknown interaction
at RequestHandler.execute (/Users/Aplex/Documents/Aplel/node_modules/discord.js/src/rest/RequestHandler.js:350:13)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async RequestHandler.push (/Users/Aplex/Documents/Aplel/node_modules/discord.js/src/rest/RequestHandler.js:51:14)
at async CommandInteraction.reply (/Users/Aplex/Documents/Aplel/node_modules/discord.js/src/structures/interfaces/InteractionResponses.js:99:5) {
method: 'post',
code: 10062,
httpStatus: 404,
requestData: {
json: {
type: 4,
data: {
content: undefined,
tts: false,
nonce: undefined,
embeds: undefined,
components: undefined,
username: undefined,
avatar_url: undefined,
allowed_mentions: undefined,
flags: undefined,
message_reference: undefined,
attachments: undefined,
sticker_ids: undefined
}
},
files: []
}
}
Does anyone have an idea of where the issue exactly is and how to fix it? I would really appreciate it
A: This normally means that you took too long to respond to the Interaction. You can add an interaction.deferReply() to defer the reply.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/71326078",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Can entities inside the aggregate be accessible or visible externally to the aggregate? I'm new to DDD and my question might seem trivial to many of you.
Consider the case of Student and Course.
The student can enroll the course only if the student's age is above the minimum age required to enroll that course.
From my point of view, Student and Course can be considered as aggregate where Student is the root entity, Course the child entity, and age the invariant to respect.
Student should have a method Student.SubscribeTo(Course course) and the method should enforce the invariant Student.Age >= Course.MinAge and generate an exception otherwise.
Is this correct in the DDD approach? Or should I pass to SubscribeTo only CourseId? Student.SubscribeTo(int CourseId)
From my point of view, if there is no way to break the invariant, access to Course externally to the aggregate should be allowed. If I change the Course.MinAge in some other places of my code I don't break my business requirements, as I want the age be respected only when subscribing the course and I don't mind if later the Course.MinAge changes.
Different case if business requirements state: when Course.MinAge changes students already enrolled in the course should be removed from the course if Student.Age < Course.MinAge.
A: I think that the aggregate you have is not correct. A Course entity can exists on its own, it is not a child entity of a Student entity. A course has its own lifecyle: e.g. if a student leaves the school, the course keep on existing. The course id doesn't depend on the student id. The student can hold the course id, but they are different aggregates.
Anyway, to your question of passing just the course id to the "student.subscribeTo" method if they were an aggregate, the answer is no, you cannot pass the id of a child entity to an operation of the aggregate, as the child entities doesn't have a global identity known outside the aggregate. They have local id into the aggregate.
UPDATE:
Since Course and Student are two aggregates, the rule "student's age must be above the minimum age required to enroll the course" isn't an invariant. Why? Because an invariant is a business rule about the state of just an aggregate, that must always be transactionally consistent. An aggregate defines a transactional consistency boundary.
So, the rule is just a validation rule that must be checked when the student subscribes to a course ("student.subscribeTo" method). Since aggregates shouldn't use repositories, you can pass a domain service to the method, and the student aggregate would double-dispatch to the domain service in order to get the course from the course id.
Take a look at the aggregates chapter of the Red Book IDDD by Vaughn Vernon (pages 361-363) or the article by the same author:
http://www.informit.com/articles/article.aspx?p=2020371&seqNum=4
Hope it helps.
A: I'm also learning DDD and few days ago I ask a question to a similar problem you can find here.
What I've learned is that the only real answer is: it depends. There is no right or wrong approaches per se, everything must serve a purpose to the business problem and its solution. Although, there are guidelines and rules of thumb that can be very useful, for instance:
*
*Don't model reality. The domain model is an abstraction designed to solve a particular problem.
*Don't model based on data relationship. Every association must be there to enforce a rule or invariant and not because those objects are related in real life. Start modeling based on behavior.
*Prefer small aggregates.
*Prefer modify a single aggregate at the same time (use case / transaction), and use eventual consistency to update other aggregates.
*Make associations between aggregates by identity only.
I think the problem in your scenario is that there is a lot missing. Who owns that association and why? Is there any other use case that span both, student and course? Why do you put student.SubscribeTo(course) instead of course.enroll(student)? Remember that the goal of DDD is tackle a complex domain logic so it shines when approaching the write side of the model, the reading side can be done in many different ways without put a lot of associations into the model.
For what you've said, just validating the age is probably not and invariant that requires making a large aggregate:
If I change the Course.MinAge in some other places of my code I don't break my business requirements, as I want the age be respected only when subscribing the course and I don't mind if later the Course.MinAge changes.
Then there is no reason to enforce Student and Course to be consistent at all times (in this particular context/scenario), and there is no necessity of make them part of the same aggregate. If the only rule you need to enforce is Student.Age >= Course.MinAge you can stick with a simple:
Student.SubscribeTo(Course course)
where Student and Course are not part of the same aggregate. There is nothing against loading two different aggregates and use them in the same transaction, as long as you modify only one. (Well, there is nothing against modify two aggregates in the same transaction either, is just a rule of thumb, but probably you don't need to break it in this case).
Here Student.SubscribeTo will enforce the rule regarding the age. I have to say, it sounds "weird" to let the Student validate his own age, but maybe it is just right in your model (remember, don't model reality, model solutions). As the result, Student will have a new state holding the identity of the course and Course will remain unchanged.
Different case if business requirements state: when Course.MinAge changes students already enrolled in the course should be removed from the course if Student.Age < Course.MinAge.
Here you have to answer first (with the help of a domain expert) some more questions: Why should they be removed? Should they be removed immediately? What if they are attending the class in that moment? What does it mean for a student to be removed?
Chances are that there is no real need in the domain to remove the students at the same time the MinAge is changed (as when the operation is only considered successful when all happens, and if not, nothing happens). The students might need to enter a new state that can be solved eventually. If this is the case, then you also don't need to make them part of the same aggregate.
Answering the question in the title, unsurprisingly: it depends. The whole reason to have an aggregate is to protect invariants of a somehow related set of entities. An aggregate is not a HAS-A relationship (not necessarily). If you have to protect an invariant that spans several entities, you can make them an aggregate and choose an entity as the aggregate root; that root is the only access point to modify the aggregate, so every invariant is always enforced. Allowing a direct reference to an entity inside the aggregate breaks that protection: now you can modify that entity without the root knowing. As entities inside the aggregate are not accessible from the outside, those entities have only local identity and they have no meaning as standalone objects without a reference to the root. It is possible to ask the root for entities inside the aggregate, though.
You can, sometimes, pass a reference to an inner entity to another aggregate, as long as it's a transient reference and no one modify that reference outside the aggregate root. This, however, muddles the model and the boundaries starts to become blurry. A better approach is passing a copy of that entity, or event better, pass a immutable view of that entity (likely a value object) so there is no way to break invariants. If you think there is no invariant to break by passing a reference to an inner entity, then maybe there is no reason to have an aggregate to begin with.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/53866617",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: how to remove all space on indent when inserting a newline under vim Xcode I am new to Xcode and use vim for my editor under Xcode. How to use shift + O to add newline in vim under Xcode without adding space as indent?
so I will not have lots of space in blank line like following during git diff
this is what I expect during git diff
A: *
*Go to Xcode Preferences.
*Choose Text Editing tab.
*Switch to the Editing page underneath.
*Check both "Automatically trim trailing whitespace" and "Including whitespace-only lines".
This works both in Vim mode and the normal mode.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/72836150",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to find whether IPs in subnet used for HSRP in softlayer API We ordered a subnet on a private VLAN and when we try to use one of the IP. We realized that IP was used for HSRP on router/switches of Softlayer infrastructure. Is there any SL API to find out whether the IP is used for this purpose? We generally extract IP using softlayer python based client code like the below
ipinfo = network.ip_lookup()
and to determine whether it is used for any reserved purpose
ipinfo['isGateway'] is True or ipinfo['isBroadcast'] is True or ipinfo['isReserved'] is True
Really appreciate your inputs on this.
Thanks
A: IP Addresses reserved for HSRP have the property isReserved as True and in note property the text “Reserved for HSRP.”
You can use the method SoftLayer_Network_Subnet::getIpAddresses with the following filter to get those IP Addresses:
objectFilter={'ipAddresses':{'note':{'operation':'Reserved for HSRP.'}}}
Below you can see an example in python.
"""
Get Ip Addresses of a subnet which are reserved for HSRP protocol.
Important manual pages:
http://sldn.softlayer.com/reference/services/SoftLayer_Network_Subnet/getIpAddresses
http://sldn.softlayer.com/reference/datatypes/SoftLayer_Network_Subnet_IpAddress
https://sldn.softlayer.com/article/object-Masks
https://sldn.softlayer.com/article/object-filters
License: http://sldn.softlayer.com/article/License
Author: SoftLayer Technologies, Inc. <[email protected]>
"""
import SoftLayer
from pprint import pprint as pp
# Your SoftLayer API username and key.
API_USERNAME = 'set-me'
API_KEY = 'set-me'
# The id of subnet you wish to get information.
subnetId = 135840
# Object mask helps to get more and specific information
mask = 'id,ipAddress,isReserved,note'
# Use object-filter to get Ip Addresses reserved for HSRP
filter = {
'ipAddresses': {
'note': {'operation': 'Reserved for HSRP.'}
}
}
# Call SoftLayer API client
client = SoftLayer.create_client_from_env(username=API_USERNAME, api_key=API_KEY)
try:
result = client['SoftLayer_Network_Subnet'].getIpAddresses(id=subnetId,
mask=mask,
filter=filter)
pp(result)
except SoftLayer.SoftLayerAPIError as e:
pp('Unable to get the Ip Addresses %s, %s' % (e.faultCode, e.faultString))
Links:
https://knowledgelayer.softlayer.com/articles/static-and-portable-ip-blocks
http://sldn.softlayer.com/reference/services/SoftLayer_Network_Subnet/getIpAddresses
http://sldn.softlayer.com/reference/datatypes/SoftLayer_Network_Subnet
I hope this help you.
Regards,
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42844927",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Drupal: PDOException: could not find driver in lock_may_be_available() I am running Drupal on my local machine using Windows and recently I opened a project solution within Visual Studio. Upon opening the solution, it asked me to install PHP7 extensions via the Microsoft Web Platform Installer. After these extensions were installed, when I navigate to my local Drupal site, I get the following error:
PDOException: could not find driver in lock_may_be_available()
I did do some research before I decided to ask this question and it seems that I'm just missing this driver.
If this is the problem, how do I install the right PDO driver for Drupal?
Any help is greatly appreciated!
A: It's not driver for Drupal, but for PHP. It's name should be "pdo_mysql", "php_pdo_mysql" or similar, depending on platform. Since you are on windows you should look for a way to install it there. I.e. check this SO post:
PHP - How to install PDO driver? (Windows)
BTW, will you site really run on windows server? If not, my advise is to develop on virtual machine, so you'll have the same development environment, as production will be (most likely linux, right?).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/47311923",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Set text from sqlite rows in Pyqt textbrowser I need a way to set some rows from sqlite.db to pyqt textbrowser,But the problem is that it just put the last row.
cur = conn.cursor()
conn.text_factory = str
cur.execute(" SELECT text FROM Translation WHERE priority = ?", (m,))
for row in cur:
print('{0}'.format(row[0]))
self.SearchResults.setPlainText('{0}'.format(m))
I used pandas but,
query = "SELECT text FROM Translation WHERE priority=2;"
df = pd.read_sql_query(query,conn)
self.SearchResults.setPlainText('{0}'.format(df['text']))
This is not what I want.And this:
cur = conn.cursor()
conn.text_factory = str
cur.execute(" SELECT text FROM Translation WHERE priority = ?", (m,))
all_rows=cur.fetchall()
self.SearchResults.setPlainText('{0}'.format(all_rows))
A: In the first code you are replacing the text every time you iterate, the solution is to use append()
cur = conn.cursor()
conn.text_factory = str
cur.execute(" SELECT text FROM Translation WHERE priority = ?", (m,))
self.SearchResults.clear() # clear previous text
for row in cur:
self.SearchResults.append('{0}'.format(str(row[0])))
| {
"language": "en",
"url": "https://stackoverflow.com/questions/51685812",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Converting '0x3132333435' to '12345' in PHP I was trying to recover some password data on my SQL SERVER 2012 files, unfortunately I forgot what encryption was used in encoding the password to the tables. I know that 0x3132333435 translates as 12345, as this was my test account before.
I tried to use hexdec() but no luck, there seems to be a pattern with the structure of the password. 0x3132333435 translates as 0x3(1)3(2)3(3)3(4)3(5) with the data 12345 being 'sandwiched' between hex 0x3 and 3's.
This is one of my code's part.
$_SESSION['error'] = 'Cannot find account with the username';
} else {
$row = sqlsrv_fetch_array($query, SQLSRV_FETCH_ASSOC);
if (hexdec($password, $row['password'])) {
$_SESSION['admin'] = $row['id'];
}
else{
$_SESSION['error'] = 'Incorrect password';
}
}
I've read some of the topics about this as well, but I don't have any idea on how to implement it:
Currently, classes "wep" and "wpa" are suported. The WEP
(Wired Equivalent Privacy) key can be either 5 or 13
bytes long. It can be provided either as an ASCII or
hexadecimal string -- thus "12345" and "0x3132333435"
are equivalent 5-byte keys (the "0x" prefix may be omit-
ted). A file containing a WEP key must consist of a sin-
gle line using either WEP key format. The WPA (Wi-Fi
Protected Access) key must be provided as an ASCII
string with a length between 8 and 63 bytes.
Is it possible to do it manually? Or is there some link that I can use as a guide or reference?
I am trying to use the old table (user's masterfile) so that my old users can still access the system. I'm currently using hash() for my new password table.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57049199",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Storing keystore password for certificate pinning in Android I've recently started to learn about security in Android apps and wanted to implement certificate-pinning. Found some useful information by googling around but I stumbled upon storing the keystore password which contains the server certificate.
As I can't trust the Android filesystem to keep my keystore password secret, mainly because any rooted user would be able to dig it out eventually, I'm starting to wonder whether if it is really needed to securily store this keystore password or not, because this keystore will only contain my server's SSL certificate, which is intended to be public.
I can't think about any malicious attack if somebody could decompile my APK and see the keystore password, as the attacker wouldn't be able to modify any of the app's code and thus change, for example, the targeted server IP or even modify the keystore switching my certificate with some other malicious cert which, in combination with the changes the attacker could made on the targeted IP, would make the app work targeting any malicious server (man-in-the-middle-attack).
I found a quite good example of certificate pinning in Android here on github, but sadly the author doesn't bother with storing the passsword securely, as it is hardcoded at the MainActivity.
So my summed up question would be: Is it really needed to protect a keystore password if that keystore only has inside an intended public SSL server certificate?
From the research I did, I found that on this question the OP addresses the posibility of passing null as the password on the Android code. Maybe I could go with this and store the keystore password at my server instead of packing it up inside the Android app.
Also during my googling I found quite useful articles that might be interesting for anybody looking into this question in the future:
*
*Certificate-Pinning in Android explained easy
*Securely storing info in Android
*Android Keystore for storing keys (WARNING any rooted user can dig out info stored here)
Progress update
- Passing null as the keystore password (as I mentioned above as one of the options) if you've set one when generating it will result in keystore bypass: requests get sent anyway and custom keystore does nothing. No exception is thrown or anything, it just works as if you didn't set any custom keystore.
KeyStore trustStore = KeyStore.getInstance("BKS");
trustStore.load(keyStoreInputStreamFromResources, null);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/43891059",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: g++/clang++ Invert compilation error order g++ and clang++ report compilation errors with the first erroneous line encountered at the top of their output. That is, the first line clang/g++ print on a compilation error are the one you usually care about. As I'm sure we have all experienced, you have to scroll up (often a lot) to see what the nasty error is. Is there any compilation flag (in clang++ or in g++) that presents compilation errors in reverse order?
I saw this question which asked the same thing I'm asking, but about GHC and thought about how much of a useful option this would be for C++ projects. I've never heard of this for clang++ or g++, and I couldn't find anything online nor on their man pages.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/51319139",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to show the time slots horizontally instead of vertically in agendaDay view, fullcalendar? i am trying to list the time slots in agendaDay horizontally, is it even possible? Read all the options listed for agendaDay but could not do it.
Here is js fiddle for test:
$('#calendar').fullCalendar({
// put your options and callbacks here
defaultView: 'agendaDay',
allDaySlot: false,
slotDuration: '00:60:00',
slotLabelFormat: 'h(:mm)a',
// columnHeader: false,
events: [
{
title: 'Blood Donation',
start: '2017-12-29T10:30:00'
},
{
title: 'Concert Event',
start: '2017-12-29T12:30:00',
end: '2017-06-10T12:30:00'
}
]
})
Have anybody done it before, its just i don't want to do heavy customization using css?
hoping for some initialization parameters for agenda view that will turn around the list in horizontal from vertical.
The view i want is something like the below picture:
| {
"language": "en",
"url": "https://stackoverflow.com/questions/48022445",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to pull the starting view for document using the Revit API How can I use the Revit API to get the Starting View for a Document? The equivalent way to access it using the user interface is seen below:
A: I used the Revit Lookup tool and browsed through the database to find a class called StartingViewSettings with the property ViewId that will get me the ElementId of the starting view. My actual code for getting the view is below
FilteredElementCollector startingViewSettingsCollector =
new FilteredElementCollector(document);
startingViewSettingsCollector.OfClass(typeof(StartingViewSettings));
View startingView = null;
foreach(StartingViewSettings settings in startingViewSettingsCollector)
{
startingView = (View)document.GetElement(settings.ViewId);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/45696372",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Autocomplete Source I have 2 autocomplete text boxes on my form. What I want to do is dynamically change the source on the 2nd autocomplete textbox if a value has been selected from the first.
a snippet of my markup is below:
$(function () {
$("#SelectedAddress").autocomplete({
source: "/CreateFIS/GetProperties",
select: function(event, ui) {
if (ui.item) {
event.preventDefault();
$('#SelectedAddress').val(ui.item.label);
$('#SelectedAddressId').val(ui.item.value);
getPropertyInformation(ui.item.value);
}
},
focus: function(event, ui) {
if (ui.item) {
event.preventDefault();
$('#SelectedAddress').val(ui.item.label);
$('#SelectedAddressId').val(ui.item.value);
//getPropertyInformation(ui.item.value);
}
}
});
});
$(function () {
$("#SelectedScheme").autocomplete({
source: "/CreateFIS/GetSchemes",
select: function (event, ui) {
if (ui.item) {
event.preventDefault();
$('#SelectedScheme').val(ui.item.label);
$('#SelectedSchemeId').val(ui.item.value);
}
},
focus: function (event, ui) {
if (ui.item) {
event.preventDefault();
$('#SelectedScheme').val(ui.item.label);
$('#SelectedSchemeId').val(ui.item.value);
}
}
});
});
<tr>
<td style="width:200px;"><label for="addresses">Please Select A Scheme</label> </td>
<td style="width:600px;">@Html.TextBoxFor(model => model.SelectedScheme, new { @class = "largeTextBox" })</td>
<td style="width:200px;"> @Html.ValidationMessageFor(model => model.SelectedSchemeId) </td>
</tr>
<tr>
<td style="width:200px;"><label for="addresses">Please Select A Property </label> </td>
<td style="width:600px;">@Html.TextBoxFor(model => model.SelectedAddress, new { @class = "largeTextBox" })</td>
<td style="width:200px;"> @Html.ValidationMessageFor(model => model.SelectedAddressId) </td>
</tr>
WHat is the best way to acomplish this?
A: Use the option method to change the source:
var source = $(".selector").autocomplete("option", "source", "/New/Source");
| {
"language": "en",
"url": "https://stackoverflow.com/questions/10834688",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Could someone help to explain why the klass could not be used in wrapper? About python __closure__ I couldn't understand why my klass couldn't be used in wrapper method
#!/usr/env/bin python
class MyClassmethod(object):
def __init__(self, func):
self.func = func
def __get__(self, obj, klass=None):
def wrapper(*args, **kwargs):
if not klass:
klass = type(obj)
return self.func(klass, *args, **kwargs)
return wrapper
class Test:
@MyClassmethod
def mytest(cls, test=None):
print(f"this is a classmethod belongs to {cls.__name__}")
if __name__ == '__main__':
Test.mytest()
It shows UnboundLocalError: local variable 'klass' referenced before assignment
But If I change the code like this, put the klass assignment out of the wrapper method
#!/usr/env/bin python
class MyClassmethod(object):
def __init__(self, func):
self.func = func
def __get__(self, obj, klass=None):
if not klass:
klass = type(obj)
def wrapper(*args, **kwargs):
return self.func(klass, *args, **kwargs)
return wrapper
class Test:
@MyClassmethod
def mytest(cls, test=None):
print(f"this is a classmethod belongs to {cls.__name__}")
if __name__ == '__main__':
Test.mytest()
Could someone help to explain this?
Cheers
A: In your first example, you're referencing the variable klass before you've defined it. That's not the case in the second example.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/62285803",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: HTML Traverse and Find Best Practices Hey I was thinking about making some crawlers so that I can get an URL and traverse through the html and just get certain things I might need/want. I was thinking about using Php + xPath but I'm not sure that might be the best way. What do you guys think? Are there any best practices, recommendations, or anything else?
A: I had some good results reusing the Parse class from Fit/Fitnesse for getting data out of html tables.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/766979",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is there a way to make a cell editable where column is readonly in XtraGrid? My grid looks like this.
Key Value
1 A
2 B
3 C
I have Value column read-only in my grid. "Value" column's columnedit is associated with memoexedit repository. Now what I want to do is on some condition like when key=2,
I want my value cell to be editable.
I tried making the whole column ReadOnly = false.
and then handled ShowingEditor to cancel edit on everything else than Key=2, but that prevents even opening up the editor for other values.
What I want is able to see the editor but it should be readonly for Others
and for Key=2, It should be editable.
Please help!
A: Try to handle the ShownEditor event as the following (semi-pseudo code):
var grid = sender as GridView;
if (grid.FocusedColumn.FieldName == "Value") {
var row = grid.GetRow(grid.FocusedRowHandle) as // your model;
// note that previous line should be different in case of for example a DataTable datasource
grid.ActiveEditor.Properties.ReadOnly = // your condition based on the current row object
}
This way you could refine the already opened editor with your needs.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/17244501",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to find only dirty object without iterating items in an ObjectStore of EnhancedGrid Is there any way to get only dirty object without iterating items in an ObjectStore of EnhancedGrid?
A: You can access it with grid.store._dirtyObjects
| {
"language": "en",
"url": "https://stackoverflow.com/questions/48584184",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Order retaining in List when retrived from SQL Query I am getting a list (initial list) from the session which contains the customer Ids in the below order:-
[208700013, 30216118005, 30616118005, 10121005444, 206700013]
Now I am passing these customerIds to the customer table as a collection using "IN" query for which I am getting a list of customerIds in string along with the other values.
But the customerIds are being retrieved in the following order:
10121005444
206700013
208700013
30216118005
30616118005
This is creating a problem when I display the values in the view.
How I can get the same order which is set in the initial list as supposed to the list order returned by the query?
A: If you only have a hand full of result sets, it might be easiest to sort them in java, using a Comparator.
If you have to do it in oracle you can use a statement like the following:
select * // never do that in production
from someTable
where id in (10121005444, 206700013, 208700013, 30216118005, 30616118005)
order by decode(id, 10121005444, 1, 206700013, 2, 208700013, 3, 30216118005, 4, 30616118005, 5)
A: You can't specify the order using the IN clause. I think you have two options:
*
*perform the query using IN, and sort your result set upon receipt
*issue a separate query for each specified id in order. This is obviously less efficient but a trivial implementation.
A: you can use this query --
SELECT id FROM table
WHERE id in (10121005444, 206700013, 208700013, 30216118005, 30616118005)
ORDER BY FIND_IN_SET(id,
"10121005444, 206700013, 208700013, 30216118005, 30616118005");
second list define the order in which you want your result set to be
| {
"language": "en",
"url": "https://stackoverflow.com/questions/12461211",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Rails + React + real time validations I have a rails 5 + react application. In this application I would like to introduce validation.
Let's say I have a product model that has a price that must be greater than 0 and less than 5 or equal to 20.
I have 2 instances when I will validate the product model on creation:
*
*When everything is submited. I will validate in rails and I will send a message back to react telling the react part that yes it was ok 200, or no, this entity is not ok 422 + the errors in json format which can be mapped to the form fields
*When the user is actually typing. Let's say the user introduces 55 for the price which is greater than 20 so I want to instantly display that the price entered is not valid.
These both are very clear to me how to do them. I have some real time validations on the react side for the form and some backend validations that await for the submission of the form. Problem is I have to have the validation data(in this case the numbers 0, 5, 20) in both react and rails.
I have been thinking that maybe I can put these 'magic' numbers in an yml file and export them to react.
Is this the right approach? Does anyone have a better idea on how to store these values that must be in both react and rails ?
A: Pass your validations to React either as props or data attributes if your Rails app serves HTML, or in the JSON if it's a Single Page App (SPA).
Continue to validate server-side as well as it's dangerous to perform client-side only validation as it can be bypassed with direct server calls.
If you're passing JSON with constraints, you might want to consider a structure that would mimic available html5 validation attributes or your custom validation names.
{
"product": {
"attributes": {
"name": {
"type":"string",
"pattern":"[A-Za-z]",
},
"price": {
"type":"decimal",
"max":"20.00",
"min":"5.00",
},
}
}
}
A: If you use a form system like Formik you can serve a dynamic validation script by ssr. The usual way this is managed anyway is to keep validation separated
| {
"language": "en",
"url": "https://stackoverflow.com/questions/52116809",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: j2me, generate random location of food for simple snake game here is my code for the snake game, the thing i need to do is generate location for the snake food, once the snake touch the snake food, it will regenerate the location of the food~pls, i really need your guys help!!! just kindly have a look
package snake;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Graphics;
public class SnakeCanvas extends Canvas{
private int currentX =getWidth()/2;
private int currentY =getHeight()/2;
private boolean condition = false;
private boolean position = false;
Random rand = new Random();
int randomX=rand.nextInt(180) + 20;
int randomY =rand.nextInt(250) + 20;
private final Midlet midlet;
private int score = 0;
Timer t;
public SnakeCanvas(Midlet midlet)
{
this.midlet = midlet;
t = new Timer();
t.schedule(new TimerTask() {
public void run() {
if((condition==false)&&(position==false))
{
currentY -= 5 ;
}
if((condition==false)&&(position==true))
{
currentY += 5 ;
}
if((condition==true)&&(position==false))
{
currentX -= 5 ;
}
if((condition==true)&&(position==true))
{
currentX += 5 ;
}
}
}, 50, 50);
}
public void paint(Graphics g) {
boolean touch=false;
//drawing Background
g.setColor(0x000000);
g.fillRect(0, 0, getWidth(), getHeight());
//drawing snake
g.setColor(0xffffff);
g.fillRoundRect(currentX, currentY, 20, 20, 5, 5);
//snake food
g.setColor(234,41,42);
g.fillRect(randomX,randomY,10,10);
if((currentX-9<=randomX+4&¤tX+9>=randomX-4)&&(currentY-9<=randomY+4&¤tY+9>=randomY-4)){
addScore();
}
//drawing block
g.setColor(82,133,190);
g.fillRect(0, 0, getWidth(), 5);
g.fillRect(0, getHeight()-5, getWidth(), 5);
g.fillRect(0, 0, 5, getHeight());
g.fillRect(getWidth()-5, 0, 5, getHeight());
if((currentX>=getWidth()-10)||(currentX<5)||(currentY>=getHeight()-5)||(currentY<5))
midlet.GameOver();
g.setColor(142,255,17);
g.drawString("Score : "+score, 8, 7, Graphics.TOP|Graphics.LEFT);
repaint();
}
protected void keyPressed(int keyCode) {
System.out.println(keyCode);
switch(keyCode)
{
case -1:
condition = false;
position = false;
break;
case -2:
condition = false;
position = true;
break;
case -3:
condition = true;
position = false;
break;
case -4:
condition = true;
position= true;
break;
}
repaint();
}
private void addScore() {
score=score+1;**strong text**
}
private void food(){
Random rand = new Random();
int randomX=rand.nextInt(150) + 20;
int randomY=rand.nextInt(250) + 20;
}
}
A: Okay. I don't know if you managed to solve your problem but there seems to be a couple things wrong with your code.
First in this code block in the beginning:
Private int currentX =getWidth()/2;
private int currentY =getHeight()/2;
private boolean condition = false;
private boolean position = false;
Random rand = new Random();
int randomX=rand.nextInt(180) + 20;
int randomY =rand.nextInt(250) + 20;
^I am sure this does not compile, you can't have function calls when declaring header variables.
Second
if((condition==false)&&(position==false))
{
currentY -= 5 ;
}
if((condition==false)&&(position==true))
{
currentY += 5 ;
}
if((condition==true)&&(position==false))
{
currentX -= 5 ;
}
if((condition==true)&&(position==true))
{
currentX += 5 ;
}
}
}, 50, 50);
}
Your block coding style is horrible and hard to read. http://en.wikipedia.org/wiki/Programming_style#Indentation has a good guide on mastering this, read it!
This applies to your switch/case statements too!
Lastly your question:
private void food(){
Random rand = new Random();
int randomX=rand.nextInt(150) + 20;
int randomY=rand.nextInt(250) + 20;
}
^ Just generates random numbers, but doesn't do anything with them. I am guessing you meant:
private void food(){
Random rand = new Random();
randomX=rand.nextInt(150) + 20;
randomY=rand.nextInt(250) + 20;
}
which sets the classes global randomX and randomY to new values.
This doesn't help though since you don't actually call the Food() function anywhere in this class! And considering it is "Private" and can only be used by this class that must be an error.
tl;dr You need to study programming some more, but it is a good effort. I will help you more in the comments if you like. If my answer helped, please accept it.
Fenix
| {
"language": "en",
"url": "https://stackoverflow.com/questions/25407516",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Setting a Struts2 select tag to a variable from the request object I want to set the Struts2 select tag to a variable from the request object instead of the action class variable.
My action class is:
public class showSchdulesAction extends ActionSupport
public String execute() throws Exception {
...
HttpServletRequest request = ServletActionContext.getRequest();
request.setAttribute("repTypList",someObj.getCommonList());
...
}
}
My JSP page:
...
<s:select onchange="genRpt(this)" list="%{repTypList}" listKey="id" listValue="val" >
</s:select>
...
I want to set the repTypeList from the request object to select tag.
When I used list="%{repTypList}" or list="repTypList" then
I got error:
tag 'select', field 'list': The requested list key '%{repTypList}' could not be resolved as a collection/array/map/enumeration/iterator type. Example: people or people.{name}
When I use list="#{repTypList}" it's working but no value is shown in the combo options, even values in list.
A: There's no reason to get an object from the request in Struts2. If you are using Struts2 tag you can get the object from the valueStack via OGNL. However in Struts2 is possible to get the value from the request attributes using OGNL. For this purpose you should access the OGNL context variable request. For example
<s:select list="%{#request.repTypList}" listKey="id" listValue="val" />
The select tag requires not null value returned via OGNL expression in the list tag, as a result of null value you got the error. So, better to check this in the action before the result is returned.
public class showSchdulesAction extends ActionSupport
public String execute() throws Exception {
...
HttpServletRequest request = ServletActionContext.getRequest();
List list = someObj.getCommonList();
if (list == null) list = new ArrayList();
request.setAttribute("repTypList", list);
...
}
}
This code will save you from the error above.
A: Did you try like this..
list="%{#repTypList}"
OR
list="%{#request.repTypList}"
in struts 2 select tag
| {
"language": "en",
"url": "https://stackoverflow.com/questions/22420421",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Laravel Environments in Route I want to have different domains for my application based on the environment;
Like so; www.prod.co.uk and www.dev.co.uk
Now in my route.php I have defined subdomains like so;
Route::group(['domain' => 'www.prod.co.uk']
Route::group(['domain' => 'blog.prod.co.uk']
Route::group(['domain' => 'careers.prod.co.uk']
In the laravel documentation you can access the env based on what your have in your .env can I do something like below in my route.php?
Use App;
if (App::environment('production')) {
// The environment is local
$domain = www.prod.co.uk;
$subdomain1 = blog.prod.co.uk;
$subdomain2 = careers.prod.co.uk;
}
if (App::environment('local', 'staging')) {
// The environment is either local OR staging...
$domain = www.dev.co.uk;
$subdomain1 = blog.dev.co.uk;
$subdomain2 = careers.dev.co.uk;
}
Route::group(['domain' => $domain]
Route::group(['domain' => $subdomain1]
Route::group(['domain' => $subdomain2]
A: A nicer (IMHO) way to do this would be to define your custom domains in .env files – this way it's clear that domain names are environment-specific and there won't be a need for any 'ifs':
.env:
URL=www.dev.co.uk
SUBDOMAIN1=blog.dev.co.uk
SUBDOMAIN2=careers.dev.co.uk
Then add to config/app.php:
'url' => env('URL'),
'subdomain1' => env('SUBDOMAIN1'),
'subdomain2' => env('SUBDOMAIN2'),
routes.php would become simpler and nicer to read:
Route::group(['domain' => Config::get('app.url')] {}
Route::group(['domain' => Config::get('app.subdomain1')] {}
Route::group(['domain' => Config::get('app.subdomain2')] {}
PS. Imagine if you get more environment-specific URLs in the future – your routes.php will get bloated and it will (it already does, actually) contain environment-specific data which is not nice!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34668674",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to Align smaller text on top of larger text I have three text items in a container. The middle text has the larger font. I would like to align the top the first item to the top of the second item.
.container {
border: 1px solid black;
}
.container p {
display: inline-block;
}
.large {
font-size: 50px;
}
<body>
<div class="container">
<p class="first">One</p>
<p class="large">Two</p>
<p>Three</p>
</div>
</body>
https://jsfiddle.net/7ofrravh/2/
The only way I can think of to do this is to use absolute position but this gets out of line when I change the screen size. I want to be able to change the size of the screen and have everything stay in place. Does anyone know a way to do this?
A: Change CSS:
.container {
border: 1px solid black;
}
.container p {
display: inline-block;
vertical-align:top;
margin:0;
}
.large {
font-size: 50px;
line-height:1;
}
.container {
border: 1px solid black;
}
.container p {
display: inline-block;
vertical-align:top;
margin:0;
}
.large {
font-size: 50px;
line-height:1;
}
<body>
<div class="container">
<p class="first">One</p>
<p class="large">Two</p>
<p>Three</p>
</div>
</body>
A: Here is the edited version of your code
.container {
border: 1px solid black;
}
.container p {
display: inline-block;
margin:0;
}
.container p.first {
vertical-align:top;
line-height:40px;
}
.large {
font-size: 50px;
}
<body>
<div class="container">
<p class="first">One</p>
<p class="large">Two</p>
<p>Three</p>
</div>
</body>
A: You would need to change the code to look more like this:
.container {
border: 1px solid black;
}
.container p {
display: inline-block;
margin:0;
}
.large {
font-size: 50px;
line-height:1;
}
.first {
vertical-align:top;
}
<body>
<div class="container">
<p class="first">One</p>
<p class="large">Two</p>
<p>Three</p>
</div>
</body>
A: That's how I would do it: https://jsfiddle.net/7ofrravh/5/ .
By making container flexible with content alignment an the start by using align-items: flex-start . Then simply fixing first paragraph position with a margin: 10px 0 0 0.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/47299691",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Non-breaking characters appears when copying from datagrid I have a curious problem. When I copy a cell (or a row) that have spaces in groups of 2 or more, when I paste this spaces are replaced with non-breaking character (Alt+160). What is more curious is that if I paste on Word then copy from Word and paste again on my program the spaces are returned, but if I paste on Excel then copy from Excel and paste on my program the non-breaking characters are still there. Obviously, the easy way is not our way, we need to copy/paste to/from Excel.
I can control on my application the introduction of this character an replace it with spaces, suposing (what is never a good idea) that nobody would introduce non-breaking characters intentionally. But we work with another application in VB 6.0 with more than 200 windows, and I don't have my boss's permition for change anything on that app.
I've debugged my code and the datagrid doesn't have the non-breaking character. The clipboard doesn't have any non-breaking character after the copy. And if I copy the same text from a textbox no spaces are replaced with non-breaking characters at pasting.
this is the axml of one column of any of my datagrids:
<DataGridTextColumn Header="Machine" CanUserSort="True" IsReadOnly="True"
MinWidth="10" Width="*" MaxWidth="Infinity"
Binding="{Binding Path=NOM_MAQ}">
<DataGridTextColumn.ElementStyle>
<Style TargetType="{x:Type TextBlock}">
<Setter Property="ToolTip" Value="{Binding Path=NOM_MAQ}"/>
<Setter Property="TextTrimming" Value="CharacterEllipsis"/>
<Setter Property="TextWrapping" Value="NoWrap"/>
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>
I tried adding to the DataGridTextColumn a converter:
ClipboardContentBinding="{Binding Path=NOM_MAQ,
Converter={StaticResource QuitNonBreakingConverter}}"
class QuitNonBreakingConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter,
CultureInfo culture)
{
string texto = value.ToString();
StringBuilder sb = new StringBuilder(texto.Length);
foreach (char c in texto.ToCharArray())
{
if (char.Equals(c, System.Convert.ToChar(160)))
{
sb.Append(System.Convert.ToChar(32));
}
else sb.Append(c);
}
return sb.ToString();
}
public object ConvertBack(object value, Type targetType,
object parameter, CultureInfo culture)
{
return value;
}
}
But as I said before, the datagrid nor the clipboard have the non-breaking character, so this converter is futile.
Any idea on how to prevent this replace of characters??
A: have you looked at all of the data flavors on the clipboard?
the plain string might not have the nonbreaking character, but one of the other more specific kinds might? in word/excel do "paste special" to see what other formats are available, or enumerate them in code.
I'm betting there are multiple kinds of data on the clipboard, and word prefers one and excel favors the other, and you're getting just the plain text string in your code?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/8298007",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How can I hide certain attribute from response with Bookshelf? I am building a simple REST API. When registering a new user, my API returns:
{
"status": "success",
"data": {
"email": "[email protected]",
"password": "$2b$10$DcFdth1FKskyy6A7uwCHDOE15oy4pgZBj.TwEBcQnSVrUK4mntZdy"
"first_name": "Tester",
"last_name": "Test",
"id": 13
}
}
I want to hide the password field in my response like so:
{
"status": "success",
"data": {
"email": "[email protected]",
"first_name": "Tester",
"last_name": "Test",
"id": 13
}
}
I've added delete user.attributes.password to my code, but is this correct?
My code:
/**
* Auth Controller
*/
const bcrypt = require('bcrypt');
const debug = require('debug')('books:auth_controller');
const { matchedData, validationResult } = require('express-validator');
const models = require('../models');
/**
* Register a new user
*
* POST /register
*/
const register = async (req, res) => {
// check for any validation errors
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(422).send({ status: 'fail', data: errors.array() });
}
// get only the validated data from the request
const validData = matchedData(req);
console.log("The validated data:", validData);
// generate a hash of `validData.password`
// and overwrite `validData.password` with the generated hash
try {
validData.password = await bcrypt.hash(validData.password, models.User.hashSaltRounds);
} catch (error) {
res.status(500).send({
status: 'error',
message: 'Exception thrown when hashing the password.',
});
throw error;
}
try {
const user = await new models.User(validData).save();
debug("Created new user successfully: %O", user);
delete user.attributes.password;
res.send({
status: 'success',
data: user,
});
} catch (error) {
res.status(500).send({
status: 'error',
message: 'Exception thrown in database when creating a new user.',
});
throw error;
}
}
module.exports = {
register,
}
This is my user model. I am using Bookshelf.js.
/**
* User model
*/
module.exports = (bookshelf) => {
return bookshelf.model('User', {
tableName: 'users',
albums() {
return this.hasMany('Album');
},
photos() {
return this.hasMany('Photo');
}
}, {
hashSaltRounds: 10,
async fetchById(id, fetchOptions = {}) {
return await new this({ id }).fetch(fetchOptions);
},
async login(email, password) {
// find user based on the email (bail if no such user exists)
const user = await new this({ email }).fetch({ require: false });
if (!user) {
return false;
}
const hash = user.get('password');
// hash the incoming cleartext password using the salt from the db
// and compare if the generated hash matches the db-hash
const result = await bcrypt.compare(password, hash);
if (!result) {
return false;
}
// all is well, return user
return user;
}
});
};
A: you can add a list of model attributes to exclude from the output when serializing it. check it out here
return bookshelf.model('User', {
tableName: 'users',
hidden: ['password']
})
| {
"language": "en",
"url": "https://stackoverflow.com/questions/71356565",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Avoid multiple page redirects http://example.com > https://example.com -> https://www.example.com My site is slowing down due to multiple page redirects, as reported by GTMetrix and Google Pagespeed Insights if a user types domain.com:
URL: TIME SPENT:
http://example.com/ 285ms
https://example.com/ 452ms
https://www.example.com 0ms
I'm trying to get to just one (conditional?) redirect that will always end up in the https and www subdomain.
This is the current htaccess code:
RewriteEngine on
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} !^www
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$
RewriteRule ^ https://www.%1%{REQUEST_URI} [NE,L,R]
It works, but is there anyone obsessed with speed that can help to make it faster into just one rewrite condition?
I searched endlessly at Stack overflow (and elsewhere) but no alternatives are combining everything in one statement with conditions and make it faster than the present solution.
I'd really appreciate your insights!
A: Change the R flag to 301:
RewriteEngine on
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} !^www
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$
RewriteRule ^ https://www.%1%{REQUEST_URI} [NE,L,R=301]
because by default, it is a 302 (Temporary) redirect, and you avoid very many redirects.
http://httpd.apache.org/docs/current/rewrite/flags.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/65239265",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Free JavaScript/jQuery library for building stacked area charts I'm looking for free JS/jQuery library that allows building charts. Right now I have necessity to build stacked area charts.
Found the link (http://www.1stwebdesigner.com/css/top-jquery-chart-libraries-interactive-charts/) that describes probably few of the best options, but:
*
*jQuery Visualize Plugin - doesn't look like it can build stacked areas
*Highcharts - requires licensing
*Flot - doesn't look like it can build stacked areas, doesn't have good documentation
*jQuery Sparklines - suites well for mini-graphs only?
*jqPlot - Could not find stacked area...
Therefore there are a bunch, but can't find those that fits my needs.
Does anybody have any good experience with these or other libraries for building graphs? Could you please recommend your choice?
Thank you.
A: d3 is good for generating charts.
*
*Stacked Area Chart example
*Stacked Bar Chart example
*more examples...
A: The google Charts is very good. link here
They also have a very cool playground, where you can see all kind of charts available, their code, examples, live demos and some fun stuff to try out. click here for playgound
| {
"language": "en",
"url": "https://stackoverflow.com/questions/15287115",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to specify arguments after dots ... in R? This probably comes down to 'how to pass optional parameters to R functions'.
Take c() for example. It's definition is:
c(..., recursive = FALSE)
However, if I use it like this c(1:5, TRUE) it gives [1] 1 2 3 4 5 1 which is perfectly understandable, but also a bit strange since I'd expect it to be simple to figure out. I guess it IS simple and I'm simply not seeing the whole thing.
Cheers for answering and not raging. I googled and searched SO, but probably got too many wrong answered and gave up.
EDIT: edited due to illogical example.
A: I was waiting to see if any of the first commenters were going to answer, but they haven't so I will.
Since in the definition of c() the first argument is ..., you must completely name any arguments that follow for them to work correctly. I say arguments plural and not argument singular because there is actually a second, undocumented argument in c(). See Why does function c() accept an undocumented argument? for more on that. For arguments that come before ..., you can use partial argument matching, but for those after ... you must write the complete argument name.
What's happening in your example is that you are concatenating the numeric value of TRUE (which is 1) to the vector 1:5
as.numeric(TRUE) ## numeric value of TRUE
# [1] 1
c(1:5, TRUE) ## try no arg name, wrong result
# [1] 1 2 3 4 5 1
c(1:5, rec=TRUE) ## try partial arg matching, wrong result
# rec
# 1 2 3 4 5 1
Furthermore, recursive really does nothing in the manner that you're attempting to use it.
c(1:5)
# [1] 1 2 3 4 5
c(1:5, recursive=TRUE) ## 1:5 not recursive, same result
# [1] 1 2 3 4 5
is.recursive(c(1:5))
# [1] FALSE
It's more for concatenating list items, or any other recursive objects (see ?is.recursive).
(x <- as.list(1:5))
# [[1]]
# [1] 1
#
# [[2]]
# [1] 2
#
# [[3]]
# [1] 3
#
# [[4]]
# [1] 4
#
# [[5]]
# [1] 5
is.recursive(x)
# [1] TRUE
c(x, recursive=TRUE) ## correct usage on recursive object x
# [1] 1 2 3 4 5
| {
"language": "en",
"url": "https://stackoverflow.com/questions/27138972",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How to print CorePlot Graph I'm trying to print an NSView which includes a couple coreplot piecharts among other items. However the piecharts do not appear. I now understand that layer backed views do not print, but I'm having difficultly locating any examples where people circumvented this and printed coreplot graphs within a NSView. What is the best approach for this?
A: For me it worked as soon as I have set-up the printRect like:
NSRect printRect = NSZeroRect;
printRect.size.width = (printInfo.paperSize.width - printInfo.leftMargin - printInfo.rightMargin) * printInfo.scalingFactor;
printRect.size.height = (printInfo.paperSize.height - printInfo.topMargin - printInfo.bottomMargin) * printInfo.scalingFactor;
self.hostingView.printRect = printRect;
op = [NSPrintOperation printOperationWithView:self.hostingView printInfo:printInfo];
Note self.hostingViewrefers to the CorePlot hostingView.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/22813782",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Private Variables in Offloaded Fortran Parallel Loop I am offloading code to a GPU using OpenMP 4.5. So far everything is working on the GPU, except when I try to make parallel sections with private variables that are allocated before I offload.
I am using gcc 7.2.0 and cuda 9.2.88. I am running on CentOS 7 and am compiling it with
gfortran ./testCode.F90 -fopenmp -o ./test
Here is a sample code:
#define LENGTH_X 4
#define LENGTH_Y 4
#define PRINT
program main
use omp_lib
implicit none
real, allocatable :: testVar(:,:)
real :: error = 0
logical :: onCPU
integer :: i, j,k
allocate(testVar(LENGTH_X,LENGTH_Y))
do i = 1, LENGTH_X
testVar(i,:) = i
#ifdef PRINT
print *, testVar(i,:)
#endif
end do
onCPU = omp_is_initial_device()
!$omp target map(tofrom:testVar, onCPU,error)
!$OMP TEAMS DISTRIBUTE PARALLEL DO private(testVar) reduction(max:error)
do i = 2, LENGTH_X-1
do j = 2, LENGTH_Y-1
testVar(i,j) = 0.25
end do
end do
!$OMP END TEAMS DISTRIBUTE PARALLEL DO
onCPU = omp_is_initial_device()
!$omp end target
print *, "Ran on CPU", onCPU
print *, "New vars"
do i = 1, LENGTH_X
#ifdef PRINT
print *, testVar(i,:)
#endif
end do
end program main
This fails to compile with
unresolved symbol _gfortran_os_error
collect2: error: ld returned 1 exit status
mkoffload: fatal error: x86_64-pc-linux-gnu-accel-nvptx-none-gcc returned 1 exit status
compilation terminated.
lto-wrapper: fatal error: /opt/software/GCC/7.2.0-cuda-9.2.88-offload/libexec/gcc/x86_64-pc-linux-gnu/7.2.0//accel/nvptx-none/mkoffload returned 1 exit status
compilation terminated.
/opt/software/binutils/2.28-GCCcore-6.4.0/bin/ld: error: lto-wrapper failed
collect2: error: ld returned 1 exit status
If I change the private to shared it works fine. I am not new to fortran but know how to program in C/C++ and python. Any advice would be appreciated!
A: Fortran allocatables may imply dynamic memory allocation (whether or not that is then actually done on the offloading device), and that is implemented via support routines in libgfortran. I suppose _gfortran_os_error would be called in case of a memory allocation error. Per https://gcc.gnu.org/PR90386 "Offloading: libgfortran, libm dependencies" you currently have to manually specify -foffload=-lgfortran to resolve such errors.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57418216",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to filter stream values using Map of Lists? I have a list of entities and I need to remove some of them using filter and Map with necessary keys and values.
It looks like that. There is a List<Comment> commentsList and Map<Integer, List<Post>> postsById. Comment entity has method getByPostId. Map looks like <Post id, has amount of comments>.
I need to remove from commentsList comments that are related to Post that has less than 3 comments.
I tried to do like that:
Stream<E> ofAtLeastComments(Stream<E> comments, Stream<Post> posts, Integer count) {
Map<Integer, List<Post>> postById = posts
.collect(Collectors.groupingBy(Post::getId)
);
return comments
.filter(comment -> postById.get(comment.getCommentId()).size() >= count);
}
But it return zero value.
A: As JB Nizet pointed out, the code seems to confuse post ids and comment ids:
Stream<E> ofAtLeastComments(Stream<E> comments, Stream<Post> posts, Integer count) {
Map<Integer, List<Post>> posts = posts.collect(Collectors.groupingBy(Post::getId));
return comments.filter(comment -> posts.get(comment.getPostId()).size() >= count);
// ^^^^
}
But the method name sounds more like you want this:
<E extends Comment> Stream<Post> ofAtLeastComments(Stream<E> comments, Stream<Post> posts, Integer count) {
// Number of comments per post ID
Map<Integer, Long> commentCounts = comments
.collect(Collectors.groupingBy(Comment::getPostId, Collectors.counting()));
return posts.filter(post -> commentCounts.getOrDefault(post.getId(), 0L) >= count);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56909647",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: jQuery $.post causes browser stack overflow I have the following jQuery code:
var id_atual
var temp_id
var tempo_flash = 50
var $slide_atual = $('#slider .atual')
var $slide_prox = $('#slider .ocultar')
setInterval(function(){
id_atual = $slide_atual.attr('alt')
$.post('get_banner.php', {atual: id_atual}, function(proximo){
temp_id = proximo.split(';;')
$slide_prox.attr('src', temp_id[0]).load(function(){
$slide_atual.hide('fade', tempo_flash, function(){
$slide_atual.attr('alt', temp_id[1]).attr('src', temp_id[0]).load(function(){
$slide_atual.show('fade', tempo_flash)
})
})
})
})
}, 4000)
And the following HTML code:
<div id="slider">
<img src="imagens/slider/imagen-slider.jpg" alt="1" class="atual"/>
<img src="" alt="" class="ocultar" />
</div>
Where the class .ocultar have a
display: none;
The vars tempo_flash is only the animation time, and the file get_banner.php is only for getting the next banner from the mysql database. It is tested and working fine.
The problem I have is that after a little (4 or 5 banner changing) the browser stops answering (for Firefox Chrome and Opera) and on IE I get an alert Stack overflow at line: 3 and the javascript of the whole page stops working.
Any help appreciated!
A: Inside each iteration of the setInterval()ed function, you assign a .load() event to an image place holder. Assigning an event to an object does not remove existing ones!
So on second iteration, the image place holder will have two .load() event handlers, then three and so on; and every time the image is loaded, it will fire all event handlers attached to .load() event. You probably need to re-factor your code, perhaps by assigning the .load() event handler only once (and use semicolons).
A: you shouldn't use setInterval, you should use a setTimeout inside a function, and execute it on the callback of the $.post, something like:
var id_atual
var temp_id
var tempo_flash = 50
var $slide_atual = $('#slider .atual')
var $slide_prox = $('#slider .ocultar')
function tictac(){
setTimeout(function(){
id_atual = $slide_atual.attr('alt')
$.post('get_banner.php', {atual: id_atual}, function(proximo){
temp_id = proximo.split(';;')
$slide_prox.attr('src', temp_id[0]).load(function(){
$slide_atual.hide('fade', tempo_flash, function(){
$slide_atual.attr('alt', temp_id[1]).attr('src', temp_id[0]).load(function(){
$slide_atual.show('fade', tempo_flash)
})
})
})
})
ticktac();
}, 4000);
}
this way, the 4 seconds only start counting if and when the response from the server is complete, you will not have your overflow problems
| {
"language": "en",
"url": "https://stackoverflow.com/questions/10090098",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Missing npm-cli.js when trying to use NodeJS as portable without installing, on Windows I try to use TiddlyWiki as a portable folder with NodeJS on Windows, without installing NodeJS, following this tutorial.
But I am getting this error.
What am I doing wrong?
https://i.stack.imgur.com/LN0Qo.jpg
| {
"language": "en",
"url": "https://stackoverflow.com/questions/73919678",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can I set one element of the Gearmenu insensitive? I wanted to set one element of the gearmenu insensitive if the "load-failed" signal is emmited.
struct GActionEntry {
const gchar *name;
void (* activate) (GSimpleAction *action,
GVariant *parameter,
gpointer user_data);
const gchar *parameter_type;
const gchar *state;
void (* change_state) (GSimpleAction *action,
GVariant *value,
gpointer user_data);
};
this is what I found (https://developer.gnome.org/gio/stable/GActionMap.html#GActionEntry) and I also used it like this:
const GActionEntry app_actions[] = {
{ "setAsHome", set_clicked , NULL, NULL, NULL, {0, 0, 0} },
{ "about", about_clicked, NULL, NULL, NULL, {0, 0, 0} }
};
I now wanted to set the set_clicked inactive but I don't know how to do it.
I mean I know how to make a callback funktion for the "load-failed"-signal but not how to set it inactive in it.
int main (int argc, char **argv)
{
int status;
struct widget *w = g_malloc (sizeof (struct widget));
w->app = gtk_application_new ("org.gtk.dialog", G_APPLICATION_HANDLES_COMMAND_LINE);
g_signal_connect (w->app, "command-line", G_CALLBACK (activate), (gpointer) w);
g_action_map_add_action_entries (G_ACTION_MAP (w->app), app_actions,
G_N_ELEMENTS (app_actions), (gpointer) w);
status = g_application_run (G_APPLICATION (w->app), argc, argv);
g_object_unref (w->app);
// free the memory for the widgets struct
g_free (w);
w = NULL;
return status;
}
struct widget
{
GtkApplication *app;
GtkWidget *window;
GtkWidget *box;
GMenu *appmenu;
GMenu *editmenu;
GtkWidget *find;
GtkWidget *back;
GtkWidget *forward;
GtkWidget *home;
GtkWidget *entry;
GtkWidget *header;
GMenu *gearmenu;
GtkWidget *gearmenubutton;
GtkWidget *gearicon;
GtkWidget *status;
WebKitWebView *wv;
guint id;
const gchar *url;
const gchar *homedir;
gboolean success;
};
// create the gear menu button
w->gearmenubutton = gtk_menu_button_new();
w->gearicon = gtk_image_new_from_icon_name ("emblem-system-symbolic", GTK_ICON_SIZE_SMALL_TOOLBAR);
gtk_button_set_image (GTK_BUTTON (w->gearmenubutton), w->gearicon);
// create a menu for the gear button
w->gearmenu = g_menu_new();
g_menu_append (w->gearmenu, "_Set as Homepage", "app.setAsHome");
w->editmenu = g_menu_new();
g_menu_append (w->editmenu, "_About", "app.about");
g_menu_append_section (w->gearmenu, NULL, G_MENU_MODEL (w->editmenu));
gtk_menu_button_set_menu_model (GTK_MENU_BUTTON (w->gearmenubutton),
G_MENU_MODEL (w->gearmenu));
g_object_unref (w->editmenu);
g_object_unref (w->gearmenu);
A: in the load-failed callback you need to remove the "setAsHome":
g_action_map_remove_action(G_ACTION_MAP (w->app), "setAsHome"
the load failed signal also emits when there is a failure and you would be redirectet to an error message page. Keep in mind that your load-change signal will be emitted 2 times once because the url can't be loaded and than to load the error page.
In order to pake it "sensitive" again, you need to add it to your menu again.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56599573",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How can I follow DRY principles with this challenge? I solved this exercise on jshero.com but I know the solution can be written more cleanly, I just don't know how.
Here are the directions:
Write a function addWithSurcharge that adds two amounts with surcharge. For each amount less than or equal to 10, the surcharge is 1. For each amount greater than 10 and less than or equal to 20, the surcharge is 2. For each amount greater than 20, the surcharge is 3.
This challenge also supposes that you use if...else if...else to solve the exercise, so I'm mainly concerned with simplification and readability, but I am also curious about ternaries. Here is my attempt which works,
function addWithSurcharge(num1, num2) {
let surcharge = 0;
if (num1 <= 10) {
surcharge += 1;
} else if (num1 > 10 && num1 <= 20) {
surcharge += 2;
} else {
surcharge += 3;
}
if (num2 <= 10) {
surcharge += 1;
} else if (num2 > 10 && num2 <= 20) {
surcharge += 2;
} else {
surcharge += 3;
}
return surcharge + num1 + num2;
}
Thank you,
much appreciated!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/63349859",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Java Swing timer does not do what I want it to I need to write a program that uses a swing countdown timer to do something (in this case, print out a String in the console). It gets the needed delay info from a spinner and executes the code when I hit the Start button. However, when I enter a value in the spinner, it just waits for twice that many seconds and finishes the run without printing out anything.
private void StartActionPerformed(java.awt.event.ActionEvent evt) {
int x = (int) Spinner1.getValue() * 1000;
Timer TIMER = new Timer(x, new MyActionListener());
TIMER.start();
try {
Thread.sleep(x * 2);
} catch (InterruptedException e) {
}
TIMER.stop();
}
class MyActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
System.out.println("Something");
}
}
Any help would be greatly appreciated!
A: The problem is that you are locking out yourself.
With
Thread.sleep(x * 2);
you are blocking the EventDispatchThread that would run your ActionListener. Still the timer internally keeps a flag that the timeout occured and that it should run your ActionListener at the next possible time.
But
TIMER.stop();
is resetting the TIMER, so that the notification is lost.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37905813",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: Class.getResource() returns null after a long time running I'm using Class.getResource() to load a file from the jar of a long-running Java app. It works fine. But after the app has been running for a long time, it starts returning null.
How do I troubleshoot this? All I can see are exceptions caused by getResource() returning null; but I can't find out why it's returning null.
I have checked for unclosed streams returned by Class.getResourceAsStream(), but I'm not calling that. (Although, one of my libraries might...) I have also checked for FileInputStreams that aren't being closed, but I haven't found any. (FileInputStreams continue to be usable while this is happening.)
Edit: this appears to be the same issue as this one. Also, possibly related.
A: I fixed it. I had code that was reading the version out of MANIFEST.MF from an InputStream returned by URL.openStream():
String manifestPath = classPath.substring(0, webInfIndex) +
"/META-INF/MANIFEST.MF";
// DON'T DO THIS!!!
// openStream() returns an InputStream that never gets closed.
Manifest manifest = new Manifest(new URL(manifestPath).openStream());
Attributes attr = manifest.getMainAttributes();
String version = attr.getValue(Attributes.Name.IMPLEMENTATION_VERSION);
Fixing the leak using Java 7 try-with-resources:
try (InputStream inputStream = new URL(manifestPath).openStream()) {
Manifest manifest = new Manifest(inputStream);
Attributes attr = manifest.getMainAttributes();
String version = attr.getValue(Attributes.Name.IMPLEMENTATION_VERSION);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/38231863",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can I find the publication history of Python PEPs? While most PEPs have a created date, some do not, see PEP 249 for example. I'm curious about the history of the PEPs. Is there some resource that tracks the proposal, acceptance, and publication dates of such PEPs?
A: Look at the Git commits history from that PEP.
A: I found the answer (1999) by emailing Python's db-sig. In this case, 1999 is two years before the first git commit on the project.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/45786368",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Fetch Core Data as comma separated list I realise that I am missing something simple but as a Swift newbie I am going around in circles & would appreciate a pointer as to what I am doing wrong?!
I have a Core Data Entity called "Numbers" with an attribute (Int16) called "userNumbers". I am fetching the results like:
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Numbers")
//request.predicate = NSPredicate(format: "age = %@", "12")
request.returnsObjectsAsFaults = false
do {
let result = try context.fetch(request)
for data in result as! [NSManagedObject] {
print("\(data.value(forKey: "userNumbers") as! Int16)")
}
} catch {
print("Failed")
}
The result in my console is:
12
13
18
19
21
I need to know how to make this a comma separated list so I can use it in an array. Essentially I need the return to be: 12,13,18,19,21
Everything I try seems to be wrong!
A: First of all create a more specific fetch request to get a distinct result type
let request = NSFetchRequest<Numbers>(entityName: "Numbers")
A comma separated list is not possible because the type of userNumbers is numeric.
You can map the result to an array of Int16 with
do {
let result = try context.fetch(request) // the type is [Numbers]
let numberArray = result.map{$0.userNumbers}
print(numberArray)
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/55184177",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Error trying to import Nuget PackageProvider I have a computer behind a proxy and trying to get the Nuget package provider installed. I ran Install-PackageProvider -Name Nuget on a different PC on a different network and copied Nuget folder to $env:ProgramFiles\PackageManagement\ProviderAssemblies.
If I run Get-PackageProvider -ListAvailable it shows Nuget available.
PS C:\Windows\system32> Get-PackageProvider -ListAvailable
Name Version DynamicOptions
---- ------- --------------
msi 3.0.0.0 AdditionalArguments
msu 3.0.0.0
nuget 2.8.5.204
PowerShellGet 1.0.0.1 PackageManagementProvider, Type, S...
Programs 3.0.0.0 IncludeWindowsInstaller, IncludeSy...
However when I try to run Import-PackageProvider -Name Nuget I get the following error:
PS C:\Windows\system32> Import-PackageProvider -Name Nuget
Import-PackageProvider : No match was found for the specified search criteria and provider name 'Nuget'. Try 'Get-PackageProvider -ListAvailable' to see if the provider exists on the system.At line:1 char:1
+ Import-PackageProvider -Name Nuget
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (Nuget:String) [Import-PackageProvider], Exception
+ FullyQualifiedErrorId : NoMatchFoundForCriteria,Microsoft.PowerShell.PackageManagement.Cmdlets.ImportPackageProvider
Any suggestions? Thank you!
A: I was able to work around the proxy by using the following:
$wc = New-Object System.Net.WebClient
$wc.Proxy.Credentials = [System.Net.CredentialCache]::DefaultNetworkCredentials
$wc.Proxy.Address = "http://proxyurl"
Once I did this I was able to use Install-PackageProvider Nuget to install the proivder.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36612652",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to input variable in dbcontext.SqlQuery query? When creating this function in my Web API project controller everything works just fine.
public IQueryable<EquipmentApproval> GetUserEquipmentApprovalRejections(string username)
{
return db.EquipmentApprovals.SqlQuery("select * from EquipmentApproval where rejectedReason is not NULL AND createdBy = 'hmbangu'").AsQueryable<EquipmentApproval>();
}
But When I try yo add a variable parameter like this:
...
return db.EquipmentApprovals.SqlQuery("select * from EquipmentApproval where rejectedReason IS NOT NULL AND createdBy = @username" + new SqlParameter("@username", username)).AsQueryable<EquipmentApproval>()
...
I receive and error when I query the API, could someone tell me please tell how to add a variable to my dbcontext.SqlQuery() query. I also want my data to be returend as an IQueryable list.
A: You need to add them comma separated
return db.EquipmentApprovals
.SqlQuery("select * from EquipmentApproval where rejectedReason IS NOT NULL AND createdBy = @username",
new SqlParameter("username", username))
.AsQueryable<EquipmentApproval>()
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60230368",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: webpack not working when introducing routes on react I am using webpack 4 to automate some tasks for my web app.
Page shows blank on production mode, when running command: npm run build
it works with npm run start all good. The thing is webpack is not being able somehow to deal with this part:
<BrowserRouter><AppRoutes/></BrowserRouter>
And my index.js looks as:
import React from "react";
import ReactDOM from "react-dom";
import { BrowserRouter } from 'react-router-dom';
import AppRoutes from './routes';
require('../src/assets/styles/main.scss');
console.log("I am being called index.js...");
ReactDOM.render(<BrowserRouter><AppRoutes/></BrowserRouter>, document.getElementById("index"));
while webpack looks like:
const HtmlWebPackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const CleanWebpackPlugin = require('clean-webpack-plugin');
const webpack = require('webpack');
module.exports = (env, argv) => {
console.log("ENV DETECTED: " + argv.mode);
return {
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
},
{
test: /\.html$/,
use: [
{
loader: "html-loader",
options: {
minimize: true
}
}
]
},
{
test: /\.css$/,
use: [
MiniCssExtractPlugin.loader,
// 'style-loader',
{
loader: 'css-loader',
options: {
importLoaders: 1,
minimize: true
}
},
{
loader: 'postcss-loader',
options: {
config: {
path: './postcss.config.js'
}
}
}
]
},
{
test: /\.scss$/,
use: [
argv.mode !== 'production' ? 'style-loader' : MiniCssExtractPlugin.loader,
{
loader: 'css-loader',
options: {
importLoaders: 1,
minimize: true
}
},
{
loader: 'postcss-loader',
options: {
config: {
path: './postcss.config.js'
}
}
},
"sass-loader"
]
}
],
},
plugins: [
new CleanWebpackPlugin('dist', {}),
new HtmlWebPackPlugin({
template: "./src/index.html",
filename: "./index.html"
}),
new MiniCssExtractPlugin({
filename: "main.css",
chunkFilename: "[id].css"
}),
require('autoprefixer'),
]
}
};
I dont know why on production the app is not showing the components at all!
ANy help on this?
Edited:
My routes.js looks as following:
import React from "react";
import { Switch, Route } from 'react-router-dom';
import Helloworld from './components/helloworld/helloworld.component';
import SecondView from './components/secondview/secondview.component';
import ThirdView from "./components/thirdview/thirdview.component";
const AppRoutes = () => (
<main>
<Switch>
<Route exact path='/' component={Helloworld}/>
<Route path='/secondview' component={SecondView}/>
<Route path='/thirdview' component={ThirdView}/>
<Route path='/thirdview/:number' component={ThirdView}/>
</Switch>
</main>
);
export default AppRoutes;
if I change <Route exact path='/' component={Helloworld}/> to <Route path='/' component={Helloworld}/> it works, but then I have problem navigation to other components, somehow my page url is different when I open the index.html on production mode.
The error I get when trying to navigate from helloworld component(after removing exact from Route tag) to secondview component is :
DOMException: Failed to execute 'pushState' on 'History': A history
state object with URL 'file:///secondview' cannot be created in a
document with origin 'null' and URL
'file:///home/webapp/Desktop/myapp/dist/index.html'.
A: Serve App With Express
Basically, when you change paths you are moving away from your index.html unless you serve the react app with a server of some kind. Try to setup an express server for index with something like this:
const express = require('express')
const path = require('path')
const port = process.env.PORT || 3000
const app = express()
// serve static assets eg. js and css files
app.use(express.static(__dirname + '/public'))
// Handles all routes
app.get('*', function (request, response){
response.sendFile(path.resolve(__dirname, 'public', 'index.html'))
})
app.listen(port)
console.log("server started on port " + port)
You can put this in your root directory as server.js, make sure index is being referred to in the sendFile line (right now assumes index.html is in /public directory), run this with babel-node server.js, and should serve your app on localhost:3000.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/50291662",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to get a signal from 74595
I used the code as shift_register_write_byte(0xFF);
I want to use the shift_register_write_byte function to generate an LED output based on an 8bit data variable.
But I did not receive a signal. How can I get a signal? Thank you!
void shift_register_reset(void){
GPIOA->BSRR=GPIO_PIN_9;
Delay_us(5);
GPIOA->BRR=GPIO_PIN_9;
Delay_us(5);
GPIOA->BSRR=GPIO_PIN_9;}
void shift_register_clk_pulse(void){
GPIOA->BSRR=GPIO_PIN_8;
Delay_us(5);
GPIOA->BRR=GPIO_PIN_8;
}
void shift_register_load_pulse(void){
GPIOA->BSRR=GPIO_PIN_10;
Delay_us(5);
GPIOA->BRR=GPIO_PIN_10;
}
void shift_register_write_byte(uint8_t data){
shift_register_reset();
for(int i=0;i<8;i++){
if(((data>>i) &0x01) == 0 ){
GPIOA->BSRR = GPIO_PIN_15;
HAL_Delay(5);
shift_register_clk_pulse();
}
else if(((data>>i)& 0x01) == 1){
GPIOA->BSRR = GPIO_PIN_15;
HAL_Delay(5);
GPIOA->BRR = GPIO_PIN_15;
shift_register_clk_pulse();
}
}
HAL_Delay(5);
shift_register_clk_pulse();
HAL_Delay(5);
shift_register_load_pulse();}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/59694674",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Java: Runtime reflection in compilation phase (?!) In Element#getAnnotation(Class<A> annotationType) javadoc it is stated that
Note: This method is unlike others in this and related interfaces. It
operates on runtime reflective information — representations of
annotation types currently loaded into the VM — rather than on the
representations defined by and used throughout these interfaces.
Consequently, calling methods on the returned annotation object can
throw many of the exceptions that can be thrown when calling methods
on an annotation object returned by core reflection. This method is
intended for callers that are written to operate on a known, fixed set
of annotation types.
Yet, this method is frequently used in annotation processing which is part of the compilation phase. What I want to understand is what, how, and why things gets loaded to VM at compilation time, and what are the pros and cons.
For example, in the case of Element#getAnnotation(Class<A> annotationType), is there any drawbacks (except possibly not being able to access values of type class in the annotation), compared to if we get the same information using mirrors (which is usually the longer code)?
A: The javac compiler is expected to be a JVM application (if only because javax.lang.model is a Java-based API). So it can naturally use runtime Reflection during it's execution.
What the documentation tries to say, — a bit clumsily perhaps, — is that JVM compiler isn't expected to load the classes it builds from source code (or their binary compilation dependencies). But when you use Element#getAnnotation(Class<A> annotationType), it might have to.
The documentation you cited actually lists several Exception classes, that may be thrown due to this:
*
*MirroredTypeException. As you already realized, it is thrown when you try to load a type that hasn't been built yet, used as argument within an annotation.
*AnnotationTypeMismatchException, EnumConstantNotPresentException and IncompleteAnnotationException. Those exceptions can be thrown when the version of annotation loaded by javac does not match the version, referenced by build classpath
The mismatched versions can be hard to avoid, because some build systems, such as Gradle, require you to specify annotation processor separately from the rest of dependencies.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/71678433",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: remote website actions and interaction exists any option, which allows me to visit any website as a "bot" and do there some actions as clicks on elements, write texts into inputs, submit an form...
I've found some solution with php curl, but it only remotely connects to website and can send HTTP requests, but I can't click on elements and redirection doesn't work also.
I'm looking for somethink like iframe with javascript timed action such as:
PSEUDOCODE:
if page is loaded {
find elem with id "button" and click on them
if redirected page is loaded {
fint input with id "x" and set value to "y"
click on submit button
return innerHTML of element with id "response-text"
}
}
But I cant send data to iframe and find elements in iframe externaly, or I don't know how :(
Is there any way how to do this?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/38199963",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Invalid XML format after removing node I have a form with load, save, add and navigation buttons, which manipulates an XML file.
Here's the structure and content of the XML file:
<?xml version="1.0" encoding="utf-8"?>
<BookList>
<Book>
<Title>Song of myself</Title>
<Author>Walt Whitman</Author>
<isbn>234-0232</isbn>
<Year>1999</Year>
<Editure>Some editure</Editure>
</Book>
<Book>
<Title>Richard III</Title>
<Author>William Shakespeare</Author>
<isbn>234-23432</isbn>
<Year>2001</Year>
<Editure>Some other editure</Editure>
</Book>
</BookList>
And here's the code for the delete button (which I have issues with):
private void button8_Click(object sender, EventArgs e)
{
XmlNodeList nodes = xmlDoc.SelectNodes("//BookList/Book");
foreach (XmlNode item in nodes)
{
string ISBN = item["isbn"].InnerText;
if (ISBN == textBox3.Text)
{
try
{
item.ParentNode.RemoveChild(item);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
saveFile();
xpatNav = moveToFirstBook(xpatNav);
List<String> values = this.retrieveCurrentValues(xpatNav);
loadTextBoxes(values);
}
The form has an ISBN text field. The code iterates through the XML nodes and, if the ISBN of the current node is the same as the ISBN of the node from the form, it deletes it (well, it should). Then the file is saved, and the form positions itself on the first node (the last three nodes).
However, let's say we position ourselves on the last book - when I press the delete button, all I get is a messed up xml file, which looks like this:
<?xml version="1.0" encoding="utf-8"?>
<BookList>
<Book>
<Title>Song of myself</Title>
<Author>Walt Whitman</Author>
<isbn>234-0232</isbn>
<Year>1999</Year>
<Editure>Some editure</Editure>
</Book>
</BookList>
<Title>Richard III</Title>
<Author>William Shakespeare</Author>
<isbn>234-23432</isbn>
<Year>2001</Year>
<Editure>Some other editure</Editure>
</Book>
</BookList>
I tried a multitude of ways to accomplish it, but I simply don't get it.
[EDIT]
Ok, so I changed a bit the code, at the suggestion of Jens Erat. The delete button code looks like(minor change though):
private void button8_Click(object sender, EventArgs e)
{
XmlNodeList node = xmlDoc.SelectNodes("//ListaCarti/Carte[isbn='" + textBox3.Text + "']");
try
{
node.Item(0).ParentNode.RemoveChild(node.Item(0));
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
saveFile();
xpatNav = moveToFirstBook(xpatNav);
List<String> values = this.retrieveCurrentValues(xpatNav);
loadTextBoxes(values);
}
Here's the code for saving the file:
private void saveFile()
{
fs = new FileStream(this.openedXml, FileMode.Open, FileAccess.Write, FileShare.Write);
xmlDoc.Save(fs);
fs.Close();
}
where this.openedXml it's the path to the opened XML.
And here's the code for the loading button:
public void loadXml()
{
if (XMLloaded)
{
try
{
fs = new FileStream(this.openedXml, FileMode.Open, FileAccess.Read);
xmlDoc.Load(fs);
fs.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
xpatNav = xmlDoc.CreateNavigator();
XPathNavigator xnav = xpatNav;
countNodes(xnav);
// we load the first value into the form
if (this.nodesNumber > 0) // if the XML it's not empty
{
xnav = moveToFirstBook(xnav
//this retrieve the values for current title, author, isbn, editure
List<string> values = retrieveCurrentValues(xnav);
loadTextBoxes(values);
}
}
}
I think this looks a bit messy, so here could be a problem.
A: Change your Save() method. The current one is only overwriting the start of the file but not removing the old (longer) content.
private void saveFile()
{
//fs = new FileStream(this.openedXml, FileMode.Open, FileAccess.Write, FileShare.Write);
fs = new FileStream(this.openedXml, FileMode.Create);
xmlDoc.Save(fs);
fs.Close();
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/17389489",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to check if the current locale uses 24-hour clock in Android? I have a time picker dialog in my app. This works just fine, but I'd like to switch between the 12-hour and 24-hour picker dialogs based on the current locale. How do I find out which clock is used?
The dialog itself is launched like this:
boolean use24HourClock = true; // This i'd like to get from the locale
new TimePickerDialog(this, new TimePickerDialog.OnTimeSetListener()
{
@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute)
{
}
}, 12, 00, use24HourClock).show();
A: Try this
boolean use24HourClock = DateFormat.is24HourFormat(getApplicationContext());
Returns true if user preference is set to 24-hour format.
See more about DateFormat here
A: Try this
public static boolean usesAmPm(Locale locale)
{
String pattern = DateTimeFormatterBuilder.getLocalizedDateTimePattern(
FormatStyle.MEDIUM, FormatStyle.MEDIUM, IsoChronology.INSTANCE, locale);
return pattern.contains("a");
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31915699",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: CasperJS not following redirect to HTTPS I'm trying to use CasperJS to automate away a lot of tedious data entry. Specifically, to register a very large batch of camera equipment on the canon website.
I have code to handle form filling and have no problems navigating around webpages using CasperJS but I can't get CasperJS to navigate to the login page.
Here's what I have so far:
var casper = require('casper').create({
verbose: true,
userAgent: 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.101 Safari/537.36',
logLevel: "debug"
});
phantom.cookiesEnabled = true;
casper.start();
casper.thenOpen('https://b2cweb.usa.canon.com/b2cweb/view/myAccountHome.jsf?LOGINACTION=Y', function(response) {
require('utils').dump(response);
});
casper.run();
Note: The code above dumps the header contents once it reaches the page. I have also tried different user agent strings in case Adobe actively blocks crawlers.
The link works flawlessly in Google Chrome but CasperJS just logs the following.
Loading resource failed with status=fail
From Google Dev Tools it appears that the link 302 redirects to
https://b2cweb.usa.canon.com/b2cweb/view/myAccountHome.jsf?LOGINACTION=Y
Then 301 redirects to:
https://b2cweb.usa.canon.com/b2cweb/view/login.jsf?TYPE=33554432&REALMOID=06-979697ef-63e3-49da-a97f-795f9d794fcc&GUID=&SMAUTHREASON=0&METHOD=GET&SMAGENTNAME=-SM-EA3lbvOPfpMVWEZ5fDNhRBdvP75YFZ%2fmmFcIOEdxcmO9f3eSAXAISOKvl7eaVyQm&TARGET=-SM-HTTP%3a%2f%2fb2cweb%2eusa%2ecanon%2ecom%2fb2cweb%2fview%2fmyAccountHome%2ejsf%3fLOGINACTION%3dY
I'm assuming that the redirects are the cause behind why CasperJS can't fetch the login page.
Is it possible to make CasperJS follow these types of redirects? Can CasperJS be used to browse and/or login via HTTPS?
Update:
I'm not so sure if it's a redirect that's causing the issue.
As a workaround, I tried pre-preloading the session cookie (copied from chrome) into casperjs then navigating directly to the account page.
I also tried adding the --ignore-ssl-errors=true flag to the command with no success.
No matter what I do it returns an about:blank url.
A: The following will get you to the sign in page:
var casper = require("casper").create ({
waitTimeout: 15000,
stepTimeout: 15000,
verbose: true,
viewportSize: {
width: 1400,
height: 768
},
onWaitTimeout: function() {
logConsole('Wait TimeOut Occured');
this.capture('xWait_timeout.png');
this.exit();
},
onStepTimeout: function() {
logConsole('Step TimeOut Occured');
this.capture('xStepTimeout.png');
this.exit();
}
});
casper.on('remote.message', function(msg) {
logConsole('***remote message caught***: ' + msg);
});
casper.userAgent('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/537.4 (KHTML, like Gecko) Chrome/22.0.1229.94 Safari/537.4');
// vars
var gUrl = 'http://www.usa.canon.com/cusa/home';
// Open URL and click sign in
casper.start(gUrl, function() {
this.clickLabel('Sign In', 'a');
});
//Sign in page
casper.then(function () {
//+++ ready for you to fill user information.
this.capture('xSignIn.png'); //+++ shows you are on signin page. can remove.
});
casper.run();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/19939062",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Process.Kill() and process events Here is the situation:
I have to create a program that would input another processes output stream into textbox. That it self wouldn't cause too much problem. What does, however, is the fact that I have to run 5 instances of this console application and redirect output to 5 textboxes, as well as to be able to kill any of these processes at any time. As far as I have learned, the best way to do this is asynchronously. But the problem here is with killing processes, that are created on different thread. How do I kill it without having access to it since it doesn't exist in scope where I have to kill it. My best guess is to get its PID on Process.Start(), so I can kill it, so...
Is it possible to fire any event from process on Process.kill() command?
And if not - is there a way to kill a process in about the same time interval as Process.Kill() that does fire some sort of event?
Or maybe someone could suggest me some other approaches or best practice on how these problems are usually solved?
EDIT: The reason I am running all processes on different threads is that I use Thread.Sleep() on some of them if there is and input parameter that tell me that the process must be killed after x seconds.
A: Process.Kill() command for some reason, does, in fact, fire process exited event. Easiest way for me to know that the process was killed, was by making a volatile string that holds information about how it ended. (Change it to "killed" before process.kill etc...)
A: First of all you do not need Threads at all. Starting a process is async in itself, so Process.Start(...) does not block and you can create as many processes as you want.
Instead of using the static Process.Start method you should consider creating Process class instances and set the CanRaiseEvents property to true. Further there are a couple of events you can register (per instance) - those will only raise if CanRaiseEvents is set to true, but also after a process is/has exited (including Kill() calls).
A: When you call
Process.Start()
it returns a Process class instance, which you can use to retrieve information from it output and kill that process any time
Process p = Process.Start("process.exe");
//some operations with process, may be in another thread
p.Kill()
| {
"language": "en",
"url": "https://stackoverflow.com/questions/8984617",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How can I work with SQL NULL values and JSON in a good way? Go types like Int64 and String cannot store null values,
so I found I could use sql.NullInt64 and sql.NullString for this.
But when I use these in a Struct,
and generate JSON from the Struct with the json package,
then the format is different to when I use regular Int64 and String types.
The JSON has an additional level because the sql.Null*** is also a Struct.
Is there a good workaround for this,
or should I not use NULLs in my SQL database?
A: Types like sql.NullInt64 do not implement any special handling for JSON marshaling or unmarshaling, so the default rules apply. Since the type is a struct, it gets marshalled as an object with its fields as attributes.
One way to work around this is to create your own type that implements the json.Marshaller / json.Unmarshaler interfaces. By embedding the sql.NullInt64 type, we get the SQL methods for free. Something like this:
type JsonNullInt64 struct {
sql.NullInt64
}
func (v JsonNullInt64) MarshalJSON() ([]byte, error) {
if v.Valid {
return json.Marshal(v.Int64)
} else {
return json.Marshal(nil)
}
}
func (v *JsonNullInt64) UnmarshalJSON(data []byte) error {
// Unmarshalling into a pointer will let us detect null
var x *int64
if err := json.Unmarshal(data, &x); err != nil {
return err
}
if x != nil {
v.Valid = true
v.Int64 = *x
} else {
v.Valid = false
}
return nil
}
If you use this type in place of sql.NullInt64, it should be encoded as you expect.
You can test this example here: http://play.golang.org/p/zFESxLcd-c
A: If you use the null.v3 package, you won't need to implement any of the marshal or unmarshal methods. It's a superset of the sql.Null structs and is probably what you want.
package main
import "gopkg.in/guregu/null.v3"
type Person struct {
Name string `json:"id"`
Age int `json:"age"`
NickName null.String `json:"nickname"` // Optional
}
If you'd like to see a full Golang webserver that uses sqlite, nulls, and json you can consult this gist.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/33072172",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "55"
} |
Q: Toggle form inside v-for using vue.js How can i toggle form inside v-for loop,I have a form inside v-for which i want to display (toggle) on click.
But when i click all the form inside the v-for gets toggled.
Secondly is it better approach to keep the form inside the loop,when have large amount of data inside loop or load it as a separate component.
This is what i am trying to do.
new Vue({
el: "#app",
data: {
todos: [{
text: "Learn JavaScript"
},
{
text: "Learn Vue"
},
{
text: "Play around in JSFiddle"
},
{
text: "Build something awesome"
}
],
show: ''
},
methods: {
toggle: function(todo) {
this.show = !this.show
}
}
})
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}
#app {
background: #fff;
border-radius: 4px;
padding: 20px;
transition: all 0.2s;
}
li {
margin: 8px 0;
}
h2 {
font-weight: bold;
margin-bottom: 15px;
}
del {
color: rgba(0, 0, 0, 0.3);
}
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
<div id="app">
<h2>Todos:</h2>
<ol>
<li v-for="(todo,key) in todos">
<p>
{{ key+1 }} - {{ todo.text}} <span @click="toggle(todo)"><b>Contact</b></span>
<div v-if="show">
<hr />
<p>
<label>Message</label>
<input type="text">
</p>
<hr />
</div>
</p>
</li>
</ol>
</div>
A: There is only 1 reactive variable show. Setting it to true while all form is using v-if="show", will show everything.
You can set show to something that each form uniquely have. For example, its text, and perform a v-if using its text.
demo: https://jsfiddle.net/jacobgoh101/umaszo9c/
change v-if="show" to v-if="show === todo.text"
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
<div id="app">
<h2>Todos:</h2>
<ol>
<li v-for="(todo,key) in todos">
<p>
{{ key+1 }} - {{ todo.text}} <span @click="toggle(todo)"><b>Contact</b></span>
<div v-if="show === todo.text">
<hr />
<p>
<label>Message</label>
<input type="text">
</p>
<hr />
</div>
</p>
</li>
</ol>
</div>
change toggle method
new Vue({
el: "#app",
data: {
todos: [{
text: "Learn JavaScript"
},
{
text: "Learn Vue"
},
{
text: "Play around in JSFiddle"
},
{
text: "Build something awesome"
}
],
show: ''
},
methods: {
toggle: function(todo) {
if (this.show === todo.text)
this.show = false
else
this.show = todo.text
}
}
})
A: property "show" should be a prop of todo,not prop of data
new Vue({
el: "#app",
data: {
todos: [{
text: "Learn JavaScript"
},
{
text: "Learn Vue"
},
{
text: "Play around in JSFiddle"
},
{
text: "Build something awesome"
}
].map(o=>({...o,show:false}))
},
methods: {
toggle: function(todo) {
todo.show = !todo.show
}
}
})
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}
#app {
background: #fff;
border-radius: 4px;
padding: 20px;
transition: all 0.2s;
}
li {
margin: 8px 0;
}
h2 {
font-weight: bold;
margin-bottom: 15px;
}
del {
color: rgba(0, 0, 0, 0.3);
}
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
<div id="app">
<h2>Todos:</h2>
<ol>
<li v-for="(todo,key) in todos">
<p>
{{ key+1 }} - {{ todo.text}} <span @click="toggle(todo)"><b>Contact</b></span>
<div v-if="todo.show">
<hr />
<p>
<label>Message</label>
<input type="text">
</p>
<hr />
</div>
</p>
</li>
</ol>
</div>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/50501886",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Display images from Assets with JSON - Windows Phone 8 I am making a WP8 application with a lot of local content in my Assets folder. So I am using a JSON file stored in the a JSON folder.
I have been able to parse the JSON to C# very easily and now I am trying to display the data in a list. I had no problem with displaying the title but I am unable to display an image, even with the filename I am got.
My images are stored in "Assets/Content/mediaXXX.jpg";
ListViewModel :
public class ListViewModel
{
public string Title { get; set; }
public string Subtitle { get; set; }
public BitmapImage ListImage { get; set; }
}
XAML
<ListBox Margin="0,1,0,0"
Height="730"
x:Name="MainList">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid Height="120"
Width="480">
<StackPanel Orientation="Horizontal">
<Image HorizontalAlignment="Left"
Source="{Binding ListImage}"
Margin="12"
Stretch="UniformToFill"
Width="130"/>
<Grid>
<TextBlock x:Name="ListItemTitle"
Text="{Binding Title}"/>
<TextBlock x:Name="ListItemSubTitle"
Text="{Binding Subtitle}"/>
</Grid>
</StackPanel>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
And my C# page
BitmapImage image = new BitmapImage(new Uri(@"Assets/Content/" + photo.filename + ".jpg", UriKind.Relative);
l.ListImage = image;
Any idea?
A: Code should work. Only problems that might occur is your ListBox databinding is incorrectly defined.
I don't see any .ItemsSource = or ItemsSource={Binding some_collection}
Another thing is make sure that photo.filename is returning the correct file.
Set a string debug_string = "Assets/Content/" + photo.filename + ".jpg";
Make sure everything is correct.
Last thing is to make sure the files are actually in the Assets Folder inside the project and its
BuildAction is set to Content
like so
| {
"language": "en",
"url": "https://stackoverflow.com/questions/26962833",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Flashing cells in excel despite conditional formatting I have some code below which makes cells within a predefined range, flash color from white to red.
For my purposes, I need this code to work only on cells that have certain values in them - for example any cell that has a numerical value below 50.
The code that works on the entire range is as follows
Public NextFlash As Double
Public Const FR As String = "Sheet1!B3:D6"
Sub StartFlashing()
If Range(FR).Interior.ColorIndex = 3 Then
Range(FR).Interior.ColorIndex = xlColorIndexNone
Else
Range(FR).Interior.ColorIndex = 3
End If
NextFlash = Now + TimeSerial(0, 0, 1)
Application.OnTime NextFlash, "StartFlashing", , True
End Sub
Sub StopFlashing()
Range(FR).Interior.ColorIndex = xlColorIndexNone
Application.OnTime NextFlash, "StartFlashing", , False
End Sub
A: Something like this to look at each cell.
Another option to avoid looking at each cell would be to alter your range "Sheet1!B3:D6" so that it only was set to cells below 50. But this would require constant tracking and re-evaluating the range for changes with events.
So for a 12 cell range, the loop approach below should suffice.
Public NextFlash As Double
Public Const FR As String = "Sheet1!B3:D6"
Sub StartFlashing()
Dim rng1 As Range
For Each rng1 In Range(FR).Cells
If rng1.Value < 50 Then
If rng1.Interior.ColorIndex = 3 Then
rng1.Interior.ColorIndex = xlColorIndexNone
Else
rng1.Interior.ColorIndex = 3
End If
Else
rng1.Interior.ColorIndex = xlColorIndexNone
End If
Next
NextFlash = Now + TimeSerial(0, 0, 1)
Application.OnTime NextFlash, "StartFlashing", , True
End Sub
Sub StopFlashing()
Range(FR).Interior.ColorIndex = xlColorIndexNone
Application.OnTime NextFlash, "StartFlashing", , False
End Sub
| {
"language": "en",
"url": "https://stackoverflow.com/questions/29580197",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Including Label Values When Emailing HTML Form Submissions I've created a dynamic HTML form that uses jQuery and customizes the form fields and labels based on the users' input.
In addition to passing the form field values to the $_POST[] array, is there also a simple way to pass the label values? I need to turn the form submission into an email, and the email should include the same label names that appeared on the form. I've contemplated using hidden input fields, but that doesn't seem like an ideal option.
Any ideas?
A: There is no use in sending those label texts around. It is unnecessary traffic, and one more thing that needs to be filtered/validated.
You create the form on the server side, so you already have access to the texts of the labels there. I'd advise you to store these texts in constants, like:
define('TEXT_EMAIL', 'Email Address');
So when you create the form, you can just type:
<label for="email"><?=TEXT_EMAIL?></label>
and use the same constant (TEXT_EMAIL and the others) when you build the email body. This way, you will also be in an easy situation if you need to add support for other languages.
A: ... maybe add the label values to dynamically created hidden fields in the form? Just name the fields (prefix them?) in such a way that you can identify them easily on the server side.
A: You are right to consider hidden form fields if you're not POSTing the data to the server through an Ajax request.
Assuming a regular form submission, only values of input and textarea elements are sent to the server. Adding appropriate hidden input elements and setting the values of these from the labels is your only option.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/6089337",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to hide/protect password details in php? I'm making a website in which I'm trying to create a form that will send the user-input to a google spreadsheet in my google docs/drive... I found a Github project that lets people code the php... It includes 2 other php files which are needed for the script. The code is as follows:
My question is, how can I hide my password from this script under $u = / $p = ??
Anyone viewing the code can see my password.. how can I prevent that?
Link to the script's source is : http://www.farinspace.com/saving-form-data-to-google-spreadsheets/
<?php
// Zend library include path
set_include_path(get_include_path() . PATH_SEPARATOR . "$_SERVER[DOCUMENT_ROOT]/ZendGdata-1.8.1/library");
include_once("Google_Spreadsheet.php");
$u = "[email protected]";
$p = "password";
$ss = new Google_Spreadsheet($u,$p);
$ss->useSpreadsheet("My Spreadsheet");
$ss->useWorksheet("wks2");
// important:
// adding a leading alpha char prevents errors, there are issues
// when trying to lookup an identifier in a column where the
// value starts with both alpha and numeric characters, using a
// leading alpha character causes the column and its values to be
// seen as a strictly a strings/text
$id = "z" . md5(microtime(true));
$row = array
(
"id" => $id // used for later lookups
, "name" => "John Doe"
, "email" => "[email protected]"
, "comments" => "Hello world"
);
if ($ss->addRow($row)) echo "Form data successfully stored";
else echo "Error, unable to store data";
$row = array
(
"name" => "John Q Doe"
);
if ($ss->updateRow($row,"id=".$id)) echo "Form data successfully updated";
else echo "Error, unable to update spreadsheet data";
?>
A: You can attempt to hide if from peering eyes using the code below. It would still be discoverable if you tried, but at least it's away from open text view. All it does is add characters to the text and then subtract them before it uses the password.
Run this script using your original password
<?php
$password = "test";
echo "Original Password In Plain Text = $password\n";
$len=strlen($password);
$NewPassword = "";
for( $i = 0; $i <= $len-1; $i++ ) {
$charcode = ord(substr( $password, $i, 1 ));
$NewChar = $charcode+5; $NewLetter = chr($NewChar);
$NewPassword = $NewPassword . $NewLetter;
} echo "Modified Password to Use in Script = $NewPassword\n";
$OrigPassword = "";
for( $i = 0; $i <= $len-1; $i++ ) {
$charcode = ord(substr( $NewPassword, $i, 1 ));
$OrigChar = $charcode-5; $OrigLetter = chr($OrigChar);
$OrigPassword = $OrigPassword . $OrigLetter;
} echo "Convert the Modified back to the Original = $OrigPassword\n";
?>
Add this part to your script with the new password from the above script
$password = "yjxy";
$OrigPassword = "";
for( $i = 0; $i <= $len-1; $i++ ) {
$charcode = ord(substr( $password, $i, 1 ));
$OrigChar = $charcode-5; $OrigLetter = chr($OrigChar);
$OrigPassword = $OrigPassword . $OrigLetter;
} $password = $OrigPassword;
echo "Script thinks this is the password = $password\n";
A: The best way to hide the password is to save it in external file and then include it in your php script. Your file with this password let's say 'config.php' should be above DOCUMENT_ROOT to make it unaccesible via browser. It's common aproach and for example you can see it in Zend Framework directory structure where only "public" directory is visible for user. The proper CHMOD should be set to this file as well.
Under this link you have ZF directory structure where you can check location of config files.
A: This question has been asked and answered lots of times here (but not specifically for Google docs). Short answer is that there is nothing you can do.
Longer answer is that you can mitigate the possibility of the credentials being compromised by:
*
*using credentials supplied the user rather than stored in code
*using tokens supplied by the user as a means of decrypting credentials stored in your code (but this gets very complicated with lots of users)
*storing the credentials in an include file held outside the document root
| {
"language": "en",
"url": "https://stackoverflow.com/questions/17020651",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: best practice in PHP Date Formatting of the year's 4-digit value I saw in PHP's documentation that there are two ways to format the year value in 4 digits:
Y - A full numeric representation of a year, 4 digits
o - ISO-8601 year number. This has the same value as Y, except that if the ISO week number (W) belongs to the previous or next year, that year is used instead. (added in PHP 5.1.0)
I researched more what the ISO-8601 is and it seems to be more "useful" or even accurate(?) based on php's documentation. I think it's more useful because it prevents ambiguity (like when handling date values like 1981-04-05).
But does it really make a difference? Is there some sort of "best practice"? Is 'o' slower that's why people use Y instead when they're not really doing anything complicated with the dates?
What specific use-cases perhaps is this useful?
Thank you for your help.
EDIT:
Thank you Jason for an example! I guess why I brought this up as well is I'm wondering why not just use 'o' all the time? I'm thinking I should just use 'o' all the time for currently unknown future specification that will require me to do more complex date operations.
A: o would be used when trying to determine the year of the current week (i.e. calendar week).
Y would be used for output of the year for a specific date.
This is shown by the following code snippet:
date('Y v. o', strtotime('2012-12-31')); // output: 2012 v. 2013
Not saying it makes it best-practice, but Y is more commonly used to output year. As noted, o would be incorrect/confusing to output the year for such boundary dates.
A: ISO 8601 is a very useful standard for representing dates, but it has several components, not all of which are useful for many purposes. In particular, the "ISO week" and "ISO year" can be slightly confusing terms, and they're often not what you really want to use (and if you do want to use them, you probably already know that).
Wikipedia has a pretty good explanation. Basically, the ISO 8601 standard defines a separate calendar that, instead of breaking up into months and days of the month, breaks up into weeks and days of the week.
You might think this wouldn't make a difference for specifying the year, but there's a little wrinkle: which year do the weeks near the beginning and end of the calendar year fit into? As Wikipedia says, it's not quite intuitive: "The first week of a [ISO] year is the week that contains the first Thursday of the [calendar] year."
The practical upshot: If you're representing dates as conventional year-month-day values, you don't want to use the "ISO year" (o). You won't notice the difference for most of the year, but as you get to December and January, suddenly you'll (sometimes) end up with dates that are a year off. If you just test your system with current dates, you can easily miss this.
Instead, you probably just want to be using plain old Y-m-d. Even though the date() documentation doesn't specifically say it, that's a perfectly valid ISO 8601 standard date.
Really, you should only be using o if you're using the ISO "week date" calendar (meaning you're likely also using W for the week number and N for the day-of-week).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/10983862",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: How do I read a User's Firestore Map to a Swift Dictionary? I have my user struct with has a dictionary of all their social medias.
struct User: Identifiable {
var id: String { uid }
let uid, email, name, bio, profileImageUrl: String
let numSocials, followers, following: Int
var socials: [String: String]
init(data: [String: Any]) {
self.uid = data["uid"] as? String ?? ""
self.email = data["email"] as? String ?? ""
self.name = data["name"] as? String ?? ""
self.bio = data["bio"] as? String ?? ""
self.profileImageUrl = data["profileImageURL"] as? String ?? ""
self.numSocials = data["numsocials"] as? Int ?? 0
self.followers = data["followers"] as? Int ?? 0
self.following = data["following"] as? Int ?? 0
self.socials = data["socials"] as? [String: String] ?? [:]
}
}
The idea is for socials (the dictionary), to be dynamic, since users can add and remove social medias. Firestore looks like this:
The dictionary is initialized as empty. I have been able to add elements to the dictionary with this function:
private func addToStorage(selectedMedia: String, username: String) -> Bool {
if username == "" {
return false
}
guard let uid = FirebaseManager.shared.auth.currentUser?.uid else {
print("couldnt get uid")
return false
}
FirebaseManager.shared.firestore.collection("users").document(uid).setData([ "socials": [selectedMedia:username] ], merge: true)
print("yoo")
return true
}
However I can't seem to read the firestore map into my swiftui dictionary. I want to do this so that I can do a ForEach loop and list all of them. If the map is empty then the list would be empty too, but I can't figure it out.
Just in case, here is my viewmodel.
class MainViewModel: ObservableObject {
@Published var errorMessage = ""
@Published var user: User?
init() {
DispatchQueue.main.async {
self.isUserCurrentlyLoggedOut = FirebaseManager.shared.auth.currentUser?.uid == nil
}
fetchCurrentUser()
}
func fetchCurrentUser() {
guard let uid = FirebaseManager.shared.auth.currentUser?.uid else {
self.errorMessage = "Could not find firebase uid"
print("FAILED TO FIND UID")
return
}
FirebaseManager.shared.firestore.collection("users").document(uid).getDocument { snapshot, error in
if let error = error {
self.errorMessage = "failed to fetch current user: \(error)"
print("failed to fetch current user: \(error)")
return
}
guard let data = snapshot?.data() else {
print("no data found")
self.errorMessage = "No data found"
return
}
self.user = .init(data: data)
}
}
}
TLDR: I can't figure out how to get my firestore map as a swiftui dictionary. Whenever I try to access my user's dictionary, the following error appears. If I force unwrap it crashes during runtime. I tried to coalesce with "??" but I don't know how to make it be the type it wants.
ForEach(vm.user?.socials.sorted(by: >) ?? [String:String], id: \.key) { key, value in
linkDisplay(social: key, handler: value)
.listRowSeparator(.hidden)
}.onDelete(perform: delete)
error to figure out
Please be patient. I have been looking for answers through SO and elsewhere for a long time. This is all new to me. Thanks in advance.
A: This is a two part answer; Part 1 addresses the question with a known set of socials (Github, Pinterest, etc). I included that to show how to map a Map to a Codable.
Part 2 is the answer (TL;DR, skip to Part 2) so the social can be mapped to a dictionary for varying socials.
Part 1:
Here's an abbreviated structure that will map the Firestore data to a codable object, including the social map field. It is specific to the 4 social fields listed.
struct SocialsCodable: Codable {
var Github: String
var Pinterest: String
var Soundcloud: String
var TikTok: String
}
struct UserWithMapCodable: Identifiable, Codable {
@DocumentID var id: String?
var socials: SocialsCodable? //socials is a `map` in Firestore
}
and the code to read that data
func readCodableUserWithMap() {
let docRef = self.db.collection("users").document("uid_0")
docRef.getDocument { (document, error) in
if let err = error {
print(err.localizedDescription)
return
}
if let doc = document {
let user = try! doc.data(as: UserWithMapCodable.self)
print(user.socials) //the 4 socials from the SocialsCodable object
}
}
}
Part 2:
This is the answer that treats the socials map field as a dictionary
struct UserWithMapCodable: Identifiable, Codable {
@DocumentID var id: String?
var socials: [String: String]?
}
and then the code to map the Firestore data to the object
func readCodableUserWithMap() {
let docRef = self.db.collection("users").document("uid_0")
docRef.getDocument { (document, error) in
if let err = error {
print(err.localizedDescription)
return
}
if let doc = document {
let user = try! doc.data(as: UserWithMapCodable.self)
if let mappedField = user.socials {
mappedField.forEach { print($0.key, $0.value) }
}
}
}
}
and the output for part 2
TikTok ogotok
Pinterest pintepogo
Github popgit
Soundcloud musssiiiccc
I may also suggest taking the socials out of the user document completely and store it as a separate collection
socials
some_uid
Github: popgit
Pinterest: pintepogo
another_uid
Github: git-er-done
TikTok: dancezone
That's pretty scaleable and allows for some cool queries: which users have TikTok for example.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/72103380",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: In ScrollView EditText is getting Unnecessary focus I have a layout which i have used for a fragment:
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="@+id/ll_root_view"
app:theme="@style/SpennTheme.Light.NoActionBar">
<androidx.appcompat.widget.Toolbar
android:id="@+id/createBusinessTb"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_collapseMode="pin"
app:navigationIcon="@drawable/ic_close_screen">
</androidx.appcompat.widget.Toolbar>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/white">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RelativeLayout
android:id="@+id/profilePicHolder"
android:layout_width="match_parent"
android:layout_height="216dp"
android:background="@color/colorPrimaryDark">
<ImageView
android:id="@+id/storePicIv"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop"
android:visibility="visible"
app:srcCompat="@drawable/ic_store_image" />
<ImageView
android:id="@+id/upload_pic_iv"
android:layout_width="56dp"
android:layout_height="56dp"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:layout_margin="@dimen/fab_margin"
android:layout_marginBottom="@dimen/fab_margin"
android:background="@drawable/shape_accent_circle"
android:clickable="true"
android:padding="14dp"
app:srcCompat="@drawable/ic_fab_edit" />
</RelativeLayout>
<View
android:id="@+id/editbusiness_focus_thief"
android:layout_width="0dp"
android:layout_height="0dp"
android:focusable="true"
android:focusableInTouchMode="true">
<requestFocus />
</View>
<TextView
android:id="@+id/createBusinessHeadingTv"
android:layout_width="match_parent"
android:layout_height="48dp"
android:layout_marginBottom="12dp"
android:background="@color/pale_grey_three"
android:gravity="center_vertical"
android:paddingStart="@dimen/activity_margin"
android:paddingEnd="@dimen/activity_margin"
android:text="Information"
android:textColor="@color/gunmetal" />
<FrameLayout
android:id="@+id/textInputContent"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:visibility="gone">
<com.google.android.material.textfield.TextInputLayout
android:id="@+id/nameTil"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginEnd="16dp"
android:layout_marginStart="0dp"
android:hint="Name on map"
app:hintEnabled="true">
<EditText
android:id="@+id/nameEt"
style="@style/EditTextProfile"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:imeOptions="actionDone"
android:inputType="textCapSentences"
android:lines="1" />
</com.google.android.material.textfield.TextInputLayout>
</FrameLayout>
<FrameLayout
android:id="@+id/textInputContent"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:visibility="gone">
<com.google.android.material.textfield.TextInputLayout
android:id="@+id/nameTil"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginEnd="16dp"
android:layout_marginStart="0dp"
android:hint="Name on map"
app:hintEnabled="true">
<EditText
android:id="@+id/addressEt"
style="@style/EditTextProfile"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:imeOptions="actionDone"
android:inputType="textCapSentences"
android:lines="1" />
</com.google.android.material.textfield.TextInputLayout>
</FrameLayout>
<View
android:layout_width="match_parent"
android:layout_height="30dp"
android:visibility="invisible" />
<Button
style="@style/ButtonStyleInactive"
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_marginLeft="16dp"
android:layout_marginTop="4dp"
android:layout_marginRight="16dp"
android:layout_marginBottom="4dp"
android:enabled="true"
android:text="Create" />
<View
android:layout_width="match_parent"
android:layout_height="30dp"
android:visibility="invisible" />
</LinearLayout>
</ScrollView>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
I am clearing focus after the done button of my keyboard like below:
et1.setOnEditorActionListener((v, actionId, event) -> {
if (actionId == EditorInfo.IME_ACTION_DONE) {
NKeyboardController.hideKeyboard(getActivity());
et1.getTextInput().clearFocus();
et1.getTextInput().setFocusableInTouchMode(true);
return true;
}
return false;
});
et2.setOnEditorActionListener((v, actionId, event) -> {
if (actionId == EditorInfo.IME_ACTION_DONE) {
NKeyboardController.hideKeyboard(getActivity());
et2.getTextInput().clearFocus();
et2.getTextInput().setFocusableInTouchMode(true);
return true;
}
return false;
});
But the second one is alway focusing to first edittext after the clicking on done button of the keyboard.
I have tried to remove focus from parent view like this in the keyboard action:
rootView.clearFocus();
getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
But nothing is helping me here. Need suggestions here.
A: You can disable edit text focus by using below code on your main layout
<AutoCompleteTextView
android:id="@+id/autotext"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:nextFocusLeft="@id/autotext"
android:nextFocusUp="@id/autotext" />
A: you can do this
clear focus from et1 and also request focus when it goes touch
et1.setOnEditorActionListener((v1, actionId, event) -> {
if (actionId == EditorInfo.IME_ACTION_DONE) {
et1.clearFocus();
et1.requestFocusFromTouch();
}
return false;
});
Suggestion : No need to hide keyboard when you click done editor option
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57923058",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to access elasticsearch.yml? How to access elasticsearch.yml?
According to this doc https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-http.html , I can access the Settings in elastic.yml .. . And once I access it, i want to check the value of "http.max_content_length" and change it if possible
ie. I have this sample curl command, how do I access it using this curl format?:
curl -u admin:QWEREGRHFDSGER
'https://portal-ssl875-6.blahblah.....-1115de1b-f544-4432-8384-3a55b1b37954@sample.com:24332/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/50351964",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Comparing columns in two different dataframes for matching values Pandas Here is what my two dataframes look like:
DF1
NAME EMAIL ID
Mark [email protected] 8974
Sam [email protected] 9823
June [email protected] 0972
David [email protected] 2143
DF2
ID ROLE-ID
2143 22
0972 34
8974 98
9823 54
What I need to help doing:
I need to COMPARE the ID column for both dataframes and if the ID from DF1 MATCHES with the ID of DF2, I need to replace the ID column in DF1 with the respective ROLE-ID from DF2.
The output would look like this:
Updated DF1
NAME EMAIL ROLE-ID
Mark [email protected] 98
Sam [email protected] 54
June [email protected] 34
David [email protected] 22
I am using the Pandas library and tried the merge function with conditions but it didnt work
print(pd.merge(df1, df2, on=(df1['Id'] == df2[])))
A: Try:
df = df1.merge(df2, on='ID', how='left')
df[['NAME', 'EMAIL', 'ROLE-ID']]
It gives the following:
Screenshot
A: You did not exactly state what should happen if id is not found or is avail multiple times this may not be 100% what you want. It will leave the id untouched then.B ut guess otherwise its what you wanted.
import pandas as pd
import numpy as np
df1 = pd.DataFrame([[1,'a'],
[7,'b'],
[3,'e'],
[2,'c']], columns=['id', 'name'])
df2 = pd.DataFrame([[1,2],
[3,8],
[2,10]], columns=['id', 'role'])
# collect roles
roles = []
for id in df1.loc[:, 'id']:
indices = df2.loc[:,'id'] == id
if np.sum(indices) == 1:
roles.append(df2.loc[indices, 'role'].iloc[0])
else:
# take id if role id is not given
roles.append(id) # could also be None if not wanted
# add role id col
df1.loc[:,'role-id'] = roles
# delete old id
del df1['id']
print(df1)
DF1:
id name
0 1 a
1 7 b
2 3 e
3 2 c
DF2:
id role
0 1 2
1 3 8
2 2 10
Output
name role-id
0 a 2
1 b 7
2 e 8
3 c 10
A: Seems like a merge problem
pd.merge(df2, df1, how='inner')
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57700913",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Can I use Write-SqlTableData Is it possible to use this cmdlet: Write-SqlTableData in sql server 2012 and below?
Its a new thing added to sql 2016. I have some powershell output that needs to be stored into MS SQL 2012 database.
Let me know
A: Initially I thought it only works in SQL 2016 but I realized that you either need to import the module: SqlServer or Install-Module SqlServer. Either 2 ways, it should work. Thanks for your help guys. Powershell is taking over the world.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/43733348",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: iPhone "from messages" paste to text box not triggering capturable events I have a web application that requests an OTP through sms and the input for that OTP is 6 individual boxes. The iPhone provides a feature that allows simply clicking the "from messages" quick link after receiving the text message to populate the data in a normal text box. However since I have 6 individual text boxes each limited to maxlength=1, only the first digit of the OTP is provided to the first box.
I have written code that will correctly take the paste command from the user input and parse it to place in the 6 individual boxes, but it does not work when doing the quick action. I have tried capturing "change", "paste", "keyup" and "keypress" events and I am not able to detect that the "from messages" has occurred to do anything with it.
Other than switching to a single text box, is there anything I can do to correctly populate those boxes. I will admit that I am not familiar with the browser capabilities of the iPhone.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/69580074",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Replace text in xml node with some value lets suppose I have an xml like
<Fractions>
<Fraction>test 1/3 test aaa</Fraction>
<Fraction>1/2 test</Fraction>
</Fractions>
I want to replace 1/3 with &frac13, 1/2 with @amp;frac12 which is in the string using xsl but I am stuck. The fraction values are limited like
1/2, 1/3, 3/4, 1/4.
A: If you can guarantee that the input XML will only have single digits, you could achieve this with simple look-up tables, which return the name of either the cardinal number (one, two, three, etc) or the ordinal form of the number (Half, Third, Fourth, etc)
<ref:cardinals>
<ref:cardinal>One</ref:cardinal>
<ref:cardinal>Two</ref:cardinal>
<ref:cardinal>Three</ref:cardinal>
... and so on...
</ref:cardinals>
<ref:ordinals>
<ref:ordinal>Half</ref:ordinal>
<ref:ordinal>Third</ref:ordinal>
... and so on ...
</ref:ordinals>
(Where the ref namespace would have to be declared at the top of the XSLT)
To look up values in these look-up tables, you could set up a variable which references the XSLT document itself
<xsl:variable name="cardinals" select="document('')/*/ref:cardinals"/>
<xsl:value-of select="$cardinals/ref:cardinal[position() = $numerator]"/>
(Where $numerator is a variable containing the top half of the fraction)
Here is a full XSLT document which can cope with all single digit fractions
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:ref="http://stackoverflow.com/users/723763/abdul-muqtadir">
<xsl:output method="xml" indent="yes"/>
<ref:cardinals>
<ref:cardinal>One</ref:cardinal>
<ref:cardinal>Two</ref:cardinal>
<ref:cardinal>Three</ref:cardinal>
<ref:cardinal>Four</ref:cardinal>
<ref:cardinal>Five</ref:cardinal>
<ref:cardinal>Six</ref:cardinal>
<ref:cardinal>Seven</ref:cardinal>
<ref:cardinal>Eight</ref:cardinal>
<ref:cardinal>Nine</ref:cardinal>
</ref:cardinals>
<ref:ordinals>
<ref:ordinal>Half</ref:ordinal>
<ref:ordinal>Third</ref:ordinal>
<ref:ordinal>Quarter</ref:ordinal>
<ref:ordinal>Fifth</ref:ordinal>
<ref:ordinal>Sixth</ref:ordinal>
<ref:ordinal>Seventh</ref:ordinal>
<ref:ordinal>Eigth</ref:ordinal>
<ref:ordinal>Ninth</ref:ordinal>
</ref:ordinals>
<xsl:variable name="cardinals" select="document('')/*/ref:cardinals"/>
<xsl:variable name="ordinals" select="document('')/*/ref:ordinals"/>
<xsl:template match="Fraction">
<xsl:variable name="numerator" select="number(substring-before(., '/'))"/>
<xsl:variable name="denominater" select="number(substring-after(., '/'))"/>
<xsl:copy>
<xsl:value-of select="$cardinals/ref:cardinal[position() = $numerator]"/>
<xsl:text> </xsl:text>
<xsl:value-of select="$ordinals/ref:ordinal[position() = $denominater - 1]"/>
<xsl:if test="$numerator != 1">s</xsl:if>
</xsl:copy>
</xsl:template>
<xsl:template match="@*|node()">
<xsl:copy>
<xsl:apply-templates select="@*|node()"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
When applied to your input XML, the following XML is returned
<Fractions>
<Fraction>One Third</Fraction>
<Fraction>One Half</Fraction>
</Fractions>
Note that you may have to look at handling plurals better. For example, if you had 3/2 as a fraction, the above solution returns Three Halfs, and not Three Halves.
A: If there's only a few, then use templates like these:
<xsl:template match="Fraction/text()[.='1/2']">half</xsl:template>
<xsl:template match="Fraction/text()[.='1/3']">one-third</xsl:template>
etc..
| {
"language": "en",
"url": "https://stackoverflow.com/questions/6894863",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Why doesn't this JSON load in python? For a couple of days i've been trying to learn how to use JSON in python, but even if i copy everything from tutorials it still won't load.
import json
data = '''
{
"people":[
{
"name": "veljko",
"age":"20",
"email": [email protected],
"educated": "true"
} ,
{
"name":"aleksandar",
"age":"24",
"email":"[email protected]",
"educated":"false"
}
]
}
'''
men = json.loads(data)
print(men)
(Ignore the random words used in code, it's just how i learn)
It just keeps giving the same error messages, i've tried with the most simple JSON but it's still the same.
Traceback (most recent call last):
File "C:\Users\*********\Desktop\code3\json.py", line 21, in <module>
men = json.loads(data)
File "C:\Users\************\AppData\Local\Programs\Python\Python310\lib\json\__init__.py", line 346, in loads
return _default_decoder.decode(s)
File "C:\Users\*************\AppData\Local\Programs\Python\Python310\lib\json\decoder.py", line 337, in decode.
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Users\************\AppData\Local\Programs\Python\Python310\lib\json\decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 7 column 14 (char 75)
Process finished with exit code 1
Please help, i'm a begginer and am not sure how to solve this problem.
A: You are missing quotes around [email protected]. You need to change it to "[email protected]", so that it is interpreted as a string. The exception tells you which line and character the error is at, so double check that line when you get errors like these.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/73167027",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: VBA Use Vlookup to place a Value into cell I'm pretty new to VBA and this has me stumped. I hope there is an easy way to do this. I know the following doesn't work, but it's an easy way to show what I'd like to do:
Application.WorksheetFunction.VLookup(date, .Range("A:A"), 2, False) = String
Basically I want to look up a date in a column A, go to the second Column and insert the string.
I've searched and can't find what I'm looking for.
Thanks in advance,
Cory
A: We can use MATCH() to find the row and deposit the string with the correct offset from column A:
Sub Spiral()
Dim s As String, i As Long
s = "whatever"
i = Application.WorksheetFunction.Match(CLng(Date), Range("A:A"))
Cells(i, 2).Value = s
End Sub
A: You can use Range.Find
Dim cell As Range
Set cell = .Range("A:A").Find(date, , , xlWhole)
If Not cell Is Nothing Then cell(, 2) = String ' or cell.Offset(, 1) = String
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39431335",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: r list of objects POINT (coordinates) I have a dataframe a.fil with Name, Lon and Lat.
name1 43.37390 132.9703
name2 43.35311 132.7493
I create objects POINT
point1.sfg <- st_point(unname(unlist(a.fil[1, 2:3])))
point2.sfg <- st_point(unname(unlist(a.fil[2, 2:3])))
class(point1.sfg)
[1] "XY" "POINT" "sfg"
I need to create list of objects POINT
ll <- list(point1.sfg, point2.sfg)
class(ll[[1]])
[1] "XY" "POINT" "sfg"
However, my dataframe contains 1000 rows
If I use for...
i <- 1
for (i in 1:nrow(a.fil)) {
ll[i] <- st_point(unname(unlist(a.fil[i, 2:3])))
}
I get list with nrow() elemets, but...
class(ll[[1]])
[1] "numeric"
How do I create list of objects POINT from this dataframe? non numeric
Help me!
A: From a data.frame you can create an sf object
library(sf)
df <- data.frame(
name = c("a","b","c")
, lon = 1:3
, lat = 3:1
)
sf <- sf::st_as_sf( df, coords = c("lon","lat" ) )
sf
# Simple feature collection with 3 features and 1 field
# geometry type: POINT
# dimension: XY
# bbox: xmin: 1 ymin: 1 xmax: 3 ymax: 3
# CRS: NA
# name geometry
# 1 a POINT (1 3)
# 2 b POINT (2 2)
# 3 c POINT (3 1)
Then the list of POINTs is just the geometry column
sf$geometry
# Geometry set for 3 features
# geometry type: POINT
# dimension: XY
# bbox: xmin: 1 ymin: 1 xmax: 3 ymax: 3
# CRS: NA
# POINT (1 3)
# POINT (2 2)
# POINT (3 1)
str( sf$geometry )
# sfc_POINT of length 3; first list element: 'XY' num [1:2] 1 3
And if you truly want a list of POINT objects you can remove the sfc class
unclass( sf$geometry )
# [[1]]
# POINT (1 3)
#
# [[2]]
# POINT (2 2)
#
# [[3]]
# POINT (3 1)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/62631066",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Saving data on Godot android export I am programming an android game with Godot 3.2.2. Of course I want to save the game data, therefore I created a new scene called SaveGame.tscn with SaveGame.gd. I exported the project to my windows pc and everything worked fine, all datas were saved. After that I also exported it to my android phone, but this time no data was saved. Instead it showed me that it could not find the save path. Maybe anybody of you can help me with this problem so that data is also saved on android.
SaveGame.gd:
extends Control
const FILE_NAME = "user://save_game_data_one.json"
var save_game_data
func _ready() -> void:
Signals.connect("load_data", self, "load")
Signals.connect("game_quit", self, "save")
save_game_data = {
"highscore": Globals.highscore,
"coins": Globals.coins,
"music_volume": Globals.music_volume,
"sound_volume": Globals.sound_volume,
"button_gameplay": Globals.button_gameplay,
"button_gameplay_side": Globals.button_gameplay_side,
}
func save():
update_data()
var file = File.new()
file.open(FILE_NAME, File.WRITE)
file.store_string(to_json(save_game_data))
file.close()
func load():
var file = File.new()
if file.file_exists(FILE_NAME):
file.open(FILE_NAME, File.READ)
var data = parse_json(file.get_as_text())
file.close()
if typeof(data) == TYPE_DICTIONARY:
save_game_data = data
else:
printerr("Corrupted data")
else:
self.show() <---- Here it shows me the hidden scene (white rectangle), this means it could not find FILE_NAME
export_data()
func export_data():
Globals.highscore = save_game_data["highscore"]
Globals.coins = save_game_data["coins"]
Globals.music_volume = save_game_data["music_volume"]
Globals.sound_volume = save_game_data["sound_volume"]
Globals.button_gameplay = save_game_data["button_gameplay"]
Globals.button_gameplay_side = save_game_data["button_gameplay_side"]
func update_data():
if Globals.score_round >= Globals.highscore:
save_game_data["highscore"] = Globals.score_round
save_game_data["coins"] += Globals.coins_round
A: I also would like to know the answer. I am trying to figure a way to have "persistent time" in my android game where "time passes" in game even when closed. Best solution I figure so far is getting the unix time on the games first start and check against it when reopening the app. My problem is finding a way to save that original unix time to call upon for checks.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/63646216",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How many Number of exceptions in a single catch clause in Java? From Java 7 we can catch multiple exceptions in a single catch clause like below.
try {
// Your code here.
} catch (IllegalArgumentException | SecurityException | IllegalAccessException |
NoSuchFieldException e) {
// Handle exception here.
}
How many number of exceptions can be caught in a same catch clause?
Is there any limit ?
What is the best practice on number of exceptions in same catch ?
A: About a general catch, not distinghuishing individual exceptions.
You can use base class exceptions, like IOException, and drop its child exceptions, like EOFException. This is a good practice as all (possibly future) child exceptions are catched. This principle also holds for a throws IOException clause.
Run time exceptions, when not treated in their own catch, should only be catched, maybe in the same way, as RuntimeException, when it is a catch-all. (One should not catch always all.)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/68250450",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: LINQ query the most recent records How to modify this query to be able to select the 5 most recent records sorted by title?
IEnumerable<Story> recentStories =
(from s in stories
orderby s.Date descending
select s).Take(5);
A: IEnumerable<Story> recentStories =
(from s in stories
orderby s.Date descending
select s).Take(5).OrderBy(s => s.Title);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/12593415",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: RoR - pass param to Bootstrap modal. Background doesn't fade out I display list of profiles and need to display more details about every user via the modal:
<%= link_to profile.full_name, { :action => :profile_modal,
:profile_id_param => profile.id },
{remote: true, 'data-toggle' => 'modal',
'data-target' => '#modal-window'} %>
Here is the container fiv for modal:
<div id="modal-window" class="modal hide fade" role="dialog" aria-labelledby="myModalLabel" aria-hidden="tue">
</div>
Controller action:
def profile_modal
@profile = Profile.find_by_id(params[:profile_id_param])
respond_to do |format|
format.js
# format.html
end
end
and profile_modal.js.erb:
$("#modal-window").html("<%= escape_javascript(render partial: 'shared/profile_modal', locals: { profile: @profile }) %>");
$("#profile_modal").modal();
Modal:
<div class="modal fade" id="profile_modal" tabindex="-1" role="dialog" aria-labelledby="msgModal" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">
<% if @profile %> <%= @profile.id %> <% end %>
This code above passes the variable according to the params[:profile_id_param] value, but there are two problems:
*
*After I open modal and close it, background doesn't fades in again. It remains darker, just modal itself disappears;
*For some reason I can't pass locals to modal. As you see, I use instance variable in it, because it errors me with undefined.
What is wrong here?
UPDATE:
Treid to turn off turbolinks like this on click:
<%= link_to profile.full_name, { :action => :profile_modal,
:profile_id_param => profile.id },
{remote: true, 'data-turbolinks' => false, 'data-toggle' => 'modal',
'data-target' => '#modal-window'} %>
But didn't helped
A: One way to go around this:
$('#modal-window').on('hide.bs.modal', function () {
$('#modal-window').css("display", "none");
})
$('#modal-window').on('show.bs.modal', function () {
$('#modal-window').css("display", "block");
})
$("#modal-window").html("<%= escape_javascript(render partial: 'shared/profile_modal', locals: { profile: @profile }) %>");
$("#profile_modal").modal();
And disable backdrop:
<%= link_to profile.full_name, { :action => :profile_modal,
:profile_id_param => profile.id },
{ remote: true, 'data-toggle' => 'modal',
'data-target' => '#modal-window',
'data-backdrop' => "false"} %>
Also noticed that #modal-window gets z-index 1050 even after modal being closed, but this:
$('#modal-window').on('hide.bs.modal', function () {
$('#modal-window').css("display", "0");
Didnt fixed it.
I keep this issue open for:
a) a better way to fix this
b) How to pass locals to this modal?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/47079432",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How can I speed up this For Each loop in VBA? I have an Worksheet_Change macro that hides/unhides rows depending on the choice a user makes in a cell with a data validation list.
The code takes a minute to run. It's looping over c.2000 rows. I'd like it to take closer to a few seconds so it becomes a useful user tool.
Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
'Exit the routine early if there is an error
On Error GoTo EExit
'Manage Events
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Application.EnableEvents = False
'Declare Variables
Dim rng_DropDown As Range
Dim rng_HideFormula As Range
Dim rng_Item As Range
'The reference the row hide macro will look for to know to hide the row
Const str_HideRef As String = "Hide"
'Define Variables
'The range that contains the week selector drop down
Set rng_DropDown = Range("rng_WeekSelector")
'The column that contains the formula which indicates if a row should
'be hidden c.2000 rows
Set rng_HideFormula = Range("rng_HideFormula")
'Working Code
'Exit sub early if the Month Selector was not changed
If Not Target.Address = rng_DropDown.Address Then GoTo EExit
'Otherwise unprotect the worksheet
wks_DailyPlanning.Unprotect (str_Password)
'For each cell in the hide formula column
For Each rng_Item In rng_HideFormula
With rng_Item
'If the cell says "hide"
If .Value2 = str_HideRef Then
'Hide the row
.EntireRow.Hidden = True
Else
'Otherwise show the row
.EntireRow.Hidden = False
End If
End With
'Cycle through each cell
Next rng_Item
EExit:
'Reprotect the sheet if the sheet is unprotected
If wks_DailyPlanning.ProtectContents = False Then wks_DailyPlanning.Protect (str_Password)
'Clear Events
Application.ScreenUpdating = True
Application.DisplayAlerts = True
Application.EnableEvents = True
End Sub
I have looked at some links provided by other users on this website and I think the trouble lies in the fact I'm having to iterate through each row individually.
Is it possible to create something like an array of .visible settings I can apply to the entire range at once?
A: I'd suggest copying your data range to a memory-based array and checking that, then using that data to adjust the visibility of each row. It minimizes the number of interactions you have with the worksheet Range object, which takes up lots of time and is a big performance hit for large ranges.
Sub HideHiddenRows()
Dim dataRange As Range
Dim data As Variant
Set dataRange = Sheet1.Range("A13:A2019")
data = dataRange.Value
Dim rowOffset As Long
rowOffset = IIf(LBound(data, 1) = 0, 1, 0)
ApplicationPerformance Flag:=False
Dim i As Long
For i = LBound(data, 1) To UBound(data, 1)
If data(i, 1) = "Hide" Then
dataRange.Rows(i + rowOffset).EntireRow.Hidden = True
Else
dataRange.Rows(i + rowOffset).EntireRow.Hidden = False
End If
Next i
ApplicationPerformance Flag:=True
End Sub
Public Sub ApplicationPerformance(ByVal Flag As Boolean)
Application.ScreenUpdating = Flag
Application.DisplayAlerts = Flag
Application.EnableEvents = Flag
End Sub
A: to increase perfomance you can populate dictionary with range addresses, and hide or unhide at once, instead of hide/unhide each particular row (but this is just in theory, you should test it by yourself), just an example:
Sub HideHiddenRows()
Dim cl As Range, x As Long
Dim dic As Object: Set dic = CreateObject("Scripting.Dictionary")
x = Cells(Rows.Count, "A").End(xlUp).Row
For Each cl In Range("A1", Cells(x, "A"))
If cl.Value = 0 Then dic.Add cl.Address(0, 0), Nothing
Next cl
Range(Join(dic.keys, ",")).EntireRow.Hidden = False
End Sub
demo:
A: Another possibility:
Dim mergedRng As Range
'.......
rng_HideFormula.EntireRow.Hidden = False
For Each rng_Item In rng_HideFormula
If rng_Item.Value2 = str_HideRef Then
If Not mergedRng Is Nothing Then
Set mergedRng = Application.Union(mergedRng, rng_Item)
Else
Set mergedRng = rng_Item
End If
End If
Next rng_Item
If Not mergedRng Is Nothing Then mergedRng.EntireRow.Hidden = True
Set mergedRng = Nothing
'........
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58304413",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Webhook time out doesn't follow documentation According to the Conversations API documentation in the case where a pre-action webhook fails to get a response:
(no response or timeout)
then
Conversations will publish the change unmodified after a series of retries; your messages will be delayed accordingly.
However it looks like the actual result is that Twilio returns an error to the mobile SDK when the webhook post times out.
Honestly the current response is the one I was hoping for, but since the documentation makes it seem like this is a bug, I just wanted clarification of what the expected result SHOULD be, before making any assumptions that break my stuff later on.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/68764938",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Possible to display elements outside modal view in ionic currently I have an HTML file that have some content that I present in modalview upon click of a button. I wish to check if it is possible to display element in the HTML outside of the modal view.
I tried using css to style the element, but I am unable to move the element out of the modal-wrapper.
Please assist to advice.
I am not able to embed image into the post yet, so i provided a link.
Modal View Image
A: By referring to the making modals 50% of size and round icon css. I have build a sample below with your requirements. You can find the working version here
Hope it helps and let me know if you have any issues.
Modal.html
<ion-content padding class="main-view">
<div class="overlay" (click)="dismiss()"></div>
<div class="modal_content">
<div class="circle"></div>
<div class="modal-content">
<h2>Welcome to Ionic!</h2>
<p>
This starter project comes with simple tabs-based layout for apps
that are going to primarily use a Tabbed UI.
</p>
<p>
Take a look at the <code>pages/</code> directory to add or change tabs,
update any existing page or create new pages.
</p>
</div>
</div>
</ion-content>
Modal.scss
modal-wrapper {
position: absolute;
width: 100%;
height: 100%;
}
@media not all and (min-height: 600px) and (min-width: 768px) {
ion-modal ion-backdrop {
visibility: hidden;
}
}
@media only screen and (min-height: 0px) and (min-width: 0px) {
.modal-wrapper {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
}
.main-view{
background: transparent;
}
.overlay {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 1;
opacity: .5;
background-color: #333;
}
.modal_content {
display: block;
position: relative;
top: calc(50% - (50%/2));
left: 0;
right: 0;
width: 100%;
height: 50%;
padding: 10px;
z-index: 1;
margin: 0 auto;
padding: 10px;
color: #333;
background: #e8e8e8;
background: -moz-linear-gradient(top, #fff 0%, #e8e8e8 100%);
background: -webkit-linear-gradient(top, #fff 0%, #e8e8e8 100%);
background: linear-gradient(to bottom, #fff 0%, #e8e8e8 100%);
border-radius: 5px;
box-shadow: 0 2px 3px rgba(51, 51, 51, .35);
box-sizing: border-box;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
//overflow: hidden;
}
.circle{
position:absolute;
height:100px;
width:100px;
border-radius:50%;
border:3px solid white;
left:50%;
margin-left:-55px;
top: -40px;
background: #d33;
z-index: 10000;
}
.modal-content{
padding-top: 5rem;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/47319407",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Android: How can I close application after a toast message disappear? Just as the title says. I'm trying to have display a Toast text when a button is clicked, and then close the application after the message disappears.
Toast toast = Toast.makeText(getApplicationContext(), "Message here", Toast.LENGTH_SHORT);
toast.show();
finish();
This closes the application as the toast message displays and I was just wondering if I could delay closing the application to after the message disappears.
Thanks!
A: You will have to set a timer for the time it takes the toast to disappear.
If I'm not mistaken, LENGTH_SHORT is 2 seconds or around it.
Call a timer with a timer task with a 2 seconds delay that will call finish in turn.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7679201",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Remove embedded images in HTML email using On-send feature To remove embedded images in HTML email, use the removeAttachmentAsync() method (in Mailbox API).
The removeAttachmentAsync() method completes successfully, but behaves differently as follows:
*
*Outlook on the web (OWA):
*
*The sent e-mail has no embedded images. This works as I expected.
*Outlook on Windows:
*
*The sent e-mail still has embedded images.
What is the correct way to remove embedded images in Outlook for Windows?
First code:
const test = async (event) => {
let timeout = null;
const item = Office.context.mailbox.item;
item.getAttachmentsAsync((result) => {
for (let i = 0; i < result.value.length; i++) {
item.removeAttachmentAsync(result.value[i].id, (result2) => {
clearTimeout(timeout);
timeout = setTimeout(() => {
event.completed({ allowEvent: true });
}, 500);
});
}
});
}
Update:
I rewrote the code using the setAsync() method. The behavior has changed:
*
*Outlook on Windows:
*
*The sent e-mail has embedded blank images.
Edited code:
const test = async (event) => {
let timeout = null;
const item = Office.context.mailbox.item;
item.getAttachmentsAsync((result) => {
for (let i = 0; i < result.value.length; i++) {
item.removeAttachmentAsync(result.value[i].id, (result2) => {
clearTimeout(timeout);
timeout = setTimeout(() => {
item.body.getAsync(Office.CoercionType.Html, (result3) => {
item.body.setAsync(result3.value, { coercionType: Office.CoercionType.Html }, () => {
event.completed({ allowEvent: true });
});
});
}, 500);
});
}
});
}
A: The code that solved the question:
const removeImagesFromBody = (event) => {
const item = Office.context.mailbox.item;
const type = Office.CoercionType.Html;
item.body.getAsync(type, (result) => {
let body = result.value;
let match;
const regex1 = new RegExp('v:shapes="([^"]+)"', 'gi');
while ((match = regex1.exec(result.value)) !== null) {
const regex2 = new RegExp(`<v:shape id="${match[1]}"[^]*?</v:shape>`, 'gi');
body = body.replace(regex2, '');
}
body = body.replace(/<img [^>]*>/gi, '');
item.body.setAsync(body, { coercionType: type }, () => {
event.completed({ allowEvent: true });
});
});
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/59298123",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: ReactJS to present the data coming from a mongodbstitch into a table I am getting data frm mongodb using mongodbstitcg in a JSON format as:
[{"_id":{"$oid":"5def1f22b15556e4e9bdb345"},"Time":{"$numberDouble":"1616180000000"},"Image_Path":"1575946831220.jpg","permission":"Read:Write"},{"_id":{"$oid":"5def1f22b15556e4e9bdb346"},"Time":{"$numberDouble":"727672000000000000"},"Image_Path":"8398393839313893.jpg","permission":"Read:Write"},{"_id":{"$oid":"5def1f22b15556e4e9bdb347"},"Time":{"$numberDouble":"84983500000000"},"Image_Path":"82492849284984.jpg","permission":"Read:Write"}]
I have a csv File and exported that using mongodbimport and when query this is the output.
I am really getting difficult to present this a editable table.
I can see in response but that it is failing when I am trying to render on screen?
A: You are getting key-value pair data.
access like this
let data = [
{"_id":{"$oid":"5def1f22b15556e4e9bdb345"},
"Time":{"$numberDouble":"1616180000000"},
"Image_Path":"1575946831220.jpg","permission":"Read:Write"},
{"_id":{"$oid":"5def1f22b15556e4e9bdb346"},
"Time":{"$numberDouble":"727672000000000000"},
"Image_Path":"8398393839313893.jpg","permission":"Read:Write"},
{"_id":{"$oid":"5def1f22b15556e4e9bdb347"},
"Time":{"$numberDouble":"84983500000000"},
"Image_Path":"82492849284984.jpg","permission":"Read:Write"}
]
let json = Object.values(data);
in reactjs
return (
<div>
{json.map(a =>
<div key={a.id}>
<h4>image path --{a.Image_Path}</h4>
<h6>Permission-- {a.permission}</h6>
</div>
)}
</div>
);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/59260610",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to set dependency DLL paths in Visual Studio? I am working with Cyclone DDS, and they have two builds,
c build (contains multiple files in the bin folder)
and c++ build (contains DLL file in the bin)
after Cyclones DDS installation, I have to set these bin paths in system environment variables.
how can I avoid this? I need to set them in the visual studio 2017 itself. without setting paths in the system environment
or can I copy bin files into my project directory? so that I can use the project file on any PC which has visual studio 2017 without reinstalling CycloneDDS?
A: Windows by default will prefer .DLL files in the same directory as the .EXE. So while developing, you can put them in your Visual Studio Debug and Release folders. For other people, you include the DLL's in the installer.
The exception is the *140.dll stuff, for which you need the Visual C++ redistributable. That's installed as part of Visual Studio 2017, but can also be distributed independently (hence the name).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66596230",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Trouble viewing my website via external ip I'm trying to set up my first publicly view-able website but I've run into trouble.
Here's the background info
I've installed Apache Server on my Windows 7 machine using XAMPP binaries and I'm able to view the XAMPP sample webpage by visiting localhost in my browser.
After some research on the web, I discovered that, in order to make the website accessible outside of my local network, I needed to forward router traffic on port 80 to my local machine.
Viewing my router settings I see that my machine is on 192.168.1.3 so I forward port 80 traffic to 192.168.1.3:80. In order to verify that my website is actually addressed (internally) by 192.168.1.3:80, I entered '192.168.1.3' into a browser and I'm directed to the XAMPP sample website as expected.
Here's where the trouble comes in
When I attempt to connect to '192.168.1.3' from my phone (connected to the same network as my server) I'm unable to reach my website.
When I attempt to connect to my external ip address (as shown by whatsmyip.org and on my router settings page) I get 'This website is not available' due to a time out.
Here's what I've tried
After a bunch of research across the web I've tried a few things. I read that some firewalls or routers might block traffic on port 80, so I downloaded a utility from portforward.com to check if a given port was open. It indicated that port 80 was closed.
I entered the windows firewall settings and created a new inbound rule to allow traffic on port 80 and then ran the port-checking utility again. This time it said that port 80 was open! However, this didn't seem to make a difference. Both of the 'troubles' that I described still persist.
Edit 1
At the suggestion of Pekka, I checked to see if port 80 was open externally through my router. I used YouGetSignal.com to find out that it was actually closed.
I've been researching ways to open that port on my router (Actiontec Mi424WR) but each article I read just explains how to add a port-forwarding entry which I've already done.
Edit 2
To configure port forwarding I set the following parameters in my router's port forwarding table:
Destination Device: 192.168.1.3:80 (internal ip address of my server device)
Protocol: TCP
Forwarded Ports: 80
WAN Connection Type: All Broadband Devices
Status: Active
I'm not sure why YouGetSignal/CanYouSeeMe show port 80 as closed while this port forwarding entry seems to be active.
Edit 3
Thanks to Lea's comment about turning off windows firewall for debugging, I was able to identify that the issue was with the firewall. There was an entry that was blocking the Apache server executable (httpd.exe) on public connections. After changing the entry to Allow, everything worked as expected!
A: From the machine running the server, search what is my ip on google (http://google.com/search?q=what+is+my+ip). It will show your public IP address, use that to access your web server from your mobile phone.
192.168.. are private IP addresses. They can only be accessed from devices on same local network.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/29200714",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: Defining dynamic list with the variables from the given list x=["a","b","c","d","e"]
for i in x:
ai=[i]
print(ai)
print(ae)
So for the above code, I am consufed, how can I call back these kind of lists. I mean for each i in the list x. I am defining "ai". Since last step is finishing with "e" what is the list a"e", or what become of my list created with a and e(from the list). How can I call a"e"=['e']? it is clearly not a"e" I tried to call as print(ae),print(a'e'), print(a"e") etc...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/71639784",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is it possible to reinstall Postresql without destroying existing databases? I have a Postgresql 10 installation on Ubuntu 18.04 that somehow broke and won't restart. Can I just reinstall it without destroying its databases, so that I can access the databases again? pg_dump doesn't work.
A: Yes, you can do that.
By default, your databases and other important files are stored in PGDATA.
Traditionally, the configuration and data files used by a database cluster are stored together within the cluster's data directory, commonly referred to as PGDATA (after the name of the environment variable that can be used to define it). A common location for PGDATA is /var/lib/pgsql/data.
https://www.postgresql.org/docs/10/storage-file-layout.html
I don't know how you will uninstall PostgreSQL, but be sure to keep PGDATA.
(yum or apt won't delete PGDATA)
After re-installing PostgreSQL, make sure to launch your PostgreSQL with your existing PGDATA
pg_ctl start -D YOUR_EXISTING_PGDATA/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/55581913",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: java.lang.NoSuchMethodError in jmeter for the methods inside the jar file I have a jar file where i have one java class.I add that to jmeter and call that jar in sampler.When the request is hit I face java.lang.NoSuchMethodError for one of the methods inside that java class.That method doesn't need any maven dependencies as I use default java functions inside it.I tried manually including that jar to jmeter lib folder but no luck.
A: Which "sampler" and how do you "call" it?
*
*Either there is a typo in your code i.e. you're trying to call the function which doesn't exist
*Or there is a typo in your code in terms of passing parameters to the function, in case if it's overloaded the candidate is determined in the runtime depending on the argument types, like function expects an integer and you're passing a string to it or something like this
In JMeter you can use Java code in 3 ways:
*
*in Java Request sampler
*in JUnit Request sampler
*write your own plugin
| {
"language": "en",
"url": "https://stackoverflow.com/questions/70150260",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.