text
stringlengths 15
59.8k
| meta
dict |
|---|---|
Q: java servlet compile error 1.i added the path C:\Program Files (x86)\Java\jdk1.6.0_01\bin for java and C:\TOMCAT\apache-tomcat-7.0.55\lib for tomcat.
2.i have started startup.bat in C:\TOMCAT\apache-tomcat-7.0.55\bin and it works fine.
3.it displays in 8084 port(localhost:8084/).
4.i created a MyServlet.java file in Directory E.
5.i wanted to compile it through command line(javac MyServlet.java) bt errror comes.
i have tried and tried bt.. :( ..plz help me to fix it.
MyServlet.java code:
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MyServlet extends HttpServlet
{
public void doGet(HttpServletRequest request,HttpServletResposne response)
throws ServletException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("<h1>Hello Readers</h1>");
out.println("</body></html>");
}
}
and cmd errors:
E:\>javac MyServlet.java
MyServlet.java:1: package javax.servlet does not exist
import javax.servlet.*;
^
MyServlet.java:2: package javax.servlet.http does not exist
import javax.servlet.http.*;
^
MyServlet.java:7: package javax.servlet does not exist
import javax.servlet.ServletException;
^
MyServlet.java:8: package javax.servlet.http does not exist
import javax.servlet.http.HttpServlet;
^
MyServlet.java:9: package javax.servlet.http does not exist
import javax.servlet.http.HttpServletRequest;
^
MyServlet.java:10: package javax.servlet.http does not exist
import javax.servlet.http.HttpServletResponse;
^
MyServlet.java:12: cannot find symbol
symbol: class HttpServlet
public class MyServlet extends HttpServlet
^
MyServlet.java:14: cannot find symbol
symbol : class HttpServletRequest
location: class MyServlet
public void doGet(HttpServletRequest request,HttpServletResposne response)
^
MyServlet.java:14: cannot find symbol
symbol : class HttpServletResposne
location: class MyServlet
public void doGet(HttpServletRequest request,HttpServletResposne response)
^
MyServlet.java:15: cannot find symbol
symbol : class ServletException
location: class MyServlet
throws ServletException
^
10 errors
A: Declaring Class
public class MyServlet extends HttpServlet
instead of
public MyServlet extends HttpServlet
A: you forget the keyword class when define a class, just put the class before the class name
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/25172750",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Formatting text using PDFsharp I want to apply style to
string "Helloword"
and have style properties
like fontFamily='Verdana', fontStyle='bold', FontSize='12', textDecoration='underline', textAlign='center', fontColor='#FF0000', x=100 and y=100.
I want to display this string in PDF using PDFsharp. can anyone suggest me how to do that?
I'm using XFont and XGraphics.DrawString method but I'm not able to apply all above styles.
A: The string is slightly incorrect, but I hope all other requirements are met:
// Create a font
XFont font = new XFont("Verdana", 12, XFontStyle.Bold | XFontStyle.Underline);
// Draw the text
gfx.DrawString("Hello, World!", font, new XSolidBrush(XColor.FromArgb(255, 0, 0)),
100, 100,
XStringFormats.Center);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/17759711",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Ruby on Rails routing by resources with many-to-many relationship Ok, this gives me some headaches!
I have a many-to-many relationship with a link table that has a few attributes on its on:
user linked to items through ownings
The active-record part is clear to me. But what are my resources here? Clearly there are users and items. Items are going to be managed on their own. I want to link users to items from the users view having a link to a page where the items of the user are shown (and can be remove from that particular user) and a link to a page where new links between the user and an existing item can be created (also entering the link table attributes).
Would you manage that by putting more user defined methods/routings in the user controller or would you have another controller as subresource of the user controller?
What confuses me is that resourceful routing takes you by the hand and says, that on a theoretical basis you have these x methods, that is probably all you gonna need. And than the rails routing guide for example has a hole lot more text to show you what else you can do to tweak around with resourceful routing. But at that point I feel left alone since I don't know what to tweak! Only two hints are given: Do not nest resources more levels deep than one and do not ad user defined methods a lot.
Do you know what to do or what book/guide would you recommend for these kind of questions.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/9093408",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: setState update a mounted or mounting component Here is my code:
import React, { Component } from 'react';
import styled from 'styled-components';
const BtnBox = styled.ul`
display:flex;
width:50vw;
align-items:center;
justify-content:flex-start;
font-weight:900;
font-size:5vw;
letter-spacing:-0.5vw;
`;
const MyBtn = styled.li`
width:30%;
font-size:5vw;
display:flex;
align-items:center;
justify-content:flex-start;
cursor:pointer;
`;
class SignAndLog extends Component {
constructor(props) {
super(props);
this.state = { Scolor: 'black', Lcolor: 'grey' };
this.chooseFun = this.chooseFun.bind(this);
localStorage.setItem('fuck', this.state.Scolor);
}
chooseFun(e) {
const myName = e.target.dataset.name;
if (myName === 'sign') {
this.setState({
Scolor: 'black',
Lcolor: 'grey'
});
localStorage.setItem('status', myName);
} else {
this.setState({
Scolor: 'grey',
Lcolor: 'black'
});
localStorage.setItem('status', myName);
}
}
render() {
return (
<BtnBox>
<MyBtn onClick={this.chooseFun} data-name="sign" style={{ color: this.state.Scolor }}>註冊</MyBtn>
<MyBtn onClick={this.chooseFun} data-name="log" style={{ color: this.state.Lcolor }}>登入</MyBtn>
</BtnBox>
);
}
}
export default SignAndLog;
And when I click both my MyBtn , it always not work , and in F12 console area shows that:
app.js:3880 Warning: setState(...): Can only update a mounted or
mounting component. This usually means you called setState() on an
unmounted component. This is a no-op.
Please check the code for the SignAndLog component.
Can any body tell me where I should fix?
PS:due to my ESlint , I cannot console.log() , so I use localStorage.setItem to be my console.log()
A: follow this article! and you will get better understanding of how to setState.
I prefer to use the fat arrow function.
try this out!
import React, { Component } from 'react';
import styled from 'styled-components';
const BtnBox = styled.ul`
display:flex;
width:50vw;
align-items:center;
justify-content:flex-start;
font-weight:900;
font-size:5vw;
letter-spacing:-0.5vw;
`;
const MyBtn = styled.li`
width:30%;
font-size:5vw;
display:flex;
align-items:center;
justify-content:flex-start;
cursor:pointer;
`;
class SignAndLog extends Component {
constructor(props) {
super(props);
this.state = { Scolor: 'black', Lcolor: 'grey' };
localStorage.setItem('fuck', this.state.Scolor);
}
chooseFun =(e)=> {
const myName = e.target.dataset.name;
if (myName === 'sign') {
this.setState({
Scolor: 'black',
Lcolor: 'grey'
});
localStorage.setItem('status', myName);
} else {
this.setState({
Scolor: 'grey',
Lcolor: 'black'
});
localStorage.setItem('status', myName);
}
}
render() {
return (
<BtnBox>
<MyBtn onClick={(e)=>this.chooseFun(e)} data-name="sign" style={{ color: this.state.Scolor }}>註冊</MyBtn>
<MyBtn onClick={(e)=>this.chooseFun(e)} data-name="log" style={{ color: this.state.Lcolor }}>登入</MyBtn>
</BtnBox>
);
}
}
export default SignAndLog;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/47205436",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Behaviour of "containsAll" with duplicates The official documentation (archive) of containsAll only says "Returns true if this list contains all of the elements of the specified collection.". However, I just tested this:
List<Integer> list1 = new ArrayList<>();
list1.add(1);
list1.add(2);
list1.add(1);
List<Integer> list2 = new ArrayList<>();
list2.add(2);
list2.add(1);
list2.add(2);
System.out.println(list1.containsAll(list2));
The result is true, even though list1 does not contain a second 2.
So what is the official, completely defined behaviour of containsAll? Does it act as if all duplicates were removed from both lists? I remember reading somewhere that it can cause problems with duplicates, but I don't know the exact case.
A: The List.containsAll method behaves just as documented: it returns true if all the elements of the given collection belong to this collection, false otherwise. The docs say nothing about the order or cardinality of the elements.
The documentation for containsAll does not explicitly say how it determines whether an element belongs to the Collection. But the documentation for contains (which is implicitly specifying the semantics of "contains") does: it uses equals. Again, no mention of cardinality.
The containsAll method is declared in the Collection interface and re-declared in the List and Set interfaces, but it's first implemented in the Collection hierarchy by the AbstractCollection class, as follows:
public boolean containsAll(Collection<?> c) {
for (Object e : c)
if (!contains(e))
return false;
return true;
}
As far as I know, this implementation is inherited by most common classes that implement the Collection interface in the Java Collections framework, except for the CopyOnWriteArrayList class and other specialized classes, such as empty lists and checked and immutable wrappers, etc.
So, if you look at the code, you'll see that it fulfils the docs you quoted:
Returns true if this list contains all of the elements of the specified collection.
In the docs of the AbstractList.containsAll method, there's also an @implSpec tag, which says the following:
@implSpec
This implementation iterates over the specified collection, checking each element returned by the iterator in turn to see if it's contained in this collection. If all elements are so contained true is returned, otherwise false.
With regard to possible optimizations, they're all relayed to the different implementations of the contains method, which is also implemented by AbstractCollection in a naive, brute-force-like way. However, contains is overriden in i.e. HashSet to take advantage of hashing, and also in ArrayList, where it uses indexes, etc.
A: You can iterate over one list and remove elements by value from another, then check if another list size == 0. If it is, then that means all second list elements were present in first list at least as many times as in the second list.
public boolean containsAll(List<Character> source, List<Character> target) {
for (Character character : source) {
target.remove(character);
if (target.isEmpty()) {
return true;
}
}
return target.size() == 0;
}
HashMap will be more efficient if lists are huge
public static boolean containsAll(List<Character> source, List<Character> target) {
Map<Character, Long> targetMap = target.stream().collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
for (Character character : source) {
Long count = targetMap.get(character);
if (count != null) {
if (count > 1) {
targetMap.put(character, --count);
} else {
targetMap.remove(character);
}
}
}
return targetMap.isEmpty();
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/48230146",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: Xcode 14.1 'SQLite3' build error : xFilter' from module 'SQLite3' is not present in definition provided earlier /Users/username/Downloads/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS16.2.sdk/usr/include/sqlite3.h:7054:9 'sqlite3_module::xFilter' from module 'SQLite3' is not present in definition of 'struct sqlite3_module' provided earlier
Any idea why getting this error?
I searched google and try to discuss with experts but did not come to a solution
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75244438",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: OAuth with Verification in .NET I'm trying to create a .NET-based client app (in WPF - although for the time being I'm just doing it as a console app) to integrate with an OAuth-enabled application, specifically Mendeley (http://dev.mendeley.com), which apparently uses 3-legged OAuth.
This is my first time using OAuth, and I'm having a lot of difficulty getting started with it. I've found several .NET OAuth libraries or helpers, but they seem to be more complicated than I think I need. All I want to do is be able to issue REST requests to the Mendeley API and get responses back!
So far, I've tried:
*
*DotNetOpenAuth
*http://github.com/bittercoder/DevDefined.OAuth
*http://oauth.googlecode.com/svn/code/csharp/
The first (DotNetOpenAuth) seems like it could possibly do what I needed if I spent hours and hours trying to work out how. The second and third, as best I can tell, don't support the verification codes that Mendeley is sending back -- although I could be wrong about this :)
I've got a consumer key and secret from Mendeley, and with DotNetOpenAuth I managed to get a browser launched with the Mendeley page providing a verification code for the user to enter into the application. However, at this point I got lost and couldn't work out how to sensibly provide that back to the application.
I'm very willing to admit that I have no idea where to start with this (although it seems like there's quite a steep learning curve) - if anyone can point me in the right direction I'd appreciate it!
A: I agree with you. The open-source OAuth support classes available for .NET apps are hard to understand, overly complicated (how many methods are exposed by DotNetOpenAuth?), poorly designed (look at the methods with 10 string parameters in the OAuthBase.cs module from that google link you provided - there's no state management at all), or otherwise unsatisfactory.
It doesn't need to be this complicated.
I'm not an expert on OAuth, but I have produced an OAuth client-side manager class, that I use successfully with Twitter and TwitPic. It's relatively simple to use. It's open source and available here: Oauth.cs
For review, in OAuth 1.0a...kinda funny, there's a special name and it looks like a "standard" but as far as I know the only service that implements "OAuth 1.0a" is Twitter. I guess that's standard enough. ok, anyway in OAuth 1.0a, the way it works for desktop apps is this:
*
*You, the developer of the app, register the app and get a "consumer key" and "consumer secret". On Arstechnica, there's a well written analysis of why this model isn't the best, but as they say, it is what it is.
*Your app runs. The first time it runs, it needs to get the user to explicitly grant approval for the app to make oauth-authenticated REST requests to Twitter and its sister services (like TwitPic). To do this you must go through an approval process, involving explicit approval by the user. This happens only the first time the app runs. Like this:
*
*request a "request token". Aka temporary token.
*pop a web page, passing that request token as a query param. This web page presents UI to the user, asking "do you want to grant access to this app?"
*the user logs in to the twitter web page, and grants or denies access.
*the response html page appears. If the user has granted access, there's a PIN displayed in a 48-pt font
*the user now needs to cut/paste that pin into a windows form box, and click "Next" or something similar.
*the desktop app then does an oauth-authenticated request for an "Access token". Another REST request.
*the desktop app receives the "access token" and "access secret".
After the approval dance, the desktop app can just use the user-specific "access token" and "access secret" (along with the app-specific "consumer key" and "consumer secret") to do authenticated requests on behalf of the user to Twitter. These don't expire, although if the user de-authorizes the app, or if Twitter for some reason de-authorizes your app, or if you lose your access token and/or secret, you'd need to do the approval dance again.
If you're not clever, the UI flow can sort of mirror the multi-step OAuth message flow. There is a better way.
Use a WebBrowser control, and open the authorize web page within the desktop app. When the user clicks "Allow", grab the response text from that WebBrowser control, extract the PIN automatically, then get the access tokens. You send 5 or 6 HTTP requests but the user needs to see only a single Allow/Deny dialog. Simple.
Like this:
If you've got the UI sorted, the only challenge that remains is to produce oauth-signed requests. This trips up lots of people because the oauth signing requirements are sort of particular. That's what the simplified OAuth Manager class does.
Example code to request a token:
var oauth = new OAuth.Manager();
// the URL to obtain a temporary "request token"
var rtUrl = "https://api.twitter.com/oauth/request_token";
oauth["consumer_key"] = MY_APP_SPECIFIC_KEY;
oauth["consumer_secret"] = MY_APP_SPECIFIC_SECRET;
oauth.AcquireRequestToken(rtUrl, "POST");
THAT'S IT. Simple. As you can see from the code, the way to get to oauth parameters is via a string-based indexer, something like a dictionary. The AcquireRequestToken method sends an oauth-signed request to the URL of the service that grants request tokens, aka temporary tokens. For Twitter, this URL is "https://api.twitter.com/oauth/request_token". The oauth spec says you need to pack up the set of oauth parameters (token, token_secret, nonce, timestamp, consumer_key, version, and callback), in a certain way (url-encoded and joined by ampersands), and in a lexicographically-sorted order, generate a signature on that result, then pack up those same parameters along with the signature, stored in the new oauth_signature parameter, in a different way (joined by commas). The OAuth manager class does this for you automatically. It generates nonces and timestamps and versions and signatures automatically - your app doesn't need to care or be aware of that stuff. Just set the oauth parameter values and make a simple method call. the manager class sends out the request and parses the response for you.
Ok, then what? Once you get the request token, you pop the web browser UI in which the user will explicitly grant approval. If you do it right, you'll pop this in an embedded browser. For Twitter, the URL for this is "https://api.twitter.com/oauth/authorize?oauth_token=" with the oauth_token appended. Do this in code like so:
var url = SERVICE_SPECIFIC_AUTHORIZE_URL_STUB + oauth["token"];
webBrowser1.Url = new Uri(url);
(If you were doing this in an external browser you'd use System.Diagnostics.Process.Start(url).)
Setting the Url property causes the WebBrowser control to navigate to that page automatically.
When the user clicks the "Allow" button a new page will be loaded. It's an HTML form and it works the same as in a full browser. In your code, register a handler for the DocumentedCompleted event of the WebBrowser control, and in that handler, grab the pin:
var divMarker = "<div id=\"oauth_pin\">"; // the div for twitter's oauth pin
var index = webBrowser1.DocumentText.LastIndexOf(divMarker) + divMarker.Length;
var snip = web1.DocumentText.Substring(index);
var pin = RE.Regex.Replace(snip,"(?s)[^0-9]*([0-9]+).*", "$1").Trim();
That's a bit of HTML screen scraping.
After grabbing the pin, you don't need the web browser any more, so:
webBrowser1.Visible = false; // all done with the web UI
...and you might want to call Dispose() on it as well.
The next step is getting the access token, by sending another HTTP message along with that pin. This is another signed oauth call, constructed with the oauth ordering and formatting I described above. But once again this is really simple with the OAuth.Manager class:
oauth.AcquireAccessToken(URL_ACCESS_TOKEN,
"POST",
pin);
For Twitter, that URL is "https://api.twitter.com/oauth/access_token".
Now you have access tokens, and you can use them in signed HTTP requests. Like this:
var authzHeader = oauth.GenerateAuthzHeader(url, "POST");
...where url is the resource endpoint. To update the user's status, it would be "http://api.twitter.com/1/statuses/update.xml?status=Hello".
Then set that string into the HTTP Header named Authorization.
To interact with third-party services, like TwitPic, you need to construct a slightly different OAuth header, like this:
var authzHeader = oauth.GenerateCredsHeader(URL_VERIFY_CREDS,
"GET",
AUTHENTICATION_REALM);
For Twitter, the values for the verify creds url and realm are "https://api.twitter.com/1/account/verify_credentials.json", and "http://api.twitter.com/" respectively.
...and put that authorization string in an HTTP header called X-Verify-Credentials-Authorization. Then send that to your service, like TwitPic, along with whatever request you're sending.
That's it.
All together, the code to update twitter status might be something like this:
// the URL to obtain a temporary "request token"
var rtUrl = "https://api.twitter.com/oauth/request_token";
var oauth = new OAuth.Manager();
// The consumer_{key,secret} are obtained via registration
oauth["consumer_key"] = "~~~CONSUMER_KEY~~~~";
oauth["consumer_secret"] = "~~~CONSUMER_SECRET~~~";
oauth.AcquireRequestToken(rtUrl, "POST");
var authzUrl = "https://api.twitter.com/oauth/authorize?oauth_token=" + oauth["token"];
// here, should use a WebBrowser control.
System.Diagnostics.Process.Start(authzUrl); // example only!
// instruct the user to type in the PIN from that browser window
var pin = "...";
var atUrl = "https://api.twitter.com/oauth/access_token";
oauth.AcquireAccessToken(atUrl, "POST", pin);
// now, update twitter status using that access token
var appUrl = "http://api.twitter.com/1/statuses/update.xml?status=Hello";
var authzHeader = oauth.GenerateAuthzHeader(appUrl, "POST");
var request = (HttpWebRequest)WebRequest.Create(appUrl);
request.Method = "POST";
request.PreAuthenticate = true;
request.AllowWriteStreamBuffering = true;
request.Headers.Add("Authorization", authzHeader);
using (var response = (HttpWebResponse)request.GetResponse())
{
if (response.StatusCode != HttpStatusCode.OK)
MessageBox.Show("There's been a problem trying to tweet:" +
Environment.NewLine +
response.StatusDescription);
}
OAuth 1.0a is sort of complicated under the covers, but using it doesn't need to be.
The OAuth.Manager handles the generation of outgoing oauth requests, and the receiving and processing of oauth content in the responses. When the Request_token request gives you an oauth_token, your app doesn't need to store it. The Oauth.Manager is smart enough to do that automatically. Likewise when the access_token request gets back an access token and secret, you don't need to explicitly store those. The OAuth.Manager handles that state for you.
In subsequent runs, when you already have the access token and secret, you can instantiate the OAuth.Manager like this:
var oauth = new OAuth.Manager();
oauth["consumer_key"] = CONSUMER_KEY;
oauth["consumer_secret"] = CONSUMER_SECRET;
oauth["token"] = your_stored_access_token;
oauth["token_secret"] = your_stored_access_secret;
...and then generate authorization headers as above.
// now, update twitter status using that access token
var appUrl = "http://api.twitter.com/1/statuses/update.xml?status=Hello";
var authzHeader = oauth.GenerateAuthzHeader(appUrl, "POST");
var request = (HttpWebRequest)WebRequest.Create(appUrl);
request.Method = "POST";
request.PreAuthenticate = true;
request.AllowWriteStreamBuffering = true;
request.Headers.Add("Authorization", authzHeader);
using (var response = (HttpWebResponse)request.GetResponse())
{
if (response.StatusCode != HttpStatusCode.OK)
MessageBox.Show("There's been a problem trying to tweet:" +
Environment.NewLine +
response.StatusDescription);
}
You can download a DLL containing the OAuth.Manager class here. There is also a helpfile in that download. Or you can view the helpfile online.
See an example of a Windows Form that uses this manager here.
WORKING EXAMPLE
Download a working example of a command-line tool that uses the class and technique described here:
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/4002847",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "109"
}
|
Q: Combined solidcolor brush Is there a way to create a kind of "solidcolorbrush" that is a mixture of 2 solidcolor brushes?
For the back color, i would like to be able to use a DynamicReference to some other brush. While the other color (in the front) could be a static color with opacity.
Feel free to ask for clarification if this doesnt really make sence!
A: I ran into the same problem. I normally just use one xaml each for the basic darks, the basic lights, and then one for each colour accent (blue, red etc). The accent is slightly lookthrough which makes it darker when then darker theme is selected with a darker background.
When creating a theme with a secondary accent colour to have more contrast in the app (for example gray when light theme is selected, accent colour when dark theme), I needed to construct a brush out of two colours as otherwise I would have to create a dark and light theme for each colour.
Here is what I use:
<DrawingBrush x:Key="SecondaryAccentColorBrush" Viewport="0,0,1,1" TileMode="Tile">
<DrawingBrush.Drawing>
<DrawingGroup>
<GeometryDrawing>
<GeometryDrawing.Geometry>
<RectangleGeometry Rect="0,0,1,1" />
</GeometryDrawing.Geometry>
<GeometryDrawing.Brush>
<SolidColorBrush Color="{DynamicResource AccentColor}"/>
</GeometryDrawing.Brush>
</GeometryDrawing>
<GeometryDrawing>
<GeometryDrawing.Geometry>
<RectangleGeometry Rect="0,0,1,1" />
</GeometryDrawing.Geometry>
<GeometryDrawing.Brush>
<SolidColorBrush Color="{DynamicResource Gray10}"/>
</GeometryDrawing.Brush>
</GeometryDrawing>
</DrawingGroup>
</DrawingBrush.Drawing>
</DrawingBrush>
When the theme is switched, the alpha of "Gray10" switches between 00 and FF, thus the brush shows either gray or the accent colour.
A: Unfortunately, custom brushes are not supported in WPF (the brush types are marked 'internal' and cannot be inherited from), so creating a brush that is a mixture of two brushes that can be used from XAML like a normal SolidColorBrush is not possible.
As a workaround, you could use a MarkupExtension to simulate the behaviour of a custom brush, which allows you to use XAML syntax and provide a custom value, which allows us to use the built-in SolidColorBrush (no custom brush necessary) set to the value you get when mixing two colors:
/// <summary>
/// Markup extension to mix two SolidColorBrushes together to produce a new SolidColorBrush.
/// </summary>
[MarkupExtensionReturnType(typeof(SolidColorBrush))]
public class MixedColorBrush : MarkupExtension, INotifyPropertyChanged
{
/// <summary>
/// The foreground mix color; defaults to white.
/// If not changed, the result will always be white.
/// </summary>
private SolidColorBrush foreground = Brushes.White;
/// <summary>
/// The background mix color; defaults to black.
/// If not set, the result will be the foreground color.
/// </summary>
private SolidColorBrush background = Brushes.Black;
/// <summary>
/// PropertyChanged event for WPF binding.
/// </summary>
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// Gets or sets the foreground mix color.
/// </summary>
public SolidColorBrush Foreground
{
get
{
return this.foreground;
}
set
{
this.foreground = value;
this.NotifyPropertyChanged("Foreground");
}
}
/// <summary>
/// Gets or sets the background mix color.
/// </summary>
public SolidColorBrush Background
{
get
{
return this.background;
}
set
{
this.background = value;
this.NotifyPropertyChanged("Background");
}
}
/// <summary>
/// Returns a SolidColorBrush that is set as the value of the
/// target property for this markup extension.
/// </summary>
/// <param name="serviceProvider">Object that can provide services for the markup extension.</param>
/// <returns>The object value to set on the property where the extension is applied.</returns>
public override object ProvideValue(IServiceProvider serviceProvider)
{
if (this.foreground != null && this.background != null)
{
// Create a new brush as a composite of the old ones
// This does simple non-perceptual additive color, e.g
// blue + red = magenta, but you can swap in a different
// algorithm to do subtractive color (red + yellow = orange)
return new SolidColorBrush(this.foreground.Color + this.background.Color);
}
// If either of the brushes was set to null, return an empty (white) brush.
return new SolidColorBrush();
}
/// <summary>
/// Raise the property changed event.
/// </summary>
/// <param name="propertyName">Name of the property which has changed.</param>
protected void NotifyPropertyChanged(string propertyName)
{
if (this.PropertyChanged != null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
Which can then be used from XAML as you would a normal brush:
<Grid>
<Grid.Background>
<local:MixedColorBrush Foreground="Blue" Background="Red"/>
</Grid.Background>
</Grid>
Or by using the markup extension syntax:
<Grid Background="{local:MixedColorBrush Foreground=Blue, Background=Red}">
The downside to this approach is that you cannot use DynamicResource or StaticResource references to bind the values to other resources in your application. MarkupExtension is not a DependencyObject, and resource binding only works on DependencyObjects; the built-in Brushes are DependencyObjects, which is why binding works with traditional brushes.
A: Get the colors from the foreground and background brushes, mix them, and create a new brush from the resulting color.
Example in C#:
Color foreground = foregroundBrush.Color;
Color background = backgroundBrush.Color;
int opacity = 25;
int r = (opacity * (foreground.R - background.R) / 100) + background.R;
int g = (opacity * (foreground.G - background.G) / 100) + background.G;
int b = (opacity * (foreground.B - background.B) / 100) + background.B;
SolidColorBrush mixedBrush = new SolidColorBrush(Color.FromArgb(r, g, b));
A: One easy way to do it (but probably not optimized),
create a LinearGradientBrush of the two colors in repeat mode with Endpoint equals to start point:
<LinearGradientBrush SpreadMethod="Repeat" EndPoint="0,0">
<GradientStop Color="Red" Offset="0" />
<GradientStop Color="Yellow" Offset="1" />
</LinearGradientBrush>
This one gives you an Orange brush.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/906045",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: How to assign color to GVIS timeline chart based on group? I have a dataset that looks like:
Start End GroupingVariable1 GroupingVariable2 Title
1/2/18 1/5/18 Team1 Project Goal
I'm able to use the gvistimeline function in the gvis package to create the timeline chart that functions like a gantt chart.
gvisTimeline(data=df,
rowlabel="GroupingVariable1",
barlabel="Title",
start="start,
end="end")
How do I make the color of each timeline event the second grouping variable?
A: Found the answer. I have to have an additional column to the data that has a defined color based on the grouping variable. Once that is done passing the following argument for bar label works.
barlabel= c("Title", "Color.style")
The color column must be named anytext.style for it to work properly.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/48736871",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Check equal values in two different Columns on Google Scripts I was wondering how can I get the following result:
var X = [ex1, ex2, ex3, ex4];
var Y = [ex3, ex8, ex1, ex5];
Each one of the variables (X and Y) are in different sheets (Let's say, 'sheet' and 'sheet4'), at the column B of the respective sheet.
The output would be
= [ex3, ex1];
I then need to exclude the rows associated with ex1 and ex3 in sheet1.
I'm trying this, but the code returns nothing.
function check(){
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Página1");
var sheet4 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Página4");
var data1 = sheet.getRange("B1:B").getValues();
var data4 = sheet4.getRange("B1:B").getValues();
var lastrow1 = data1.filter(String).length;
var lastrow4 = data4.filter(String).length;
for (var i = 1; i <= lastrow1; i++){
var email1 = sheet.getRange(i, 2).getValue();}
for (var j = 1; j <= lastrow4; j++){
var email4 = sheet4.getRange(j, 2).getValue();}
if (email1[i] == email4[j]){
sheet.deleteRow(i);
}
}
}
}
Thank you!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/51811085",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: React Modal only close when I click background or close icon? Here is a codepen https://codesandbox.io/s/amazing-morning-ukxp2?file=/src/App.js
So I created this modal and I wrapped it with a Background styled component, but I can't figure out how to get the close function to only work if I only click the background or the close icon.
Right now my entire modal is wrapped with this background so no matter where I click it always closes. I only want it to close if I click on the Background or the CloseModalButton, but not when I click on my actual modal.
Here is my code below
export const Modal = ({ showModal, setShowModal }) => {
const animation = useSpring({
opacity: showModal ? 1 : 0,
transform: showModal ? `translateY(0%)` : `translateY(-200%)`
});
return (
<>
{showModal ? (
<Background onClick={() => setShowModal(!showModal)}>
<animated.div style={animation}>
<ModalWrapper showModal={showModal}>
<div>hi</div>
<CloseModalButton
aria-label='Close modal'
onClick={() => setShowModal(!showModal)}
/>
</ModalWrapper>
</animated.div>
</Background>
) : null}
</>
);
};
Then here is my App.js with the function to open and close the modal
function App() {
const [showModal, setShowModal] = useState(false);
const openModal = () => {
setShowModal(!showModal);
};
return (
<Container>
<Button onClick={openModal}>Aye what's good</Button>
<Modal showModal={showModal} setShowModal={setShowModal} />
<GlobalStyle />
</Container>
);
}
The main issue is the Background wraps my entire modal, so I need a way to only trigger my close function if the target is the actually background or the X icon, but not the actual modal itself (which is wrapped inside of the background)
A: You need to track event.target which gives where is has been called i.e
const closeModal = (event) => {
const modal = document.getElementById("myModal");
if (event.target === modal) {
setShowModal(false);
}
};
<Background id="myModal" onClick={closeModal}>
Here is the demo: https://codesandbox.io/s/cranky-hodgkin-o77em?file=/src/components/Modal.js
A: The problem is due to event bubbling. Everytime you click any descendants of the Background element, the click handlers of them fires and bubbles up until it reaches the Background element firing the handler of itself. To solve this, you can either stop the propagation of the click handler of the child elements using stopPropagation() method or you can simply add ID to background and determine if the id matches the background only then firing the showModal method.
<Background onClick={closeModal} id="bg">
const closeModal = (e) => {
if (e.target.id === 'bg') {
setShowModal(false);
}
};
It is not necessary to add id to the close button and check for the targeted button's id since clicking on the button definitely closes the modal.
A: I seen an comment asking how to achieve this with useRef (included typescript types):
const modalBackgroundRef = useRef<HTMLDivElement>(null);
const closeModal = () => {
// Close the modal...
};
const onClickBackground = (event: MouseEvent<HTMLDivElement>) => {
if (event.target === modalBackgroundRef.current) closeModal();
};
return (
<div id="modal-background" tabIndex={-1} ref={modalBackgroundRef} onClick={onClickBackground}>
// Modal goes here...
</div>
);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/64421474",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: multiple layout in a single xml file I just want to use multiple layout in a single xml file.I have attached my code below. In that there will be an absolute layout that should be under Horizontal scroll. As a beginner I don't know how to implement it
need your help friends..
xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/aagr_background2"
android:orientation="vertical" >
<fragment
android:id="@+id/adview153613"
android:name="com.sentientit.theiWedplanner.Fragadmob"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
<RelativeLayout
android:id="@+id/RelativeLayout1"
android:layout_width="fill_parent"
android:layout_height="50dp"
android:background="@drawable/aanavigationbar" >
<Button
android:id="@+id/back"
android:layout_width="70dp"
android:layout_height="50dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="8dp"
android:layout_marginTop="3dp"
android:layout_x="8px"
android:layout_y="3px"
android:background="@drawable/custom_btn_breaker_bay"
android:text="Back"
android:textColor="#ffffff"
android:textSize="20sp" />
<Button
android:id="@+id/home"
android:layout_width="50px"
android:layout_height="30px"
android:layout_alignParentRight="true"
android:layout_alignTop="@+id/back"
android:layout_marginRight="46dp"
android:background="@drawable/home1"
android:paddingBottom="12px"
android:paddingTop="10px"
android:visibility="gone" />
</RelativeLayout>
<AbsoluteLayout
android:layout_width="fill_parent"
android:layout_height="61dp" >
<AbsoluteLayout
android:layout_width="fill_parent"
android:layout_height="61dp"
android:layout_x="120dp"
android:layout_y="35dp" >
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="38dp"
android:layout_y="30dp"
android:text="- Kid Seated"
android:textColor="#000000"
android:textSize="13dp"
android:typeface="serif" >
</TextView>
<ImageView
android:id="@+id/imageView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="6dp"
android:layout_y="28dp"
android:src="@drawable/kid" >
</ImageView>
</AbsoluteLayout>
<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="437dp"
android:layout_y="3dp"
android:src="@drawable/add11_table" />
<Button
android:id="@+id/button3"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="48dp"
android:layout_y="4dp"
android:text="Line"
android:textSize="20sp" />
<Button
android:id="@+id/button1"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="128dp"
android:layout_y="4dp"
android:text="circle"
android:textSize="20sp" />
<Button
android:id="@+id/button2"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="212dp"
android:layout_y="6dp"
android:text="vshape"
android:textSize="20sp" />
</AbsoluteLayout>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<HorizontalScrollView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<LinearLayout
android:id="@+id/table"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
</LinearLayout>
</HorizontalScrollView>
</ScrollView>
Thank you in advance
A: Yes, you can use use multiple layouts in single XML using the <include>.
Here is a example for that:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/app_background"
android:orientation="vertical" >
<include layout="@layout/actionbar_main" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="vertical" >
<ImageView
android:id="@+id/img_rest_pic"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_weight=".35"
android:src="@drawable/upload_image" />
</LinearLayout>
</LinearLayout>
The actionbar_main.xml file is in different XML:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="?android:attr/actionBarSize"
android:background="@drawable/navbar_txt"
android:orientation="vertical" >
<ImageButton
android:id="@+id/ibtn_action_back"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginLeft="5dp"
android:background="@null"
android:src="@drawable/navbar_back" />
<ImageButton
android:id="@+id/ibtn_action_settings"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignTop="@+id/ibtn_action_back"
android:layout_marginRight="5dp"
android:background="@null"
android:src="@drawable/nacbar_setting" />
<View
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_alignParentBottom="true"
android:background="@color/white" />
</RelativeLayout>
A: Not sure whether your looking for this alignment but i just gave a shot..... whenever you wish to fix layout at the bottom of screen make sure you use weight property i.e if you want fix button at the bottom of screen then put android:layout_height = "0dp" and layout_weight="1" for other major layout in the xml and to button which has to be fixed at the bottom use android:layout_height="wrap_content" and layout_weight = "0" that's all is the trick (sorry if i have made it hard to understand... just simply saying play with weight and height property)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#fff"
android:orientation="vertical" >
<fragment
android:id="@+id/adview153613"
android:name="com.sentientit.theiWedplanner.Fragadmob"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" />
<RelativeLayout
android:id="@+id/RelativeLayout1"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1" >
<Button
android:id="@+id/back"
android:layout_width="70dp"
android:layout_height="50dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="8dp"
android:layout_marginTop="3dp"
android:layout_x="8px"
android:layout_y="3px"
android:text="Back"
android:textColor="#ffffff"
android:textSize="20sp" />
<Button
android:id="@+id/home"
android:layout_width="50px"
android:layout_height="30px"
android:layout_alignParentRight="true"
android:layout_alignTop="@+id/back"
android:layout_marginRight="46dp"
android:paddingBottom="12px"
android:paddingTop="10px"
android:visibility="gone" />
</RelativeLayout>
<ScrollView
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:orientation="vertical" >
<HorizontalScrollView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<LinearLayout
android:id="@+id/table"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
</LinearLayout>
</HorizontalScrollView>
</ScrollView>
<AbsoluteLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="0" >
<AbsoluteLayout
android:layout_width="fill_parent"
android:layout_height="61dp"
android:layout_x="120dp"
android:layout_y="35dp" >
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="38dp"
android:layout_y="30dp"
android:text="- Kid Seated"
android:textColor="#000000"
android:textSize="13dp"
android:typeface="serif" >
</TextView>
<ImageView
android:id="@+id/imageView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="6dp"
android:layout_y="28dp" >
</ImageView>
</AbsoluteLayout>
<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="437dp"
android:layout_y="3dp" />
<Button
android:id="@+id/button3"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="48dp"
android:layout_y="4dp"
android:text="Line"
android:textSize="20sp" />
<Button
android:id="@+id/button1"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="128dp"
android:layout_y="4dp"
android:text="circle"
android:textSize="20sp" />
<Button
android:id="@+id/button2"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="212dp"
android:layout_y="6dp"
android:text="vshape"
android:textSize="20sp" />
</AbsoluteLayout>
</LinearLayout>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/31738374",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Method was expected to be of type virtual I've tried to initialize AWSMobileClient.defaultMobileClient() from my AWS Mobile Hub sample project into my test project using this code:
if (AWSMobileClient.defaultMobileClient() == null) {
Log.e("MainActivity", "Initializing AWS Mobile Client...");
final ClientConfiguration clientConfiguration = new ClientConfiguration();
clientConfiguration.setUserAgent(AWSConfiguration.AWS_MOBILEHUB_USER_AGENT);
final IdentityManager identityManager = new IdentityManager(getApplicationContext(), clientConfiguration);
final AWSMobileClient awsClient =
new AWSMobileClient.Builder(getApplicationContext())
.withCognitoRegion(AWSConfiguration.AMAZON_COGNITO_REGION)
.withCognitoIdentityPoolID(AWSConfiguration.AMAZON_COGNITO_IDENTITY_POOL_ID)
.withIdentityManager(identityManager)
.withClientConfiguration(clientConfiguration)
.build();
AWSMobileClient.setDefaultMobileClient(awsClient);
}
When I opened the app in my device, I got this error log in the Android Studio:
09-21 13:01:34.596 28886-28886/com.intap.snspushtest E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.intap.snspushtest, PID: 28886
java.lang.IncompatibleClassChangeError: The method 'java.io.File android.support.v4.content.ContextCompat.getNoBackupFilesDir(android.content.Context)' was expected to be of type virtual but instead was found to be of type direct (declaration of 'com.google.android.gms.iid.zzd' appears in /data/app/com.intap.snspushtest-1/base.apk)
at com.google.android.gms.iid.zzd.zzeC(Unknown Source)
at com.google.android.gms.iid.zzd.<init>(Unknown Source)
at com.google.android.gms.iid.zzd.<init>(Unknown Source)
at com.google.android.gms.iid.InstanceID.zza(Unknown Source)
at com.google.android.gms.iid.InstanceID.getInstance(Unknown Source)
at com.amazonaws.mobile.push.GCMTokenHelper.<init>(GCMTokenHelper.java:44)
at com.amazonaws.mobile.AWSMobileClient.<init>(AWSMobileClient.java:121)
at com.amazonaws.mobile.AWSMobileClient.<init>(AWSMobileClient.java:24)
at com.amazonaws.mobile.AWSMobileClient$Builder.build(AWSMobileClient.java:101)
at com.intap.snspushtest.MainActivity.onCreate(MainActivity.java:43)
at android.app.Activity.performCreate(Activity.java:6876)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1135)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3206)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3349)
at android.app.ActivityThread.access$1100(ActivityThread.java:221)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1794)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7224)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
The lines are as below.
AWSMobileClient.java:121
this.gcmTokenHelper = new GCMTokenHelper(context, AWSConfiguration.GOOGLE_CLOUD_MESSAGING_SENDER_ID);
AWSMobileClient.java:24
public class AWSMobileClient {
AWSMobileClient.java:101
return
new AWSMobileClient(applicationContext,
cognitoIdentityPoolID,
cognitoRegion,
identityManager,
clientConfiguration);
MainActivity.java:43
final AWSMobileClient awsClient =
new AWSMobileClient.Builder(getApplicationContext())
.withCognitoRegion(AWSConfiguration.AMAZON_COGNITO_REGION)
.withCognitoIdentityPoolID(AWSConfiguration.AMAZON_COGNITO_IDENTITY_POOL_ID)
.withIdentityManager(identityManager)
.withClientConfiguration(clientConfiguration)
.build();
I don't really understand what problem I am facing with, so could you please help me?
A: I have changed my Google Play Services library version from 9.0.0 to 9.0.1 and it solved it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/39613580",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: What is the difference between Calling a method by one of the three methods? What is the difference between Calling a method by one of the three methods ?
*
*via Creating a new thread
*Synchronous call through Invoke
*Asynchronous call through BeginInvoke and alternatively EndInvoke
I am assuming all the calls will be using a matching delegate under the hood.
A: (Assuming .NET given your user name...) These three options are different ways to use a delegate.
Creating a new thread doesn't specifically "call a method", but rather starts a new thread using a specified delegate as the method to run within the new thread. This will launch an entire new thread for you, and run your delegate within the separate thread.
Asynchronously calling the delegate via BeginInvoke/EndInvoke is similar, except that it will use the ThreadPool instead of creating a new thread.
Synchronously calling the delegate via Invoke will just call the delegate directly on the currently executing thread. This effectively just calls the method being referenced by the delegate.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/10033589",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Importing to IntelliJ - Error package org.springframework.boot does not exist Dear Stackoverflow Community, I have the following problem with my spring boot starter application. I imported the starter project as a new maven project into IntelliJ. But IntelliJ does not find the dependencies I specified in the pom.
Image of my Application Class:
If I try to run the project I get the following error message.
Image of the Error Message:
I already tried everything from re-installing IntelliJ to re-importing the project or redownloading the dependencies. I simply dont know why IntelliJ doesn´t find the dependencies.
My pom.xml looks as following
Image of my pom.xml:
The first time I tried to edit the pom.xml it said to me "this file does not belong to the project". Maybe this might be one reason.
Running the whole thing with 'mvn install' or 'mvn clean verify' works.
A: Sometimes your workspace could get corrupted.
In my case, I tried to Reload the project and it worked
A: in my case changed JDK version in Maven importer from JDK 11 to my local JDK version 1.8
A: Try this and then build: mvn -U idea:idea
A: Had the same problem. I have tried everything: invalidating cache, deleting the whole .m2 folder, changing settings, reloding the project, nothing helped.
The solution for me was to delete the .iml files which are IntelliJ module files used for keeping module configuration. After reopening the project it worked.
The idea was not mine, I found the hint here: https://intellij-support.jetbrains.com/hc/en-us/community/posts/203365204--package-does-not-exist-error-despite-autocomplete-being-aware-of-them
A: Here is how my IntelliJ settings for spring boot application looks like
Click open -> browse your workspace -> and select POM.xml file
Check this in your intelliJ settings
Do this too [Settings --> Maven --> Importing]
A: I just had the same issue. My solution was to remove all dependencies from the pom, reload via maven -> Reload All Maven Projects. Run mvn compile. Add dependencies back to the pom, maven -> Reload All Maven Projects. Run mvn compile.
Now the Intellij build works.
A: You need to change Maven's JDK for importing option from Project JDK to the Path variable for Java on your machine.
You can get to this by going to Settings -> Build, Execution, Deployment -> Build Tools -> Maven -> Importing. Scroll down to the bottom and look for JDK for importing:. Select from the list the path variable for JAVA.
For Windows users, JAVA_HOME should be an option in the drop-down list.
A: Follow these steps, your problem should be solved. You just need to add Spring-framework-starter-web and Spring-framework-starter-tester from your pom.xml file.
*
*Got to generate(ALT+Insert)
*Add dependencies
*Search "springframwork"
*Add...
Here is the link
A: In my case, adding the project as maven project helped .
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/53869118",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
}
|
Q: Using a wrapper class to hide functions A colleague of mine preferes to encapsulate all of the PHP functions behind classes. His justification seems to be that if its in a class its going to be easier to change if they ever update the code. My concern after looking at his code is I have no clue what might be happening, or why things might error out. Additionally if it were in class form I'd prefer a a static function to what he is doing as it seems to me would be better practice.
For example instead of:
$var = filter_var('0755', FILTER_VALIDATE_INT);
He would have:
class Filter {
public function filterInt($var) {
return filter_var($var, FILTER_VALIDATE_INT);
}
}
$filter = new Filter();
$var = $filter->filterInt('0755');
Which way would be better practice? better for long term performance? better for understanding?
A: Hiding functionality in methods is good practice, Code Complete explains quite well, why that's the case.
If you ever want to change the filterInt, e.g. add upper and lower bounds, you are way better off if you have encapsulated it.
*
*less code lines to be changed
*easier to test against
*..
A: For only one method like your example, it does not make much sense.
It start to make sense if you use it to group all your filter function here, you could have Filter::filterDeliveryAdress and then, anytime you have to filter something you might remember that you already have a function for this. So if you filter function is for exsample not accurate enough, you can fix it in the class to get it fixed in all your code.
Of course here a static function would be better, it's even easier to use.
If, as I think, it's only for grouping related function and your using PHP >= 5.3, namespace would be more appropriate.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/9508235",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Android wear app with Line App Integration I would like to know more about the weather android wear will support the Line app or not. I've an requirement that sign-In with Line app. When I pair with the device and watch, where I could not able to see the my line app in android watch. Please suggest me the best possible solutions.
Please revert back for any clarification.
A: There's no indication at http://line.me that LINE supports Android Wear. So if LINE isn't running on the watch, you'll need to build an interface with the phone, and connecct to the LINE API there.
Get started with the documentation at https://developer.android.com/training/wearables/data-layer/index.html
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/43703202",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to get velocity vector for a point of a fixture? (Box2d) I have a top-down view tank project written in C++(QT). The tank consists of a "base" which is connected through a revjoint to the "turret" which can rotate and shoot. Turret is a circle shape and a rectangle attached to it as the barrel. Quite basic.
When a projectile is shot, its initial velocity vector should be added to the velocity vector of the tip of the barrel, otherwise the shot is unrealistic if the tank or the barrel moves. I can get only the velocity vector of a body, and it is not enough here, since the velocity vector of the tip of the barrel is a different thing then the velocity vector of the turret body.
I tried to weldjoint a fixtureless body to the tip of the barrel as a "muzzle". The muzzle body velocity vector is exactly the one I'm looking for. It didn't work though, the welded fixtureless body constrained the turret from rotating for some reason.
Then I did the same with a body with a fixture. It works, but seems overcomplicated solution, brings in new issues.
My questions are:
*
*Is there any issues with fixtureless bodies I'm not aware of? Why I can't them just weld somewhere for easily accessing the speed vector of that point?
*Is there any "standard" solution to get the velocity vector of an arbitrary point of a fixture?
Daniel
A: I think the function you are looking for is b2Body::GetLinearVelocityFromWorldPoint
https://code.google.com/p/box2d/source/browse/trunk/Box2D/Box2D/Dynamics/b2Body.h#273
You can get the 'world point' of the end of the gun barrel with b2Body::GetWorldPoint.
To find the direction of the gun in world coordinates, b2Body::GetWorldVector might be useful.
A: I'm answering my own question after some research.
*
*If a body is used without any fixtures, be sure to set some mass to it manually, otherwise it'll behave unexpected. After doing so, the muzzle body's paramaters were exactly I was about using them. Here's how to set mass to a body without any fixtures.
b2MassData md;
md.center = b2Vec2(0,0);
md.I = 0.000001f;
md.mass = 0.000001f;
body->SetMassData(&md);
*An other solution might be the one iforce2d posted. Thanks for that, I'll check it out!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/27398392",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Running Java program with custom directory structure as Windows service I am using YAJSW to install (and uninstall) my program as Windows service (win 32 and win 64) with the following directory structure.
How do I go about it ?
apps - user works with this dir
log - user works with this dir
core - core of my program, user not works with this dir, here may be anything, include wrappers.
install.cmd - user launch it to install software as windows service
uninstall.cmd - user launch it to uninstall windows service
settings.cmd - a very short file with user properties. javapath, ntservicename, dburl, dbuser, dbpass at all - user edit it.
A: Here is the comprehensive tutorial..
http://yajsw.sourceforge.net/
and one for windows service
https://docs.wso2.org/display/Carbon403/Installing+as+a+Windows+Service
A: You can play around with the scripts located in yajsw/bat, specifically with setenv.bat.
That is the script that creates your environment variables.
A: I found and look throught about 20 wrappers and helpers. Some of them is payd, some of them needs code modification, some complex, some have issues. I found only one good solution - NSSM . I think it solve the problems as it must be solved.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/22522721",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Regex match last occurrence of a string from multiple lines I'm trying to match the last occurrences of a string from a log file.
[03/03/2019 09:16:36] Moving message 123456789 from NEW to PENDING
[03/03/2019 09:16:36] Retrieving file(s) of type DATAWAREHOUSE for 123456
[03/03/2019 09:16:36] collecting warehouse version 7.3.1 files for 123456...
[03/03/2019 09:16:37] Moving message 123456789 from NEW to PENDING
[03/03/2019 09:16:37] Retrieving file(s) of type DATAWAREHOUSE for 123456
[03/03/2019 09:16:37] collecting warehouse version 7.3.1 files for 123456...
[03/03/2019 09:16:38] Moving message 123456789 from NEW to PENDING
[03/03/2019 09:16:39] Retrieving file(s) of type DATAWAREHOUSE for 123456
[03/03/2019 09:16:40] collecting warehouse version 7.3.1 files for 123456...
Above is the sample log file from which there are three occurrences of the below string,
Moving message 123456789 from NEW to PENDING
I need to match the last occurrence to get the respective timestamp "[03/03/2019 09:16:38]".
But when all these are in a single line using greedy approach (.*) it works fine. But when they are present in multiple lines it isn't working. I haven't tried multiline (m) as I'm not sure how to use it. Can someone please help me construct the regex query to retrive this last occurrence timestamp?
Example: https://regex101.com/r/fnwPsB/1
A: You may use
(?s:.*\n)?\K\[(\d{2}\/\d{2}\/\d{4} \d{2}:\d{2}:\d{2})\] Moving message 123456789 from NEW to PENDING
See the regex demo
Details
*
*(?s:.*\n)? - an inline modifier group that matches any 0+ chars as many as possible up to the last LF char that is followed with the last occurrence of the subsequent patterns.
*\K - match reset operator removing all text matched so far from the match memory buffer
*\[(\d{2}\/\d{2}\/\d{4} \d{2}:\d{2}:\d{2})\] Moving message 123456789 from NEW to PENDING - the specific line pattern to get with the datetime captured in Group 1.
Alternatively, use
(?s)(\[\d{2}\/\d{2}\/\d{4} \d{2}:\d{2}:\d{2}\] Moving message 123456789 from NEW to PENDING)(?!.*(?1))
See this regex demo.
Details
*
*(?s) - DOTALL modifier making . match any char
*(\[(\d{2}\/\d{2}\/\d{4} \d{2}:\d{2}:\d{2})\] Moving message 123456789 from NEW to PENDING) - the necessary pattern to match captured into Group 1 and the datetime in Group 2
*(?!.*(?1)) - a negative lookahead that fails the match if there is the same pattern as defined in Group 1 after any 0+ chars to the right of the current position.
A: Here is a solution that is not dependent on PCRE feature using negative lookahead:
(?s)\[(\d{2}\/\d{2}\/\d{4} \d{2}:\d{2}:\d{2})\] Moving message 123456789 from NEW to PENDING(?!.* Moving message 123456789 from NEW to PENDING)
RegEx Demo
Date-time is available in 1st capture group.
Here (?!.* Moving message 123456789 from NEW to PENDING) is negative lookahead that ensures we match very last occurrence of given pattern.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/55001166",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: FirebaseAnimatedList doesn't return anything I'm trying to write an app that will detect Barcode ID. Once detected, it will fetch value in my Firebase Database and display them inside my Widget. I want my widget to be dynamic since i don't know how many items could be inside each ID. So i tried using FirebaseAnimatedList class. Issue is i can't get my Widget show up in my page at all.
Here's my code
import 'dart:async';
import 'package:firebase_database/ui/firebase_animated_list.dart';
import 'package:flutter/material.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:logistec/widget/result_page/productlist.dart';
class Scanning_Result_Page extends StatefulWidget {
Scanning_Result_Page(this.phyid, {Key? key}) : super(key: key);
String phyid;
@override
State<Scanning_Result_Page> createState() => _Scanning_Result_PageState();
}
class _Scanning_Result_PageState extends State<Scanning_Result_Page> {
late String productcode;
late String productname;
late int quantity;
late Query _ref =
FirebaseDatabase.instance.ref().child('Database').child(widget.phyid);
//firebase structure currently goes like this
//PHYID
//|---number
//|-----items_name
//|-----items_codes etc...
//Therefore i need it to first fetch PHYID
//then after that, use for loop from 0 to the full lenght of that ID
//
@override
Widget build(BuildContext context) {
return Scaffold(
resizeToAvoidBottomInset: false,
appBar: PreferredSize(
preferredSize: Size(40, 40),
child: AppBar(
backgroundColor: Colors.amber.shade400,
)),
body: Container(
height: double.infinity,
child: FirebaseAnimatedList(
shrinkWrap: true,
query: _ref.equalTo(widget.phyid),
itemBuilder: (BuildContext context, DataSnapshot snapshot,
Animation<double> animation, int index) {
Map database = snapshot.value as Map;
if (database != null) {
//result = key - phyid | value - 0?
return ProductList(
productcode: 'Test 1', //will change this later. just need it to work for now.
productname: 'Test 1',
serial: 'Test 1',
quantity: 1,
phyid_result: widget.phyid,
);
} else {
return Text("no data");
}
return CircularProgressIndicator();
},
),
),
);
}
}
And here's my Widget page. (I don't think it's related to my issue but i'll include them regardless.)
import 'package:flutter/material.dart';
class ProductList extends StatelessWidget {
ProductList({
Key? key,
required this.productcode,
required this.productname,
required this.quantity,
required this.phyid_result,
required this.serial,
}) : super(key: key);
final String productcode;
final String productname;
final int quantity;
final String phyid_result;
final String serial;
//The Look in my head
//Each Container will have
///////////////////////////////////
///ProductCode /
///ProductName /
/// /
/// ///////////////////////////////
/// Quantity/
/// ///////////////////////////////
final appBar = AppBar();
@override
Widget build(BuildContext context) {
final screenSize = MediaQuery.of(context);
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
resizeToAvoidBottomInset: false,
body: CustomScrollView(
scrollDirection: Axis.vertical,
slivers: [
SliverList(
delegate: SliverChildListDelegate([
Container(
padding: const EdgeInsets.all(15.0),
alignment: Alignment.center,
color: Colors.black,
height: 70.0,
child: Text(
phyid_result,
style: const TextStyle(
color: Colors.white,
fontSize: 25,
),
),
),
Container(
height: screenSize.size.height,
decoration: BoxDecoration(
border: Border.all(color: Colors.grey.shade600)),
child: IntrinsicHeight(
child: Column(
//mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Container(
padding: EdgeInsets.all(5),
child: Text(
productcode,
style: const TextStyle(fontSize: 20),
),
),
Container(
padding: EdgeInsets.all(5),
width: screenSize.size.width,
decoration: BoxDecoration(
border: Border.all(
color: Colors.grey.shade200,
strokeAlign: StrokeAlign.inside)),
child: Text(
productname,
style: const TextStyle(fontSize: 20),
),
),
Container(
padding: EdgeInsets.all(5),
width: screenSize.size.width,
decoration: BoxDecoration(
border: Border.all(
color: Colors.grey.shade200,
strokeAlign: StrokeAlign.inside)),
child: Text(
serial,
style: const TextStyle(fontSize: 20),
),
),
Align(
alignment: Alignment.topRight,
child: Flexible(
fit: FlexFit.loose,
child: SizedBox(
width: 90,
child: Container(
decoration: BoxDecoration(
border:
Border.all(color: Colors.grey.shade200),
),
padding: EdgeInsets.all(5),
child: Text(
'Quantity : \n\v${quantity}',
style: TextStyle(fontSize: 18),
textAlign: TextAlign.right,
)),
),
),
)
],
),
),
),
]))
],
),
),
);
}
}
The Scaffold part works. But everything inside FirebaseAnimated List all the way to CircularProgressIndicator doesn't work at all. It didn't even return if else statement. Just empty blank page with Scaffold.
The Widget itself will work fine if i remove everything out, and return only the ProductList widget itself. I tried searching on Google and didn't find anyone having issue like me. So i think i'm stuck. Does anyone know what could be the issue? Thanks for the assistance in advance!
A: So i solve my own issue.
It turns out that my Widget is the actual root cause. I don't think SliverList is playing well with FirebaseAnimatedList (maybe because they are doing essentially the same thing?) So i refactor and remove everything related to SliverList.
Widget build(BuildContext context) {
final screenSize = MediaQuery.of(context);
return Container(
decoration:
BoxDecoration(border: Border.all(color: Colors.grey.shade600)),
child: Column(
//mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Container(
padding: EdgeInsets.all(5),
child: Text(
productcode,
style: const TextStyle(fontSize: 20),
),
),
Container(
padding: EdgeInsets.all(5),
width: screenSize.size.width,
decoration: BoxDecoration(
border: Border.all(
color: Colors.grey.shade200,
strokeAlign: StrokeAlign.inside)),
child: Text(
productname,
style: const TextStyle(fontSize: 20),
),
),
Container(
padding: EdgeInsets.all(5),
width: screenSize.size.width,
decoration: BoxDecoration(
border: Border.all(
color: Colors.grey.shade200,
strokeAlign: StrokeAlign.inside)),
child: Text(
serial,
style: const TextStyle(fontSize: 20),
),
),
Align(
alignment: Alignment.topRight,
child: Flexible(
fit: FlexFit.loose,
child: SizedBox(
width: 90,
child: Container(
decoration: BoxDecoration(
border: Border.all(color: Colors.grey.shade200),
),
padding: EdgeInsets.all(5),
child: Text(
'Quantity : \n\v${quantity}',
style: TextStyle(fontSize: 18),
textAlign: TextAlign.right,
)),
),
),
)
],
),
);
Then i reimplemented it into my pages. Now it works as expected. all is well again!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73795760",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: EAS build development for IOS fails on Pods install I hope someone can help me, when i try to build an app using expo with the command eas build --profile development --platform ios, it gives me the error below "The following Swift pods cannot yet be integrated as static libraries: ...". This happens only on IOS, android is working fine, i try to look for a solution but didn't find a lot of information regarding this issue...
Any solution ?
This is the error message in the expo logs.
[!] The following Swift pods cannot yet be integrated as static libraries:
The Swift pod `FirebaseCoreInternal` depends upon `GoogleUtilities`, which does not define modules. To opt into those targets generating module maps (which is necessary to import them from Swift when building as static libraries), you may set `use_modular_headers!` globally in your Podfile, or specify `:modular_headers => true` for particular dependencies.
The Swift pod `FirebaseStorage` depends upon `FirebaseStorageInternal`, `FirebaseAppCheckInterop`, `FirebaseAuthInterop`, `FirebaseCore`, and `FirebaseCoreExtension`, which do not define modules. To opt into those targets generating module maps (which is necessary to import them from Swift when building as static libraries), you may set `use_modular_headers!` globally in your Podfile, or specify `:modular_headers => true` for particular dependencies.
pod exited with non-zero code: 1
Printscreen of error log
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73489662",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: API & app for sending notifications to iPhone? In a project I'm working on, I want to send notifications to my user's iPhone from my Chrome extension. The notifications will mostly be about their accounts on my site, and I would like them to be able to reply with the type of action they want taken concerning the alerts.
To help me do this, I found http://pushme.to/1 which works by allowing the iPhone owner to download their app, create an account via that app, and from then on be able to receive
"IM"-like messages and push notifications. I can send my iPhone users messages via http://pushme.to/iphone_users_username by automating that page with javascript. However, it will be imperative that I also send images along with the alerts, and am unable to do that as the site uses a flash uploader.
[EDIT: To clarify - pushme.to has a feature that allows you to send along images with a message, this is what I was referring to]
So, to cut to the chase and hit the bottom line: does anyone know of an app the provides a companion app & API for sending messages that the user can reply to? Meaining that the user receives my messages, can reply to them - and my Chrome Extension receive their replies?
Thanks in advance!
1 Service no longer active
A:
However, it will be imperative that I also send images along with the alerts
I might be misunderstanding your question, but the push notification framework doesn't support images. You can only send text, badges (the red numbers next to an app icon), or sounds (which must already be installed in the app bundle).
Perhaps you can use a third-party option to do it, but push.me wasn't really designed for automated comms, but for friend to friend IMs. You may have to create your own app to achieve this...I'm not sure of any third party app you could use.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/5220742",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Run-time 438 on searching and pasting gender I am running the following code that takes a value from column A, searches it on the URL: https://gender-api.com and returns the gender of the person and pastes it in column B.
I get a
run-time error 438
when running the code. Please help.
Sub URL_Get_Gender_Query()
strSearch = Range("a4")
With ActiveSheet.QueryTables.Add(Connection:="URL;https://gender-api.com?SearchText=" & strSearch & "&safe=active", _Destination:=Range("b4"))
'^ Run-time error 438 here
.BackgroundQuery = True
.TablesOnlyFromHTML = True
.Refresh BackgroundQuery:=False
.SaveData = True
End With
End Sub
A: Here's another way to do it, using the WinHttpRequest object:
Dim httpRequest As Object
Dim url As String
Dim i As Long
Dim jsonResponse As String
Set httpRequest = CreateObject("MSXML2.ServerXMLHTTP")
url = "https://gender-api.com/get?name=elizabeth" ' For example
httpRequest.Open "POST", url, False
httpRequest.send
jsonResponse = httpRequest.ResponseText
MsgBox jsonResponse
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/46315340",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
}
|
Q: Polymorphic queries with NHibernate Search I have multiple entities stored in a single NHibernate Search index, in the hope that I'd be able to query over all of them at once. The use case is a simple search page which returns mixed results. So, for example, the code could look like this:
public interface ISearchable {}
[Indexed(Index = "TheIndex")]
public class SearchableEntityA : ISearchable
{
// Some [Field]s
}
[Indexed(Index = "TheIndex")]
public class SearchableEntityB : ISearchable
{
// Some other [Field]s
}
This all indexes fine, and of course is queryable in raw NHibernate like so:
session.CreateCriteria<ISearchable>().List<ISearchable>();
I have some fields on ISearchable, but these aren't specifically referenced in NHibernate mappings.
My hope was that I could just say:
var query = "some keyword";
fullTextSession.CreateFullTextQuery<ISearchable>(query).List<ISearchable>();
And retrieve a list of ISearchables, containing results from various different entities. However, the reality is that it throws NHibernate.HibernateException: Not a mapped entity: NetComposites.Model.ISearchable.
So, what's the simplest way to achieve something resembling polymorphic queries with NHibernate Search?
A: An overload of CreateFullTextQuery exists that allows you to specify the types to search:
fullTextSession.CreateFullTextQuery(query, typeof(EntityA), typeof(EntityB)).List<ISearchable>();
It's a little clunky having to specify all the types, but they load fine. The only remaining problem I have is that my assumption that you could just do an all fields search by default was incorrect, so it requires building a MultiFieldQueryParser over all properties of all searchable entities:
private static Query ParseQuery(string query, IFullTextSession searchSession)
{
var parser = new MultiFieldQueryParser(GetAllFieldNames(searchSession), new StandardAnalyzer());
return parser.Parse(query);
}
private static string[] GetAllFieldNames(IFullTextSession searchSession)
{
var reader =
searchSession.SearchFactory.ReaderProvider.OpenReader(
searchSession.SearchFactory.GetDirectoryProviders(typeof (Company)));
var fieldNames = reader.GetFieldNames(IndexReader.FieldOption.ALL);
return fieldNames.Cast<string>().ToArray();
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/9176624",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Zookeeper install via Ambari Performing install via Ambari 1.7 and would like to get some clarification regarding the Zookeeper installation. The setup involves (3) Zookeeper and (3) Kafka instances.
Ambari UI asks to specify Zookeeper master(s) and Zookeeper clients/slaves. Should I choose all three Zookeeper nodes as masters and install Zookeeper client on each Kafka server?
Zookeeper doesn't have any master node(s) and I am a little confused here with this Ambari master/slave terminology.
A: Zookeeper Server is considered a MASTER component in Ambari terminology. Kafka has the requirement that Zookeeper Server be installed on at least one node in the cluster. Thus the only requirement you have is to install Zookeeper server on one of the nodes in your cluster for Kafka to function. Kafka does not require Zookeeper clients on each Kafka node.
You can determine all this information by looking at the Service configurations for KAFKA and ZOOKEEPER. The configuration is specified in the metainfo.xml file for each component under the stack definition. The location of the definitions will differ based on the version of Ambari you have installed.
On newer versions of Ambari this location is:
/var/lib/ambari-server/resources/common-services/<service name>/<service version>
On older version of Ambari this location is:
/var/lib/ambari-server/resources/stacks/HDP/<stack version>/services/<service name>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/27555286",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Qt signal/slots - consume signal in one of many slots? Is there a way to consume future slots (and stop them from executing) in one of many slots connected to the same signal?
My goal here is to emit a signal with a message to many QObjects and consume (stopping iteration to future slots) when the QObject in which the message belongs to finds it.
From what I understand in the Qt Documentation:
If several slots are connected to one signal, the slots will be
executed one after the other, in the order they have been connected,
when the signal is emitted.
I want to be able to stop this process from within a slot.
Suggestions?
A: No, there's no way to do it, and you should not think of it this way. The sender should perform the same no matter what number of slots are connected to a signal. That's the basic contract of the signal-slot mechanism: the sender is completely decoupled from, and unaware of, the receiver.
What you're trying to do is qualified dispatch: there are multiple receivers, and each receiver can process one or more message types. One way of implementing it is as follows:
*
*Emit (signal) a QEvent. This lets you maintain the signal-slot decoupling between the transmitter and the receiver(s).
*The event can then be consumed by a custom event dispatcher that knows which objects process events of given type.
*The objects are sent the event in the usual fashion, and receive it in their event() method.
The implementation below allows the receiver objects to live in other threads. That's why it needs to be able to clone events.
class <QCoreApplication>
class <QEvent>
class ClonableEvent : public QEvent {
Q_DISABLE_COPY(ClonableEvent)
public:
ClonableEvent(int type) : QEvent(static_cast<QEvent::Type>(type)) {}
virtual ClonableEvent * clone() const { return new ClonableEvent(type()); }
}
Q_REGISTER_METATYPE(ClonableEvent*)
class Dispatcher : public QObject {
Q_OBJECT
QMap<int, QSet<QObject*>> m_handlers;
public:
Q_SLOT void dispatch(ClonableEvent * ev) {
auto it = m_handlers.find(ev->type());
if (it == m_handlers.end()) return;
for (auto object : *it) {
if (obj->thread() == QThread::currentThread())
QCoreApplication::sendEvent(obj, ev);
else
QCoreApplication::postEvent(obj, ev.clone());
}
}
void addMapping(QClonableEvent * ev, QObject * obj) {
addMapping(ev->type(), obj);
}
void addMapping(int type, QObject * obj) {
QSet<QObject*> & handlers = m_handlers[type];
auto it = handlers.find(obj);
if (it != handlers.end()) return;
handlers.insert(obj);
QObject::connect(obj, &QObject::destroyed, [this, type, obj]{
unregister(type, obj);
});
m_handlers[type].insert(obj);
}
void removeMapping(int type, QObject * obj) {
auto it = m_handlers.find(type);
if (it == m_handlers.end()) return;
it->remove(obj);
}
}
class EventDisplay : public QObject {
bool event(QEvent * ev) {
qDebug() << objectName() << "got event" << ev.type();
return QObject::event(ev);
}
public:
EventDisplay() {}
};
class EventSource : public QObject {
Q_OBJECT
public:
Q_SIGNAL void indication(ClonableEvent *);
}
#define NAMED(x) x; x.setObjectName(#x)
int main(int argc, char ** argv) {
QCoreApplication app(argc, argv);
ClonableEvent ev1(QEvent::User + 1);
ClonableEvent ev2(QEvent::User + 2);
EventDisplay NAMED(dp1);
EventDisplay NAMED(dp12);
EventDisplay NAMED(dp2);
Dispatcher d;
d.addMapping(ev1, dp1); // dp1 handles only ev1
d.addMapping(ev1, dp12); // dp12 handles both ev1 and ev2
d.addMapping(ev2, dp12);
d.addMapping(ev2, dp2); // dp2 handles only ev2
EventSource s;
QObject::connect(&s, &EventSource::indication, &d, &Dispatcher::dispatch);
emit s.indication(&ev1);
emit s.indication(&ev2);
return 0;
}
#include "main.moc"
A: If connection was in one thread, I think that you can throw an exception. But in this case you should be catch any exception during emit a signal:
try {
emit someSignal();
} catch(...) {
qDebug() << "catched";
}
But I think that it's bad idea. I'll would be use event dispatching for this.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/31592972",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to integrate role based access token authentication for API methods generated using node-restful package? I am using the node-restful package for automatic API generation.
But I am not sure how to integrate role based access token validation for each of the automatically generated API methods GET, POST, PUT and DELETE
For Eg:
var Resource = app.resource = restful.model('resource', mongoose.Schema({
title: String,
year: Number,
}))
.methods(['get', 'post', 'put', 'delete']);
Resource.register(app, '/resources');
I want admin to have access to all the above methods but a normal user should have access to only post and get method.
Please help me with this. Thanks.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/57509368",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Syntax errors in the verilog code I want to convert this c code to verilog module but I am having some difficulty
void window_averaging(void) {
register unsigned int i, k;
for (i = 0; i < 128; i++) {
// Copying first 128 output samples to the Window 0 and so on till Window 7.
W[count][i] = O[i];
}
for (i = 0; i < 128; i++) {
for (k = 0; k< 8; k++) {
O[i] += W[k][i];
}
O[i] /= 8; // Averaging over 8 window
}
count = (count++)%8; // Count = 0 after all the window elements are filled.
}
Verilog:
module window_averaging(
input [16:0]in_noise, //input from noise cancellation
input clk,
output reg [16:0]window_average // output after window averaging
);
integer i;
integer k;
integer count = 0;
reg [16:0] store_elements[0:7][0:128]; // 2-D array for window averaging
reg [16:0] temp;
always @(posedge clk)
begin
// Copying first 128 output samples to the Window 0 and so on till Window 7
for(i=0 ; i < 128 ; i = 1+1)
begin
store_elements[count][i] = in_noise;
end
for(i=0; i<128 ; i=i+1)
begin
for(k=0;k<8;k = k+1)
begin
temp = temp + store_elements[i][k];
end
window_average = temp/8;
count = (count+1)%8;
end
end
endmodule
The errors I am getting are syntax error near "(" and "=". I am little new to verilog can anyone help me how to proceed.
A: First you are trying to drive a wire from inside an @always block which is not allowed. If you convert the wires to regs then it will work:
module window_averaging(
input [16:0]in_noise, //input from noise cancellation
input clk,
output reg [16:0]window_average // output after window averaging
);
integer i;
integer k;
integer count = 0;
reg [16:0] store_elements[0:7][0:128]; // 2-D array for window averaging
reg [16:0] temp;
...
Also I believe to be consistent with your C code the line count = (count+1)%8; should be outside the for loop like so:
window_average = temp/8;
end
count = (count+1)%8;
end
endmodule
A: I don't know what you are using to compile, but I think the following stuff should give you errors:
For the first loop:
for(i=0 ; i < 128 ; i = 1+1)
change to i= i+1
Also, in line:
temp = temp + store_elements[i][k];
remember the declaration store_elements[0:7][0:128] , so may be switch i and k ?
This isn't an answer really. Sorry, I don't have comment privilege yet.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/26378440",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to do scroll control in flutter by passing the data fetched from api as pageno How to make scroll control by sending the next page parameter as pageno in url. I have url where I am sending the pageno as pageno='', and to get the next page I need to pass the data which is returned from the future fetchpost. For example I have initial url as
"https://example.org/api.php&action=query&gcmtitle=Category:$cname&pilimit=max&generator=categorymembers&format=json&gcmcontinue=$pageno where pageno=''
and second url to get next page content is
https://example.org/api.php&action=query&gcmtitle=Category:$cname&pithumbsize=600&generator=categorymembers&format=json&gcmcontinue=$pageno
where pageno='some string value'.
I have written code but the when I scroll to the end of the page I am passing next page data to url and it wipes out the data of first page and displays next page page content list on it instead continuing with the list below the firstpage.
Below is my code please help me with the issue.
class Herbs extends StatefulWidget {
final String title;
Herbs(this.title);
@override
_HerbsState createState() => new _HerbsState();
}
class _HerbsState extends State<Herbs> {
List<Herbslist> herbslist = [];
var cname;
var gcm;
var pageno = '';
ScrollController _scrollController = new ScrollController();
@override
void initState() {
fetchPost(pageno);
_scrollController.addListener(() {
if (_scrollController.position.pixels ==
_scrollController.position.maxScrollExtent) {
setState(() {
pageno = gcm;
fetchPost(pageno);
});
}
});
super.initState();
}
Future<Herbslist> fetchPost(String pageno) async {
final response = await http.get(
'https://example.org/api.php?action=query&gcmtitle=Category:$cname&pilimit=max&prop=pageimages&pithumbsize=600&generator=categorymembers&format=json&gcmcontinue=$pageno'
);
if (response.statusCode == 200) {
if(this.mounted){
var jsonData = json.decode(response.body);
gcm = jsonData["continue"]["gcmcontinue"];
}
} else {
print(Exception);
throw (e) {
print("Exception thrown: $e");
Exception(e);
};
}
return Herbslist.fromJson(json.decode(response.body));
}
@override
void dispose() {
_scrollController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
cname = widget.title;
return new Scaffold(
appBar: AppBar(
title: Align(
alignment: Alignment(-0.2, 0.3),
child: Text(
cname,
),
),
),
body: Center(
child: FutureBuilder<Herbslist>(
future: fetchPost(gcm),
builder: (context, snapshot) {
if (snapshot.hasData) {
return ListView.builder(
shrinkWrap: true,
controller: _scrollController,
itemCount: snapshot.data.query.pages.length,
itemBuilder: (BuildContext context, int index) {
var img = snapshot.data.query.pages.values.toList()[index].thumbnail.source;
return Container(
child: Card(
child: GestureDetector(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => Detailpage(
snapshot.data.query.pages.values.toList()[index].title,
),
));
},
child: ListTile(
contentPadding: EdgeInsets.symmetric(
horizontal: 8.0, vertical: 8.0),
leading: Container(
padding: EdgeInsets.only(right: 10.0),
decoration: new BoxDecoration(
border: new Border(
right: new BorderSide(
width: 1.5, color: Colors.grey)),
),
child: img == img.isEmpty
? SizedBox(height: 50.0,width: 50.0,child: Image.asset('images/ayurwiki.png'),)
:SizedBox(
height: 50.0,
width: 50.0,
child: FadeInImage.assetNetwork(
placeholder: 'images.png',
image: img,
fit: BoxFit.fill,
),
)
),
title: Text(
snapshot.data.query.pages.values.toList()[index].title),
),
)));
},
);
} else {
return Center(
child: CircularProgressIndicator(),
);
}
},
),
));
}
}
Herbslist.dart
class Herbslist {
String batchcomplete;
Continue herbslistContinue;
Limits limits;
Query query;
Herbslist({
this.batchcomplete,
this.herbslistContinue,
this.limits,
this.query,
});
factory Herbslist.fromJson(Map<String, dynamic> json) => Herbslist(
batchcomplete: json["batchcomplete"],
herbslistContinue: Continue.fromJson(json["continue"]),
limits: Limits.fromJson(json["limits"]),
query: Query.fromJson(json["query"]),
);
Map<String, dynamic> toJson() => {
"batchcomplete": batchcomplete,
"continue": herbslistContinue.toJson(),
"limits": limits.toJson(),
"query": query.toJson(),
};
}
class Continue {
String gcmcontinue;
String continueContinue;
Continue({
this.gcmcontinue,
this.continueContinue,
});
factory Continue.fromJson(Map<String, dynamic> json) => Continue(
gcmcontinue: json["gcmcontinue"],
continueContinue: json["continue"],
);
Map<String, dynamic> toJson() => {
"gcmcontinue": gcmcontinue,
"continue": continueContinue,
};
}
class Limits {
int categorymembers;
int pageimages;
Limits({
this.categorymembers,
this.pageimages,
});
factory Limits.fromJson(Map<String, dynamic> json) => Limits(
categorymembers: json["categorymembers"],
pageimages: json["pageimages"],
);
Map<String, dynamic> toJson() => {
"categorymembers": categorymembers,
"pageimages": pageimages,
};
}
class Query {
Map<String, Page> pages;
Query({
this.pages,
});
factory Query.fromJson(Map<String, dynamic> json) => Query(
pages: Map.from(json["pages"]).map((k, v) => MapEntry<String, Page>(k, Page.fromJson(v))),
);
Map<String, dynamic> toJson() => {
"pages": Map.from(pages).map((k, v) => MapEntry<String, dynamic>(k, v.toJson())),
};
}
class Page {
int pageid;
int ns;
String title;
Thumbnail thumbnail;
String pageimage;
Page({
this.pageid,
this.ns,
this.title,
this.thumbnail,
this.pageimage,
});
factory Page.fromJson(Map<String, dynamic> json) => Page(
pageid: json["pageid"],
ns: json["ns"],
title: json["title"],
thumbnail: json["thumbnail"] == null ? Thumbnail(source:'',width:0,height:0) : Thumbnail.fromJson(json["thumbnail"]),
pageimage: json["pageimage"] == null ? null : json["pageimage"],
);
Map<String, dynamic> toJson() => {
"pageid": pageid,
"ns": ns,
"title": title,
"thumbnail": thumbnail == null ? null : thumbnail.toJson(),
"pageimage": pageimage == null ? null : pageimage,
};
}
class Thumbnail {
String source;
int width;
int height;
Thumbnail({
this.source,
this.width,
this.height,
});
factory Thumbnail.fromJson(Map<String, dynamic> json) => Thumbnail(
source: json["source"],
width: json["width"],
height: json["height"],
);
Map<String, dynamic> toJson() => {
"source": source,
"width": width,
"height": height,
};
}
A: You are overriding the list you have. You need to append new data into your list.
Your logic should be like this:
// Declare a list
List<Herbslist> herbslist = [];
// Update the list
herblist.add(Herbslist.fromJson(json.decode(response.body)));
// Return the updated list
return herblist;
Without further information about your Herblist class, I can't guarantee that this would work. You probably need to flat you List of Lists.
Update
Your data structure seems unconvinient for this situation. There are better ways to structure your data and respresent it on the UI. You wrapped iterable data into a class and whenever you get new instance from that class you end up with having two different data stores. Since you pass the newest instance to the UI, only the latest results will show up on the list.
You should have a single data store (eg. a list or map for your API results) and append new data into it. You only have model classes now. They should declare how is your data structured. They shouldn't store any real data.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/59499627",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: WPF white screen rendering issue I am taking over a legacy WPF app.
What I have noticed that occasionally it will display with a white screen when launched. This does not happen all the time. Only when I move the mouse over the screen do I start seeing sections of the UI drawn. I never get the whole UI drawn and have to restart the app.
We are on windows 8.1 and .net 4.5
Sorry for the minimum amount of information but an clues on where to look would be great.
A: Without actually knowing what the code is doing it looks like the WPF rendering thread is not catching up, I would suggest you try a few things:
*
*Try this on different machines / graphics cards and see if the same behavior is happening
*Can you check is your CPU is doing extensive work?
*Check if your memory is constantly increasing?
*Profile the application (garbage collections, generations sizes, etc)
However, best is to start looking at the code this might just be a bug that messes up the UI.
See some troubleshooting tips here
Graphics card troublehooting
Windows Presentation Foundation (WPF) differs from prior application platforms on Windows in that it uses its own DirectX-based hardware-accelerated rendering pipeline, when available, to draw the contents of any WPF windows.Prior application platforms were typically much less dependent on display driver quality because the bulk of their rendering was done in software rather than hardware. As a result, the visual quality of WPF applications is heavily dependent on the quality of the system’s display device and its display drivers. Faulty display devices may cause drawing artifacts within WPF applications or elsewhere on the desktop when an application uses the WPF hardware-rendering pipeline.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/40310645",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: RTCDataChannel's ReadyState is not 'open' I'm trying to send text over an RTCPeerConnection with RTCDataChannel using WebRTC's adapter.js, but I'm getting the following error:
Uncaught InvalidStateError:
Failed to execute 'send' on 'RTCDataChannel':
RTCDataChannel.readyState is not 'open'
My code is available via this fiddle and below:
var peerConnection = new RTCPeerConnection(null, {
optional: [{
RtpDataChannels: true
}]
});
peerConnection.ondatachannel = function(event) {
receiveChannel = event.channel;
receiveChannel.onmessage = function(event){
alert(event.data);
};
};
var dataChannel = peerConnection.createDataChannel("data", {reliable: false});
dataChannel.send("Hello");
Am I doing anything wrong?
A: You can't just create peerConnection, dataChannel and start using it right away.
And btw you don't have 2 peers here...
*
*You'll need to create peerConnections object in the 2 peers
*Transfer SDP's
*get ice candidates
*and only after that the dataChannel is open and then you can send information on top of it
I suggest start by reading this, it will give you knowledge of the basic concepts
And then continue to this awesome code lab by Sam Dutton.
Update to answer mhenry's request:
Here's the entirety of setting up data channel in one class: https://gist.github.com/shacharz/9661930
Follow the comments, you'll just need to:
*
*Add signaling, sending SDP's ice candidates to the other peer (targetId)
*If you'de like to handle all the connection lost and stuff like that by a higher level logic.
*Make sure that when receiving an sdp you call the "Handlmessage" method
*Use the class with its public methods: SetupCall, Send, Close
A: I wrote the following code this morning that uses RTCPeerConnection and RTCDataChannel in a single page. The order in which these functions are declared is important.
var localPeerConnection, remotePeerConnection, sendChannel, receiveChannel;
localPeerConnection = new RTCPeerConnection(null, {
optional: [{
RtpDataChannels: true
}]
});
localPeerConnection.onicecandidate = function(event) {
if (event.candidate) {
remotePeerConnection.addIceCandidate(event.candidate);
}
};
sendChannel = localPeerConnection.createDataChannel("CHANNEL_NAME", {
reliable: false
});
sendChannel.onopen = function(event) {
var readyState = sendChannel.readyState;
if (readyState == "open") {
sendChannel.send("Hello");
}
};
remotePeerConnection = new RTCPeerConnection(null, {
optional: [{
RtpDataChannels: true
}]
});
remotePeerConnection.onicecandidate = function(event) {
if (event.candidate) {
localPeerConnection.addIceCandidate(event.candidate);
}
};
remotePeerConnection.ondatachannel = function(event) {
receiveChannel = event.channel;
receiveChannel.onmessage = function(event) {
alert(event.data);
};
};
localPeerConnection.createOffer(function(desc) {
localPeerConnection.setLocalDescription(desc);
remotePeerConnection.setRemoteDescription(desc);
remotePeerConnection.createAnswer(function(desc) {
remotePeerConnection.setLocalDescription(desc);
localPeerConnection.setRemoteDescription(desc);
});
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/22470291",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
}
|
Q: IIS 7 how to customize the security model using c# We have migrated a legacy streaming server to Wowza. As well as streaming on that server we need to have some mobile handsets have their delivery of mp4 files to be handled by IIS (7) HTTP straight download.
I need to replicate the security model that we had before based on our own key within the url parameters. (This I have done in Wowza also now). Nothing built-in in IIS would match our needs. So what I need to do is create a plugin for IIS that can see the URL of all incoming requests and either accept or deny them.
Can anyone point me into the right direction as to the API / plugin I should be interested in?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/29364915",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: can sessions variables be altered by the user in their browser I'm trying to learn more on sessions and I was wondering if checking if a specific session is set is enough to prevent a user from accessing a webpage without having logged in first
example:
if(!isset($_SESSION['jfn7^j3#$jnj;7gs!~']))
{
header('location:abc.php');
}
or is there a way this can be bypassed
And secondly if I initialize a session variable once a user has successfully logged in
example:
$_SESSION['username']='MAX';
Is there a way the user can change the value of the set $_SESSION['username'] on their browser
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/63624450",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Reading Json with C# via HTTP Request I have a problem reading json from our local API.
This is a well known public json side which I also used for testing: https://jsonplaceholder.typicode.com/todos
This is my Json on my local API:
In C# I tried this:
HttpClient client = new HttpClient();
string httpResponse = "";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(testurl);
WebResponse responseinger = null;
StreamReader reader = null;
static async Task Main(string[] args)
{
Program p = new Program();
await p.Get();
}
public async Task Get()
{
string response = await client.GetStringAsync("https://jsonplaceholder.typicode.com/todos");
Console.WriteLine(response);
Console.WriteLine();
string response2 = await client.GetStringAsync(testurl);
Console.WriteLine(response2);
Console.WriteLine();
string json = JsonConvert.SerializeObject(response2);
Console.WriteLine(json);
Console.WriteLine();
try
{
responseinger = request.GetResponse();
}
catch (WebException ex)
{
responseinger = ex.Response;
}
reader = new StreamReader(responseinger.GetResponseStream());
httpResponse = reader.ReadToEnd();
Console.WriteLine(reader);
Console.WriteLine();
Console.WriteLine(httpResponse);
Console.WriteLine();
using (WebClient wc = new WebClient())
{
var jsonwc = wc.DownloadString(testurl);
Console.WriteLine(jsonwc);
Console.WriteLine();
}
}
So I used different methods to get my json.
The json from the public json side works but my local not.
This is my output in the Console:
What can I do about it? Thanks in Advance!
A: Try adding your accept header
var req = WebRequest.CreateHttp(uri);
req.Headers.Add(HttpRequestHeader.Accept, "application/ json");
req.Method = "Get";
A: SOLUTION:
My problem was gzip it compressed my json.
using (WebClient wc = new WebClient())
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(testurl);
req.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
responseinger = req.GetResponse();
reader = new StreamReader(responseinger.GetResponseStream());
httpResponse = reader.ReadToEnd();
//Console.WriteLine(reader);
//Console.WriteLine();
Console.WriteLine(httpResponse);
Console.WriteLine();
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/69850517",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Adding the combo box drop down list value to the new rows Hi i know it might sound easy but since i am new to VBA thus i need some help in adjusting the user form vba codes below for the combo box drop down list value to be inserted in the new rows. Currently i have an add command button that will add all the input on the userform to the new rows found. The current problem i am facing now is the adjustment i need to made for the comboBox line ".Text" in the add command button for it to run smoothly. Below the the code that i have and i have commented on the line where i am facing a problem right now.
Private Sub CommandAddButton1_Click()
Dim sh As Worksheet: Set sh = ThisWorkbook.Sheets("Program Status Summary")
Dim emptyRow As Integer: emptyRow = 1 + sh.UsedRange.Find(ComboBoxProjSizes.Text).End(xlDown).Row
With sh
.Cells(emptyRow, "A").Value = 1 + Application.Max(.Columns(1)) ' to generate a new identifier in column 1
.Cells(emptyRow, "B").Value = TextBoxProjCode.Text
.Cells(emptyRow, "C").Value = TextBoxProjName.Text
.Cells(emptyRow, "D").Value = TextBoxSector.Text
.Cells(emptyRow, "E").Value = TextBoxObjective.Text
.Cells(emptyRow, "H").Value = TextBoxProjSponsor.Text
.Cells(emptyRow, "G").Value = TextBoxProjSponsorNew.Text
.Cells(emptyRow, "F").Value = TextBoxProjM.Text
.Cells(emptyRow, "T").Value = TextBoxRegulatory.Text
.Cells(emptyRow, "N").Value = TextBoxRiskLvl.Text
.Cells(emptyRow, "M").Value = TextBoxDatePar.Text
.Cells(emptyRow, "J").Value = TextBoxCostPar.Text
.Cells(emptyRow, "O").Value = TextBoxAffectCust.Text
.Cells(emptyRow, "Q").Value = TextBoxCustNonRetail.Text
.Cells(emptyRow, "P").Value = TextBoxCustRetail.Text
.Cells(emptyRow, "S").Value = TextBoxOutsourcingImp.Text
.Cells(emptyRow, "R").Value = TextBoxKeyStatus.Text
.Cells(emptyRow, "K").Value = TextBoxSchStart.Text
.Cells(emptyRow, "L").Value = TextBoxSchEnd.Text
.Cells(emptyRow, "V").Value = ComboBoxRagSchedule.Text 'Not Sure what to change the word ".Text" to so that the value in the comboBox would appear in the cell'
.Cells(emptyRow, "U").Value = ComboBoxRagFinancial.Text'Not sure what to change the word ".Text" to so that the value in the comboBox would appear in the cell'
.Cells(emptyRow, "W").Value = ComboBoxRagBenefit.Text'Not sure what to change the word ".Text" to so that the value in the comboBox would appear in the cells )
.Cells(emptyRow, "I").Value = TextBoxCost.Text
.Rows(emptyRow + 1).Insert
End With
Unload AddProject
End Sub
Any help is much appreciated. Thank you :)
A: Instead of .Text, try .Value, should insert current selected value to the cell, after running the macro. You can read some more about this here.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/33008742",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Can someone explain how this works please? JLabel label = new JLabel("Underlined Label");
Font font = label.getFont();
Map attributes = font.getAttributes();
attributes.put(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON);
label.setFont(font.deriveFont(attributes));
I have seen this code at least 100+ times today and i have tried it 100+ times and every single time it does not work. I am trying to underline text in a JLabel and this is the only block of code that i have found at all, and everyone else on stackoverflow seems to understand this, except me??? Is Map a class?
A: So, according to your question and comments, you have code somewhere that creates a JLabel named topCaption, adds it to a JPanel called viewWindow, and you can see the label as a results.
So somewhere you have:
JLabel topCaption = new JLabel( you may have some stuff here );
Right after that, do this:
Font font = topCaption.getFont();
Map attributes = font.getAttributes();
attributes.put(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON);
topCaption.setFont(font.deriveFont(attributes));
Also, I might suggest you need to do more reading before you continue with this, as knowledge of what a Map is, etc. is pretty basic to most UI programming, and you're going to continue to have trouble like this without some fundamentals under your belt.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/36525106",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Processing Payment with PayPay after authorizing with Apple Pay I have a shopping cart that currently uses a PayPal NVP to accept credit cards as well as checkout with PayPal accounts.
I've integrated Apple Pay, and am now on to actually processing the payment after Apple has validated the transaction. How do I use the payment data/tokens with PayPal to actually capture the funds and process the purchase?
I keep seeing a lot of references to Braintree, but thats a whole separate product, similar looking to Stripe.
Thank you for the help!
A: Looks like it's only available through BrainTree; confirmed by PayPal customer support.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/45601644",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How can I stop my program from generating the same key? I writing a password generator and I ran into this annoying issue, and it is the repeating a a number or letter on the same line. The user gives the program a format on how they want their password to be generated ex "C@@d%%%"
where @ is only letters and where % is only numbers, and the user also inputs the numbers and letters to generate the password, then the program is suppose to print out something like cold123, but instead it prints out cood111 or clld111, I will post a snippet of my code below, but please don't bad mouth it, I'm fairly new to python, self-taught and just about couple of months into the python experience.
class G()
.
.
.
# self.forms is the format the user input they can input things such as C@@d%%%
# where @ is only letters and where % is only numbers
# self.Bank is a list where generated things go
AlphaB = [] #list Of All Of The Positions That have The @ sign in The self.forms
NumB = [] #list of All of the positions that have a % sign
for char in self.forms:
if char == '@':
EOL=(self.Position) # Positions End Of Line
Loc = self.forms[EOL] # Letter
AlphaB.append(EOL)
if char == '%':
EOL=(self.Position)
Loc = self.forms[EOL]
NumB.append(EOL)
self.Position+=1 # Move right a position
for pos in AlphaB:
for letter in self.alphas: #letters in The User Inputs
GenPass=(self.forms.replace(self.forms[pos],letter))
#Not Fully Formatted yet, because Only The letter been formatted
if GenPass.find('%'):
for Pos in NumB:
for number in self.ints:
GenPass=(GenPass.replace(GenPass[Pos],number))
if GenPass not in self.Bank:
#Cood111
print (GenPass)
self.Bank.append(GenPass)
else:
if GenPass not in self.Bank:
print (GenPass)
self.Bank.append(GenPass)
A: GenPass.replace(GenPass[Pos],number) will replace every occurrence of the character at GenPass[Pos] with the value of number. You need to make sure you replace one character at a time.
A: Create a list of all chars and a list with all nums, then just pick one by using list.pop(randint(0, len(list) - 1), you will always pick a different letter / number like this but you will also be limited to 10 digits (0-9) and 20-something letters.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/38639395",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Find user location with mapbox and Nativescript To be honest I still have some difficulty to understand how to call the native IOS api with Nativescript. I've read some brief tutorials on how to build a plugin for Nativescript, but I guess a bit of knowledge with Objective-C or Android is required.
I would like to center the map to the user location using the EddyVerbruggen/nativescript-mapbox plugin and because I can't find any method that return the user coordinates, I'm trying to mimic the structure of this plugin to add a new method:
on mapbox.d.ts
export function findUserPosition(): Promise<any>;
on mapbox.ios.js
mapbox.findUserPosition = function(){
return new Promise(function (resolve, reject) {
try {
console.log('trying to get the user location.....')
mapbox.mapView.userLocation = MGLUserLocation.location;
console.dir(mapbox.mapView.userLocation)
resolve();
} catch (ex) {
console.log("Error in mapbox.findUserLocation: " + ex);
reject(ex);
}
});
};
on map-view-model.js
DemoAppModel.prototype.findUserPosition = function(){
mapbox.findUserPosition().then(function(result){
console.log(result)
},function(error){
console.log(error)
})
};
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/38763178",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: the Default 'List' constructor isn't available when null safety enabled i have an error when i write the code
heres the code i wrote
class ProgressHUD extends StatelessWidget {
final Widget child;
final bool inAsyncCall;
final double opacity;
final Color color;
final Animation<Color> valueColor;
ProgressHUD({
required Key key,
required this.child,
required this.inAsyncCall,
this.opacity = 0.3,
this.color = Colors.grey,
required this.valueColor,
}) : super(key: key);
@override
Widget build(BuildContext context) {
List<Widget> widgetList = new List<Widget>();
widgetList.add(child);
if (inAsyncCall) {
final model = new Stack(
children: [
new Opacity(
opacity: opacity,
child: ModalBarrier(dismissible: false, color: color),
),
new Center(
child: new CircularProgressIndicator()
),
],
);
return Stack(children: widgetList,);
}
}
}
The error message that appear is on Build says The body might complete normally, causing 'null' to be returned, but the return type is a potentially non-nullable type.
Then the Second error is in List says 'list' is deprecated and shouldnt be used
can someone help me to fix it thanks before
A: List<Widget> widgetList = new List<Widget>();
widgetList.add(child);
needs to be
final widgetList = [child];
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/68341630",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: what is the procedure of registering the webhook for twitter? I am trying to register url as webhook on twitter through the curl command given in the twitter documentation. I think twitter documentation is a bit outdated or incorrect.
curl --request POST --url "https://api.twitter.com/1.1/account_activity/all/prod/webhooks.json?url=https%3A%2F%2FXXXX.com%2Fwebhook%2Ftwitter" --header "authorization: OAuth oauth_consumer_key='XXXXXXXXXXXXXXXXXXXXXX', oauth_nonce='ODgyNjc5NjQ0MTM3NzI4NTcwMjY4NDQ0', oauth_signature='7daMyzB1JClE4xv8hXNCimWpGtA%3D', oauth_signature_method='HMAC-SHA1', oauth_timestamp='1568620293', oauth_token='XXXXXXXXXXXXXXXXXXXXX', oauth_version='1.0'"
after running this code, I am getting error as
{"errors":[{"code":215,"message":"Bad Authentication data."}]}
the codes that i have used to generate timestamp, oauth_nonce, oauth_signature is given below. These codes are in python3. I am not very sure whether they are giving the correct output or not.
oauth_timestamp = str(int(time.time()))
#oauth_nonce
def get_nonce():
nonce = ''.join(random.choice(string.ascii_uppercase + string.ascii_lowercase + string.digits)for x in range(32))
return nonce
#oauth_signature
def escape(s):
"""Percent Encode the passed in string"""
return urllib.parse.quote_plus(s, safe='~')
def create_auth_header(parameters):
"""For all collected parameters, order them and create auth header"""
ordered_parameters = {}
ordered_parameters = collections.OrderedDict(sorted(parameters.items()))
auth_header = (
'%s="%s"' % (k, v) for k, v in ordered_parameters.items())
val = "OAuth " + ', '.join(auth_header)
return val
def generate_signature(method, url, url_parameters, oauth_parameters, oauth_consumer_key, oauth_consumer_secret, oauth_token_secret=None, status=None):
"""Create the signature base string"""
#Combine parameters into one hash
temp = collect_parameters(oauth_parameters, status, url_parameters)
#Create string of combined url and oauth parameters
parameter_string = stringify_parameters(temp)
#Create your Signature Base String
signature_base_string = (
method.upper() + '&' +
escape(str(url)) + '&' +
escape(parameter_string)
)
#Get the signing key
signing_key = create_signing_key(oauth_consumer_secret, oauth_token_secret)
return calculate_signature(signing_key, signature_base_string)
def stringify_parameters(parameters):
"""Orders parameters, and generates string representation of parameters"""
output = ''
ordered_parameters = {}
ordered_parameters = collections.OrderedDict(sorted(parameters.items()))
counter = 1
for k, v in ordered_parameters.items():
output += escape(str(k)) + '=' + escape(str(v))
if counter < len(ordered_parameters):
output += '&'
counter += 1
return output
def collect_parameters(oauth_parameters, status, url_parameters):
"""Combines oauth, url and status parameters"""
#Add the oauth_parameters to temp hash
temp = oauth_parameters.copy()
#Add the status, if passed in. Used for posting a new tweet
if status is not None:
temp['status'] = status
#Add the url_parameters to the temp hash
for k, v in url_parameters.items():
temp[k] = v
return temp
def calculate_signature(signing_key, signature_base_string):
"""Calculate the signature using SHA1"""
hashed = hmac.new(signing_key, signature_base_string.encode('utf-8'), hashlib.sha1)
sig = binascii.b2a_base64(hashed.digest())[:-1]
return escape(sig)
def create_signing_key(oauth_consumer_secret, oauth_token_secret):
"""Create key to sign request with"""
signing_key = escape(oauth_consumer_secret) + '&'
signing_key += escape(oauth_token_secret)
return signing_key.encode('utf-8')
oauth_parameters = {
'oauth_timestamp': str(int(time.time())),
'oauth_signature_method': "HMAC-SHA1",
'oauth_version': "1.0",
'oauth_token': "vvvvvvvvvvvvvvv",
'oauth_nonce': get_nonce(),
'oauth_consumer_key': 'bbbbbbbbbbbbbbb'
}
oauth_parameters['oauth_signature'] = generate_signature(
method,
url,
url_parameters, oauth_parameters,
consumer_key,
consumer_secret,
access_token_secret
)
auth_headers = {'Authorization': create_auth_header(oauth_parameters),
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
}
auth_data = {
'grant_type': 'client_credentials'
}
webhook_endpoint ='https%3A%2F%2Fmy-site.com%2Fwebhook%2Ftwitter'
url = 'https://api.twitter.com/1.1/account_activity/all/env/webhooks.json?url={}'.format(webhook_endpoint)
method = "post"
url_parameters = {
'exclude_replies': 'true'
}
r = requests.post(url, headers=auth_headers, data=auth_data)
Kindly tell me which code is incorrect or am i doing something wrong? If you can write the code below in the answer, it would be beneficial.
A: Ok, so i was finally able to register my webhook, following are the steps that i followed
1) first i installed ruby with the help rbenv
2) then i installed twurl using
gem install twurl
3) now authorize your app by using the following command
twurl authorize --consumer-key key --consumer-secret secret
4) After running the above command on the command prompt you will get output as
Go to https://api.twitter.com/oauth/authorize?oauth_consumer_key=xxxxxxxxxxxxx&oauth_nonce=xxxxxxxxxxx&oauth_signature=xxxxxxxxxxxx&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1568986465&oauth_token=xxxxxxx&oauth_version=1.0 and paste in the supplied PIN
5) Just go to the url , twitter page will open with a pin like 9876506 ,just copy the pin and paste in the command line.
6)Then you will get an output of authorization successful in your cmd.
7) Now you have authorized your app.
8) Now before registering the webhook, your call back url that you have given in the details section of your twitter app, should generate a crc token.
9) If your domain is "www.my_domain.com" create an endpoint as "www.my_domain.com/webhook/twitter" and add the following code to generate crc in your web application.
def twitterCrcValidation():
crc = request.args['crc_token']
validation = hmac.new(key=bytes(CONSUMER_SECRET, 'utf-8'),msg=bytes(crc, 'utf-8'),
digestmod = hashlib.sha256
)
digested = base64.b64encode(validation.digest())
response = {
'response_code':200,
'response_token': 'sha256=' + format(str(digested)[2:-1])
}
print('responding to CRC call')
return json.dumps(response)
10) Now run the following command to register the webhook, in place of put the name of your environment e.g "prod"
twurl -X POST "/1.1/account_activity/all/<environment>/webhooks.json?url=https://www.my_domain.com/webhooks/twitter"
11) After this you will get a json response as the following
{"id":"1174326336837472256",
"url":"https://www.my_domain.com/webhooks/twitter",
"valid":true,
"created_timestamp":"2019-09-18 14:16:31 +0000"
}
12) Finally your url is registered as webhook.
P.S ----Twitter sends crc token to your endpoint in every 24 hours to check whether the url endpoint is alive or not. So your server containing the url endpoint should be in running condition. I deployed my flask app containing the url endpoint on heroku server. So heruko provides you a free server with a single url unlike ngrok. In ngrok you get a new url whenever you run the server, which is not required for twitter. But heroku server sleeps in every 10 minutes if you do not refresh the website.
So twitter might have run the crc check on my site and my site was in sleeping condition due to heroku's policy and my webhook id became invalid.
You can make your webhook id valid again by running the following command given.
twurl -X PUT "/1.1/account_activity/all/prod/webhooks/11743xxxxxxxxxx6.json"
then you can get the info about your webhook by running the following command
twurl -X GET "/1.1/account_activity/all/webhooks.json" --header authorization:bearer token
A: Someone should pay you a beer for this reply. Twitter makes things insanely complicated, LOL.
Thanks, it works perfectly.
Just a reminder, the env comes from https://developer.twitter.com/en/account/environments. So make sure to create something there in order to put in the POST url.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/57953470",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Postgres 9.0 File System level backup on Debian Jessie I'm on Debian 8.2.0 and trying to run a postgres server from a folder I received. Version is 9.0.18. Here is the command I issue:
./postgres -D /home/swapps/project/PostgreSQL/9.0/data/
but the cursor keeps blinking in the terminal. I'm not sure what is happening?
Thanks
A: Sounds like it's started, and log_min_messages is set to a high enough value that you don't see any output.
Using another terminal session connect to the server on the port it's running on. If you don't know that check the port value in the postgresql.conf inside the data directory.
Generally you should use pg_ctl -D blah -w start rather than postgres directly. See the manual.
Or, for long term use, set it up to run on startup via an init script.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/33613648",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Djongo search error string with parentheses I'm working on a website using Django template and MongoDB.
I implemented a search but some items have parentheses in their fields. When I use contains or icontains function to search in the database, it throw me an error or doesnt find the item.
For example, if I search
"Test (test"
it will throw a regular expression missing error.
If I search
"Test (test)"
It won't find anything
I manage to find that parentheses are not considered as string for mongo. I tried to escape parentheses with \ ( and \\ ) but it doesn't work.
I don't know what I can do.
A: @Lop Castro, I would suggest you use regex in your case. You can check the documentation of Django how to use regex with ORM.
https://docs.djangoproject.com/en/dev/ref/models/querysets/#regex
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/62713346",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Rails - Change Image Directory? I've developed a simple app to display images in a series of subdirectories based on querystring input. (I more or less built my own Rails version of 360Works SuperContainer, for FileMaker.) I have copied a few test directories into public/images and everything seems to be working just great, but this app needs to operate over upwards of 60gb of images, and putting them all into the public/images folder isn't going to really be feasible.
Other than hard-coding the path into my model, how can I set a configuration option to specify a different default directory for the images folder?
A: I think you can change the asset_host field :
http://api.rubyonrails.org/classes/ActionView/Helpers/AssetTagHelper.html#M001688
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/5979200",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: ASP.Net Website Routing I have an ASP.NET website in framework 4.0
This website contains a subvirtual directory say directory1.
I want to add routing like when I type in browser
www.mydomain.com/funds it will get contents from www.mydomain.com/directory1
Example 2
**www.mydomain.com/funds/page1**
it will get contents from
**www.mydomain.com/directory1/page1**
URL in browser should remain **www.mydomain.com/funds/page1**
I have added reference of System.Web.Routing for this purpose. Initially tried with routes.MapPageRoute but there are no physical pages as directory1 is an wordpress website.
Any suggestions will be appreciated
Thank you
A: You may try URL Rewrite if you're using IIS for hosting website.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/41114149",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Accessing Websphere MQ from a Notes Java agent I want to access (Websphere) MQ via a Notes Java agent. The inspiration for my initial code I got from this article: https://www.ibm.com/developerworks/lotus/library/domino-jms/
If I run my agent I get the 2009 message: "MQ queue manager closed channel immediately during connect Closure reason = 2009".
I have checked the connection via the MQ Explorer client and here I can access the channel and read messages.
I presume the connection via the Notes agent fails due to the fact it does not use the SSL key I got provided.
My question is how I should setup my Java agent, including the key file and use it in my code?
Anyone who can enlighten me? Thank you in advance!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/44301845",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to call API SignalR service from MVC application? How to call API SignalR service from MVC application?
client code : $.connection.hub.url = "http://localhost:PortNumber/signalr"
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/50268221",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How does log axis plot in python works? What formula does matplotlib.pyplot.yscale('log') use when plotting in log scale? For e.g. with
x=[1,2, 3]
y=[0.0088 , 0.0283 , 0.121 ]
plt.yscale('log')
plt.plot(x,y,linewidth=3, marker ='p', markersize=7)
plots the graph with y-axis values in the positive range of 0.001 to 1. But 10*math.log10(y) gives negative values as y < 0. So how does the matplotlib.pyplot.yscale('log') applies log?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72757161",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to use a tab widget in Android? Can anyone show me how to make a tab widget in Android?
A: There is a developer guide showing how to implement tabbed activities/fragments http://developer.android.com/guide/topics/ui/actionbar.html
It's very important to follow new solution, because the method using TabActivity is deprecated since API level 13.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/1117641",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Cheerio returns undefined when I try to retrieve JSON data I am trying to make a webscraber, and have succeded in downloading the html. With this code I now try to find the title of my html:
fs.readFile(__filename.json , function (err, data) {
if(err) throw err;
const $ = cheerio.load(data);
const urlElemt = $('article.product-tile');
if(urlElemt){
console.log("Found " + urlElemt.length + " elements");
let urlTitle = $(urlElemt.find("h2.product-tile__title"));
let urlPrice = $(urlElemt.find("span.__price"));
for(let i = 0; i < 1; i++) {
console.log(Title[i].children)
}
}
When I just console.log the children of the object I get:
[ { type: 'text',
data: 'Tuborg Grøn Pilsner Øl 4,6%',
parent:
{ type: 'tag',
name: 'h2',
namespace: 'http://www.w3.org/1999/xhtml',
attribs: [Object],
'x-attribsNamespace': [Object],
'x-attribsPrefix': [Object],
children: [Circular],
parent: [Object],
prev: [Object],
next: [Object] },
prev: null,
next: null } ]
where data: 'Tuborg Grøn Pilsner Øl 4,6%',
is the data I want to retrieve.
I have tried using both
console.log(Title[i].children["data"])
and
console.log(Title[i].children.data)
but I always get "undefined" as a result, what have I misunderstood and/or been doing wrong?
A: In your
const urlElemt = $('article.product-tile')
...
let urlTitle = $(urlElemt.find("h2.product-tile__title"))
find() function already returns a Cheerio object, hence you don't need to pass it to $ function. This will suffice:
let urlTitle = urlElemt.find("h2.product-tile__title")
thus you can do
console.log(urlTitle.text())
or
console.log(urlTitle.html())
to see the serialized versions of the dom nodes, which in your case should be a plain text string. (see the api docs)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/55089487",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: SQL query taking longer time to execute I'm trying to execute the query. It take 32 min to execute. I have tried NOLOCK but only optimized it with 3 min.
the query is given below:-
SELECT PO.payday, PO.facility, PO.department, PO.workcenter, PO.shift, PO.team, PO.orderno, PO.fg_productno,
PO.sfg_productno, NoCarton = '1', NoPack = 5, NoCigarette = PO.nocigarette, VNC.sampleid, VNC.comment,
VNC.createdby, SampleDateTime = dbo.AF_GetUTCToLocal(VNC.UTCStartDate),
SampleTime = Cast(CONVERT(CHAR(10), VNC.utcstartdate, 101) AS DATETIME), VNC.ncgroup, VNC.productcomponent,
VNC.nc, VNC.ncname, VNC.weightingfactor, VNC.ConsumerSensitive, VNC.[lowunits], VNC.[low %], VNC.[highunits],
VNC.[high %], VNC.vqi, VNC.deepcontrol,
--Modification done for CHE10045964
PO.ResourceClassName
FROM
(SELECT PayDay = WCS.payday, Facility = R.facility, Department = R.department, WorkCenter = R.workcenter,
Shift = WCS.workperiod, Team = SD.teamid, OrderNo = WO.orderno,
FG_ProductNo = P.productno + Isnull('.' + P.productrevision, ''),
SFG_ProductNo = CASE
WHEN UCHSC.attribute_ != P.productno
THEN UCHSC.attribute_
ELSE NULL
END,
WO.actualstartdate, WO.actualcompletiondate,
NoCigarette = dbo.Af_getunitcharacteristicattribute(OD.unitid,'ZPPPI_ITEM_PACK') ,
RC.Name as ResourceClassName
FROM order_header OH
INNER JOIN dbo.wip_order WO ON OH.orderno = WO.orderno
INNER JOIN dbo.order_detail OD ON OD.orderno = WO.orderno
INNER JOIN dbo. product P ON WO.productid = P.id
INNER JOIN dbo.resource_ R ON R.resourcename = WO.resourcename AND R.resourcetype = WO.resourcetype
Inner Join dbo.Resource_Class RC ON R.ResourceClassID = RC.ID
INNER JOIN dbo.work_center_work_schedule WCS ON WO.oawipentityid = WCS.id
INNER JOIN at_work_center_work_schedule_detail SD ON WCS.id = SD.workcenterworkscheduleid
LEFT JOIN dbo.unit_characteristic UCHSC ON UCHSC.unitid = OD.unitid
AND UCHSC.characteristic = 'ZPPPI_SPA_CIGARETTE'
WHERE OH.ordertype = 23
GROUP BY WCS.payday, R.facility, R.department, R.workcenter, WCS.workperiod, SD.teamid,
WO.orderno, P.productno + Isnull('.' + P.productrevision, ''),
CASE
WHEN UCHSC.attribute_ != P.productno THEN UCHSC.attribute_
ELSE NULL
END,
WO.actualstartdate, WO.actualcompletiondate,
dbo.Af_getunitcharacteristicattribute(OD.unitid,'ZPPPI_ITEM_PACK'),
RC.Name
) PO INNER JOIN
(
SELECT NC.orderno, NC.sampleid, NC.comment, NC.deepcontrol, NC.createdby, NC.utcstartdate, NC.ncgroup, NC.productcomponent,
NC.nc, NC.ncname, NC.weightingfactor, NC.ConsumerSensitive, NC.[lowunits], NC.[low %], NC.[highunits], NC.[high %],
VQI = Round(NC.weightingfactor * ( Log (1 + [low %] / 3.0 + [high %]) ), 0),
--Added By Sukanya Biswas(CHE10045964)
NC.WorkCenter
FROM (SELECT orderno, b.sampleid, b.comment, b.deepcontrol, b.utcstartdate, b.ncgroup, b.productcomponent,
b.nc, b.ncname, b.weightingfactor, b.ConsumerSensitive, b.createdby,
[LowUnits] = Isnull(b.[1], 0),
[Low %] = CASE CONVERT(NVARCHAR(1),b.deepcontrol) + b.ncgroup
WHEN '0Bundle' THEN CASE WHEN (Isnull(b.[1], 0) * 100) > 100 THEN 100 ELSE Isnull(b.[1], 0) * 100 END
WHEN '1Bundle' THEN CASE WHEN (Isnull(b.[1], 0) * 100) > 100 THEN 100 ELSE Isnull(b.[1], 0) * 100 END
WHEN '0Pack' THEN CASE WHEN (Isnull(b.[1], 0) * NoofCigarette ) > 100 THEN 100 ELSE Isnull(b.[1], 0) * NoofCigarette END
WHEN '1Pack' THEN CASE WHEN (Isnull(b.[1], 0) * NoofCigarette ) > 100 THEN 100 ELSE Isnull(b.[1], 0) * NoofCigarette END
WHEN '0Cigarette' THEN CASE WHEN (Isnull(b.[1], 0) * 5 ) > 100 THEN 100 ELSE Isnull(b.[1], 0) * 5 END
WHEN '1Cigarette' THEN CASE WHEN (Isnull(b.[1], 0) * 1 ) > 100 THEN 100 ELSE Isnull(b.[1], 0) * 1 END
WHEN '0Filter' THEN CASE WHEN (Isnull(b.[1], 0) * 10 ) > 100 THEN 100 ELSE Isnull(b.[1], 0) * 10 END
WHEN '1Filter' THEN CASE WHEN (Isnull(b.[1], 0) * 10 ) > 100 THEN 100 ELSE Isnull(b.[1], 0) * 10 END
ELSE Isnull(b.[1], 0)
END, [HighUnits] = Isnull(b.[2], 0),
[High %] = CASE CONVERT(NVARCHAR(1),b.deepcontrol) + b.ncgroup
WHEN '0Bundle' THEN CASE WHEN (Isnull(b.[2], 0) * 100) > 100 THEN 100 ELSE Isnull(b.[2], 0) * 100 END
WHEN '1Bundle' THEN CASE WHEN (Isnull(b.[2], 0) * 100) > 100 THEN 100 ELSE Isnull(b.[2], 0) * 100 END
WHEN '0Pack' THEN CASE WHEN (Isnull(b.[2], 0) * NoofCigarette ) > 100 THEN 100 ELSE Isnull(b.[2], 0) * NoofCigarette END
WHEN '1Pack' THEN CASE WHEN (Isnull(b.[2], 0) * NoofCigarette ) > 100 THEN 100 ELSE Isnull(b.[2], 0) * NoofCigarette END
WHEN '0Cigarette' THEN CASE WHEN (Isnull(b.[2], 0) * 5 ) > 100 THEN 100 ELSE Isnull(b.[2], 0) * 5 END
WHEN '1Cigarette' THEN CASE WHEN (Isnull(b.[2], 0) * 1 ) > 100 THEN 100 ELSE Isnull(b.[2], 0) * 1 END
WHEN '0Filter' THEN CASE WHEN (Isnull(b.[2], 0) * 10 ) > 100 THEN 100 ELSE Isnull(b.[2], 0) * 10 END
WHEN '1Filter' THEN CASE WHEN (Isnull(b.[2], 0) * 10 ) > 100 THEN 100 ELSE Isnull(b.[2], 0) * 10 END
ELSE Isnull(b.[2], 0)
END ,
--Added By Sukanya Biswas(CHE10045964)
B.WorkCenter
FROM (SELECT D .orderno, SampleID = DTS.id,
--Added By Sukanya Biswas(CHE10045964)
DL.WorkCenter,
Comment = CASE Isnull(DTS.comment_, '')
WHEN '' THEN 'N/A'
ELSE DTS.comment_
END, UTCStartDate = DTS.actualstartdate, NC.ncgroup, NC.productcomponent, NC.nc, NC.ncname,
NC.weightingfactor, NC.ConsumerSensitive,
Severity = Isnull(QD.qualitydefectseverityid, 0),
QD.noofdefects, DTS.createdby, DeepControl = DTS.overridesumresults,
NoofCigarette = dbo.Af_getunitcharacteristicattribute(OD.unitid,'ZPPPI_ITEM_PACK')
FROM dbo.disposition D
INNER JOIN dbo.disposition_line DL ON D .disposition = DL.disposition
--Inner Join dbo.Work_Center WC ON DL.Workcenter = WC.Workcenter
INNER JOIN dbo.disposition_test DT ON DT.disposition = D .disposition
AND DT.linesequenceno = DL.linesequenceno
INNER JOIN dbo.disposition_test_sample DTS ON DTS.dispositiontestid = DT.id
LEFT JOIN quality_defect QD ON QD.dispositiontestsampleid = DTS.id
INNER JOIN dbo.AV_RPT_VSI_Nonconformity NC ON Isnull(QD.defectreasoncode, '00.00.00') = NC.nc
LEFT JOIN ORDER_DETAIL OD ON OD.ORDERNO=D.ORDERNO
WHERE DL.linecode = 'VQ'
) A
PIVOT (Sum(a.noofdefects)
FOR severity IN ([1],[2]))
B)
NC
A: As per your query filter and columns needed, please make index on respected columns.
By default SQL will create clustered index on your primary key, but you may create some other unclustered index on your table to make your execution faster.
You may find this link for your reference or Google it there are hundreds of article available on Internet for same.
"https://learn.microsoft.com/en-us/sql/t-sql/statements/create-index-transact-sql?view=sql-server-2017"
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/56343179",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Conditional formatting in Tableau connected to Cube data Could someone help me to color these measures on 3 variations - less than 0, equal to 0 and greater than 0. I tried with a calculation
IF [Margin 1] > 0 THEN 1 ELSEIF [Margin 1] < 0 THEN 2 ELSEIF [Margin 1] = 0 THEN 3 END
The reason I have assigned numbers instead of string in the above calculation is, the data is from a cube which will not allow string to be mixed with IF conditon
This is only for Margin 1 while a similar one is also required for Margin 2 and Margin 3 as well. Once I put this calculation to color shelf it colored first value of Margin 1 correctly but at the same time even colors Margin 2 and Margin 3 as well with same shade.
Could someone help to nest color logic calculation for all three Margins so I can have control to choose less than, equal to and greater than 0 in different shades.
Attached is the image of data and tableau sheet of what I have arrived as of now, do let me know for any other details
A: Not sure how the fact the data is from cube makes much difference, inside of tableau you're looking at a integer and returning a string shouldn't matter.
If you want give this a try
create a calculated field like this:
ZN([Margin 1]) + ZN([Margin 2]) + ZN([Margin 3])
Then create your if statement based on the new calculated field returning string
If [NewCalculated field] <0 then
"Red"
If [NewCalculated field] 0 then
"Amber"
Else
"Green"
End
Have a go
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/50496210",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: masking the built-in variable with its magic behavior? I am not able to follow this statement in python tutorials:
This variable should be treated as read-only by the user. Don’t explicitly assign a value to it — you would create an independent local variable with the same name masking the built-in variable with its magic behavior.
A: In the interactive prompt, _ has "magic" behavior -- it gets set to the value of whatever expression was evaluated last:
>>> 3 + 3
6
>>> _
6
If, however, you assign something to a variable named _ yourself, then you only "see" that variable, and the magic variable is hidden ("masked"):
>>> _ = 3
>>> 3 + 3
6
>>> _
3
This happens because your local variable _ is unrelated to the variable that has the magic behavior, it just happens to have the same name.
So don't do that, not in the interactive prompt anyway.
A: It means exactly what it says it means; you should not assign anything to the _ variable as that would hide the real magic variable:
>>> 1 + 1
2
>>> _
2
>>> _ = 'foo'
>>> 2 + 2
4
>>> _
'foo'
The magic _ variable stores the result of the last expression that was echoed, but by assigning to _ you no longer can 'see' this magic variable. Looking up _ shows whatever value I assigned to it now.
Luckily, you can also delete the shadowing _ name again:
>>> del _
>>> 2 + 2
4
>>> _
4
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/31662713",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How does one prevent MS Access from concatenating the schema and table names thereby taking them over the 64 character limit? I have been trying to get around this for several day's now with no luck. I loaded Libre Office to see how that would handle it, and its native support for PostgeSQL works wonderfully and I can see the true data structure. Which is how I found out I was dealing with more than one table. What I am seeing in MS Access is the two names concatenated together. The concatenation takes them over the 64 character limit that appears to be built into the ODBC driver. I have seen many references to modifying namedatalen on the server side, but my problem is on the ODBC side. Most of the tables are under the 64 character limit even with the concatenation and work fine. As such I know everything else is working. The specific error I am getting is
'your_extra_long_schema_name_your_table_name_that_you_want_to_get_data_from'
is not a valid name. Make sure it does not include invalid characters
or punctuation and that it is not too long.
A: Object names in an Access database are limited to 64 characters (ref: here). When creating an ODBC linked table in the Access UI the default behaviour is to concatenate the schema name and table name with an underscore and use that as the linked table name so, for example, the remote table table1 in the schema public would produce a linked table in Access named public_table1. If such a name exceeds 64 characters then Access will throw an error.
However, we can use VBA to create the table link with a shorter name, like so:
Option Compare Database
Option Explicit
Sub so38999346()
DoCmd.TransferDatabase acLink, "ODBC Database", "ODBC;DSN=PostgreSQL35W", acTable, _
"public.hodor_hodor_hodor_hodor_hodor_hodor_hodor_hodor_hodor_hodor", _
"hodor_linked_table"
End Sub
(Tested with Access 2010.)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/38999346",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: NextTick() does not working [Interleaving CPU-intensive task with other events] I was reading http://howtonode.org/understanding-process-next-tick
However, the code it come with does not implement CPU-intensive task.
I tried to write my version. But it is wrong.
None of the IO is serving after compute() get executed.
So, my question is: What's the proper way to use nextTick() function under this scenario ?
I don't want to block IO when compute() is executing.
var http = require('http');
function compute() {
// performs complicated calculations continuously
// ...
var result = 0;
for(var i = 0; i < 1000000; i++){
for(var j = i; j < 1000000; j++){
result += i + j;
}
}
process.nextTick(compute);
}
http.createServer(function(req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World');
}).listen(5000, '127.0.0.1');
compute();
A: nextTick simply schedules your function to be invoked on the next tick of the event loop. It does not give that function magical non-blocking properties; JavaScript is still single-threaded. If the function blocks (by performing a lot of CPU-bound work), it will still cause I/O events to queue until the function finishes.
If you need to do CPU-intensive work, do it in a worker process.
A: nextTick is a blocking call (in node v0.10.29 at least, where I tested this), it prevents other events from running. use setImmediate()
A: setImmediate will work better as explained in my blog post setTimeout and Friends as it will allow IO tasks to run before again locking up the main execution thread for a full run of compute. But as the other answers posted suggest, the way to think of this is not "nextTick doesn't work", but perhaps "oops I'm trying to do one of the only things you absolutely must not do in a node.js app and I'm getting the result I was warned about". You can't hog the execution thread in node as it is cooperative multitasking. Break computation into small chunks, use external process helpers, split something off into a supporting C++ library, etc.
A: I'll rewrite your code a little bit. Say we need to process 1000000s of items, and there is a (cpu bound, but ok to call sometimes) function computeItem() and io-bound postItem(). We want to process as much items as possible in the background, but still have responsive event loop. For simplicity, no external workers / queues / services used. Possible solution:
var desiredLatency = 10; // ms
function doBackgroundWork() {
var start = new Date();
var end;
var item;
while (item = computeItem()) {
postItem(item);
if (end - start >= desiredLatency) {
setImmediate(doBackgroundWork); // resume at next event loop invocation after processing other handlers
}
}
}
http.createServer(function(req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World');
}).listen(5000, '127.0.0.1');
doBackgroundWork();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/27263071",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How would you add a dialog that alerts user of which page he is staying on after pressing Cancel? - JavaScript This function asks a user if he is sure he wants to exit a page or not. My question is... If the user pressed cancel (if he wanted to stay on the page) how would you make it so the alert says "Staying on 'page title' " ?
This is the code:
window.onbeforeunload = function(e) {
return "Do you want to exit this page?";
};
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72163581",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: FFmpeg WebM AV1 Support With FFmpeg how can I use AV1 codec in a webm container?
I get the error:
Only VP8 or VP9 video and Vorbis or Opus audio and WebVTT subtitles are supported for WebM.
Could not write header for output file #0 (incorrect codec parameters ?): Invalid argument
Error initializing output stream 0:0 --
However Wikipedia says WebM supports AV1.
https://en.wikipedia.org/wiki/AV1
AV1 is intended to be able to be used together with the audio format Opus in a future version of the WebM container format for HTML5 web video
Or can FFmpeg simply not encode this new version?
My settings:
ffmpeg -y
-i "C:\Users\Matt\video.mp4"
-c:v libaom-av1 -strict experimental
-cpu-used 1 -crf 28
-pix_fmt yuv420p
-map 0:v:0? -map_chapters -1
-sn
-c:a libopus
-map 0:a:0?
-map_metadata 0
-f webm
-threads 0
"C:\Users\Matt\video.webm"
A: ffmpeg currently doesn't support muxing AV1 in WebM. The error you're getting comes from this code:
if (mkv->mode == MODE_WEBM && !(par->codec_id == AV_CODEC_ID_VP8 ||
par->codec_id == AV_CODEC_ID_VP9 ||
par->codec_id == AV_CODEC_ID_OPUS ||
par->codec_id == AV_CODEC_ID_VORBIS ||
par->codec_id == AV_CODEC_ID_WEBVTT)) {
av_log(s, AV_LOG_ERROR,
"Only VP8 or VP9 video and Vorbis or Opus audio and WebVTT subtitles are supported for WebM.\n");
return AVERROR(EINVAL);
}
Note the lack of AV_CODEC_ID_AV1 in the expression.
This isn't too surprising, though. AV1 in Matroska (and therefore WebM) hasn't been finalized yet. If you want to follow progress on AV1 in Matroska (and WebM), follow the discussion here on the IETF CELLAR mailing list.
A: Update, FFmpeg does support AV1 in Webm now!
if (!native_id) {
av_log(s, AV_LOG_ERROR,
"Only VP8 or VP9 or AV1 video and Vorbis or Opus audio and WebVTT subtitles are supported for WebM.\n");
return AVERROR(EINVAL);
}
Source code here.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/51316811",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
}
|
Q: How To Send Email Via Python With CSV File Attached I am able to send emails with attachments such as images but unable to do so with csv files. I am pretty new to Python and unsure what to do next.
import os
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
import smtplib
email_address = os_environ.get(`EMAIL_ADDRESS`)
email_password = os.environ.get(`EMAIL_PASS`)
message = MIMEMultipart()
message['From'] = email_address
message['To'] = #Sending message to my email
message['Subject'] = `This is A Test Email`
message.attach(MIMEText('body'))
file_name = 'Daily_Ticket_Aging_Overview'
with open('C:/Users\\odigii01\\Desktop\\Daily_Ticket_Aging_Overview.csv', 'rb') as file:
message.attach(MIMEApplication(file.read(), Name = file_name))
with smtplib.SMTP(host='smtp.gmail.com', port=587) as smtp:
smtp.ehlo() #Telling the client that we want to send an email
smtp.starttls() #TLS MODE (Transport Layer Security)
smtp.login(email_address, email_password)
smtp.send_message(message)
print('Sent...')
Realized the data is being pulled but not as a CSV File. I can download the data and open it in the Notepad.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75299660",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How clone source repository in /tmp/ space of cloud function I want clone source repository into /tmp/ space of cloud function.I have explored the subprocess module.But No success.I have also explored gitpython.But how to clone repo in git python.See below code.But it is not working in cloud function.But when am running this code locally it is working fine.In cloud function function it giving error like:fatal: could not read Username for 'https://source.developers.google.com'
def clone_gitpython():
import git
#path = 'C:\\Users\\anuragja\AppData\\Local\\Temp\\tmp\\'
path='/tmp/'
try:
git.Git(path).clone("https://source.developers.google.com/p/dev-sandbox-2XXXX/r/poc_git")
for x in os.listdir("/tmp"):
print(" cloned files name")
print(x)
except Exception as e:
print(str(e))
Update
Now I Updated code by adding ssh key on source repo and running git ssh command for cloning but still unable to cloned.Getting Error "ssh: connect to host source.developers.google.com port 2022: Connection timed out
"
def hello_world(event=None, context=None):
dir_path = os.path.dirname(os.path.realpath(__file__))
print(dir_path)
print("cloning into tmp")
url = "ssh://jainXXX1XXX@gmail.com@source.developers.google.com:2022/p/dev-sandbox-XXXX/r/test_repo"
path_temp = '/tmp'
try:
git.Repo.clone_from(url, path_temp , env={"GIT_SSH_COMMAND": 'ssh -i' + dir_path + '/id_rsa.pub '})
print("cloning completed 200")
for x in os.listdir("/tmp"):
print("List of files")
print(x)
except Exception as e:
print(str(e))
A: I was able to clone my repo on local machine with this code. On cloud function I got connection time up
def hello_world(request):
from google.cloud import storage
from git import Repo
import os
storage_client = storage.Client()
path_temp = '/tmp'
path_clone = path_temp + '/clone'
try:
os.mkdir(path_clone)
except OSError:
print ("Creation of the directory failed")
else:
print ("Successfully created the directory ")
url = 'ssh://v@.com@source.developers.google.com:2022/p/user/r/myrepo'
bucket = storage_client.get_bucket('source-marian')
blob = bucket.blob('id_rsa')
envFile = path_temp + '/id_rsa'
print ("Successfully reading rsa ")
blob.download_to_filename(envFile)
print ("Download the file from bucket")
with open (envFile, 'r') as f :
print(f.read())
ssh_cmd ='ssh -i '+ envFile
print(ssh_cmd)
print (url)
print (path_clone)
print(env)
try:
print("start git clone")
git.Repo.clone_from(url, path_clone , branch='master', env={'GIT_SSH_COMMAND': ssh_cmd})
print ("end git clone")
print("cloning completed 200")
for x in os.listdir(path_clone):
print("List of files")
print(x)
except Exception as e:
print(str(e))
And added a requirements.txt which has:
gitpython
google-cloud-storage
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/58709227",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Get a signed URL of google storage object via Terraform I am trying to get an object (ex. abc.png) signed URL from google bucket via a Terraform .tf script. But I am not getting any output on the console.
I have installed terraform on my local Linux machine, I am providing service account JSON key as credentials but not getting the signed URL, please check my script below:
provider "google" {
credentials = "account.json"
}
data "google_storage_object_signed_url" "get_url" {
bucket = "my bucket"
path = "new.json"
content_md5 = "pRviqwS4c4OTJRTe03FD1w=="
content_type = "text/plain"
duration = "2h"
credentials = "account.json"
extension_headers = {
x-goog-if-generation-match = 1
}
}
Please let me know what I am doing wrong.
A: If you need see Output Values, please add the Outputs code as below
output "signed_url" {
value = "${data.google_storage_object_signed_url.get_url.signed_url}"
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/55186365",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Pandas dataframe drop duplicates based in another column value I have a dataframe with duplicates:
timestamp id ch is_eval. c
12. 1. 1. False. 2
13. 1. 0. False. 1
12. 1. 1. True. 4
13. 1 0. False. 3
When there are duplicated, it is always when
I want to drop_duplicates with the key (timestamp,id,ch) but keep the row where is_eval is True.
Meaning, if there is a row with is_eval==True then keep it. Otherwise, it doesnt matter.
So the output here should be:
12. 1. 1. True. 4
13. 1 0. False. 1
How can I do it?
A: Use:
df = df.sort_values('is_eval', kind='mergesort', ascending=False).drop_duplicates(['timestamp','id','ch'])
print (df)
timestamp id ch is_eval c
2 12 1 1 True 4
1 13 1 0 False 1
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72457859",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Lambda function not able to read from S3 S3 bucket in account A has below policy
sid:whitelistIp
Effect: Deny
Principal: *
Resource :
arn:aws:s3:::my-s3
arn:aws:s3:::my-s3/*
Condition
NotIpaddress
awsSourceIP
[ list of Ips ]
StringsNotEqual
awsourcevpce
[ List of VpceIds ]
Sid: DenyNonSSLTraffic
Effect: Deny
Principal: *
Resource :
arn:aws:s3:::my-s3
Condition
Bool
"aws:secureTransport": "false"
Sid: AllowspecificIamRoles
Effect: Allow
Principal: *
Action:
s3:ListBucket
s3:DeleteObject
s3:GetObject
s3:PutObject
Resource :
arn:aws:s3:::my-s3
arn:aws:s3:::my-s3/*
Condition:
StringsLike:
awsuserId: [ List of userIds ]
Now from Account B I am trying to read objects from lambda function.
s3_client.list_objects() This methods works
But when i use s3_client.download_file() this gives me Access Denied error
I have verified Lambda has sufficient permissions to read from S3.
Also one Question if i give bucket policy do still i have to specify ACL for cross account access?
A: if your lambda function run into vpc then you have to create one endpoint to access s3
create s3 endpoint for vpc from vpc dashboard
select s3 gateway and attach your vpc
add endpoint routes to your route table.
Now you can read your s3 object.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/69475110",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: entity framework query and performance I have a Project Like social Network
I have to write a query to get some posts and last comment of post that my followers (not blocked) liked That
my code
public List<PostProject> GetFavoritePosts(string userId, int currentPage, int noOfRecords)
{
var skipPosts = noOfRecords * currentPage;
int i = -260;
var day = DateTime.Now.AddDays(i);
var blockedusers = DataContext.BlockedUsers.Where(bu => bu.BlockerId == userId);
var followers = DataContext.FollowUser.Where(u => u.FollowFromUserId == userId);
var posts = DataContext.Posts.Where(p => p.UserId != userId
&& p.DateOfUpdate > day
&& p.Likes.Any(l => followers.Any(fu => fu.FollowToUserId == l.UserId))
&& p.PostStatusId == 1
&& p.PostType == false
&& blockedusers.All(bu => bu.BlockedId != p.UserId));
var feed = posts
.OrderByDescending(post => post.Likes.Count)
.Select(post => new PostProject
{
PostId = post.PostId,
Content = post.Content,
Image = post.Image,
Location = post.Location,
Video = post.Video,
CreatedDate = post.CreatedDate,
DateOfUpdate = post.DateOfUpdate,
User = post.User,
ILiked = post.Likes.Any(like => like.UserId == userId),
LikeCount = post.Likes.Count,
CommentsCount = post.Comments.Count,
PostStatusId = post.PostStatusId,
ShareCount = post.SharePosts.Count,
Comments = new List<Comment> { post.Comments.OrderByDescending(c => c.CommentDate).FirstOrDefault() }
});
return feed.Skip(() => skipPosts).Take(() => noOfRecords).ToList();
}
This code generate sqlQuery with 16 select and 50ms to run !!!!
Where is my mistake
thanks
sql Query :
SELECT
[Project13].[PostStatusId] AS [PostStatusId],
[Project13].[PostId] AS [PostId],
[Project13].[Content] AS [Content],
[Project13].[Image] AS [Image],
[Project13].[Location] AS [Location],
[Project13].[Video] AS [Video],
[Project13].[CreatedDate] AS [CreatedDate],
[Project13].[DateOfUpdate] AS [DateOfUpdate],
[Project13].[Id] AS [Id],
[Project13].[VisualId] AS [VisualId],
[Project13].[ProfilePicUrl] AS [ProfilePicUrl],
[Project13].[DateCreated] AS [DateCreated],
[Project13].[Activated] AS [Activated],
[Project13].[ActivationCode] AS [ActivationCode],
[Project13].[RoleId] AS [RoleId],
[Project13].[TeamId] AS [TeamId],
[Project13].[RegisterToken] AS [RegisterToken],
[Project13].[Email] AS [Email],
[Project13].[EmailConfirmed] AS [EmailConfirmed],
[Project13].[PasswordHash] AS [PasswordHash],
[Project13].[SecurityStamp] AS [SecurityStamp],
[Project13].[PhoneNumber] AS [PhoneNumber],
[Project13].[PhoneNumberConfirmed] AS [PhoneNumberConfirmed],
[Project13].[TwoFactorEnabled] AS [TwoFactorEnabled],
[Project13].[LockoutEndDateUtc] AS [LockoutEndDateUtc],
[Project13].[LockoutEnabled] AS [LockoutEnabled],
[Project13].[AccessFailedCount] AS [AccessFailedCount],
[Project13].[UserName] AS [UserName],
[Project13].[C1] AS [C1],
[Project13].[C4] AS [C2],
[Project13].[C5] AS [C3],
[Project13].[C6] AS [C4],
[Project13].[C2] AS [C5],
[Project13].[CommentId] AS [CommentId],
[Project13].[CommentText] AS [CommentText],
[Project13].[PostId1] AS [PostId1],
[Project13].[CommentDate] AS [CommentDate],
[Project13].[UserId] AS [UserId],
[Project13].[RowVersion] AS [RowVersion]
FROM ( SELECT
[Project11].[PostId] AS [PostId],
[Project11].[Content] AS [Content],
[Project11].[PostStatusId] AS [PostStatusId],
[Project11].[Image] AS [Image],
[Project11].[Location] AS [Location],
[Project11].[Video] AS [Video],
[Project11].[CreatedDate] AS [CreatedDate],
[Project11].[DateOfUpdate] AS [DateOfUpdate],
[Project11].[Id] AS [Id],
[Project11].[VisualId] AS [VisualId],
[Project11].[ProfilePicUrl] AS [ProfilePicUrl],
[Project11].[DateCreated] AS [DateCreated],
[Project11].[Activated] AS [Activated],
[Project11].[ActivationCode] AS [ActivationCode],
[Project11].[RoleId] AS [RoleId],
[Project11].[TeamId] AS [TeamId],
[Project11].[RegisterToken] AS [RegisterToken],
[Project11].[Email] AS [Email],
[Project11].[EmailConfirmed] AS [EmailConfirmed],
[Project11].[PasswordHash] AS [PasswordHash],
[Project11].[SecurityStamp] AS [SecurityStamp],
[Project11].[PhoneNumber] AS [PhoneNumber],
[Project11].[PhoneNumberConfirmed] AS [PhoneNumberConfirmed],
[Project11].[TwoFactorEnabled] AS [TwoFactorEnabled],
[Project11].[LockoutEndDateUtc] AS [LockoutEndDateUtc],
[Project11].[LockoutEnabled] AS [LockoutEnabled],
[Project11].[AccessFailedCount] AS [AccessFailedCount],
[Project11].[UserName] AS [UserName],
[Project11].[C1] AS [C1],
[Limit1].[CommentId] AS [CommentId],
[Limit1].[CommentText] AS [CommentText],
[Limit1].[PostId] AS [PostId1],
[Limit1].[CommentDate] AS [CommentDate],
[Limit1].[UserId] AS [UserId],
[Limit1].[RowVersion] AS [RowVersion],
1 AS [C2],
[Project11].[C2] AS [C3],
[Project11].[C3] AS [C4],
[Project11].[C4] AS [C5],
[Project11].[C5] AS [C6]
FROM (SELECT
[Project9].[PostId] AS [PostId],
[Project9].[Content] AS [Content],
[Project9].[PostStatusId] AS [PostStatusId],
[Project9].[Image] AS [Image],
[Project9].[Location] AS [Location],
[Project9].[Video] AS [Video],
[Project9].[CreatedDate] AS [CreatedDate],
[Project9].[DateOfUpdate] AS [DateOfUpdate],
[Project9].[Id] AS [Id],
[Project9].[VisualId] AS [VisualId],
[Project9].[ProfilePicUrl] AS [ProfilePicUrl],
[Project9].[DateCreated] AS [DateCreated],
[Project9].[Activated] AS [Activated],
[Project9].[ActivationCode] AS [ActivationCode],
[Project9].[RoleId] AS [RoleId],
[Project9].[TeamId] AS [TeamId],
[Project9].[RegisterToken] AS [RegisterToken],
[Project9].[Email] AS [Email],
[Project9].[EmailConfirmed] AS [EmailConfirmed],
[Project9].[PasswordHash] AS [PasswordHash],
[Project9].[SecurityStamp] AS [SecurityStamp],
[Project9].[PhoneNumber] AS [PhoneNumber],
[Project9].[PhoneNumberConfirmed] AS [PhoneNumberConfirmed],
[Project9].[TwoFactorEnabled] AS [TwoFactorEnabled],
[Project9].[LockoutEndDateUtc] AS [LockoutEndDateUtc],
[Project9].[LockoutEnabled] AS [LockoutEnabled],
[Project9].[AccessFailedCount] AS [AccessFailedCount],
[Project9].[UserName] AS [UserName],
CASE WHEN ( EXISTS (SELECT
1 AS [C1]
FROM [dbo].[Likes] AS [Extent10]
WHERE ([Project9].[PostId] = [Extent10].[PostId]) AND (([Extent10].[UserId] = @p__linq__4) OR (([Extent10].[UserId] IS NULL) AND (@p__linq__4 IS NULL)))
)) THEN cast(1 as bit) ELSE cast(0 as bit) END AS [C1],
[Project9].[C1] AS [C2],
[Project9].[C2] AS [C3],
[Project9].[C3] AS [C4],
[Project9].[C4] AS [C5]
FROM ( SELECT
[Project8].[PostId] AS [PostId],
[Project8].[Content] AS [Content],
[Project8].[PostStatusId] AS [PostStatusId],
[Project8].[Image] AS [Image],
[Project8].[Location] AS [Location],
[Project8].[Video] AS [Video],
[Project8].[CreatedDate] AS [CreatedDate],
[Project8].[DateOfUpdate] AS [DateOfUpdate],
[Project8].[Id] AS [Id],
[Project8].[VisualId] AS [VisualId],
[Project8].[ProfilePicUrl] AS [ProfilePicUrl],
[Project8].[DateCreated] AS [DateCreated],
[Project8].[Activated] AS [Activated],
[Project8].[ActivationCode] AS [ActivationCode],
[Project8].[RoleId] AS [RoleId],
[Project8].[TeamId] AS [TeamId],
[Project8].[RegisterToken] AS [RegisterToken],
[Project8].[Email] AS [Email],
[Project8].[EmailConfirmed] AS [EmailConfirmed],
[Project8].[PasswordHash] AS [PasswordHash],
[Project8].[SecurityStamp] AS [SecurityStamp],
[Project8].[PhoneNumber] AS [PhoneNumber],
[Project8].[PhoneNumberConfirmed] AS [PhoneNumberConfirmed],
[Project8].[TwoFactorEnabled] AS [TwoFactorEnabled],
[Project8].[LockoutEndDateUtc] AS [LockoutEndDateUtc],
[Project8].[LockoutEnabled] AS [LockoutEnabled],
[Project8].[AccessFailedCount] AS [AccessFailedCount],
[Project8].[UserName] AS [UserName],
[Project8].[C1] AS [C1],
[Project8].[C2] AS [C2],
[Project8].[C3] AS [C3],
(SELECT
COUNT(1) AS [A1]
FROM [dbo].[SharePosts] AS [Extent9]
WHERE [Project8].[PostId] = [Extent9].[PostId]) AS [C4]
FROM ( SELECT
[Project7].[PostId] AS [PostId],
[Project7].[Content] AS [Content],
[Project7].[PostStatusId] AS [PostStatusId],
[Project7].[Image] AS [Image],
[Project7].[Location] AS [Location],
[Project7].[Video] AS [Video],
[Project7].[CreatedDate] AS [CreatedDate],
[Project7].[DateOfUpdate] AS [DateOfUpdate],
[Project7].[Id] AS [Id],
[Project7].[VisualId] AS [VisualId],
[Project7].[ProfilePicUrl] AS [ProfilePicUrl],
[Project7].[DateCreated] AS [DateCreated],
[Project7].[Activated] AS [Activated],
[Project7].[ActivationCode] AS [ActivationCode],
[Project7].[RoleId] AS [RoleId],
[Project7].[TeamId] AS [TeamId],
[Project7].[RegisterToken] AS [RegisterToken],
[Project7].[Email] AS [Email],
[Project7].[EmailConfirmed] AS [EmailConfirmed],
[Project7].[PasswordHash] AS [PasswordHash],
[Project7].[SecurityStamp] AS [SecurityStamp],
[Project7].[PhoneNumber] AS [PhoneNumber],
[Project7].[PhoneNumberConfirmed] AS [PhoneNumberConfirmed],
[Project7].[TwoFactorEnabled] AS [TwoFactorEnabled],
[Project7].[LockoutEndDateUtc] AS [LockoutEndDateUtc],
[Project7].[LockoutEnabled] AS [LockoutEnabled],
[Project7].[AccessFailedCount] AS [AccessFailedCount],
[Project7].[UserName] AS [UserName],
[Project7].[C1] AS [C1],
[Project7].[C2] AS [C2],
(SELECT
COUNT(1) AS [A1]
FROM [dbo].[Comments] AS [Extent8]
WHERE [Project7].[PostId] = [Extent8].[PostId]) AS [C3]
FROM ( SELECT
[Project6].[PostId] AS [PostId],
[Project6].[Content] AS [Content],
[Project6].[PostStatusId] AS [PostStatusId],
[Project6].[Image] AS [Image],
[Project6].[Location] AS [Location],
[Project6].[Video] AS [Video],
[Project6].[CreatedDate] AS [CreatedDate],
[Project6].[DateOfUpdate] AS [DateOfUpdate],
[Project6].[Id] AS [Id],
[Project6].[VisualId] AS [VisualId],
[Project6].[ProfilePicUrl] AS [ProfilePicUrl],
[Project6].[DateCreated] AS [DateCreated],
[Project6].[Activated] AS [Activated],
[Project6].[ActivationCode] AS [ActivationCode],
[Project6].[RoleId] AS [RoleId],
[Project6].[TeamId] AS [TeamId],
[Project6].[RegisterToken] AS [RegisterToken],
[Project6].[Email] AS [Email],
[Project6].[EmailConfirmed] AS [EmailConfirmed],
[Project6].[PasswordHash] AS [PasswordHash],
[Project6].[SecurityStamp] AS [SecurityStamp],
[Project6].[PhoneNumber] AS [PhoneNumber],
[Project6].[PhoneNumberConfirmed] AS [PhoneNumberConfirmed],
[Project6].[TwoFactorEnabled] AS [TwoFactorEnabled],
[Project6].[LockoutEndDateUtc] AS [LockoutEndDateUtc],
[Project6].[LockoutEnabled] AS [LockoutEnabled],
[Project6].[AccessFailedCount] AS [AccessFailedCount],
[Project6].[UserName] AS [UserName],
[Project6].[C1] AS [C1],
(SELECT
COUNT(1) AS [A1]
FROM [dbo].[Likes] AS [Extent7]
WHERE [Project6].[PostId] = [Extent7].[PostId]) AS [C2]
FROM ( SELECT
[Project5].[PostId] AS [PostId],
[Project5].[Content] AS [Content],
[Project5].[PostStatusId] AS [PostStatusId],
[Project5].[Image] AS [Image],
[Project5].[Location] AS [Location],
[Project5].[Video] AS [Video],
[Project5].[CreatedDate] AS [CreatedDate],
[Project5].[DateOfUpdate] AS [DateOfUpdate],
[Extent6].[Id] AS [Id],
[Extent6].[VisualId] AS [VisualId],
[Extent6].[ProfilePicUrl] AS [ProfilePicUrl],
[Extent6].[DateCreated] AS [DateCreated],
[Extent6].[Activated] AS [Activated],
[Extent6].[ActivationCode] AS [ActivationCode],
[Extent6].[RoleId] AS [RoleId],
[Extent6].[TeamId] AS [TeamId],
[Extent6].[RegisterToken] AS [RegisterToken],
[Extent6].[Email] AS [Email],
[Extent6].[EmailConfirmed] AS [EmailConfirmed],
[Extent6].[PasswordHash] AS [PasswordHash],
[Extent6].[SecurityStamp] AS [SecurityStamp],
[Extent6].[PhoneNumber] AS [PhoneNumber],
[Extent6].[PhoneNumberConfirmed] AS [PhoneNumberConfirmed],
[Extent6].[TwoFactorEnabled] AS [TwoFactorEnabled],
[Extent6].[LockoutEndDateUtc] AS [LockoutEndDateUtc],
[Extent6].[LockoutEnabled] AS [LockoutEnabled],
[Extent6].[AccessFailedCount] AS [AccessFailedCount],
[Extent6].[UserName] AS [UserName],
[Project5].[C1] AS [C1]
FROM (SELECT
[Extent1].[PostId] AS [PostId],
[Extent1].[Content] AS [Content],
[Extent1].[PostStatusId] AS [PostStatusId],
[Extent1].[UserId] AS [UserId],
[Extent1].[Image] AS [Image],
[Extent1].[Location] AS [Location],
[Extent1].[Video] AS [Video],
[Extent1].[CreatedDate] AS [CreatedDate],
[Extent1].[DateOfUpdate] AS [DateOfUpdate],
(SELECT
COUNT(1) AS [A1]
FROM [dbo].[Likes] AS [Extent5]
WHERE [Extent1].[PostId] = [Extent5].[PostId]) AS [C1]
FROM [dbo].[Posts] AS [Extent1]
WHERE ( NOT (([Extent1].[UserId] = @p__linq__0) AND (0 = (CASE WHEN (@p__linq__0 IS NULL) THEN cast(1 as bit) ELSE cast(0 as bit) END)))) AND ([Extent1].[DateOfUpdate] > @p__linq__1) AND ( EXISTS (SELECT
1 AS [C1]
FROM ( SELECT
[Extent2].[UserId] AS [UserId]
FROM [dbo].[Likes] AS [Extent2]
WHERE [Extent1].[PostId] = [Extent2].[PostId]
) AS [Project1]
WHERE EXISTS (SELECT
1 AS [C1]
FROM [dbo].[FollowUsers] AS [Extent3]
WHERE ([Extent3].[FollowFromUserId] = @p__linq__2) AND ([Extent3].[FollowToUserId] = [Project1].[UserId])
)
)) AND (1 = [Extent1].[PostStatusId]) AND (0 = [Extent1].[PostType]) AND ( NOT EXISTS (SELECT
1 AS [C1]
FROM [dbo].[BlockedUsers] AS [Extent4]
WHERE ([Extent4].[BlockerId] = @p__linq__3) AND (([Extent4].[BlockedId] = [Extent1].[UserId]) OR (CASE WHEN ([Extent4].[BlockedId] <> [Extent1].[UserId]) THEN cast(1 as bit) WHEN ([Extent4].[BlockedId] = [Extent1].[UserId]) THEN cast(0 as bit) END IS NULL))
)) ) AS [Project5]
LEFT OUTER JOIN [dbo].[AspNetUsers] AS [Extent6] ON [Project5].[UserId] = [Extent6].[Id]
) AS [Project6]
) AS [Project7]
) AS [Project8]
) AS [Project9] ) AS [Project11]
OUTER APPLY (SELECT TOP (1) [Project12].[CommentId] AS [CommentId], [Project12].[CommentText] AS [CommentText], [Project12].[PostId] AS [PostId], [Project12].[CommentDate] AS [CommentDate], [Project12].[UserId] AS [UserId], [Project12].[RowVersion] AS [RowVersion]
FROM ( SELECT
[Extent11].[CommentId] AS [CommentId],
[Extent11].[CommentText] AS [CommentText],
[Extent11].[PostId] AS [PostId],
[Extent11].[CommentDate] AS [CommentDate],
[Extent11].[UserId] AS [UserId],
[Extent11].[RowVersion] AS [RowVersion]
FROM [dbo].[Comments] AS [Extent11]
WHERE [Project11].[PostId] = [Extent11].[PostId]
) AS [Project12]
ORDER BY [Project12].[CommentDate] DESC ) AS [Limit1]
) AS [Project13]
ORDER BY [Project13].[C3] DESC, [Project13].[PostId] ASC, [Project13].[Id] ASC, [Project13].[C2] ASC
A: First, it seems there is confusion between Linq and Linq to SQL. Not all of Linq can be translated into SQL queries. For example: Any() and All() can't be used with Linq to Sql here - they are in-memory collection functions. This means that all rows need to be fetched and then resolved afterwards.
You are also not resolving your first two queries, for example by calling ToList().
var blockedusers = DataContext.BlockedUsers.Where(bu => bu.BlockerId == userId);
var followers = DataContext.FollowUser.Where(u => u.FollowFromUserId == userId);
This leaves them to run on-demand every time that they are used (deferred query execution) - meaning they call SQL each time. Beware the IEnumerable!
You could probably get rid of all your issues by doing joins onto BlockedUser and FollowUser all in the same query. For example, use a left join to BlockedUser and eliminate those rows by testing that the blocked user is null.
A: I think, you should firstly orderby, skeep, take and then select new PostObject in return
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/44622904",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: boost asio timer hangs the second time I read async I have a RS485 communication that I talk over with boost::asio::serial_port. I'm testing what happens when there is no connection. The first time the timer cancels the operation. The second time the program just hangs on io.run(). I'm confused, because I create a new fresh timer, reset io and try to have a clean plate before I start to read anything from the wire.
boost::asio::io_context io;
boost::asio::serial_port port;
std::size_t readUntil(std::vector<char>& buffer, char delim, std::chrono::microseconds timeout) {
using boost::system::error_code;
error_code read_result {};
size_t msglen = 0;
io.reset();
boost::asio::system_timer timer(io, timeout);
boost::asio::async_read_until(port, boost::asio::dynamic_buffer(buffer), delim, [&](error_code ec, size_t n) {
timer.cancel();
read_result = ec;
msglen = n;
}
);
timer.async_wait([&](error_code ec) {
if (!ec) {
port.cancel();
throw exception::read_exception(exception::read_exception::Code::TIME_OUT);
}
});
io.run(); // Hangs here, the second time, not the first
if (read_result) {
std::stringstream sstream;
sstream << read_result;
throw exception::read_exception(exception::read_exception::Code::PORT, sstream.str());
}
return msglen;
}
int main() {
//set up port options (baudrate etc)
for(size_t i = 0; i<10; i++) {
std::vector<char> buffer;
readUntil(buffer, '\', std::chrono::microseconds(1000));
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75259810",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to access txt file using relative path I'm currently trying to open a file using
io.open(file_name, "r")
My directory structure is
parent_dir
-src
-main.lua
-tests
-test.txt
I'm currently trying to open the txt file from the tests folder in the main.lua using
io.open(file_name, "r") but it won't recognize the file as existing. If I place the absolute path into the file_name it works. I'm not sure how to format a relative path? I've tried some version of ../../../tests/test.txt but I can't seem to get it to work.
The actual path of the file is something like /Users/user_name/parent_dir/tests/test.txt
A: The ../ syntax is correct to specify relative paths.
But this is not relative to the location of your Lua script but to your current working directory.
Refer to get current working directory in Lua
You cannot change the current working directory from within a Lua script unless you use libraries like LuaFileSystem.
If you're running a single script you can check if global arg[0] (if it is not nil) contains the path of that script. You can use that to build an absolute path from your script's location.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/55701371",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: From iPhone 4 to iPhone 5 - UIMageView I am working on my existing app to customize the screen to make compatible to iPhone 5 screen.
However as you could see in the following figures, my imageview is not properly placed. I dont know what I am doing wrong. Any help is appreciated! unlockView represent the arrow. lockViewOutlet image represent the outer of the arrow image.
- (void)viewDidLoad {
[super viewDidLoad];
float screenSizeHeight=[UIScreen mainScreen].bounds.size.height;
if(screenSizeHeight==568)
{
[lockViewOutlet setFrame:CGRectMake(0, 20, 320, 548)];
[unlockImageView setFrame:CGRectMake(24, 500, 68, 43)];
[unlockText setFrame:CGRectMake(105, 500, 182,43)];
}
if(screenSizeHeight==480)
{
[lockViewOutlet setFrame:CGRectMake(0, 20, 320, 460)];
[unlockImageView setFrame:CGRectMake(24, 411, 68, 43)];
[unlockText setFrame:CGRectMake(105, 411, 182,43)];
}
}
iPhone 5 screenshot
iphone 4 screenshot
A: Ok I got you,
The problem is with your image view lockViewOutlet.
in your code : [lockViewOutlet setFrame:CGRectMake(0, 20, 320, 548)];
You try to resize your background imageView. Resizing only the imageView does not solve your problem. Real problem is with the size of lockViewOutlet.image.
Best way is design a new image with the size 320, 568. Then set the image for iphone 5 after resizing your imageview.
if(screenSizeHeight==568)
{
[lockViewOutlet setFrame:CGRectMake(0, 20, 320, 548)];
[lockViewOutlet setImage:[UIImage imageNamed:@"iPhone5LockNackground.png"]];
[unlockImageView setFrame:CGRectMake(24, 500, 68, 43)];
[unlockText setFrame:CGRectMake(105, 500, 182,43)];
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/16432238",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Safe PDO mySQL SELECT statement with for loop I was told to use PDO to safely retrieve data from a database. Now I'm wondering if this would be safe or work at all:
$dbtype = "sqlite";
$dbhost = "localhost";
$dbname = "test";
$dbuser = "root";
$dbpass = "admin";
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
$firstName = htmlspecialchars($_POST["firstName"]);
foreach($conn->query('SELECT * FROM employeeTable WHERE firstName = ' . $firstName) as $row) {
echo $row['lastName'].' '.$row['email'];
}
Because to me it looks like it would still be possible to "inject" something into the query.
So my question is: Is that really safe and if not how exactly would I make it safe?
A: I think you'd better use the following to prepare, the process of preparing is to void the injection
$sql = 'SELECT * FROM employeeTable WHERE firstName = :firstName';
$sth = $conn->prepare($sql);
$sth -> bindParam(':firstName', $firstName);
$sth -> execute();
$result = $sth->fetchAll(PDO::FETCH_OBJ);
foreach ($result as $key => $value) {
echo $value->lastName, $value->email;
}
A: Just remember to don't directly concatenate post variables to your query, just use prepared statements. And after the execution of prepared statements, you need to fetch the results:
$select = $conn->prepare('SELECT * FROM employeeTable WHERE firstName = :firstName');
$select->execute(array(':firstName' => $_POST["firstName"));
while($row = $select->fetch(PDO::FETCH_ASSOC))
echo $row['lastName'].' '.$row['email'];
}
Here is a good read:
http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/26188688",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How can I make one line of a bash script into multiple lines? Im tying to make some of my bash scripts a bit easier on the eyes. Lets says I have this script and its working fine.
if [ "$PASSWDCHECK" = "<title>401 Authorization Required</title>" ]
then echo "The Subsubscription password is wrong" ; exit
else mkdir /home/"$USERNAME"/src && mkdir /opt/logstash && mkdir /etc/snort && mkdir /etc/snort/rules/
fi
I would like to make it more like this, but it fails to execute. What am I missing?
if [ "$PASSWDCHECK" = "<title>401 Authorization Required</title>" ]
then echo "The Subsubscription password is wrong" ; exit
else mkdir /home/"$USERNAME"/src \ &&
mkdir /opt/logstash \ &&
mkdir /etc/snort \ &&
mkdir /etc/snort/rules/ \ &&
fi
A: You need to put the \ at the end of each line, not before the &&. Make sure there is no whitespace after the \.
A: As long as the && is the last non-whitespace token on the line, the command will automatically continue onto the next line.
if [ "$PASSWDCHECK" = "<title>401 Authorization Required</title>" ]
then echo "The Subsubscription password is wrong" ; exit
else mkdir /home/"$USERNAME"/src &&
mkdir /opt/logstash &&
mkdir /etc/snort &&
mkdir /etc/snort/rules/
fi
A && list joins two commands, so the parser knows that a newline before the second command should be discarded.
A: if [ "$PASSWDCHECK" = "<title>401 Authorization Required</title>" ]
then echo "The Subsubscription password is wrong" ; exit
else
mkdir /home/"$USERNAME"/src && \
mkdir /opt/logstash && \
mkdir /etc/snort && \
mkdir /etc/snort/rules/
fi
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/22024838",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Hide blue box around code during slideshow of a Jupyter Notebook I am preparing a presentation in Jupyter Notebook (version 6.1.4, not Lab)
(not the final notebook, just an example)
I also hide the code through a nbextension.
When I go into the slideshow (RISE), though, and arrive to the code cells, there is always the blue box around input-output.
Is there a way to hide or disable it in slideshow mode?
Or do I have to write everything in markdown somehow?
A: Just export the slides to html using the no input option:
jupyter nbconvert YOURNOTEBOOKSNAME.ipynb --to slides --no-input serve
For more check out nbconvert's documention
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/68345251",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to count real total number of chars in a string? Sorry if the question is silly. I need to count real number of chars in a string. For example I have the following string:
हा य
With .length I have the following result:
let chars = "हा य";
console.log(chars.length);
for(var i = 0; i < chars.length; i++){
console.log(chars[i]);
}
As you can see, it's wrong. I have three chars here:
This one - हा, - this one (empty space) and य this one. Which is proper and shortest way to count it correctly?
A: Hope this helps.
For all languages you can try Count number of characters present in foreign language
function countChars(text){
return text.split("").filter( function(char){
let charCode = char.charCodeAt(); return charCode >= 2309 && charCode <=2361 || charCode == 32;
}).length;
}
let chars = "हा य";
console.log(countChars(chars));
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/62455293",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to change timestamp column size in DB2? Any idea how to change timestamp column size in DB2?
I tried altering table, drop and then create table. Both didn't work.
Here are the queries I've tried:
alter table clnt_notes alter column lupd_ts set data type timestamp(26)
create table CLNT_NOTES
(NOTE_ID int not null generated always as identity (start with 1, increment by 1),
CLNT_ID varchar(10) not null,
TX varchar(200),
LUPD_TS timestamp(26) not null)
A: It depends on your DB2 platform and version. Timestamps in DB2 used to all have 6 digit precision for the fractional seconds portion. In string form, "YYYY-MM-DD-HH:MM:SS.000000"
However, DB2 LUW 10.5 and DB2 for IBM i 7.2 support from 0 to 12 digits of precision for the fraction seconds portion. In string form, you could have from "YYYY-MM-DD-HH:MM:SS" to "YYYY-MM-DD-HH:MM:SS.000000000000".
The default precision is 6, so if you specify a timestamp without a precision (length), you get the six digit precision. Otherwise you may specify a precision from o to 12.
create table mytable (
ts0 timestamp(0)
, ts6 timestamp
, ts6_also timestamp(6)
, ts12 timestamp(12)
);
Note however, that while the external (not exactly a string) format the DBMS surfaces could vary from 19 to 32 bytes. The internal format the TS is stored in may not. On DB2 for IBM i at least the internal storage format of TS field takes between 7 and 13 bytes depending on precision.
*
*timestamp(0) -> 7 bytes
*timestamp(6) -> 10 bytes (default)
*timestamp(12) -> 13 bytes
A: Since you refer to 10 as the length, I'm going to assume you're looking in SYSIBM.SYSCOLUMNS (or another equivalent table in the catalog.
The LENGTH column in the catalog refers to the internal length of the field. You can calculate this using the following formula:
FLOOR( ((p+1)/2) + x )
*
*p is the precision of the timestamp (the number of places after the decimal [the microseconds])
*x is 7 for a timestamp without a timezone, or 9 if it has a timezone (if supported by your platform)
If you are comparing the to a field in the SQLCA, that field will be the length of a character representation of the timestamp. See this Information Center article for an explanation between the two fields.
If you truly want to change the scale of your timestamp field, then you can use the following statement. x should be an integer for the number of places after the decimal in the seconds position.
The number of allowed decimals varies by platform and version. If you're on an older version, you can likely not change the scale, which is set at 6. However, some of the newer platforms (like z/OS 10+, LUW 9.7+), will allow you to set the scale to a number between 0 and 12 (inclusive).
ALTER TABLE SESSION.TSTAMP_TEST
ALTER COLUMN tstamp
SET DATA TYPE TIMESTAMP(x);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/30298796",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: PHP date format variable I would like to change the date format in the following code:
#search for all event start dates
$starts = $sxml->xpath('//event/startdate');
#get the unique start dates of these event
$dates = array_unique($starts);
foreach($dates as $date) {
echo "<li class='header'><h1>{$date}</h1></li>" ."\n";
currently, it pulls from an XML feed as 25/11/2021 and I would like to show it as Thursday 25 November 2021 - probably as multiple variables. However, date() is not working.
Any help is appreciated!
A: Using the DateTime object it can be easy and accurate
$dates = ['25/11/2021','24/11/2021','23/11/2021'];
foreach ( $dates as $date){
$df = (DateTime::CreateFromFormat('d/m/Y', $date))->format('l d F Y');
echo "<li class='header'><h1>{$df}</h1></li>" ."\n";
}
RESULTS
<li class='header'><h1>Thursday 25 November 2021</h1></li>
<li class='header'><h1>Wednesday 24 November 2021</h1></li>
<li class='header'><h1>Tuesday 23 November 2021</h1></li>
PHP Manual for DateTime object
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/70114958",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Unexpected line wrap A very simple html:
<div style="width:200px">
<p>f 22222222222222222222222222</p>
</div>
will be rendered as:
f
22222222222222222222222222
and what I was expected is:
f 222222222222222
22222222222
is it possible to fix this?
Fiddle: http://jsfiddle.net/8yL6j/
A: Use word-wrap: break-word to break the text up in the middle of a word:
.container {
width: 200px;
word-wrap: break-word;
}
Demo: http://jsfiddle.net/8yL6j/1/
A: It seems that you would like browsers to put as many characters on a line that fit there and then break, with no regard to normal line breaking behavior, rules of languages, etc., then use word-break: break-all on the element.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/13320634",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to do a conditional write in dynamodb transactions using boto3 python library I have two documents in dynamodb with Id as hash key (no range key)
one document looks like this
{
'Id': 'x',
'ExpiresAt': 1634889543
}
another document looks like below
{
'Id': 'y',
'counter': 1
}
If the document with id x does not exist or it exists but expires_at is less than current time, then I want to increment counter in document with id y. I believe I have to use transactions.
I found this article where they tell us how to do this using a transaction manager library in Java - https://aws.amazon.com/blogs/developer/performing-conditional-writes-using-the-amazon-dynamodb-transaction-library/
But I couldn't find anything where they explain how to do this in python. How can I achieve this in python using Boto3?
A: Use query to find the current status of document with 'Id':x and the update the other document using UpdateExpression with "ADD"
import boto3
from boto3.dynamodb.conditions import Key, Attr
from datetime import datetime
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('your_table_name')
result = table.query(
KeyConditionExpression=Key('Id').eq('x')
)
if result is None or result['ExpiresAt'] < datetime.now():
table.update_item(
Key={
"Id": "y"
},
UpdateExpression='ADD counter :inc',
ExpressionAttributeValues={
':inc': {'N': '1'}
}
)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/69673443",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to set context of provided module through ProvidePlugin? I have wrapper module over promise-polyfill -
/* jshint node: true */
/* global Promise: false */
"use strict";
if ( typeof Promise === "undefined" ) {
module.exports = require('promise-polyfill');
} else {
module.exports = Promise;
}
Then i inject it into all my modules:
new webpack.ProvidePlugin({
'Promise': 'require-promise',
})
And i getting a problem. Promise is an empty object, instead native Promise or undefined. How i can pass context (window or global) to this module?
Generated code looks like:
function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(Promise) {/*** IMPORTS FROM imports-loader ***/
(function() {
/* jshint node: true */
/* global Promise: false */
"use strict";
console.log(Promise);
if ( typeof Promise === "undefined" ) {
module.exports = __webpack_require__(59);
} else {
module.exports = Promise;
}
/*** EXPORTS FROM exports-loader ***/
module.exports = Promise;
}.call(window));
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7)))
/***/ },
A: Fixed:
new webpack.ProvidePlugin({
'Promise': 'imports?Promise=>window.Promise!require-promise',
})
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/39788534",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Filling fields in Word using c# and Microsoft Word Interop I tried to Fill out Form Fields in Microsoft Word using C# Interop Assemblies with the following Code
string filename = @"N:\mehler\Vorlage2.dotx";
Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();
Microsoft.Office.Interop.Word.Document doc = new Microsoft.Office.Interop.Word.Document();
doc = word.Documents.Open(filename);
doc.Activate();
foreach (Microsoft.Office.Interop.Word.FormField field in doc.FormFields)
{
switch (field.Name)
{
case "Text2":
field.Range.Text = "1";
break;
default:
break;
}
}
doc.SaveAs2(@"N:\mehler\Ausgefuellt.docx");
doc.Close();
word.Quit();
System.Diagnostics.Process.Start(@"N:\mehler\Ausgefuellt.docx");
Microsoft Word can not open the File Ausgefuellt.docx and Shows a Message saying that an unknown Error has occured.
I created a simple Word Document with a bit of unformated text and 2 Text-Form-Fields
can anyone tell me, what went wrong or if ia have an Error in my Source Code
Edit:
I managed to specify the Problem. I created an Document only conaining one Text Form Field.
In Word 2013 this is found unter the Topic "Formulare aus Vorversionen" (I would translate this to "Formfields from former Versions")
If I comment out the whole foreach Block so that I would only open and save the Document, I get the same result.
If I open the Source File directly in Word it is no Problem. I also tried to load the Document and make Word Visible. The Result looked like an empty Word instance with no Document loaded.
A: Use that, it should work:
Word.Application WordApp;
Word.Document WordDoc;
object misValue = System.Reflection.Missing.Value;
WordApp = new Word.ApplicationClass();
WordDoc = WordApp.Documents.Open(filePath2, misValue, misValue, misValue, misValue, misValue,
misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue);
WordDoc.Activate();
A: You should use:
doc = Word.Documents.Add(filename);
Instead of:
doc = Word.Documents.Open(filename);
So Word will use the template to create a document file, and not open the template itself.
It seems Word behaves differently when the active document is a Template.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/18533198",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
}
|
Q: Using couchbase as a single node Can couchbase be used as only one node for development purposes, or benchmarking inserts, updates and reads?
And can couchbase run in a computer with 1vCPU and 512 MB of RAM?
A: This page covers the minimum recommended specification for running Couchbase Server.
The minimum hardware specifications to install and effectively operate
Couchbase Server are:
Dual-core x86 CPU running at 2GHz. 4GB RAM (physical).
It then goes on to say...
The specification can be as low as 1GB of free RAM beyond operating
system requirements and a single CPU core.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/41673429",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Minimal amount of swaps Assume we have got sequence (of length n) of ones and zeroes, eg. 10100100. We want to rearrange them, so 1 follows every 0, and 0 follows every 1 - but in the end there can be some 0s or 1s left - so our sequence will become 10101000. Let's say there is k amount of 1 and n-k amount of 0, so we need to have min(n, n-k) groups of 10 (or 01) and then the rest left.
We can do one operations - swap two chosen elements. We need to calculate the minimum amount of swaps to rearrange sequence into given order - e.g. we need just one swap (between indexes 4 and 5, indexing from 0), to rearrange that correctly. For 0101011111 or 10101000000 we need 0 swaps.
Any ideas how to calculate that? Any complexity actually would be apprieciated - I got no idea how to do that.
A: From your example, I'm assuming that your surplus characters must appear at the right side of the string. This means that the previous characters must alternate. This gives you only two possible solutions for the final string. In the case you give, these would be
10101000
01010100
Your entire algorithm is simple: produce both of these sequences (k 0's alternating with k 1's) and append the n-k extras. Compare each with the original to see which of the two has the smaller quantity of displaced characters. Identify those pairs and swap. For instance, using the above:
10100100 original
10101000 candidate
--------
....!!.. two differences, one swap
10100100 original
01010100 candidate
--------
!!!!.... four differences, two swaps
You use the first candidate, with locations 4 and 5 already identified.
A: Convert String to collection of Ints:
("10100100".toList).map (_.toInt-'0')
= List(1, 0, 1, 0, 0, 1, 0, 0)
Zip it with index:
.zipWithIndex
List((1,0), (0,1), (1,2), (0,3), (0,4), (1,5), (0,6), (0,7))
with modulo, find for index (0,1,2...), which value we either expect, (010...) a is string value, b is possible, alternating value of 01, c is index in String
.map {case (a,b)=> (a, b%2, b)}
List((1,0,0), (0,1,1), (1,0,2), (0,1,3), (0,0,4), (1,1,5), (0,0,6), (0,1,7))
filter those who match expectation (do the same for those in opposite order, a!=b):
.filter {case (a,b,c) => a==b }
List((0,0,4), (1,1,5), (0,0,6))
group by alternating value for later counting:
.groupBy {case (a,b,c)=> b}
Map(1 -> List((1,1,5)), 0 -> List((0,0,4), (0,0,6)))
get the lenghts and count:
.map {case (a, b) => (a, b.length)}
Map(1 -> 1, 0 -> 2)
Ignore the 1 and 0 as identifier, just take the count:
.map (i => (i._2))
List(1, 2)
Since we can only perform swaps for 1 where we have a corresponding 0 and vice versa, take the minimum of both:
"10100100".toList).map (_.toInt-'0').zipWithIndex.map {case (a,b)=> (a, b%2, b)}.filter {case (a,b,c) => a==b }.groupBy {case (a,b,c)=> b}.map {case (a, b)=> (a, b.length)}.map (i => (i._2)).min
1
In the end, we didn't need the c-value, it was just useful for keeping track, what's happening. Here is the version without c, and which starts with 1, not 0:
("10100100".toList).map (_.toInt-'0').zipWithIndex.map {case (a,b)=> (a, b%2)}.filter {case (a,b) => a!=b }.groupBy {_._2}.map {case (a, b)=> (a, b.length)}.map (i => (i._2)).min
2
The minimum of those two values (1, 2) is the solution.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/48753323",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: 'TypeErroe: cannot read property NAME of undefined' after trying to retrieve key/ value from nested object I am trying to fetch some data in react-native where I store the fetched data in a state variable so I can access them anywhere in the component. This is the code:
export default class Result extends Component {
state = {
data: {}
};
async componentDidMount() {
const that = this;
const url = 'https://world.openfoodfacts.org/api/v0/product/8002270014901.json';
let response = await fetch(url);
if (response.status == 200) {
let data = await response.json();
this.setState({ data });
}
}
... some code ...
render() {
console.log(this.state.data.product);
...some more code ...
}
}
I got the code from the componentDidMount from another SOF article to make sure that I have some data I can work with.
When I try to test the outcome it works perfectly fine with the console.log you see in the code. But if I try to go just one layer deeper within the object (e.g. console.log(this.state.data.product.brands); I get the error message mentioned in the subject. Why is that? How do I make sure that the entire object is 'loaded' before I proceed?
A: What comes to my mind in this case is that you are receiving the response after the render method is being executed.
You may ask But how it works when I log just this.state.data.product?
Well, when you initialize your state you are defining that it have a data object, so in that case the code won't break because this.state.data.product is undefined, but when you try to get one layer deeper now you are trying to access to a property of an undefined value, which leads to the error you are getting (cannot read property x of undefined).
So, what can I make to fix that?
You have to store a boolean variable in your state, let's call it fetchingData and give it a default value of true, so now you have
state = {
data: {},
fetchingData: true
};
then, on your render method you validate if its fetching the data or if you already have te response from the server, modify it to be like this:
render() {
if(this.state.fetchingData) return <View><Text>Fetching data...</Text></View>
console.log(this.state.data.product.brands);
return(
Whatever you want to do with the data...
)
}
What it does is when you are still waiting for the data, a Fetching data... message will be shown, now when you receive the data you also have to change fetchingData to false.
if (response.status == 200) {
let data = await response.json();
this.setState({
data: data,
fetchingData: false
});
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/54876875",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: JQuery UI Tooltip on span with disabled child link I'm working on a project that frequently requires the use of tooltips on disabled links. The project includes a draft/publish system, so I like to inform the user why a certain action is not available through the use of a tooltip.
The way I've been adding these tooltips is by wrapping the link in a <span> and adding the tooltip to the <span> instead of the link itself.
<span class="tooltip-class" title="Reason this link is disabled.">
<a disabled>Action Name</a>
</span>
Up until now this seemed to do the trick. Recently, this method no longer works. Hovering over the <span> does not open the tooltip.
I am using chrome, but have experienced the same result in firefox as well.
JSFiddle Example
Any ideas why this stopped working? Suggestions for a workaround or a better solution to my problem are also welcome! Thanks!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/58457638",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Rails: Get checked radio-button value with html input tags I have a simple structure of contest:
*
*The contest has multiple questions
*Each question has multiple answers
possible
For this I feel like what I've created is a good structure:
I am trying to get the answers of a user for each question from the form in my view to my controller. Long story short, I was unable to use the <%= collection_radio_buttons ... %> because the method wouldn't be right. There is not one column in my model for each answer to each question. answer_option is not a column in my questions table it's an association because it's another table... (or would you know how to help on that?)
So I've bypassed this issue by creating loops on answers_options of each question and using html inputs and labels, like this:
<%= simple_form_for @contest, url: contest_send_quizz_path(@contest), method: :post do |f| %>
<%= f.fields_for :questions do |q| %>
<% @questions.each do |question| %>
<h4 class="mt-5"><%= question.title %></h4>
<% question.answer_options.each do |answer_option| %>
<div class="inputGroup">
<input type="radio" name=<%= answer_option.question_id %> value="<%= answer_option.answer %>" id=<%= answer_option.id %> />
<label for=<%= answer_option.id %>><%= answer_option.answer %></label>
</div>
<% end %>
<% end %>
<% end %>
<div class="mt-3">
<span class="button-effect-2">
<%= f.button :button, "Envoyer", type: :submit, class:"text-white" %>
</span>
</div>
<% end %>
However now the problem is fetching those values in the controller. It seems with this question that I'd have to get it with params[:something] and that :something being the name of the input. Is that right? And now that I know that, does putting params[:name] (which is the same for all concerned radio buttons of one question) directly get the checked radio, or is there another thing to do?
Here is what I have for now, there is stuff to ignore since the structure of the rest of my code is bigger than just the contest. This is in the ContestsController:
def show
@contest = Contest.find(params[:id])
authorize @contest
@time_left = seconds_to_units(@contest.deadline - Time.now)
@is_done = @contest.deadline < Time.now
if @is_done
get_winner
end
@questions = @contest.questions.includes([:answer_options])
end
def send_quizz
@contest = Contest.find(params[:contest_id])
@questions = @contest.questions.includes([:answer_options])
authorize @contest
current_user.contests << @contest
user_choice = # TODO : Get checked radio value from view
user_contest = current_user.contests.select { |contest| contest.title == @contest.title }.first
user_contest.questions.each do |question|
question.user_answer = user_choice
end
# TODO : make sure every questions were answered before submitting request
redirect_to contests_path
flash[:notice] = "Ta réponse a été prise en compte"
end
So is there a way to get this value, or should I change my db structure so that each question has one column for each answer? Or maybe another solution? Thanks !
EDIT:
I also tried replacing this:
<input type="radio" name="<%= answer_option.question_id %>" value="<%= answer_option.answer %>" id="<%= answer_option.id %>" />
<label for="<%= answer_option.id %>"><%= answer_option.answer %></label>
With this:
<%= q.check_box :answer_option, name:answer_option.question_id, id:answer_option.id %>
<%= q.label :answer_option, answer_option.answer, for:answer_option.id %>
And getting the value in the controller with user_choice = params[:answer_option] but when I replaced check_box with radio_button, it messed up the name, id etc. values AND I couldn't select anymore.
EDIT 2:
By adding this structure:
<%= q.radio_button :answer_option, answer_option.answer %>
<%= q.label :answer_option, answer_option.answer %>
It works (no errors), however the name is set automatically and to something not specific to each question i.e. contest[questions][answer_option] and the label's for is set to contest_questions_answer_option, therefore clicking on the label does not link to the checkbox.
A: Managed to retrieve the value of the checkbox with this structure for the radio-buttons:
<%= q.radio_button answer_option.question_id, answer_option.answer %>
<%= q.label "#{answer_option.question_id}_#{answer_option.answer.parameterize.underscore}", answer_option.answer %>
And the controller:
user_choices = params[:contest][:questions]
user_contest.questions.each do |question|
question[:user_answer] = "#{user_choices[:'#{question.id}']}"
question.save
end
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/61597545",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Optimize a function over a set of values I'm fairly new to python, and I'm trying to minimize a function over a given dataset. That is, I have a set of values for a vector x, and I'm trying to minimize a function f(x) for x in my data.
For clarity, I have data X=np.array([[1,-1], [2,2], [-1,0]]) and I want to minimize a function f(x) = x[0] + x[1], such that it returns a functional value -1 for x = [-1,0].
In actuality my dataset is much larger, so I'd rather not create an array of functional values and minimize that with min(), if it can be avoided.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/58379183",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: .net Interop in windows 7 with VB6 I've got a legacy VB6 DLL that I've modified to take advantage of DirectShow when on Windows 7, due to WIA not working well in Win7 for cam capture.
I've incorporated a .NET DLL into the vb6 DLL that has functions to provide information and one function to display forms for the DirectShow capture stuff.
The DLL functions as expected on the development XP box and a test client XP machine, but I'm having difficulty with Win7.
I've registered the DLLs, ran gacutil, and set it up just like I did for the XP machine, but I'm getting automation errors.
Error Description: Automation error
Error Source: bvImgCap
Module: clsMain
Procedure: CaptureGraphic
This particular Win7 machine happens to be the development platform for the .NET DLL, and it runs fine by itself.
A: "Automation error" points to an error in resolving the proper Net dll's. This may be caused by the fact that the Net Framweworks (1.1., 3(.5),4.0) on the XP machine may not be the same as the Win7 box. Alternatively the file structure of the Net dll's is wrong and some dll's cannot be found.
I have had good results by using fuslogvw to troubleshoot these issues.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/8085611",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Gzip response from soapUI in PHP I m trying to get gzip response and for that I'm sending this node in body.
$body['TPA_Extensions']['IntelliSellTransaction']['CompressResponse']['Value'] = "true";
It returned successful response but didn't show it in var_dump. In var_dump it shows Null. In below image it shows successful response. Successful Response Image
Can anyone tell me how I get this data "H4sIAAAAAAAAALWS0WvbMBDG/5VDe/BLbTkLY..."
A: For the request test step, add Script Assertion with below snippet:
//Check response is not empty
assert context.response
//Parse response and fetch required value
def cResponse = new XmlSlurper().parseText(context.response).'**'.find {it.name() == 'CompressedResponse'}?.text()
log.info "Extracted data : $cResponse"
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/46928586",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Why messages from en.json are not translated in vue 3 + i18n I have created a default vue2 + i18n project. in en.json (in lacales folder) I have
{
"message": "hello i18n !!"
}
HelloWorld component code is
<template>
<p>{{ $t("message") }}</p>
</template>
<script>
export default {
name: "HelloWorld",
mounted() {
alert(this.$t("message"));
},
};
</script>
<i18n>
{
"en": {
"hello": "Hello i18n in SFC!"
}
}
</i18n>
At startup, the lines will be translated and I will get an alert "hello i18n !!"
However, I will also receive warnings.
Value of key 'message' is not a string or function !
Fall back to translate the keypath 'message' with root locale.
But if I create a vue project with + and i18n I also get warnings but the translation will not come. (this only comes with the lines in the locales folder, using vue 2 and vue 3)
However, translations created in the tag do not cause errors, why does this happen?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/67865108",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Showing view controller from AppDelegate when notification arrived I am tring to show UIViewController which is inside the UIStoryboard. There isn't any problem about poping up the view. But the navigation is not working in the popup viewcontroller; such as when I touch back button
[self.navigationController popViewControllerAnimated:YES];
I am using that code in AppDelegate --> didReceiveRemoteNotification method
UIStoryboard *mystoryboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
PFProfileInfoVC *viewcontroller = [mystoryboard instantiateViewControllerWithIdentifier:@"SBID_ProfileVC"];
viewcontroller.strAuthorID = [userInfo objectForKey:@"aps"][@"targetId"];
[self.window.rootViewController presentViewController:viewcontroller animated:YES completion:nil];
Thanks,
A: When you use presentViewController, the viewController is not pushed onto the navigation stack. Normally, it is presented modally. So if you want to dismiss it, use
[self dismissViewControllerAnimated:true completion:nil];
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/31677600",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to change the number of components in a UIPickerView? I have a UITableView for different datas. When the user select one row, then I will popup a UIPickerView to let the user select some values. And I have implemented the numberOfComponentsInPickerView DataSource method to return the number of components for different row in the UITableView. actually they are all 1.
But now, I will download more data from the internet and add more rows in the UITableView. I called [pickerView reloadAllComponents] after finishing the downloading. I expected the numberOfComponentsInPickerView will be called so I can have more components in the picker view for the new rows in UITableView. But it's not working.
How can I do that? thanks.
A: In XCode 4.2 running on an IOS 5 device, I was able to get [pickerView reloadAllComponents] to change the number of components in a UIPickerView.
It works exactly as you originally expected it to. Calling reloadAllComponents caused the numberOfComponentsInPickerView method to get called.
A: I found a solution for my problem. Instead of trying to make the UIPickerView reload and change the number of components dynamically, I use two UIPickerView, one has 1 component, and the other has two. And I will switch between these two when the user select different rows of data in the tableview.
Hope this can help if other people has similar need.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/6909324",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to track function calls in MATLAB? I would like a way to track all function calls that have operated on a specific workspace variable -- for instance, a sound waveform that will be transformed by various signal processing functions.
One cumbersome and fragile way is to do this:
>> cfg = [];
>> curr_call = 'data_out = my_function(cfg,data_in);';
>> eval(curr_call);
>> data_out.cfg.history = cat(1,data_out.cfg.history,{curr_call});
What would be much better is the following:
>> cfg = [];
>> data_out = my_function(cfg,data_in);
>> data_out.cfg.history
'data_out = my_function(cfg,data_in);'
EDIT for clarification: In other words, this variable has a field, cfg.history, that keeps track of all history-enabled functions that have operated on it (ideally with arguments). The history field should be updated regardless of where function calls originate: my example above is from the command line, but calls made from cell mode or within a script should also be appended to the history. Obviously, I can edit my_function() in the above example so that it can modify the history field.
NOTE in response to discussion below: the motivation for doing this is to have the history "attached" to the data in question, rather than say, in a separate log file which would then need to be packaged with the data somehow.
Can this be done?
A: You can access the full Session history using this code:
import com.mathworks.mlservices.MLCommandHistoryServices
history=MLCommandHistoryServices.getSessionHistory;
To achive what you want, use this code:
import com.mathworks.mlservices.MLCommandHistoryServices;
startcounter=numel(MLCommandHistoryServices.getSessionHistory);
disp('mydummycommand');
disp('anotherdummycommand');
history=MLCommandHistoryServices.getSessionHistory;
commands=cell(history(startcounter-2:end-1));
Be aware that these functions are undocumented. It uses the command history which is typically located at the bottom right in your matlab.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/24065992",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: How can I directly use url to access my spring boot web application without any port? I have deployed my spring boot application which using spring security for security in a ubuntu server.So, I have an problem.I can only access my application with using url like:https://example.com:8443. As for, why do I use the port of 8443?It is seems that spring security using the port of 8443.Is there any solutions help me to access my application with url of www.example.com?
my related code is as follows:
spring.freemarker.cache=false
spring.datasource.url=jdbc:mysql://MyIp:3306/keziqu?serverTimezone=UTC
spring.datasource.username=user
spring.datasource.password=password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
server.port=8443
server.ssl.key-store=classpath:**.pfx
server.ssl.key-store-password=password
#server.ssl.key-password=another-secret
logging.file.path=./log/
#logging.level.org.springframework.security=debug
@Configuration
public class TomcatConfig {
@Bean
TomcatServletWebServerFactory tomcatServletWebServerFactory() {
TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory(){
@Override
protected void postProcessContext(Context context) {
SecurityConstraint constraint = new SecurityConstraint();
constraint.setUserConstraint("CONFIDENTIAL");
SecurityCollection collection = new SecurityCollection();
collection.addPattern("/*");
constraint.addCollection(collection);
context.addConstraint(constraint);
}
};
factory.addAdditionalTomcatConnectors(createTomcatConnector());
return factory;
}
private Connector createTomcatConnector() {
Connector connector = new
Connector("org.apache.coyote.http11.Http11NioProtocol");
connector.setScheme("http");
connector.setPort(80);
connector.setSecure(false);
connector.setRedirectPort(8443);
return connector;
}
}
A: If you want to visit your website without having to specify the port, you need to make sure it's running on the default port.
The default secured HTTP (https://) port is 443.
The default unsecured HTTP (http://) port is 80.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/66184618",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: how to change take photo text to retake photo text when there is image I am working on one camera app. There is one button called Take Photo where user can take photo and it will show in below of that button.
What i need is. Once i took picture n=and when photo is show under take photo button. I want to change the text from take photo to retake photo. If no images are available i need to show take photo text. How to do that ?
Here my code html :
<button class="button button-energized" ng-click="getPhoto()">
Take Photos
</button>
<div class="spacer" style="height: 10px;" ></div>
<div style="padding-left: 20px; padding-top: 10px; padding-bottom: 30px;">
<img ng-src="{{lastPhoto}}" style="max-width: 70%;max-height: 70%;">
</div>
My controller code :
$scope.getPhoto = function() {
Camera.getPicture().then(function(imageURI) {
console.log(imageURI);
$scope.lastPhoto = imageURI;
}, function(err) {
console.err(err);
}, {
quality: 75,
targetWidth: 320,
targetHeight: 320,
saveToPhotoAlbum: false
});
};
A: You can use ng-show or ng-if for this
<button class="button button-energized" ng-click="getPhoto()"><span ng-if="!lastPhoto ">Take Photos</span><span ng-if="lastPhoto">Retake Photo</span></button>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/42975220",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Find Predecessor in a BST I want to search recursively and efficiently a predecessor in a binary search tree without using parent pointer.
I give the root of the tree and a certain data (that can be contained or not in the BST) as parameter of the function.
I'm having troubles because if the BST does not contain the data, the function should give in output the maximum value smaller than it.
Node *recPredecessor(Node *root, int data, Node *pred){
if(root->key > data){
return recPredecessor(root->left, data, pred);
}
if(root->key < data){
return recPredecessor(root->right, data, root);
}
if((root == NULL) || (root->key == data)){
if(root == NULL){
return pred;
}
if(root->key == data){
if(root->left != NULL){
return bstRecGetMax(root->left); //this func return node with Max key
}else{
return pred;
}
}
}
}
A: Given you want the predecessor to node N in an in-order traversal sense, there are three possibilities:
*
*N has a left child. In this case, the predecessor is the rightmost element of N's left subtree.
*N does not have a left child, and there is at least one rightward step in the path from the root to N. In this case, the predecessor is the source node of the rightward step nearest to N on that path.
*N does not have a left child, and there are no rightward steps along the path to it from the root. In this case, N is the minimum element in the tree, so it has no predecessor.
What you must do, therefore, is track the source of the most recent rightward step (not necessarily the immediate parent) as an additional parameter to the recursive search function by which you find node N. When you reach N, you will then have that ready to use in the event that N has no left child, and you can ignore it if N does have a left child.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/56082214",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Pycharm cant run WSL 2 interpreter because Source Root is marked as a windows dir instead of WSL dir When using the WSL python interpreter, Pycharm attempts to cd to the project Source root folder.
However it is using the full windows path: \\wsl$\Ubuntu-18.04\home\ubuntu\code\my-repo
Instead of the needed WSL path: ~/code/my-repo
resulting the following error :
C:\Users\user\AppData\Local\Microsoft\WindowsApps\ubuntu1804.exe run "export PYTHONUNBUFFERED=1 && export PYTHONIOENCODING=UTF-8 && export PYTHONPATH=\\wsl$\Ubuntu-18.04\home\ubuntu\code\my-repo:/mnt/c/Users/user/AppData/Local/JetBrains/Toolbox/apps/PyCharm-P/ch-0/202.6397.98/plugins/python/helpers/pycharm_matplotlib_backend:/mnt/c/Users/user/AppData/Local/JetBrains/Toolbox/apps/PyCharm-P/ch-0/202.6397.98/plugins/python/helpers/pycharm_display && export PYCHARM_HOSTED=1 && export PYCHARM_DISPLAY_PORT=63342 && cd \\wsl$\Ubuntu-18.04\home\ubuntu\code\my-repo && /home/ubuntu/code/my-repo/venv/bin/python '//wsl$/Ubuntu-18.04/home/ubuntu/code/my-repo/code.py'"
/bin/bash: line 0: cd: \wsl$Ubuntu-18.04homeubuntucodemy-repo: No such file or directory
Pycharm Professional 2020.2
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/63246025",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How does static work inside a function? I came across something I haven't seen before. I have the following recursive function that only works when i is static
void printNthFromLast(Node* head, int n) {
static int i = 0;
if(head == nullptr)
return;
printNthFromLast(head->next, n);
if(++i == n)
cout << head->data;
}
I assume static in this context means shared among multiple recursive calls to the same function printNthFromLast?
The real confusing part is that it doesn't reinitialize it to 0 every time the recursive function calls itself. It's like this whole line of code static int i = 0; is skipped?
Can someone explain this to me?
A: The behavior you observed :
The real confusing part is that it doesn't reinitialize it to 0 every time the recursive function calls itself. It's like this whole line of code static int i = 0; is skipped?
is exactly what you are asking for with static. A local static variable is initalized the first time its definition (i.e, the line static int i = 0;) is reached.
In your case it means it will be set to zero only on the first call ever to this method during the whole runtime of your program. There is no notion of multiple recursive calls to the same function, so it will make no difference if the method is invoked by itself (the multiple recursive call you are referring to) or if you are starting a whole new stack of recursion somewhere else in your client code.
Possible solution
To go back on your description, it will only work with i being static (for n!=1) because, if your removed static keyword, then i would be initialized to zero each time the method is entered (a different local instance of i for each invocation of the method). Thus in your condition
if(++i == n)
++i would always evaluate to 1, independently of the recursion depth.
If you want the static i to be reinitialized each time you call your method in your client code (i.e. to start a new stack of recursion), you could write it like :
void printNthFromLast(Node* head, int n, bool reinit=true)
{
static int i = 0;
if(reinit)
{
i=0;
}
if(head == nullptr)
return;
printNthFromLast(head->next, n, false);
if(++i == n)
cout << head->data;
}
Thread safe with tail call optimization
A cleaner solution would be to have i as a mutable parameter to the function, so your function would be thread-safe. And with a better ordering of the operation, you do not need to save the previous invocation frame, thus enjoying tail call optimization offered by most of recent compilers.
EDIT : As pointed by Matthieu, my original implementation printed the Nth element instead of the Nth from last element. Fixing while enabling TCO is less elegant, but can be done as follows :
/// n==1 means printing the last element here
static void printNthFromLastImpl(const Node* currentNode, const Node* offsetNode, const int n, int currentDepth)
{
// n == 0 will never print in the original example by op, so forbid it
assert(n);
if(++currentDepth > n)
{
offsetNode = offsetNode->next;
}
if(currentNode->next)
{
currentNode = currentNode->next;
}
else
{
if(currentDepth >= n)
{
cout << offsetNode->data;
}
return;
}
return printNthFromLastImpl(currentNode, offsetNode, n, currentDepth);
}
/// \brief : code to call from client
static void printNthFromLast(const Node* head, const int n)
{
if (head)
{
printNthFromLastImpl(head, head, n, 0);
}
}
A: When you declare a static local variable the compiler only initializes it once (the first time control flow passes over the variable declaration); thereafter the variable keeps its value across all calls to the function that declares it for the lifetime of the program, much like a global variable.
How is this achieved?
When the compiler sees something like this:
void foo() {
static int i = 0;
cout << i++;
}
It produces code equivalent to this:
bool foo_i_initialized = false; // global
int foo_i; // global
void foo() {
if (!foo_i_initialized) {
foo_i = 0;
foo_i_initialized = true;
}
cout << foo_i++;
}
The above example is a bit contrived because here foo_i is a primitive initialized with a constant and as such it could have been statically initialized in global scope (removing the need for the boolean flag), but this mechanism also handles more complicated scenarios.
A: The initialization is only executed at the first call of the function. Subsequent calls will use the already inititalized value.
A: So, as said, static int i = 0; is local to the function. It is initialized the first time flow-control passes through its definition, and skipped ever after. Two special cases are made:
*
*in case of dynamic initialization (by a function) which throws an exception, initialization will be reattempted the next time flow-control passes through the definition.
*in case of calls from multiple threads, the first thread does the initialization and all others are blocked until it is done (or fails with an exception)
Now, regarding your code: don't. A local static is a global variable in disguise, your code is equivalent to:
int i = 0;
void printNthFromLast(Node* head, int n) {
if(head == nullptr)
return;
printNthFromLast(head->next, n);
if(++i == n)
cout << head->data;
}
Note: not only is it more difficult to debug, it is also not thread-safe.
Instead, you should provide a local variable for this usage:
static void printNthFromLastImpl(Node const* const head, int& i, int const n) {
if(head == nullptr)
return;
printNthFromLastImpl(head->next, i, n);
if(++i == n)
cout << head->data;
}
// Each call to this function instantiates a new `i` object.
void printNthFromLast(Node const* const head, int const n) {
int i = 0;
printNthFromLastImpl(head, i, n);
}
EDIT: As remarked by Ad N, since the list is not modified it should be passed by const pointer.
Following Ad N latest edit (TCO version), I realized an iterative implementation should work (note, there might be some off by one errors).
void printNthFromLast(Node const* const head, int const n) {
if (n == 0) { return; }
// Set "probe" to point to the nth item.
Node const* probe = head;
for (int i = 0; i != n; ++i) {
if (probe == nullptr) { return; }
probe = probe->next;
}
Node const* current = head;
// Move current and probe at the same rhythm;
// when probe reaches the end, current is the nth from the end.
while (probe) {
current = current->next;
probe = probe->next;
}
std::cout << current->data;
}
A: You've described it very well yourself. A static variable is initialised only once, the first time through the function, and the variable is then shared across calls to the function.
A: A variable declared static is initialized only once. So even, when the function is called again, the value of the variable i here in this context is retained from the previous call.
The next time the program reaches the static initialize statement to an initialized variable, it skips the statement.
Since, static variables are stored in the BSS segment and not on the stack, the previous state of the variable in previous function calls, is not altered.
A: Not only shared among multiple recursive calls, shared among all calls.
There is actually only a single instance of the variable i, and it's shared among all calls of the function.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/18099236",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to play audio in codenameone I am developing an application based on codenameone. Now I try to play sounds in the background. Unfortunatly I didn't found a code sample for that.
The only thing I have I the following, which didn't work:
InputStream uri = getClass().getResourceAsStream("startsound.mp3");
try {
findMediaPlayer().setDataSource(uri,"audio/mpeg",null);
} catch (IOException ex) {
}
findMediaPlayer().run();
Does anyone have a sample code for that problem?
A: Not Sure whether this can imply in the case of codenameone. But u can try :-
MediaPlayer player = MediaPlayer.create(this, R.raw.music);
player.setLooping(true); // Set looping
player.setVolume(100,100);
public int onStartCommand(Intent intent, int flags, int startId) {
player.start();
return 1;
}
@Override
public void onDestroy() {
player.stop();
player.release();
}
public void onStart(Intent intent, int startId)
{
// TODO
}
Or u can refer to the discussion here : Play Background Sound in android applications
A: Check out the developer guide for code samples of this including a small sample of an audio recording/playback app:
Form hi = new Form("Capture", BoxLayout.y());
hi.setToolbar(new Toolbar());
Style s = UIManager.getInstance().getComponentStyle("Title");
FontImage icon = FontImage.createMaterial(FontImage.MATERIAL_MIC, s);
FileSystemStorage fs = FileSystemStorage.getInstance();
String recordingsDir = fs.getAppHomePath() + "recordings/";
fs.mkdir(recordingsDir);
try {
for(String file : fs.listFiles(recordingsDir)) {
MultiButton mb = new MultiButton(file.substring(file.lastIndexOf("/") + 1));
mb.addActionListener((e) -> {
try {
Media m = MediaManager.createMedia(recordingsDir + file, false);
m.play();
} catch(IOException err) {
Log.e(err);
}
});
hi.add(mb);
}
hi.getToolbar().addCommandToRightBar("", icon, (ev) -> {
try {
String file = Capture.captureAudio();
if(file != null) {
SimpleDateFormat sd = new SimpleDateFormat("yyyy-MMM-dd-kk-mm");
String fileName =sd.format(new Date());
String filePath = recordingsDir + fileName;
Util.copy(fs.openInputStream(file), fs.openOutputStream(filePath));
MultiButton mb = new MultiButton(fileName);
mb.addActionListener((e) -> {
try {
Media m = MediaManager.createMedia(filePath, false);
m.play();
} catch(IOException err) {
Log.e(err);
}
});
hi.add(mb);
hi.revalidate();
}
} catch(IOException err) {
Log.e(err);
}
});
} catch(IOException err) {
Log.e(err);
}
hi.show();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/41608212",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Merge 2 lists with linq where at least one property has changed var usersOld = new List<User>();
var userOld1 = new User { IsDisabled = true, IsLicenced = false, Id = 1 };
var userOld2 = new User { IsDisabled = true, IsLicenced = false, Id = 2 };
var userOld3 = new User { IsDisabled = true, IsLicenced = false, Id = 3 };
var userOld4 = new User { IsDisabled = true, IsLicenced = false, Id = 4 };
usersOld.Add(userOld1);
usersOld.Add(userOld2);
usersOld.Add(userOld3);
usersOld.Add(userOld4);
var usersToday = new List<User>();
var userNew1 = new User { IsDisabled = true, IsLicenced = true, Id = 1 };
var userNew2 = new User { IsDisabled = true, IsLicenced = false, Id = 2 };
var userNew3 = new User { IsDisabled = false, IsLicenced = false, Id = 3 };
var userNew4 = new User { IsDisabled = true, IsLicenced = true, Id = 4 };
usersToday.Add(userNew1);
usersToday.Add(userNew2);
usersToday.Add(userNew3);
usersToday.Add(userNew4);
var query = null;
How can I merge both lists into one list where at least one property hasChanged so the User is "dirty"
// According to my logic the users with id 1, 3 and 4 have changed in any of both properties. Note in real life there can and will
// be more properties than these 2 properties.
A: As Mephy says, implementing IEquatable<User> would make this simpler - at that point, you could just perform a join:
var changes = usersOld.Join(usersNew, o => o.Id, n => n.Id,
(o, n) => new { Old = o, New = n })
.Where(pair => !pair.Old.Equals(pair.New));
Then whenever you add a relevant property, you just need to change the Equals implementation to take account of that.
The result is a sequence of pairs - currently as an anonymous type, but you could use Tuple<,> if you wanted to return from a method.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/25506528",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: R Shiny dynamic tab number and input generation I've got an issue with my current shiny code.
I have to generate a dynamic number of tabs depending on the results of a given function (that part works fine). Then, I want to generate the input of these tabs in other loops of for example renderText. However, the final output of the textOutput for my generated renderText is always the one of the last renderText of the loops.
Here is a small example of the idea:
library(shiny)
library(shinydashboard)
ui <- pageWithSidebar(
headerPanel("xxx"),
sidebarPanel(),
mainPanel(
uiOutput("multipleUI")
)
)
server <- function(input, output) {
output$multipleUI <- renderUI({
tabs <- list(NULL)
for(i in 1:5){
tabs[[i]] <- tabPanel(title = paste0("tab ",i),
textOutput(paste0("out",i)), # prints j as 5 in all tabs
paste0("local out ",i)) # prints i as current loop value for each tab)
}
do.call(tabBox,tabs)
})
observe({
for(j in 1:5){
txt = paste0("generated out ", j)
print(txt) # print with current j
output[[paste0("out",j)]] <- renderText({txt})
}
})
}
shinyApp(ui, server)
While it might not be that important for renderText where I can just work around the issue, I intend to render a lot of plots and tables and couldn't think of a workaround there.
I'd appreciate any help!
EDIT: I've updated the code to show a small working example
A: Here's a solution that seems to work. I'm using lapply to create the tabs. Let me know if it works for what you need.
library(shiny)
ui <- pageWithSidebar(
headerPanel("xxx"),
sidebarPanel(),
mainPanel(
do.call(tabsetPanel, c(id='tab',lapply(1:5, function(i) {
tabPanel(
title=paste0('tab ', i),
textOutput(paste0('out',i))
)
})))
)
)
server <- function(input, output) {
lapply(1:5, function(j) {
output[[paste0('out',j)]] <- renderPrint({
paste0('generated out ', j)
})
})
}
shinyApp(ui, server)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/42535038",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: [JavaScript]Is there a way to use Cloudinary without terminal my development environment(chat bot app) doesnt offer terminal.(uses Rhino)
but what I can do is putting module(.js) files in it.
Would there be a way to use Cloudinary upload and etc codes?
It would be nice if there is a .js format of Cloudinary module.
A: I'm Danny and I work on Cloudinary's Developer Support team.
We've got a Node SDK, as well as a jQuery one and a vanilla Javascript one too. If you're just looking to allow users to upload content via your site, the upload widget may be a better solution for you.
Would you mind posting a little about your use case? If you let us know the specific problem you're trying to solve, we should be able to help. Feel free to reply here, or if you're providing specific details about your account, you may prefer to raise a ticket via our support center.
Looking forward to hearing back from you.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/70003700",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to convert FileOpenDialog's return value into array in autoit? This is the code :-
Local $var = FileOpenDialog($message, @WindowsDir & "\", "Images (*.jpg;*.bmp)", 1 + 4)
If @error Then
MsgBox(4096, "", "No File(s) chosen")
Else
$var = StringReplace($var, "|", @CRLF)
MsgBox(4096, "", "You chose " & $var)
EndIf
FileOpenDialog returns string and I just want it to convert to an array which stores the names of image files. I used StringToASCIIArray, but it returned some junk values which were not file names.
A: Your code works just fine. If my understanding is correct and all you need is just converting the output value (string separated by "|") to an array, then you can do it just by
Local $arr = StringSplit($var, "|")
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/17715180",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: DataError in datagridview when you see the row I have strange problem. I have datagridview fill from XML file and a button that add a new row at the end to that datagridview.
I have scrollbar so I can't see all the rows at once. When I add new row and if I don't see the new created row everything is OK.
The row is created and I can edit cell and everything is fine. But if I scroll down to the end and then press the button there is DataError in
datagridview1.Rows[datagridview1.Rows.Count - 1].Cells[3].
This column is special. It's DataGridViewComboBoxColumn and when it doesn't have value the
I have - DisplayStyle = Nothing. But when I have values from the xml I make the style - ComboBox. I have no problem with that.
Here is the code that add the row:
private void AddNewBlock_Click(object sender, EventArgs e)
{
datagridview1.Rows.Add(val[0], 0, val[1], new DataGridViewComboBoxCell(), 4, 0);
datagridview1.Rows[datagridview1.Rows.Count - 1].Cells[3].ReadOnly = false;
(datagridview1.Rows[datagridview1.Rows.Count - 1].Cells[3] as DataGridViewComboBoxCell).DisplayStyle = DataGridViewComboBoxDisplayStyle.ComboBox;
AddNewDataGridvRow(datagridview1.Rows.Count - 1, 3, true);
}
The method `AddNewDataGridvRow' contains:
private void AddNewDataGridvRow(int row, int col, bool isNewBBlock = false)
{
AddNewNumber newNum = new AddNewNumber(); // this shows form with one textbox
// in it you type the value. Nothing special.
DataGridViewComboBoxCell cb = new DataGridViewComboBoxCell();
if (newNum.ShowDialog() == DialogResult.OK)
{
cb = new DataGridViewComboBoxCell();
cb = (DataGridViewComboBoxCell)datagridview1.Rows[row].Cells[col];
byte num= newNum.Num;
cb.ValueMember = num.ToString();
cb.Items.Add(num.ToString());
datagridview1.Rows[row].Cells[col].Value = ver.ToString();
}
Is there something that I do wrong?
When I debug it I get the error after I press f10 in this line
if (newNum.ShowDialog() == DialogResult.OK)
The form code:
public partial class AddNewNumber : Form
{
public byte Num= 0;
public AddNewNumber ()
{
InitializeComponent();
}
private void btnOk_Click(object sender, EventArgs e)
{
try
{
Num= Convert.ToByte(tbNum.Text);
this.Close();
}
catch
{
this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
}
}
}
A: Try this when you open the dialog :
newNum.ShowDialog()
if (newNum.DialogResult == DialogResult.OK)
{
}
DialogResult.OK cannot be compared to a .showDialog() I guess.
You must compare the DialogResult property of your form, with the value DialogResult.OK, not the .showDialog().
A: I manage to fix it thanks for the help. The error comes from the line
datagridview1.Rows.Add(val[0], 0, val[1], new DataGridViewComboBoxCell(), 4, 0);
I change it to
datagridview1.Rows.Add(val[0], 0, val[1], null, 4, 0);
and it worked.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/23110027",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.