text stringlengths 70 452k | dataset stringclasses 2 values |
|---|---|
Xamarin Forms Bug?
In one of the standard Pixel device emulators, while running your app, if you go into "sleep" mode by pressing the power button, then wake the device up-- and do this twice -- then the UI becomes unresponsive, but actions will fire if you press buttons--you just won't see the UI update or the screen change.
EASY TO REPRODUCE:
Just create a new Xam Forms project using master detail template. Run it using one of the Pixel emulators. Browse, and then pick an item. Then do the power on/off TWO TIMES. Then click the back button. (after this, if you use the home button and then return to your running app, the correct page will now be displayed.)
Can anyone confirm this? Is it just me or my emulators? I haven't tried on a real Pixel -- I need to talk to someone who has one.
Note, this does not occur using the low-end simulator.
https://github.com/xamarin/Xamarin.Forms/issues
Have you tried it on a new emulator instance? If its reproducible then you should file a bug in the link shared by Jason
| common-pile/stackexchange_filtered |
How to make soft/rounded edges using PathGeometry in .xaml C#
I am trying to draw in C# for the first time and I have a problem with positioning.
I made some background but I have problem to finish it. I always destroy the whole figure...
I need to change down edges and make them soft/rounded like on mobile screen. I have tried to change this, but I don't understand where to input <ArcSegment>(or some other command) and how to rotate that part of edge.
This is how my .xaml code looks:
<Path.Data>
<PathGeometry>
<PathFigure StartPoint="0,0">
<ArcSegment Size="50,50" RotationAngle="180" IsLargeArc="True" SweepDirection="Clockwise" Point="500,0"/>
<LineSegment Point="500,400"/>
<LineSegment Point="450,500"/>
<LineSegment Point="50,500" />
<LineSegment Point="0,400"/>
<LineSegment Point="0,0" />
</PathFigure>
</PathGeometry>
</Path.Data>
After my code I got:
Thank you in advance!
Here is how I solved my problem.
<LineSegment Point="0,475"/>
<BezierSegment Point1="0,475" Point2="0,500" Point3="25,500" />
<LineSegment Point="475,500" />
<BezierSegment Point1="475,500" Point2="500,500" Point3="500,475" />
<LineSegment Point="500,0" />
I have applied BezierSegment to make rounded/soft edges.
Explanation:
In BezierSegment I have three points. I drew first LineSegment which is going to the first red arrow, then I set the same spot to be the first point. After that I move to spot where is going to be rounded shape, and then I place Point3 which will connect another two. I did the same thing for right part.
Also, you can check curved angle in this answer. There are a lot more things described there. It seems to be the same thing, but I didn't understand how to apply it at that time because I didn't know about the name of BezierSegment and I was confused with all other commands.
At least I presented a specific case of layout and code, hope it will help someone.
| common-pile/stackexchange_filtered |
calculate average with a dynamic filter
I have a set of data that looks something like the attached, I would like to create a matrix that allows me to calculate the average size by the number of months selected. For example, if the filter is set on Jan and Feb, the average for city abc would be zone 1 (848) and zone 2 (306). TIA
Updated after your comment:
Given a table called Sheet1 such as this:
Create a New Measure to calculate the quantity of months between the first month and the last one. If you have one entry per months this should work:
Months =
var MonthStart = CALCULATE(Year(FIRSTDATE(Sheet1[month]))*12+Month(FIRSTDATE(Sheet1[month])),ALLEXCEPT(Sheet1,Sheet1[month]))
var MonthEnd = cALCULATE(Year(LASTDATE(Sheet1[month]))*12+Month(LASTDATE(Sheet1[month])),ALLEXCEPT(Sheet1,Sheet1[month]))
RETURN
MonthEnd-MonthStart+1
Create a New Measure to sum over all values and divide it by the [Months] measure.
TotalAmount = sum(Sheet1[size])/[Months]
This should yield the results:
This method gives me the average of each records, I need the average per number of months selected.
| common-pile/stackexchange_filtered |
Excel 2003 Freezes When Worksheet with PivotTable Selected
All of the sudden, my Excel 2003 began an odd behavior today. Whenever I click on a worksheet tab that has a PivotTable on it, I become unable to click on any other tabs or on the menu with the options to minimize, maximize, and size at the top left of the worksheet window. I am left unable to click on the other tabs until I double-click inside a cell in the PivotTable worksheet and get a blinking curor as if to type. Then, I can navigate to other tabs normally.
I can't think of any major changes I have made to my computer in the last day that would have caused this. I did instiall PC Tools antivirus over a week ago, and since that time have noticed my computer behaving in odd ways, but excel has been just fine until now.
Does anyone have any thoughts on what might cause this?
Thanks so much.
| common-pile/stackexchange_filtered |
How to show a dialog on top of a locked screen with Jelly Bean
I have an Eclair based app that shows a full screen dialog on a locked phone. The dialog appears, and once the dialog disappears (because a user clicked a button on it), the locked screen is shown to the user for them to enter a passcode. All desired behaviour.
This is the snippet that works
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.alertdialog);
When I install this app on a Nexus 7 with Jelly Bean, I do not get the same behaviour. The tablet wakes up and shows the locked screen for the user to enter a passcode. No dialog is presented on top of the locked screen. I enter the passcode and I still do not see the dialog anywhere. Has the way to accomplish the same behaviour changed in a recent release? Is there another way to do this?
I'd say that's what's excepted. An app should never be able to override the lockscreen and put dialogs on top of it. That kinda takes away the security aspect of having a lockscreen.
There are some scenarios where you want this behavior, for example an alarm that you should be able to snooze.
Android does allow this, it works on my phones. It does not however work on my new Nexus 7 tablet. (By the way, the phone is still locked with a lockscreen. All the user can do is see and interact with the single dialog, and once they do, they are presented with the lockscreen. They cannot do anything else with the phone unless they go through the lockscreen.
| common-pile/stackexchange_filtered |
How do I use compc to build a swc that dynamically links in Flex components?
In Flash Builder 4.6, when managing a Flex project, under the Build Path options for a Flex Library Project, I can select between "external" and "Merged into code" Framework linkage, with "external" being the default.
How can I use external linkage when calling compc directly?
It seems like compc by default puts the Flex components in the library-path section instead of in the external-library-path section (looking at the generated -dump-config file).
It seems like the option available in Flash Builder ought to be accessible through some option on compc or through some combination of arguments. I've looked through the compc options documentation and unfortunately have come up empty. Any help would be appreciated.
Why do you want to do this? The "External / Merged into Code" is really a runtime dependency and there is no runtime for a SWC. When creating a SWF that uses a SWC, the Flex Compiler will automatically optimized out unused classes when creating the SWF.
My objective is to make a SWC that is compatible with client apps with a variety of Flex versions. For instance, when I used the as3commons-logging SWC, it worked with Flex 3.5 projects as well as 4.6 projects. It seems like this is the standard way of distributing SWCs (with external Flex framework linking) and is the default when building from the Flash Builder. When the SWC is compiled with static linking, it makes for a larger SWC and one that results in compile-time errors in newer projects.
@www.Flextras.com I do this all the time: it makes your libraries more lightweight, which is important if you wish to use them as RSL's. The framework classes will be loaded by the main application anyway, so you don't need link them again in your libraries. I never understood why this isn't the default for compc.
First have a look at the flex-config.xml file. You'll find it in [flex_sdk_path]/frameworks/flex-config.xml. Now find the nodes called runtime-shared-library-path. Here you'll find a list of all the libraries that will be merged when you compile with compc (the nodes are called runtime-shared-library-path because RSL is the default linkage when you use mxmlc). These are the files that you need to link externally.
You have two options to do this:
Create your own config file in which you translate all those runtime-shared-library-path nodes to external-library-path nodes. Load this file instead of the default by adding -load-config=my-config.xml to the compiler command.
Keep the default config file but override the linkage with command options. Simply add each swc to the external-library-path: -external-library-path+=libs/framework.swc and so forth.
When you compile an application with mxmlc though, the default linkage is RSL. You may want to override this too and make it 'merged'. In this case you'll first have to reset the RSL path: -runtime-shared-library-path= (that's right, nothing after the =). Then add each swc to the -library-path: -library-path+=libs/framework.swc
Alternatively (warning! shameless self-promotion on the way), you could use a build tool called GradleFx. If you create a build file with just this line:
type = 'swc'
it will compile your library with the framework linked externally. You can override this default if the need be:
type = 'swc'
frameworkLinkage = 'merged'
Thanks RIAstar for the detailed answer. I started poking around with flex-config.xml because I realized that's where the defaults were coming from just before I saw your response, but I didn't know about -load-config or exactly what params to change, so I appreciate the push in the right direction. Let me explore your two recommended options and report back on my progress. Once I understand how to rig compc up myself, I hope to be able to poke around with GradleFx. From what I've checked out, seems neat!
Both options appear to work great! Two questions.. The only hurdle was that Flexrake seems to make a habit of evaluating all paths relative to pwd or the config file being referenced. This prevented option 2 from working out of the box for me since compc complained that libs/framework.swc didn't exist. Fortunately, our build tool allowed us to interpolate in the Flex SDK path. Do you know of a Flex-internal way to do it though? Also, it did not appear to my experimentation that clearing -runtime-shared-library-path made any difference. Is this expected?
@StevenXu 1) I've always used absolute paths; I don't think the compiler can do what you want. 2) You're right, minor mistake of mine: clearing the rsl-path is required if you would like to merge the framework instead of rsl-linking it with mxmlc, it's not required with compc. I suppose you'd rather have to clear library-path, but putting the swcs on the external-library-path seems to already supersede that.
@StevenXu BTW, what is this Flexrake? I've been trying to find information ont it, but couldn't find any.
thanks for clarifying the ecosystem at work. I'm not quite 100% on the semantics of all the configuration settings, but it's making a lot more sense now. RE: Flexrake, sorry I mistyped. I meant to say Flex :). I got the name mixed up with one of our build tools!
| common-pile/stackexchange_filtered |
Oracle regexp to match only digits after certain combination of signs
I have a string which roughly looks like: XXXXXXXXX - 1234567 XXXXXXXX,
where X can be either digit, string or sign (<,>,. or space).
I need to extract only these numbers after ' - '.
I have tried following:
select regexp_substr('17.12.12 <XXXXXXXXXX> - 1234567 <XXXXXXXXXX>','(- )[0-9]{1,7}') from dual
I end up with - 1234567.
How to I get rid of '- '?
Thank you in advance
Why not just use substr() ?
Position of numbers are not fixed
Try select regexp_substr('17.12.12 <XXXXXXXXXX> - 1234567 <XXXXXXXXXX>',' - ([0-9]{1,7})', 1,1,NULL,1) from dual
Thanks @WiktorStribiżew
This should work with Oracle 11g.
Place the capturing group around the pattern part you are interested in first. Since you need the digits, wrap the [0-9]{1,7} with the capturing parentheses.
Then, pass all the 6 arguments to the REGEXP_SUBSTR function where the 6th one indicates the number of capturing group you want to extract:
select regexp_substr('17.12.12 <XXXXXXXXXX> - 1234567 <XXXXXXXXXX>',' - ([0-9]{1,7})', 1,1,NULL,1) from dual
Here, 1,1,NULL,1 means: start looking for a pattern match from Position 1, just for the first match, with no specific regex options, and return the contents of Group 1.
What @Gordon Linoff was trying to say was:
select substr(regexp_substr('17.12.12 <XXXXXXXXXX> - 1234567 <XXXXXXXXXX>','(- )[0-9]{1,7}'), 3)
from dual
Substr the remaining "- " off of your result.
I ended up using sbstr because I had to finish task, but I thought it was a 'work around' and was wondering about proper way to do this :)
@Cezary I completely agree. I have many multiple substr calls (hammer) will have to do for now when a single regex call (screwdriver) would be best because of time.
| common-pile/stackexchange_filtered |
How to achieve drop-shadow with no blur in React Native
I'm new using React Native and I'm trying to map the following component (made in web) but for React Native with no success:
Elevation and shadow properties does not do the trick because they add some blur to the resulting shadow. Which would be the proper way to handle this?
Regards
Use react-native-cardview
import React, { Component } from 'react';
import {
View,
ScrollView,
TextInput,
} from 'react-native';
import CardView from 'react-native-cardview';
import styles from './styles';
export default class Signup extends Component {
render() {
return (
<View style={{ flex: 1, backgroundColor: colors.whiteColor }}>
<ScrollView contentContainerStyle={styles.signupContainer}>
<View style={styles.signupInputs}>
<CardView
style={styles.cardStyle}
cardElevation={2}
cardMaxElevation={2}
cornerRadius={5}
>
<TextInput
underlineColorAndroid="transparent"
style={[styles.signupInput, styles.commonsignupStyle]}
placeholder="Nom *"
placeholderTextColor={colors.primaryColor}
/>
</CardView>
<CardView
style={styles.cardStyle}
cardElevation={2}
cardMaxElevation={2}
cornerRadius={5}
>
<TextInput
underlineColorAndroid="transparent"
style={[styles.signupInput, styles.commonsignupStyle]}
placeholder="Prénom *"
placeholderTextColor={colors.primaryColor}
/>
</CardView>
</View>
</ScrollView>
</View>
);
}
}
Edit:
For dynamic height, two lines or more of text, as asked for in the comments, I had to use another workaround.
https://snack.expo.io/7bVXvbmE0
const Label = () => {
return <View style={{width: 100, height: 50}}>
<View style={styles.topView}>
<Text>Hello world</Text>
<Text>Hi world</Text>
</View>
<View style={styles.shadowView} >
<Text style={{color: 'transparent'}}>Hello world</Text>
<Text style={{color: 'transparent'}}>Hi world</Text>
</View>
</View>;
}
Whatever dynamic text you have on the label, duplicate for the shadow label, but make it transparent. That way you are guaranteed that the shadow follows the top view.
Also, get rid of the hardcoded heights in the styles. For both top view and shadow view, their heights are informed by the text input, and the wrapper container's height is informed by the two views.
Lastly, change shadow view style's top to be just a few points above 0 to make sure you it peeks from under topview. You can adjust borderRadius of the shadow view to fit your preferences.
const styles = StyleSheet.create({
topView: {
width: '100%',
position: 'absolute',
top: 0, backgroundColor: 'white',
justifyContent: 'center',
alignItems: 'center',
borderRadius: 25,
},
shadowView: {
position: 'absolute',
top: 3,
width: '100%',
zIndex: -10,
borderRadius: 17,
backgroundColor: '#ddd'}
});
Previous Post
A little bit hacky, but you can do this if you absolutely don't want any blur.
https://snack.expo.io/pWyPplcm3
const Label = () => {
return <View style={{width: 100, height: 30}}>
<View style={styles.topView}>
<Text>Hello world</Text>
</View>
<View style={styles.shadowView} />
</View>;
}
styles:
const styles = StyleSheet.create({
topView: {
height: 25,
width: '100%',
position: 'absolute',
top: 0, backgroundColor: 'white',
justifyContent: 'center',
alignItems: 'center',
borderRadius: 15,
},
shadowView: {
position: 'absolute',
top: 0,
height: 28,
width: '100%',
zIndex: -10,
borderRadius: 13,
backgroundColor: '#ddd'}
});
Thank you for your time! But I have a question, does this solution is going to work with dynamic height? We may write a component with dynamic text that overflows container and extends to a new line. In that case topView's height will be higher. Regards
As was, not dynamic. I edited the post to fit your needs.
| common-pile/stackexchange_filtered |
Linux SSH database transferring between two databases MySQL
This is the situation: I have server with linux, and there is two databases in it. I need to make a cron job to transfer some data from db1 to db2. The thing is i need this:
db1->table1->column1 + db1->table1->column2 + db1->table2->column1 TRANSFER TO db2->table1(create table) with these three fields. Can anyone help me to form a proper cron job command? I know how to transfer tables between databases, but this is far more complicated.
Your question is not accurate enough: apart the cronjob, you must first define which programming language you'll use, write and test your transfer script. Then it's pretty easy to transform it as a cronjob.
Sorry, i want to use pure mysql. I mean i want to write linux command wich i will you as cron job to transfer mentioned data. I managed to write this by myself:
CREATE TABLE testas.test SELECT pgs_id, pg_id_t, kodas, pavad, if(del_date IS NOT NULL, 1, if(rod_int<>1, 2, 0)) FROM 9001_komeksimas.pg_seima INNER JOIN 9001_komeksimas.pg_zodynas ON 9001_komeksimas.pg_seima.pgs_id=9001_komeksimas.pg_zodynas.pg_id; But now i need a linux command to use it as cron job :)
Partial duplicate of this.
In command line there are (at least) two ways to achieve this :
mysql -u[user] -p[pass] -e "[mysql commands]"
or :
mysql -u[user] -p[pass] <<QUERY_INPUT
[mysql commands]
QUERY_INPUT
Put your command "CREATE TABLE testas.test ..." instead of [mysql commands],
Save this into a bash script "myscript" :
#!/bin/bash
user=$1
pwd=$2
mysql -u"$user" -p"$pwd" <<QUERY_INPUT
[mysql commands]
QUERY_INPUT
Make it executable by the crontab user
chmod +x myscript
Then it depends on the distro you're using for the cronjob.
For example in Debian's-like distro, you don't need to do anything else than putting your script into the right directory. For example, il you wish the script to be run daily, move the file into /etc/cron.daily.
Just take care in this case not to forget to call the cronjob with the 2 datas user and pwd :-)
| common-pile/stackexchange_filtered |
Martin: The apartness approach seems backwards at first - defining when points are separate rather than when they're close. But I'm starting to see why Bishop found classical topology inadequate constructively.
Stephen: Exactly. When we can only prove that two points aren't equal by exhibiting a concrete separation, apartness becomes the natural primitive. Consider how in metric spaces, $x \bowtie S$ when the distance from $x$ to $S$ is positive - that's directly verifiable.
Martin: That makes the axiom A5 crucial then. If $x$ is apart from set $A$, and $y$ can't be distinguished from $x$, then $y$ should also be apart from $A$. But this fails without some form of decidability.
Stephen: Right, and that's where Markov's principle enters. Take the real line with denial inequality versus metric inequality. With the metric, A5 holds naturally because distances are positive real numbers. But with denial inequality, proving A5 requires Markov's principle to decide whether a real number is zero or positive.
Martin: So topological consistency becomes | sci-datasets/scilogues |
How to open powerpoint from Windows 8.1 app
I am trying to build an windows 8.1 app that open powerpoint file from local computer in full screen, and within that it contain three buttons to perform next ,previous and exit. I was able to do so using winform but not in WPF. In winform I used panel control in which I embedded the ppt. panel is replaced by canvas in WPF but I do not know how I can embed ppt in it. is there any other approach than this please share? I can not use XPS as it does not support any animation.
//System.Diagnostics.Process.Start("POWERPNT.EXE", "C:/Users/SAURABH/Desktop/office/Engineer's.pptx");
// Microsoft.Office.Interop.PowerPoint.Application application;
// // For Display in Panel
// IntPtr screenClasshWnd = (IntPtr)0;
// IntPtr x = (IntPtr)0;
// application = new Microsoft.Office.Interop.PowerPoint.Application();
// Microsoft.Office.Interop.PowerPoint.Presentation presentation = application.Presentations.Open(@"C:\Users\delink\Documents\SAMPLE_PPT.pptx", MsoTriState.msoTrue, MsoTriState.msoTrue, MsoTriState.msoFalse);
// pptViewPanel.Children.Add(application as Control);
// //pptViewPanel.Controls.Add(application as Control);
// Microsoft.Office.Interop.PowerPoint.SlideShowSettings sst1 = presentation.SlideShowSettings;
// sst1.LoopUntilStopped = Microsoft.Office.Core.MsoTriState.msoTrue;
// Microsoft.Office.Interop.PowerPoint.Slides objSlides = presentation.Slides;
// sst1.LoopUntilStopped = MsoTriState.msoTrue;
// sst1.StartingSlide = 1;
// sst1.EndingSlide = objSlides.Count;
// // pptViewPanel.Dock = DockStyle.Fill;
// sst1.ShowType = Microsoft.Office.Interop.PowerPoint.PpSlideShowType.ppShowTypeKiosk;
// Microsoft.Office.Interop.PowerPoint.SlideShowWindow sw = sst1.Run();
// //sw=Objssws
// oSlideShowView = presentation.SlideShowWindow.View;
// IntPtr pptptr = (IntPtr)sw.HWND;
// SetParent(pptptr, pptViewPanel.handle);**"**this where I am getting-"in 'pptviewpanel.handle'"** rror"**
You could convert your presentation to a video format on-the-fly:
// not tested as I don't have the Office 2010, but should work
private string GetVideoFromPpt(string filename)
{
var app = new PowerPoint.Application();
var presentation = app.Presentations.Open(filename, MsoTriState.msoTrue, MsoTriState.msoTrue, MsoTriState.msoFalse);
var wmvfile = Guid.NewGuid().ToString() + ".wmv";
var fullpath = Path.GetTempPath() + filename;
try
{
presentation.CreateVideo(wmvfile);
presentation.SaveCopyAs(fullpath, PowerPoint.PpSaveAsFileType.ppSaveAsWMV, MsoTriState.msoCTrue);
}
catch (COMException ex)
{
wmvfile = null;
}
finally
{
app.Quit();
}
return wmvfile;
}
And then you would play it with MediaElement:
<MediaElement Name="player" LoadedBehavior="Manual" UnloadedBehavior="Stop" />
public void PlayPresentation(string filename)
{
var wmvfile = GetVideoFromPpt(filename);
player.Source = new Uri(wmvfile);
player.Play();
}
Don't forget to File.Delete(wmvfile) when you're done playing the video!
Thanx but I need it to interact with user means user can toggle b/w next and previous slide
I am afraid, you may need to create the slides inside the application itself as controls using next/previous button. Else why don't you just open the ppt file from the application?
If you're ready to spend some time for this, give this article a read : http://www.codeproject.com/Articles/118676/Embedding-PowerPoint-presentation-player-into-a-WP
it helped....but now I am facing another issue now . I can not set buttons over the open ppt . buttons do showed up as I start application but when I launch ppt all over the screen taken by slide . I want to set buttons over it so that I can control ppt and also ppt animation does not work.
| common-pile/stackexchange_filtered |
Coming "down" or "up" (traveling from one place to another)
In English (at least US English), it is common to use "up" and "down" when giving directions. For example:
When are you coming down to visit us?
I went up to see him for the weekend.
The "up" and "down" can refer to either north/south or higher/lower elevation. Are there equivalent terms in Spanish? What would be the most natural translation of sentences like these?
Not only you can use subir and bajar in the same situations, but you can say Subir [bajar] por la calle Velázquez to mean you walked it in ascending [descending] house number order.
Si alguien vive en la montaña y va hacia un valle, es común (coloquialmente) decir:
"¿Cuándo vas a bajar a visitarnos?"
exactamente lo mismo vale para "subir"
WRT the Notrth-South orientation, depends on the region, but yes, I've heard it many times (but more colloquial yet than the previous usage)
Edit
However, the common use to add "up" or "down" to round up the sound of some verbs in English hasn't a correlation in Spanish.
| common-pile/stackexchange_filtered |
"Invalid security token" while using urllib2
I am trying to get the content of a http request using a python script. But I am receiving
Invalid security token error while executing it.
Here is the following snippet
#!/usr/bin/python
import urllib2
username="username"
password="password"
url='some_url'
def encodeUserData(user, password):
return "Basic " + (user + ":" + password).encode("base64").rstrip()
req = urllib2.Request(url)
req.add_header('Accept', 'application/json')
req.add_header("Content-type", "application/json")
req.add_header('Authorization', encodeUserData(username, password))
# make the request and print the results
print res.read()
Username and password has special characters.
.encode("base64") is no text encoding. Could you explain what you are trying to do with the function encodeUserData ?
I am trying to encode my user name and password
You can follow this: https://docs.python.org/3/library/base64.html and just need to make your words as byte: base64.b64encode(b'username' + b":" + b'password'). Is this helping you?
@giosans I guess I am doing something wrong otherthan the encoding stuff. It is not working.
@snakecharmerb Here's the header
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3 Accept-Encoding: gzip, deflate, br Accept-Language: en-US,en;q=0.9 Cache-Control: max-age=0 Connection: keep-alive Host: <host_url> Sec-Fetch-Mode: navigate Sec-Fetch-Site: none Sec-Fetch-User: ?1 Upgrade-Insecure-Requests: 1 User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36
@sriramsm04 Right. I suggested that because the invalid security token makes me think about auth issues, therefore this bit encodeUserData(username, password).
@giosans curl -H "Authorization:Basic <token>" - X GET "<url>"
I am able to do this in bash. Can you help me out with a python script? I have tried both requests and urllib2 modules.
@sriramsm04 I did the same in curl and python and all options work for me, which I wrote as answer.
Given that you are able to successfully run the request with curl on bash, and get <Response [200]>, you should be able to run it in python-2.7 with both requests and urllib2. In fact, I just tried and the following works for me:
# with requests
import requests
username="username"
password="password"
url='https://url.html'
def encodeUserData(user, password):
return "Basic " + (user + ":" + password).encode("base64").rstrip()
response = requests.get(url, headers={'Authorization': encodeUserData(username, password)})
print response.content
If you want to use urllib2, this also works.
# with urllib2
import urllib2
username="username"
password="password"
url='https://url.html'
def encodeUserData(user, password):
return "Basic " + (user + ":" + password).encode("base64").rstrip()
req = urllib2.Request(url)
req.add_header('Authorization', encodeUserData(username, password))
res = urllib2.urlopen(req)
print res.read()
If this does not work, I would suggest you to substitute username and password with the encoded line directly, and see if that would work.
| common-pile/stackexchange_filtered |
How should we deal with ill-founded questions?
Inspired by this question on the parent site.
Somewhat related to this meta question, but people who ask ill-founded questions are not necessarily cranks.
People will continue to ask questions like "how do I prove X?" for false statements X. What is the best way to deal with such questions?
They should be answered with a proof or explanation of why X is false/unprovable.
They should be closed as "not a real question," because they demand the impossible.
I'd say answering in the comments is best. If the question was well-thought out and well-written, I'm sympathetic; in this case, since there is no motivation for the question, my inclination is to close it.
| common-pile/stackexchange_filtered |
Msfvenom format specifier
In msfvenom what does it mean exactly when i specify the format to C or Python? And what is the format 'raw' for? I know, when the format is psh-cmd it runs in the command prompt and when it is exe it runs as a normal executable, what about the others?
msfvenom -p windows/shell/reverse_tcp -f c
C and python are other programming languages.
psh_cmd is a powershell (programming language)
and exe is simply a compiled executable.
| common-pile/stackexchange_filtered |
"No default Matlab path found" When trying to install packages
I'm on an academic license for using mathematica, so I need to be connected to my institute network through the VPN. By while installing i get the error.
I tried to run following command: sudo apt-get install openvpn
Reading package lists... Done
Building dependency tree
Reading state information... Done
openvpn is already the newest version (2.3.10-1ubuntu2.2).
The following packages were automatically installed and are no longer required:
libdbusmenu-gtk4 linux-headers-4.4.0-128 linux-headers-4.4.0-128-generic
linux-image-4.4.0-128-generic linux-image-extra-4.4.0-128-generic
Use 'sudo apt autoremove' to remove them.
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
1 not fully installed or removed.
After this operation, 0 B of additional disk space will be used.
Do you want to continue? [Y/n] y
Setting up matlab-support (0.0.21) ...
No default Matlab path found. Exiting.
dpkg: error processing package matlab-support (--configure):
subprocess installed post-installation script returned error exit status 1
Errors were encountered while processing:
matlab-support
E: Sub-process /usr/bin/dpkg returned an error code (1)
A window is always popping up where i have to define the path for matlab.
openvpn is already installed and up to date. The matlab error is unrelated. See below for an answer.
To use the matlab-support package, you need to download and install matlab.
If matlab is installed, run the following command to show your matlab path:
which matlab
This is the path you will need to input when you get the popup window.
If matlab is not installed, you have two options. Option one: you could install matlab (download and unzip the installer and then run the "install" file, you may need to use sudo to run the file). Option two: you could uninstall the matlab-support package.
sudo apt remove matlab-support
As for the VPN package, openvpn is already installed and up to date. The installation error is unrelated.
thank you thank you, your this command sudo apt remove matlab-support helped me to get rid of matlab support that was the main blockage to update my system and i face same issue when update the system as shown in the question
| common-pile/stackexchange_filtered |
How to flush the serial port struct serial_icounter_struct
I am working on serial communication with linux driver. In which I am using tcflush() call with TCIOFLUSH to flush port.
Also I am using serial_icounter_struct to get the port statistics of rx,tx,parity,overrun etc.
I want to clear the serial_icounter_struct when I do tcflush() with TCI0FLUSH, but it is flusing the tx and rx hardware buffer,but not clearing the serial_icounter_struct. I am still getting the previous tx and rx counts from serial_icounter_struct.
Could someone please help on flushing the serial_icounter_struct port statistics?
Thanks.
| common-pile/stackexchange_filtered |
How to work with third-party libraries when doing unit-testing?
I'm a newbie when it comes to unit-testing, I've tried to do a unit-test with Karma and Jasmine from an app that already existed.
Basically the app has a lot of dependencies from different third-party libraries being used. So when I tried to create a unit-test a stumbled upon a lot of errors from Karma/Jasmine. One of them is the screenshot below:
From the screenshot, I'm getting an unknown provider: socketFactoryProvider, which I've traced down and found out that it belongs to the btford.socket-io module. So what I've did was to have a code like this to mock the dependencies:
// Set the app module
beforeEach(function () {
angular.module('btford.socket-io', []);
module('opensportsAdmin');
});
But I'm still getting an error (based on the screenshot).
So my question is, how can you work with third-party libraries for your unit-test? I'm kind of new and didn't find any articles that can help me with my problem.
Here's a reference to my code.
you need to inject socketFactory before test case starting.
But I'm not using a socketFactory in my controller. It was being used by the third-party library itself.
The best practice is to use one internal module for your app and one module for dependencies.
detailed explanation and example here:
Truly mocking providers
| common-pile/stackexchange_filtered |
Did Swami Vivekananda ever write a book called Gnana deepam?
So, I found these suspicious pictures in twitter.
Christian preachers and missionaries are badly needed for India. Let them come here in hundreds and thousands. Teach us about the Holy life and history of JESUS. Let His spiritual teachings penetrate the heart of our society. Preach in every nook and corner about JESUS CHRIST…. (Swami Vivekananda Part 1, page 128-129 Gnana Deepam)
If you want Mukthi (Salvation) follow JESUS.....is in the top most priority than any other GOD you can imagine ("Gnana Deepam", part-7, page 294)
After searching web I found some old dead links to a tamil book Gnana deepam by vivekananda (not sure if this is the Swami Vivekananda), published in 1963. Unfortunately, I cannot find copy of this book.
Can someone verify the legitimacy of these quotes?
Swami Vivekananda Actually criticized Christian missionaries for ignoring the needs of starving millions in India. He further stated in Chicago that " He said that the people did not need missionaries to preach to them or to build more churches; there was already a surfeit of religion in the East. Thousands had perished out of hunger but the Christians had ignored them" See Religion not the crying need of India .So the quotes look dubious at first glance
no, he didn't. I have read his Complete Works and never found any such thing.
bogus. Vivekananda was highly critical of the Christian missionaries. There is no book that he wrote that you refer to. If you refer to Vol 3 of his Complete Works, Lectures from Colombo to Almora, he, in fact, says that only the through the Santana Dharma can moksha be achieved.
OK, these pictures are fake. Thanks everyone for commenting.
https://www.amazon.in/Swami-Vivekanandarin-Gnana-Deepam-volumes/dp/B077YGD84H copy of the book, just found this
Brother, the words in this pictures are not at all fake , all are original, even twenty years back I was searched this book to clarify the same doubt, but book was not available in the market, that printing was stopped because so many people can be accepted Jesus as a god, so some religious leader got the rights of the book and stopped the book
But original copy of old printing was available in some old library and in some Ministry hands
You just think about it
If it is not a original quote from that book itself
Religious people will go to court and file a case against them surely, but why it was not happening till now ( past 50 years)
So try to find out a original copy of this book, and if this book was not available in the market, just ask a question for you, why this book was blocked, then you find a reality
(Swami Vivekananda Part 1, page 128-129 Gnana Deepam)
| common-pile/stackexchange_filtered |
BeautifulSoup4: Missing Parsed Table Data
I'm trying to extract the Earnings Per Share data through BeautifulSoup 4 from this page.
When I parse the data, the table information is missing using the default, lxml and HTML 5 parsers. I believe this has something to do with Javascript and I have been trying to implement PyV8 to transform the script into readable HTML for BS4. The problem is I don't know where to go from here.
Do you know if this is in fact my issue? I have been reading many posts and it's been a very big headache for me today. Below is a quick example. The financeWrap includes the table information, but beautifulSoup shows that it is empty.
import requests
from bs4 import BeautifulSoup
url = "http://financials.morningstar.com/ratios/r.html?t=AAPL®ion=usa&culture=en-US"
response = requests.get(url)
soup_key_ratios = bs(response.content, 'html5lib')
financial_tables = soup_key_ratios.find("div", {"id":"financeWrap"})
print financial_tables
# Output: <div id="financeWrap">
# </div>
@Begueradj That is a funny observation. I've found that normally if you look hard enough you can find the answer!
@BryceDoganer Tag your question with beautifulsoup. It will help you to receive a good answer quickly.
Perhaps I'm missing something, but is there any reason why http://...en-US isn't quoted as a string?
@alexwlchan in my code it is in quotes, I forgot to add it here. It has been edited
use chrome visit: view-source:http://financials.morningstar.com/ratios/r.html?t=AAPL®ion=usa&culture=en-US, you will found that bs4 is nothing wrong
That is to say, the website display the data use Javascipt, you should find where it is and analysis the js code
The issue is that you're trying to get data that is coming in through Ajax on the website. If you go to the link you provided, and looked at the source via the browser, you'll see that there should be no content with the data.
However, if you use a console manager, such as Firebug, you will see that there are Ajax requests made to the following URL, which is something you can parse via beautifulsoup (perhaps - I haven't tried it or looked at the structure of the data).
Keep in mind that this is quite possibly against the website's ToS.
Great! This is what I want to say.
@Duniyadnd Thank you for pointing that out. I figured it had to be related to something along those lines, I just didn't know how to find the request links. I'm going to look into Firebug and also see about the ToS.
| common-pile/stackexchange_filtered |
Prove that for all positive integers n, $20^{2n} + 16^{2n} −3^{2n} −1$ is a multiple of 323
Prove that for all positive integers n, $20^{2n} + 16^{2n} −3^{2n} −1$ is a multiple of 323
I tried to prove by induction, no luck
Step 1: Base Case (n = 1)
$20^{2(1)} + 16^{2(1)} - 3^{2(1)} - 1$
$= 646$
The expression is divisible by 323 when n = 1
Step 2: Inductive Hypothesis
Assume that for some positive integer k, the expression $20^{2k} + 16^{2k} - 3^{2k} - 1$ is divisible by 323.
Step 3: Inductive Step
Consider the expression for k+1:
$20^{2(k+1)} + 16^{2(k+1)} - 3^{2(k+1)} - 1$
We can rewrite it as follows:
$20^{2(k+1)} + 16^{2(k+1)} - 3^{2(k+1)} - 1$
$= (20^2)^{k+1} + (16^2)^{k+1} - (3^2)^{k+1} - 1$
$= (400)^{k+1} + (256)^{k+1} - (9)^{k+1} - 1$
We assumed that:
$20^{2k} + 16^{2k} - 3^{2k} - 1$ is divisible by 323.
So, we can write it as:
$20^{2k} + 16^{2k} - 3^{2k} - 1 = 323m$ for some integer m.
$400^{k} + 256^{k} - 9^{k} - 1 = 323m$
Now, we can substitute this into our expression for k+1:
$(400)^{k+1} + (256)^{k+1} - (9)^{k+1} - 1$
What have you tried? show your attempts.
Have you considered breaking it down into sub-problems? $323$ has a prime factorization of $17\times 19$, so if $323|x$, then $17|x$ and $19|x$. Those numbers are much easier to work with; furthermore, you might find it profitable to write $20, 16$ and $3$ as $17k+r$ and $19k+r$ for some integers $k$ and $r$ and making use of the binomial theorem... no messy induction argument required.
First reduce your expression modulo 19 and check it always divides 19. Second reduce it modulo 17 and check it always divides 17.
Exploit innate $\rm\color{#c00}{symmetry}$ as in linked dupe.
$\tag*{}$
$\qquad\phantom{\Rightarrow}\ \ { 20^2,\ \ \ \ 16^2}\ \equiv, {3^2,\ \ \ 1^2}\ \ \ \ {\rm mod},\ 17,19,\ \ $
$\tag*{}$
$\qquad\Rightarrow\ {20^{2k},\ \ 16^{2k}} \equiv {3^{2k},\ ,1^{2k}}\ \ \ {\rm mod},\ 17,19,\ \ $ by the Congruence Power Rule
$\tag*{}$
$\qquad\Rightarrow\ \ 20^{2k} + 16^{2k}\ \ \equiv \ 3^{2k}+ 1^{2k}\ \ \ \ {\rm mod},\ 17,19,\ \ $ so also $,{\rm mod}\ 323 = {\rm lcm}(17,19)$ by CCRT.$\ \ $
Please search for answers before posting questions, e.g. here searching on "323 20" quickly finds many dupes. See the sidebar "Linked" questions in the dupes for many more worked examples.
Assuming you know congruence theory this exercise is pretty straightforward, i.e:
From $20=17+3=19+1$ and $16=17-1=19-3$ you get
$\begin{cases}
20^{2n}+16^{2n}-3^{2n}-1\equiv (+3)^{2n}+(-1)^{2n}-3^{2n}-1\equiv 0\pmod{17}\\
20^{2n}+16^{2n}-3^{2n}-1\equiv (+1)^{2n}+(-3)^{2n}-3^{2n}-1\equiv 0\pmod{19}
\end{cases}$
So the expression is simultaneously divisible by $17$ and $19$ and consequently by $323$.
Now if you have never heard of modulo, just consider (for $n\ge 1$) the binomial expansion of
$\begin{align}(m+a)^n&=a^n+\binom{n}{1}a^{n-1}m+\binom{n}{2}a^{n-2}m^2+\cdots+m^n\\&=a^n+m\times(\cdots)\end{align}$
You can see that in the division by $m$ the terms $(m+a)^n$ and $a^n$ have the same remainder (i.e. their difference is a multiple of $m$); we say they are equivalent relatively to the division by $m$.
Considering $m=17$ and $a=3$ then $20^{2n}$ and $3^{2n}$ are equivalent and get cancelled by the trailing term $-3^{2n}$ in the expression.
Similarly with $a=-1$, it get cancelled thanks to the even exponent and the trailing term $-1$.
And we can say the same for $m=19$.
If you really prefer induction, then if it advisable to take advantage of the facts seen above.
$\begin{align}20^{2n+2}+16^{2n+2}-3^{2n+2}-1
&=20^{2n}(17+3)^2+16^{2n}(17-1)^2-9\times 3^{2n}-1\\
&=17\times(\cdots)+9\times 20^{2n}+16^{2n}-9\times 3^{2n}-1\\
&=17\times(\cdots)+9\times (\underbrace{20^{2n}-3^{2n}}_\text{divisible by 17}) + (\underbrace{16^{2n}-1}_\text{divisible by 17})\\
\end{align}$
But you see that you have to carry out a double hypothesis of divisibility by $17$ and not just a single one under the form of a sum which makes it more intractable.
Please strive not to post more (dupe) answers to dupes of FAQs, cf. recent site policy announcement here. Note that this dupe is very easy to find, e.g. search on "323 20".
Expanding my comment into an answer:
$323$, being much larger than any of the numbers in the given expression, is unwieldy to work with. It is better to make use of its prime factorization — which is $17\times19$ — and the fact that a number is divisible by $323$ if and only if it is simultaneously divisible by $17$ and $19$. Here's how that proof goes.
Working with $17$ first, rewrite $20$ as $17+3$ and $16$ as $17-1$. It would be awkward to rewrite $3$ in this way however, so we shall leave it alone. Next, consider the binomial expansion of $(17+3)^{2n}$ and its reduction modulo $17$. It is not too hard to see that all but one of the terms in the expansion contain at least one factor of $17$; thus, the remainder modulo $17$ is simply $3^{2n}$. That cancels out with the $-3^{2n}$, conveniently enough. Next, consider the binomial expansion of $(17-1)^{2n}$. By exactly the same argument, the remainder of this expansion modulo $17$ is nothing but $(-1)^{2n}$. Since $(-1)^m=1$ for all even numbers $m$, and $2n$ is even for all values of $n$, we have that $(-1)^{2n}=1$ for all values of $n$. This cancels out with the $-1$ in the given expression; thus the entire sum is congruent to $0 \mod(17)$, proving that it is divisible by $17$ for all values of $n$.
The other case proceeds in exactly the same way. Rewrite $20$ as $19+1$ and $16$ as $19-3$, then consider the reduction of $(19+1)^{2n}$ and $(19-3)^{2n}$ modulo $19$: all but one term of $(19+1)^{2n}$ contains at least one factor of $19$, leaving $1^{2n}=1$ as the remainder; this cancels with the $-1$ in the given expression. Likewise, all but one term of $(19-3)^{2n}$ contains a factor of $19$, leaving $(-3)^{2n}$ as the remainder; furthermore, just as $(-1)^{2n} = 1^{2n}$ for all values of $n$, $(-3)^{2n} = 3^{2n}$ for all values of $n$, which means that it cancels with the $-3^{2n}$ in the original expression. Thus the original expression is congruent to $0 \mod(19)$ for all values of $n$.
We have successfully proved that for all values of $n$, $20^{2n}+16^{2n}-3^{2n}-1$ is congruent to $0$ modulo $17$ and $19$, which by definition means that it is congruent to $0$ modulo $323$. Thus the claim is proved. All without induction!
Please strive not to post more (dupe) answers to dupes of FAQs, cf. recent site policy announcement here. Note that this dupe is very easy to find, e.g. search on "323 20".
| common-pile/stackexchange_filtered |
Finding a frame for a vector bundle in a smooth manifold with a connection
I am trying to solve the following exercise:
Let $P$ be a vector bundle over a smooth manifold $M$ with a connection $\nabla$, and let $p \in M$ . Show that there is an open set $U$ of $M$ with $p \in U$ and a frame $E_1, \ldots, E_k$ of $P$ defined in $U$ such that for all $v \in T_pM, \nabla_v \ E_i = 0$, for $i \in \{1, \ldots, k\}$.
However, I am not sure how to begin, and I would like some sort of hint, if possible - how would one define such a frame? Is there some intuitive way of doing it?
Thank you in advance.
Please improve your title so that it describes exactly what your question is. This will help future users find your question and will also help your question receive more answers.
I don't understand how the riemannian structure intervenes in the question. Could you elaborate on this?
You're right, it actually doesn't. I'll edit accordingly.
Work over a coordinate patch $U$ around $p$ with local coordinates $\phi:U\xrightarrow{\sim\,}\Bbb R^n$ ($n$ is the dimension of $M$). Take a basis $(e_1,\dots,e_r)$ a basis of the ($r$-dimensional) vector space $P_p$. Extend it to a local basis of $P|_U$ by the formula
$$\forall q\in U,\,E_i(q)=\mathrm{PT}^\nabla_{\gamma_{q}}(e_i)$$
Where $\mathrm{PT}^\nabla_\gamma$ is parallel transport (in the sense of $\nabla$) along a path $\gamma$, and $\gamma_{q}:[0,1]\to M$ is the path connecting $p$ to $q$ defined by
$$\phi(\gamma_{q}(t))=\phi(p)+t(\phi(q)-\phi(p))$$
$(E_1,\dots,E_r)$ form a basis of sections of $P$ over $U$, and you can check (almost by definition) that $\left(\nabla E_j\right)_p=0$.
Can you point out a reference in which I can find a proof of existence of parallel transport in an arbitrary vector bundle? (So far I've seen it only for the tangent bundle.) And thank you for your answer.
@sylvia You'll find it in these notes: http://webusers.imj-prg.fr/~vincent.minerbe/m2dg.pdf (page 41 and onwards). The gist is that parallel transport along a fixed curve obeys a first order linear differential equation, and thus exists and is smooth in the parameters (i.e. the curve and the starting vector).
| common-pile/stackexchange_filtered |
convert List of hashmap into set
i want to cast List<HashMap<String, Object>> into Set<StudentInfo>
i have method
public List<HashMap<String,Object>> getStudentData(studentId);
i want to convert the result into Set so i used
Set<StudentInfo> studentFilteredInfo = new HashSet<>();
List<Map<String, Object>> studentCompleteRecord = getStudentData(1005);
studentFilteredInfo.addAll((Collection<? extends StudentInfo>studentCompleteRecord ));
initially when i executed on localhost it with java 8, eclipse and tomcat 8 it is working fine.
when i tried to build it with maven
mvn clean package
it will through an Error:
incompatible types: java.util.List<java.util.Map<java.lang.String,java.lang.Object>>
cannot be converted to java.util.Collection<? extends com.school.model.StudentInfo>
That never worked. That does not even compile.
Casting isn't just magic, seems like you are trying to convert between two completely incompatible types. You need some way to convert your Map<String,Object> into a StudentInfo
i know. i also used to do that using loop or iterator. but eclipse suggested me this and i tried it. i wondered it is working.
it is still working correctly but when i deployed it on my cloud environment it it uses maven to build and it through error.
You are mistaken: there is no casting from List<Map<String, Object>> into some Set<Whatever>!
Casting basically means: you know that some "Object" has a more specific type; thus you tell the compiler: "you can safely assume that this thingy here is something else in reality".
But that means: in reality (at runtime), that "thingy" really is "something else"! And alone the generic types that you provide in your question make it very clear: you can't be doing a cast here!
In other words: you have to write code that iterates your List of Maps; to extract that information that is required to create new StudentInfo objects. Then you collect those newly created objects; and put them into a new Set; which you then can return from your method!
And finally: always avoid "concrete" implementation types; you used List<HashMap<... - instead, you should go for List<Map<... !
You need to write code to explicitly convert a Map<String,Object> to a StudentInfo instance. Suppose StudentInfo has a method like this:
static StudentInfo create(Map<String, Object> info) {
String name = info.get("name");
Transcript transcript = info.get("grades");
return new StudentInfo(name, transcript);
}
Then you would need to iterate over each element in the list and use your method to convert the Map instances to StudentInfo objects.
With lambdas:
Set<StudentInfo> studentFilteredInfo = studentCompleteRecord.stream()
.map(StudentInfo::create)
.collect(Collectors.toSet());
Without lambdas:
Set<StudentInfo> studentFilteredInfo = new HashSet<>();
for (Map<String,Object> e : studentCompleteRecord)
studentFilteredInfo.add(StudentInfo.create(e);
| common-pile/stackexchange_filtered |
Ember simple auth tests failing intermittently
I am struggling to debug failing tests on an Ember 3.0 app. I have a login form using ember-simple-auth. The authenticate action looks like this:
let { identification, password } = this.getProperties('identification', 'password');
this.get('session').authenticate('authenticator:devise', identification, password)
.catch((reason) => {
this.set('loginError', reason.errors || reason);
});
My test simply fills in the form and clicks a button to trigger this action, then checks a user is logged in:
invalidateSession();
await visit('/');
fillIn('#identification', 'test@email.com');
fillIn('#password', 'secret');
await click('.login-btn');
let sesh = currentSession();
let isAuthed = get(sesh, 'isAuthenticated');
assert.equal(
isAuthed,
true,
'after a user submits good creds to login form, they are logged in'
);
Using a Mirage backend, this works every time. However, using a Rails API which returns the same response, this test fails about half the time. It seems to be random whether it will pass or fail.
I'm not sure where the problem is here. The Rails app is running locally on port 3000 so it is not a network issue. I wonder if the test is timing out because the API takes longer to respond than Mirage - although this does seem unlikely as the tests run in under a second. Has anyone encountered a problem like this?
Thanks
My hunch is that you may be evaluating isAuth before ember-simple-auth has completed authenticating with the backend. For my tests that are similar to yours, I have await settled(); after await click();.
If that doesn't do the trick then you could try using waitFor or waitUntil from the ember-test-helpers to make sure that authentication has finished.
Glad to help. :-)
| common-pile/stackexchange_filtered |
Router-outlet not appearing below navbar module
I am trying to create a website using angular. I am done with the navbar, but when I try to add the next module, it is not appearing under the navbar module.
The app.component.html looks like this:
<app-navbar></app-navbar>
<router-outlet></router-outlet>
And my homepage.component.html looks like this:
<h2>homepage component works!!</h2>
app-routing.component.ts:
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomepageComponent } from './pages/homepage/homepage.component';
const routes: Routes = [{
path: 'home',
component: HomepageComponent
},
{
path: '',
redirectTo: 'home',
pathMatch: 'full'
}];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
When I change my navbar template to this:
<h2>Navbar works!!</h2>
the homepage component is appearing below the navbar, as it should. But when I add my styling to the navbar, it no longer appears under the navbar, appearing in the wrong position. This is the designed navbar template:
<div class="absolute inset-x-0 top-0 z-50 bg-gradient-to-b from-orange-400 to-[#e1d471]">
<nav class="flex items-center justify-between p-6 lg:px-8 " aria-label="Global">
<!-- Logo -->
I am using TailwindCSS for styling. What could be the problem, and how can I fix this?
I am trying to create a homepage for a product, but the homepage is not appearing under the navbar. Instead, it is appearing behind the navbar.
Have you declared the HomepageComponent in the declarations:[] array in the app.module.ts?
@Prav Yes, I have declared the HomepageComponent
Does it show the HomepageComponent HTML in the Inspect tool? Can you also try updating the RouterModule? RouterModule.forRoot(routes, { useHash: false })
Based on your explanation, the content of <router-outlet> does show up on the page; albeit in the wrong place. So, it is not Angular issue; let alone Angular routing. And looking on your screen shot, you have some CSS applied.
The next step would be to turn off all CSS and confirm that you get your home component HTML under the navbar content. If you get that, then start analyzing CSS of the home component. In case you have CSS inside Home component - remove it. If you have questions, probably worth tagging it with CSS.
| common-pile/stackexchange_filtered |
Restrict access to admin area by IP
What is the best way to restrict the access to the admin area by IP in Magento? Bear in mind that admin can work either from /admin or index.php/admin
You can place the following codes into your .htaccess file:-
RewriteCond %{REQUEST_URI} ^/(index.php/)?admin/ [NC]
RewriteCond %{REMOTE_ADDR} !^1\.1\.1\.1
RewriteRule ^(.*)$ http://%{HTTP_HOST}/ [R=302,L]
Where <IP_ADDRESS> is your IP address.
* For the last line, make sure that there's no spacing between http:// and %{HTTP_HOST}/. StackExchange doesn't allow the code http://% to be posted so I have to add a spacing in between.
This code redirect from admin pages with slash after admin (admin/) and with something after the slash (admin/abc). But admin page is still loaded on "myeshop.com/admin". Is better to use rule without last slash (RewriteCond %{REQUEST_URI} ^/(index.php/)?admin [NC]) to prevent page loading
In case anyone uses Nginx:
location ~* ^/(index\.php/bcknd|bcknd) {
allow <IP_ADDRESS>;
try_files $uri $uri/ /index.php?$args;
location ~* \.php$ { try_files /dummy @proxy; }
deny all;
}
Multiples are handled by adding another match line
RewriteCond %{REQUEST_URI} ^/(index.php/)?admin(.*) [NC]
RewriteCond %{REMOTE_ADDR} !^10\.1\.1\.10
RewriteCond %{REMOTE_ADDR} !^10\.2\.1\.10
RewriteRule .* - [F,L]
Basically it translates to if this url regex, and not these addresses, then 403, you're out of here.
Just reading the documentation: If you specify F then L is implied.
https://httpd.apache.org/docs/2.4/rewrite/flags.html.
"When using [F], an [L] is implied - that is, the response is returned immediately, and no further rules are evaluated."
You can also set up "allow from" rules in the httpd config for the virtual host files. I would also change the admin URL for additional security (ok kind of redundant with the "allow from"s but belt and braces).
Inside the conf file I do something like this:
<Location /index.php/mynewadminname>
Order deny,allow
deny from all
#home
allow from <IP_ADDRESS>
#office
allow from <IP_ADDRESS>
</Location>
<Location /mynewadminname>
Order deny,allow
deny from all
#home
allow from <IP_ADDRESS>
#office
allow from <IP_ADDRESS>
</Location>
Where <IP_ADDRESS> and <IP_ADDRESS> are two allowed IP addresses. Might be an alternative.
Allow admin access by ip
RewriteCond %{REMOTE_ADDR} !^10\.125\.192\.50
RewriteCond %{REMOTE_ADDR} !^10\.125\.192\.50
RewriteCond %{REQUEST_URI} admin [NC]
RewriteRule ^(.*)$ / [F,L]
| common-pile/stackexchange_filtered |
How to loop through pandas df column, finding if string contains any string from a separate pandas df column?
I have two pandas DataFrames in python.
DF A contains a column, which is basically sentence-length strings.
|---------------------|------------------|
| sentenceCol | other column |
|---------------------|------------------|
|'this is from france'| 15 |
|---------------------|------------------|
DF B contains a column that is a list of countries
|---------------------|------------------|
| country | other column |
|---------------------|------------------|
|'france' | 33 |
|---------------------|------------------|
|'spain' | 34 |
|---------------------|------------------|
How can I loop through DF A and assign which country the string contains? Here's what I imagine DF A would look like after assignment...
|---------------------|------------------|-----------|
| sentenceCol | other column | country |
|---------------------|------------------|-----------|
|'this is from france'| 15 | 'france' |
|---------------------|------------------|-----------|
One additional complication is that there can be more than one country per sentence, so ideally this could assign every applicable country to that sentence.
|-------------------------------|------------------|-----------|
| sentenceCol | other column | country |
|-------------------------------|------------------|-----------|
|'this is from france and spain'| 16 | 'france' |
|-------------------------------|------------------|-----------|
|'this is from france and spain'| 16 | 'spain' |
|-------------------------------|------------------|-----------|
There's no need for a loop here. Looping over a dataframe is slow and we have optimized pandas or numpy methods for almost all of our problems.
In this case, for your first problem, you are looking for Series.str.extract:
dfa['country'] = dfa['sentenceCol'].str.extract(f"({'|'.join(dfb['country'])})")
sentenceCol other column country
0 this is from france 15 france
For your second problem, you need Series.str.extractall with Series.drop_duplicates & to_numpy:
dfa['country'] = (
dfa['sentenceCol'].str.extractall(f"({'|'.join(dfb['country'])})")
.drop_duplicates()
.to_numpy()
)
sentenceCol other column country
0 this is from france and spain 15 france
1 this is from france and spain 15 spain
Edit
Or if your sentenceCol is not duplicated, we have to get the extracted values to a single row. We use GroupBy.agg:
dfa['country'] = (
dfa['sentenceCol'].str.extractall(f"({'|'.join(dfb['country'])})")
.groupby(level=0)
.agg(', '.join)
.to_numpy()
)
sentenceCol other column country
0 this is from france and spain 15 france, spain
Edit2
To duplicate the original rows. We join the dataframe back to our extraction:
extraction = (
dfa['sentenceCol'].str.extractall(f"({'|'.join(dfb['country'])})")
.rename(columns={0: 'country'})
)
dfa = extraction.droplevel(1).join(dfa).reset_index(drop=True)
country sentenceCol other column
0 france this is from france and spain 15
1 spain this is from france and spain 15
Dataframes used:
dfa = pd.DataFrame({'sentenceCol':['this is from france and spain']*2,
'other column':[15]*2})
dfb = pd.DataFrame({'country':['france', 'spain']})
Thanks @NaturalFrequency appreciate it!
Ah, I see one problem. So my dfa in this instance does not already have the string values duplicated, so dfa would just be: dfa = pd.DataFrame({'sentenceCol':['this is from france and spain'], 'other column':[15]}) . That is why I'm getting a Value Error: ValueError: Length of values does not match length of index
Not sure if I understand you, does the solution work or do you get that error?
I get that error, because my data is not already duplicated dependent on if there are multiple country names involved. So the sentence 'this is from france and spain' is just one row in my dataset.
Thanks for the response, apologies if I'm making this confusing. I see what you did there, concatenating the country tags with a comma. But instead of that, is it possible, to actually duplicate the sentence by creating a new row with each row containing one country a piece?
I see what you mean. See edit2, this should work as intended @Justin
Thank you for this great answer. However, If you don't mind me adding on - what if the sentenceCol can be duplicated, but we still want the countries commpa separated in the country column for each occurence?
You can iterate through a dataframe with the method iterrows(). You can try this:
# Dataframes definition
df_1 = pd.DataFrame({"sentence": ["this is from france and spain", "this is from france", "this is from germany"], "other": [15, 12, 33]})
df_2 = pd.DataFrame({"country": ["spain", "france", "germany"], "other_column": [7, 7, 8]})
# Create the new dataframe
df_3 = pd.DataFrame(columns = ["sentence", "other_column", "country"])
count=0
# Iterate through the dataframes, first through the country dataframe and inside through the sentence one.
for index, row in df_2.iterrows():
country = row.country
for index_2, row_2 in df_1.iterrows():
if country in row_2.sentence:
df_3.loc[count] = (row_2.sentence, row_2.other, country)
count+=1
So the output is:
sentence other_column country
0 this is from france and spain 15 spain
1 this is from france and spain 15 france
2 this is from france 12 france
3 this is from germany 33 germany
Thanks! I believe this did work when testing it out, but it also took ~5 mins to run (about 9000 sentence rows and 270 country rows)
| common-pile/stackexchange_filtered |
keybase/coinbase
How can I export xlm from keybase to coinbase?
Keybase app says, "Stellar transactions are no longer supported in keybase app", "Please export your stellar balances to alternative wallets using your secret keys"
However, there are no options (that I can see) to export wallet!
Additionally, I have tried to within coinbase to "receive", and that too was a dead end.
I appreciate any guidance, preferably step-by-step on how to make this happen!
Thank you!
Does this answer your question? https://stellar.stackexchange.com/q/4065/683
Unfortunately no, this does not answer my question. The 2 answers provided were apparently workable in 2020. Keybase has since removed (I'm not sure when) the option to "send" Lumen.
I think this blog post should help:
How to Extract Stellar Lumens from Keybase
Please post the relevant parts from that link here. Answers consisting only of links are not particularly helpful and are liable to be deleted.
| common-pile/stackexchange_filtered |
Why is the print statement in the class executed when an object isn't even created?
When I run the code below the output is "hello".
However, the print statement is part of the class pl, and i never created an instance of the class pl, so why is the print statement being executed?
class pl:
def __init__(self,a,b):
self.aa=a
self.bb=b
print("hello")
Class bodies (even nested class bodies) are executed at import time (as opposed to functions or methods).
Demo script:
class Upper:
print('Upper')
class Mid:
print('Mid')
def method(self):
class Low:
print('Low')
print('method')
Output:
$ python3
>>> import demo
Upper
Mid
Thanks! Does 'def method(self):' belong to class Mid or class Upper? Based on indentation i would say it belongs to upper, but it's below/within Mid so I'm confused. Also am I correct in saying that print('method') doesn't belong to class Low?
@user3124200 method is an attribute of the class Upper. print('method') is a print statement executed in the body of method, not in the body of Low. You can work this out by looking at the indentation levels.
@timegb Thanks! I am confused on the following point though: 1) print('Upper') is executed as part of the Upper class and then 2) print('Mid') is executed as part of the Mid class and then 3) method is an attribute of the class upper. I'm confused at how the code jumps around from having statements belong to the upper class, then the mid class, and then the upper class again. Shouldn't everything defined within one class first & then within a nested class, and then within another sub class etc. How would you express the above code if python used curly brackets rather than indentation?
@user3124200 does this pseudo-code help?
| common-pile/stackexchange_filtered |
A parametrization for $\frac{\sin(x)}{x}$ as a revolution surface around $y$ axis
I'm looking for a parametrization for $\frac{\sin(x)}{x}$ as a revolution surface arround the $y$ axis.
I have tried $X(x,y)=\Big(\frac{\sin(y)\sin(x)}{x},x,\frac{\cos(y)\sin(x)}{x}\Big)$.
ParametricPlot3D[
{Sin[y] Sin[x]/x,x ,Cos[y] Sin[x]/x},
{x, 0, 6*Pi}, {y, 0, 2*Pi},
PlotRange -> All
]
But it does not make the surface it should be
Plot3D[Sin[Sqrt[x*x + y*y]]/Sqrt[x*x + y*y], {x, -10, 10}, {y, -10, 10}, PlotRange -> All]
Is my parametrization right?
Can you give me some advice?
Any help thanks!
Perhaps something like this. Just rotate the original function about the z-axis directly:
RotationMatrix[θ, {0, 0, 1}].{x, 0, Sin[x]/x}
(* {x Cos[θ], x Sin[θ], Sin[x]/x} *)
and so:
ParametricPlot3D[RotationMatrix[θ, {0, 0, 1}].{x, 0, Sin[x]/x}
, {x, 0, 20}, {θ, 0, 2 π}
, RegionFunction -> (-10 <= #1 <= 10 && -10 <= #2 <= 10 &)
, PlotRange -> All
, BoxRatios -> {1, 1, 1/2}]
Your original code seems to rotate around the x-axis:
ParametricPlot3D[RotationMatrix[θ, {1, 0, 0}].{x, 0, Sin[x]/x}
, {x, 0, 10}, {θ, 0, 2 π}
, PlotRange -> All
, BoxRatios -> {2, 1, 1}]
and rotating it about the y-axis is uninteresting. (Note that I have taken z to be "vertical".)
Try this:
RevolutionPlot3D[Sin[x]/x, {x, 0, 6 \[Pi]}]
Have fun!
Or to rotate around the x-axis: evolutionPlot3D[Sin[x]/x, {x, 0, 6 Pi}, RevolutionAxis -> "X", BoxRatios -> {1, 0.25, 0.25}]
| common-pile/stackexchange_filtered |
Identity Column Inserting Null With MVC Code First
I am using MVC to generate my database. I have the following code structure in my UserProfile class:
[KeyAttribute()]
[DatabaseGenerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string UserName { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string EmailAddress { get; set; }
This generates the database fine, but when I try to insert a record it says UserId cannot be null. I cannot figure out why it isn't auto generating an Id integer.
This was because I had some issues updating the database. Needed to manually drop this table and re-create it. Is working fine now.
| common-pile/stackexchange_filtered |
Number of ways of arranging three boys and two girls in a line of five chairs so that the girls are adjacent
We have $3$ guys and $2$ girls who are going to be seated on five lined-up chairs. The question is how many ways can they sit so that the girls stay next to each other.
My thought is that (if we number the chairs from 1 to 5) they either sit on 1-2 , 2-3 , 3-4 or 4-5, so $4$ ways for the girls. As for the guys, the first one has $3!$ ways, the second is $2!$, and the third is $1!$. So, the final number of ways is $4 \cdot 3! \cdot 2! \cdot 1!=48$ ways?
Uh... you got the right numerical answer but your explanation makes it sound like you got it for the wrong reasons. If it were $100$ guys and $2$ girls, your logic sounds like you might have gotten an answer of $101\cdot 100!\cdot 99!\cdot 98!\cdot 97!\cdots 3!\cdot 2!\cdot 1!$, much larger than the $102!$ ways that you can arrange the people ignoring the condition that the girls be together.
Why would the first boy have 3! options? Seems like it should just be 3. Even so, you assume the boys are distinct ... but the girls are not?!
Welcome to MathSE. This tutorial explains how to typeset mathematics on this site.
Your answer is correct, but your reasoning is not.
Method 1: There are four ways to place the leftmost girl. Since the girls are adjacent, choosing where the leftmost girl determines which two seats the girls occupy. There are $2!$ ways to arrange the two girls in those seats. The three boys can be arranged in the remaining three seats in $3!$ ways. Hence, there are
$$4 \cdot 2!3! = 48$$
admissible arrangements.
Method 2: We can temporarily think of the girls as a single object. Then, we have four objects to arrange, the three boys and the block of girls. The objects can be arranged in $4!$ ways. The two girls can be arranged within the block in $2!$ ways. Hence, there are
$$4!2! = 48$$
arrangements of three boys and two girls if the girls are adjacent.
What is wrong with your explanation?
Once you chose where the block of consecutive seats occupied by the girls begins, you have to arrange the two girls in the selected seats. Thus, there are $4 \cdot 2!$ ways to arrange the girls rather than $4$ ways. Also, the first boy may be seated in three ways (not $3!$, which is the number of ways of arranging three distinct objects in three positions), leaving two ways to seat the second boy, and one way to seat the third boy, giving
$$4 \cdot 2! \cdot 3 \cdot 2 \cdot 1 = 4 \cdot 2! \cdot 3! = 4!2! = 48$$
admissible arrangements.
| common-pile/stackexchange_filtered |
Expectation of Ito Integrals.
Consider the stochastic differential equation:$$dx(t)=f(x(t))dt+g(x(t))dB(t)$$
where $B(t)$ is the standard brownian motion.
Is the following always true:
$$\mathbb{E}\int_0^tH(x(t))dB(t)=0$$
If it is not true in general, what are the conditions on the function $H(x)$ that makes the equality holds?
Obviously there need be SOME conditions on $H$ for the integral to be well-defined. At the very least it should be measurable, I would think.
If the stochastic integral wrt to the B.M. is well defined, then your claim is always true. For the integral to be well defined we need the integrand process H to be $\{\mathscr{F}_t\}$-adapted and also to satisfy
$$\int_0^t |H_u|^2 du < \infty.$$
| common-pile/stackexchange_filtered |
Does Tensorflow Lite support the TimeDistributed layer?
I'm currently working with a Keras model with TimeDistributed, Conv2D and Bidirectional(LSTM) layers (code example below) and I'm trying to convert to TF Lite.
x = TimeDistributed(Conv2D(16, kernel_size=(3,3), strides=(1,1), activation='tanh', padding='same'))(input_a)
x = TimeDistributed(Conv2D(32, kernel_size=(3,3), strides=(1,1), activation='tanh', padding='same'))(x)
x = TimeDistributed(Conv2D(64, kernel_size=(3,3), strides=(1,1), activation='tanh', padding='same'))(x)
x = TimeDistributed(MaxPooling2D(pool_size=(2,2), strides=(1,1)))(x)
x = TimeDistributed(Flatten())(x)
x = Model(inputs=input_a, outputs=x)
y = TimeDistributed(Conv2D(16, kernel_size=(3,3), strides=(1,1), activation='tanh', padding='same'))(input_b)
y = TimeDistributed(Conv2D(32, kernel_size=(3,3), strides=(1,1), activation='tanh', padding='same'))(y)
y = TimeDistributed(Conv2D(64, kernel_size=(3,3), strides=(1,1), activation='tanh', padding='same'))(y)
y = TimeDistributed(MaxPooling2D(pool_size=(2,2), strides=(1,1)))(y)
y = TimeDistributed(Flatten())(y)
y = Model(inputs=input_b, outputs=y)
combined = concatenate([x.output, y.output])
z = Bidirectional(LSTM(512))(combined)
z = Dense(5, activation='softmax')(z)
The conversion is actually successful (code below), but I experience a strong accuracy drop when testing the TF Lite model.
def representative_data_gen():
for input_value in tf.data.Dataset.from_tensor_slices(predictors_train).batch(1).take(100):
input_value_1 = numpy.array(input_value[:,:,:4,:], dtype=numpy.float32)
input_value_2 = numpy.array(input_value[:,:,4:,:], dtype=numpy.float32)
yield [input_value_1, input_value_2]
converter = tf.lite.TFLiteConverter.from_keras_model(model)
converter.optimizations = [tf.lite.Optimize.DEFAULT]
converter.representative_dataset = representative_data_gen
converter.experimental_new_converter=True
converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS, tf.lite.OpsSet.SELECT_TF_OPS, tf.lite.OpsSet.TFLITE_BUILTINS_INT8]
converter._experimental_lower_tensor_list_ops = False
converter.inference_input_type = tf.uint8
converter.inference_output_type = tf.uint8
tflite_model_quant = converter.convert()
Since I can't find the TimeDistributed layer on the supported operation list but the conversion is successful anyway, I asked myself if this layer could actually be the problem.
Any hint or insight would be appreciated.
In case somebody is having the same problem: I've done some debugging in the past few days and the problem seems to be elicited not by the TimeDistributed layer, but by the combination of TimeDistributed layers with Conv2D inside and an LSTM right after.
I'm still analyzing the problem in-depth... Update ASAP.
Try first a float version without quantization to see if accuracy is good. If there is a drop even with float, then file a github issue for TFLite team.
If the drop is in the quantized version, then you can start by inspecting which layer(s) are the culprit by using the QuantizationDebugger.
I already tried the float32 version, the accuracy drop is there... Thank you for your help, I wasn't aware of the Debugger existence!!
| common-pile/stackexchange_filtered |
Cannot retrieve a Google Profile for editing
I'm trying to retrieve a Google Profile for editing from the Profile API using the C# .NET GData SDK but authentication seems to be failing. I'm using a number of other Google API's and can authenticate with them just fine and am using the same code approach:
var settings = new RequestSettings("appname", ApiUsername, ApiPassword);
var contactsRequest = new ContactsRequest(settings);
var uri = new Uri(string.Format("https://www.google.com/m8/feeds/profiles/domain/{0}/full/{1}", googleDomain, googleUsername));
var contact = contactsRequest.Retrieve<Contact>(uri);
I get the following exception:
Google.GData.Client.GDataRequestException: Execution of request
failed:
https://www.google.com/m8/feeds/profiles/domain/xxx/full/joe.bloggs
---> System.Net.WebException: The remote server returned an error: (401) Unauthorized.
On the advice of Google Enterprise support I used their OAuth2 Playground site using the same credentials as in the code and it worked.
My guess is that the SDK whilst taking in a username and password does not use these credentials in the RequestSettings object and authentication is failing, even though this same approach works on their Provisioning API.
My fear is that I need to use OAuth2, which seems unecessarily complicated for what we're trying to do and there's no Google documentation to support this.
Does anyone have any code examples of how to authenticate with the Profiles API?
Edit:
So yes, it seems I have to use OAuth2 and the Google SDK is broken as it doesn't allow you to just use username and password to authenticate. I've been hacking around with a lot of examples and am using another Google SDK that offers OAuth2 support.
I've created a Client ID for installed applications via the API console, assigned this id API access to the scope and am using the following code:
var oAuth2Parameters = new OAuth2Parameters
{
ClientId = "xxx",
ClientSecret = "xxx",
RedirectUri = "urn:ietf:wg:oauth:2.0:oob",
Scope = "https://www.google.com/m8/feeds/"
};
// get an access token
OAuthUtil.GetAccessToken(oAuth2Parameters);
var settings = new RequestSettings("xxx", oAuth2Parameters);
var contactsRequest = new ContactsRequest(settings);
This gets me further along, but now I get the following exception:
System.ArgumentNullException: Value cannot be null. Parameter name:
refresh_token
This code is running as part of a back-end service. I don't know if the client id type of Installed Application is wrong for the type of authentication exchange. My first thought was to use the Service Account client id type, but this produced a certificate which isn't usable by the OAuth2Parameters object.
Any helpful pointers?
I am retagging this to google-apps from google-apps-script (Cloud based JavaScript).
Regarding your question - yes, you'll need to use oAuth 2 but oAuth 2 itself gives you some options. Once you spend a few hours understanding it - it will really pay off as it is becoming very standard and commonplace across many vendors.
Google offers several starter libraries (including .NET) to get you started here - https://developers.google.com/accounts/docs/OAuth2#libraries
Try some of that out and share if you run into any issues.
Arun, I was told by Google Enterprise Support to tag it that way so they would see it and answer it. Thanks for your reply all the same. I've updated my question above...
After much experimenting, I've got the results back from the Profile API I need without using OAuth2, which was way too much of a headache (mainly because of the poor quality of the Google SDK and their documentation, the concept is simple enough).
I used the simple username & password authentication method and instead of using ContactsRequest.Retrieve(uri) I used:
var settings = new RequestSettings("xxx", ApiUsername, ApiPassword);
var cr = new ContactsRequest(settings);
var uri = new Uri(string.Format("https://www.google.com/m8/feeds/profiles/domain/{0}/full/{1}", googleDomain, googleUsername));
var query = new ContactsQuery(uri.AbsoluteUri);
var feed = cr.Get<Contact>(query);
| common-pile/stackexchange_filtered |
ChatMessages.Add(message) is not hit
I'm getting started with simple signalR application. When user puts his "name" and "room". It is sent to my hub
//This is Index page
public async Task<ActionResult> OnPost()
{
UserConnection userConnection = new()
{
Name = UserInput,
Room = JoinRoomInput
};
await _hubConnection.SendAsync("JoinRoom", userConnection);
return RedirectToPage("ChatGroup");
}
my chat looks like this
public class ChatHub : Hub<IChatClient>
{
private readonly string _botUser;
public ChatHub()
{
_botUser = "MyChat Bot";
}
public async Task JoinRoom(UserConnection userConnection)
{
await Groups.AddToGroupAsync(Context.ConnectionId, userConnection.Room);
await Clients.Group(userConnection.Room).ReceiveMessage(_botUser, $"{userConnection.Name} has joined {userConnection.Room}");
}
public async Task SendMessage(UserConnection userConnection, string message)
{
await Clients.Group(userConnection.Room).ReceiveMessage($"{userConnection.Name} : ", message);
}
}
So then, the use posts his details and hit joinroom. He is redirected to another razor page called Chatgroup.In this page, He should get the message as defined in "JoinRoom" in ChatHub.
//This is Chatgroup page
private readonly HubConnection _hubConnection;
public List<string> ChatMessages { get; set; }
public ChatGroupModel(HubConnection hubConnection)
{
_hubConnection = hubConnection;
}
public void OnGet()
{
_hubConnection.On<string>("ReceiveMessage", (message) => //Breakpoint hits here
{
ChatMessages.Add(message); // When placed a breakpoint here, It is skipped.
});
}
I'm getting ChatMessages is Null error.
So my question is how will my client side code _hubConnection.On<> get the response from chathub?
I think this is the issue.
I've registered my signalr in startup class like this
services.AddTransient<HubConnection>((ChatClient) => {
var hubConnection = new HubConnectionBuilder().WithUrl("https://localhost:44389/chathub").Build();
hubConnection.Closed += async (error) =>
{
await Task.Delay(new Random().Next(0, 5) * 1000);
await hubConnection.StartAsync();
};
hubConnection.StartAsync();
return hubConnection;
});
I get a null exception error in my razor page. I think it's because _hubConnection.On<>... skips chatmessage.add.
@foreach(var messages in Model.ChatMessages) //ChatMessages is Null
{
<div>
@messages
</div>
}
| common-pile/stackexchange_filtered |
Upload file in PHP using DAV Protocol
Can someone please advise on uploading a file using the DAV protocol in PHP? I have had a look around the web and everything seems pretty over-complicated.
I will need to be uploading image files server side after user upload to a directory over DAV - is there a good PHP class available to do this?
SabreDav seems a very good current package, I've has some success using it in tests, but due to business decisions never employed in in production yet.
a more 'sysadmin' solution is having the distant DAV always mounted on the OS where you werbser is, as a distant fielsystem, then the webserver only access his 'local' filesystem and any auth negociation is done once at OS startup.
Have a look to WebDAV Client Pear package, which implements a nice stream wrapper.
There is an example into the package. But you can do more or less things like this require '/path/to/pear/package.php'; mkdir("webdav://www.example.com/foo/"); file_put_contents("webdav://www.example.com/foo/bar.txt", $httpfile); $httpfile = file_get_contents("webdav://www.example.com/foo/bar.txt");
Also, you can take a look at SabreDAV, which is (unlike Pear's library) more regularly updated and implements new workarounds regarding Windows Vista & 7.
| common-pile/stackexchange_filtered |
Method naming convention in Scala -- mutable and not version?
This example is trivial just to show the point.
Let's say I use matrix library, but is lacks some power, let's say doubling every element in matrix is so crucial for me, I decide to write a method doubleIt. However, I could write 2 versions of this method
mutable -- doubleItInPlace
non mutable -- doubleItByCreatingNewOne
This is a bit lengthy, so one could think of naming convention, adding to mutable version _! suffix, or prefixing it with word "mut".
Is there any establishing naming convention for making such difference?
The convention is to name the mutable (in general, side-effecting) version with a verb in imperative form. Additionally, and more importantly, use the empty parameter list () at the end:
def double()
def doubleIt()
The immutable version, i.e. one producing a new object, you should name via verb in the passive form. More importantly, do not use the empty parameter list () at the end:
def doubled
def doubledMatrix
Note that naming the non-side-effecting method in the passive form is not always adhered (e.g. the standard collections library), but is a good idea unless it makes the name overly verbose.
Source: Scala styleguide.
| common-pile/stackexchange_filtered |
Removing/Appending images with radio button
I have a set of radio buttons I'm using to append and remove images within a div. My image sources are in a data set value within the radio buttons:
<input class="radioGroup" name="radioGroup" type="radio" id="radio1" data-source-image="/image1.jpg" data-source-desc="This is the First Image">
<label for="#radio1">Image 1</label><br />
<input class="radioGroup" name="radioGroup" type="radio" id="radio2" data-source-image="/image2.jpg" data-source-desc="This is the Second">
<label for="#radio2">Image 2</label>
I am appending the image with a class which corresponds with the radio buttons id and using that to remove the image if it's not checked:
$('.selections input').live("change", function () {
// 'Getting' data-attributes using dataset
var appendImg = $(this).data('sourceImage');
var itemDesc = $(this).data('sourceDesc');
var item = $(this).attr('id');
if ($(this).is(':radio')) {
var radioGroupName = $(this).attr('name');
var radioGroup = $('input[name="' + radioGroupName + '"]')
radioGroup.each( function() {
if ($(this).attr("checked")) {
$('.imageContainer').append('<img src="' + appendImg + '" alt="' + itemDesc + '" class="' + item + '" />');
}
if ( ! $(this).attr("checked")){
$('.imageContainer').children('img').remove('.' + item);
}
});
} });
I can not get this to work though, I've tried multiple variations of this code each with slightly different results but none of them functioning as expected. In the case with this code, my first radio button does not function at all and the second radio button only adds its image.
Also, any other suggestion to clean up it up would be welcome (my radio check is there because there are other inputs I'm handling in this function).
Thanks!
Maybe you're complicating things... If you wrap the radio input in the label you don't need the id:
<label><input type="radio" .../></label>
Then, instead of figuring out if it's a radio with the live event which is deprecated and I don't think you need either, you can use the change event of those particular radios. If you have dynamic radio inputs, then I'd suggest you use on on the closest static container, instead of live on document.
var $container = $('.imageContainer');
$('input[name=radioGroup]').change(function() {
var $this = $(this),
imgSrc = $this.data('source-image'),
imgDesc = $this.data('source-desc'),
$img = $('<img/>', { src: imgSrc, alt: imgDesc });
$('img', $container).remove(); // remove all images
$container.append( $img ); // add the image linked to the current input
});
Since radios are exclusive, only one can be selected, you don't need to figure out if it's checked or not, and find other images, unless you already have images inside that same container. In that case, I would just create an extra wrapper for the images that are linked to radios.
Demo: http://jsbin.com/isitos/1/edit
Thanks elclanrs, this is definitely a step in the right direction for me. I probably should have elaborated more, as I need to account for varying numbers of radio input groups and I can't clear all of the images within the container since I have other images displaying here via other checkboxes. Also, I know wrapping an input in a label is valid but I usually prefer keeping them separated.
Then you can use the class you were using, that should do it as well as adding all the groups you want to the change event. http://jsbin.com/isitos/2/edit <- demo seems weird because images are repeated but it works.
| common-pile/stackexchange_filtered |
syslog stops logging after log rotation
Every time after newsyslog rotates the log file, syslog stops logging into the file. Until a syslogd restart is done.
(myserver:wheel)# logger -p local1.info -t myprocess "hello thiru"; ll myfile.log; cat myfile.log
-rw-r--r-- 1 root wheel 0B Nov 10 11:26 myfile.log
(myserver:wheel)# /etc/rc.d/syslogd restart
Stopping syslogd.
Starting syslogd.
(myserver:wheel)# logger -p local1.info -t myprocess "hello thiru"; ll myfile.log; cat myfile.log
-rw-r--r-- 1 root wheel 44B Nov 10 12:04 myfile.log
Nov 10 12:04:31 myserver myprocess: hello thiru
(myserver:wheel)#
On Linux (which uses logrotate), we can solve this by doing syslog/rsyslog restart in the postrotate section of the logroate conf.
Is there something similar to postrotate in newsyslog?
Edit:
Syslog and newsyslog conf files:
(TPC-E11-36:wheel)# cat /etc/newsyslog.d/newsyslog-myprocess.conf
/var/log/myfile.log 644 20 10000 * Z
(TPC-E11-36:wheel)# cat /etc/syslog.d/syslog-myprocess.conf
!myprocess
local1.info /var/log/myfile.log
(TPC-E11-36:wheel)#
See man newsyslog.conf, but by default syslogd receives a signal when a log file is rotated unless either an N flag or another process has been specified. Check your newsyslog.conf or newsyslog.conf.d/* files.
@RichardSmith I don't know how to specify a process in newsyslog.conf? And I haven't used N flag either.
I cannot replicate the problem. If I add your lines to my /etc/syslog.conf and invoke newsyslog -f newsyslog-cnd.conf, the logfile is rotated, a new one is created with a message logfile turned over due to size and logger works fine into the new file. I do not recognise your subdirectories newsyslog.d and syslog.d and I do not get a 0B file after log rotation.
@RichardSmith I too can't replicate it now :( Is it possible that this happened because of Daylight Saving Time change?
And please ignore the sub directories. My syslog.conf and newsyslog.conf include them.
Add the path of the pidfile into the /etc/newsyslog.conf and if required a signal for example 1 that stands for SIGHUP, more info about newsyslog here: https://www.freebsd.org/doc/handbook/configtuning-syslog.html
The format/example is this:
# logfilename [owner:group] mode count size when flags [/pid_file] [sig_num]
/var/log/your-app.log root:wheel 600 7 * @T00 GBJC /var/run/your-app.pid 1
Also see this answer: https://serverfault.com/a/701563/94862
There is actually something similar to postrotate in newsyslog, it's the R flag in the configuration file in combination with path_to_pid_cmd_file (that's what it's called in the FreeBSD manual entry of newslog.conf(5)). With this flag set, the path provided will not be interpreted as a path to a PID file, but as a path to a script (for example a shell script) which will be executed after the log rotation is finished.
You can even pass arguments to the script, but for this you'll have to use the IFS-variable (separated by a space, the argument would be interpreted as a signal and likely throw an error).
# logfilename [owner:group] mode count size when flags [/cmd_file]
/var/log/myfile.log root:wheel 644 20 10000 * ZR /path/to/my/script${IFS}myargument
| common-pile/stackexchange_filtered |
SSRS data set variables not read by the other data source query
I have an issue in querying 2 datasets in SSRS. I have 4 datasets out of which 3 points to 1 data source and 1 point to the second data source.
The parameters of the report get the values from the datasets of 1 data source. Then once the parameters are assigned a value, I am using these to query the other data source to display the results. However, when I run the report, I get the following error:
Declare a scalar variable @Date1.
It could be due to the data sources being on 2 separate servers.
Anybody faced this issue before?
it's been a while I have worked the last time with SSRS, but I remember that the order of data sources mattered. Meaning: the 1 data source needs to be accessed first, so that the other data sources can make use of this parameter.
A few things to check. @Date1 must NOT be declared in your in the last dataset query. The parameter name referenced in your last dataset query must be exactly the same as the report parameter name - it is case sensitive. ALL references to @Date1 in your dataset query must be the same case.. If this does not help, edit your question and show the last dataset query and the details of the related parameter.
| common-pile/stackexchange_filtered |
Calculating fields in confirmation email
Is it possible to:
Set a number value for a dropdown, but don't show it in the UI (can be in the source)?
Take the values from the multiple fields and multiply/add them and send the output in the confirmation email?
Looking to create a form that people can fill out and send them the quote in an email and not present them the pricing right away.
I see I could have a calculation field that is hidden and then I could send that field in the confirmation email, but can I hide the value for dropdown fields in the UI?
I am a developer for Cognito Forms.
Although we don't have the ability to hide the price attached to a choice field, you can use a Calculation field.
I used a simple Choice field and a number field as shown below.
Next I added a Calculation field and gave it a simple name, I then set this field to show "internally" or "never". The calculation you will need to add to this field is below:
=(Choice = "First Choice" ? 10 : Choice = "Second Choice" ? 20 : Choice = "Third Choice" ? 30 : 0) * Quantity + " " + "Dollars"
This will take the choice option and assign it a numeric value (eg. 10, 20, 30) and then multiply that number by the number in the Quantity field. I am then adding the word "Dollars" to the end, this is to show that extra text can be added after the value has been calculated.
You can then navigate into your Submission Settings and enable the Confirmation option. You will need to be collecting the users email address so that you can assign the email field using the drop down under "To". In the message text block you can place your hidden Calculation field in your message, like this:
This will result in an email being sent to your user that looks like this:
Awesome! Thank you! I started down this path a little too so this is good that you verified this is the best path.
Corey, make sure your calculation has a type of Currency. This should make the value format correctly in the confirmation message.
This worked out great! I made sure I had currency. I just have to play with the email now, but otherwise this is exactly what I was looking for. Thanks for the help!
| common-pile/stackexchange_filtered |
Compute Coordinates From Arc Length In Snell's Law
I want to build a raytracer for materials of continuous optical density. I found (or actually someone on Reddit found it for me) this article, which is basically exactly what I needed. Just a minor thing, it would be nice to have an inverse function of the arc length, so that I could plug the step size into some formula and receive the point at the end of the arc. So my idea is, looking at $(1.8.5)$, to compute the arc length as something like $$\begin{align*}\int_\alpha^\psi\frac{dy}{\sin(\phi)}&=(y-k)\int_\alpha^\psi\frac{\tan(\phi)d\phi}{\sin(\phi)}\\&=\frac{k\cos(\alpha)}{\cos(\psi)}\int_\alpha^\psi \frac{\tan(\phi)d\phi}{\sin(\phi)}.\end{align*}$$ The last term can be further transformed by $$\int\frac{\tan(\phi)d\phi}{\sin(\phi)}=(\log(\cos+\sin)-\log(\cos-\sin))(\phi/2)$$ but I don't know if this helps to find the inverse to this function, I guess there is no easy way?
Sadly true. No easy way.
Thanks for the comment! But are my calculations correct so far? (I'm just worried that I made a mistake which makes it look impossible when it isn't.)
I don't know if your calculations are correct and it would take me more time than I have to check. They look reasonable.
| common-pile/stackexchange_filtered |
Get Header Request Javascript: cURL working, fetch forbidden
i want to GET Request the Header of this link https://soundcloud.app.goo.gl/u6XXuqp3Q7Q7WXgH8 in a React App. When doing a simple request
request('https://soundcloud.app.goo.gl/u6XXuqp3Q7Q7WXgH8', function (error, response, body) {
console.error('error:', error);
console.log('body:', body);
});
I get
Access to fetch at 'https://soundcloud.app.goo.gl/u6XXuqp3Q7Q7WXgH8' from
origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-
Control-Allow-Origin' header is present on the requested resource. If an
opaque response serves your needs, set the request's mode to 'no-cors' to
fetch the resource with CORS disabled.
When using the cors-anywhere proxy
request('https://cors-anywhere.herokuapp.com/https://soundcloud.app.goo.gl/u6XXuqp3Q7Q7WXgH8', function (error, response, body) {
console.error('error:', error);
console.log('body:', body);
});
I get
request.js:150 GET https://cors-anywhere.herokuapp.com/https://soundcloud.app.goo.gl/u6XXuqp3Q7Q7WXgH8 403 (Forbidden)
But when I just cURL I get the right response
curl -s -o /dev/null -D - https://soundcloud.app.goo.gl/u6XXuqp3Q7Q7WXgH8
Can anyone explain this behaviour to me and maybe tell me how to overcome this?
Thanks!
You have a CORS issue here, your clients domain needs to be whitelisted in your server or, if it already is, you need to correct your request headers.
The point is, I don't have access to the soundcloud servers. And using the cors-anywhere proxy is working for every other website except the soundcloud link :(
I also ran the application on an express server using the ´cors´ module and everything, but nothing works :(
CORS error usually comes up when you are trying to call an API from your browser directly and that API doesn't allow any other website to get the data.
There can be 2 workarounds to this problem I can think as of now -
Either you call that API from your backend code and you gather the data received from the website in backend and transfer the data on the client-side. Basically, you will be Wrapping the original API.
You can use Web Servers like NGINX and configure a specific path on the domain pointing to External API and other paths to your project. Which will help in making both the External API and Your React code on the same domain name.
Mainly your objective is to have that external API to work through your domain working along with your react code.
yeah you're right...i just thought there might be solutions such as a special type of api request that won't be blocked by any cors stuff..
In browser context JS, such as a in a fetch call to an API, CORS applies. Rather with a CURL request, you are essentially running server side context, therefore CORS doesn't apply. This is why you can hit instagrams unofficial api from a server context or node.js context, but not from the same fetch call in a browser. Possible solutions:
Allow-Content-Orgin header set by the server must include the domain your page is hosted on.
Use Eletron or NodeWebkit.js for visual apps running client side with a browser (chromium) to launch your app in (mix of both browser and server context, CORS does not apply)
Run a node.js app (no browser, server context) and run your app from the terminal. (CORS does not apply)
| common-pile/stackexchange_filtered |
Android why does this NOT throw wrong thread exception?
I was under the impression that views can only be manipulated from the main thread... however, why does this NOT crash:
public class MainActivity extends Activity {
TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
tv = new TextView(this);
tv.setText("original text");
setContentView(tv);
new Thread(new Runnable() {
@Override
public void run() {
tv.setText("trollollolol i should die here but i won't.");
}
}).start();
}
}
i ran on device & emulator, both work just fine and i see the text change. what's going on?
i also checked thread IDs and the background thread is DEFINITELY not the main thread (threadID = 1)
While I am not too familiar with Android UI -thread implementation and checks - I can't help wondering is there such a thing as "running UI thread" during call to Activity.onCreate? Adding a short Thread.sleep into this Thread crashes the app as expected after all.
I'm not familiar with the particular implementation of checks either (i've definitely seen some CalledFromWrongThreadException happen before). but by running on UI Thread, i assumed Android perhaps may have had some check for calls to check that your current Thread ID is not 1 or something. thread ID 1 has always been the "main/UI thread" from what i understand
This is pretty interesting I believe: Add a Thread.sleep(1000); inside the thread, before updating the text view. The application will crash and the expected CalledFromWrongThreadException is thrown.
Android doesn't actually stop you from updating the UI from outside the main thread. It's just more of a ticking time bomb. If the main UI thread isn't updating the UI at the time, then your thread can do it.
At least that was my understanding. I don't 100% know for sure, but I've been able to (accidentally) update the UI from outside the main UI thread before. Sometimes it would work and sometimes it wouldn't. But as a good practice i would use a Async task.
FYI: you don't need a Async task you could just use runOnUiThread(Runnable) from within the other thread. But sometimes Async is indeed more useful for real background work.
I know that. Async Task is just the preferred way.
| common-pile/stackexchange_filtered |
Given members $x$, $y$ of subroup $HN$, show that $xy^{-1} \in HN$?
Let $H$ and $N$ be subgroups of a group $G$, with $N$ normal in $G$.
It is given that $HN$, the subset of $G$ consisting of elements of the
form $hn$, where $h \in H$ and $n \in N$, is a subgroup of $G$.
Given members $x$, $y$ of subgroup $HN$, show that $xy^{-1} \in HN$.
I'm looking for something more rigorous than just "$HN$ is a subgroup and thus closed under inverses and products."
So $N$ normal in $G$ means $\forall a \in N, \forall g \in G, gag^{-1} \in N$. However I'm not sure how to proceed from there. What's a good way to show $xy^{-1} \in HN$?
$x=hn$ and $y=h'n'$, then $xy^{-1}=hnn'^{-1}h'^{-1}=hh'^{-1}(h'nn'h'^{-1})$
Can you please explain that last step?
$hh'\in H$ and $h'(nn')h'^{-1}\in N$ ($N$ normal), hence $xy^{-1}\in HN$
| common-pile/stackexchange_filtered |
HowTo test Modal emitter in Angular2?
This is my class component:
export class GoalSettingsPage {
public goal: Goal;
dismiss() {
this.viewCtrl.dismiss();
}
}
This is my test:
it('should emit on click', () => {
let g = new Goal()
let settingModal = Modal.create(GoalSettingsPage, { g:Goal });
settingModal.subscribe(hc => {
console.log(hc);
expect(hc).toEqual({hasCompleted:true});
});
settingModal.dismiss()
})
This is my error:
04 07 2016 16:36:48.438:ERROR [Chrome 51.0.2704 (Mac OS X 10.11.3) | Goal Settings | should emit on click]: TypeError: Cannot read property 'remove' of undefined
at Modal.ViewController.dismiss (http://localhost:9876/absolute/var/folders/zb/tpysrhsx7hbg1dnsn4gwtqq00000gn/T/65a6294f711f882f7429da26bc12e438.browserify?2c82fe582a9911b998cb77bce54ea6804460d5cd:59060:25)
Any idea what I am doing wrong?
Which library do you use for modals? Thanks!
modal from ionic-angular
| common-pile/stackexchange_filtered |
Identification of plant gall / seed pod
I hope someone can anyone identify this plant material found in a meadow beside a river in UK. The nearest trees are about 50m away, across the river.
It is about 10cm long; flattish, soft and fleshy. There is a suggestion of a stalk at one end. It's been trodden on, so it might be squashed.
The first two pictures show it from each side, the third is a detail of the second side.
My searches have variously suggested
A caterpillar.
A gall from a hornbeam tree.
A seed pod of a mangolia tree.
It makes me think of a rhizome of a small water lilly, but I only have the picture to go by.
@Willeke that's an interesting suggestion. Perhaps it looked like the linked picture once, before being beaten up and had insect eggs laid in it.
Weather Vane, if comparing the item you have with descriptions of rhizomes bring you to a positive identification, can you please post it as a self answer?
Magnolia sprang to mind for me too; definitely not caterpillar. I don't think the "stalk" is really a stalk
@bob1 certainly not a caterpillar. If it's a rhizome the 'stalk' is more likely to be a root. The two sides look different, and in the alamy link the roots are coming from one side. Perhaps the pock-marks are root nodes and not insect exit holes.
...and the roots seem to grow out in groups. The pockmarks in my picture 2 are in groups.
@WeatherVane it bears some resemblance to Oxalis tuberosa, so a root/rhizome/tuber could well be right.
...except that seems to occur in the high Andes.
@WeatherVane consumed in many parts of the world (particuarly southern hemisphere/Pacific) as "yams", though of course it isn't a true yam.
| common-pile/stackexchange_filtered |
Listing directories with a specific one first
Is it possible in unix shell to get all folders, starting with specific one? For example I have folder1 and folder2, after I use "tree" I get them both like: folder1, folder2. But I want to get: folder2, folder1. ( in a different sequence)
What kind of 'different sequence'? Alphabetical? Reverse Alphabetical? Please explain better what do you want to achieve
What order do you want them in? It's not clear from your two-item example.
If the only thing you want to change is putting a specific item first, but otherwise keeping collation locale order, that's straightforward enough (though the details depend on knowing exactly which shell you're using, and the question presently doesn't specify).
It would also be helpful to have a bit more context. Do you want to iterate over these items with a loop (so it'd be helpful to collect them in an array)? Do you want to pass them on an argument list?
Ubuntu terminal. The order is not very important. I just want to start with an exact folder, but display others as well. Names may not me similar.
Is the one you want to start with first named in a variable? Does the code need to correctly handle the case where the entry named in that variable doesn't exist?
And again, which specific shell? bash? ash? dash? ksh? zsh? The terminal makes no difference to what syntax is allowed; the shell makes all the difference.
Bash. Code may not. I know that the one I'm looking for exists.
I've tried to edit to make the title more specific. "A different sequence" doesn't really say anything about what that sequence is, other than that it's different, but since you actually know what the difference you want is, better to describe that. (And "folder" is Windows terminology; on UNIX, we call them "directories").
Silly but working (in bash or ksh93):
#!/usr/bin/env bash
[[ -d $1 ]] || { echo "Usage: ${0##*/} first-directory" >&2; exit 1; }
first_directory=$1
all_directories=( */ )
all_directories=( "${all_directories[@]%/}" )
printf '%q\n' "$first_directory"
for directory in "${all_directories[@]}"; do
[[ $directory = "$first_directory" ]] && continue
printf '%q\n' "$directory"
done
Note that we're printing directories in eval-safe form, which guarantees that they're one-per-line. Because filenames on UNIX can contain literal newlines, printing literal names is unsafe unless NUL delimiters (which cannot exist in names) are used.
| common-pile/stackexchange_filtered |
Quick Settings Toggle in Android N
I'm trying to add a quick settings toggle to my app in Android N. The quick tile shows up, but it doesn't do anything when clicked. I can see the visible feedback when touched, so I know that it is recognizing the click, but it doesn't do anything when clicked.
Here's my service code:
public class QuickSettingTileService extends TileService {
public QuickSettingTileService()
{
}
@Override
public IBinder onBind(Intent intent)
{
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startID)
{
//some setup code is here
return START_STICKY;
}
@Override
public void onClick()
{
Context context = getApplicationContext();
Toast.makeText(context, "Quick Setting Clicked", Toast.LENGTH_SHORT).show();
//Toggle code is here
}
}
My manifest has the code almost directly copied from the documentation. Only slight modifications have been made:
<service
android:name=".QuickSettingTileService"
android:label="@string/app_name"
android:icon="@drawable/quick_toggle_off"
android:permission="android.permission.BIND_QUICK_SETTINGS_TILE">
<intent-filter>
<action android:name="android.service.quicksettings.action.QS_TILE" />
</intent-filter>
</service>
The service is started upon opening the app:
Intent serviceIntent = new Intent(this, QuickSettingTileService.class);
startService(serviceIntent);
Try logging to LogCat, rather than using a Toast.
Just remove these lines from your QuickSettingTileService class
@Override
public IBinder onBind(Intent intent)
{
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startID)
{
//some setup code is here
return START_STICKY;
}
There is no need to override onBind() or onStartCommand() on a TileService.
Also, you don't need to explicitly start this service. The permission and intent-filter in the manifest will make sure Android OS will start your service when your tile is added to the Notification bar.
Wow, that was simple. Thanks! I was originally getting an error without overriding onBind, but I think I was mistakenly extending Service at the time instead of TileService.
I'm glad that worked out. Please remember to mark as answer so this can help other people.
| common-pile/stackexchange_filtered |
LAMP/MySQL - run time delay during SQL batch insert
I have a SQL batch insert statement that is properly indexed and verified via explain. I am creating 73 rows with the batch insert. As part of the batch insert I am recording the date/time stamp using NOW() on each inserted record.
During the insert, after 68 records are inserted, there is a 50 second delay before the remaining 5 records are created.
What may be causing the delay during the inserts and what logs should I check?
$values = "";
foreach ($recipients as $recipient) {
$values = $values . "(" .
$msg['msg_id'] . "," .
$recipient['mbr_id'] . "," .
"NOW()" . "),";
}
// remove the last comma from the value list to terminate the values list
$values = rtrim($values, ",");
$sql = "INSERT INTO message (message_id, member_id, create_dtm)
VALUES " . $values;
// internal library function using PDO to write to the database
$pdb->db_commit($sql);
Any help would be greatly appreciated.
Please [edit] your question to show us your SQL batch insert statement.
done as requested
Try it with SYSDATE() instead of NOW(). Is innodb_lock_wait_timeout equal to 50? Was anything else running at the same time?
Thank you for the help. With the help you provided me, I found that more memory had to be assigned to MYSQL. The database was underperforming, which led to the lock timeout.
Thanks to the comments regarding the innodb_lock_wait_timeout, I discovered that more memory had to be allocated to MySql.
| common-pile/stackexchange_filtered |
Unable to incorporate birth pulses in a SIR model using deSolve
I am working on a SIR model with birth pulses, using deSolve package. With the following code, I expected birth pulses at time step 0, 12 and 24, but the output reveals that there are no birth pulses-actually no births at all!
library(deSolve); library(ggplot2)
SIR <- function (times,x,parameters) {
SL = x[1]
IL = x[2]
RL = x[3]
NL = x[4]
if (IL<0) IL=0
with(as.list(c(x,parameters)), {
npopL <- SL + IL + RL
dSL <- -(betaL*SL*IL/npopL) - ((b + (.5*(a-b)*npopL/kl))*SL) + ((((.918*round(cos(2%%((times%%12)+2)))))*(SL+RL)))
dIL <- +(betaL*SL*IL/npopL) - gamma*IL - (b+0.015)*IL
dRL <- +gamma*IL - b*RL
dNL <- +dSL + dIL + dRL
out <- c(dSL,dIL,dRL,dNL)
list(out)
})
}
times <- seq(1,24, by = 1)
parameters <- c(betaL = 0.9, gamma = 0.3, a= 0.0765, b = 0.06,kl = 50)
init <- c(SL=50,IL=0,RL=0,NL=50)
out <- as.data.frame(ode(y = init, times = times, func = SIR, parms = parameters))
mydata1 <- data.frame(Period=rep((1:length(out$SL)),4),Population = c(out$SL,out$IL,out$RL,out$NL),Indicator=rep(c("SusceptibleL","InfectedL","RecoveredL","TotalL"),each=length(out$SL)))
p1 = ggplot(mydata1,aes(x=Period,y=Population, group=Indicator))
f1 = p1+geom_line(aes(colour = Indicator))
f1
What am I doing wrong? Thanks in advance for your help!
Perhaps you could start by explaining why you expect 'birth pulses'. Then examine both the output of your SIR and of ode applied to that to see if, at each step, you are getting the values you expect.
It's not clear where your birth pulses are happening in your model. I can guess but you ought to give sufficient details. If you need discrete events in this type of model you should have a look at events or maybe forcings in package deSolve.
@Bhas In my function SIR, in dSL, the last part is the birth pulse [+ ((((.918round(cos(2%%((times%%12)+2)))))(SL+RL)))]-as only at time 0, 12 and 24 the value of round(cos(2%%((times%%12)+2))) is 1, and therefore .918*(SL+RL) should be added as birth pulse.
library(deSolve); library(ggplot2)
I'm having a go at modifying your model since I think it can be simplified.
There is no need to use npopL since you have variable NLwhich is what you need.
SIR <- function (times,x,parms) {
SL = x[1]
IL = x[2]
RL = x[3]
NL = x[4]
if (IL<0) IL=0
# with(as.list(c(x,parameters)), {
with(as.list(c(x,parms)), {
dSL <- -(betaL*SL*IL/NL) - ((b + (.5*(a-b)*NL/kl))*SL)
dIL <- +(betaL*SL*IL/NL) - gamma*IL - (b+0.015)*IL
dRL <- +gamma*IL - b*RL
dNL <- +dSL + dIL + dRL
out <- c(dSL,dIL,dRL,dNL)
list(out)
})
}
As I said in my comment have a look at events in the documentation of package deSolve.
So create an event function for your birth pulses (where does this come from??) where I have changed the birth pulse to a fraction of total population (NL).
eventfun <- function(t, y, parms){
with (as.list(c(y,parms)),{
SL <- SL + .1*round(cos(2%%((t%%12)+2)))*NL
return(c(SL,IL,RL,NL))
})
}
This changes SL at discrete times and that is the event: birth pulse.
The rest of your code doesn't really need modification but I'm assumning that ode passes parms literally, so I changed parameters in your function to parms.
times <- seq(1,24, by = 1)
parameters <- c(betaL = 0.9, gamma = 0.3, a= 0.0765, b = 0.06,kl = 50)
init <- c(SL=50,IL=0,RL=0,NL=50)
out <- as.data.frame(ode(y = init, times = times, func = SIR, parms = parameters, events=list(func=eventfun,time=times))
)
mydata1 <- data.frame(Period=rep((1:length(out$SL)),4),Population = c(out$SL,out$IL,out$RL,out$NL),
Indicator=rep(c("SusceptibleL","InfectedL","RecoveredL","TotalL"),each=length(out$SL)))
p1 = ggplot(mydata1,aes(x=Period,y=Population, group=Indicator))
f1 = p1+geom_line(aes(colour = Indicator))
f1
I find the results rather weird.
It's up to you to find a sensible set of parameters and to correct any further errors.
This works! The results definitely make sense now. You asked about the birth pulses- in most of the systems that I study, births do not occur year-round. Most species have seasonal breeding, i.e. all the reproducing females breed seasonally. From a disease ecology perspective, such birth pulses usually mean an increase in the proportion of susceptible individuals.
| common-pile/stackexchange_filtered |
"Subject" and "predicate" in sentences starting with "there"?
A third grade student has been asked to find out the subject and the predicate in the sentence:
There are a book and a pen on the table.
Here, it says that the real subject is "a book and a pen" but I know that "there" can also be called a "dummy subject".
What should be the most suitable subject and predicate in this context?
The real subject "there" because it's involved in the subject-auxiliary inversion and used in a question tag:
Subject-auxiliary inversion:
Are there a book and a pen on the table?
Question tag:
There are a book and a pen on the table, aren't there?
"A book and a pen" is a displaced subject. A displaced subject is not syntactically a subject, but it semantically corresponds to the subject in the non-existential counterpart.
And the predicate is everything except the "there"?
Yes @user100323
and the same thing applies to the the sentences starting with "it"?
@user100323 For example?
for example, "it is a pleasure working with you"
Yes, @user100323, in an "extraposition" construction like that, the subject is realized by the dummy "it".
| common-pile/stackexchange_filtered |
How can I change component without changing URL in Angular?
I would like to change component without changing URL. Let's assume that I have a component register. When I open my website I have url www.myweb.com. Then I would like to register by clicking sign up. I would like to display my component register without changing URL. Should I use ngIf or something else? Can you show me example how it should be done?
UPDATE I am sorry, but it seems to me that I was misunderstood. I tried
this solution:
login.component.ts:
showSignUp: boolean = false;
login.component.html:
<button (click)="showSignUp = true">Sign Up</button>
<register *ngIf="showSignUp"></register>
However when I clicking the button Log in I get this:
before:
after clicking:
After clicking the button Log in I would like to get a new website but with the same URL like this:
UPDATE
What do you think about solution shown below? In html file I will be checking whether variable authenticated is equal true. If so then I will display home component.
login() {
this.loading = true;
this.authenticationService.login(this.model.username, this.model.password)
.subscribe(
data => {
this.authenticated = true;
// this.router.navigate([this.returnUrl]);
},
error => {
this.authenticated = false;
this.alertService.error(error);
this.loading = false;
});
}
UPDATE
Unfortunately it doesn't work. Any ideas how can I use it with this button?
<button [disabled]="loading" class="btn btn-primary">Log in</button>
Unless you objectively define what you mean by "more optimal", this will be based on opinion.
I'm just wondering why you would not want to change the URL?
@JamieR I would like to have it done in the same way as Instagram has. You can take a look on it. There is the same situation that I would like to achieve. After authentication they have still url www.instagram.com.
You can use *ngIf and show the component in condition!
examle
In your sign up component, set a variable and change its value on click of sign up button. And display your register component on click of the login by pitting the condition in display
// sign up component
showRegister = false;
in your sign up component html
<register *ngIf="showRegister"></register>
Don't set variables used in templates as private. Production builds fail if you do.
I have updated my question because it seems to me that I described it in the wrong way first time round. Thank you for help.
you have to make another button for sing up and on click of that you need to show the register and hide login form. on lick of the login you are validating the login form and unless the form is valid you cannot do any thing else.
ngIf is the way to go on this kind of thing.
Just put in your component code something like
showSignUp: boolean = false;
then in template:
<button (click)="showSignUp = true">Sign Up</button>
<register *ngIf="showSignUp"></register>
And since you seem new to Angular, I'll mention that in order to use ngIf in template, your module needs to import the CommonModule like
import { CommonModule } from '@angular/common';
imports: [
CommonModule,
]
I have updated my question because it seems to me that I described it in the wrong way first time round. Thank you for help.
I read your revised question. Your approach to this is a bad idea. You should leverage the router to make a separate pages for /login and /signup and then navigate to your home page. Trying to keep the URL the same is a bad idea for a lot of reasons.
I have seperated URLs at the moment using routes. But I would like to have the same for welcome page which is a login component and home component which is a page that is visible after clicking the button Log in. Why in your opinion it is a bad idea? You can take a look on instagram. There is the same situation that I would like to achieve. After authentication they have still url www.instagram.com.
Yes, this is a perfect use case for ngIf. Try not to over engineer it.
| common-pile/stackexchange_filtered |
Which is the correct way to say it "who are you spending it with?" Or "whom are you spending it with?"
As per the grammar rules, if "I" is the subject of the sentence then the other person must the object. And generally whom is used in the objective form but in this case the prior format is more common than the latter. So which one is correct?
Much depends on location and audience. Some English speakers expect the proper use of "whom", and wince when ending a sentence with a preposition. Others could not care less.
While I know how to use "whom", perhaps because I'm American, I rarely use it. In most situations it sounds too formal, or even (to some extent) pretentious.
Then again, "Who are you spending it with?" already sounds somewhat stilted and formal, so in any situation where I might say something like that, I would probably feel obligated to use "whom" and reorganize the sentence appropriately. Without more context, I couldn't say what the informal version would be, but possibly something like:
Who are you going with?
Who is going with you?
Who else will be there?
and so on.
Again, it's a personal choice. Other English speakers might feel your example is perfectly ordinary conversation.
"With whom are you spending it?" is the "most correct". But in real life, when speaking, one would say "Who are you spending it with?". The word "whom" is very unusual in spoken text nowadays; most people use "who" for all cases, not just the nominative.
From the OED:
Although there are some speakers who still use who and whom according to the rules of formal grammar as stated here, there are many more who rarely use whom at all; its use has retreated steadily and is now largely restricted to formal contexts. The normal practice in modern English is to use who instead of whom (and, where applicable, to put the preposition at the end of the sentence): who do you wish to speak to?; who do you think we should support?
| common-pile/stackexchange_filtered |
Detrrminant of a matrix
I need to prove that $\det A_n \ne 0$, if $a_i \ne a_j$ and $a_i \ne 0$, where
$A_n$ is a matrix with the first row
$a_1 +a_2, a_2+a_3, \ldots , a_{n-1}+a_n , a_n$.
Second row consists of all products of two elemnts where at least one is $a_i$ or $a_{i+1}$ for $2i$ - entire. For example $a_{12} = \sum_{i \ne 1} a_1 a_i + \sum_{i \ne 2} a_2 a_i - a_1a_2$.
Third row consist of all products of three elements where at least one is $a_i$ or $a_{i+1}$ or $a_{i+2}$ for $3i$ - entire. For example $a_{13} = \sum_{i<j; i,j \ne 1} a_1 a_i a_j + \sum_{i<j; i,j \ne 2} a_2 a_i a_j - \sum_{i\ne 1,2} a_1a_2a_i$
and so on. Every entire of last row are $1$.
For example if $n=2$:
$
A_2=\begin{pmatrix}
a_1+a_2 & a_2 \\
1 & 1
\end{pmatrix}
; \det A_2 = a_1$.
$n=3$: $A_3= \begin{pmatrix}
a_1+a_2 & a_2+a_3 & a_3 \\
a_1a_2+a_1a_3+a_2a_3 & a_1a_2+a_1a_3+a_2a_3 & a_1a_3+a_2a_3 \\
1 & 1 & 1
\end{pmatrix}
$; $\det A_3 = a_1a_2(a_1-a_3)$.
$n=4$: $A_4 = \begin{pmatrix}
a_1+a_2 & a_2+a_3 & a_3+ a_4 & a_4 \\
a_1a_2+a_1a_3+a_1a_4+a_2a_3+a_2a_4 & a_1a_2+a_1a_3+a_2a_3+a_2a_4+a_3a_4 & a_1a_3+a_1a_4+a_2a_3+a_2a_4+a_3a_4 & a_1a_4+a_2a_4+a_3a_4 \\
a_1a_2a_3 + a_1a_2a_4+a_1a_3a_4+a_2a_3a_4 & a_1a_2a_3 + a_1a_2a_4+a_1a_3a_4+a_2a_3a_4 & a_1a_2a_3 + a_1a_2a_4+a_1a_3a_4+a_2a_3a_4 & a_1a_2a_4+a_1a_3a_4+a_2a_3a_4 \\
1 & 1 & 1 &1
\end{pmatrix};$
$\det A_4= a_1a_2a_3(a_1 - a_3)(a_1-a_4)(a_2-a_4) $.
May be it is a well-known determinant?
Did you try to do some particular cases with $;n=1,2,3;$ ...? I didn't understand the definition of the matrix, btw.
Hm, I wrote cases $n=2,3,4$.
| common-pile/stackexchange_filtered |
jdk1.8.0_25 no javac.exe
I've seen other questions like this but not concerning JDK1.8.1_25. There is no java.exe fin in the bin file. In fact there isn't much in the bin file at all like there is in JDK<IP_ADDRESS>. So when I'm trying to execute java programs from the cmd line, nothing is happening. When I type javac -version there is nothing found. I'm trying to follow a Lynda tutorial but this isn't helping as it isn't doing the same as tutorial although tutorial is using an earlier version of JDK but really I would of thought the latest version should work.
My %Path% is:
-C:\ProgramData\Oracle\Java\javapath;C:\MinGW\bin;C:\MinGW\msys\1.0\bin;C:\Program Files\Common Files\Microsoft Shared\Windows Live;C:\oraclexe\app\oracle\product\11.2.0\server\bin;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files\Microsoft SQL Server\110\Tools\Binn\;C:\Program Files\Windows Live\Shared;C:\Program Files\QuickTime\QTSystem\C:\Program Files\Java\jdk1.7.0_71\bin;
Wow didn't realise that was so long, that can't be right either can it !?!
Regards,
Caroline
If there is no java.exe or javac.exe file in bin folder of jdk1.8.0_25, probabaly your installation not perfect. Also in your path, you've configured the path to jdk1.7.0_71 instead of jdk1.8.0_25
Oh yes I see, I had changed that to jdk1.8.0_25 but changed it back again. No there is definitely no java.exe or javac.exe files anyway in the bin. I'll try re-installing I think - thanks :-)
A long %PATH% is normal.
If your 1.8 JDK is incomplete (it can happen), revert your jdk in the %PATH% to previous version, and also %JAVA_HOME%.
Remember to close any console windows and restart any applications for it to take effect :)
To test:
echo %JAVA_HOME%
java -version
Yes i think that's what i tried in %Path% - as you can see it's the previous version above.... I think I'll try re-installing jdk 8. Do I need to append the jdk8 file path to %Java_Home% too ? I'm just noticing I don't have that in my environment variables that %Java_Home% thing.
Reinstalling jdk8 should correctly set %JAVA_HOME%. If not, then yes, you should google it to see exactly what the value should be, and set it yourself in Control Panel -> System -> Advanced system settings (System Properties) -> Advanced tab -> Environment Variables -> User variables for Catess76 (or whatever your user name is.)
If your 1.8 JDK is corrupt, yes you should download it preferably from the official sun site and install again, and check afterwards that the %PATH% is correct. But if you revert to 1.7 then you just need to change the environment variables. Have a look again for %JAVA_HOME%, and note that it is in CAPS.
It's working now :-) although there is still no %JAVA_HOME%. path, it's working as i need it too - thankyou
Your path should include (probably start with) the following:
C:\Program Files\Java\jdk1.8.1_25\bin;
My jdk1.8.0_05\bin contains 53 files, 3,188,466 bytes, (including javac.exe,) and I doubt that they have drastically changed anything from 0_05 to 1_25, so if your bin does not contain anything like that, there must be something wrong with your installation. If so, then uninstall it and re-install it from scratch.
Also, if your path does really begin with a - character, or if it does really contain the string QTSystem\C:\ instead of QTSystem\;C:\ then you also have a corrupt path. (Your java 7 should have never worked.)
Ok I think I'm going to try re-installing JDK 8 and see how that goes and change path to relevant version. Back soon. Thanks
Ok I've reinstalled and amended the QTSystem so it looks correct and not corrupt, and have added C:\Program Files\Java\jdk1.8.0_31\bin to the end. lets see if it works. But I still can't see a %JAVA_HOME% path as someone suggested it should have below.
it IS recognising javac.exe now in command line anyway - fabulous, thankyou
Be careful, the path is traversed sequentially, so if jdk1.7.0_71\bin is before jdk1.8.1_25\bin in your path, then the javac.exe selected will be the javac of jdk7.
It's working now :-) thanks to all you lovely wonderful clever people .. thankyou
| common-pile/stackexchange_filtered |
Java processes vs. threads for thread affinity
I recently wrote some code[1][2] that tried using JNA to make calls to sched_setaffinity in an attempt to set the affinity of the process to a particular core. The first argument of the function sched_setaffinity is the process id.
Calling the function with pid as 0(referring to the process itself) works fine. However, I'd like to be able to set the affinity on a thread id basis rather than the process. Is there any way I could do that?
https://github.com/eQu1NoX/JavaThreadAffinity/blob/master/src/com/threads/ctest.c
https://github.com/eQu1NoX/JavaThreadAffinity/blob/master/src/com/threads/ThreadAffinity.java
There is a function called pthread_setaffinity_np that can set the CPU affinity mask of the thread thread to the CPU set pointed to by cpuset.
cpu_set_t cpuset;
CPU_ZERO(&cpuset);
CPU_SET(core_id, &cpuset);
pthread_t current_thread = pthread_self();
pthread_setaffinity_np(current_thread, sizeof(cpu_set_t), &cpuset);
This piece of code can set the a thread to the core(represented by core_id).
As far as I know, a Java Thread is not always matched to a thread in OS. So I'm not quite sure whether this piece of native code can help you.
| common-pile/stackexchange_filtered |
Can you develop Desktop(.exe) In Visual studio?
I Started learning Python 3-4 months ago and today I accidently saw a friend use VS 2019
I became curios and searched up the usage for it using python
It says Build WEB APPS using python...
Can I make .exe apps using VS 2019 using PYTHON by any chance?
VS will do nothing that you cannot do without it - it is just an IDE. It may wrap some things done manually into a click / gui-ish behaviour to simplify it but that is it.
You do not want to do it.
Python is an interpreted programming language which means that the code is being executed just after being read. Simple to debug, able to be changed without even stopping the application.
On the other side, .exe apps are compiled, that means translated to the efficient machine code. When you code in C++, the translation is needed to build the executable. As you get the .exe file, you do not understand its contents, so you can no longer change the behaviour of your built application. The native Windows apps are coded in compiled languages, preferably in C# (just-in-time compilation) or C++. Their code is understandable only for the machine.
That's great you are learning Python and that you want to see the results of your work in a form of native Windows apps. The truth is just that this language has been created for a different purpose.
As you opened VS 2019, you saw the button "Build web apps". It means that with a little help from Visual Studio you can run a Python server with a framework like Flask and create an interactive web service. Actually, Flask is used for API-s in many well-known projects like Pinterest, Netflix and Uber. When you deploy a service like these, you do not necessarily need an .exe.
Here you go!
https://learn.microsoft.com/en-us/visualstudio/python/learn-flask-visual-studio-step-01-project-solution?view=vs-2022
Yes you can write your python code as usual and then use pyinstaller and turn it to .exe
Also note that if your python code doesn't have GUI functionality then it will run in the background till you stop it.
If the python code uses console to output then don't use the no console option
Pyinstaller Docs - https://pyinstaller.readthedocs.io/en/stable/
Also the web apps part. Python is good at those with 2 mostly used frameworks:
Flask - https://flask.palletsprojects.com/en/2.0.x/
Django - https://docs.djangoproject.com/en/3.2/
| common-pile/stackexchange_filtered |
How to get duration a video - laravel
I want to get the duration of my videos when I upload them.
To do this, I upload my videos like this:
$video = Carbon::now()->timestamp . '_' .
$request->file('video')->getClientOriginalName();
$request->file('video')->move(
$this->getCorrectPathOnServerAndLocal('/assets/videos/videos'), $video
);
My movie is uploaded well.
now I want to get the duration of this video.
I'm using PHP-FFMpeg:
composer require php-ffmpeg/php-ffmpeg
$ffprobe = FFProbe::create(); //error
dd("test");
$duration = $ffprobe
->format($this->getCorrectPathOnServerAndLocal('/assets/videos/videos').$video) // extracts file informations
->get('duration');
but I got this error:
(2/2) ExecutableNotFoundException
Unable to load FFProbe
in FFProbeDriver.php (line 50)
at FFProbeDriver::create(array(), null)in FFProbe.php (line 207)
Did you install FFMpeg? If you installed, did you add it to your system PATH?
if I want to use this lib on server side, does it work?
@S.M_Emamian FFMpeg is not installed on your server
first install getID3 by composer require james-heinrich/getid3
then
$getID3 = new \getID3;
$file = $getID3->analyze($video_path);
$duration = date('H:i:s.v', $file['playtime_seconds']);
I personally created a Video CMS and found the easiest way to be using ID3 as follows:
public function getDuration($full_video_path)
{
$getID3 = new \getID3;
$file = $getID3->analyze($full_video_path);
$playtime_seconds = $file['playtime_seconds'];
$duration = date('H:i:s.v', $playtime_seconds);
return $duration;
}
Before I used ffmpeg like this:
// Get the video duration
$parameters = "2>&1 | grep Duration | cut -d ' ' -f 4 | sed s/,//";
$cmd_duration_ffmpeg = "$ffmpeg_path -i $full_video_path $parameters";
$duration = shell_exec($cmd_duration_ffmpeg);
Both options will work perfectly, choose whichever works best for you.
I'm getting Class 'getID3' not found @Chris
Using FFMPEG PHP library, and using FFprobe like this to get video duration in seconds:
$ffprobe = FFProbe::create();
$duration = $ffprobe->format($request->file('video'))->get('duration');
$duration = explode(".", $duration)[0];
| common-pile/stackexchange_filtered |
Changing image back to original after it is changed on hover?
I am attempting to use jQuery to hover over an image while it changes the other. I have that part done, the part I don't understand is when I hover over the image and then move the mouse off of it, how do I get the original image to come back? Any help would be greatly appreciated.
Here is what I have so far:
$(document).ready(function(){
$("#04").hover(function(){
$("#imgBig").attr("src", "imgLab10/04.jpg");
});
});
You can do this with pure CSS, you don't even need jQuery. There is an answer that explains this.
.hover() accepts two callbacks, one for hoverIn and one for hoverOut.
So you could do something like
$(document).ready(function(){
$("#04").hover(
function(){
$("#imgBig").attr("src", "imgLab10/04.jpg");
},
function() {
$("#imgBig").attr("src", "oldImg.jpg");
}
);
});
I'm not a fan of changing the img source because you can have lag or disconnect issues then your alternative image may now show. This can also be done without jQuery altogether.
.img-swap{
width: 100px;
height: 100px;
}
.img-swap .img-swap-alt{
display: none;
}
.img-swap:hover .img-swap-alt{
display: block;
}
.img-swap:hover .img-swap-def{
display: none;
}
<div class="img-swap">
<img class="img-swap-def" src="http://lorempixel.com/output/abstract-q-c-300-300-10.jpg"/>
<img class="img-swap-alt" src="http://lorempixel.com/output/food-q-c-300-300-1.jpg" />
</div
This is a nice approach! It will incur an increased loading time though, so beware if you have large images and lots of instances to apply this to.
Agree on the approach using pure-CSS whenever possible, and that this method works for smallish numbers of instances where all resources are downloaded during page load. Leverage sprites where possible and simply manipulate via CSS. Highest x-device/x-browser support.
The you have to use it like :
$( "#04" ).hover(
function() {
//When the mouse enter
$("#imgBig").attr("src", "imgLab10/04.jpg");
}, function() {
//When the mouse out
$("#imgBig").attr("src", "imgLab10/OriginalImage.jpg");
}
);
Hope this helps.
I recommend you use .prop() instead of .attr() because it will eventually become deprecated.
If you want to change the image back, you need to use .mouseenter() and mouseleave()
$(document).ready(function() {
$("#04").mouseenter(function() {
$("#imgBig").prop("src", "imgLab10/04.jpg");
});
$("#04").mouseleave(function() {
$("#imgBig").prop("src", "orignalPath");
});
});
I think this makes the code easier to understand because you're explicitly coding for both events, but that's just my opinion and .hover() also works well.
JQuery .hover() method takes two function parameters. One is onMouseover event and the second is onMouseout event.
https://api.jquery.com/hover/
.hover(handlerIn, handlerOut)
handlerIn
Type: Function( Event eventObject )
A function to execute when the mouse pointer enters the element.
handlerOut
Type: Function( Event eventObject )
A function to execute when the mouse pointer leaves the element.
| common-pile/stackexchange_filtered |
How do I check if a network drive is online/offline without my program hanging?
I want to do some IO operations (reading files, listing folder content, etc) on a shared/network folder (\\JoulePC\Test\). If the folder is offline then the program will freeze for quite a while EVERY TIME I try to access it.
What I need to build is something like this:
function DriveIsOnline(Path: string): Boolean;
The function should return an answer quickly (under 1 second). I would use the DriveIsOnline before performing any IO operations on that remove folder.
__
The API function GetDriveType will return 1 (which means 'The root path is invalid') if the drive is offline. Will it be logically correct to consider this answer ('1') as an indication that the drive is offline?
Do the read in a worker thread, or use overlapped I/O.
@RemyLebeau - But then I will have to wait anyway until the thread finishes :)
@RemyLebeau - oh... I could end the thread after 1 second...
Could try temporarily lowering the network timeout property if using Indy components.
@ThisGuy - I don't use Indy. I simply want to list all files in that folder.
@Altar: Don't kill the thread. Let it timeout and terminate gracefully. If you use overlapped I/O in a thread, you can specify a timeout on the I/O so the thread can terminate itself, while still not blocking your main thread. However, how are you planning on enumerating the files? That is a different issue than simply checking the folder for its online status. File enumeration is synchronous. In that case, I would simply do the enumeration in a thread without timeouts, report results to the main thread as needed, and let the thread handle any errors reported if the folder is/goes offline.
You have to ask. If it times out, then perhaps it's offline. There's no other way.
@RemyLebeau - Sorry. I think didn't explained clearly what I want to achieve: I want to do some operations (doesn't matter what) on a network folder. If the folder is offline then the program will freeze for quite a while. What I need is something like this: function DriveIsOnline(Path): boolean. The function should return an answer quickly. I would use the DriveIsOnline before using the other IO operations on that remove folder.
There is really no point in checking ahead of time if it is offline or not. It could go offline at any time, even in the middle of your operations. You have to be prepared to handle that either way, so you may as well just start the operations unconditionally and let them fail if they need to. As for the freeze, doing the operations in a worker thread would avoid freeing the rest of the app.
I agree with the second part but not with the first one. Why waiting soooo long at application start up (if the drive is offline) if I can check it (supposing it can be done) and move on in less than a second?
| common-pile/stackexchange_filtered |
Screen resolution scale in JavaFx game
I'm creating a board game in JavaFx, and it works fine in my desktop PC, with a 1920x1080 screen. When i try to open it in my Laptop (which is 1920x1080 as well, but with the default screen size at 125%), it doesn't show the elements properly anymore (their size overflows the bounds of the screen). The only way to make the app work properly is to run it on a 1920x1080 screen with default scree size at 100%
I need a way to scale the whole stage to the right resolution
This is my Main.java:
public class Main extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) throws IOException {
final double WIDTH = Toolkit.getDefaultToolkit().getScreenSize().getWidth();
final double HEIGHT = Toolkit.getDefaultToolkit().getScreenSize().getHeight();
Parent board = FXMLLoader.load(getClass().getResource("/board.fxml"));
Pane innerBoard = ((Pane)board.getChildrenUnmodifiable().get(0));
Assert.assertCmp(innerBoard.getId(), "BOARD");
Scene scene = new Scene(board, WIDTH, HEIGHT);
scene.getStylesheets().add(getClass().getResource("/style.css").toExternalForm());
primaryStage.setScene(scene);
primaryStage.setFullScreen(true);
primaryStage.setResizable(true);
innerBoard.setVisible(false);
primaryStage.setFullScreenExitHint("");
primaryStage.show();
innerBoard.setVisible(true);
}
}
This is the FXML:
<Pane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="1080.0" prefWidth="1920.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1">
<children>
<Pane id="BOARD" fx:id="innerBoard" layoutX="356.0" layoutY="-7.0" style="-fx-background-color: #cfffd1;">
<children>
<!-- Lots of children -->
</children>
</Pane>
</children>
</Pane>
What does "it stops working" mean? Please describe what happens when this occurs.
@jewelsea The description was misleading, it doesn't stop working. I corrected it
Toolkit is an awt class. You shouldn't be mixing UI toolkits. If you want screen dimensions in JavaFX, you can get them from the JavaFX Screen (this is not related to your issue).
Do you need to "scale"? In this context, scaling is usually a kind of transform. Or instead, do you need to use layout managers and constraints so that the scene adapts to various window sizes? With scaling, everything will get bigger or smaller, including text, potentially stretching items non-proportionally. With layout management, the nodes will adjust their size and placement to available space.
To understand the difference, resize your stackoverflow window, layout management is applied. Adjust your browser zoom settings using a menu, scaling is applied.
Since you’re making your Stage fullscreen, forget about obtaining the screen size and just do Scene scene = new Scene(board);. The Scene will fill the fullscreen Stage. Now, how to make the board scale properly might be another matter, but it is certainly doable.
If the purpose is to scale by transform, this might be a duplicate.
I recommend you forego Pane and numeric positions and sizes. You want your board to be capable of displaying in any resolution; explicit positions and sizes directly contradict that.
Layouts are the best way to make your board fit into any size.
(Of course, layouts only work with rectangular board regions; I will assume you aren’t going for something complex like a circular or hexagon-based board, or a board with winding paths. In those cases, a Canvas may be a better choice than a Pane.)
GridPane allows setting RowConstraints and ColumnConstraints, each of which can be percentage-based. If rows and columns have a size that is a percentage of the width of their parent, you get scaling for free. Here is a very primitive rendition of a Monopoly board:
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.Node;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.RowConstraints;
import javafx.scene.layout.ColumnConstraints;
import javafx.scene.layout.Priority;
public class MonopolyBoard
extends Application {
// Source:
// https://commons.wikimedia.org/wiki/File:Store_Building_Flat_Icon_Vector.svg
private static final String SIDE_SPACE_IMAGE_URI =
"https://upload.wikimedia.org/wikipedia/commons/thumb/5/53"
+ "/Store_Building_Flat_Icon_Vector.svg"
+ "/240px-Store_Building_Flat_Icon_Vector.svg.png";
// Source:
// https://commons.wikimedia.org/wiki/File:Car_icon_transparent.png
private static final String CORNER_SPACE_IMAGE_URI =
"https://upload.wikimedia.org/wikipedia/commons/7/7e"
+ "/Car_icon_transparent.png";
@Override
public void start(Stage stage) {
GridPane grid = new GridPane();
Node[] row = new Node[11];
row[0] = createSpace(CORNER_SPACE_IMAGE_URI);
row[10] = createSpace(CORNER_SPACE_IMAGE_URI);
for (int i = 1; i <= 9; i++) {
row[i] = createSpace(SIDE_SPACE_IMAGE_URI);
}
grid.addRow(0, row);
for (int i = 1; i <= 9; i++) {
grid.add(createSpace(SIDE_SPACE_IMAGE_URI), 0, i);
grid.add(createSpace(SIDE_SPACE_IMAGE_URI), 10, i);
}
row[0] = createSpace(CORNER_SPACE_IMAGE_URI);
row[10] = createSpace(CORNER_SPACE_IMAGE_URI);
for (int i = 1; i <= 9; i++) {
row[i] = createSpace(SIDE_SPACE_IMAGE_URI);
}
grid.addRow(10, row);
grid.getColumnConstraints().add(createColumnConstraints(2 / 11.0));
for (int i = 1; i <= 9; i++) {
grid.getColumnConstraints().add(createColumnConstraints(1 / 11.0));
}
grid.getColumnConstraints().add(createColumnConstraints(2 / 11.0));
grid.getRowConstraints().add(createRowConstraints(2 / 11.0));
for (int i = 1; i <= 9; i++) {
grid.getRowConstraints().add(createRowConstraints(1 / 11.0));
}
grid.getRowConstraints().add(createRowConstraints(2 / 11.0));
stage.setScene(new Scene(grid, 50 * 11, 50 * 11));
stage.setTitle("Monopoly");
stage.show();
}
private ColumnConstraints createColumnConstraints(double percentage) {
ColumnConstraints constraints = new ColumnConstraints();
constraints.setPercentWidth(percentage * 100);
constraints.setHgrow(Priority.ALWAYS);
return constraints;
}
private RowConstraints createRowConstraints(double percentage) {
RowConstraints constraints = new RowConstraints();
constraints.setPercentHeight(percentage * 100);
constraints.setVgrow(Priority.ALWAYS);
return constraints;
}
private Node createSpace(String imageURI) {
BorderPane container = new BorderPane();
container.setStyle(
"-fx-border-width: 1px;"
+ " -fx-border-style: solid;"
+ " -fx-background-image: url('" + imageURI + "');"
+ " -fx-background-position: center;"
+ " -fx-background-repeat: no-repeat;"
+ " -fx-background-size: contain;");
return container;
}
public static void main(String[] args) {
launch(args);
}
}
In addition to using the percentage properties of RowConstraints and ColumnConstraints, the above code takes advantage of CSS image scaling using -fx-background-size: contain.
Resize (or maximize) the window to see the scaling at work. Obviously, if it were fullscreen, the same scaling would apply.
| common-pile/stackexchange_filtered |
android.support.v7.widget.SwitchCompat render error in targetSdkVersion 24 (Android N)
I am using
dependencies {
compile 'com.android.support:appcompat-v7:24.0.0'
}
for
android {
compileSdkVersion 24
buildToolsVersion "23.0.3"
minSdkVersion 18
targetSdkVersion 24
}
I have an Activity with a theme
<style name="BaseTheme" parent="Theme.AppCompat.Light.NoActionBar">
</style>
and would like to use a layout with switches. I used
<android.support.v7.widget.SwitchCompat />
earlier (with older SDK versions) and it worked fine. Now however, SwitchCompat switches render wired. Here is what I get for the two different switches in my layout:
<android.support.v7.widget.SwitchCompat
android:text="android.support.v7.widget.SwitchCompat"/>
<android.support.v7.widget.SwitchCompat
android:text="Switch" />
In OFF
and in ON mode
Is this a bug in the Android N SDK? Or the appcompat-v7:24.0.0? Od did I miss something?
The problem is --no-crunch in combination with targetSdkVersion 24. Removing --no-crunch solved the issue for me.
I am using Xamarin, so I had <AndroidResgenExtraArgs>--no-crunch </AndroidResgenExtraArgs> in my .csproj file. I don't know where is --no-crunch specified in native android but I guess it won't be a problem to find id.
| common-pile/stackexchange_filtered |
Can we use bash here document to run perl script?
I run the below perl script as a bash here document. My intention is that a variable is read from STDIN, then the arithmetic calculation is done and then printed.
However, the program is finished at once without waiting for input from STDIN.
A warning "Use of uninitialized value $input in multiplication (*) at - line 6." is printed out before the 2 strings in line 4 and line 6 are printed. Note that no prompt exists to read the STDIN.
Why would this happen?
I would like to combine the here document in bash and the perl script, so the perl script with very few lines can be run in the shell without bothering to write a script file.
(I know perl -e option is an alternative, but I just wonder why my method doesn't work.)
bash-4.1$ bash
bash-4.1$ perl <<'EOF'
> use strict;
> use warnings;
> my $input;
> print "Please enter a number:";
> $input=<STDIN>;
> print 2+2*3.141592654*$input."\n";
> EOF
Use of uninitialized value $input in multiplication (*) at - line 6.
Please enter a number:2
bash-4.1$
| common-pile/stackexchange_filtered |
Not allow same email to register multiple times
I would like my newsletter signup to only allow diffrent emails to signup and not allow the same email to sign up multiple times with a message email is allready in use. I cant seem to figure it out any help would be appreciated. The code is below i added the code i thought was usefull if u need more to figure it out i can post it, its a small app in a bigger project just for the email newsletter signup.
newsletter template
{% load static %}
{% block page_header %}
<div class="container header-container">
<div class="row">
<div class="col"></div>
</div>
</div>
{% endblock %}
<div id="delivery-banner" class="row text-center">
<div class="col bg-success text-white">
<h4 class="logo-font my-1">Sign up to Newsletter and get 5% discount</h4>
</div>
<div class="content-wrapper text-center bg-warning container-fluid" id="newsletter-wrapper">
<form v-on:submit.prevent="onSubmit">
<div class="card text-black bg-warning mb-3">
<div class="card-footer">
<div class="alert alert-success" role="alert" v-if="showSuccess">
You are Subscribed to our Newsletter!
</div>
<h2>Subscribe to our newsletter</h2>
<div class="form-group">
<input type="email" class="" v-model="email" name="email" class="input" placeholder="e-mail address" required>
</div>
<div class="form-group">
<button class="btn btn-success ">Submit</button>
</div>
</div>
<div class="social">
<a target="_blank" rel="noopener noreferrer" href="https://facebook.com/" class="btn btn-social-icon btn btn-primary btn-outline-facebook "><i class="fa fa-facebook"></i></a>
<a target="_blank" rel="noopener noreferrer" href="https://youtube.com/" class="btn btn-social-icon btn btn-danger btn-outline-youtube"><i class="fa fa-youtube"></i></a>
<a target="_blank" rel="noopener noreferrer" href="https://twitter.com/" class="btn btn-social-icon btn btn-info btn-outline-twitter"><i class="fa fa-twitter"></i></a>
<a target="_blank" rel="noopener noreferrer" href="https://linkedin.com/" class="btn btn-social-icon btn btn-dark btn-outline-linkedin"><i class="fa fa-linkedin"></i></a>
</div>
</form>
</div>
</div>
<script>
var newsletterapp = new Vue({
el: '#newsletter-wrapper',
data () {
return {
email: '',
showSuccess: false
}
},
methods: {
onSubmit() {
console.log('onSubmit')
fetch('/api/add_subscriber/', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRFToken': '{{ csrf_token }}'
},
body: JSON.stringify({'email': this.email})
})
.then((response) => {
return response.json()
})
.then((data) => {
console.log(data)
this.showSuccess = true
this.email = ''
})
.catch(function(error) {
this.showSuccess = false
console.log('Error:', error);
});
}
}
})
</script>
admin.py
from django.contrib import admin
from .models import Subscriber
admin.site.register(Subscriber)
models.py
from django.db import models
class Subscriber(models.Model):
email = models.EmailField(max_length=255)
date_added = models.DateTimeField(auto_now_add=True)
def __str__(self):
return '%s' % self.email
views.py is empty
Just pass unique=True to the emailField. i.e. email = models.EmailField(max_length=255, unique=True) and django will take care of preventing duplicates.
For whatever field you want it to be duplicated you can use unique=True in the definition of the field. Your models has to define something like the following.
from django.db import models
class Subscriber(models.Model):
email = models.EmailField(max_length=255, unique=True)
date_added = models.DateTimeField(auto_now_add=True)
def __str__(self):
return '%s' % self.email
I tried the two answers and it dident work ithink its the vue.js code that is hindering it i added some more code to show. I tried both answers below and nothing happend.
And you ran makemigrations and migrate just to double check?
Yes i forgot to migrate i tried both solutions but the other one dident work but urs did after migrations. You got any way with that code to add a message that sais that email is already registerd if you enter a email that is already registerd?
Best way to achieve that is through serializers.ModelSerializer you can create a new questions with that and link here to get more context about what you want to achieve.
Another approach is to use get_or_create like if the subscriber already exists return already exists msg if not create one. Your api_add_subscriber function will be
def api_add_subscriber(request):
data = json.loads(request.body)
email = data['email']
subscriber, created = Subscriber.objects.get_or_create(email=email)
if created:
success = True
msg = "You subscribed!"
else:
success = False
msg = "This email has already subscribed!"
return JsonResponse({'success': success, 'msg': msg})
And you handle accordingly in the frontend;
It works but definitely the restriction in the database is required unique=True to spread the constraint across al the system. Best practice could be mix with a serializer.ModelSerializer.
def clean_email(self):
if User.objects.filter(email=self.cleaned_data['email']).exists():
raise forms.ValidationError("the given email is already registered")
return self.cleaned_data['email']
add the code above in your models.py
| common-pile/stackexchange_filtered |
How to use vlookup and countif together to get needed result
I am trying to come up with result for the following problem:
I have a spreadsheet with two sheets - Report and Groups.
Report sheet has two columns - UPI and Disabled groups
Group sheet has three columns - UPI, Group Name and Status.
Every time I type 'Disable' in column Status I want that to reflect as count in sheet Report, column Disabled groups
I have been trying to combine vlookup and countif, but with no luck so far. Any ideas how to get to resolved?
Thank you!
Why the vlookup? It sounds like you need countifs: =COUNTIFS(Groups!C:C,"Disable",A:A,Groups!A1). This makes the assumption that C:C is the Status column. A:A would be making sure whatever is in column A of "Report" (UPI or Group Name) are the same.
If the Report Sheet has the UPI in column A, first row is headers, you can use this formula in column B
=countifs(Group!A:A,A2,Group!C:C,"disable")
in words: in the Group sheet, count all rows where column A has the same word as in cell A2 in this sheet AND the column D has the word "disable".
Adjust the formula to your scenario and copy down.
Amazing! That worked pretty good. Thank you so much :)
| common-pile/stackexchange_filtered |
Need guidance to simplify this query
We have a huge query with many conditions.
However, we feel that some of the conditions are irrelevant
can you please let me know if where clause here, can be removed
Please find below excerpt of the huge query ( the sub-query) with where clause
SELECT f1, ... f10
FROM A
JOIN
SELECT f1, f2 ... f10
FROM B where PROC_DT IN (SELECT PROC_DATE FROM C)
ON A.ID = B.ID
WHERE ISNOTNULL(PROC_DT)
I think the query will already validate the PROC_DATE in getting data from table B. so can we remove the where clause here.
Can someone please confirm my findings
I think the query will already validate the PROC_DATE in getting data from table B how can anyone know that? You are the one who has access to the actual data.
@forpas of course you can -- it can't be null because of PROC_DT IN (SELECT PROC_DATE FROM C)
@Hogan there are 2 where clauses here. To which are you referring and to which is the OP referring? Which where can or can't be removed?
@forpas the where is not null statement -- that was implied where he said (in just the sentence before) it will already validate because it is getting the data from b.
yes you are correct, because of the in it can't be null. I would use an inner join instead, in some cases it will be faster.
SELECT f1, ... f10
FROM A
JOIN B ON A.ID = B.ID
join (SELECT DISTINCT PROC_DATE FROM C) AS X ON B.PROC_DT = X.PROC_DATE
| common-pile/stackexchange_filtered |
Flutter drag and drop items between multiple lists
I'm trying to implement a two-level drag and drop list in Flutter with draggable sections and draggable items within those sections, that can be dragged from one section to another. I found the drag_and_drop_lists package. Functionality-wise it is exactly what I'm looking for, but it seems to be no longer maintained and didn't feel smooth when I tried it out.
I also looked at Draggable and DragTarget. Combined with columns it seems to be easy to implement the required functionality, but again, it doesn't feel smooth. Some issues
The drag target has to have a minimum height to be able to precisely drop something on it, which means I need to add additional space to the beginning or end of the list
Wrapping list items in the drag target works, but it feels unnatural. The drag targets should instead be offset by 50% item height (this is how dragging works with ReorderableListView), but that doesn't seem to be possible.
It doesn't animate (although that's probably something I could figure out somehow...)
Do you have any recommendations, other than to reimplemented the ReorderableListView (which seems quite complicated)?
| common-pile/stackexchange_filtered |
Recover DHCP lease if it has been lost
So my system lost it's DHCPv4 lease. Since this is the WAN uplink, the system then became unreachable. I can't see any trace that it has tried to recovery from this.
Apr 3 00:31:47 mistik systemd-networkd[1519076]: vlan20: DHCP lease lost
Apr 3 00:31:47 mistik systemd-networkd[1519076]: vlan20: DHCPv4 address x.x.x.x/24 via x.x.x.1
In RedHat you have "PERSISTENT_DHCLIENT" that can be set in the interface configuration files, if you don't set it, it will retry forever (I think).
How do I instruct netplan to retry forever?
You've provided no OS/release details; but do mention an off-topic system, so why ask here? Please read https://askubuntu.com/help/on-topic and clarify why you're asking here.
Have you tried restarting networking?
| common-pile/stackexchange_filtered |
How to restart the program? (Restart button in game)
I am making a game and when you loose there is a Play Again button. I'd like to when you hit that have the game totally start over. It may seem like a basic question but it's within a class and it's not at the end of the program so it can't just be one big while to go back to the top. Any ideas?
This cannot be said without a code. 2. You do need to provide some kind of a global loop.
@Beginner what do you mean? There is no global loop. The only looping thing is the run class which handles calling other classes and running some things. I don't want to post my whole code. I don't know what code you would require as there is not much other then that run class that deals with looping.
@Fogest Without seeing the code it will be very hard to help you.
@Fogest what is the first method that you call in the run/main method?
Call that method, maybe?
@Mr1159pm yeah I could, but... that would mean that all variables and GFX drawings are not reset unless I added that all.
If you have some function to initialize all the things that need initializing (for instance, take the contents of your constructor and put it in an init() function), then the "Play Again" button can just call init() to reset everything.
I'm quite new I don't have a full understanding of constructors but the only thing I think may have one is the class dealing with GFX and this would be it public void paintComponent(Graphics g). If that is what your talking about how would you go about doing that?
Do you have a method that you call at the beginning of the game?
Add action listener to the play again button and from that action listener call that method.
I am just guessing here...
public class draw extends JPanel implements KeyListener,MouseListener{ That is my class. What actionlistener would I be adding to it?
You said in your question that you have a big button at the end of the game. Add action listener to that button then from the method action preformed call your start method (or whatever it's called).
Oh it's not a swing button it's a button made in photoshop and when clicked in the specific area of the image it is suppose to restart.
| common-pile/stackexchange_filtered |
Looking to update from google-analytics.com/ga.js to stats.g.doubleclick.net/dc.js with old code
I would like to change google-analytics.com/ga.js to stats.g.doubleclick.net/dc.js
My current code (old, but afraid to change it -- inherited) is
<script type="text/javascript">
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>
<script type="text/javascript">
try {
var pageTracker = _gat._getTracker('UA-051510-6');
pageTracker._setDomainName('mydomain.org');
pageTracker._addIgnoredOrganic('mydomain.org');
pageTracker._setAllowHash(false);
pageTracker._setAllowLinker(true);
pageTracker._trackPageview();
} catch(err) {}</script>
I tried changing it to
<script type="text/javascript">
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "stats.g.doubleclick.net/dc.js' type='text/javascript'%3E%3C/script%3E"));
</script>
But got an error saying it couldn't load, since it was looking in localhost:dc.js
Any help appreciated!
I think you should update to Classic async code (Universal Analytics doesn't support doubleclick yet) like this:
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-051510-6']);
_gaq.push(['_setDomainName', 'mydomain.org']);
_gaq.push(['_setAllowLinker', true]);
_gaq.push(['_addIgnoredOrganic', 'mydomain.org']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 'stats.g.doubleclick.net/dc.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
_setAllowHash is deprecated
Thanks for all who helped. Essentially I just had to remove the www since it was tyring to pull www.stats.g.doubleclick.net/dc.js
So final code was
<script type="text/javascript">
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://");
document.write(unescape("%3Cscript src='" + gaJsHost + "stats.g.doubleclick.net/dc.js' type='text/javascript'%3E%3C/script%3E"));
</script>
| common-pile/stackexchange_filtered |
Unity Container with Composition Root
I am new to DI and unity container. I am trying to use Unity with Composition Root. I have all my unity mappings/registrations in app.config file and just want to centralise all the resolve calls for my application.
The Application has many classes and very nested object graph created using constructor injection. So in a centralise location I want to create this object graph and then start make the call to do the actual work.
Please suggest a good way to implement composition root with unity.
Thanks!
What kind of application are you working on? Different application types have different ideal composition root locations.
I can suggest you a principle of composition root.
Composition root is an application infrastructure component so only application should have it and it is the unique location where modules are composed together.
Moreover, It depends on your application that you are developing.
For instance:
- Console application . It's main method.
- ASP.NET MVC application. It's global.asax
So no matter what is DI container. you can easily organize Composition root if you understand the principle behind that.
I'm not using Unity but I think, It's not much different with others
Hope it helps for you.
Thanks! for the reply, My app is a batch process. After reading many views including yours I am feeling to create a dedicated static class to build the object graph. Somewhat like this http://blog.anthonybaker.me/2011/02/factory-pattern-using-unity-application.html
| common-pile/stackexchange_filtered |
How can I hide children of draft pages using wp_list_pages()?
I'm displaying a simple sitemap with wp_list_pages();
$args = array(
'sort_column' => 'menu_order',
'title_li' => '',
'post_status' => 'publish'
);
wp_list_pages( $args );
The problem is that by default this also shows the published children of draft pages, like so :
Page 1 (published) -> displayed
--- Page 2 (draft) -> not displayed
------ Page 3 (published) -> displayed
What I would like to achieve is :
Page 1 (published) -> displayed
--- Page 2 (draft) -> not displayed
------ Page 3 (published) -> not displayed
I suspect a custom Walker would do the trick, but I could never really understand how those work..
Is there a way to hide those child pages without having to set them all to draft ?
Edit:
To clarify, let's try some imagery. So you have a tree with the complete hierarchy of your pages. We are climbing up the tree. The moment we encounter a a draft branch, we cut it down. Naturally all the other branches attached to it further along are also discarded (no matter if they are drafts or not). I hope that explains it better.
Here is an example with a somewhat deep hierarchy :
Page 1 (published) -> displayed
--- Page 2 (draft) -> not displayed <- Cut here and exclude all further children
------ Page 3 (published) -> not displayed
--------- Page 4 (published) -> not displayed
------------ Page 5 (draft) -> not displayed
--------------- Page 6 (published) -> not displayed
Great answers above. I took on the challenge trying to find yet another way to solve this.
The exclude parameter:
We could try:
'exclude' => wpse_exclude_drafts_branches()
where:
function wpse_exclude_drafts_branches()
{
global $wpdb;
$exclude = array();
$results = $wpdb->get_col( "SELECT ID FROM {$wpdb->posts} where post_status = 'draft' AND post_type = 'page' " );
$exclude = array_merge( $exclude, $results) ;
while ( $results ):
$results = $wpdb->get_col( "SELECT DISTINCT ID FROM {$wpdb->posts} WHERE post_type = 'page' AND post_status = 'publish' AND post_parent > 0 AND post_parent IN (" . join( ',', $results ) . ") " );
$exclude = array_merge( $exclude, $results) ;
endwhile;
return join( ',', $exclude );
}
and the number of queries depends on the tree depth.
Update:
The exclude_tree parameter:
I just noticed the exclude_tree parameter mentioned on the Codex page, so I wonder if this would work (untested) to exclude the whole of the draft nodes branches:
$exclude = get_posts(
array(
'post_type' => 'page',
'fields' => 'ids',
'post_status' => 'draft',
'posts_per_page' => -1,
)
);
and then use:
'exclude_tree' => join( ',', $exclude ),
with wp_list_pages().
That's nice and short. I think you should implode $exclude before returning, the exclude parameter of wp_list_pages() does't accept an array.
@mike23 thanks, I updated the answer ;-)
I wonder if we can simplify this much more with the exclude_tree parameter, to exclude the whole draft branches.
I can confirm that exclude_tree option you suggested in your update does work. Which really is kind of funny, considering the amount of code that has been produced to answer this question. I feel this should be the accepted answer.
@ialocin oh, it's maybe not as elegant and deep as the other solutions you and G.M. provided, but I'm glad to hear it works ;-) I'm not sure why I didn't notice this parameter before on the Codex page, but I guess that can happen when putting the nose too deep into the source code instead ;-)
Ok, maybe its not as fancy of a solution :) But its built-in and only needs about 8 extra lines code, so thats actually not that bad. I guess you are right, that is what happens.. ;)
I removed my prev comment because now this works. And +1. What exclude_tree does is what @ialocin did in his code: to call get_page_children inside a loop. Now that function [recursively call itself].(http://developer.wordpress.org/reference/functions/wp_parse_id_list/). Inside a for loop of possibly hundrends of posts. Result: to do this task 8 lines are required, but is possible that dozen of hundrends functions are called. I have no doubt that this is the right WordPress way, but as someone said in The Loop: "nobody does things the f**king WordPress way... and thank God for that!"
Yea, the almighty WordPress way... ;) @G.M.
@G.M. I guess the ways of WordPress are inscrutable ;-) Thanks, I also removed my related comment. It looks like there was a bug in exclude_tree with multiple arguments that was reported 6 years ago but it was fixed 5 months ago according to this trac ticket.
Wow I had no idea exclude_tree existed. In the end it seems this answer is the simplest, thanks all for the great code, I'm learning a lot from it.
Sincerly I found custom walkers annoying: sometimes what can be done with a simple filter require an entire class to coded and, but probably it's me, I don't really like logic behind WordPress walkers.
This is the reason why I often use a trick to filter elements before they are walked. It is a really simple Walker class:
class FilterableWalker extends Walker {
private $walker;
function __construct( Walker $walker ) {
$this->walker = $walker;
}
function walk( array $elements = null, $max_depth = null ) {
$args = func_get_arg( 2 );
$filtered = apply_filters( 'filterable_walker_elements', $elements, $args, $this );
if ( is_array( $filtered ) ) {
$walk_args = func_get_args();
$walk_args[0] = $filtered ;
return call_user_func_array( array( $this->walker, 'walk' ), $walk_args );
}
return call_user_func_array( array( $this->walker, 'walk' ), func_get_args() );
}
function getWalker() {
return $this->walker;
}
function getWalkerClass() {
return get_class( $this->getWalker() );
}
}
This is an all-purpose, reusable walker that enable filtering items before they are passed to real walker that must be passed in constructor.
In your case, you should do something like:
$args = array(
'sort_column' => 'menu_order',
'title_li' => '',
'post_status' => 'publish',
'skip_draft_children' => 1, // <- custom argument we will use in filter callback
'walker' => new FilterableWalker( new Walker_Page ) // <-- our walker
);
$pages = wp_list_pages( $args );
Now you can code a filter callback to filter pages using 'filterable_walker_elements' hook fired by FilterableWalker class:
add_filter( 'filterable_walker_elements', function( $elements, $args, $filterable ) {
$walker = $filterable->getWalkerClass();
if (
$walker === 'Walker_Page'
&& isset( $args['skip_draft_children'] )
&& $args['skip_draft_children'] // <-- our custom argument
) {
$ids = array_filter( array_unique( wp_list_pluck( $elements, 'post_parent' ) ) );
$parents = get_posts(
array(
'post__in' => $ids, 'post_status' => 'publish',
'fields' => 'ids', 'post_type' => 'page',
'nopaging' => true
)
);
$pages = $elements;
foreach( $pages as $i => $page ) {
if ( $page->post_parent !== 0 && ! in_array( $page->post_parent, $parents, true ) ) {
unset($elements[$i]);
$self_i = array_search( $page->ID, $parents, true );
if ( $self_i !== FALSE ) unset( $parents[$self_i] );
}
}
}
return $elements;
}, 10, 3 );
Thanks for your detailed answer ! Although it doesn't seem to do what I'm after. I am displaying a sitemap of pages (like a tree), whenever we arrive at a page that is in draft, I want to stop showing any other page further down in the hierarchy of that particular branch. I'll try to fiddle with your code to see what I can find.
@mike23 I edited the answer, now it should work. Before editing only direct children of a draft pages were removed, now any page down in the hierarchy of a draft page should be removed.
@G.M. Does this work no matter at which depth the first draft page is ?
@mike23 yes, absolutely
Making use of a custom Walker is actually not that hard, it basically goes like this:
Create a class;
A class is a collection of variables and functions working with these variables.
By extending another one;
The extended or derived class has all variables and functions of the base class [...] and what you add in the extended definition.
Like this:
class Extended_Class extends Base_Class {
// code
}
Which gives you the possibility to change/extend the methods aka functions of the base class that has been extended. Additionally you can/could extend by adding methods or variables to the extended class.
To fully understand and make use of the possibilities it is necessary to get deeper into OOP: Classes and Objects aspects of PHP. But that would be too much here and not the rightplace anyway.
So lets get back to WordPress and wp_list_pages(). The class we want to extend to make use of with wp_list_pages(), the Walker_Page class - source -, itself has been derived by extending the class Walker - source.
Following the above explained schema we are going to do the same:
class Wpse159627_Walker_Page extends Walker_Page {
// code
}
Now Walker_Page has two variables - $tree_type and $db_fields - and four methods - start_lvl(), end_lvl(), start_el() and end_el(). The variables won't concern us, regarding the methods we are at least have to take a closer look at start_el() and end_el().
The first thing to see is that those two methods have the parameter $page:
@param object $page Page data object.
Which contains all the relevant data we need, like the post_parent, and is pretty much a WP_Post/$post/"$page" object. Given back by the get_pages() return
An array containing all the Pages matching the request, or false on failure. The returned array is an array of "page" objects.
inside the wp_list_pages() function.
What we need to check is the post status of the current page parent, for doing this the function get_post_status() is available. Like determined we can use the $page object available to do so.
$page_parent_id = $page->post_parent;
$page_parent_status = get_post_status( $page_parent_id );
Now we can use this to check against the status of the currents page parent:
if ( $page_parent_status != 'draft' ) {
// code
}
Lets implement it in our extended Walker class:
class Wpse159627_Walker_Page extends Walker_Page {
function start_el( &$output, $page, $depth = 0, $args = array(), $current_page = 0 ) {
$page_parent_id = $page->post_parent;
$page_parent_status = get_post_status( $page_parent_id );
if ( $page_parent_status != 'draft' ) {
if ( $depth )
$indent = str_repeat("\t", $depth);
else
$indent = '';
extract($args, EXTR_SKIP);
$css_class = array('page_item', 'page-item-'.$page->ID);
if( isset( $args['pages_with_children'][ $page->ID ] ) )
$css_class[] = 'page_item_has_children';
if ( !empty($current_page) ) {
$_current_page = get_post( $current_page );
if ( in_array( $page->ID, $_current_page->ancestors ) )
$css_class[] = 'current_page_ancestor';
if ( $page->ID == $current_page )
$css_class[] = 'current_page_item';
elseif ( $_current_page && $page->ID == $_current_page->post_parent )
$css_class[] = 'current_page_parent';
} elseif ( $page->ID == get_option('page_for_posts') ) {
$css_class[] = 'current_page_parent';
}
$css_class = implode( ' ', apply_filters( 'page_css_class', $css_class, $page, $depth, $args, $current_page ) );
if ( '' === $page->post_title )
$page->post_title = sprintf( __( '#%d (no title)' ), $page->ID );
$output .= $indent . '<li class="' . $css_class . '"><a href="' . get_permalink($page->ID) . '">' . $link_before . apply_filters( 'the_title', $page->post_title, $page->ID ) . $link_after . '</a>';
if ( !empty($show_date) ) {
if ( 'modified' == $show_date )
$time = $page->post_modified;
else
$time = $page->post_date;
$output .= " " . mysql2date($date_format, $time);
}
}
}
function end_el( &$output, $page, $depth = 0, $args = array() ) {
$page_parent_id = $page->post_parent;
$page_parent_status = get_post_status( $page_parent_id );
if ( $page_parent_status != 'draft' ) {
$output .= "</li>\n";
}
}
}
The new class can be used with wp_list_pages() like this:
$args = array(
'sort_column' => 'menu_order',
'title_li' => '',
'post_status' => 'publish',
'walker' => new Wpse159627_Walker_Page
);
wp_list_pages( $args );
Edit:
Adding this for completeness reasons, so to make this work for trees, all descendants, not just children. It is not the optimal way to do it though, enough other suggestion have been made.
Because WordPress' get_ancestors() and get_post_ancestors() functions aren't made to get drafts too, I constructed a function to get every ancestor:
function wpse159627_get_all_post_ancestors( $post_id ) {
$post_type = get_post_type( $post_id );
$post = new WP_Query(
array(
'page_id' => $post_id,
'include' => $post_id,
'post_type' => $post_type,
'post_status' => 'any',
'cache_results' => false,
'update_post_meta_cache' => false,
'update_post_term_cache' => false
)
);
$post = $post->posts[0];
if (
! $post
|| empty( $post->post_parent )
|| $post->post_parent == $post->ID
) {
return array();
}
$ancestors = array();
$id = $ancestors[] = $post->post_parent;
while (
$ancestor = new WP_Query(
array(
'page_id' => $id,
'include' => $id,
'post_type' => $post_type,
'post_status' => 'any',
'cache_results' => false,
'update_post_meta_cache' => false,
'update_post_term_cache' => false
)
)
) {
$ancestor = $ancestor->posts[0];
if (
empty( $ancestor->post_parent )
|| ( $ancestor->post_parent == $post->ID )
|| in_array( $ancestor->post_parent, $ancestors )
) {
break;
}
$id = $ancestors[] = $ancestor->post_parent;
}
return $ancestors;
}
Additionally it is necessary to get the status of those ancestors. Which can be done with the following function:
function wpse159627_get_all_status( $ids ) {
$status_arr = array();
foreach ( $ids as $id ) {
$post_type = get_post_type( $id );
$post = new WP_Query(
array(
'page_id' => $id,
'include' => $id,
'post_type' => $post_type,
'post_status' => 'any',
'cache_results' => false,
'update_post_meta_cache' => false,
'update_post_term_cache' => false
)
);
$post = $post->posts[0];
$status_arr[] = $post->post_status;
}
return $status_arr;
}
This can be used to replace above explained conditional:
$ancestors = wpse159627_get_all_post_ancestors( $page->ID );
$ancestors_status = wpse159627_get_all_status( $ancestors );
if ( ! in_array( 'draft', $ancestors_status ) ) {
// code
}
Problem with this approach is that get_post_status called for each element will trigger a DB query. And a DB query for every page is not a great thing if there are a lot of pages...
Sure, its not quite optimal, but believe me if I would be as knowledgeable as you are I would have suggested a solution as smart as yours. @G.M.
I just hate walkers, and you don't, so I had to find a solution to don't use them :) And believe me, you are enough knowledgeable to answer questions far better than me :)
Ok, lets agree we are both somewhat capable :) My feeling towards walkers just indifferent :) Aside from that reading through source plus documentation and answering questions is just another way for me to learn a bit more about the matter. @G.M.
That's a whole tutorial you wrote ! :) I'll see if I can make it work, for now just copypasta doesn't solve the problem.. I still see published pages whose parents are in draft.
I was in the mood to write something comprehensive :) I actually did not run the code myself, but I'm certain that the children aren't shown. I suppose what you mean is that not whole tree gets discarded, meaning that grandchildren and so forth aren't filtered out. But, not to be nit-picky, your question doesn't say anything about trees and grandchildren or all descendants, it does say children though. So the only thing I can say is, you have to specify you requirements exactly to get an exact answer. @mike23
This answer is offering another way of doing this. The code is pretty much self-explaining, I named everything pretty literal to make it better understandable. What I did is constructing a function that determines the draft pages and their descendants, which than can be used with the exclude parameter of wp_list_pages().
Helper Function:
function wpse159627_exclude_draft_sub_trees() {
$pages_any_status = get_posts(
array(
'post_type' => 'page',
'post_status' => 'any',
'posts_per_page' => -1,
// make this as inexpensive as possible
'cache_results' => false,
'update_post_meta_cache' => false,
'update_post_term_cache' => false
)
);
$draft_posts_ids = array_filter(
array_map(
function ( $array_to_map ) {
if( $array_to_map->post_status == 'draft' ) {
return $array_to_map->ID;
} else {
return null;
}
},
$pages_any_status
)
);
$children_of_draft_posts_arr_of_obj = array();
foreach ( $draft_posts_ids as $draft_id ) {
$children_of_draft_posts_arr_of_obj[] = get_page_children(
$draft_id,
$pages_any_status
);
}
$children_of_draft_posts = array();
foreach ( $children_of_draft_posts_arr_of_obj as $object ) {
foreach ( $object as $key => $value ) {
$children_of_draft_posts[] = $value;
}
}
$children_of_draft_posts_ids = array_map(
function ( $array_to_map ) {
return $array_to_map->ID;
},
$children_of_draft_posts
);
$exclude_from_list_pages = array_merge(
$draft_posts_ids,
$children_of_draft_posts_ids
);
$exclude_comma_sep_list = implode(',',$exclude_from_list_pages);
return $exclude_comma_sep_list;
}
Usage:
$args = array(
'sort_column' => 'menu_order',
'title_li' => '',
'post_status' => 'publish',
'exclude' => wpse159627_exclude_draft_sub_trees()
);
wp_list_pages( $args );
If you are on a PHP version smaller than 5.3 you need a version without closures. In my book, to say that clearly, it is a mistake to operate on anything below 5.4. But I'm very well aware of the WordPress requirements, PHP 5.2.4, so here you go:
function wpse159627_extract_ids( $array_to_map ) {
return $array_to_map->ID;
}
function wpse159627_extract_ids_of_drafts( $array_to_map ) {
if( $array_to_map->post_status == 'draft' ) {
return $array_to_map->ID;
} else {
return null;
}
}
function wpse159627_exclude_draft_sub_trees_old_php() {
$pages_any_status = get_posts(
array(
'post_type' => 'page',
'post_status' => 'any',
'posts_per_page' => -1,
// make this as inexpensive as possible
'cache_results' => false,
'update_post_meta_cache' => false,
'update_post_term_cache' => false
)
);
$draft_posts_ids = array_filter(
array_map(
'wpse159627_extract_ids_of_drafts',
$pages_any_status
)
);
$children_of_draft_posts_arr_of_obj = array();
foreach ( $draft_posts_ids as $draft_id ) {
$children_of_draft_posts_arr_of_obj[] = get_page_children(
$draft_id,
$pages_any_status
);
}
$children_of_draft_posts = array();
foreach ( $children_of_draft_posts_arr_of_obj as $object ) {
foreach ( $object as $key => $value ) {
$children_of_draft_posts[] = $value;
}
}
$exclude_from_list_pages = array_merge(
$draft_posts_ids,
$children_of_draft_posts_ids
);
$exclude_comma_sep_list = implode(',',$exclude_from_list_pages);
return $exclude_comma_sep_list;
}
| common-pile/stackexchange_filtered |
How can we get CA's public key?
To get a public key of some organization or someone we want to send an encrypted message to, we need to make a request to CA asking that organization's public key. CA then returns X509 certificate. It contains CA's signature. To decrypt it we need to have a CA's public key. How can we securely obtain CA's public key?
Related:
- How can we get CA's public key?
- I've got my private key compromised. How does CRL work?
- What happens when a root CA has its private key compromised?
CA public keys are shipped with OS or applications like browsers.
If the CA cert is self signed (not cross-certified by any CA that is shipped with your OS or browser and thus trusted) then you have to obtain it by some means and to check if it is the original one. For instance, download it from some trusted location and check the hash value of the certificate (where the hash value is typically also published at the trusted location).
@CodesInChaos: make that an answer.
You can search for root certificates of a given CA.
E.g.:
http://www.symantec.com/page.jsp?id=roots, but this page is served over plain HTTP so maybe you shouldn't trust it!
or https://www.mozilla.org/projects/security/certs/included/.
From there when you want to check a certificate you can check whether it belongs to/was signed by a root CA you trust. If you trust it, then you can get its public key.
More commonly as CodesInChaos said, trusted certificates are shipped with your OS/browser.
| common-pile/stackexchange_filtered |
Live output status from subprocess command Python
I'm writing a script to get netstat status using subprocess.check_output.
cmd = 'netstat -nlpt'
result = subprocess.check_output(cmd, shell=True, timeout=1800)
print(result.decode('utf-8'))
The above is running perfectly. Is there any way to get the live-streaming output. I have heard poll() function does this job. In live output from subprocess command they are using popen but i'm using check_output please some one help me on this issue. Thank you!
Actually no, they are using Popen and here i'm using check_output
You can't using check_output.
Why do you use check_output when you want life output instead?
Please do not edit your question in a way that changes its topic. This has invalidated previous answers.
Sorry for that i will ask a new question
From this answer:
The difference between check_output and Popen is that, while popen is a non-blocking function (meaning you can continue the execution of the program without waiting the call to finish), check_output is blocking.
Meaning if you are using subprocess.check_output(), you cannot have a live output.
Try switching to Popen().
| common-pile/stackexchange_filtered |
An invalid provider type has been specified
I have the following code to generate electronic documents (SUNAT). I have tried to capture the key of a .pfx with "RSACryptoServiceProvider ()" and "X509Certificate2 ()" of the variable "certificate" to the variable "rsaKey" that contains the data (The digital certificate, the password) to encrypt and sign an xml. But it does not allow me to do so and it shows me an error "An invalid provider type has been specified." and Error "System.Security.Cryptography.Utils.CreateProvHandle(CspParameters parameters, Boolean randomKeyContainer) in System.Security.Cryptography.Utils.GetKeyPairHelper(CspAlgorithmType keyType, CspParameters parameters, Boolean randomKeyContainer, Int32 dwKeySize, SafeProvHandle& safeProvHandle, SafeKeyHandle& safeKeyHandle)"
I read in some pots that could be for the computer, but I already eliminated the certificates that were in the computer, in addition the operating system is a windows 10 and I use the .net 4.6.1. Please your help is of great importance to me.
var response = new FirmadoResponse();
var rsaKey = new RSACryptoServiceProvider();
var certificate = new X509Certificate2();
certificate.Import(Convert.FromBase64String(request.CertificadoDigital),
request.PasswordCertificado, X509KeyStorageFlags.MachineKeySet);
//===>ERROR
if (certificate.HasPrivateKey) {
rsaKey = (RSACryptoServiceProvider)certificate.PrivateKey;
}
else{
rsaKey = (RSACryptoServiceProvider)certificate.PublicKey.Key;
}
var xmlDoc = new XmlDocument();
string resultado;
var betterBytes = Encoding.Convert(Encoding.UTF8,
Encoding.GetEncoding(Formatos.EncodingIso),
Convert.FromBase64String(request.TramaXmlSinFirma));
using (var documento = new MemoryStream(betterBytes))
{
xmlDoc.PreserveWhitespace = false;
xmlDoc.Load(documento);
var indiceNodo = request.UnSoloNodoExtension ? 0 : 1;
var nodoExtension = xmlDoc.GetElementsByTagName("ExtensionContent", EspacioNombres.ext)
.Item(indiceNodo);
if (nodoExtension == null)
throw new InvalidOperationException("No se pudo encontrar el nodo ExtensionContent en el XML");
nodoExtension.RemoveAll();
var signedXml = new SignedXml(xmlDoc) {SigningKey = rsaKey };
var xmlSignature = signedXml.Signature;
var env = new XmlDsigEnvelopedSignatureTransform();
var reference = new Reference(string.Empty);
reference.AddTransform(env);
xmlSignature.SignedInfo.AddReference(reference);
var keyInfo = new KeyInfo();
var x509Data = new KeyInfoX509Data(certificate);
x509Data.AddSubjectName(certificate.Subject);
keyInfo.AddClause(x509Data);
xmlSignature.KeyInfo = keyInfo;
xmlSignature.Id = "SignOpenInvoicePeru";
signedXml.ComputeSignature();
if (reference.DigestValue != null)
response.ResumenFirma = Convert.ToBase64String(reference.DigestValue);
response.ValorFirma = Convert.ToBase64String(signedXml.SignatureValue);
nodoExtension.AppendChild(signedXml.GetXml());
using (var memDoc = new MemoryStream())
{
using (var writer = XmlWriter.Create(memDoc,
new XmlWriterSettings {Encoding = Encoding.GetEncoding(Formatos.EncodingIso)}))
{
xmlDoc.WriteTo(writer);
}
resultado = Convert.ToBase64String(memDoc.ToArray());
}
}
response.TramaXmlFirmado = resultado;
New certificates start to use CNG providers, so you cannot blindly convert to RSACryptoServiceProvider. That's the cause of the error. Ask Google and you should see lots of suggestions.
Use cert.GetRSAPublicKey() or cert.GetRSAPrivateKey() instead of the older properties
It was fixed by changing X509KeyStorageFlags.MachineKeySet by X509KeyStorageFlags.UserKeySet. Will there be any inconvenience when installing in another machine?
| common-pile/stackexchange_filtered |
Write GeoJSON As Feature Object in Postgis
I'm trying to create a geofence/circle from a lat/long set and I'm close except that the GeoJSON that PostGIS creates differs in structure from the client library that our front-end uses. Here is my python to create the geofence:
session = DatabaseSessionService().create_session()
METERS_IN_HALF_MILE = 805
longitude = 21.304116745663165
latitude = 38.68607570952619
geom = func.ST_Buffer(func.ST_MakePoint(longitude, latitude), METERS_IN_HALF_MILE)
geofence = Geofence(
geom=geom,
geojson=cast(func.ST_AsGeoJSON(geom), JSON),
company_id=188,
name='Test Fence 1'
)
session.add(geofence)
session.commit()
This will create a record with geojson set to:
{
"type":"Polygon",
"coordinates":[
[
[
<PHONE_NUMBER>45663,
38.6860757095262
],
...
]
]
}
However I'd like to maintain the convention set previously and have the GeoJSON written as a Feature Object like this:
{
"type":"Feature",
"properties":{
},
"geometry":{
"type":"Polygon",
"coordinates":[
[
[
-92.29188859462738,
38.913722221672636
],
...
]
]
}
}
I've looked into using ogr2ogr but I'd prefer that this be an automated process that happens on creation as opposed to being a post-creation task.
As you probably noticed ST_AsGeoJSON gives only the geometry part. This http://www.postgresonline.com/journal/archives/267-Creating-GeoJSON-Feature-Collections-with-JSON-and-PostGIS-functions.html may help you further.
See also http://gis.stackexchange.com/q/112057/18189
I ended up doing an INSERT and then UPDATE to use the python libs geojson and shapely to generate the geoJSON. So my code now looks like this.
import geojson
from models import Geofence
from geoalchemy2.shape import to_shape
from sqlalchemy import func
from services.DatabaseSessionService import DatabaseSessionService
session = DatabaseSessionService().create_session()
longitude = -92.339292
latitude = 39.005994
geom = func.ST_Buffer(func.ST_MakePoint(longitude, latitude), 0.5)
geofence = Geofence(
geom=geom,
company_id=188,
name='Test Fence 1',
alert_enter=False,
alert_exit=False
)
session.add(geofence)
session.commit()
geometry = to_shape(geofence.geom)
geofence.geojson = geojson.Feature(geometry=geometry, properties={})
session.add(geofence)
session.commit()
Could this be of any help? It describes the way to create valid GeoJSON within the PostGIS database.
| common-pile/stackexchange_filtered |
Importing package in client mode PYSPARK
I need use virtual environment in pyspark EMR cluster.
I am launching application with spark-sumbit using the following configuration.
spark-submit --deploy-mode client --archives path_to/environment.tar.gz#environment --conf spark.yarn.appMasterEnv.PYSPARK_PYTHON=./environment/bin/python
Environment variables are setting in python script. The code is working importing packages inside spark context function, but i wannt import outside the function. What's wrong?
from pyspark import SparkConf
from pyspark import SparkContext
import pendulum #IMPORT ERROR!!!!!!!!!!!!!!!!!!!!!!!
os.environ["PYSPARK_PYTHON"] = "./environment/bin/python"
os.environ["PYSPARK_DRIVER_PYTHON"] = "which python"
conf = SparkConf()
conf.setAppName('spark-yarn')
sc = SparkContext(conf=conf)
def some_function(x):
import pendulum #IMPORT CORRECT
dur = pendulum.duration(days=x)
# More properties
# Use the libraries to do work
return dur.weeks
rdd = (sc.parallelize(range(1000))
.map(some_function)
.take(10))
print(rdd)
import pendulum #IMPORT ERROR
from the looks of it, seems you are using the correct environment for the workers ("PYSPARK_PYTHON") but override the environment for the driver ("PYSPARK_DRIVER_PYTHON") so that the driver's python does not see the package you wanted to import. the code in the some_function gets executed by the workers ( never by the driver), and thus it can see the imported package, while the latest import is executed by the driver, and fails.
| common-pile/stackexchange_filtered |
GTK - How to style a button in headerbar?
I want to set color like blue and red in a application, is something like
this image.
I imagine that I can do it with css styles, but if is there other way much more simple like set a property or a class.
I use GTK 3.12 and Python, but you can show me examples in other lenguages and I can traduce it.
I think you can't do it. https://developer.gnome.org/gtk3/stable/GtkHeaderBar.html
Maybe you can solved creating a custom dialog for this
Is not for a dialog, really is for a custom Gtk.Window with header bar, but I want a blue button on the header bar.
The correct way to do it is with the suggested-action and destructive-action CSS classes. Here is some documentation. Is there any particular objection that you have against CSS?
Use this code:
button.get_style_context().add_class(Gtk.STYLE_CLASS_SUGGESTED_ACTION)
or
button.get_style_context().add_class(Gtk.STYLE_CLASS_DESTRUCTIVE_ACTION)
before you add the button to the header bar.
Very good information, I will read these documentation, I don't use CSS because I want to respect the theme of the user and my buttons-made-with-css was looked very ugly
| common-pile/stackexchange_filtered |
How to send a message to a running app (Node.js)
I have a running app called "app.js" it keeps running to do some task.
How can I let the user run another process of the app just to send a message to the current running process to tell it to do something.
node app.js reload
One solution is utilizing some sort of storage mechanism, like a database or file to queue up messages. So while one instance of app.js is running it can keep reading from the database to see if there are new messages to process.
Another solution would be to make one of the app.js instances act as a server, and have another one try to connect over TCP, and as soon as it establishes a connection start pushing messages to the client instance.
You can use a message broker (RabbitMq) to notify the running process of an event and handle the message from running process.
| common-pile/stackexchange_filtered |
Is it possible to download complete webpage using typhoeus instead of HTML only in Ruby?
I am using ruby to download a complete web page using typhoeus, but it downloads only HTML,
request = Typhoeus::Request.new(
"www.example.com",
method: :get,
headers: { Accept: "text/html" }
)
response.body returns only HTML, Can I add any format to download complete webpage with its data which is being loaded via javascript? Or is there any other way to get the data?
Usually you're responsible for parsing the HTML with something like Nokogiri and then fetching any resources you want after the fact. It's worth noting that the wget tool has a -m option that recursively spiders and downloads everything if you need a quick and dirty solution.
Via nokogiri , I used open but it too gets the html only as the webpage I am trying to parse is loading its data via javascript.
What does JavaScript have to do with anything here? Once again, Nokogiri is an HTML parser. It is not a site downloader. If you need JavaScript for this to work you need to use a headless browser, so good luck with that.
You're using the wrong tool unless you are willing to write a lot more code. As @tadman said, wget -m is a good solution. There are many different existing tools to do what you want but those are for you to discover and evaluate as asking for recommendations is off-topic. It'd probably help you if you studied how a browser renders a page by retrieving the elements, if you choose to write your own.
This can't be done in a single request. You need to parse the html to find all the images required and download them
Depending on what you are doing with this, you may need to do the same for other assets on the page (eg css)
I need to get the content from webpage, which is loading via javascript, how to parse to get the data loaded via javascript?
| common-pile/stackexchange_filtered |
Limit of the composition function $\sin(\cos(x))/\cos(x)$ at $\pi/2$ in Apostol Exercises 3.8
In Apostol calculus exercise there is a bunch of exercises where we need to find a limit of a composite function. One example is this:
$\lim_\limits{x \rightarrow \frac{\pi}{2}} \frac{\sin(\cos(x))}{\cos(x)}$
Well, intuitively we simply take $\cos(x) \rightarrow 0$ as $x \rightarrow \pi/2$. Then $\lim_\limits{x \rightarrow \frac{\pi}{2}} \frac{\sin(\cos(x))}{\cos(x)} = 1$, since the limit of $\sin(x)/x$ is 1 as $x \rightarrow 0$. Multiple online solutions suggest the same without any explanation.
How to show this rigorously? In Apostol, there is a proof that composition of two continuous functions is continuous at any $x = p$. However, there is no proof about general limits. Moreover, we know that $\sin(x)/x$ is not even defined at $0$. How is it allowed to substitute $\cos(x) \rightarrow 0$ into this outer sine then?
PS. L'Hopital rule has not been specified yet. The only available option is delta-epsilon arguments, and simplest limit rules: sum, difference, product, and division. Squeezing limit theorem can be used (proved before). Plus sin(x)/x limit at 0 has been proven with squeezing limit theorem.
You can check that $f(x)=\sin(x)/x$ has a continuous extension to $x=0$ with $f(0)=0$. Then you can apply the composition rule.
@CalvinKhor, However, this extension is not specified (allowed?) in the exercise. And it would be better to understand the work with general limits (from where continuity follows).
Can you use the rules of L'Hospital?
@Dr.SonnhardGraubner, no. The derivative is the next section. The only tools available at this step are delta-epsilon arguments.
For $y$ small, put $x = \pi/2 +y$, then $ \cos x = cos ( \pi/2 + y ) = - \sin y$?
You can substitute $$t=\cos(x)$$ and for $x$ tends to $\frac{\pi}{2}$ so $t$ tends to zero.
$$\lim_{t\to 0}\frac{\sin(t)}{t}=1$$
@Dr.SonnhardGraubner, I do not think this is valid conclusion, since t is not really a function output, but a limit. Is there some proof about substitution of limits somewhere in delta-epsilon terms?
Plus sin(x)/x limit at 0 has been proven with squeezing limit theorem.
OK, then you're basically done. Fix $\epsilon>0$. Choose $\delta$ so that $|(\sin y)/y-1 | < \epsilon$ if $0<|y|<\delta$. Now choose $0<\delta_1<1$ such that
$$ 0<|x-\pi/2| < \delta_1 \implies |\cos x | < \delta.$$
This implies
$$ 0<|x-\pi/2| < \delta_1 \implies \left|\frac{\sin\cos x }{ \cos x} - 1\right| < \epsilon.$$
Further,
In Apostol, there is a proof that composition of two continuous functions is continuous at any $x=p$
. However, there is no proof about general limits.
You will find that the proof for limits is nearly the same as the proof for continuous functions, I recommend it as an exercise for you.
Wonderful! Exactly the proof I wanted.
I think I can easily extend this to the general limit theorem - I just assume that the inner function is continuous everywhere, then your proof becomes the proof of the general limit case! Thanks.
@John You don't need continuity anywhere, just need the two limits to exist, and the domains/codomains need to match up. For instance if the inner function was $\cos : \mathbb [0,\pi/2) \to \mathbb R$ then it still works
We should make $\cos x$ never be equal to 0 by making $\delta_1$ < $\frac{π}{2}$ , or $\frac{\sin \cos x}{\cos x}$ will get error .
You are correct but usually issues that pop up when delta or epsilon is too large aren't very important :) I'll fix the answer @Mathematicianwannabe
You may apply the L'Hospital rule.
$$\lim _{x\to \pi /2} \frac {\sin (\cos x)}{\cos x} =\lim _{x\to \pi/2} \frac {\cos (\cos x)(-\sin x)}{-\sin x}=1$$
I cannot - L'Hopital rule has not been specified yet. The only available option is delta-epsilon arguments, and simplest limit rules: sum, difference, product, and division. Squeezing theorem can be used. Plus sin(x)/x limit at 0 has been proven with squeezing limit theorem.
| common-pile/stackexchange_filtered |
Databricks job cannot find python library imported in the cluster
I am trying to run a cron job on my notebook and I get an "no module found" error. When I look at the job logs this is the full error:
ModuleNotFoundError Traceback (most recent call last)
<command-2307930105977041> in <module>
1 from __future__ import print_function
2 import sys
----> 3 import pymysql
ModuleNotFoundError: No module named 'pymysql'
This library has been installed to my cluster that I am running the job from and the notebook that uses this library runs and does not show a ModuleNotFoundError. I ran the import pymysql in it's own cell and it does not throw me back an error, only when I run a job on that notebook do I get an error.
What can be the cause for this?
https://kb.databricks.com/jobs/job-fails-no-library.html
@Chris thanks got the libraries to work. Now it's erroring out when it comes to authenticating AWS keys in the notebook so it looks like the environment variables I set for my cluster are not transitioning to the job? Would I set those in the Parameters section of the job?
| common-pile/stackexchange_filtered |
HTML address validation pattern
Can any one help me with regex patter to allow address validation based on below limitations:
Allow only alphanumeric characters, spaces, apostrophes ('), dashes (-), commas, (,), periods (.), number signs (#), and slashes (/),
Must contain at least one numeral, one alphabetic character, and one space.
I tried below patterns:
/^(?=.*[0-9])(?=.*[a-zA-Z])([a-zA-Z0-9]+)$/
(?=.*\d)(?=.* ).{8,}
You can use
^(?=\S*\s)(?=[^a-zA-Z]*[a-zA-Z])(?=\D*\d)[a-zA-Z\d\s',.#/-]*$
Or, a Unicode variation:
^(?=\S*\s)(?=\P{L}*\p{L})(?=\D*\d)[\p{L}\d\s',.#/-]*$
See the regex demo.
Details:
^ - start of string
(?=\S*\s) - at least one whitespace required
(?=[^a-zA-Z]*[a-zA-Z]) - at least one letter
(?=\D*\d) - at least one digit
[a-zA-Z\d\s',.#/-]* - zero or more letters, digits, whitespaces, ', ,, ., #, / or - (replace * with + to require at least one char in the string)
$ - end of string.
Declaration in PHP:
$regex = '~^(?=\S*\s)(?=[^a-zA-Z]*[a-zA-Z])(?=\D*\d)[a-zA-Z\d\s\',.#/-]*$~';
$regex = '~^(?=\S*\s)(?=\P{L}*\p{L})(?=\D*\d)[\p{L}\d\s\',.#/-]*$~u';
I have used your pattern like below, but its not working.
<input type="text" name="address" placeholder="e.g. 123 River Rd. Apt 45" pattern="(?=\S*\s)(?=\P{L}*\p{L})(?=\D*\d)[\p{L}\d\s',.#/-]*$" required>
@AkshayPaghdar You must use pattern="(?=\S*\s)(?=[^a-zA-Z]*[a-zA-Z])(?=\D*\d)[a-zA-Z\d\s',.#/-]*"
Can you help me with this too please:- Name Validation: Can only contain letters, spaces, apostrophes ('), dashes (-), commas, (,), periods (.). Must be at least 2 characters long and can only start with a letter. ?
@AkshayPaghdar pattern="[a-zA-Z][a-zA-Z\s\x27,.-]+"
| common-pile/stackexchange_filtered |
Touch events with D3.js and TUIO
I have my D3 Map which will show several data and right now I'm stuck with the implementation of multi touch and the d3.slider and in general touch events. This video shows what it does right now. I can spawn points with the d3 slider and pan around the map. All this was achieved by using Caress-server and Caress-client. The touch table is a Samsung SUR40 which is using Reactivision. I get the touches as you see I can pan an I also can zoom. But the slider won't revert and I can'T see why. the d3.slider.js is modified slightly so it can react to .on("drag) and not .on("click"). Since i changed nothing else I'm confused. The slider is still working though if you use mouse only but with Multitouch/TUIO you just can slide forward with the handle but not backwards.
This is the slider/filter function which is also looking for the current viewport in my main js script:
var slider = d3.slider()
.axis(false).min(minDate).max(maxDate).step(secondsInDay)
.value(minDate)
.on("slide", function(evt, value) {
// console.log("SLIDE");
// console.log(d3.touch);
temp = moment(value,"x").utc().format("YYYY-MM-DD");
tempVal = moment(temp).unix()*1000;
if( filterCheck == 0 ){
if( zoomCheck == 0 ){
newDataW = site_dataW.features.filter(function(d){
dataDate = moment(d.properties.date).utc().unix()*1000;
// console.log("dataDate " + new Date(dataDate));
// console.log("slidDate " + new Date(value));
//console.log("-- " + moment(dataDate).toDate());
if (dataDate == tempVal) {
//console.log("Sucess");
//console.log(moment(dataDate).toDate());
return moment(dataDate).toDate();
}
});
showWorldSite(newDataW)
}
else if( zoomCheck == 1 ){
newDataG = site_dataG.features.filter(function(d){
dataDate = moment(d.properties.date).utc().unix()*1000;
//console.log(value);
if (dataDate == tempVal) {
//console.log("Sucess")
return moment(dataDate).toDate();
}
})
showGermanSite(newDataG);
}
else if( zoomCheck == 2 ){
newDataS = site_dataS.features.filter(function(d){
dataDate = d.properties.Date;
if (dataDate == temp) {
return moment(dataDate).toDate()
}
});
showSyrianSite(newDataS);
}
}
//================================================================================================
//================================================================================================
//================================================================================================
else if( filterCheck == 1 ) {
//
if( zoomCheck == 0 ){
newDataW = site_dataW.features.filter(function(d){
dataDate = moment(d.properties.date).utc().unix()*1000;
//console.log(new Date(dataDate) < new Date(value));
return moment(dataDate).toDate() < moment(tempVal).toDate() ;
});
//console.log(newDataW.length);
showWorldSite(newDataW)
}
//
else if( zoomCheck == 1 ){
newDataG = site_dataG.features.filter(function(d){
dataDate = moment(d.properties.date).utc().unix()*1000;
//console.log(moment(dataDate).toDate());
return moment(dataDate).toDate() < moment(tempVal).toDate() ;
})
// console.log(newDataG.length);
// console.log(new Date(value));
showGermanSite(newDataG);
}
else if( zoomCheck == 2 ){
newDataS = site_dataS.features.filter(function(d){
// dataDate = moment(d.properties.Date).utc().unix()*1000;
dataDate = d.properties.Date;
// return dpS(d.properties.Date) < new Date(value);
// return moment(dataDate).toDate() < moment(tempVal).toDate() ;
// return moment(dataDate).isBefore(tempVal);
return new Date(dataDate) < new Date(temp);
});
showSyrianSite(newDataS);
}
}
});
d3.select('#slider3').call(slider);
If you want to try this at home you can download Caress Server and start it up. Tongseng if you got OSX and if you want to use your DROID or IOS device you can downoad TUIODROID or TUIOpad. You can download all data from my repo. I'd appreciate every help and tip I can get because this project is very important to me.
The slider was not centered so every time i moved back the finger left the slider handle and was not on the handle anymore. So i got this in my css file to fix this. Now it is possible to move the slider with multitouch events too
.d3-slider-horizontal .d3-slider-handle {
top: -.3em;
margin-left: -5.5em;
/*half of the slider handle*/
}
| common-pile/stackexchange_filtered |
How to Restrict a Standard macOS Account While Allowing System Updates and Specific App Updates?
I'm using macOS Sonoma (latest version, as of December 2024), and I have a MacBook with the following setup:
I am the admin account holder.
A standard account is used by someone else (a trusted individual).
The standard account does not currently have admin privileges, as revoking them seemed like the best solution to prevent access to a specific app and protect the DNS configuration profile. However, if there's a way to allow admin privileges while still achieving these restrictions, I’m open to exploring simpler solutions.
Here's what I'm trying to achieve:
Allow the standard account to:
Install macOS updates (e.g., security patches, OS upgrades).
Update specific apps, like Spotify and GitHub-related apps, which are not automatically updated via the Mac App Store.
Restrict the standard account from:
Accessing one specific app (e.g., Apple Configurator or any other app I specify).
Removing or modifying a DNS server configuration set through a profile.
Additional Considerations:
I don't want to log in as the admin every time macOS or apps need to be updated.
I attempted to use sudo to grant specific permissions to the standard account for updates and other tasks, but the commands I tried didn’t work as expected.
I do not want to use Apple Screen Time because the restriction period (e.g., 1-minute limit) is not sufficient to prevent the access I need to block.
What I've tried so far:
Removing admin privileges from the standard account to prevent workarounds.
Using a configuration profile to lock DNS settings, but I need it to be non-removable by the standard account.
Exploring sudo permissions for limited escalation, but I may not have implemented it correctly.
I’ve read about tools like Privileges by SAP (available on GitHub), which allow temporary admin rights, but I’m unsure if this is the best solution. My main goal is to make this MacBook secure while still being practical for the standard user.
Key Questions:
What’s the best way to restrict app access and lock DNS settings for a standard account while still allowing OS and app updates?
How can I properly configure sudo to give the standard account specific permissions for tasks like softwareupdate or app installations?
Are there better tools or workflows for this use case?
Any advice or step-by-step guidance would be greatly appreciated!
| common-pile/stackexchange_filtered |
Optional parameters in python dict
Is there a way to include optional parameters into Python dictionary?
For example, I have the following return statements for get requests. They are dependent on the input and mostly identical.
If the region is passed as an input parameter, we have:
if region:
return {
'success': True,
'result': {
'country': country,
'region': region, # optional region param
'cities': cities
}
}
If the city is passed:
if city:
return {
'success': True,
'result': {
'country': country,
'city': city, # optional city param
'cities': cities
}
}
If nor city or region are passed:
return {
'success': True,
'result': {
'country': country,
'cities': cities
}
}
What I want is to have one return statement:
return {
'success': True,
'result': {
'country': country,
if region: 'region': region, # I know this and the next lines don't work
if city: 'city': city,
'cities': cities
}
}
You can pass all keys to dict then filter keys with None value. Check this answer how to filter dict.
Control statement is not allowed with dict literal, but it is trivial to do this:
r = {
'country': country,
'cities': cities
}
if region:
r['region'] = region
if city:
r['city'] = city
return {
'success': True,
'result': r
}
Option 1
As mentioned in other answers, create a dictionary locally, and add optional parameters along the way.
Option 2
When using the dictionary returned from your function, use
retdict.get('city', 'defaultvalue') instead of retdict['city'] to make sure your don't fail on trying to get a non-existent parameter.
Option 3
Use defaultdict. Some easy-to-understand examples are listed in the Python Docs and here
| common-pile/stackexchange_filtered |
Do Interlocked.Xxx methods guarantee value updated in all data caches?
Example:
Thread a: Interlocked.Increment(ref x);
Thread b: int currentValue = x;
Assuming thread b executes after thread a, is "currentValue" in thread b guaranteed to be the incremented value? Or, does thread b need to do a Thread.VolatileRead(ref x)?
Technically that depends on the CPU .NET is running on, but for any common CPU the answer is yes, cache coherency is guaranteed for an Interlocked.Increment. It acts as a memory barrier as required by MESI.
a CPU can have in its cache a line which is invalid, but where it doesn't yet know that line is invalid - the invalidation queue contains the invalidation which hasn't yet been acted upon. (The invalidation queue is on the other "side" of the cache; the CPU can't scan it, as it can the store buffer). As a result, memory barriers are required.
http://en.wikipedia.org/wiki/MESI_protocol (x86)
MOESI (used on AMD64 chips) is quite similar:
http://en.wikipedia.org/wiki/MOESI_protocol (AMD64)
As I understand it, Interlocked is only guaranteed when accessed by other Interlocked methods. This may be especially important when talking about 64-bit values on x86 systems, where it cannot be guaranteed to be atomic, so torn values are a concern. A good trick for robustly reading a value that can be changed by Interlocked is CompareExchange:
int val = Interlocked.CompareExchange(ref field, 0, 0);
This mutates the value of field to 0, but only if the old value was 0 - otherwise it does nothing. Either way the old value is returned. So basically: it reads the value without ever changing it, and is safe vs other Interlocked methods.
Good point, but does not directly address cache coherency. As far as I understand it, the cache is guaranteed to be consistent at any point in time. However, when reading without Interlocked, there is no memory barrier to prevent torn values. My understanding on this point is incomplete though. I would appreciate any references that shed further light.
| common-pile/stackexchange_filtered |
how to display all percentages on Google PieChart
I'm facing two problems.
How can I make sure that the whole legend can be seen under the graph? Indeed when the legend is too big three points are added.
My other problem concerns pie charts. How to make all the percentages appear on the graph, by default it puts them only when the place is sufficient on the graph?
Bar Chart problem
Pie Chart problem
Thanks you
It would be more helpful if you share your implementation so we can get a clear picture.
I don't think that this is possible without changing the chart size.
Hello and welcome to stackoverflow, please check this before you post a question: How to ask a good question
I put two images to illustrate my problem
Still could't get the Bar Chart problem !
Bar Chart Problem : Its the default behaviour. The 3-dots is called ellipses. It is used to truncate the strings to fit the in to the containing box/div. For more info, refer this. This workaround would help you if you wish the axes labels are need to be shown full. In case legend values, please refer this.
Please refrain rom using such long names for the axes as it affects the UX.
Pie Chart Problem : Its the default behaviour of Google Charts to show the values only if the values are sufficient to fit in the place. As a workaround, you can display all the values, in the chart using the option {legend : "labelled"}. Thanks to this Google Forum.
Example JS Fiddle
Do you have any idea about my other problem ?
No. I still couldn't get what you are trying to tell about the first !
If there is a large string of characters, the graph cuts it automatically. For example on the image I inserted, you can see three dots after the q because the string must contain too many? the character chain for this example is in fact : qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq.
I hope it's clearer.
| common-pile/stackexchange_filtered |
Mat-form-field - Styling when out of focus and with text in mat-input
How can I make it so that the out of focus styles don't apply when there is text inside the mat-input while simultaneously being out of focus?
I want to keep these styles when out of focus and with text:
But right now this is what I'm getting when out of focus and with text:
Also, this is how the field looks when there is no text and out of focus:
My current styles:
.mat-form-field-appearance-outline .mat-form-field-outline {
background-color: #FFFFFF66;
border-radius: 10em;
color: transparent;
opacity: 0.5;
}
.mat-form-field-appearance-outline.mat-focused .mat-form-field-outline-thick {
color: white;
background-color: transparent;
}
Thank you in advance.
I see in the comments that you have noticed Angular removes the mat-focused class, so applying it to the mat-form-field directly will not work. However, we should be able to apply classes to a wrapper container that will match the 'focused' style.
div.mat-form-field-outline has 'focused' rules when nested in an
element with mat-form-field-appearance-outline and mat-focused
classes
The mat-label element has 'focused' rules when nested in an element
with mat-form-field and mat-focused classes.
So we can provide the mat-form-field-appearance-outline and mat-form-field classes to a container and toggle the mat-focused class based on the form field value.
<p>
<span
class="mat-form-field mat-form-field-appearance-outline"
[ngClass]="{'mat-focused': field.value}"
>
<mat-form-field appearance="outline">
<mat-label>Outline form field</mat-label>
<input #field matInput placeholder="Placeholder" />
<mat-icon matSuffix>sentiment_very_satisfied</mat-icon>
<mat-hint>Hint</mat-hint>
</mat-form-field>
</span>
</p>
https://stackblitz.com/edit/angular-ckvs4z?file=src/app/form-field-appearance-example.html
You sir just made my day! I cannot thank you enough. I really appreciate you taking the time to help a noob junior dev like myself :-)
No problem at all, looks like you are up to some cool stuff, I wish you good luck
Oh and by the way, I forgot to ask: would it also be possible if I wanted to keep the focused style like the way it is in your answer, but with a different border opacity? If so, how? I was thinking of doing 0.5 opacity for the border when out of focus + with text.
Should be able to do it with something like: .mat-focused mat-form-field:not(.mat-focused) - I updated the stackblitz if you want to take a look.
Thanks, it's almost exactly that! But what I was looking for was something like: border 0.5 opacity, but the floating label and the text inside the input field remain with opacity 1.
Ah, ok. You should be able to target that with .mat-form-field-outline-thick
Right on the money again! However, I never messed around with SASS, do I just need to rename the global styles.css to styles.scss? Or is there a way to have it on my component folder somehow?
You should be able to rename it, assuming your project is setup to support sass. I'd recommend using it as it makes a lot of tedious css stuff a lot more simple. For this specific case you can just use normal css nesting as well though.
Nested CSS did the trick :-) I will definitely check out SASS in the future. Appreciate it, you saved me again today.
| common-pile/stackexchange_filtered |
Access HttpServletRequest from an Authenticator using Dropwizard
Using DropWizard(Jersey Server), Is it possible to access HttpServletRequest from an Authenticator?
I would give it an attribute.
I tried with:
@Context
private HttpServletRequest servletRequest;
But it's not injected.
I registered my Authenticator using:
env.jersey().register(
new AuthDynamicFeature(new BasicCredentialAuthFilter.Builder<User>().setAuthenticator(new FooAuthentificator())
.setRealm("Realm").buildAuthFilter()));
It's possible, but the problem is, the Authenticator never goes through the DI lifecycle, so it never gets a chance to get injected. What we can do though is explicitly inject it ourselves. To do that, we need to get a hold of the ServiceLocator (which is the main IoC container, kind of like ApplicationContext with Spring). Once we have the ServiceLocator, we can call locator.inject(anyObject) to explicitly resolve any injection dependencies.
The easiest place to get the ServiceLocator, when configuring the app, is in a Feature. Here we can also register Jersey components. Calling register on the FeatureContext (seen below) is just like calling env.jersey().register(...) with Dropwizard, it has the same effect. So we can do
public class AuthenticatorFeature implements Feature {
@Override
public boolean configure(FeatureContext ctx) {
ServiceLocator locator = ServiceLocatorProvider.getServiceLocator(ctx);
TestAuthenticator authenticator = new TestAuthenticator();
locator.inject(authenticator);
ctx.register(new AuthDynamicFeature(new BasicCredentialAuthFilter.Builder<User>()
.setAuthenticator(authenticator)
.setRealm("SEC REALM")
.buildAuthFilter()));
ctx.register(new AuthValueFactoryProvider.Binder<>(User.class));
return true;
}
}
You can see that explicitly inject the authenticator, with the call to locator.inject(authenticator). Then we register this feature through Dropwizard
env.jersey().register(new AuthenticatorFeature());
Tested, and works fine.
Note, if you are wondering how it's possible to inject the HttpServletRequest, when there is no current request, it's because a proxy is injected. Same thing as if you were to inject the request into a Jersey filter, the same thing happens; a proxy is injected, as there is only a singleton filter, but the request changes from request to request, so a proxy needs to be injected.
See Also:
Injecting Request Scoped Objects into Singleton Scoped Object with HK2 and Jersey
| common-pile/stackexchange_filtered |
Why FirstName, LastName, Company field not found in FieldPermission query result?
I'm trying to get all fields and its read and write permission using below query
SELECT Field, PermissionsRead, PermissionsEdit FROM FieldPermissions WHERE SObjectType ='Lead' AND parentId IN ( SELECT permissionSetId FROM PermissionSetAssignment where assigneeId IN('#assignee_Id #'))
I'm getting expected result :
But still some fields are missing in the output like "FirstName, LastName, Company, Street, City, Country..."
assignee_Id is System Administrator and having Field-Level access to all fields.
Facing same issue with Account and Contact.
FieldPermissions represents the enabled field permissions for the parent Permission Set. It's not a representation of everything that someone has access to.
The fields you identified: FirstName, LastName, Street, etc are fields that Salesforce sets access to.
You'll notice, within a permission set, that when you set Object Settings for Lead, those fields aren't included (meaning they're not permissionable).
You can see this another way through the fields property of DescribeSObjectResults (or through workbench explorer). A field has a property called permissionable
Schema.DescribeFieldResult dfr = Schema.SObjectType.Lead.fields.FirstName;
System.debug(dfr.isPermissionable()); //returns false
Indicates whether FieldPermissions can be specified for the field
(true) or not (false).
Thanks @kris-goncalves
Fields that are database required (e.g. Name), and fields that are "compound fields" (e.g. City) are not included in the field level security fields. The former are always required and therefore don't need to be checked for access, while the latter are turned on/off at the compound field level (e.g. Address contains City).
| common-pile/stackexchange_filtered |
How to move all vertical scrollbars to the left side?
I am left-handed and recently started using the touchscreen on my laptop more. There is even a bluetooth connected stylus available for it that works quite well for painting with applications like MyPaint or Gimp.
However, whenever there is a dialog or window that has a scrollbar, it is annoying for a left-handed person to use the vertical scrollbar, which is usually located on the right side of windows.
For instance in MyPaint, the brush selection dialog is quite hard to use with a stylus held in the left hand. Also the layers dialog in gimp and so on.
Is there a way to tell Ubuntu/Gnome that I want all vertical scrollbars to appear on the left side in general (as in "not per application")? Or at least for all GTK-based applications?
As a left-handed person I feel discriminated.
Followup:
It seems that left-handed touchscreen users are a minority out there, probably touchscreen users in general. Maybe I was naive to assume there would be simply some switch to flip. All answers so far are informative and helpful, yet not quite answering the question. I'll let the engine decide about the bounty.
There are references on moving the vertical scroll bar to the left in Gnome Terminal and LibreOffice but I haven't found the exact methods yet. If you use Firefox extensively, moving the scroll bar to the left will help enormously:
You need to change your settings in about:config. Here's what to do:
Enter about:config into the address bar (if it gives a warning about your warranty, click the button to say you'll be careful)
Enter layout.scrollbar.side into the search box at the top of the page
Double-click the result and replace the current value with a 3 when the prompt comes up
Click OK and then restart Firefox.
Source
So far no luck finding left-handed details for MyPaint or Gimp. However there is a left-handed mouse Q&A that might be helpful: How to set left-handed mouse pointer?
Left hand scrollbar in general
There is a discussion in Stack Exchange User Experience that will interest you. It addresses moving scrollbar to left side not just for RTL (Right To Left) languages (Arabic and Hebrew), nor just for left handed users, but for LTR users that like to hover mouse pointer to left side whilst reading paragraphs. For all these cases a scrollbar on the left side makes sense.
Perhaps between this Q&A and posting an answer on the above link, you can persuade GTK (GIMP & GNOME) developers to resurrect the left side scrollbar.
As a side note: I use vivaldi due to firefox lacking any useful touchscreen support
@SebastianStark I looked briefly at vivaldi (cool website) but didn't find anything on left scrollbar. I did update the answer with a Stack Exchange User Design Q&A requesting left side scrollbar that might interest you.
Read a bit through that "user experience" link. I feel they are more discussing about how and when to do things with left or right hand. It's a design decision and as such questionable. I think we should simply support both, so users can choose.
@SebastianStark I agree 100%. It takes the same amount of space whether it's on the left or right side. It should be simple function to swap it from side to side.
The option mentioned by other answers is deprecated in version 3.10.
GtkSettings:gtk-scrolled-window-placement has been deprecated since
version 3.10 and should not be used in newly-written code.
This setting is ignored.
Source: Gnome - GtkSettings
AFAIK, It is difficult to get all apps with scroll to the left. Even if the source of GTK3 libraries is modified to get it, It will affect only apps which uses gtk-scrolled-window. Not apps which compose their own window using scroll component.
GTK-based apps
You can do that with a config file in your home, namely gtkrc :
Use your favourite editor
nano ~/.gtkrc
enter the following
gtk-scrolled-window-placement = top-right
To make sure every gtk app is using the file, I've created symlinks
ln -s ~/.gtkrc ~/.gtkrc-2.0
ln -s ~/.gtkrc ~/.gtkrc-3.0
The next time you open a GTK app, the scrollbar should have moved to the left
Source and further Documentation:
What is the .gtkrc file ?
GTK3 developer reference manual for gtkrc
Doesn't seem to be working with GIMP - maybe someone else has an idea ?
It works for the brushes dialog in gimp, but not for the main windows. It does not work in mypaint at all. Also not in nautilus and epiphany.
It might be that this is hardcoded in GIMP. It brings its own gtkrc files, but seems to ignore (or override?) the gtk-scrolled-window-placement = top-right line. I'm sorry about that... If no one here is able to help, you might consider opening a bug with GIMP and/or Ubuntu, since this is not expected behaviour.
These things are where linux could shine, but it doesn't :( Thanks for all your efforts. (also @Ratler)
| common-pile/stackexchange_filtered |
How to find the number of lines in a text file given input in a program
We have to create 2 programs sortwords.c and print_anagrams.c
We are then supposed to type the command (to obtain the output):
./sortwords < wordfile.txt | sort | ./print_anagrams > anagrams.txt
In the sortwords.c program, I'm using gets() function, but I don't know how many times I should loop it. I have a similar problem with print_anagrams.c... I don't know how many input lines, so I don't know how many times should I call gets().
Any suggestions for how I can get the number of lines within the program?
You read until EOF — gets will return NULL. But be careful with gets, as you might overflow your buffer.
| common-pile/stackexchange_filtered |
JAXB unmarshalling returns null attributes command line
JAXB unmarshalling returns null attributes when I run the jar in command line. But works fine with eclipse.
File file = new File("oozie1.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(com.ClassGen.ObjectFactory.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
Source source = new StreamSource(file);
JAXBElement<com.ClassGen.COORDINATORAPP> root = jaxbUnmarshaller.unmarshal(source, com.ClassGen.COORDINATORAPP.class);
com.ClassGen.COORDINATORAPP obj3 = root.getValue();
obj3.getAction(); // This returns a null. But works fine with eclipse. With Eclipse it returns an ACTION object.
Any idea on whats going wrong?
Thanks,
Mahalakshmi
What is obj3 ? here . Are you getting obj3 as null ? or the obj3.getAction ( your method) returns null ?
Just made an edit to the above code.. Obj3 is root.getValue() - Here it is: class COORDINATORAPP. it doesn't return null.
Add your xml and class ClassGen. Are you sure that same jdk is used in both cases?
Is your classpath correct when you run it from command line? If your classpath isn't correct, then your context classes won't be found and you'll get null references...
@Ryan, I use a Manifest file to specify the classpath while building the jar. Manifest file specifies the external jars used in the project but doesn't specify the java library jars.
@Ilya: When running in the command line, I removed the packages. I have put all the java files and classes and the xml in the same folder I used JDK 1.6.0 in the Eclipse. I checked the java -version in command line.. it aslo says 1.6.0. But I am not sure if it is a JDK or a JRE. How to add JDK to class path using Manifest File in command line?
You don't use a manifest if you're not using a jar file to execute, but if you want to specify additional classes, you use the -cp or -classpath option to the java command. Mind you, this will not work if you use the -jar option...
@MahalakshmiLakshminarayanan Have you been able to resolve this issue? I'm stuck at the same place right now
@ephilip I couldn't resolve it. But I guess its probably due to jdk differences. Were you able to resolve it?
Yes I was. and yes, the JDK was causing the issue; I had developed it using JDK1.7_60 but the deployment machine was using JDK1.8_05
Try to check if the file exists. The problem could be, that the file cannot be found.
File file = new File("oozie1.xml");
if(file.exists())
{
// your code
}
No, I checked. The file is actually present. I even read the complete file in the code and checked.
| common-pile/stackexchange_filtered |
Hiding & Unhiding Excel Rows
Here are my requirements:
The user will select 1 - 10 in a drop down list, which unhides up to 10 groups of rows below this. Let's call each group to be hidden/shown "X", and X consists of about 13 rows, and there are 10 X's stacked vertically on the sheet. Therefore, when a user selects '2' for example it will reveal the first two X's, but the remaining 8 groups of rows remain hidden. This part of the code works fine, but it is the background.
Here is the not-working part. Within each "X" (group of rows now made visible based on previous input), the user enters info down the page, and as they go down I would like certain rows within individual X's to hide/unhide based on inputs.
For example, if the user inputs "Residential status" as "Renting", a row should be unhidden saying "Input weekly rent here." Or if they input it as "Other" a different row should be unhidden saying "Please comment."
Hope this clarifies,
This is my current code for just the first 'X', I figured I'd fix this part first then replicate it:
If Cells(3, 55).Value = "1" Then
Rows("57:70").EntireRow.Hidden = False 'User selects options 1- 10
If (Range(C62) = "Renting" Or Range(C62) = "Paying Off Home - Mortgaged To OFI") Then
Rows("63").EntireRow.Hidden = False
Rows("64").EntireRow.Hidden = True
ElseIf (Range(C62) = "" Or Range(C62) = "*") Then
Rows("63:64").EntireRow.Hidden = True
ElseIf Range(C62) = "Other" Then
Rows("63").EntireRow.Hidden = True
Rows("64").EntireRow.Hidden = False
End If
End If
use Cells(3, 55).Value = 1
I'm not sure I understand what you mean when you talk about this X that the user is picking? They're supposed to select options 1-10 but you're only showing us 3 of the scenarios you have so far. Does this code work as is and you want to add something to it?
Yeah it (sort of) works but doesn't do everything desired. Only showing one example for clarity.
In this case, I would say "X" is rows 57:70 (line 2).
Code doesn't work around the part where it is hiding/unhiding the same rows that have been hidden/unhidden previously
| common-pile/stackexchange_filtered |
Why does the root element in layout xml file have height and width as match_parent
When I create a new android project using eclipse for android developers, it generates all the files which includes the layout XML file. I checked the root element (LinearLayout) in it and its attributes are,
android:layout_width="match_parent"
android:layout_height="match_parent"
I am not able to understand what "match_parent" means for the root element. I did a little bit of digging and found out :
For the root LinearLayout, the value of both the height and width
attributes is match_parent. The LinearLayout is the root element, but
it still has a parent – the view that Android provides for your app’s
view hierarchy to live in.
Can someone please explain what this means.
You have your own answer. When you have match_parent your LinearLayout will match the same height and width as the view that Android provides for your app's view hierarchy to live in.
I am not understanding - "but it still has a parent – the view that Android provides for your app’s view hierarchy to live in."
Yes, that View provided by the system is the parent for whatever view you create.
Basically, think of the parent as "all available space". Of course this excludes space taken up by the Action Bar, System Notification Bar, and (on devices that have them) the software buttons at the bottom of the screen.
ok... So the view provided by android is the entire canvas/screen except action bar**??.. and it is the parent of all root elements in layout files?...
Yeah. You'll never interact with it directly (that I know of) and your view in most cases should stay match_parent for both height and width.
| common-pile/stackexchange_filtered |
How can I see a list of status-completed questions sorted by when they were completed?
I'd like to see a list of "status-completed" questions so I can tell what has changed lately. Right now you can see everything with that tag, and you can sort by date. However, this is the date the question was asked, not when the suggestion was implemented. Is there any way to see sort this way? Is this something that could be added?
Your best bet is to sort by active. While this will introduce some false positives (i.e. recent activity other than the addition of status-completed), you will be able to see what posts have been recently marked as well. Protip: If Jeff Atwood is the last modifier, there's a good chance that modification is the addition of the tag.
Well, it would have worked. But now that we have this question and you posted how to do it, everyone will be reading through those items today and making changes that throw the order off ;)
I don't think you can, but you could try and rank them by the number of votes they receive. Atwood said in the past that they tend to take on the ones with the highest vote totals first, so that may be an indicator of the order of completion.
Why don't you use the RSS feed of the tag?
| common-pile/stackexchange_filtered |
How to validate format of data using glob in python?
I have a list of different files in my folder and these files have several formats, like PDF, txt, Docx and HTML. I want to validate the format of the files in python.
Here is my attempt
import os
import pdftables_api
import glob
path = r"myfolder\*"
files = glob.glob(path)
for i in files:
if i.endswith('.pdf'):
conversion = pdftables_api.Client('my_api')
conversion.xlsx(i,r"destination\*")
The reason for this is I want to iterate through each file and check if the file is pdf, then it is pdf, convert it into excel using API from PDFTable_api package in python and save it in the destination folder. But I don't feel like this is an efficient way to do this.
Can anyone please help me if there is an efficient manner of achieving this?
What about glob.glob('myfolder/*.pdf')
@zamir yes I can use that, but how can I iterate through the files if I use glob.glob?
| common-pile/stackexchange_filtered |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.