text
stringlengths 64
89.7k
| meta
dict |
---|---|
Q:
Simple variance question: variance of the whole expression when one variable is random
A very simple question about the variance!
I'm interested in the variance of an expression with a random variable inside it.
For an expression of this form:
$a = \sum_{i=1}^{m}(x_i \cdot y_i - z_i)$
where $y_i$ is a random variable with an expectation $\mathbb{E}(y_i)$, would the expectation of the whole function simply be:
$\mathbb{E}(a)=\sum_{i=1}^{m}(x_i \cdot \mathbb{E}(y_i) - z_i)$
Since variance is $Var(a)=\mathbb{E}(a^2)-(\mathbb{E}(a))^2$, I assume I can simply plug this expression (if correct) into this variance formula. Is this correct?
Thanks!
A:
If $x_i$ and $z_i$ are deterministic constants for each $i = 1, \ldots, m$, and $m$ is also a known constant--that is to say, $y_i$ for $i = 1, \ldots, n$ are the only random variables involved, and they are independent--then the variance of $a$ is better calculated as $$\operatorname{Var}[a] \overset{\text {ind}}{=} \sum_{i=1}^m x_i^2 \operatorname{Var}[y_i].$$ This is because $z_i$, being deterministic, has zero variance. If the $y_i$ are not independent, then the variance of $a$ will require knowing the covariances between each $y_i$, $y_j$ for $1 \le i \ne j \le m$ in addition to the variances of each $y_i$.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to list linux running process from C#.net client?
I want to read all the running process in linux server from my C#.net client ?
Can you please show me the way or possibility for achieving this ?
We are in same domain.. I guess no firewall issue and but I cannot write or install anything on server.
(I am trying this to get hold of the process id running on linux box and when that process changes the process id .. i have to run some logic in my client app)
A:
You will need to do this via SSH. For C#, I'd take a look at SharpSSH. Run ps -e | grep and you should be able to parse the ID number quite easily.
As far as I know, process IDs only change when the process is restarted, but I am no authority on the matter.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Using conditional clause in IFindFluent .SortBy block
I'm trying to apply a conditional SortBy to a find as follows:
var findFluent = Collection.Find (...)
.SortBy (record => record.IsActive)
.SortBy (record => record.Client != null
? record.Client.Profile.FirstName
: record.Profile.FirstName);
However, I'm receiving the following error:
"Unable to determine the serialization information for record => IIF((record.Client != null), record.Client.Profile.FirstName, record.Profile.FirstName)."
Do I have to add/implement IBsonDocumentSerializer on one of the classes in question or is this operation not possible?
A:
I ended up simply adding a new .SortBy () clause based on the logic in the conditional:
var findFluent = Collection.Find (...)
.SortBy (record => record.IsActive)
.SortBy (record => record.Client.Profile.FirstName)
.SortBy (record => record.Profile.FirstName);
The driver seems to ignore the sort if a value is null or cannot be evaluated.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
jquery-select2: selection of multiple options at once with a button
I have a list of users that can be selected (multiple selection is possible). Of course all users can be selected manually, which is excellent.
Further on I have user groups. Most of the times it is required to select only those users of a group. Therefore i would like to have a kind of quickway to add all the users, just by clicking on the a group name.
I'm a big fan of select2, but i wasn't able to get this to work.
I have found that via the .val() function elements could be selected. But these elements are only displayed when another element is selected.
So i need a kind of update function. How can i do this?
I have tried to trigger events (like change) but without success.
Can you help me?
<link href="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0-rc.2/css/select2.css" rel="stylesheet" />
<script src="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0-rc.2/js/select2.full.js"></script>
<script type="text/javascript">
$("#id_invited_user").select2({
"placeholder": "Select user",
});
$("#testbuttonclick").on('click',function (clickEvent){
clickEvent.preventDefault();
$("#id_invited_user").val([1,2]);
});
</script>
<select multiple="multiple" class="selectmultiple form-control"
id="id_invited_user" name="invited_user">
<option value="1">Option1</option>
<option value="2">Option2</option>
<option value="3">Option3</option>
<option value="4">Option4</option>
<option value="5">Option5</option>
</select>
<a href="" id="testbuttonclick" >select predefined options</a>
A:
You have all of the right code, except you are missing one important detail.
Whenever you change the value of Select2 (or any other JavaScript component), you should always trigger the change event. This event is nativly triggered by the browser when the value is changed, but it must be manually triggered when the value is changed programmatically.
$("#id_invited_user").trigger("change");
This should always be placed after your call to .val(xyz).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Prevent Azure Cloud Service from uninstalling software automatically
We are running an Azure cloud service. We have an instance of Scalyr agent installed on the box to capture the logs. Every few days/weeks, the scalyr agent gets automatically removed from the instances. We believe this happens when windows automatically patches the boxes. Is there a way to prevent this from happening?
A:
Cloud Services are the old, legacy solution , I would recommend you move away from that.
The issue you are having is due to you using cloud services, this is a PaaS solution where whatever you want to run on the VM is supposed to be part of your application bundle you deploy with the cloud service. Manually installing things on the cloud service VM's is not supported and you will see the issue you have observed.
You can see this from the docs here:
Unlike VMs created with Virtual Machines, writes made to Azure Cloud
Services VMs aren't persistent. There's nothing like a Virtual
Machines data disk
If you want a VM you can manually updated then you want to look at using IaaS virtual machines (and use the ARM version, not classic).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Java interface implementations factory object
Background
Since I don't have a java background I'm struggling to create a factory object that returns implementations of a specific interface. Something similar to this...
Factory.create();
where create should return an interface. Obviously, create needs to know what I'm trying to "create". It could be by passing in a enum so that create can switch through all values of the enum and decide what to create/return...I don't know exactly what's the best way to go about this.
Problem
The main problem I'm trying to solve is to provide an implementation-agnostic solution where consumers of this "factory framework" don't need to know anything about the implementation details. This allows me to change implementation classes and even swap out concrete implementations without having to re-factor an entire application or system.
What I currently have
I have the following interface in place
public interface EntityValidator<T> {
public boolean isValid(T t);
public List<String> getErrors();
}
and so far a couple of implementations that look like the class below...
public class Foo implements EntityValidator<EntityA> {
private List<String> errors;
public boolean isValid(EntityA a){
///implementation details
}
public List<String> getErrors(){
return errors;
}
}
the actual example is a fair bit more complex since there's an abstract class involved but that's out of the scope of this question. And finally the factory object, which is where I'm stuck at the moment
public final class EntityValidatorFactory {
public static <T> EntityValidator<T> create(MyEnum value){
if(value == VALUE_X){
//THIS IS WHERE I'm stuck
}
}
}
I can't seem to find the way to return out of the if statement (which could be a switch BTW)
Question
Is there a way to return a generic interface from a concrete class that implements it without having to manually cast it to that interface?
Any solution would be appreciated as long as it doesn't involve change the consuming code when I change or swap implementation classes.
A:
As seen in the Wikipedia article on the Factory pattern, to make differing concrete versions of the factory’s output objects, your factory itself should actually be various different factory classes. The various factory classes should be implementing a shared factory interface or extending a shared factory abstract superclass.
By the way, I've seen the verb make used with Factory classes to stick with the metaphor of a real physical factory that makes things. You may want to use that word rather than "create".
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to get 2x image as screen shot?
I want to take screen shot of window and use that image as background view for new view controller. My problem is, that image is some what blur in retina display because the image should be 640X1136. But the following code returns image with size of only 320X568.
Note: If I use the apple's private API UIGetScreenImage() it returns the image in size 640X1136.
-(UIImage*)getScreenShot:(CALayer*)layer
{
UIGraphicsBeginImageContextWithOptions(layer.frame.size, NO, 0.0);
[layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
[self getScreenShot:self.window.layer];
Is any way to get the screen shot image in size 640X1136 with out using apple's private API?
A:
-(UIImage*)getScreenShot:(CALayer*)layer
{
CGFloat scale = 1.0;
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 40000
if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]){
scale = [[UIScreen mainScreen] scale];
}
#endif
UIGraphicsBeginImageContextWithOptions(CGSizeMake(layer.frame.size.width*scale, layer.frame.size.height*scale), NO, 0.0);
[layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Some confusions setting up Asterisk IVR menu
I have some confusions regarding setting up Asterisk and your help will be much appreciated!, I have a 4 port FXO card and I have 4 analog lines, currently I have 1 line in the card where a user can call, upon calling he hears a sample ivr menu, my questions are:
If i put all 4 lines, how do I make it so I can use all 4 lines on IVR menu, lets say I have given everyone (Number 1) and 3 people call at a time, the line 1 will go busy for the other 2 users then, how do i resolve it to use all the 4 lines?
Is it possible to entertain more than 4 people at a time for just the IVR menu NOT the customer support
Your help will be much appreciated! Thanks
A:
1) you can setup different context for every new line. You can write any number of contextes and put in dialplan almost anything you can imagine, it just matter of skills.
2) PSTN line have 1 wire. So 4 lines is 4 wires. It is analog connection. You can't use same wire for 2 or more channels. IF you need more then 1 per wire, you have use PRI lines.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Python object appears as map (dict) but can't call by attribute or __getitem__?
I have an object myobj (an instance of MyObj) in python which, when called with print(), prints
{"host": "localhost", "user_indices": [], "password": null, "port": 27017}
So myobj appears to be a dictionary-style object. But myobj['host'] raises
TypeError: 'AutoProxy[MyObj]' object has no attribute '__getitem__'
And I get an AttributeError when trying myobj.host.
I've also tried using myobj.__dict__['host'] and dict(myobj)['host'] to no avail. Has anyone encountered this problem before?
A:
First of all, there is no such thing as "null" in python. You should use "None" instead. When you are using null the code should raise a NameError.
Second, try this code, maybe just switching the null to None should fix the problem:
>>> temp = {"host": "localhost", "user_indices": [], "password": None, "port": 27017}
>>> temp['host']
'localhost'
>>>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Using pyfmi with multiprocessing for simulation of Modelica FMUs
I am trying to simulate multiple Modelica FMUs in parallel using python/pyfmi and multiprocessing. However I am not able to return any pyfmi FMI objects from the subprocesses once the FMUs are initialized. It seems that pyfmi FMI objects (e.g. pyfmi.fmi.FMUModelCS2 or pyfmi.fmi.FMUState2) are not pickable. I also tried dill to pickle, which doesn't work for me eather. With dill the objects are picklable though, meaning no error, but somehow corrupted if I try to reload them afterwards. Does anyone have an idea of how to solve this issue? Thanks!
A:
The problem is that pyfmi.fmiFMUModelCS2 is a Cython class dependent on external libraries which makes it unpickable. So it is not possible unfortunately.
If you want to use multiprocessing the only way forward that I see is that you first create the processes and then load the FMUs into the separate processes. In this way you do not need to pickle the classes.
A:
I faced a similar problem when I created EstimationPy. I ended up creating a wrapper for running parallel simulation of the same FMU using multiple processes.
I suggest you to look at the implementation here
https://github.com/lbl-srg/EstimationPy/blob/master/estimationpy/fmu_utils/fmu_pool.py
And to the example http://lbl-srg.github.io/EstimationPy/modules/examples/first_order.html#run-multiple-simulations
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Split Date and time in javascript or jquery
I am getting date as below
2010-10-18,09:11:00
How to split date and time in comma seperated values like 2010,10,18,09,11,00
I tried Date.split('-').join(",") but i get as 2010,10,18 09:11:00
I also want to split time into comma seperated value. So my final output is `2010,10,18,09,11,00
How to achieve this using javascript or jquery? Also i may get date time in either of following format
2010-10-18 09:11:00 or 2010.10.18 09:11:00
Update`
Sorry i get date as below 2010-10-18 09:11:00
A:
Super easy to do with regex:
var str = "2010-10-18,09:11:00"
var replaced = str.replace(/[-,:\s]/g, ",")
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Windows sessions questions
I'm developing an app (AppRunner) that executes another app (APP) using the console logged in user's token (CreateProcessAsUser). AppRunner should be able to execute APP from any session/user combo, including session 0 + System or a standard user's session / username.
Since this topic is new for me, I have a few questions about sessions for which I didn't find answers after googling:
1. Can there be more than 1 active sessions?
2. Is it possible to not have any active sessions?
3. Is there a scenario where user System will fail getting the active session's user token? (WTSQueryUserToken)
4. If I enumerate through sessions using WTSEnumerateSessions, and I failed finding an active session, is there any point using WTSGetActiveConsoleSessionId? or WTSGetActiveConsoleSessionId is just a wrapper of WTSEnumerateSessions?
Thank you very much!
A:
Can there be more than 1 active sessions?
There can be multiple sessions in the WTSActive state at a time, yes. These represent sessions with logged in users, both local (on the physical machine) as well as remote. Though, only 1 local session at a time will ever be attached to the physical keyboard/mouse/monitor (KMM) at a time. That session is what you see onscreen, and it may or may not have a user logged in to it. And a local user can switch between multiple local sessions, or log in/out of them, at will, thus affecting which session is attached to the KMM at any given moment. Users that are remoted in will be logged in to their own sessions, but those sessions will never be attached to the KMM.
Is it possible to not have any active sessions?
Yes, if there are no users logged in.
Is there a scenario where user System will fail getting the active session's user token? (WTSQueryUserToken)
Yes. If there is no user logged in to the requested session, WTSQueryUserToken() will fail and GetLastError() will return ERROR_NO_TOKEN. Also, even if you query a remote session that has a logged in user, WTSQueryUserToken() may or may not fail depending on HOW the user logged in to the session.
If I enumerate through sessions using WTSEnumerateSessions, and I failed finding an active session, is there any point using WTSGetActiveConsoleSessionId? or WTSGetActiveConsoleSessionId is just a wrapper of WTSEnumerateSessions?
WTSGetActiveConsoleSessionId() returns the session that is currently attached to the KMM. That session may or may not have a user logged in, but it can still display a UI.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Regex code tested but not matching when used with sed
Why does the following
$ echo "test\|String" | sed 's/(?!\||\\)./&./g'
test\|String
Not produce:
t.e.s.t.\|S.t.r.i.n.g.
I have tested the regex code and it picks the string up correctly in my tests
I want it to do the following:
$ echo "test\|String" | sed 's/(?!\||\\)./&./g'
t.e.s.t.\|S.t.r.i.n.g.
A:
I would have written what you describe like this:
echo "test\|String" | sed 's/[^\\|]/&./g'
|
{
"pile_set_name": "StackExchange"
}
|
Q:
detecting changes to my program's focus
When other programs are open in Android, how do I know when my program loses focus or gains focus?
I've seen the View onFocusChanged event, but I think that's unrelated (when i use a view changer).
How can this be done?
A:
In your Activity, you can override the life cycle methods. Specifically, onCreate, onStart, onResume, onPause, onStop and onDestroy. The most useful ones are:
onCreate: great for one time initialization.
onResume: refresh your data because your app is about to take foreground again.
onPause: save your data and stop anything that doesn't need to be running while your app doesn't have the foreground.
See http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle for a complete overview of these methods and your activities life cycle.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Why did my Nexus 4 download the Jelly Bean 4.3 update again?
I've got a stock, non-rooted Nexus 4 which I updated to Jelly Bean 4.3 when the OTA update came out a month or more ago. Just today I got another message that there was a system update available. It said it would update to 4.3, and I double-checked (and took a screenshot), and confirmed I already had it in "About phone."
Nonetheless, I went ahead with the update to get rid of the notification, and it went through the usual process. The before and after screenshots of the about screen confirm that I had the exact same Android, Baseband, and Kernel versions, as well as the same Build Number. I can't find any differences after the update. Does anyone know why this might have happened?
Before screenshot, taken 2013-08-23 16:28:04, before the update was started about a minute later:
After screenshot, taken 2013-08-23 16:36:14 after the update finished and it restarted.
A:
The before and after screenshots of the about screen confirm that I had the exact same Android, Baseband, and Kernel versions, as well as the same Build Number
Actually, they do not. The first screenshot shows a build number of JWR66V, and the second is JWR66Y. An official changelog has not been released, but T-Mobile's documentation indicates that the update contains "security" updates. You can also find some (unofficial) discussion of the actual code commits in this article. So although the version number was not incremented, it is a different build than you previously had.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
ActiveAndroid how to get single column items from table and store those in arraylist
I am new to active android, i have a table named MyTable with columns articleName, articleId and imageTicket, i want to store all imageTicket column values in a ArrayList. can anyone help me with a query?
A:
Here is my code to get imageTicket column from MyTable
private ArrayList<MyTable> myTableList = new ArrayList<MyTable>();
// to get all table data
myTableList = new Select().from(MyTable.class).execute();
for(int i = 0; i < myTableList.size(); i++){
String imageTicket = myTableList.get(i).getImageTicket();
// do something with imageticket value
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to change a players game mode when crossing a threshold
I am running a vanilla Minecraft server on my Azure account and have an idea for it that I'm not sure is possible or not. Essentially I want to set up an area, something like 8x8 chunks that is designated as a creative area.
In order to achieve this I'm thinking that I will need at least one command block running constantly checking for players entering or exiting the area and adjusting their game mode accordingly. The problem I'm having is that I can't think of or find a way to reliably detect the threshold crossing, specifically for any height.
One potential solution I've come up with is to surround the creative chunks with barrier blocks to limit the ways in which the player can leave the area, but this is not ideal.
Bonus #1: If the player attempts to fly out of the creative zone it would be nice to also teleport them to the ground so they don't die when the game mode is switched.
Bonus #2: Can I have another set of command blocks that will store/restore a players inventory when crossing the threshold.
A:
This answer covers the main question and Bonus #1, but not Bonus #2.
Target selectors can be used to select a player in a cuboid area.
I'd first set up a dummy objective, which will store whether or not a player is in the area:
/scoreboard objectives add inCreativeArea dummy
As an overview, you then want to, in this order on a clock:
Set everyone who is in this specific area's inCreativeArea score to 3
Reduce everyone's inCreativeArea score by 1
Give creative mode to anyone with an inCreativeArea score of 2, survival mode for anyone with an inCreativeArea score of below that
Teleport anyone with an inCreativeArea score of 1 to the ground
1
The actual command for this part should look something like:
/scoreboard players set @a[X,Y,Z,dx=DX,dy=DY,dz=DZ] inCreativeArea 3
Replace the capital X, Y and Z with the coordinates of the most negative corner of the cuboid creative area, and the DX, DY, DZ with the length, height and width of the area.
This sets anyone who is in the creative area's score to 3.
2
/scoreboard players remove @a[score_inCreativeArea_min=1] inCreativeArea 1
This reduces everyone's inCreativeArea score by 1. People who are in the area will now have a score of 2, people who just left the area a score of 1, and others a score of 0.
3
/gamemode 1 @a[score_inCreativeArea_min=2,m=0]
/gamemode 0 @a[score_inCreativeArea=0,m=1]
These set the gamemodes appropriately. The m argument prevents it updating people who are already in that gamemode, which would work but spam their screen endlessly with the "Your game mode has been updated" message.
4
Finally, the easiest way to teleport players who have just left to the ground is a relative spreadplayers command which always chooses a location on a solid block:
/execute @a[score_inCreativeArea_min=1,score_inCreativeArea=1] ~ ~ ~ spreadplayers ~ ~ 0 1 false @p
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Add jQuery to Wordpress head
I'm trying to add some custom jQuery to a page on my wordpress site.
I have used a plugin that allows me to insert my code directly in to my head.php file for the specific page but the code doesn't run, i just get the error
TypeError: $ is not a function
$(document).ready(function(){
I used jQuery(function ($) { ... from an answer to this question: TypeError: $ is not a function when calling jQuery function
<script>
jQuery(function ($(document).ready(function(){
jQuery(function ($)("#a").mouseover(function(){
jQuery(function ($)("#b").css("background-image", "url('https://oxfordriderwear.com/wp-content/uploads/2019/07/straight-black-cropped.jpg')");
});
jQuery(function ($)("#a1").mouseover(function(){
jQuery(function ($)("#b").css("background-image", "url('https://oxfordriderwear.com/wp-content/uploads/2019/07/straight-blue-cropped.jpg')");
});
jQuery(function ($)("#a2").mouseover(function(){
jQuery(function ($)("#b").css("background-image", "url('https://oxfordriderwear.com/wp-content/uploads/2019/07/straight-wash-cropped.jpg')");
});
jQuery(function ($)("#slim-a").mouseover(function(){
jQuery(function ($)("#slim-b").css("background-image", "url('https://oxfordriderwear.com/wp-content/uploads/2019/07/black-slim-rollover-cropped.jpg')");
});
jQuery(function ($)("#slim-a1").mouseover(function(){
jQuery(function ($)("#slim-b").css("background-image", "url('https://oxfordriderwear.com/wp-content/uploads/2019/07/blue-slim-rollover-cropped.jpg')");
});
jQuery(function ($)("#slim-a2").mouseover(function(){
jQuery(function ($)("#slim-b").css("background-image", "url('https://oxfordriderwear.com/wp-content/uploads/2019/07/blue-washed-slim-rollover-cropped.jpg')");
});
});
</script>
I think I'm getting my syntax wrong but I'm not sure where.
I also tried linking jQuery in the code via CDN, but this stopped the other jQuery elements on my page working that are from plugins, such as my navigation bar.
If anyone knows what I'm doing wrong and how to get around this issue, i'd greatly appreciate the help!
A:
When I run this code, it throws:
Uncaught SyntaxError: Unexpected token (
function ($)("#b")
… is a syntax error.
You use $ as the name of an argument and inside the function as a variable. You've skipped the bit where you create the body of the function with { and } and the bit where you put the function name ($) before the (arguments) to it.
The syntax you are looking for is (I've split it up into clear, named functions instead of inlining everything).
function readyEventHandler ($) {
// Inside this function `$` is whatever is passed as the first argument
function mouseoverEventHandler(event) {
// Code to run on mouseover
}
const element = $("#a");
element.on("mouseover", mouseoverEventHandler);
}
jQuery(mouseoverEventHandler); // When the DOM is ready, this will call mouseoverEventHandler and pass the jQuery object in as the first argument
… or the version where everything is inlined:
jQuery(function ($) {
$("#a").on("mouseover", function (event) {
// Code to run on mouseover
});
// Put other calls to `$` here. Don't create additional `jQuery(readyEventHandler)`s!
});
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Can someone else patent an invention that I have introduced in my open source project?
Is open source protected in any way if I haven't filed for a patent myself? Maybe a specific license?
Any examples of open source projects that introduced 'inventions' that could be patented (but they were not) would be really appreciated.
And please take into consideration: design & utility patents.
A:
In general, no: once you've published your idea (whether as open source or not), it becomes part of the "prior art" and is no longer eligible to be patented. Patents are for innovation, and almost by definition something can't be innovative if it's just taking someone else's idea.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Problem - Expected value and Martingales
I have a problem with the following exercise.
Let $(X_n)$ be a limited martingale (there exists $M>0$ such that for each $n$ is valid $P(|X_n|<M)=1$).
Show that for each $m>n$ is valid $E[(X_m-X_n)^2]=Var(X_m)-Var(X_n)$.
I tried to solve the exercise in the following way:
$E[(X_m-X_n)^2]=E[(X_m-X_n)]^2+Var(X_m-X_n)
=(E[X_m]-E[X_n])^2+Var(X_m-X_n)=Var(X_m-X_n)
=Var(X_m)+Var(X_n)-2Cov(X_m,X_n)$
I'm stuck here.
Thanks in advance for your help.
A:
Note that
$$\mathbb{E}[(X_m-X_n)^2]=\mathbb{E}[\mathbb{E}[(X_m-X_n)^2\mid \mathcal{F}_n]]$$
If you expand out the square and use properties of conditional expectation and the fact that $\{X_n\}$ is a martingale, you should get
$$ \mathbb{E}[(X_m-X_n)^2]=\mathbb{E}[X_m^2]-\mathbb{E}[X_n^2]=\mathrm{var}(X_m)-\mathrm{var}(X_n)$$
with the last equality following from the fact that $\mathbb{E}[X_m]=\mathbb{E}[X_n]$.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Installing SQL Server 2016 for Azure development
Coming from a dev background, I'm not an expert in SQL Server. When installing SQL Server 2016, I have the option of installing three different components:
New SQL Server stand-alone installation
SQL Server Management Tools
SQL Server Data Tools
I'm only interested in SQL Azure development with Visual Studio. The question is should I only install the last two items on my local machine? Do I need the full-blown SQL Server 2016 from the first item?
A:
If you're not planning on deploying to a local SQL Server database engine, you can skip that section from the installer, yes.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Server process data table continously when next button is clicked
I used datatable to process big data on my backend. In DTOptionsBuilder, I'm used withFnServerData method to get a range of data from the database. It parsed everything in the table from start to limit. But the below pagination number was always one. Seems like not working, I only can use the top left number filter but is not what I want.
Controller
$scope.dtColumns = [
DTColumnBuilder.newColumn('d', 'column').withOption('defaultContent', ""),
DTColumnBuilder.newColumn('m', 'mukim').withOption('defaultContent', ""), ....
];
$scope.pageData = {
total: 0
};
var get = function(sSource, aoData, fnCallback, oSettings){
var draw = aoData[0].value;
var order = aoData[2].value;
var start = aoData[3].value;
var length = aoData[4].value;
var params = {
start:start,
limit:length
};
ValuationService.SearchValuation(params, function(result, response){
if(result == true){
var records = {
'draw': 0,
'recordsTotal': 0,
'recordsFiltered': 0,
'data': []
};
if(response.result){
records = {
'draw': draw,
'recordsTotal': response.total_data,
'recordsFiltered':response.result.length,
'data': response.result
};
}
$scope.pageData.total = response.total_data;
fnCallback(records);
}
});
}
$scope.dtOptions = DTOptionsBuilder.newOptions()
.withFnServerData(get) // method name server call
.withDataProp('data')// parameter name of list use in getLeads Fuction
.withOption('processing', true) // required
.withOption('serverSide', true)// required
.withOption('paging', true)// required
.withPaginationType('full_numbers')
.withDisplayLength(10)
.withOption('rowCallback', rowCallback)
.withDOM('lrtip');
function rowCallback (nRow, aData, iDisplayIndex, iDisplayIndexFull) {
$compile(nRow)($scope);
}
HTML
table.row-border.hover(datatable="", dt-instance="dtInstance",dt-columns="dtColumns", dt-options="dtOptions" style="overflow:auto;")
What I want
The table below will show the number of pagination. I can click the next and previous. When I click next, it will call the API again to retrieve and parse another start to limit into table.
Current Issue
Table pagination shows '1' only, next button disabled.
I can solve the issue by select the number at top left corner, but it shown in one page which I don't want.
A:
The problem lies on the filter data part, because my data was filtered, not showing all the data. Simply by changing the records filtered respect to total data available will solve the issue.
records = {
'draw': draw,
'recordsTotal': response.total_data,
'recordsFiltered':response.total_data, // Change total_data
'data': response.result
};
|
{
"pile_set_name": "StackExchange"
}
|
Q:
how to avoid hard-coding urls in webapp templates
I'm developing software on google app engine. I'm using the webapp framework. is there any way to avoid hard-coding urls in the html templates? django provides a solution, but I couldn't find one for webapp. thanks in advance..
A:
WebApp is really very basic.
Django url templatetag is closely tied to its idea of URL resolving by matching regex patterns. As WebApp does not have any serious URL resolver, I imagine this would be really hard task to implement something in this line.
But you are not totally out of luck. Werkzeug has very easy to understand yet powerful URL routing mechanism that allows for reversing urls. You can try to base your implementation on this one (or throw away WebApp and use Werkzeug ;), it's really worth a try).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to make Voiceover to spell each letter in a word?
I have a text CPN34THX which should be read by voiceover as C N 3 4 T H X
Is there any property to be set to UIAccessibility so that it can be read character by character?
A:
Set the accessibilityLabel separately as you needed.
let code = "CPN34THX"
let accessibleCode = code.map { String($0) + " " }.joined() // output: "C P N 3 4 T H X"
myLabel.text = code
myLabel.accessibilityLabel = accessibleCode
For making it more pronounceable, make a string like this:
myLabel.accessibilityLabel = "C^. P^. N^. 3. 4. T^. H^. X^."
|
{
"pile_set_name": "StackExchange"
}
|
Q:
When building HTTP API with Rails 3.2, should I disable front end things such as .js files?
When building HTTP API which respond only JSON format with Rails 3.2, should I turn off things like Asset Pipeline and javascript files?
If so, how to do it correctly instead of manually deleting which sounds dirty?
A:
Probably a good idea if you're only serving up the api, here's how:
rails new appname --skip-sprockets
For an existing application, in your application.rb:
config.assets.enabled = false
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Projectile motion on incline with time-limited, constant acceleration
I have a projectile in 2D space $r=(x, y)$ at time $t_0=0$, which has an initial velocity $v_0$, a launch angle $\theta$ from $(1, 0)$ and which accelerates with a constant $a_0$ until time $t_1$ in the current flight direction of the projectile as well as a constant $g$ downwards $(0, -1)$.
This is, for example, a simplified model of a rocket with a short-lived motor, ignoring changes in mass from the propellant and any air drag.
I'm looking for a definition of the flight trajectory, so that I can determine functions describing the angle $\theta$ to hit a point $(x, y)$, the time to get there, and similar. I only found https://cnx.org/contents/--TzKjCB@8/Projectile-motion-on-an-incline so far. I planned to use the given formulas there to piece together a case distinction based on whether the time to target is smaller or larger than $t_1$, but I am not really sure how to connect the "ends" of the two cases and with the acceleration vector changing over time, I don't know if this can even be done in this way.
A:
The flight path is given by:
$$\frac{d^2}{dt^2}\vec r(t) = a_0(t) \frac{d}{dt}\hat r (t)+ \vec g$$ where $$a_0(t)=\begin{cases}
a_0 & t<t_1 \\
0 & t_1<t
\end{cases}$$ and $$\hat r (t) = \frac{\vec r (t)}{||\vec r (t)||}$$
I put this differential equation into Mathematica, as well as a simpler differential equation involving just the initial portion where $a_0(t)=a_0=const.$. In both cases Mathematica was unable to evaluate it using DSolve, so unfortunately, this does not appear to have an analytical solution. It will need to be solved numerically, which I did using NDSolve.
For a fairly brief rocket burn, this produces a trajectory that is nearly parabolic:
Perhaps more interesting is a trajectory with a long rocket burn. This trajectory it seems that the rocket gradually tips over and then propels itself into the ground on a decidedly non-parabolic trajectory:
|
{
"pile_set_name": "StackExchange"
}
|
Q:
how to calculate pixel count of three images at same time
How can i calculate total pixel of three images at the same time?
I was tried with java Swing Worker and Thread, i got the answer but it takes 1.30 min to return total pixel count(30 seconds for each image, image size 480*303) of specified range. But I need to get answers of three images at same time within 30 sec.
public class ImageProcessor1 implements Runnable{
static int blackPix=0;
BufferedImage tempImg;
public static int blackPixel=0;
public ImageProcessor1(String path) throws Exception{
tempImg = ImageIO.read(new File(path));
}
private static int[] getPixelData(BufferedImage img, int x, int y) {
int argb = img.getRGB(x, y);
int rgb[] = new int[]{
(argb >> 16) & 0xff, //red
(argb >> 8) & 0xff, //green
(argb) & 0xff //blue
};
System.out.println("Process1 :rgb: " + rgb[0] + " " + rgb[1] + " " + rgb[2]);
return rgb;
}
@Override
public void run() {
int[][] pixelData = new int[tempImg.getHeight() * tempImg.getWidth()][3];
int[] rgb;
int height=tempImg.getHeight();
int width=tempImg.getWidth();
int counter = 0;
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
rgb = getPixelData(tempImg, i, j);
if(rgb[0]<125 && rgb[0]>105 && rgb[1]<125 && rgb[1]>105 && rgb[2]<125 && rgb[2]>105)
{
blackPixel+=1;
}
}
}
}
}
A:
It is very strange that iterating over such a small picture takes you 30 seconds!
After a little profiling it seems, that having a println-statement in a hot loop is slowing you down dramatically.
After little modification of your code , a 10500x5788 image takes ~3secs on my machine.
The modified version:
package application;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.concurrent.TimeUnit;
import javax.imageio.ImageIO;
public class ImageProcessor1 implements Runnable {
BufferedImage tempImg;
public static int blackPixel = 0;
public ImageProcessor1(final String path) throws Exception {
final long start = System.nanoTime();
tempImg = ImageIO.read(new File(path));
// Use tracing, profiling and sampling to proof performance issues and fixes
System.out.println("ImageIO took " + TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start)
+ " ms.");
}
@Override
public void run() {
long start = System.nanoTime();
final int height = tempImg.getHeight();
System.out.println("Getting height '" + height + "' took "
+ TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start) + " ms.");
start = System.nanoTime();
final int width = tempImg.getWidth();
System.out.println("Getting width '" + width + "' took "
+ TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start) + " ms.");
start = System.nanoTime();
// reuse variables
int argb;
int red;
int green;
int blue;
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
// HOT LOOP. Do as little as possible. No println calls!
argb = tempImg.getRGB(i, j);
// inline all method calls
red = argb >> 16 & 0xff; // red
green = argb >> 8 & 0xff; // green
blue = argb & 0xff; // blue
if (red < 125 && red > 105 && green < 125 && green > 105 && blue < 125 && blue > 105) {
blackPixel += 1;
}
}
}
System.out.println("Iterating pixels took "
+ TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start) + " ms.");
}
public static void main(final String[] args) throws Exception {
new ImageProcessor1("big.jpg").run();
System.out.println("Number of blackpixels = " + blackPixel);
}
}
On a more general note, you have to be careful with your approach, because you read all of the image into RAM, and then process it. If you do that with 3 or more large images at once, there is a chance of an OutOfMemoryError. If that becomes an issue, you could read an image in as an input stream and process only small buffers of the image at a time.
To see how this can be done see http://imagej.nih.gov/ij/source/ij/io/ImageReader.java .
To see how to accumulate the output of multiple threads , see How write mulithreaded code and accumulate the output from all the threads in a single file .
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Conversion Table
I have been tasked with creating a conversion table, and I cannot figure out why my output on one side is repeating as the other finishes their loop. Can anyone help? Below is my code:
public class Conversion {
public static double celsiusToFahrenheit(double celsius) {
// make conversion
double f = (celsius * 9 / 5) + 32;
return f;
}
public static double fahrenheitToCelsius(double fahrenheit) {
// make conversion
double c = (fahrenheit - 32.0) * 5 / 9.0;
return c;
}
public static void main(String args[]) {
double c;
double f;
//Display table
System.out.println("Celsius \t Fahrenheit \t | \tFahrenheit \t Celsius");
//When i = 40, if i is greater than, or equal to 31, decriment until false
for (double i = 40; i >= 31; i--) {
c = i;
//When j = 120, if j is greater than, or equal to 30, decriment by 10 until false
for (double j = 120; j >= 30; j -= 10) {
f = j;
//Show result
System.out.println(c + "\t\t " + (Math.round(celsiusToFahrenheit(c) * 10.0) / 10.0) + "\t\t |\t" + f + "\t\t" + (Math.round(fahrenheitToCelsius(f) * 100.0) / 100.0));
}
}
}
}
A:
This is due to the nested loop you've introduced.
for (double i = 40; i >= 31; i--) {
c = i;
//When j = 120, if j is greater than, or equal to 30, decriment by 10 until false
for (double j = 120; j >= 30; j -= 10) {
f = j;
//Show result
System.out.println(c + "\t\t " + (Math.round(celsiusToFahrenheit(c) * 10.0) / 10.0) + "\t\t |\t" + f + "\t\t" + (Math.round(fahrenheitToCelsius(f) * 100.0) / 100.0));
}
}
Think of a double loop like the hands of a watch face. The inner loop moves faster than the outer loop (like the minute hand moves faster than the hour hand). What this means is that for every iteration in the Celsius loop, we have ten iterations in the Fahrenheit loop, just as if we were looking at a watch face (we'd have 60 minutes for every 1 hour in that scenario).
As a hint, you can actually declare multiple variables inside of your loop to iterate on. You're going to want to adjust the bounds of the loop condition so that you get the results that you want, but this is a start.
//When i = 40, if i is greater than, or equal to 31, decriment until false
//When j = 120, if j is greater than, or equal to 30, decriment by 10 until false
for (double i = 40, j = 120; i >= 31 && j >= 30; i--, j -= 10) {
c = i;
f = j;
//Show result
System.out.println(c + "\t\t " + (Math.round(celsiusToFahrenheit(c) * 10.0) / 10.0) + "\t\t |\t" + f + "\t\t" + (Math.round(fahrenheitToCelsius(f) * 100.0) / 100.0));
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Why is it Valid to Concatenate Null Strings but not to Call "null.ToString()"?
This is valid C# code
var bob = "abc" + null + null + null + "123"; // abc123
This is not valid C# code
var wtf = null.ToString(); // compiler error
Why is the first statement valid?
A:
The reason for first one working:
From MSDN:
In string concatenation operations,the C# compiler treats a null string the same as an empty string, but it does not convert the value of the original null string.
More information on the + binary operator:
The binary + operator performs string concatenation when one or both operands are of type string.
If an operand of string concatenation is null, an empty string is substituted. Otherwise, any non-string argument is converted to its string representation by invoking the virtual ToString method inherited from type object.
If ToString returns null, an empty string is substituted.
The reason of the error in second is:
null (C# Reference) - The null keyword is a literal that represents a null reference, one that does not refer to any object. null is the default value of reference-type variables.
A:
Because the + operator in C# internally translates to String.Concat, which is a static method. And this method happens to treat null like an empty string. If you look at the source of String.Concat in Reflector, you'll see it:
// while looping through the parameters
strArray[i] = (str == null) ? Empty : str;
// then concatenate that string array
(MSDN mentions it, too: http://msdn.microsoft.com/en-us/library/k9c94ey1.aspx)
On the other hand, ToString() is an instance method, which you cannot call on null (what type should be used for null?).
A:
The first sample will be translated into:
var bob = String.Concat("abc123", null, null, null, "abs123");
The Concat method checks input and translate null as an empty string
The second sample will be translated into:
var wtf = ((object)null).ToString();
So a null reference exception will be generated here
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Graphing in R program
So basically, I have this R output that I am using to make some line graphs
f x N y sd se ci
1 Carla 1 5 0.577437500 0.538098341 0.240644894 0.668137337
2 Carla 2 21 1.975978653 3.258871642 0.711144094 1.483420586
3 Carla 3 8 1.217090357 1.936489842 0.684652549 1.618946022
4 Carla 4 6 0.004543219 0.002500954 0.001021010 0.002624590
5 Liam 1 4 0.356406250 0.203422619 0.101711309 0.323690780
6 Liam 2 8 5.164708412 5.169434477 1.827671087 4.321755376
7 Liam 3 4 0.019294020 0.002592634 0.001296317 0.004125459
8 Meg 1 3 0.337395833 0.383621255 0.221483835 0.952968025
9 Meg 2 11 2.218085777 3.889646592 1.172772574 2.613100136
10 Meg 3 3 2.239833477 3.810413346 2.199943171 9.465591491
11 Meg 4 3 0.004317894 0.002512864 0.001450803 0.006242301
And I used the following code, to make some line graphs:
# Standard error of the mean
ggplot(dfc, aes(x=x, y=y, colour=f)) +
geom_errorbar(aes(ymin=y-se, ymax=y+se), width=.1) +
geom_line() +
geom_point()
# The errorbars overlapped, so use position_dodge to move them horizontally
pd <- position_dodge(.1) # move them .05 to the left and right
ggplot(dfc, aes(x=x, y=y, colour=f)) +
geom_errorbar(aes(ymin=y-se, ymax=y+se), width=.1, position=pd) +
geom_line(position=pd) +
geom_point(position=pd)
But I was wondering if its possible to "highlight" the area occupied by the standard error and stuff.
A:
ggplot(dfc, aes(x=x, y=y, colour=f, fill=f, ymin=y-se, ymax=y+se)) +
geom_ribbon(aes(colour=NULL),alpha=0.5) +
geom_errorbar(width=.1) +
geom_line() +
geom_point()
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Virulent , Pernicious and Detrimental
I would like to compare the words virulent, pernicious and detrimental in a certain contexts in terms of meaning so order to make sure I use them correctly.
From the definitions on dictionaries I can say that the words detrimental and pernicious overlap more in a sense of something harmful, while virulent has a sense of something poisonous or deadly. It is not hard to see virulent reminds of the noun virus. However, apparently being used in certain context, virulent still conveys a sense of something harmful because viruses are harmful or detrimental.
I will give some examples and would like to ask if they sound correct.
Being exposed to second-hand smoking in public places is as virulent
as active smoking.
Being exposed to second-hand smoking in public places is as
detrimental as active smoking.
Being exposed to second-hand smoking in public places is as
pernicious as active smoking.
However I am less sure about these following examples:
Being exposed to violence at early ages is likely to has virulent
effects on children's psychological developments.
Being exposed to violence at early ages is likely to has detrimental
effects on children's psychological developments.
Being exposed to violence at early ages is likely to has pernicious
effects on children's psychological developments.
Virulent also has a meaning of stern or harsh as in "virulent/harsh criticism/remarks" or can be said to imply that you have negative feelings or you are disapproving. Do other words work in the following sentence as well?
Virulent individualism can cause fall apart relationships in a society.
Pernicious individualism can cause fall apart relationships in a society.
Pernicious individualism can cause fall apart relationships in a society.
A:
Detrimental is the most general of these, as it simply means "mildly harmful":
Smoking can be detrimental to one's health.
Virulent means "like a virus": spreads quickly, hard to get rid of, and usually detrimental:
There has been a virulent sense of disenfranchisement spreading through the Western world.
Pernicious is perhaps the most specific of these, as it means "bad, but often in a way that is subtle, sneaky, and generally difficult to detect."
Both the FBI and the CIA have now claimed that Russian hackers exerted a pernicious influence on the recent US election.
So these three words are distant synonyms at best, and should not be swapped for each other.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Fatal error: Class ‘MagentoPycho_Lightboxes_Helper_Data’ not found in appMage.php on line 516
I am facing problem after installing jQuery Lightboxes (FancyBox, PiroBox etc.)
Fatal error: Class ‘MagentoPycho_Lightboxes_Helper_Data’ not found in appMage.php on line 516
[UPDATED]
Some parameters in the js/colorswatch/colorswatch.js (line 34) are undefined when Lightboxes are instaslled ( even if they are disabled ).
Here is my error message. in var\log\system.log:
2013-03-01T10:05:02+00:00 ERR (3): Notice: Trying to get property of
non-object in
D:\xampp\htdocs\store\includes\src\Mage_Adminhtml_Model_Config_Data.php
on line 135 2013-03-01T10:05:02+00:00 ERR (3): Notice: Trying to get
property of non-object in
D:\xampp\htdocs\store\includes\src\Mage_Adminhtml_Model_Config_Data.php
on line 135 2013-03-01T10:05:09+00:00 ERR (3): Notice: Undefined
variable: productId in
D:\xampp\htdocs\store\app\design\frontend\default\helloresponsive\template\catalog\product\compare\sidebar.phtml
on line 32 2013-03-01T10:05:17+00:00 ERR (3): Notice: Undefined
variable: productId in
D:\xampp\htdocs\store\app\design\frontend\default\helloresponsive\template\catalog\product\compare\sidebar.phtml
on line 32 2013-03-01T10:05:22+00:00 ERR (3): Notice: Undefined
variable: productId in
D:\xampp\htdocs\store\app\design\frontend\default\helloresponsive\template\catalog\product\compare\sidebar.phtml
on line 32
This function $this->getGroups() is not returning anything.
A:
First of all make sure it's not your cache or compile.
Then check have app/code/local/MagentoPycho/Lightboxes/Helper/Data.php file in place and there's MagentoPycho_Lightboxes_Helper_Data class inside.
If the problem is still there it is possible that you have another (same extension in another scope) which uses that same group mame (in your case lightboxes).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to balance audio levels to be loud enough yet safe
There are a few sound effects in my game that sound a bit piercing over earbuds but OK when played through the iPhone speaker. Also sound levels seem lower on older hardware. Is there some objective way to be sure my sounds are loud enough yet safe?
Notes: I made my music with GarageBand for iPad. The output was very hot but not clipped. To preview the sounds on my computer I played them in the iPad simulator and matched the volume coming out of my iPhone. To resolve my volume issues, I reduced the high end in Amadeus Pro using the EQ tool. A couple passes for each of the worst sound clips let me reduce the shrillness without muting the volume too badly. Thanks everyone for your help.
A:
I'm not an expert on this field, but this is what my intuition tells me, both from a technical and from a more subjective point of view.
Technical
From a technical point of view, in order to preserve quality, you should start by authoring your audio files as loud as possible but making sure not to exceed a certain volume threshold which would induce clipping on the sound's waveform. Most audio software lets you monitor the levels of your file and detect if there's any clipping taking place.
For instance, in Audacity, you can keep an eye on the Meter Toolbar to make sure your file's within an acceptable volume range. Here's what the toolbar looks like, and read the link above for more information. Basically, the meter should never exceed the scale throughout the duration of the file.
You can use effects like Normalize or Amplify in Audacity to make all of your audio files have the same peak volume without clipping them (in fact by default it normalizes the maximum amplitude to -3dB instead of 0dB, which is probably a good idea too).
Subjective
Then there's a more subjective point of view which is, some sound effects are by nature more aggressive to the ears and should probably be toned down a bit. This depends mostly in the very nature of the sound, so I'm not aware of any existing procedure to automate this correction.
Therefore my suggestion would be to use your ears. In particular, author your audio files using headphones, and preferably on your iPhone and try to adjust the volume levels on your audio files manually so that they are as loud as possible without getting to the point that they "pierce" your ears.
Possibly ask a few other people around you for opinion too, as different people might have different sensibilities.
A:
This grew to be too big for a comment on David's answer, which I endorse.
A good rule of thumb for correcting for different response is that you want to tone down high-pitched sounds. The general reason is that the frequency response of the ear is stronger at higher frequencies (which isn't surprising, given that the ear is quite small). Obviously it falls away at really high frequencies, but in the range where all you're hearing is third or fourth order harmonics.
But specifically talking about headphones, there are two extra reasons: firstly, they have a higher frequency response at higher frequencies (again, because they're small); so you want to compensate for that. Secondly, because higher frequencies are attenuated more with distance. This means that moving the speakers closer to your ears will tend to over-emphasise the treble.
I don't know the iPhone API. Can you test whether headphones are in use and adjust the level of your sound effects accordingly (or even run them through a different EQ)?
A:
One possible objective method to determine if sounds are loud enough yet "safe" is to measure playback frequency response curves at a range of loudness levels for each target.
For each device and listening output combination you wish to audit, record a series of 5 second sine wave sweeps from 10Hz to 22kHz at a range of playback volumes from quiet to loud, stepping in 3dB increments from -48 dB to -9dB and 1dB increments from -9dB to 0dB. Analyze the recordings of these sweeps to build a map of the level-specific frequency response for each target combination. Use an audio spectral view to visually reveal where frequency response drops off and over-modulates (distorts).
The resultant data set will inform you of the point at which distortion can occur, defining the upper-limit of your safe zone for loudness. Subtract 3dB for each instance of sound layering that might occur to allow a reasonable headroom which will technically not distort the sound.
This does not guarantee subjective assurance to not ever be "too piercing". Because the rate at which a sound replays has a big effect on its annoyance factor, you could reduce volume further based on the count of playback instances per second of a sound in your game.
The above method would be suitable for informing the production of many sounds. If you are only concerned with one sound, then you may substitute that sound for the sine sweeps. Alternatively the sine sweep recordings may be used with audio convolution dsp process to predict the frequency response of any particular sound on any particular target playback combination.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
What kind of javascript code should stay in the html file?
How right is it put all the javascript code in the tags of the html file?
Is it considered any better to put all the js code in separate .js files?
I've noticed that many sites (including this) have some js code written in html file itself(enclosed in script tags).
And lets say I decided to put all possible javascript code in separate files. Now, will those external files have access to the elements of the elements of the html document.
I mean, lets say I want to create a new <p> element with text everytime a user clicks a button. Will the external javascript file have access to the document elements to allow this?
A:
If you reference the .js file in your HTML, the JavaScript will have access to all the elements on the page. This applies to dynamically created elements as well.
It is good practice to have as much JavaScript in external files as possible. There shouldn't be a reason for having JavaScript code in the page itself.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Using both JSLint and JSHint
The project I joined is using JSLint and JSHint at the same time. They're launched for the same files, with a unique grunt task. My understanding is that one could use one of them, but when using both of them there's an overlap on the analysis and the checks made.
Is it reasonable to use both of them in the same project ?
A:
JSHint started life as a fork of JSLint. It retains much of the same functionality, to the point you can configure it to behave almost exactly as JSLint does.
A few warnings from JSLint have been removed from JSHint, but these tend to be ones that give little benefit to you. Off the top of my head, one of these warnings is "Unexpected 'else' after disruption", which warns you that you have a redundant else block following a return or throw statement:
if (x) {
return y;
} else { // This `else` block is unnecessary
return z;
}
It is reasonable to use both JSLint and JSHint if you need to cover situations like this. But on the whole, it is usually possible to configure JSHint to cover all situations you are concerned about.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to clear badge number while preserving notification center in iOS8
this question is asked in other several links like How to clear badge number while preserving notification center
My question is a little more specific.
I would like to clear the badge number when opening app but i want the notificaiton in the notification center to not be cleared.
The suggested answer in the link above is to set the badge number to -1:
[[UIApplication sharedApplication] setApplicationIconBadgeNumber:-1]
This works with iOS8? I'm trying without any success.
Thank you
Davide
A:
As the doc says, the notification will be gone from notification area when you assign your badge count to 0. <0 will also cause to same effect.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
np.r_ does not work with 2 ranges or many slices
My dataframe shapes (199, 7). I want to select the columns which are column 0:4 and -2: (which is two last columns). I want to get the rows of the columns selected which the [final_data['unemployed']=='yes']. My columns are
['panicattacks', 'compulsivebehavior', 'depression', 'anxiety','tiredness', 'unemployed', 'cluster']
My first trial returns error ValueError: special directives must be the first entry.
final_data[np.r_[final_data.columns[0:4],final_data.columns[2]]][final_data['unemployed']=='yes']
My Second trial somehow it cannot work (perhaps it's because of the .iloc, please correct me if i'm wrong)
final_data.iloc[:,np.r_[0:4,-2:]][final_data['unemployed']=='yes']
Why don't they work? How should i do it?
A:
This is the kind of expression that produces your error message. I don't see it in your samples:
In [158]: np.r_[1:3, '-1']
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-158-0b702ddf8054> in <module>
----> 1 np.r_[1:3, '-1']
/usr/local/lib/python3.6/dist-packages/numpy/lib/index_tricks.py in __getitem__(self, key)
358 elif isinstance(item, str):
359 if k != 0:
--> 360 raise ValueError("special directives must be the "
361 "first entry.")
362 if item in ('r', 'c'):
ValueError: special directives must be the first entry.
testing your r_ in a simpler context:
In [151]: import pandas as pd
In [152]: df = pd.DataFrame(np.arange(21).reshape(3,7))
In [153]: df
Out[153]:
0 1 2 3 4 5 6
0 0 1 2 3 4 5 6
1 7 8 9 10 11 12 13
2 14 15 16 17 18 19 20
In [154]: np.r_[df.columns[0:4],df.columns[2]]
Out[154]: array([0, 1, 2, 3, 2])
In [155]: df[np.r_[df.columns[0:4],df.columns[2]]]
Out[155]:
0 1 2 3 2
0 0 1 2 3 2
1 7 8 9 10 9
2 14 15 16 17 16
and
In [150]: np.r_[0:4,-2:-1]
Out[150]: array([ 0, 1, 2, 3, -2])
In [156]: df.iloc[:,np.r_[0:4,-2:-1]]
...:
...:
Out[156]:
0 1 2 3 5
0 0 1 2 3 5
1 7 8 9 10 12
2 14 15 16 17 19
I'm not quite sure what 2nd range you want. Keep in mind that with r_, negative ranges are tricky, r_ does not know the size of df.columns.
edit
[154] works because my sample dataframe had numeric column headers. Change that to strings:
In [173]: df = pd.DataFrame(np.arange(21).reshape(3,7),columns=list('abcdefg'))
In [174]: df
Out[174]:
a b c d e f g
0 0 1 2 3 4 5 6
1 7 8 9 10 11 12 13
2 14 15 16 17 18 19 20
In [176]: df[np.r_[df.columns[0:4],df.columns[2]]]
....
ValueError: special directives must be the first entry.
It's the r_ that's raising the error:
In [177]: np.r_[df.columns[0:4],df.columns[2]]
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-177-c0b1d20ac1a7> in <module>
----> 1 np.r_[df.columns[0:4],df.columns[2]]
/usr/local/lib/python3.6/dist-packages/numpy/lib/index_tricks.py in __getitem__(self, key)
358 elif isinstance(item, str):
359 if k != 0:
--> 360 raise ValueError("special directives must be the "
361 "first entry.")
362 if item in ('r', 'c'):
ValueError: special directives must be the first entry.
the problem is the first argument, an array of strings:
In [178]: df.columns[0:4]
Out[178]: Index(['a', 'b', 'c', 'd'], dtype='object')
Looks like the simplest way around this is to use hstack (or just 'concatenate) instead ofr_. This list doesn't needr_'s` special handling of slices:
In [182]: np.hstack((df.columns[0:4],df.columns[2]))
Out[182]: array(['a', 'b', 'c', 'd', 'c'], dtype=object)
In [183]: df[np.hstack((df.columns[0:4],df.columns[2]))]
Out[183]:
a b c d c
0 0 1 2 3 2
1 7 8 9 10 9
2 14 15 16 17 16
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Ignoring a column when joined column has more than one value
I have a table, Orgs, that contains the following data:
ID Name AddressID
0 McDonalds 4
1 Starbucks 5
2 Burger King 7
I also have a table, Addresses, that contains the following data:
ID OrgID Address
3 0 123 Main St.
4 0 456 East Ave.
5 1 789 Young St.
6 2 5 Riverside Dr.
7 2 8 Lakeview Ave.
I need to create a select statement that selects the names of companies from Orgs table and their address. A company in the Orgs table can have 1 or more addresses. If the company only has one address, I don't want to return any address for that company. If the company has more than one address, I want to return the address where Orgs.AddressID = Addresses.ID
So my results should look like this:
ID Name Address
0 McDonalds 456 East Ave.
1 Starbucks
2 Burger King 8 Lakeview Ave.
I'm not sure how to do this. Thanks for your help!
A:
SELECT
O.ID, O.Name, A.Address
FROM
Orgs O
LEFT OUTER JOIN
(SELECT OrgID FROM Addresses GROUP BY OrgID HAVING COUNT(*) > 1) X ON O.ID = X.OrgID
LEFT OUTER JOIN
Addresses A ON X.OrgID = A.OrgID AND O.AddressID = A.ID
|
{
"pile_set_name": "StackExchange"
}
|
Q:
A remarkable musical ode
On his deathbed, the great blind composer Charles Triangle composed the following remarkable piece, but his penchant for puzzles has left critics in tears searching for a deeper meaning to a piece whose significance seems, upon listening, to lie not merely in the sound.
Do you have the ability to follow where his fingers wrote, and uncover the poetic words intimated here, that occupied the mind of this immortal composer as he recalled his youth?
Hint:
While you could not be expected to identify the meaning of each bar without some thought, I can assure you that a number of bars (e.g. the first, second, sixth, seventh, tenth, fourteenth, twenty-fourth, twenty-fifth, twenty-sixth, twenty-eighth, forty-eighth, forty-ninth, fifty-third and fifty-fourth) will yield their meaning at a glance once you get a feel for the composer's method, remembering all you have been told about him. Once you have interpreted each bar, you will be one step closer to recovering the composer's meaning.
Hint 2:
As it has now been pointed out by one particularly astute critic that the patterns formed by the outlines of each note or chord within a bar may be interpreted to deduce a letter with some level of certainty, I would prompt you to go one step further and realize the composer's infallible rule that leaves nothing to chance in the placement of each note. Bear in mind, of course, that at his advanced age the hills and valleys that mark the path of life had been transformed into one unending climb to glory!
Hint 3:
It seems that while a certain astute critic has grasped the meaning of the notes and chords within each bar (although a level of uncertainty still remains), the significance of their position on the stave remains as yet unelucidated. Bearing in mind that critic's tentative interpretation of each bar, examine more closely bars nineteen, thirty-seven, forty-two, and fifty-five, and see if you can learn something thence which might be more broadly applicable.
A:
Final answer: The secret to 'A Radiance Enduring' is:
A BRIGHT MIND!
TL;DR - There are several steps to solving this cipher:
1. Convert each bar to a letter of the alphabet through its similarity to a Braille symbol.
2. Notice that for each occurrence of the same Braille-bar letter in the cipher the first chord of notes in the bar is consistently offset from the last chord of notes in the previous bar by the same amount. Similarly, in any bar with two chords, the second chord is consistently offset from the first by the same amount. (NB For any given letter, the two offsets are not necessarily equal.)
3. Write out a table of the offsets for each letter of the alphabet, arranged in alphabetical order:
4. Create one long string of numbers by concatenating the offset values in alphabetical order:
042352032339729811860396860207325884826718038645
5. Decode the resulting string using a Base 26 cipher to get the message "A WHAT THOUGH THE RADIANCE WHICH WAS MIND".
6. Realise that the composer is quoting an ode by William Wordsworth here (which specifically concerns reassurance to others after one's death - topical to our composer's situation), and that the word which can be substituted for "WHAT THOUGH THE RADIANCE WHICH WAS" is BRIGHT...
...giving us the final answer: A BRIGHT MIND!
Now for the full explanation, reflecting my solving process... (Including an account of the various errors of judgement I made, and how I repeatedly made this whole thing unnecessarily hard for myself!)
The first thing to note upon considering this puzzle is that from the description:
Its composer, Charles Triangle, is blind. Automatically this should set us to thinking about BRAILLE.
With this in mind, looking at each bar we see that:
Each bar can indeed be interpreted as a specific Braille letter, if we treat each written note as an individual Braille dot. Importantly:
- Where a bar contains two separate notes or chords (which is how I shall refer to several notes played at the same time), these correspond to the two columns of dots in a Braille symbol;
- Where a bar contains just one note or chord, this implies that the right-hand column of the Braille symbol contains no dots, i.e. it is one of A, B, K or L, depending on how many notes are present;
- Where two notes in a chord are touching, the dots in the Braille symbol are adjacent, one directly on top of the other (like the left-hand column of a Braille G), whereas when they are separated by a tone, with clear space in between them, the Braille dots similarly appear at the top and bottom of their column, with a gap between them.
By following these rules, we can soon see that the first line...
would work out as...
A | Q | (MOU) | (CEI) | (CEI) | K | B | (PRV) | (MOU) | W | (NZ)
where unambiguous letters are indicated in bold, while ambiguities are presented in brackets. A little thought reveals that this can spell out 'A QUICK BROWN', which should instantly be recognisable to most regular puzzle solvers as the opening words of a famous pangram. Proceeding through the next two lines, we can resolve further ambiguities to continue and complete the pangram 'tribute act' (since it isn't quite a pangram here, as the lack of 'the' means it lacks T and H) - this serves as a confirmatory message that our approach is on the right track.
Seeing this through results in the first bar after the 'pangram' message being the one which is headed "Three Commands". This implies that the coded letters which follow this should provide us with three instructions to carry out to solve the puzzle.
Applying the same techniques to the rest of the coded message results in something of the form:
A | Q | U | I | C | K | B | R | O | W | N
F | O | X | J | U | M | P | S | O | V | E
R | A | L | A | Z | Y | D | O | G | (CEI) | (MOU)
(MOU) | (NZ) | (GT) | (FHS) | (FHS) | (CEI) | (FHS) | (GT) | (FHS) | (MOU) | (PRV)
(DJ) | (CEI) | (PRV) | A | L | (GT)
(CEI) | (PRV) | B | A | (FHS) | (FHS)
What can we make of this? Well, just by trying to form real (and potentially relevant) words among these letters, one potential interpretation which fits is:
COUNT SHIFTS ORDER ALTER BASS/BASH - where the last word could be one of two things in a music/cipher context. The following diagram shows my rough working in arriving at this possibility...
- All bars coloured green are unambiguous and have only one possible letter.
- All others are colour-coded to match other bars with the same Braille pattern, with my initial best-hypothesis prediction made bold and underlined in the letter suggestions above them.
At this point in my working the OP hinted that particular bars (boxed in blue here) might be useful in helping to pinpoint the identity of the letter in the final bar. Each of these corresponds to the letter 'S' in my projected message. The OP went on further to recommend considering the missing Braille dots also - this turned out to be a critical breakthrough in the puzzle that I might otherwise not have considered... Ignoring the missing second-column dots for A, B, L and K, I plotted these onto the same diagram:
It then became clear that the two columns/chords of Braille dots in bars which represented the same letter always had the same offset (or 'shift' - that word is important...), i.e. the difference in pitch between the highest notes of the two columns in that bar was always constant. For the final bar in the piece of music, the highest note of the first chord is a C and the highest of the second is a D one octave higher - a difference of 8 notes (C-D-E-F-G-A-B-C-D - count the hyphens here, not the letters). Since previous F's had a shift of only 3 notes, and H only 2, this final bar therefore had to represent an S, which always had a shift of 8 notes in a bar everywhere it was encoded.
In fact (and it took me an embarrassingly long time to realise this), every instance of a letter also has a consistent number of shifts before it, i.e. between the highest note of the last chord of the previous letter and the first chord of its own (for a bar representing an S, the first chord is always shifted by 5 from the last chord of the previous bar, for example). This means that each of the 26 letters of the alphabet can be represented by a specific pair of numbers, almost like a set of coordinates: (shift before bar, shift within bar).
Using this method also confirms that all of the other letters I had previously derived were correct, which finalises our instructions as:
COUNT SHIFTS ORDER ALTER BASS
This can best be split into: COUNT SHIFTS, ORDER, ALTER BASS. The question now is: How do we carry out these instructions?
1. COUNT SHIFTS - this is what we have already done. We have counted the note shifts that occur between two different bars and also those that occur within a bar. We have noticed that the shifts are consistently the same for each occurrence of the same letter.
2. ORDER - a sensible next step is to put them in a table. To that end, the shifts for each letter are as follows:
Conveniently (and this was confirmed by the OP to corroborate that things were moving in the right direction), in the construction of this table we have ordered the letters and shift-related numbers exactly how we are supposed to (i.e. alphabetically). What we now have is a sequence of pairs of numbers, where we have left the 'within letter' value blank if only one Braille column is required in the corresponding symbol.
3. ALTER BASS - to carry out this instruction, we have to note the use of a pun here. When the OP writes 'alter bass', what they intend is for us to 'alter the base' of a number in this puzzle! (In fact, this was something I had suggested in an earlier partial answer, but when push came to shove I had little success deriving this correctly and needed some very patient and persistent encouragement from the OP to point me in the right direction - more on that shortly...) What number can we change the base of? Well, why not concatenate our ordered pairs of shifts to form one long number:
042352032339729811860396860207325884826718038645
So what base do we convert this number to? In hindsight, the obvious answer when trying to convert numbers into letters is to decrypt this using base 26 (and in my defence, I did try this initially but ended up with gibberish that led me nowhere - it turned out this was because the online tool I used to decrypt it only permitted a certain number of digits in the number to be decoded and truncated my input! I recommend this tool for your decryption purposes...). Doing so provides a string of letters:
AWHATTHOUGHTHERADIANCEWHICHWASMIND
This is the message that has been encoded in the sheet music by Charles Triangle. But it needs some interpretation. Noticing the quote tag, we need to realise that:
Here, Charles Triangle is quoting a section from a William Wordsworth ode, Ode on Intimations of Immortality:
“What though the radiance which was once so bright
Be now for ever taken from my sight,
Though nothing can bring back the hour
Of splendour in the grass, of glory in the flower;
We will grieve not, rather find
Strength in what remains behind;
In the primal sympathy
Which having been must ever be;
In the soothing thoughts that spring
Out of human suffering;
In the faith that looks through death,
In years that bring the philosophic mind.”
(Note the use of 'intimated' and 'immortal' in the puzzle's original flavourtext both clue the title of this poem!)
If we therefore parse our encoded phrase as "A 'WHAT THOUGH THE RADIANCE WHICH WAS' MIND", we can infer that the central phrase here should be substituted by the word at the end of the first sentence in the Wordsworth poem: BRIGHT.
Altogether, this means that the secret to Charles Triangle's piece, 'A Radiance Enduring' is A BRIGHT MIND, likely suggesting the poem should be taken as comfort to others after his own death and implying that a bright mind will leave behind creations whose radiance will endure far longer than one lifetime... Deep words!
One final note about a part of the puzzle I did not use in my solving process:
Both Charles Triangle's name and the musical instruction 'echeggiante' were intended as subtle pointers to part of the solution. 'Echeggiante' is an Italian word meaning 'echoing' and the Greek capital letter 'delta' is shaped like a triangle. 'Echo', 'Delta' and 'Charlie' (a more familiar name for 'Charles') are keywords in the NATO Phonetic Alphabet and were intended by the OP as a little hint towards step 2 of the 'Three Commands', indicating that the Braille letter shifts once decoded should be arranged alphabetically. In fact, (OP's intention from comments) even the title could be seen to be cluing further codewords if you link 'Alpha' to 'Radiance' (alpha radiation) and 'Bravo' to 'Enduring' (bravo --> 'braving'), which then means the first 5 codewords all appear in alphabetical order...
Final remarks: This puzzle was nicely put together. The idea of encoding a message in a musical score was inspired, and doing so using Braille was a real novelty. The encoded commands should have been sufficient for me to solve the puzzle with some trial-and-error, although something inbuilt to help confirm when the second command was complete would have been very useful. I am glad I persisted with the solving process, as it is great to see this satisfying puzzle brought to its clever conclusion. Part of me wishes other puzzlers had joined the fray (I was really flailing about at some times!) but in everybody's defence it was a difficult puzzle to get into and required some real time investment. Rewarding though - it's a good feeling to bring this one home! :)
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How can I use a regular expression to detect a list or enumeration in PHP
I'm getting data from an XML feed. I can't control the feed nor it's content.
Sometimes, the data contains a list / enumeration. I want to parse this as a clean HTML unordered list.
The data I receive will be in a format like this:
<p>Some text in a paragraph tag</p>
<p>
- List item one <br>
- List-item-two<br>
-List item three <br>
- Listitem four<br>
</p>
<p>Another paragraph with text, and maybe even more paragraphs after this one!
They might even contain - dashes - - - or <br><br> breaks!</p>
Note that not every list item is neatly formatted. Some contain trailing paces between the <br>tag or between the dash and the text.
How can I postprocess this in PHP to get this result:
<p>Some text in a paragraph tag</p>
<p><ul>
<li>List item one</li>
<li>List-item-two</li>
<li>List item three</li>
<li>Listitem four</li>
</ul></p>
<p>Another paragraph with text, and maybe even more paragraphs after this one!
They might even contain - dashes - - - or <br><br> breaks!</p>
Can I do it with a regular expression? If so, what would it look like?
A:
Yes, I think regex are a good start point. Have a look to preg_replace
The regex could be something like this (not tested) :
$li = preg_replace('/^-([a-z]+)(<br>)?$/i', '<li>$1</li>', $entry);
Of course this is not working (you need support for whitespace and so on), but I think you get the idea.
A:
You can get started by replacing ^-\s*\b(.+)\b\s*<br>$ with <li>$1</li>. I'll leave the hard part of wrapping it all in a <ul/> up to you.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Can't install libmodman from source
I have this file libmodman-2.0.1.tar.gz, and want to install it, so I extracted it, navigated to the directory, then ./ configure and I get this :
~/Downloads/libmodman-2.0.1$ ./configure
bash: ./configure: No such file or directory
This is the content of the libmodman-2.0.1 directory:
/cmake/
/libmodman/
AUTHORS
CMakeLists.txt
COPYING
INSTALL
NEWS
In the file install is this:
cmake ./
make
make test
sudo make install
I tried cmake ./ in the terminal but i get this :
bash: ./cmake: Is a directory
How can I install this file?
A:
You should be trying to run cmake in ~/Downloads/libmodman-2.0.1/
Then once you have done that as the INSTALL file says, run make, make test and then sudo make install.
So that is:
cd ~/Downloads/libmodman-2.0.1/
cmake ./
make
make test
sudo make install
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Xcode Issue Adding Action
I'm working on a UI. When I want to add an action, I drag from the control to the code in the assistant editor. When the action is created, the code is inserted in to the middle of other functions, causing errors. This has been happening more and ore frequently. I even updated Xcode to the latest (7.3.1), to try and fix it. Here's an example of what happens:
override func viewDidLoad() {
super.viewDidLoad()
@IBAction func doneClicked(sender: AnyObject) {
}
//self.navigationItem.setHidesBackButton(true, animated: false)
}
You can see that the doneClicked Action is inserted in to the middle of viewDidLoad. The only way to fix it is to cut the code out of the middle of viewDidLoad, paste it lower, and then reconnect the action to the control.
It's getting really annoying. Is there any way to fix it or is there a better way to create the actions without doing it this way?
A:
I think this is an Xcode bug because I have had similar problem too. After selecting Assistant Editor, you can fix this by selecting your file from automatic menu. This is what fixed it for me. You can refer the screenshot below.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to find the mathematical expectation?
$190$ people take part in the marathon, and $124$ of them use the youth team of the university. The random value $\zeta$ is equal to the place of the best member of the university team. How to find the mathematical expectation of $\zeta$?
A:
Of the competitors $66$ are not members of the university team.
For $i=1,\dots,66$ let random variable $X_{i}$ take value $1$ if
person $i$ gets a higher ranking then all members of the university
team and let $X_{i}$ take value $0$ otherwise.
Then: $$\zeta=1+\sum_{i=1}^{66}X_{i}$$
Now apply linearity of expectation and symmetry.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Jade: mimick simple PHP function
I am currently trying to convert a PHP file into a Jade file to decrease server load*, but have run into some issues with converting the main PHP function - the reason for which that the page is not a HTML file in the first place - into Jade.
The function simplifies the listing of "items", and accepts multiple arguments in order to populate the different parts of the HTML code.
<?php
function item( $name, $category, $url, $color, $partner=NULL ) {
# convert åäö -> aao (lower- and uppercase)
$filename = preg_replace(array('/å/','/ä/','/ö/','/Å/','/Ä/','/Ö/', '/\s+/'), array('a','a','o','A','A','O', '-'), $name);
$filename = strtolower($filename);
?>
<div class="projekt__item item-<?php echo $filename ?>" style="background-color: <?php echo $color; ?>">
<div class="item__logo item__logo--<?php echo $filename ?>"></div>
<div class="item__figcaption">
<span class="item__figtext">
<?php echo $category; ?><br>
<?php if ($partner) : ?>
<br>
<span class="item__figtext--sub">
<strong>Partner: </strong> <?php echo $partner; ?>
</span>
<?php endif; ?>
</span>
</div>
<a href="<?php echo $url ?>" rel="nofollow" target="_blank"></a>
</div> <!-- /item -->
<?php } ?>
There are different components of the PHP code which I find difficult to replicate in Jade. These are:
Give one of the passable a variables a default value (e.g. partner=NULL)
Convert "åäö " into "aao_" for lower and uppercase letters
use the variables passed into the mixin in the code without syntax errors
I have set up a pen containing my so progress so far (which isn't very much - it just throws me a couple of errors which does not help me)
If anyone could assist me with this it would be greatly appreciated.
*I am aware of that there are other means to decrease server load, and that caching should make this redundant. However, it is also a matter of learning jade for future reference, and I would very much like to solve this problem instead of just leaving it behind :)
Update:
Thanks to @laggingreflex the problem has been solved. The final solution is seen below:
mixin item(name, category, url, color, partner)
- var filename = name.replace(/å/g,'a').replace(/ä/g,'a').replace(/ö/g,'o').replace(/Å/g,'A').replace(/Ä/g,'A').replace(/Ö/g,'O').replace(/\s+/g,'-')
- filename = filename.toLowerCase()
div(class='projekt__item item-#{filename}' style="background-color: #{color};")
div(class='item__logo item__logo--#{filename}')
div.item__figcaption
span.item__figtext
| #{category}
if (partner)
br
span.item__figtext--sub
strong Partner: #{partner}
a(href=url rel="nofollow" target="_blank")
A:
There's couple of mistakes in your Jade syntax
When defining a mixin method you can't assign default values to arguments.
item(name, category, url, color, partner=NULL) // error
item(name, category, url, color, partner)
btw if you don't pass an argument it's undefined by default.
At some places you're not actually interpolating the values of the variables, but simply outputting the variable names as plain strings
span.item__figtext
| category // will output the text "category"
| #{category} // will output the value stored in the variable category
Semi-colons are not a part of the Jade syntax (* unless you're doing inline JavaScript)
+item( "Intern...", ... ); // error
+item( "Intern...", ... )
Update with couple more suggestions
When you want to assign variable values to an attribute you don't want to put them in quotes
a(href="url" // will output <a href="url"
a(href=url // will output <a href="http://example.com"
When using a variable in a class name, you can't use the dot .class notation, so you want to define it as an attribute
div.item-filename // will output <div class="item-filename"
div.item-#{filename} // will result in error
div(class="item-#{filename}" // this is what you want
As for PHP's preg_replace, .replace is the JavaScript's equivalent, although it doesn't support arrays so you have to chain them, and you have to specify the /g regex modifier specifically.
Also to inline JavaScript code inside Jade you want to begin it with a hyphen -
- var filename = name.replace(/å/g,'a').replace(/ä/g,'a').…
So this is what your completed Jade should look like
mixin item(name, category, url, color, partner)
//- convert "åäö B C" -> "aao-b-c" (lower- and uppercase)
- var filename = name.replace(/å/g,'a').replace(/ä/g,'a').replace(/ö/g,'o').replace(/Å/g,'A').replace(/Ä/g,'A').replace(/Ö/g,'O').replace(/\s+/g,'-')
- filename = filename.toLowerCase()
div(class='projekt__item item-#{filename}' style="background-color: #{color};") #{filename}
div(class='item__logo item__logo--#{filename}')
div.item__figcaption
span.item__figtext
| #{category}
if (partner)
br
span.item__figtext--sub
strong Partner: #{partner}
a(href=url rel="nofollow" target="_blank")
+item( "Example Name 1 åäö", "Design & Utveckling", "http://www.example_url.com/", "#45c0ae", "Example Partner" )
+item( "Example Name 2", "Design & Utveckling", "http://www.example_url.com/", "#346b98" )
+item( "Example Name 3", "Design & Utveckling", "http://www.example_url.com/", "#8191b2", "Example Partner" )
+item( "Example Name 4", "Design & Utveckling", "http://www.example_url.com/", "#485230", "Example Partner" )
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is there any difference between {strlen($var) == 0} and {empty($var)}
considering that the variable only can be String fetched from an HTML Form (input-text, textarea).
A:
Yes, there is a difference between strlen($str)==0 and empty($str). empty returns true if the value is "0". See the PHP type comparison tables.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
where can I find the .cpp file in CGAL?
I download the source code of CGAL in Github, but I just find the .h file,no .cpp, where can I get it? cause there is only declaration of function in the class of .h, but i want to see the source code of the function.
Thanks.
A:
There are almost no .cpp files in CGAL. It is a libary just as Boost, that is it is header only. This means that what you call "the source code" is template code which is in the header files. Sometimes you have to dig a litte bit deeper, that is the code is in another header files that gets #included.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Haskell: ScopedTypeVariables needed in pattern matching type annotations
Why does this code require the ScopedTypeVariables extension?
{-# LANGUAGE ScopedTypeVariables #-}
char = case Just '3' of
Just (x :: Char) -> x
Nothing -> '?'
When I read the documentation on ScopedTypeVariables, it seems to mean unifying type variables in the function body with the parent function signature. This code snippet isn't unifying any type variables though!
Also what is the effect of loading ScopedTypeVariables without also loading ExplicitForAll? All the other usecases of ScopedTypeVariables seem to require ExplicitForAll to actually work. But in the above snippet, there's no ExplicitForAll.
A:
ScopedTypeVariables enables ExplicitForAll automatically For the sake of your sanity I would suggest always using ScopedTypeVariables when using any other type system extensions (except possibly the ones dealing only with classes/instances/contexts) and never using ExplicitForAll directly.
The reason ScopedTypeVariables is required for pattern variable signatures is just that such signatures are part of the extension. Among other uses, they give you a way to bring a type variable into scope. For example:
f (Just (x::a)) = bob
where
bob::[a]
bob = [x]
I do not know why the pattern signatures are part of ScopedTypeVariables, per se; most likely they were created for this purpose, and all the code was written in one go. Teasing them apart to make orthogonal extensions was almost certainly considered more trouble than it was worth.
Edit
Actually, there's a pretty good reason. With the exception of pattern bindings, a type variable in a pattern signature is generalized, bringing that variable into scope. So in the above example, you don't need to know if there is an a in the outer type environment. If you could enable pattern signatures without scoped type variables, then the variable could be generalized or not depending on whether scoped type variables were turned on or not. The same sort of confusion happens for ExplicitForAll without ScopedTypeVariables, which is why I'd like to kill that extension and make ScopedTypeVariables the default, or at least turn it on automatically with the extensions that currently enable ExplicitForAll.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to replace the contents of an element?
I use VueJS to set the content of elements via data defined in a Vue instance:
<p id="hello">
{{ message }}
</p>
How can I completely replace the content of such an element (discarding the previous content, in the case above {{ message }}), to turn the <p>into for instance
<p id="hello">
The replacement text
</p>
In jQuery I would have called $("#hello").html("the replacement text"); - what is the equivalent in VueJS?
A:
Vue is MVVM so you map data to the view. You can replace HTML with v-html, but your html would have to be stored in your vm and this isn't recommended:
HTML:
<div id="app">
<span v-html="message"></span>
<button v-on:click="newHtml">Change HTML</button>
</div>
Javascript:
new Vue({
el: "#app",
methods: {
newHtml() {
this.message = '<p style="color:red;">New Message</p>';
}
},
data: {
message: "<p>Message</p>"
}
});
Heres the JSFiddle: https://jsfiddle.net/e07tj1sa/
Really, with vue you should try to move away from thinking in jQuery, they are conceptually different. In vue the preferred method is to build up your app with reusable components not to directly affect the html in the DOM.
https://vuejs.org/guide/components.html#What-are-Components
|
{
"pile_set_name": "StackExchange"
}
|
Q:
snowflake: Dateadd only weekdays
is it possible to add only weekdays in a date function?
dateadd(day,10,business_date) ==> instead of returning next 10 days, is it possible to retirve next 10 weekdays ?
regards,
Sridar
A:
There are some semi complicated functions out there in other languages for this that could be converted, but without knowing more, I'd generally recommend the method of creating a calendar table.
In that table, you can label dates as weekdays and then join and filter with that table.
This also lets you extend to holidays with an additional IsHoliday flag
Then you can join to lists of dates with queries like this
SELECT DateColumnValue, RANK() OVER(ORDER BY DATEKEY) RNK
FROM DIMDATE
WHERE DateColumnValue >= CURRENT_DATE
AND isWeekday = 1
AND isHoliday = 0
QUALIFY RNK <= 10
|
{
"pile_set_name": "StackExchange"
}
|
Q:
TIKZ - changing one block into parallel multiple blocks
I have the following code:
\documentclass[crop,tikz]{standalone}
\usepackage{tikz}
\usepackage{textcomp}
\usetikzlibrary{shapes,arrows}
\usetikzlibrary{positioning}
\usetikzlibrary{arrows,
chains,
decorations.markings,
shadows, shapes.arrows,shapes}
\begin{document}
\begin{tikzpicture}
\begin{scope}[start chain = going below,
every node/.append style={on chain,fill opacity=0.8,draw,
join},every join/.style={thick,-latex},
cs/.style={minimum width=4.5cm,copy shadow={shadow scale=1, shadow xshift=0.5ex, shadow yshift=-0.5ex}}
]
\node[fill=white] (N1) {\begin{tabular}{p{1cm}cp{1cm}}
IOH\\
& \enspace\tiny $K\times K$\quad\quad \quad &
\end{tabular}};
\node[fill=orange] (N2) {\begin{tabular}{p{4cm}cp{1cm}}
COI\\
\qquad\enspace\tiny\quad\quad\quad\quad $K\times K$
\end{tabular}};
\node[fill=white] (N3) {\begin{tabular}{p{4cm}cp{4cm}}
\qquad
\end{tabular}};
\node[fill=white] (N4) {\begin{tabular}{p{1cm}cp{1cm}}
GOH &\\
& \tiny $K\times K$ \enspace\enspace&
\end{tabular}};
\end{scope}
\path (N1) -- (N2) coordinate[pos=0.5] (aux);
\path (N2) -- (N3) node[pos=0.5,right,font=\bfseries\itshape]{};
\path (N3) -- (N4) node[pos=0.5,right,font=\bfseries\itshape]{};
\end{tikzpicture}
\end{document}
which produces the following figure:
Now I want to change this code in order to get the new figure:
Note that above the character 'N' appears an underbrace.
A:
\documentclass[tikz, margin=3mm]{standalone}
\usetikzlibrary{arrows.meta,
chains,
decorations.pathreplacing,
calligraphy,% has to be after decorations.pathreplacings
}
\usepackage{textcomp}
\usepackage{array}
\begin{document}
\begin{tikzpicture}[
node distance = 5mm and 7mm,
start chain = going below,
box/.style = {draw, fill=#1, minimum size=2em},
box/.default = white,
every edge/.style = {draw, -Latex},
BC/.style = {decorate,
decoration={calligraphic brace, amplitude=5pt,
raise=1mm},
very thick, pen colour=#1
}
]
\begin{scope}[every node/.append style={on chain}]
\node (N1) [box]
{\begin{tabular}{p{12mm} >{\tiny}c p{12mm}}
IOH & & \\
& $K\times K$ &
\end{tabular}};
\node (N2) [box=orange]
{\begin{tabular}{p{12mm} >{\tiny}c p{12mm}}
COI & & \\
& $K\times K$ &
\end{tabular}};
\node (N3) [box, node font=\bfseries] {A};
\end{scope}
\node (N4) [box,below=11mm of N3]
{\begin{tabular}{p{12mm} >{\tiny}c p{12mm}}
GOH & & \\
& $K\times K$ &
\end{tabular}};
\node (N3L) [box, node font=\bfseries, left=of N3] {A};
\node (N3R) [box, node font=\bfseries,right=of N3] {A};
%
\path (N1) edge (N2)
(N2) edge (N3)
(N2) edge (N3L.north)
(N2) edge (N3R.north);
\draw[BC] (N3R.south east) -- node (aux) [below=2mm] {$N$} (N3L.south west);
\path[shorten >=1pt] (aux -| N3L) edge (N4)
(aux) edge (N4)
(aux -| N3R) edge (N4);
\draw[ultra thick, shorten <=1mm, shorten >=1mm, dotted]
(N3L) edge[-] (N3)
(N3R) edge[-] (N3);
\end{tikzpicture}
\end{document}
Note: from your MWE I remove all not used TikZ libraries and defined style and add arrows.meta (for arrows head), and decorations.pathreplacing and calligraphy for brace under nodes with text "A".
A:
This is a little variation on Zarko's excellent code.
Node's contents are defined as labels instead of tabulars. This way, node's size must be declared.
Positions are defined with positioning library and no chains are used.
Nodes in third row are declared with a matrix node.
All edges are drawn using Zarko's code adapted to new names for third row nodes.
\documentclass[tikz, margin=3mm]{standalone}
\usetikzlibrary{arrows.meta,
decorations.pathreplacing,
calligraphy,% had to be after lib. decorations.pathreplacings
matrix,
positioning
}
\usepackage{textcomp}
\begin{document}
\begin{tikzpicture}[
node distance = 5mm,
box/.style = {draw, fill=#1, minimum height=1cm, minimum width=4.5cm},
box/.default = white,
every edge/.style = {draw, -Latex},
BC/.style = {decorate,
decoration={calligraphic brace, amplitude=5pt,
raise=1mm},
very thick, pen colour=#1
}
]
\node (N1) [box, label={[anchor=north west]north west:IOH},
label={[anchor=south, font=\tiny]south:$K\times K$}]
{};
\node (N2) [box=orange, label={[anchor=north west]north west:COI},
label={[anchor=south, font=\tiny]south:$K\times K$},
below=of N1]
{};
\matrix (N3) [matrix of nodes, inner sep=0pt, nodes={minimum size=1cm, draw, anchor=center, node font=\bfseries, node contents=A}, nodes in empty cells, column sep=.5cm,
below=of N2]{&&\\};
\node (N4) [box, label={[anchor=north west]north west:GOH},
label={[anchor=south, font=\tiny]south:$K\times K$},
below=1cm of N3]
{};
\path (N1) edge (N2)
(N2) edge (N3-1-1.north)
(N2) edge (N3-1-2)
(N2) edge (N3-1-3.north);
\draw[BC] (N3.south east) -- node (aux) [below=2mm] {$N$} (N3.south west);
\path[shorten >=1pt] (aux -| N3-1-1) edge (N4)
(aux) edge (N4)
(aux -| N3-1-3) edge (N4);
\draw[ultra thick, shorten <=1mm, shorten >=1mm, dotted]
(N3-1-1) edge[-] (N3-1-2)
(N3-1-2) edge[-] (N3-1-3);
\end{tikzpicture}
\end{document}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Vectorized dot product in pandas?
I have two dataframes, df1 is indexed by date and contains some numeric values val1, val2 for products/entries A,B,...:
Date entry val1 val2
2017-04-12 A 1 10
2017-04-12 B 2 10
2017-04-12 C 3 10
2017-04-13 A 1 20
2017-04-13 B 2 20
2017-04-13 D 3 20
df2 has coefficients for each value for each date:
2017-04-12 2017-04-13
val1 4 6
val2 5 7
Is there a nice vectorized way of getting the dot product of values in df1 with coefficients in df2? The output would look like:
Date entry result
2017-04-12 A 54
2017-04-12 B 58
2017-04-12 C 62
2017-04-13 A 146
2017-04-13 B 152
2017-04-13 D 158
I know that looping over dates works.
A:
Use DataFrame.mul with MultiIndex in df1 with transpose df2, then sum per rows and convert MultiIndex Series by Series.reset_index to DataFrame:
df = (df1.set_index(['Date','entry'])
.mul(df2.T, level=0)
.sum(axis=1)
.reset_index(name='result'))
print (df)
Date entry result
0 2017-04-12 A 54
1 2017-04-12 B 58
2 2017-04-12 C 62
3 2017-04-13 A 146
4 2017-04-13 B 152
5 2017-04-13 D 158
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Should backend IDs be public or not on a REST API?
Based on what this guy says: http://toddfredrich.com/ids-in-rest-api.html
Let assume he is right about using UUID to identify the api resources. Then I run into troubles trying to implementing it that way, this is:
class FooEntity {
final String id = null; //auto-generated by my backend (mongodb), not shared
final UUID uid = UUID.randomUUID(); //the resource id
}
(Between client and server, are sent and received DTOs, not data base entities.)
The problem now is that id is not useful as I'm not using it anymore. The client makes the requests with uid so why do I bother to handle 2 id's ?
Then we get back to the same issue of the beginning. If I set UUID as the primary key (_id) then I'm exposing the backend id to the public.
Beside of that, there is the efficiency topic. I've read that indexing by ObjectId is much more efficient than UUID.
A:
I'm exposing the backend id to the public
What other means do you have to identify your entities when they're returned through a request? That's perfectly legitimate and safer than SSN or similar identifiers. That's what Todd is talking about - making identifications technology and entity neutral and he's right.
Efficiency topic
You can keep both identifiers if ObjectId is really much more efficient. Theoretically it's always better to use UUIDs for identifiers than database auto incrementers.
A:
No, as far as the database goes, nothing about the internal structure is exposed to the outside API. ID's have no intelligence. They're not even unique in the real world. ID: 47 is everywhere. There are entities you have access to and possibly can manipulate the data, but whether this database stores everything in one table or ten, uses incremental ID as PK and relates to an FK, you'll never know.
If you can GetUserAccountByID(12345) is just asking for someone to try GetUserAccountByID(12346). Eventhough it won't work due to other security measures, don't even try and don't try to social hack the company by asking for information on Account: 12346. Unless you call the DBA and are willing to wait 2 weeks for a reponse;)
So create the GUIDs however you see fit or any other natural key like a phone number or email address. Put a unique constraint on the field in the table to avoid some obscure copy and paste attempt in some merge data attempt.
This is not redundant. The two fields serve different purposes.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Trying to get a Canon LBP6030W to work
I was wondering if anyone has had success getting a Canon imageClass LBP6030W to work with linux. I have tried using the printer manager to add the printer after I plug it in, but there doesn't seem to be a driver available either through the built in list of drivers for Ubuntu or online. Trying the generic and the LBP5975 drivers have gotten me a setup where when I send jobs to the printer nothing happens.
Suggestions?
A:
You need to have CUPS installed... which is already installed (if i am not wrong)
if not installed
sudo apt-get install cups
install the drivers for the respective printer from the vendors website (use ".deb" package for you arch ie. i386/amd64 (32/64 bit arch))
try in your browser
localhost:631
try this link for drivers
or you may also try this for more help with linux printing.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Should the damage from an unarmed strike be reduced by Heavy Armor Master?
The Heavy Armor Master feat (PH p.167) grants the following benefit:
While you are wearing heavy armor, bludgeoning. piercing, and slashing damage that you take from non-magical weapons is reduced by 3.
Recent errata to the Player's Handbook changes the definition of an unarmed strike:
Unarmed strike doesn’t belong on the Weapons table.
Instead of using a weapon to make a melee weapon attack, you can use an unarmed strike: a punch, kick, head-butt, or similar forceful blow (none of which count as weapons). On a hit, an unarmed strike deals bludgeoning damage [...]
Should the damage from an unarmed strike be reduced by Heavy Armor Master?
A:
Yes, Heavy Armor Master should reduce damage from unarmed strikes.
Back in June, Jeremy Crawford stated that the intended Errata which will be released eventually with the next Monster Manual will clarify that all instances (for example) of "bludgeoning damage from non-magical weapons" to instead read "resistance to nonmagical bludgeoning damage" and for lycantrhopes, that would read "nonmagical weapon attacks.", instead of "nonmagical weapons"
See here for the full conversation.
A:
No, not anymore.
The changes in the errata remove Unarmed Strike from the weapons table and explicitly outlines punches, etc. as not weapons.
Heavy Armor Master only reduces damage from weapons, not all sources of nonmagical bludgeoning, piercing, and slashing damage.
As an example, Heavy Armor Master does not reduce the nonmagical bludgeoning damage taken from falling more than 10 feet.
Is this intended?
I doubt it, but Unarmed Strikes are still weapon attacks, and thus qualify for divine favor and the monk feature Stunning Strike. Heavy Armor Master could easily include Unarmed Strike by changing the wording from "nonmagical weapons" to "nonmagical weapon attacks".
|
{
"pile_set_name": "StackExchange"
}
|
Q:
HTML anchor treating all paths as Relative
I cannot get my website to treat links as absolute paths.
here is my website:
caseyshancock.com
Look under the contact me and note how the two links are being treated as relative addresses.
Instead of
http://www.linkedin.com/pub/casey-hancock/51/98/880
it tries to make it add my domain name before the link
A:
You're using smart quotes in your HTML. Use regular ' or "".
<p><a href=“mailto:[email protected]”>[email protected]</a></p>
<a href=“http://www.linkedin.com/pub/casey-hancock/51/98/880”>linkedin</a>
should be:
<p><a href="mailto:[email protected]">[email protected]</a></p>
<a href="http://www.linkedin.com/pub/casey-hancock/51/98/880">linkedin</a>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Program is stopping even though conditions haven't been met
It prints "that wasn't an option" When I press Y or N even though I have it
I have it set as != (not equal to)
if c.upper() != 'N' or "Y":
print ("that wasn't an option")
if c.upper() != 'N' or "Y":
sys.exit()
Whole code
import sys
c = input('do you like piza? Y or N:')
if c.upper() != 'N' or "Y": print ("that wasn't an option")
if c.upper() != 'N' or "Y": sys.exit()
if c.upper() == 'Y':
print ('Me To')
if c.upper() == 'N': print ("really i thought everybody likes piza.")
if c.upper() == 'N': sys.exit()
name = input("sooo what's ur name? ")
print("that a pretty good name i guess ")`
A:
You had made a mistake by just putting the or statement without specifying a condition. Instead of just oring a value, you have to specify another condition. Here I have provided an example how it should be.
import sys
c = input('do you like piza? Y or N:')
if c.upper() != 'N' or c.upper() != "Y":
print ("that wasn't an option")
if c.upper() != 'N' or c.upper() != "Y":
sys.exit()
if c.upper() == 'Y':
print ('Me To')
if c.upper() == 'N':
print ("really i thought everybody likes piza.")
if c.upper() == 'N':
sys.exit()
name = input("sooo what's ur name? ")
print("that a pretty good name i guess ")
You could also slightly refactor the code, by combining the last 2 ifs like so:
if c.upper() == 'N':
print("really i thought everybody likes piza.")
sys.exit()
and also the 1st two ifs like so:
if c.upper() != 'N' or c.upper() != "Y":
print ("that wasn't an option")
sys.ext()
EDIT
The or should be replaced with an and, otherwise that check makes no sense.
Credit to khelwood for pointing it out.
Hope this helps!
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How do I say 'On second thought' in Spanish?
How do I say "On second thought" in Spanish?
Pensándolo bien, ¡no vamos al cine!
Are there any alternative for this?
A:
The expression «pensándolo bien» is a very good translation and pretty common. Also «pensándolo mejor».
Some alternatives:
reconsiderándolo
por otro lado (sería mejor)
ahora que lo pienso (suggested by Alexis and SysDragon)
repensándolo (suggested by Diego Andrés)
si lo pienso (bien/mejor) (suggested by Diego Andrés)
al pensarlo mejor (suggested by vartec)
(I'll keep posting if I remember more)
A:
Pensándolo bien, the one that you gave, is the most common in my opinion, but you could also use:
Pensándolo mejor, ...
Ahora que lo pienso, ...
Mejor pensado, ...
And some sentences that should be used with context, but can have similar meaning:
Ya que lo dices, ...
Ahora que caigo, ...
|
{
"pile_set_name": "StackExchange"
}
|
Q:
.style.color is working but still throws an error
I am trying to make HTML paragraph element appear by changing their color. The line where I style the specific elements (multiple elements, its inside a for loop) is throwing an error. It works fine but after that line I cant do anything since the error stops it.
This is the code (its stopped by the chrome tools). U can see that the element is defined, and if I hover over it displays the exact one I need.
The error message says the element is undefined but I am absolutely sure it is, I have no clue what to do.
const letterIndex = findIndexOfLetter(word, letter.innerHTML);
for (w = 0; w <= letterIndex.length; w++) {
var theLetter = wordLetters[letterIndex[w]]
theLetter.style.color = "azure";
}
A:
When iterating over an array (or an array-like collection, not important here) with the for loop, you go
for (let i = 0; i < collection.length; i++) { //...
and not
for (let i = 0; i <= collection.length; i++) { //...
With the <= stop condition, the last iteration is outside the array.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How the ports really work?
I'm bit confused with the concepts of ports. Lets say that I opened inbound port for 3306 (mysql) to my-ip. So my-ip will make a connection to 3306. But I wonder in-turn how mysql speaks to my ip?
Say for example lets my application from my-ip is querying mysql, how mysql sends the data back to my my-ip machine? I mean it again uses port?
Thanks in advance.
A:
A TCP session is defined by 4 bits of information: a pair of IP addresses, and a pair of ports.
When you open a connection in firefox to stackoverflow.com, your operating system allocates an unused port to that connection. Usually something fairly high, say 32012. stackoverflow.com is listening on port 80, so no choice there.
The TCP session is therefore you:32012 - stackoverflow.com:80. This connection is used bi-directionally. So your HTTP requests are sent to stackoverflow.com:80, and the HTTP responses are sent to you:32012.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Pre-filling request headers using classes derived from requests.Session in Python
I'm trying to refactor some code in which many HTTP requests are made using the requests module. Many of these requests have (partially) the same headers, so I would like to 'pre-fill' these using Session objects.
However, I'm having difficulty making multiple inheritance work in this context. Here is what I've tried:
import requests, time
requestbin_URL = 'http://requestb.in/1nsaz9y1' # For testing only; remains usable for 48 hours
auth_token = 'asdlfjkwoieur182932385' # Fake authorization token
class AuthorizedSession(requests.Session):
def __init__(self, auth_token):
super(AuthorizedSession, self).__init__()
self.auth_token = auth_token
self.headers.update({'Authorization': 'token=' + self.auth_token})
class JSONSession(requests.Session):
def __init__(self):
super(JSONSession, self).__init__()
self.headers.update({'content-type': 'application/json'})
class AuthorizedJSONSession(AuthorizedSession, JSONSession):
def __init__(self, auth_token):
AuthorizedSession.__init__(self, auth_token=auth_token)
JSONSession.__init__(self)
""" These two commented-out requests work as expected """
# with JSONSession() as s:
# response = s.post(requestbin_URL, data={"ts" : time.time()})
# with AuthorizedSession(auth_token=auth_token) as s:
# response = s.post(requestbin_URL, data={"key1" : "value1"})
""" This one doesn't """
with AuthorizedJSONSession(auth_token=auth_token) as s:
response = s.post(requestbin_URL, data={"tag" : "some_tag_name"})
If I inspect the result of the last request at http://requestb.in/1nsaz9y1?inspect, I see the following:
It seems like the Content-Type field is correctly set to application/json; however, I don't see an Authorization header with the fake authentication token. How can I combine the AuthorizedSession and JSONSession classes to see both?
A:
I've found that the request works if I define AuthorizedJSONSession more simply as follows:
class AuthorizedJSONSession(AuthorizedSession, JSONSession):
def __init__(self, auth_token):
super(AuthorizedJSONSession, self).__init__(auth_token=auth_token)
The resulting request now has updated both the Authorization and Content-Type headers:
I've understood that when a class inherits from multiple classes which in turn inherit from the same base class, then Python is 'smart enough' to simply use super to initialize.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Adding a new NOT NULL field to a table causes an error
When attempting to add a new column to a table within an update hook, the error Null value not allowed: 1138 Invalid use of NULL value occurred, the definition was changed to allow NULL, and the value for existing rows was set to NULL.
function MYMODULE_update_8101() {
Drupal::database()->schema()->addField(
'MYMODULE_table',
'created',
[
'type' => 'int',
'unsigned' => TRUE,
'not null' => TRUE,
]
);
}
When adding the column to the database with an SQL query, using the NOT NULL restriction causes the field to have a default value of 0, and no error happens.
How can the error be fixed, and the proper schema set?
A:
If the field spec sets 'not null' => TRUE but does not define a default value, the column is created allowing null values and later altered to disallow them (see the mysql driver Schema::addField(), and the $fixnull variable). The second query attempting add the restriction fails, causing the error.
To fix the error, either
An 'initial' value needs to be added to the spec provided to addField()
Drupal::database()->schema()->addField(
'MYMODULE_table',
'created',
[
'type' => 'int',
'unsigned' => TRUE,
'not null' => TRUE,
'initial' => 0,
]
)
Or a 'default' value needs to be added to the spec provided to addField().
When providing a default value, the spec in hook_schema() should also be changed to match.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to append a new list to an existing CSV file?
I already have a CSV file created from a list using CSV writer. I want to append another list created through a for loop columnwise to a CSV file.
The first code to create a CSV file is as follows:
with open("output.csv", "wb") as f:
writer = csv.writer(f)
for row in zip(master_lst):
writer.writerow(row)
I created the CSV file using the list master_lst and the output is as follows:
read
ACACCUGGGCUCUCCGGGUACC
ACGGCUACCUUCACUGCCACCC
AGGCAGUGUGGUUAGCUGGUUG
Then I create another list (ind_lst) through a for loop and the contents of the list has to be appended columnwise to the CSV file created in the previous step. I used the following code:
with open("output.csv", "ab") as f:
writer = csv.writer(f)
for row in zip(ind_lst):
writer.writerow(row)
The output I obtained is as follows:
read
ACACCUGGGCUCUCCGGGUACC
ACGGCUACCUUCACUGCCACCC
AGGCAGUGUGGUUAGCUGGUUG
sample1
3
3
1
sample2
4
4
1
However I need the output columnwise as follows:
read sample1 sample2
ACACCUGGGCUCUCCGGGUACC 3 4
ACGGCUACCUUCACUGCCACCC 3 4
AGGCAGUGUGGUUAGCUGGUUG 1 1
I checked for solutions but I can find only solutions for appending row wise, but I need to append it columnwise: append new row to old csv file python
I used writer.writerows instead of writer.writerow but I get this error:
_csv.Error: sequence expected
The output is as follow:
read
ACACCUGGGCUCUCCGGGUACC
ACGGCUACCUUCACUGCCACCC
AGGCAGUGUGGUUAGCUGGUUG
s a m p l e 1
As you can see, it prints the first element of the list in each cell and terminates thereafter with an error. I am a beginner in python, so if anyone could help solve this issue that would be awesome.
EDIT:
The master_lst is created using the following code:
infile= open(sys.argv[1], "r")
lines = infile.readlines()[1:]
master_lst = ["read"]
for line in lines:
line= line.strip().split(',')
fourth_field = line [3]
master_lst.append(fourth_field)
the ind_lst is created using the following code:
for file in files:
ind_lst = []
if file.endswith('.fa'):
first = file.split(".")
first_field = first [0]
ind_lst.append(first_field)
fasta= open(file)
individual_dict= {}
for line in fasta:
line= line.strip()
if line == '':
continue
if line.startswith('>'):
header = line.lstrip('>')
individual_dict[header]= ''
else:
individual_dict[header] += line
for i in master_lst[1:]:
a = 0
if key in individual_dict.keys():
a = individual_dict[key]
else:
a = 0
ind_lst.append(a)
A:
You're actually trying to append several columns to the existing file, even if the data for these new columns is all stored in a single list. It might be better to arrange the data in the ind_lst differently. but since you haven't showed how that's done, the code below works with the format in your question.
Since modifying CSV files is tricky—since they're really just text file—it would be much easier to simply create a new file with the merged data, and then rename that file to match the original after deleting the original (you've now been warned).
import csv
from itertools import izip # Python 2
import os
import tempfile
master_lst = [
'read',
'ACACCUGGGCUCUCCGGGUACC',
'ACGGCUACCUUCACUGCCACCC',
'AGGCAGUGUGGUUAGCUGGUUG'
]
ind_lst = [
'sample1',
'3',
'3',
'1',
'sample2',
'4',
'4',
'1'
]
csv_filename = 'output.csv'
def grouper(n, iterable):
's -> (s0,s1,...sn-1), (sn,sn+1,...s2n-1), (s2n,s2n+1,...s3n-1), ...'
return izip(*[iter(iterable)]*n)
# first create file to update
with open(csv_filename, 'wb') as f:
writer = csv.writer(f)
writer.writerows(((row,) for row in master_lst))
# Rearrange ind_lst so it's a list of pairs of values.
# The number of resulting pairs should be equal to length of the master_lst.
# Result for example data: [('sample1', 'sample2'), ('3', '4'), ('3', '4'), ('1', '1')]
new_cols = (zip(*grouper(len(master_lst), ind_lst)))
assert len(new_cols) == len(master_lst)
with open(csv_filename, 'rb') as fin, tempfile.NamedTemporaryFile('r+b') as temp_file:
reader = csv.reader(fin)
writer = csv.writer(temp_file)
nc = iter(new_cols)
for row in reader:
row.extend(next(nc)) # add new columns to each row
writer.writerow(row)
else: # for loop completed, replace original file with temp file
fin.close()
os.remove(csv_filename)
temp_file.flush() # flush the internal file buffer
os.fsync(temp_file.fileno()) # force writing of all data in temp file to disk
os.rename(temp_file.name, csv_filename)
print('done')
Contents of file after creation followed by update:
read,sample1,sample2
ACACCUGGGCUCUCCGGGUACC,3,4
ACGGCUACCUUCACUGCCACCC,3,4
AGGCAGUGUGGUUAGCUGGUUG,1,1
|
{
"pile_set_name": "StackExchange"
}
|
Q:
how to check whether user is admin
I want to block functionality of my client application if user is not admin. But the problem is how to check in program that login and password was admin's?
A:
I'm assuming two things:
You want to know whether the logged-in user is an administrator or not in the SQL Server context.
There is some role which all "administrator" users belong to, such as for example db_owner. (Sorry, I don't have SQL Server in front of me and don't remember all the role names off the top of my head, so I'm pulling one that is close enough out of the MSDN documentation page example.)
If these assumptions hold, then it looks like IS_MEMBER will work.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Letter codes in molecular term symbols
I'm trying to find an explanation for the letter codes (X, A, B, C, etc) when you get a term symbol like this
$$X\,{}^3{\Sigma}^-_g$$
Can anyone point me to some literature that explains these letter codes?
A:
Quoting from Hollas, Modern Spectroscopy, 4th ed. (p 236):
There is a convention, which is commonly but not always used, for labelling electronic states. The ground state is labelled $X$ and higher states of the same multiplicity are labelled $A, B, C\ldots$ in order of increasing energy. States with multiplicity different from that of the ground state are labelled $a, b, c \ldots$ in order of increasing energy.
As such, for the oxygen molecule, where the lowest three states are ${}^3{\Sigma}_g^-$, ${}^1{\Delta}$ and ${}^1{\Sigma}^+_g$ (in increasing order of energy), the triplet ground state would be labelled $X$ and the next two states $a$ and $b$ respectively.
A word of caution: it seems that this convention is not always obeyed. On the next page, Hollas writes (for $\ce{I2}$, where the ground state is a singlet)
The transition $B\,{}^3{\Sigma}_{0_u^+} - X\,{}^1{\Sigma}_g^+$ involves the $\Omega = 0$ component of the $B$ state [...] The labelling of the $B\,{}^3{\Sigma}_{0_u^+}$ state follows general usage rather than convention, which would label it $b\,{}^3{\Sigma}_{0_u^+}$.
Wikipedia also adds, although without a citation:
In polyatomic molecules (but not in diatomics) it is customary to add a tilde (e.g. $\tilde{X}$, $\tilde{a}$) to these empirical labels to prevent possible confusion with symmetry labels based on group representations.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How come Q deferreds are so slow on Node.js?
So I created this simple test server in Node.js
Whenever I do a direct response, I get 2200 requests/second (fast!).
When I only wrap a simple Q deferred around it, it drops to 580 requests/second (4 times slower!). Can anybody explain that huge difference?
// Requires
var server = require('http');
var q = require('q');
// Start server
var http = require('http');
http.createServer(function(request, response) {
// Comment out either of two below sections
// Without deferred
// 2200 reqs/second
response.writeHead(200, {"Content-Type": "text/html"});
response.write("test");
response.end();
// Q deferred
// 580 reqs/second
var deferred = q.defer();
deferred.promise.then(function() {
response.writeHead(200, {"Content-Type": "text/html"});
response.write("test");
response.end();
});
deferred.resolve();
}).listen(1234);
A:
Edit: Performance has improved greatly since stacktraces have been turned off since Q 0.9.6. (They can be re-enabled for debugging with Q.longStackSupport = true;)
Original: Q promises are slow because they capture a full stack trace on every promise to help with debugging. This is very slow. You can turn them off with Q.longStackJumpLimit = 0; (which is likely to be the default in the next version). We found a roughly 30x speedup by turning them off. You can find out more here https://github.com/kriskowal/q#long-stack-traces
There's also been some performance work on the nextTick implementation, but I think the above is the main reason.
A:
The reasons I'm aware of, are:
Q uses Object.freeze, and that slows V8 by magnitudes
Many nextTick calls (already mentioned in comments). This however shouldn't be that much of the case with latest Node.js version (v0.10), as there nextTick overhead is minimal.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is there a mathematical function giving an approximation to human breathing over time?
I want to animate something with the same frequency that a human breathes in and out, something like the Apple Macbook power light when it is in sleep mode.
So basically an ease in ease out function over time, but that has a curve that approximates the way a human breathes.
Edit: I just need the algorithm as a function of time, don't care which language.
Pretty close graph of what I need on this page:
http://www.normalbreathing.com/d/etco2-capnography.php
A:
Just a search on google images:
If you like the first one, a lot of functions could look like that. For example, get partly cos(t)^3 and partly flat. Of course, with coefficients to adjust it.
A:
Your curves look like they could be approximated by exponentials. The first could be $1-\exp (\lambda_1 t)$ for $0<t<3$, $\exp (\lambda_2 (t-3)t)$ for $3<t<5$ then repeat. Choose the $\lambda$s to make it look right. For the hyperventilation, change the range of $t$s appropriately. The easiest way to set the $\lambda$s is to look for the $\frac{1}{e}$ point, where the signal is about $0.37$ of the final value and set $\lambda$ to the inverse of that time.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
CSS animation doesn't trigger after onclick event
I have css blocks that must go away from the page when they gain the .gone class.
I register a click event in Javascript, in the event handler I add the .gone class to the clicked element.
The bullet should go away to the left, or to the right, but it just disappears.
Here is the HTML code:
<div id="firstPage">
<div id="bullets">
<div data-href="#projects" class="top left">Projects</div>
<div data-href="#skills" class="top right">Skills</div>
<div data-href="#experiences" class="bottom left">Experiences</div>
<div data-href="#contact" class="bottom right">Contact</div>
</div>
</div>
The javascript code:
var bullets = [];
function openPage(e) {
e.preventDefault();
this.classList.add('gone');
}
var tmpBullets = document.querySelectorAll('#bullets div');
for(var i = 0 ; i < tmpBullets.length ; i++) {
tmpBullets[i].addEventListener('click', openPage, true);
bullets.push(tmpBullets[i]);
}
The CSS code:
html {
font-family: QuattrocentoSans;
overflow: hidden;
}
#firstPage {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-image: url('../images/noise.png');
}
#firstPage h1 {
display: block;
margin: auto;
text-align: center;
margin-top: 100px;
font-family: Pacifico;
font-size: 50px;
color: #fff;
text-shadow: 0 0 3px #000;
}
#bullets {
display: block;
width: 320px;
margin: auto;
}
#bullets div {
position: absolute;
display: inline-block;
width: 150px;
height: 150px;
line-height: 150px;
border-radius: 50%;
background-color: #333;
text-align: center;
color: white;
text-decoration: none;
margin-top: 10px;
margin-right: 5px;
margin-left: 5px;
text-shadow: 0 0 3px #999;
font-size: 1.2rem;
transition: box-shadow 500ms, left 1000ms, right 1000ms;
}
#bullets div.top {
top: 100px;
}
#bullets div.bottom {
top: 270px;
}
#bullets div.left {
left: calc(50% - 165px);
}
#bullets div.right {
right: calc(50% - 165px);
}
#bullets div:hover {
box-shadow: 0 0 10px #555;
transition: box-shadow 500ms;
}
#bullets div.left.gone {
left: -160px;
}
#bullets div.right.gone {
right: -160px;
}
See jsfiddle for live demo : http://jsfiddle.net/8u9j6n6x/
Thanks for your help
A:
You need to add the transition to the .gone class not the #bullets div
#bullets div.gone {
transition: box-shadow 500ms, left 1000ms, right 1000ms;
}
updated fiddle http://jsfiddle.net/8u9j6n6x/1/
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to get the name of the nearest interactive ancestor shell from a script?
I know that one can use the $- contains i or not or check if $PS1 is empty to tell if a shell is interactive.
However, those solutions only work for the current shell.
I have a bash script trying to find the immediate parent shell that is interactive.
For example:
interactive shell: zsh
bash script 1 which executes bash script 2
bash script 2 contains the mechanism to find out the immediate interactive shell
So when we execute bash script 1 under our interactive shell zsh, we expects an output of zsh.
I cannot figure out how I can do it, when the script is running in the sub-shell.
Note
I want the script to be executed, not sourced.
Clarify
I have a bash script trying to find the first ancestor shell that is
interactive.
By first ancestor, I meant that the first interactive shell we encounter during the bottom-up process-chain scanning process.
For example, in the case of: zsh(first interactive shell) -> bash(second interactive shell) -> bash(batch shell for script 1) -> bash(batch shell for script 2), we want to output bash(the second interactive shell).
A:
This is a really weird requirement. Why would you care what interactive shell invoked your script, or invoked some other program that isn't an interactive shell which in turn invoked your script? This has a very strong smell of a XY problem.
IF you really need to know, you can try to figure it out, but I don't think there's a fully reliable method, just one that works in typical cases.
Starting from $PPID, trace your script's ancestor processes (ps -o ppid= -p $ancestor_pid) until you either find the one that you're looking for, or one that indicates you've gone too far.
A simple strategy is to look for a process in a different process group (ps -o pgid= -p $ancestor_pid). Under normal circumstances, if your script was invoked by (a script that was invoked by) an interactive shell, that process you've reached is a shell with job control, which ran your script('s parent script) in a separate process group.
Here are some examples of things that can go wrong with this strategy:
One of the processes on that chain is already dead.
Your script was not invoked through an interactive shell, but through a cron job, from an X11 program, etc.
You may or may not want check that this process's standard input, standard output and standard error (e.g. with lsof, or via /proc if you don't need portability beyond Linux) are the same terminal as your script. It depends how you want to handle cases such as
bash$ xterm -e your_script
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to implement a search system in a database for an iphone application
This is pretty wide question, but I'm hoping to get a push in the right direction (technologies and methodology).
Ok, I have an iphone app (which I am developing) that works with a web service (c#) through http requests. The web service connects to the underlying database, extracts the necessary data depending on the request and feeds it back to the application.
Now, I need to implement a search system in the app. The user searches for some words, and I need to provide the most relevant results. The search must be performed on different tables in the database. Each table can be searched in a number of columns. For example, when searching through the people table I need to search in the first name, lastname, company, and other fields. Other tables have other important columns.
I have so many questions that I don't even know where to start.
How do I make my sql queries to make the search, but still be fast enough. Do I need to make some extra tables with indexed content somehow?
How should I add relevance factor to the results so I can ultimately filter only the most relevant results? For example, if an user searches for Smith, maybe there is a person named Smith or even a Company. They should be displayed before any other content that can have smith in the description.
I know the question is a little vague/wide but I can explain more if somebody desires.
Thank you
A:
In the end I have decided to use Lucene. It's a wonderful piece of technology and even if I had some doubts in the beginning, after reading 3/4 of the book called "Lucene in Action" it was clear to me that it had everything I needed (and much more).
I know it's not a fully-functional searching system (with all the elements needed), but merely a library handling the core of a search system. It will need some work to integrate it with my application/webservice/database. I will let you know how it goes :)
Thanks for your input!
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Scrape text under br tag under class
I've been trying to scrape addresses in this page:
https://www.yellowpages.my/listing/results.php?keyword=boutique&where=selangor&screen=2
It is difficult for me to get the address under the br tag:enter image description here
What i've tried
addresses = page_content.select(' .cbp-vm-address')[0]
address = addresses.get_text(' ', strip=True)
address = list(addresses.stripped_strings)
which doesn't give me everything under the class
i've also tried:
for br in page_content.findAll('br'):
item = br.next_siblings
item = list(item)
print(item)
which gives me results as below (snippet):
[<br/>, <br/>, <br/>, <br/>, <br/>, '\n', <a href="/solutions">DigitalSolutions</a>, '\n', <a href="https://www.yellowpages.my/deal/results.php">Deals</a>, '\n', <a class="sign-up" href="https://www.yellowpages.my/profile/add.php">Sign Up</a>, '\n', <a class="sign-up" href="https://www.yellowpages.my/profile/login.php">Login</a>, '\n']
How do i get the address? relatively new to scraping here.
A:
Thanks Ohad for the quick response. I just want to slightly improve the answer below:
import requests
from bs4 import BeautifulSoup
raw = requests.get("https://www.yellowpages.my/listing/results.php?keyword=boutique&where=selangor&screen=2")
# raw = raw.replace("</br>", "") # try not to do this
soup = BeautifulSoup(raw.content, "lxml") # instead, change "html.parser" to "lxml"
addresses = [x.text.strip().split("\r\n")[-1].strip() for x in soup.find_all("div", class_="cbp-vm-address")]
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Comparing arrays with identical values
$array1 = array(1,1,1);
$array2= array(1,5,9,2,2,1);
I need to compare $array2 with $array1 and if $array2 has the same identical values should return true, otherwise should be returning false. In this case it should return false
A:
Well thanks @Shadowfax for trying help but i made the solution, so i post here if anyone have the same problem..
function compareArrayValues($array1,$array2){
$result= array();
for ($a=0; $a< count($array1); $a++){
$array2=array_values($array2);
for ($b=0; $b < count($array2) ; $b++) {
if ($array1[$a] == $array2[$b]){
array_push($result,$array1[$a]);
unset($array2[$b]);
break;
}
}
}
if ($result == $array1){
return true;
}else{
return false;
}
}
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Two If Statements with a Logical Operator
I have the following code:
fhand=open('mbox-short.txt')
count=0
for line in fhand:
words=line.split()
print(words)
if len(words)==0: continue
if words[0]!='From': continue
print(words[2])
This code prints a valid output (I am trying to get the day of a sent email from a mbox.txt file). When I try to combine the two "if" statements as follows:
if words[0]!='From' and len(words)==0: continue
I get this error:
['From', '[email protected]', 'Sat', 'Jan', '5', '09:14:16', '2008']
Sat
['Return-Path:', '<[email protected]>']
Traceback (most recent call last):
File "untitled.py", line 7, in <module>
print(words[2])
IndexError: list index out of range
I see that the issue occurs at the Return-Path line but why is it taken into consideration? And shouldn't the combined if statement have the same output as the two separated if statements?
A:
The issue you're having is that you flipped the order of your tests. You're now testing the length after attempting to check what the first value is:
if words[0]!='From' and len(words)==0: continue
Python checks conditions from left to right, so it will first check if words[0]!='From' and then test len(words)==0, however if words is empty then the first test tries to access a non existent index and creates your error.
You need to use this order instead and use the or operator as deceze pointed out, because you only care if one of these is True, not both.
if len(words)==0 or words[0]!='From': continue
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Breakpoint right before page refresh?
I'm debugging some 3rd-party minified Javascript that somewhere is triggering a browser page refresh. However, I can't figure out what part of the code is causing the refresh.
Is there a way to put a breakpoint in Chrome that will be hit just before a page refresh so I can inspect the call stack to see what caused it?
A:
Try this:
Open your Chrome Dev Tools
Navigate to the "Sources" tab
On the right panel, expand "Event Listener Breakpoints"
Expand the "Load" tree
Check the beforeunload and unload options
See if that helps; screenshot below.
Edit: Alternately, if that doesn't work, you can use Chrome to search all loaded scripts for the code that might be responsible. There's apparently a lot of ways to refresh the page with JavaScript but they mostly have a few common strings like "navigator", "location", "reload", "window".
Finally, if there's a link to the same page you are on, it's possible some JS is triggering a click on it-- unlikely, but worth exploring if nothing else has worked thus far...
(Please excuse the formatting as I'm on mobile...)
NOTE: It seems occasionally, for reasons I don't yet fully understand, this solution fails to actually cause the debugger to pause; in this situation, I found that thorn̈'s answer to this question did the trick for me.
A:
In Firefox (not Chrome, it's important) Developer Tools, go to the console, enter addEventListener('beforeunload',()=>{debugger}), and execute your code. After the debugger stops at the debugger statement, look at the call stack. You'll see what triggered the event. Chrome didn't have it there.
At least, this worked for me.
A:
In the devtool, network pane, toggle the "Preserve log", carefully check the initiator column.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Huawei bootloader: what is "FB Lock" and how to unlock it?
I was playing around with my spare Huawei phone trying to bypass the security without wiping data and came along this article: https://blog.salvationdata.com/2018/09/07/case-study-mobile-forensics-a-practical-solution-to-unlock-huawei-bootloader/
In step 3, you should "temporarily disable FB lock". What does this mean and how do I unlock it using fastboot? I suppose, that I cannot do that using standard fastboot oem unlock command, but I couldn't find anything else in the fastboot documentation.
EDIT: Result of fastboot help command as requested:
https://pastebin.com/2rhr1PTT
platform-tools$ ./fastboot help
usage: fastboot [OPTION...] COMMAND...
flashing:
update ZIP Flash all partitions from an update.zip package.
flashall Flash all partitions from $ANDROID_PRODUCT_OUT.
On A/B devices, flashed slot is set as active.
Secondary images may be flashed to inactive slot.
flash PARTITION [FILENAME] Flash given partition, using the image from
$ANDROID_PRODUCT_OUT if no filename is given.
basics:
devices [-l] List devices in bootloader (-l: with device paths).
getvar NAME Display given bootloader variable.
reboot [bootloader] Reboot device.
locking/unlocking:
flashing lock|unlock Lock/unlock partitions for flashing
flashing lock_critical|unlock_critical
Lock/unlock 'critical' bootloader partitions.
flashing get_unlock_ability
Check whether unlocking is allowed (1) or not(0).
advanced:
erase PARTITION Erase a flash partition.
format[:FS_TYPE[:SIZE]] PARTITION
Format a flash partition.
set_active SLOT Set the active slot.
oem [COMMAND...] Execute OEM-specific command.
boot image:
boot KERNEL [RAMDISK [SECOND]]
Download and boot kernel from RAM.
flash:raw PARTITION KERNEL [RAMDISK [SECOND]]
Create boot image and flash it.
--cmdline CMDLINE Override kernel command line.
--base ADDRESS Set kernel base address (default: 0x10000000).
--kernel-offset Set kernel offset (default: 0x00008000).
--ramdisk-offset Set ramdisk offset (default: 0x01000000).
--tags-offset Set tags offset (default: 0x00000100).
--page-size BYTES Set flash page size (default: 2048).
--header-version VERSION Set boot image header version.
--os-version MAJOR[.MINOR[.PATCH]]
Set boot image OS version (default: 0.0.0).
--os-patch-level YYYY-MM-DD
Set boot image OS security patch level.
Android Things:
stage IN_FILE Sends given file to stage for the next command.
get_staged OUT_FILE Writes data staged by the last command to a file.
options:
-w Wipe userdata.
-s SERIAL Specify a USB device.
-s tcp|udp:HOST[:PORT] Specify a network device.
-S SIZE[K|M|G] Break into sparse files no larger than SIZE.
--slot SLOT Use SLOT; 'all' for both slots, 'other' for
non-current slot (default: current active slot).
--set-active[=SLOT] Sets the active slot before rebooting.
--skip-secondary Don't flash secondary slots in flashall/update.
--skip-reboot Don't reboot device after flashing.
--disable-verity Sets disable-verity when flashing vbmeta.
--disable-verification Sets disable-verification when flashing vbmeta.
--wipe-and-use-fbe Enable file-based encryption, wiping userdata.
--unbuffered Don't buffer input or output.
--verbose, -v Verbose output.
--version Display version.
--help, -h Show this message.
A:
There are two types of bootloader locks in Huawei devices: FB Lock and USER Lock.
USER Lock restricts the standard partitions like system, data, recovery, kernel etc, but not the critical bootloader-partitions which I don't remember the names of. (So you can't edit them even if you perform a USER Unlock) The USER Lock is what requires the bootloader unlock code to unlock. Also, there are some hidden hardware commands which are used for serious debugging like JTAG, that cannot be accessed with a USER Unlock.
FB Lock is used for protecting these restricted functions. A FB Unlock works as a key for all of Fastboot. (So if you perform a FB Unlock then you can unlock everything USER Unlock does, and the other restricted stuff) FB Lock is intended to be used by Huawei personnel for repairing. It is NOT supposed to be unlocked by users, but it is possible anyway, as I discovered after quite some research, but it doesn't work on very new firmware versions like EMUI 8.2 or July/August Security patch. It has been used for years by paid software for performing FRP Unlock, full system restoring, and it can even be used for obtaining a bootloader code for USER Unlock. A FB Unlock is usually temporary.
The method of FB Unlock has been kept behind cover for quite some time now, but I saw recently that it has been leaked on XDA. You can check it out here. That guide also covers a method for extracting the NVME partition for a permanent FB Unlock. If you don't want a permanent FB Unlock, but would like just a normal USER Unlock, you can skip doing steps after 3, but instead when you boot into TWRP, you can use:
su -c "grep -m1 -aoE 'WVLOCK.{14}[0-9]{16}' /dev/block/mmcblk0p7 |grep -aoE '[0-9]{16}'"
That will output the bootloader unlock code which you can use for standard USER Unlock. Good Luck!
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How do I load classes using the ctools plugin class loader?
Perhaps, the question should be how do I implement ctools plugins using classes to extend different types of an object? I can't find a simple explanation.
A:
mymodule.module:
<?php
/**
* Implements hook_ctools_plugin_api().
*/
function mymodule_ctools_plugin_api() {
list($module, $api) = func_get_args();
if ($module == 'mymodule' && ($api == 'plugins')) {
return array('version' => 1.0);
}
}
/**
* Implements hook_ctools_plugin_type().
*/
function mymodule_ctools_plugin_type() {
return array(
'plugin_type' => array(
'classes' => array('handler'),
),
);
}
/**
* Implements hook_ctools_plugin_directory().
*/
function mymodule_ctools_plugin_directory($owner, $plugin_type) {
if ($owner == 'mymodule') {
return "plugins/$plugin_type";
}
}
plugins/plugin_type/example.inc:
<?php
$plugin = array(
'title' => t('Example'),
'handler' => array(
'class' => 'ExamplePlugin',
),
);
plugins/plugin_type/ExamplePlugin.class.inc:
<?php
class ExamplePlugin {
function __construct($plugin){
}
}
Anywhere:
<?php
// Get all available plugins
$plugins = ctools_get_plugins('mymodule', 'plugin_type');
// Load a specific plugin
ctools_include('plugins');
$plugin = ctools_get_plugins('mymodule', 'plugin_type', 'example');
$class_name = ctools_plugin_get_class($plugin, 'handler');
$example = new ExamplePlugin($plugin);
|
{
"pile_set_name": "StackExchange"
}
|
Q:
When to call SetProcessWorkingSetSize? (Convincing the memory manager to release the memory)
In a previous post ( My program never releases the memory back. Why? ) I show that FastMM can cache (read as hold for itself) pretty large amounts of memory. If your application just loaded a large data set in RAM, after releasing the data, you will see that impressive amounts of RAM are not released back to the memory pool.
I looked around and it seems that calling the SetProcessWorkingSetSize API function will "flush" the cache to disk. However, I cannot decide when to call this function. I wanted to call it at the end of the OnClick event on the button that is performing the RAM intensive operation. However, some people are saying that this may cause AV.
If anybody used this function successfully, please let me (us) know.
Many thanks.
Edit:
1. After releasing the data set, the program still takes large amounts of RAM. After calling SetProcessWorkingSetSize the size returns to few MB. Some argue that nothing was released back. I agree. But the memory foot print is now small AND it is NOT increasing back after using the program normally (for example when performing normal operation that does not involves loading large data sets). Unfortunately, there is no way to demonstrate that the memory swapped to disk is ever loaded back into memory, but I think it is not.
2. I have already demonstrated (I hope) this is not a memory leak:
My program never releases the memory back. Why?
How to convince the memory manager to release unused memory
A:
If SetProcessWorkingSetSize would solve your problem, then your problem is not that FastMM is keeping hold of memory. Since this function will just trim the workingset of your application by writing the memory in RAM to the page file. Nothing is released back to Windows.
In fact you only have made accessing the memory again slower, since it now has to be read from disc. This method has the same effect as minimising your application. Then Windows presumes you are not going to use the application again soon and also writes the workingset in RAM to the pagefile. Windows does a good job of deciding when to write RAM to the pagefile and tries to keep the most used memory in RAM as long as it can. It will make the workinset size smaller (write to pagefile) when there is little RAM left. I would not mess with it just to give the illusion that you program is using less memory while in fact it is using just as much as before, only now it is slower to access. Memory that is accessed again will be loaded into RAM again and make the workinset size grow again. Touching less memory keeps the workingset size smaller.
So no, this will not help you forcing FastMM to release the memory. If your goal is for your application to use less memory you should look elsewhere. Look for leaks, look for heap fragmentations look for optimisations and if you think FastMM is keeping you from doing so you should try to find facts to support it. If your goal is to keep your workinset size small you could try to keep your memory access local. Maybe FastMM or another memory manager could help you with it, but it is a very different problem compared to using to much memory. And maybe this function does help you solve the problem you are having, but I would use it with care and certainly not use it just to keep the illusion that your program has a low memory usage.
A:
I agree with Lars Truijens 100%, if you don't than you can check the FasttMM memory usage via FasttMM calls GetMemoryManagerState and GetMemoryManagerUsageSummary before and after calling API SetProcessWorkingSetSize.
A:
Are you sure there is a problem? Working sets might only decrease when there really is a memory shortage.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
PhoneGap Build Code of wakeuptimer plugin doesn't work
Hi I am working on project that use plugin wakeup timer the issue is that I get from SuccessCallback (this is the first argument of wakeup) "wakeup unhandled type"
I use the github's plugin https://github.com/wnyc/cordova-plugin-wakeuptimer
my index.html Where I must modify JS to make it works?
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<!--<meta name="viewport" ... /> -->
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script type="text/javascript" charset="utf-8">
function init() {
document.addEventListener("deviceready", onDeviceReady, false);
}
function onDeviceReady() {
myDevice = document.getElementById('deviceProperties');
myDevice.innerHTML = window.wakeuptimer.wakeup(function(result) {
if (result.type==='wakeup') {
alert('wakeup alarm detected--' + result.extra);
} else if(result.type==='set'){
alert('wakeup alarm set--' + result);
} else {
alert('wakeup unhandled type (' + result.type + ')');
}
}, function() {
alert('Error!');
}, {alarms : [{type : 'onetime',
time : { hour : 15, minute : 00 },
extra : { message : 'json containing app-specific information to be posted when alarm triggers' },
message : 'Alarm has expired!'}]
}
);
}
</script>
</head>
<body>
<h1>Dane z alarmu</h1>
<button type="button" id="deviceProperties" onclick="init()">Ustaw alarm</button>
</body>
</html>
A:
Version Requirements
This plugin is meant to work with Cordova 3.5.0+.
I use version 1 of PGB so this quote is an answer
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is there an easy way to selecting multiple criteria in vba?
I want to check if a cell is equal to some elements, like the example below.
If Range("A1") = "Element1" Or Range("A1") = "Element2" Or Range("A1") = "Element3" Or Range("A1") = "Element4" Or Range("A1") = "Element5" Then
'Do the code
End if
I think this way is a little confusion to read, especially because the real code that I'm making will have 35 elements.
I know that in MySql can use the command IN like the example below.
subject IN ('Cookery','Chemistry','Literature')
Is there something like that in vba?
A:
A Case switch is probably best-suited for this:
Select Case Range("A1").Value
Case "Element1", "Element2", "Element3", "Element4", "Element5"
'Do stuff
Case Else
'Do other stuff, or do nothing at all
End Select
Note that the above is case-sensitive. If you have mixed-case and don't care about capitalization, convert to a single case using the LCASE or UCASE function:
Select Case LCase(Range("A1").Value))
Case "element1","element2","element3","element4","element5"
Alternatively, you can use the filter function on a vector array:
Const Elements As String = "element1,element2,element3,element4,element5"
Dim val$, myArray
myArray = Split(Elements, ",")
val = "element3"
If UBound(Filter(myArray, val)) >= 0 Then
'the value is in the array
MsgBox True
Else
'the value is not in the array
MsgBox False
End If
There are some quirks with the Filter function though, and I think it is not always 100% reliable since it will return partial matches.
Or you can use the Match function against an array:
If Not IsError(Application.Match(val, myArray, False)) Then
'value exist in the list
Else
'value does not exist in the list
End If
|
{
"pile_set_name": "StackExchange"
}
|
Q:
NSData & NSURL - url with space having problem
I have following code in my application.
NSData *data=[NSData dataWithContentsOfURL:[NSURL URLWithString:pathOfThumbNail]];
pathOfThumbNail has following path
http://70.84.58.40/projects/igolf/TipThumb/GOLF 58B.jpg
When I open above path in safari browser - path is changed automatically & image is successfully displayed.
http://70.84.58.40/projects/igolf/TipThumb/GOLF%2058B.jpg
But in iPhone, due to space in path, image isn't loaded in nsdata.
A:
Use: stringByAddingPercentEscapesUsingEncoding:
Returns a representation of the receiver using a given encoding to determine the percent escapes necessary to convert the receiver into a legal URL string.
-(NSString *)stringByAddingPercentEscapesUsingEncoding:(NSStringEncoding)encoding
A representation of the receiver using encoding to determine the percent escapes necessary to convert the receiver into a legal URL string. Returns nil if encoding cannot encode a particular character
Added per request by @rule
NSString* urlText = @"70.84.58.40/projects/igolf/TipThumb/GOLF 58B.jpg";
NSString* urlTextEscaped = [urlText stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString: urlTextEscaped];
NSLog(@"urlText: '%@'", urlText);
NSLog(@"urlTextEscaped: '%@'", urlTextEscaped);
NSLog(@"url: '%@'", url);
NSLog output:
urlText: '70.84.58.40/projects/igolf/TipThumb/GOLF 58B.jpg'
urlTextEscaped: '70.84.58.40/projects/igolf/TipThumb/GOLF%2058B.jpg'
url: '70.84.58.40/projects/igolf/TipThumb/GOLF%2058B.jpg'
A:
A swift 3.0 approach (stringByAddingPercentEscapesUsingEncoding and stringByAddingPercentEncodingWithAllowedCharacters seems now deprecated):
let urlString ="your/url/".addingPercentEncoding( withAllowedCharacters: .urlQueryAllowed)
A:
stringByAddingPercentEscapesUsingEncoding has been deprecated in iOS 9.0, it is recommended you use stringByAddingPercentEncodingWithAllowedCharacters instead.
Here's the Objective-C code for > iOS 9.0
NSString* urlText = @"70.84.58.40/projects/igolf/TipThumb/GOLF 58B.jpg";
NSString* urlTextEscaped = [urlText stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
NSURL *url = [NSURL URLWithString: urlTextEscaped];
NSLog(@"urlText: '%@'", urlText);
NSLog(@"urlTextEscaped: '%@'", urlTextEscaped);
NSLog(@"url: '%@'", url);
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Cover text() node of existing node from new node - XSLT
I'm doing html to xml transformation. In html I have table like this,
<doc>
<ol>
<li>
<p>List<span style="color: rgb(255,0,255);">The scope of this project is to:</span></p>
<ol>
<li>nested list1</li>
<li>nested <span style="color: rgb(255,0,255);">The scope of this project is to:</span> list1</li>
<li>nested list1</li>
<li>nested list1</li>
<li>nested list1</li>
</ol>
</li>
<li>
<p>List<span style="color: rgb(255,0,255);">The scope of this project is to:</span></p>
</li>
<li>
<p>List<span style="color: rgb(255,0,255);">The scope of this project is to:</span></p>
</li>
</ol>
Here I need to transform html elements names to certain xml elements name and should cover the text content by <para> element.
SO my output should be,
<doc>
<oli>
<listitem><para>List<style type="color: rgb(255,0,255);">The scope of this project is to:</style></para>
<oli>
<listitem><para>nested list1</para></listitem>
<listitem><para>nested <style type="color: rgb(255,0,255);">The scope of this project is to:</style> list1</para></listitem>
<listitem><para>nested list1</para></listitem>
<listitem><para>nested list1</para></listitem>
<listitem><para>nested list1</para></listitem>
</oli>
</listitem>
<listitem><para>
List<style type="color: rgb(255,0,255);">The scope of this project is to:</style>
</para></listitem>
<listitem><para>
List<style type="color: rgb(255,0,255);">The scope of this project is to:</style>
</para></listitem>
</oli>
</doc>
I have written following xsl to transform html to xml,
<xsl:template match="ol">
<oli>
<xsl:apply-templates/>
</oli>
</xsl:template>
<xsl:template match="li">
<listitem>
<para>
<xsl:apply-templates/>
</para>
</listitem>
</xsl:template>
<xsl:template match="span">
<style type="{@style}">
<xsl:apply-templates/>
</style>
</xsl:template>
<xsl:template match="p">
<para>
<xsl:apply-templates/>
</para>
</xsl:template>
<xsl:template match="li/p">
<xsl:apply-templates/>
</xsl:template>
The problem I have is when ul contain nested list, li text that has contain nested list is not correctly covered with <para> element.
in above example currunt output that I'm getting for nested list is follwos,
<listitem><para>
List<style type="color: rgb(255,0,255);">The scope of this project is to:</style>
<oli>
<listitem><para>nested list1</para></listitem>
<listitem><para>nested <style type="color: rgb(255,0,255);">The scope of this project is to:</style> list1</para></listitem>
<listitem><para>nested list1</para></listitem>
<listitem><para>nested list1</para></listitem>
<listitem><para>nested list1</para></listitem>
</oli>
</para></listitem>
so simply, instead of
<listitem><para>
List<style type="color: rgb(255,0,255);">The scope of this project is to:</style>
<oli>
........
</oli>
</para>
</listitem>
I need,
<listitem><para>
List<style type="color: rgb(255,0,255);">The scope of this project is to:</style>
</para>
<oli>
........
</oli>
</listitem>
I tried to cover text() content of li element by <para> but then <span> elements are not coming to the output.
Can anyone suggest a method how can I do this..
A:
I would simply change the template:
<xsl:template match="li/p">
<xsl:apply-templates/>
</xsl:template>
to:
<xsl:template match="li[p]">
<listitem>
<xsl:apply-templates/>
</listitem>
</xsl:template>
This template will match an <li> that contains a <p>. In this case, you don't have to add some <para>. For the <li>s that contain some <p>, the other template will match, and it does output the desired <para>.
Alternatively, you can also do something like this:
discard the template <xsl:template match="li/p">
modify the template <xsl:template match="li"> like follows:
<xsl:template match="li">
<xsl:choose>
<xsl:when test="p">
<listitem>
<xsl:apply-templates/>
</listitem>
</xsl:when>
<xsl:otherwise>
<listitem>
<para>
<xsl:apply-templates/>
</para>
</listitem>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is there a way in R to group by 'runs'?
Say I have:
df<-data.frame(group=c(1, 1, 1, 1, 2, 2, 2, 2),
date=c("2000-01-01", "2000-01-02", "2000-01-04", "2000-01-05", "2000-01-09", "2000-01-10", "2000-01-11", "2000-01-13"),
want_group=c(1, 1, 2, 2, 3,3,3,4))
I want to create a want_group variable that groups by date, group, and whether they were "daily". So for example I want to create unique id's for within group 1 for the 1st and 2nd, and then a new unique id for the 4th and 5th, and then similarly for group 2 for the 9th, 10th, and 11th.
group date want_group
1 1 2000-01-01 1
2 1 2000-01-02 1
3 1 2000-01-04 2
4 1 2000-01-05 2
5 2 2000-01-09 3
6 2 2000-01-10 3
7 2 2000-01-11 3
8 2 2000-01-13 4
Thanks,
A:
We can use diff and cumsum to calculate the runs. This increments everytime the difference in date is more than 1.
df$new <- cumsum(c(TRUE, diff(as.Date(df$date)) > 1))
df
# group date want_group new
#1 1 2000-01-01 1 1
#2 1 2000-01-02 1 1
#3 1 2000-01-04 2 2
#4 1 2000-01-05 2 2
#5 2 2000-01-09 3 3
#6 2 2000-01-10 3 3
#7 2 2000-01-11 3 3
#8 2 2000-01-13 4 4
We add TRUE in the beginning since diff returns output of length 1 less than the original vector.
To handle this by group we can do
library(dplyr)
df %>%
mutate(date = as.Date(date)) %>%
group_by(group) %>%
mutate(new = c(TRUE, diff(date) > 1)) %>%
ungroup() %>%
mutate(new = cumsum(new))
|
{
"pile_set_name": "StackExchange"
}
|
Q:
hardisk or network bottleneck?
Im trying to determine which hardware causing the bottleneck of the server, the server is mainly used for serving video files on a heavy traffic site.
i have dstat output look like below (will get up to 500+ for send part on peak hour):
interface output as below showing max speed is 4000Mb/s:
below is mrtg for daily showing 500Mbyets max speed:
The hardisk info using: smartctl -a /dev/sda
HDD info:
Vendor: DELL
Product: PERC H710P
Revision: 3.13
User Capacity: 1,999,307,276,288 bytes [1.99 TB]
Logical block size: 512 bytes
Logical Unit id: 0x6b82a720d22304002116d6c01027fc4d
Serial number: 004dfc2710c0d61621000423d220a782
Device type: disk
Local Time is: Mon Sep 11 09:06:33 2017 CST
Device does not support SMART
Error Counter logging not supported
Device does not support Self Test logging
how do i know which one is causing the bottleneck? using pure-ftp i always get listing directory failed, once i disable the nginx, i immediately able to list the directory. Now im not sure which is causing the bottleneck problem, either the max hdd data read or the network bandwidth, please help me so that i can decide to add a new hdd or add bandwidth.
A:
Based on provided information, I guess the problem is in the network speed Your peak at ~500 MB is the same as maximum throughput of your bonded network interface (4000 Mb).
The information about the disk says that it's Dell RAID controller. So real disks are hidden and the disk controller gives you virtual drive based on some type of RAID array. We use HPE hardware so I can't give you any command for DELL array which would give you more information. However I believe you can google it easily or someone please attach it as comment.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is there a way to determine the current boot phase in Powershell?
I have a need to ensure that a Powershell script which may be executed during an early portion of the Windows boot phase waits until the Winlogon Init or Post Boot phase to continue executing. Is there a way to determine the current boot phase in Powershell/.NET? P/Invoke is acceptable if necessary.
A:
Not really, the problem is that the complete boot process is asynchronous.
You might determine that the logon screen is shown as Mathias suggested by checking the winlogon.exe or even if at least one user is logged on by e.g. checking userinit.exe has been started:
Register-WmiEvent -Query SELECT * FROM Win32_ProcessStartTrace WHERE ProcessName='userinit.exe'" -Action {...}
But even that doesn't automatically imply that e.g. the network is up and running, that the internet or the domain can be reached. This is because since windows 7, Microsoft has fast user logon enabled by default (see also: Understand the Effect of Fast Logon Optimization and Fast Startup on Group Policy).
This basically means that in of lot of cases the user is already logged on (using cached credentials) prior the network connection is made...
So if you script depends on e.g. a domain, you will need to create an event to capture a network change:
Register-ObjectEvent ([System.Net.NetworkInformation.NetworkChange]) 'NetworkAddressChanged' -Action {...}
And than ping to domain to confirm that the domain is really available...
Conclusion
Instead of trying to define the "current boot phase", you will need to define the dependencies of your cmdlet and check them (or build specific events) accordingly.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to solve the differential equation $e^{(y^{'}-x)}y^{'}+1=0$
How to solve this differential equation
$e^{(y^{'}-x)}y^{'}+1=0;y(0)=0;y(1)=\frac{1}{2}$.
I am finding it very difficult to solve .Is there any specific way available for this?
A:
$$e^{y'-x}y'+1=0$$
$$y'e^{y'}=-e^x$$
The condition $y(0)=0$ implies $y'e^{y'}=-1$ which is impossible for $y'$ real.
So there is no real solution if the condition $y(0)=0$ is required.
The condition $y(1)=\frac{1}{2}$ implies $y'e^{y'}=-e$ which is impossible for $y'$ real.
Again, there is no real solution if the condition $y(1)=\frac{1}{2}$ is required.
Analytical solving, thanks to the Lambert W fonction $W(X)e^{W(X)}=X$ :
$$y'=W(-e^x)$$
$X=-e^x$ hense $dx=-e^x dX$ then $dx=\frac{dX}{X}$
$$y=\int W(-e^x)dx +C=-\int \frac{W(X)}{X}dX+C=\frac{1}{2}W(X)\left(W(X)+2\right)+C$$
$$y=\frac{1}{2}W(-e^x)\left(W(-e^x)+2\right)+C$$
$W(-e^x)$ is real only if $x\leq -1$
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Appcode vs Intellij?
I cannot seem to find the plugin for appcode in intellij. I've read online that intellij encapsulates all functionality in the other ideas through plugins. However I cannot seem to find the one for appcode? Thanks in advance.
A:
There isn't one. AppCode runs only on a Mac because it depends on a Mac-only toolchain, and uses a different project format (XCode projects instead of IntelliJ's own format). Because of that, it's not possible to release it as a plugin for IntelliJ IDEA.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Adding a electrical outlet in a closet for wireless router
I want to move my wifi router to a central location in my home. The only ethernet jack is all the way at one end of my house. However I have a hall closet that is centered in the house and would be a perfect location but there is not an outlet in there. On the other side of the closet is the kitchen with an outlet. Can I run wire from that outlet through the attic and back down through the top plate of one of the other walls of the closet. I plan on putting the router fairly high in the closet (about one and half feet from the ceiling) on a shelf and have the outlet right next to it. I have the tools to do the work just not sure if it would be legal.
A:
I don't think it's legal to power an outlet that's not in the kitchen off of one of the 2 required kitchen branch circuits (i.e. counter outlets). I think it would be OK to tap off of the un-switched side of a light circuit for the kitchen.
Since you have access through the attic, is there another general purpose branch circuit (that is non-kitchen) that you can tap into for the closet outlet?
There may be exceptions to the "kitchen branch circuit" restriction in the code that I'm not aware of that would allow you to do what you want.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is the top-down approach to universe-juggling mathematical consistent?
Here's an idea I've been sitting on for awhile. I guess it's time to expose it to the flaming sword of expert opinion. Not sure if it will remain standing by the end of this - oh well. Here goes nothing.
The default way of thinking about set-theoretic universes is (arguably) that there's a set $U_0$ of small sets, which is an element of a larger universe $U_1$ of slightly less small sets, which is included in a larger universe of yet less small sets, etc. We end up with a sequence $$U_0 \in U_1 \in U_2 \in \ldots$$ that's probably best regarded as ordinal-indexed. Let's call this the bottom-up approach.
However for the purposes of universe-juggling, it would be more convenient to start at the top, and just deal with (unqualified) sets for as long as we can. Then when we need to do some juggling, we move from the whole universe to a smaller subuniverse $U_0$ whose elements are thought of as "small sets". If we need another level of the hierarchy, we deal with the elements of a yet smaller universe $U_1$ which is thought of as the universe of very small sets. Thus we end up with a sequence $$U_0 \ni U_1 \ni U_2 \ni \ldots.$$ Let's call this the top-down approach.
If I understand correctly, the bottom-up approach is believed to be mathematically consistent; in particular, if our definition of "universe" is "a set $U$ such that $|U|$ is a strongly inaccessible cardinal and $(U, \in \restriction_U)$ is elementarily-equivalent to the the cumulative hierarchy $V$", then the bottom-up approach is equivalent to a moderately strong large cardinal axiom. I think it's equally as strong as "there exists a proper class of strongly Mahlo cardinals" (can an expert comment on this?)
I'm not sure the top-down approach is consistent, which is a shame since it's the approach I prefer. At first-blush it seems to contradict the axiom of regularity and in particular the well-foundedness theorem. However, I think we can save the approach by just being careful to make sure the internal language cannot actually see the full sequence $n \in \mathbb{N} \mapsto U_n$. In particular, if our approach to axiomatizing is to include a constant symbol $U_n$ for each $n \in \mathbb{N}$, while avoiding the axiom "for each $n \in \mathbb{N}$ there exists an $n$-long sequence of universes $U_0 \ni \cdots \ni U_n$" it seems possible that the threat of contradiction can be averted.
Question. Is the top-down approach to universe-juggling mathematical consistent? If so, what is its consistency strength?
A:
One first stab at this would be to look at the following theory: we take the language of set theory together with new constant symbols $\kappa_i$ for each $i\in\mathbb{N}$, and look at the theory gotten from ZFC by:
extending the Separation and Replacement schemes to formulas in the new larger language;
adding for each $i\in\mathbb{N}$ the sentence $\kappa_i\ni\kappa_{i+1}$; and
adding for each $i\in\mathbb{N}$ the scheme saying that $V_{\kappa_i}\prec_{\{\in\}\cup\{\kappa_j: j>i\}} V$. (That is, for each $i\in\mathbb{N}$ and each $\varphi$ in the language $\{\in\}\cup\{\kappa_j:j>i\}$, we add the axiom "$\varphi\iff\varphi^{V_{\kappa_i}}$.")
I believe this will suffice for your purposes. And unless I'm making a silly mistake this is consistent as long as for each $i, j\in\mathbb{N}$, ZFC + "there is a tower of length $i$ of $\Sigma_j$-elementary submodels of the universe" is consistent, which is fairly mild by large cardinal standards.
Similarly, we could get $\mathbb{Q}$-many universes, or ...
In fact, a bit more compactness juggling gives (under appropriate consistency hypotheses of course) a model $M$ of ZFC in which the set of $M$-ordinals $\alpha$ with $(V_\alpha)^M\prec M$ is cofinal in $Ord^M$ and has ordertype exactly $\mathbb{Q}$. In some sense this is the extreme example: the universes are as homogeneously and plentifully arranged as possible and the model itself is small so amenable to silly external combinatorics.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Self-deportation of American Citizens from US
It is conceivable that US citizens detained at CBP will self deport to exit overcrowded CBP detainment facilities avoid lengthy detainments (>20 days). How would a US citizen's self-deportation affect one's ability to cross borders and return home?
Update:
"Food for thought" for responses:
Upon deportation, why would CBP allow you to re-enter the country with the questioned documents?
Would CBP not confiscate the questioned documents before deportation?
Citizen is held incommuncado.
There is a claim that 2 of 3 Americans live in the 100-Mile border zone patrolled by CBP:
A:
They can't take his citizenship...
Since he claims to be a born citizen, he has citizenship by birthright and nothing CBP can do can possibly revoke it.
He can voluntarily renounce his citizenship, but he has to do that through the State Dept. (which CBP is not part of). And that is an elaborate and expensive process that can't even be done inside the United States. If someone could do it merely by entering without papers and asking for a self-deport, lots of expats would save a lot of money - and that's not gonna happen :)
...but they could put him to serious inconvenience
In this particular case, CBP found his documents suspect. Probably because (if it's the case we've seen documented elsewhere) he was with two other people whose entry was illegal, and they had forged documents.
So most likely, if he agreed to self-deport, CBP would use that as prima-facie evidence that he is not a bona-fide citizen, and therefore, that his papers are faked. They certainly will not give fake papers back to someone who has tried to pass them.
So the victim would be obliged to go back to SSA, the state, etc. and re-acquire his identity documents. From outside the country. It's a pretty big chore.
A:
He's a citizen; his citizenship can't be taken by ICE or CBP, and he can't legally be kept from returning to the US from Mexico by them. He was offered "self-deportation" because ICE was illegally or irrationally detaining him, thinking that his documents were forged or stolen.
He could have "self-deported" in order to simply get out of detention, since it was offered by ICE; but he's a US citizen, so as soon as he was in Mexico, he could simply go to the border and cross with his documents. If CBP kept him from crossing at the border, his lawyer could attest to his citizenship with documents. And any "self-deportation" document he signed could be shown to be meaningless in court, since he's a citizen, and ICE was illegally or irrationally detaining him.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Is there a way to pre-filter a powerBI report server side?
I have uploaded a report, and using the .net SDK I've embedded said report into my website. However we show private data for many organizations. If I edit the reports iframe url to filter the report by the users org id so they can only see data for their organization then that ends up being a URL you can edit in javascript on the client side so a use could put another id there and view some other organizations data.
Is there any way possible to filter the data a report shows before it is sent client side?
I know you can edit the report file it'self but if you have hundreds of organizations, you'd need 100 copies of the same report which is obviously a maintenance and upkeep nightmare.
A:
I would use the "Row Level Security" (RLS) feature for this requirement. Basically you set up roles, assign users to them and assign DAX expressions to them to filter the data.
There's a good explanation of it here:
https://azure.microsoft.com/en-us/documentation/articles/power-bi-embedded-rls/
The most efficient design of RLS (from a coding and admin perspective) is if you can feed in a username variable and filter your data by that (as shown in that example).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to print values from bibtex entry fields?
I have multiple website references on my document. I'm using bibtex with @misc to specify them.
I need to keep switching between referencing this sites in the normal way together with all the other references, or have them in footnotes. I want to make this switches as painless as possible and so my idea is to use a new command to cite a website, say \wcite. I would define it as:
\newcommand{\wcite}[1]{\cite{#1}} %normal cite
\newcommand{\wcite}[1]{\footnote{\bibtitle{#1} - \bibhowpublished{#1}}} %footnote cite
Then I would comment the one I'm not using at the moment. This allows me to switch from citations to footnotes quickly, writing the website's data only once. I can also easily change the format of the footnote.
My obvious problem is that \bibtitle or \bibhowpublished do not exist. I couldn't find a way to get the string values from a bib entry.
A:
BibLaTeX provides the entry type @online with url as one of the field. Thus you might want to consider to use this entry type to store website.
One can define new types of citations using \DeclareCiteCommand, thus the way to define the command to print the title and the url in footnotes could be something like:
\DeclareCiteCommand{\wcite}
[\mkbibfootnote]
{}
{\printfield{title}--\printfield{url}}
{\addcomma\addspace}
{}
The first argument is the name of the command (\wcite); the second argument, an optional one, is to wrap the command (in this cases in a footnote, using the facility provided by BibLaTeX; the third argument is for a pre code; the fourth is for the content of the citation: the value of a field can be printed using \printfield{field name}; the fifth argument is for the code to be printed between multiple citations; finally the last argument is for the postcode.
To use the howpublished field replace \printfield{url} with \printfield{howpublished}
EDIT
It is possible to prevent the inclusion of web-site (@misc) in the bibliography by using the defenumbers option (the document must be compiled an even number of times after the bibliography has been generated)
\usepackage[defernumbers]{biblatex}
\printbibliography[nottype=misc]
|
{
"pile_set_name": "StackExchange"
}
|
Q:
left align an alignedat environment
now I am trying to get this output aligned to the left of my document
This is the code that I am using to achieve it :
\documentclass{article}
\usepackage{amsmath}
\begin{document}
\begin{flalign*}
\begin{alignedat}{10}
&a &&\phantom{+ b} &&\phantom{+ c} &&\phantom{+ d} &&\phantom{+ e} &&\phantom{+ f} &&\phantom{+ g} &&\phantom{+ h} &&\phantom{+ i} &&= 0 \\
&\phantom{a} &&\phantom{+}b &&\phantom{+ c} &&+ d &&\phantom{+ e} &&\phantom{+ f} &&\phantom{+ g} &&\phantom{+ h} &&\phantom{+ i} &&= 0 \\
&\phantom{a} &&\phantom{+ b} &&\phantom{+} c &&\phantom{+ d} &&\phantom{+ e} &&\phantom{+ f} &&+ g &&\phantom{+ h} &&\phantom{+ i} &&= 0 \\
&\phantom{a} &&\phantom{+}b &&\phantom{+ c} &&+ d &&\phantom{+ e} &&\phantom{+ f} &&\phantom{+ g} &&\phantom{+ h} &&\phantom{+ i} &&= 0 \\
&\phantom{a} &&\phantom{+ b} &&\phantom{+ c} &&\phantom{+ d} &&\phantom{+} e &&\phantom{+ f} &&\phantom{+ g} &&\phantom{+ h} &&\phantom{+ i} &&= 0 \\
&\phantom{a} &&\phantom{+ b} &&\phantom{+ c} &&\phantom{+ d} &&\phantom{+ e} &&\phantom{+} f &&\phantom{+ g} &&+ h &&\phantom{+ i} &&= 0 \\
&\phantom{a} &&\phantom{+ b} &&\phantom{+} c &&\phantom{+ d} &&\phantom{+ e} &&\phantom{+ f} &&+ g &&\phantom{+ h} &&\phantom{+ i} &&= 0 \\
&\phantom{a} &&\phantom{+ b} &&\phantom{+ c} &&\phantom{+ d} &&\phantom{+ e} &&\phantom{+} f &&\phantom{+ g} &&+ h &&\phantom{+ i} &&= 0 \\
&\phantom{a} &&\phantom{+ b} &&\phantom{+ c} &&\phantom{+ d} &&\phantom{+ e} &&\phantom{+ f} &&\phantom{+ g} &&\phantom{+ h} &&\phantom{+} i &&= 0
\end{alignedat}
\end{flalign*}
\end{document}
This is what I am getting though :
Could you help me get it to the left of the page as desired?
Any help would be greatly appreciated, thanks in advance.
A:
This doesn't use flalign but I hope that it helps!
\documentclass{article}
\begin{document}
$\begin{array}{cccccccccc}
a & & & & & & & & &=0 \\
& b & &+\;d& & & & & &=0 \\
& & c & & & &+\;g& & &=0 \\
& b & &+\;d& & & & & &=0 \\
& & & & e & & & & &=0 \\
& & & & & f & &+\;h& &=0 \\
& & c & & & &+\;g& & &=0 \\
& & & & & f & &+\;h& &=0 \\
& & & & & & & & i &=0
\end{array}$
\end{document}
One advantage of this is that you can use it in the same line with your text (though I don't use that advantage usually).
|
{
"pile_set_name": "StackExchange"
}
|
Q:
ConnectionExceprion при получении маркера доступа в есиа отправляя post запрос
Привет. Помогите пожалуйста с получением маркера доступа к данным есиа. Авторизационный код получил. Нужно сделать post запрос на тестовую среду для получения токеда доступа. Вот мой код:
public void getNewToken(String code, String state, String scope, Token token, boolean byRefresh)
throws OAuthSystemException, OAuthProblemException, JsonException {
if (state.equals(this.state.getStateAuthorize())) {
String timestamp = timestampUtil.generateTimestamp();
String clientSecret = certificateUtil.getUrlSafeSign(
scope + timestamp +
rpguConfig.getClientID() + this.state.generateStateToken()
);
GrantType grantType;
if (byRefresh) {
grantType = GrantType.REFRESH_TOKEN;
} else {
grantType = GrantType.AUTHORIZATION_CODE;
}
OAuthClientRequest requestToEsia = OAuthClientRequest
.tokenLocation(esiaConfig.getEsiaTokenPoint())
.setClientId(rpguConfig.getClientID())
.setRedirectURI(rpguConfig.getRedirectUrl())
.setScope(scope)
.setCode(code)
.setGrantType(grantType)
.setClientSecret(clientSecret)
.setParameter("state", this.state.getStateToken())
.setParameter("token_type", rpguConfig.getTokenType())
.setParameter("timestamp", timestamp)
.setParameter("access_type", rpguConfig.getAccessType())
.buildBodyMessage();
OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient());
//OAuthAccessTokenResponse response = oAuthClient.accessToken(requestToEsia);
OAuthJSONAccessTokenResponse oauthResponse = oAuthClient.accessToken
(requestToEsia, OAuth.HttpMethod.POST, OAuthJSONAccessTokenResponse.class);
if (!inspectorToken.checkToken(oauthResponse.getAccessToken())) {
parserTokenData.parseTokenData(oauthResponse, token); //парсим данные токена
}
}
}
Но при выполнении метода по получению токена - oAuthClient.accessToken выбрасывает ошибку такую:
org.apache.oltu.oauth2.common.exception.OAuthSystemException: java.net.ConnectException: Connection timed out: connect
at org.apache.oltu.oauth2.client.URLConnectionClient.execute(URLConnectionClient.java:108)
at org.apache.oltu.oauth2.client.OAuthClient.accessToken(OAuthClient.java:65)
at org.apache.oltu.oauth2.client.OAuthClient.accessToken(OAuthClient.java:55)
at org.apache.oltu.oauth2.client.OAuthClient.accessToken(OAuthClient.java:71)
at controller.server.esia.AuthorizationServer.getNewToken(AuthorizationServer.java:140)
at service.token.TokenService.getNewTokenByScope(TokenService.java:48)
at web.controller.EsiaController.getAccessCode(EsiaController.java:78)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:220)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:134)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:116)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:635)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:504)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:650)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:803)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:790)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1459)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:748) ....
Если пройти по трейсу и посмотреть вглубь всех вызывающих методов то ошибка вываливается при конекте(получение стрима) объекта HttpСlient. В документации сказано что нужно отправлять запросы на: https://esia-portal1.test.gosuslugi.ru/aas/oauth2/te
В чем может быть ошибка? Почему к нему нет доступа?
A:
Эта ошибка выбрасывается в нескольких основных случаях:
1) нет доступа к данному ресурсу с машины на которой запущено приложение
2) (похоже на первое) если машина имеет доступ к ресурсу но работает через прокси то необходимо в настройках tomcat jvm добавить эти проски примерно выглядит так -Djava.net.useSystemProxies=true -Dhttp.proxyHost=proxy -Dhttp.proxyPort=22 -Dhttps.proxyHost=proxy -Dhttps.proxyPort=33 -Dfile.encoding=UTF8 -Dhttp.nonProxyHosts="192.168.*"
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How can I convert a case class to a lift-json jobject class?
I have a case class
case class Doc(title:String, ....)
which I want to convert to a lift-json JObjectso I can more easily use JObject methods merge, etc.
A:
Extraction.decompose(Doc("foo", ...))
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Calculate $\iint\limits_{\mathbb{R}^2} (x^2+y^2)^p e^{-x^2-y^2} d x d y$.
I want to calculate an integral
$$
\iint\limits_{\mathbb{R}^2} (x^2+y^2)^p e^{-x^2-y^2} d x d y,
$$
using gamma-functions.
A:
Fill in details in the following:
Use first polar coordinates , so your integral is
$$\int_0^{2\pi}\int_0^\infty r^{2p}e^{-r^2}rdr\,d\theta=2\pi\int_0^\infty r^{2p+1}e^{-r^2}dr\;\;(**)$$
and now a new substitution: $\;t:=r^2\implies dt=2r\,dr\implies dr=\frac{dt}{2\sqrt t}\;$:
$$(**)=2\pi\int_0^\infty t^{p+1/2}e^{-t}\frac{dt}{2\sqrt t}=\pi\,\Gamma(p+1)$$
...as long as $\;\Gamma(p+1)\;$ is defined , of course.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Laravel Model - Want to check where (or) orWhere in DB::raw
This is my model function now its working correctly, but i want to check where (or) orwhere. I Already try that but cant get the apt answer
public static function getPlacementCountByStatus(){
$countStatus = DB::table('placements')->where('status','1')->select(DB::raw('count(joborderid) as total, joborderid'))->groupBy('joborderid')->get();
return $countStatus;
}
I want to check something like this
->where('statusid','=','3')->orWhere('statusid','=','4')->orWhere('stageid','=','4')->orWhere('stageid','=','8');
// i want to check this in my $countStatus something like and or condition in my db::raw query
A:
Use where() closure:
$countStatus = DB::table('placements')->where(function($q){
$q->where('statusid','=','3')->orWhere('statusid','=','4')->orWhere('stageid','=','4')->orWhere('stageid','=','8');
})
->select(DB::raw('count(placementid) as total,statusid'))
->groupBy('statusid')->get();
return $countStatus;
From the docs
Sometimes you may need to create more advanced where clauses such as
"where exists" clauses or nested parameter groupings.
In your case, you need to use where closure as you are trying to combine AND,OR operation, means you are trying to group your parameters in a block. Here closure mainly does what a parenthesis does in a sql query.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Pattern in new iPhone UDID format
Previously iPhone UDID was 40 characters. Now for iPhone Xs, Xr, Xs Max, they change to 20 characters with hyphen. It looks like it is following some sort of pattern. Does anyone know anything about it?
We have several Xs and they all start with 00008020-
A:
Apple has changed UDIDs for the new devices so they are not always 40 characters long anymore. They can be either shorter, or longer than 40 characters. This has already caused some issues for MDM vendors that relied on UDIDs to be 40 characters, for example VMWare:
VMWare AirWatch support article
|
{
"pile_set_name": "StackExchange"
}
|
Q:
How to call a method inside another method in Powershell?
In my Powershell code bellow, inside the class XMLpipe the method get_processObj calls the method getObj_fromXML, but it returns the following error:
+ $this = getObj_fromXML
+ ~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (getObj_fromXML:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
If I understood right, it is not calling the method correctly, so what would be the right way to call a method inside another method in Powershell class?
class XMLpipe
{
hidden $pp_path = (Join-Path $ENV:temp 'HPCMpipe.xml')
hidden [System.Diagnostics.Process]$logoff_processObj
hidden [String]$LastUpdate_SheetRange
hidden [String]$reservationId
XMLpipe()
{
if([System.IO.File]::Exists($this.pp_path))
{
$this = Import-Clixml -Path $this.pp_path
}
}
[XMLpipe]getObj_fromXML()
{
$this = Import-Clixml -Path $this.pp_path
return $this
}
[void]setObj_toXML()
{
$this | Export-Clixml -Path $this.pp_path
}
[void]set_processObj($value)
{
$this.logoff_processObj = $value
setObj_toXML()
}
[System.Object]get_processObj()
{
$this = getObj_fromXML
return $this.logoff_processObj
}
[void]set_LastUpdate_SheetRange($value)
{
$this.LastUpdate_SheetRange = $value
setObj_toXML($this)
}
[string]get_LastUpdate_SheetRange()
{
$this = getpublic_pipeline
return $this.LastUpdate_SheetRange
}
}
#PROCESS 1:
$myobj = New-Object -TypeName XMLpipe
#This starts a 2nd process
$ProcessObj = Start-Process notepad -PassThru
$myobj.set_processObj($ProcessObj)
#PROCESS 3:
$myobj = New-Object -TypeName XMLpipe
#This gets the process object started in the 1st process
$ProcessObj = $myobj.get_processObj()
#This stops the 2nd process
$ProcessObj | Stop-Process
A:
All properties and methods when referenced inside a class in PowerShell should be referenced with the $this variable. That includes the logoff_processObj I believe you intended to assign here.
[System.Object]get_processObj()
{
$this.logoff_processObj = $this.getObj_fromXML
return $this.logoff_processObj
}
You are just referencing $this in a couple of methods. Please check this is what you intend to do, as you are then dealing with the entire instantiated object, not any of it's specific properties.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Sending a Json File in express
I'm trying to set route in my application to download a .json file when it is opened, however I can't quite figure out how res.sendFile works. When I send my file, for some reason the client receives a completely blank file with the correct name.
Here's my code:
fs.writeFile(path.join(__dirname, '../../public/send/file.json'), JSON.stringify(resultDict));
res.setHeader('Content-disposition', 'attachment; filename=file.json');
var options = {
root: __dirname + '/../../public/send/',
dotfiles: 'deny',
headers: {
'x-timestamp': Date.now(),
'x-sent': true
}
};
res.sendFile('file.json', options, function(err){
if(err){
console.log(err);
res.status(err.status).end();
}
else{
console.log('Sent: ' + "file.json");
}
});
Why is the sent file completely empty?
A:
You are using the fs.writeFile function, but not waiting for the callback (which will indicate error, or success) See: https://nodejs.org/api/fs.html#fs_fs_writefile_filename_data_options_callback.
Because of this, by the time the send file code runs, the file has not been written, and so blank contents are sent.
To fix this put everything from res.setHeader to the end in a function and add it as the last argument to fs.writeFile.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Ordering of entities in an ontology
I have a system that models some domain data in an ontology, the usual sort of triplestore.
I've been looking around for a way to express plurality and ordering but haven't found anything via the googles. My main use case is something like one entity in the domain can be a list of tasks, (get groceries, cook meal, eat meal, something like that) but in general I feel like having the ability to 'weight' your edges might be useful across the board.
Is there an accepted way of doing this? Just go to a quadstore? Intermediary items (list → listitem) with edges to an ordinality and a domain entity? Predicates from predicates to Weights?
Here's an example:
A:
To represent something like what you've shown in your figure, you'd typically treat it as an n-ary relation. You should have a look at the W3C working note Defining N-ary Relations on the Semantic Web, but the short version is that you've got a 3-ary relation, and you're expressing
hasTask(list,1,socks)
hasTask(list,2,shoes)
hasTask(list,3,leash)
For each one of those, you'd have a resource, usually a blank node, but it could be a URI, too, and have properties relating it to the various components, and perhaps a type:
_:rel1 rdf:type :taskItem ;
:hasList :list ;
:hasord 1;
:hasTask :socks .
_:rel2 rdf:type :taskItem ;
:hasList :list ;
:hasord 2;
:hasTask :shoes .
_:rel3 rdf:type :taskItem ;
:hasList :list ;
:hasord 3;
:hasTask :leash .
There's some variability here, of course. Rather than having the reified relation have the list, number, and task as property values, the list could be related to each task item:
:list :hasTaskItem [ rdf:type :taskItem ;
:hasord 1;
:hasTask :socks ] ,
[ rdf:type :taskItem ;
:hasord 2;
:hasTask :shoes ] ,
[ rdf:type :taskItem ;
:hasord 3;
:hasTask :leash ] .
The basic idea is the same though. Alternatively, you could use a list. In pure RDF, you can use RDF lists and leave the numbers implicit, like:
:list :hasTasks ( :socks :shoes :leash ) .
That's just shorthand for
:list :hasTasks [ rdf:first :socks ;
rdf:rest [ rdf:first :shoes ;
rdf:rest [ rdf:first :leash ;
rdf:rest rdf:nil ]]].
In OWL, you can't use rdf:first and rdf:rest, but you can define your own analogous properties and implement the same structures. There's an example of specifying a list class in my answer ot Can I specify a range for rdf:List members? (where someone wanted a list all of whose elements had to be a certain type). If you do take this route, and you want to recover the position of each element in the list, you can actually do it using a SPARQL query over the RDF, as I've described in an answer to Is it possible to get the position of an element in an RDF Collection in SPARQL?.
|
{
"pile_set_name": "StackExchange"
}
|
Q:
Proper method of localizing aspx pages
I have a feature in which several aspx pages are deployed to the pages library of a 2010 environment. These are fairly standard aspx pages in that they are attaching to the default maser page, have placeholder main and placeholder additionalpagehead content regions, and have the page content publishing control in them. They have dataview web parts and jQuery in them.
These pages now need to be localized in some other languages. I can add resource files to the solution and put them into place like:
<span class="form-headers"><b><asp:Literal runat="server" Text="<%$Resources:Locs,FullName%>"/></b></span>
This results in an error as such:
Description: An error occurred during the parsing of a resource
required to service this request. Please review the following specific
parse error details and modify your source file appropriately.
Parser Error Message: Literal expressions like
'<%$Resources:Locs,FullName%>' are not allowed. Use <asp:Literal
runat="server" Text="<%$Resources:Locs,FullName%>" /> instead.
I've tried putting the resources files in the App_GlobalResources and every other place imaginable as mentioned in the various articles on localizing SharePoint features. I cannot get this to work properly.
So my question is how can you localize pages that get deployed to the Pages library or do I have to take some other approach to localize these files?
A:
In the SharePoint projects I have worked on I have used a few different ways to localize page content. I think the simplest way for you will be with an EncodedLiteral:
<SharePoint:EncodedLiteral runat='server' text='<%$Resources:wss,language_value%>' EncodeMethod='HtmlEncode' />
For the RESX files, in the SharePoint project I create a SharePoint mapped folder for the Resources folder in the 14/15 HIVE. This ensures they are in the right place and get loaded on the next IISRESET.
The other methods I have used that could work:
1) Create a custom ASP.NET control that gets the resources for you from a compiled form
2) Use JavaScript for localization (the way SharePoint-hosted apps get localized)
|
{
"pile_set_name": "StackExchange"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.