INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
The motion of the projectile
I've got the following $$h(t) = -\frac{1}{2} gt^2 + Vt + h'$$ where $h'$ and $V$ are the initial height and velocity of the object, respectively. Suppose a person standing at the top of the tower of pisa ($176$ft high) throws a ball directly upward with an initial speed of $96$ft/s. Find the ball's height, its velocity and acceleration at time.
|
Here's how you can solve this problem:
* For the height, just plug in whatever $t$ is into the formula for $h(t)$.
* For the velocity, because of gravity, the velocity decreases by $g$ for every second, so it decreases by $gt$ for every $t$ seconds. Thus, we get $v(t)=V-gt$, so to get the velocity, just plug in whatever $t$ is into that formula.
* The acceleration is $a(t)=-g$ regardless of time as that is the acceleration due to gravity.
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 1,
"tags": "algebra precalculus, classical mechanics"
}
|
bypass messenger must install a new version (forced upgrade)
Is there anyway to keep my old (version 8.5) messenger ? For some reason it doesn't let me log in and want to force an upgrade (I really don't like the new versions)
|
From <
1. Right Click on your "Windows Live Messenger's icon
2. Click on Properties you will see many tabs,Shortcut,Compatibility,General,Security,Details and Previous Version.
3. Click on Compatibility Tab in This Tab you will see "Compatibility Mode"
4. Check in front of Run this Program in compatibility mode for:
* if you use Windows XP, Select Windows NT or 2000 (Msnplus can't run on this mode) [if you use Windows Vista or 7, Select Windows Server 2003(SP1)( msnplus can run on this mode]
5. Apply and OK this setting
6. Let's enjoy on your Windows Live Messenger 8.0 and 8.5
I haven't tried it personally . But sounds like its working.
|
stackexchange-superuser
|
{
"answer_score": 3,
"question_score": 3,
"tags": "instant messaging, windows live messenger"
}
|
Can't delete file (you need permission/file open in another program)
So I was going through an old HDD that was once the primary HDD for my old laptop, browsing through it in my new desktop.
I decided to delete the entire contents but it's stuck on two files
`F:\old\bin\Windows\SysWOW64\Macromed\Flash\Flash32_1\1_6_602_171.ocx` `F:\old\bin\Windows\System32\Macromed\Flash\Flash64_11_6_602_171.ocx`
However I get a "you don't have permissions" error. I have tried the "take ownership" command, which worked for all the other files.
That's what happens if I `delete` it, but if I `shift + delete` I get "the file is open in another program".
I guarantee you, this file is _not_ open in another program.
|
You could use the tool Unlocker to unlock the file or kill the process, which uses the file. So you don't need to start with a Live-CD to delete the file.
After you downloaded the unlocker, there is an additional option in the contextmenu called _Unlocker_.
!enter image description here
Just click on it, and it will delete all the files.
|
stackexchange-superuser
|
{
"answer_score": 1,
"question_score": 2,
"tags": "windows 7"
}
|
sklearn logistic regression parameter in GridSearch
just wondering how to separate parameters into a group and pass it to gridsearch? As i want to pass penalty l1 and l2 to grid search and corresponding solver newton-cg to L2.
However, when i run the code below, the gridsearch will first run l1 with newton-cg and result in error msg ValueError: Solver newton-cg supports only l2 penalties, got l1 penalty.
Thanks
param_grid = [
{'penalty':['l1','l2'] ,
'solver' : ['newton-cg', 'lbfgs', 'liblinear', 'sag', 'saga']
}
]
|
Try this example:
param_grid = [
{'penalty': ['l1'], 'solver': [ 'lbfgs', 'liblinear', 'sag', 'saga']},
{'penalty': ['l2'], 'solver': ['newton-cg']},
]
here **l1** will be tried with **'lbfgs', 'liblinear', 'sag', 'saga'** and **l2** will be tried with only **'newton-cg'**
|
stackexchange-stackoverflow
|
{
"answer_score": 7,
"question_score": 3,
"tags": "machine learning, scikit learn, pipeline, logistic regression"
}
|
convert memo field in Access database from double byte to Unicode
I am using Access database for one system, and SQL server for another system. The data gets synced between these two systems. The problem is that one of the fields in a table in Access database is a **Memo** field which is in **double-byte** format. When I read this data using DataGridView in a Windows form, the text is displayed as ???. Also, when data from this field is inserted in sql server database nvarchar(max) field, non-English characters are inserted as ???.
How can I fetch data from memo field, convert its encoding to Unicode, so that it appears correctly in SQL server database as well?
Please help!!!
|
I solved this issue by converting the encoding as follows:
//Define Windows 1252, Big5 and Unicode encodings
System.Text.Encoding enc1252 = System.Text.Encoding.GetEncoding(1252);
System.Text.Encoding encBig5 = System.Text.Encoding.GetEncoding(950);
System.Text.Encoding encUTF16 = System.Text.Encoding.Unicode;
byte[] arrByte1 = enc1252.GetBytes(note); //string to be converted
byte[] arrByte2 = System.Text.Encoding.Convert(encBig5, encUTF16, arrByte1);
string convertedText = encUTF16.GetString(arrByte2);
return convertedText;
Thank you all for pitching in!
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "sql server, ms access, encoding, memo"
}
|
Get the list of hyperlinks in a PDF file
I have a pdf file.I need to find all the hyperlinks available in that file and then make change on those links. I am using C# and I'd rather not to use a third party tool!
|
You can use iTextSharp. Its an open-source API to manipulate pdf written in c#.
The basic algorithm would be:
1. Loop through every pages in the PDF file.
2. For every page, loop through every annotation in the annotations collection (annots dictionary).
3. If you found an annotation of subtype link, increases your count or do whatever logic you need to do.
RWendi
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 2,
"tags": "c#, pdf"
}
|
Show that if $V\in A(G)$ is such that $T_aV=VT_a$ for all $a\in G$, then $V=L_a$ for some $b\in G$
> Define:$T_a:G\to G,T_a(x)=ax$,$L_a:G\to G,L_a(x)=xa^{-1}$. Show that if $V\in A(G)$ is such tath $T_aV=VT_a$ for all $a\in G$, then $V=L_a$ for some $b\in G$. (Hint: Acting on $e\in G$, find out what $b$ should be.) $A(G)$: the symmetrict group for $G$
I tried this: $\forall x\in G, T_eV(x)=VT_e(x)$ but this only leads to $V(x)=V(x)$. I also tried: $\forall a\in G, T_aV(e)=VT_a(e)$, which leads to $V(a)=aV(e)$. So I'm stucked now. What to do next please?
|
OK, a simpler solution.
For any $x \in G$, $T_xV(e) = VT_x(e) = V(x)$ implies $V(x) = xV(e)$, so if this holds for all $x \in G$, then $V = L_b$ with $b=T(e)^{-1}$.
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 1,
"tags": "abstract algebra, group theory"
}
|
Appcelerator - Using REST API
I am calling the following curl command, but it is always returning me invalid username/password.
curl -F "login=myemailAddress" -F "password=myPassword" "
I am using the key defined in TiApp.xml as acs-api-key-production. Now if I use the same username and password and login through dashboard.appcelerator.com, then I am able to do so.
Can someone please point out as to what issue is this. I am doing a similar implementation in C#, which too is returning the same invalid username/password error.
|
The username and password should not be from your AppC account, but from an (admin) user you create at:
In the dashboard, navigate to your ArrowDB app > Manage Data > Users > Create User. There should already be an admin user you can use.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "appcelerator, appcelerator arrow"
}
|
How to Validate Facebook LoginSession in iOS app
I am implementing Facebook login in my iOS App.
I need to know how to retrieve `ifLoginSession` is currently valid or not .
In latest `FacebookSDK FBSession` class is no more used, therefore we cannot use `FBSession.activeSession` property.
So I have written my code to validate session as
- (BOOL)isSessionValid
{
return ([FBSDKAccessToken currentAccessToken])?YES:NO;
}
Is it correct way to implement session validity? or am i missing something
|
In `didFinishLaunchingWithOptions` always update the token and then check its not nil or not
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[FBSDKProfile enableUpdatesOnAccessTokenChange:YES];
return [[FBSDKApplicationDelegate sharedInstance] application:application didFinishLaunchingWithOptions:launchOptions];
}
Then u can check like this
if (![FBSDKAccessToken currentAccessToken]) {
//session invalid
} else {
//session valid
}
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "ios, objective c, facebook graph api, facebook login"
}
|
Error Package file was not signed corrctly
I am trying to learn how to put apps out in the market and I made a quick JS-Light (Flashlight) app with Esclipe-IDE. I did and export of a signed package and uploaded to the market. it downloads and then I get the following error
Error Package file was not signed corrctly
|
If you've been testing your application on your phone, the application package on your phone has been signed with a different debug key, whereas the package you uploaded to the Market is signed with your own key.
In order for an application to be replaced with a new version of it, the keys have to match. An ordinary user will have no trouble downloading your app and installing it.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "java, android, google play"
}
|
Supported Problem types for Mosek Infeasibility Report
I was using Commercial Mosek via its Cvxpy interface. Specifically leveraging its **infeasibility report feature** for debugging of my infeasible problems.
Though it ran perfectly fine for sample LP problems but **failed on MILP problems** (i.e. no infeasibility report in the solver logs).
In the official documentation of Mosek [0], I couldn't find any specification on supported problem types for infeasibility report.
Kindly tell the supported problem types for infeasibility report.
(or does it work for all problem types?)
0 - <
|
The infeasibility report is based on Farkas Lemma as discussed in
<
Since Farkas Lemma does not apply to MILPs, then this report is not available for MILPs.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "python, optimization, cvxpy, mosek"
}
|
How getopts is setting a bash variable
I would like to re-implement my own getopts (in python if possible).
My problem is that I don't understand how this is possible:
# The call of the following script
./script -h
#!/bin/bash
getopts 'h' TEST # output nothing
echo $TEST # output h
env | grep # output nothing
We read all over the Internet that you can't set a variable in the parent process. But this is done here and without an export.
I want to understand how it works as I would like to do approximately the same in python. So my second question will be, is it possible to do the same in python?
Thank you very much! :)
|
`getopts` is a bash builtin. Since it operates within the shell process it is welcome to change shell variables at will.
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 0,
"tags": "bash, getopts"
}
|
How to set the language a plain text is read as in Visual Studio
I've been using Notepad++ for editing CSS, and for just plain text. In Notepad++ I can paste a block of text and specify if I want the file to be highlighted as HTML, CSS, etc.
How do I set the language that Visual Studio will use to interpret a block of text I pasted from my clipboard? What about when I open a plain TXT file?
Am I using the wrong tool for the job? I've been hearing about "Visual Studio Code". Is that what I should use instead?
|
In general, _Visual Studio_ works with "Project". It is designed to work with the relevant files for the project, and it will recognize them according to the extension.
In Visual Studio, you can override the default config for the file extension with this docs.microsoft. This configuration will work against all files with this extension, but not against a specific file.
I guess there are plugins that can help on the subject, but as you said, _Visual Studio Code_ is more like a **file editor** like _Notepad++_ , with very powerful plugins and capabilities. So yes, in case you want an enhanced **Notepad++** , you need to use the _Visual Studio Code_ and not the _Visual Studio_.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 2,
"tags": "css, visual studio, visual studio 2017, syntax highlighting"
}
|
Mate executable as desktop manager in core applications
In "Default Applications for LXSession", in Lubuntu, there is the tab "Core Applications". There is a field called "Desktop Manager". The entry is 'filemanager' by default, and it uses pcmanfm to control the desktop and icons.
I have installed mate destkop and sometimes things work fine, but sometimes don't. What mate executable should I put in that field in order for it work without further problems? As for now, that field is left blank.
|
It seems like nemo (cinnamon's file manager) what getting in the way (according to what I could see in 'ps -fax' listings. So removing nemo seemed to solve the issue.
|
stackexchange-askubuntu
|
{
"answer_score": 0,
"question_score": 0,
"tags": "lubuntu, mate"
}
|
getting grails 2.0.0M1 config info in domain object, and static scope?
How do I get to the Config.groovy information from a domain object, or from a static scope? I'm using ConfigurationHolder.config.* now, but that and ApplicationHolder are deprecated so I'd like to 'do it right' ... but the grailsApplication object isn't available in a DO/static scope.
|
I'd add the `grailsApplication` to the metaclass of domain classes - this is something I'm thinking about doing for 2.0 final. For now, put it in `BootStrap.groovy`, e.g.
class BootStrap {
def grailsApplication
def init = { servletContext ->
for (dc in grailsApplication.domainClasses) {
dc.clazz.metaClass.getGrailsApplication = { -> grailsApplication }
dc.clazz.metaClass.static.getGrailsApplication = { -> grailsApplication }
}
}
}
Then you can access the config from `grailsApplication.config`, and Spring beans via `grailsApplication.mainContext.getBean('foo')` or just `grailsApplication.mainContext.foo`.
|
stackexchange-stackoverflow
|
{
"answer_score": 8,
"question_score": 6,
"tags": "grails, grails domain class"
}
|
how to get actual height of Grid Row before rendering
In my project there are many nested Grids. And mostly rows and columns width is defined as "*" in XAML.
I am trying to expand a particular row(lets say Row1) by seting other row's height to 0, and i am using the .ActualHeight property to get the width of Row1 then its not giving me actual height.
As per I know that is happening because height and width of Grid rows and columns are set on rendering time.
I searched on net and somebody suggested to use UpdateLayout() method ..but that is also not working for me.
I can not post code snippet because it is very long code.
my project in c#.net wpf.
|
You need to do a full layout update, that is you need to call Measure, Arrange and UpdateLayout:
//Make the framework (re)calculate the size of the element
_Element.Measure(new Size(Double.MaxValue, Double.MaxValue));
Size visualSize = _Element.DesiredSize;
_Element.Arrange(new Rect(new Point(0, 0), visualSize));
_Element.UpdateLayout();
_Element being a FrameworkElement (Grid is one).
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 3,
"tags": "c#, .net, wpf"
}
|
Evitar que se muestre el día anterior al obtener fecha de un input
Tengo que usar Javascript, es un `<input type="date">` y a la hora de escoger cualquier fecha y mandarla a imprimir, me imprime la de un día anterior. Vivo en CDMX y no sé si la zona horaria esta mal:
function funcionfecha(){
var Fecha = new Date(document.getElementById("fecha").value);
window.alert(Fecha);
}
<input type="date" id="fecha" onChange="funcionfecha( this.value )">
Por ejemplo escogí la fecha de hoy Viernes 6 de Septiembre del 2019 y me sale esto:
Tue Sep 05 2019 19:00:00 GMT-0500 (hora de verano central).
La fecha es pasada.
|
Las Fechas en Javascript incluyen el huso horario, si te fijas, al final pone "19:00:00 GMT-0500", lo que significa que tu huso horario está cinco horas por delante del uso horario UTC, es decir, que si le sumas 5 horas a Sep 05 2019 19:00:00, obtendrás la fecha en UTC Sep 06 2019 00:00:00, si lo que quieres es tarbajar con fechas en UTC puedes usar las funciones que provee Javascript por defecto:
Fecha.toUTCString() <- esto te imprimirá Sat, 06 Sep 2019 00:00:00 GMT
Fecha.getUTCDay()
Fecha.getUTCMonth()
etc ...
O para más funcionalidad utiliza la biblioteca moment.js, que tiene muchísimas utilidades a la hora de trabajar con fechas
|
stackexchange-es_stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "javascript, date"
}
|
How to output the title of the blogs home page
I am using a static frontpage and a page for my blogposts. In my header.php I want to display the title of the selected page of my blogposts.
For example:
<?php
if( is_home() )
echo '<h1>' . get_the_title() . '</h1>';
?><nav>
...
</nav>
But of course `get_the_title()` returns the first element of the displayed posts and not of the page itself.
How can I display the title of the assigned home page?
|
You can make use the queried object to return the title of the page used as blogpage
You can use the following: ( _Require PHP 5.4+_ )
$title = get_queried_object()->post_title;
var_dump( $title );
|
stackexchange-wordpress
|
{
"answer_score": 6,
"question_score": 0,
"tags": "wp query, title, homepage, get the title"
}
|
How to use the values of a list that is inside another list as arguments of a function in Python
I am very new to Python. I have a function `DISTANCE(lat1, long1, lat2, long2)` that calculates the distance between 2 points.
Then I have a list called `POINTS`, where each value is another list which contains those four values.
I would like to obtain the sum of the results of the function `DISTANCE` for all the values inside `POINTS`.
Can anybody help me with that? Thanks!
|
use `for-in` loop if you're new to python:
result=[]
for item in POINTS:
res=DISTANCE(*item)
result.append(res)
print(sum(result))
if you're confused about what's `*` here, you should read this
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 2,
"tags": "python, list, function, arguments"
}
|
Mono - Flux switchIfEmpty and onErrorResume
In project reactor is it possible to implement a stream with `switchIfEmpty` and `onErrorResume` at the same time?
infoRepository.findById(id); //returns Mono<Info>
in case of `empty or error then switch to the same backup stream`?
|
There's no _single_ operator that does these things together, but you can trivially switch to an empty publisher on an error, then handle both cases through `switchIfEmpty` like:
infoRepository.findById(id)
.onErrorResume(e -> Mono.empty())
.switchIfEmpty(newPublisher);
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "spring, mono, spring webflux, project reactor, flux"
}
|
Java apache poi error: java.lang.IllegalArgumentException: Unknown error type: -60
I'm getting error `java.lang.IllegalArgumentException: Unknown error type: -60` , in following code:
...
> evaluator.evaluateFormulaCell(c);
...
In excel file, all formulas works fine.
Stacktrace:
java.lang.IllegalArgumentException: Unknown error type: -60
at org.apache.poi.ss.usermodel.FormulaError.forInt(FormulaError.java:131)
at org.apache.poi.xssf.usermodel.XSSFCell.setCellErrorValue(XSSFCell.java:611)
at org.apache.poi.xssf.usermodel.XSSFFormulaEvaluator.setCellValue(XSSFFormulaEvaluator.java:203)
at org.apache.poi.xssf.usermodel.XSSFFormulaEvaluator.evaluateFormulaCell(XSSFFormulaEvaluator.java:147)
...
|
You need to upgrade to a newer version of Apache POI.
Specifically, you need to be running POI 3.12 beta 1 or newer. If you look at the changelog for Apache POI, you'll see that this bug was fixed between 3.11 final and 3.12 beta 1
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "java, excel, apache poi"
}
|
Shouldn't Elliot have been caught or at least noticed outside of the prison?
I don't know what's considered a spoiler, so I'll put more than probably necessary in a spoiler block...
At the end of episode 1.5 of _Mr. Robot_ , Elliot and Vera's brother are standing outside of the prison waiting for Vera to come out.
> After the prison doors open and the prisoners begin to escape, there's a really obvious lack of police. I know Elliot mentioned that there was a 2 minute delay before sirens went off, but even when they do go off and we start to hear sirens and police, we don't see them. Not only that, but Elliot, Vera, Isaac, and DJ stood around for an awfully long time about 20 meters from the prison gate.
Wouldn't they have been caught?
|
The logical answer is yes, they should have been caught. Suspension of disbelief is a common narrative technique. As both of our beliefs didn't quite get extended far enough in this scene, an answer could be that they simply failed to "sell it".
However, Eliot's tenuous grip on reality is a major element of the show, so it's possible some or all of that story-line was imagined. Eliot's fingerprints and DNA were all over the place, after all.
The literal explanation is probably that the chaos caused by the hack was sufficient to allow them to escape. Since Eliot has never been arrested, so far as we know, his fingerprints wouldn't be on file anywhere.
|
stackexchange-movies
|
{
"answer_score": 7,
"question_score": 9,
"tags": "plot explanation, realism, mr robot"
}
|
Doxygen exclude getter and setter
is it possible to configure Doxygen to exclude my getter and setter? We're using beans Extensivly, and for the internal documentation there is really no need to have the getter and setter visible every time. However, i'd like to keep
HIDE_UNDOC_MEMBERS = NO
as it's good to see what still needs documentation.
I thought that I could achive this with EXCLUDE_SYMBOLS, but till now I didn't succeed. Here's my try:
EXCLUDE_SYMBOLS = */*::get*
I also tried `*::get*`, `*/*::get*` etc, but none of these seemed to work. Any help is appriciated!
|
You can have a look at the \cond command ?
You will have to manually "tag" all of your files, but you will gain in granularity : if you create some kind of getter or setter that you want in the documentation, it will be possible.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "java, doxygen, getter"
}
|
Using ADB shell in C++ program
I'm am working on a project that requires me to make adb shell commands. The code below is just a test program so that I can understand how to pass adb shell commands from C++. When I run this code I get the following error: sh: adb: command not found. I have the android sdk tools and platform tools in my path and I can run adb shell from my terminal.
#include <iostream>
#include <stdio.h>
using namespace std;
int main()
{
system("adb devices");
return 0;
}
|
Thanks to Jiang YD I was able to solve it. I just called adb from it's absolute path and it worked.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "android, c++, linux, shell, adb"
}
|
Richfaces extendedDatatable sort the empty row to be the last
I am using richfaces extendedDataTable as an editable grid. The build-in sorting always sorts the empty row to be the first. I want to sort the empty row to be the last. How can I do that? Thanks,
|
Items in RichFaces _extendedDataTable_ are sorted by items natural sort oder. The list items you set as value of _extendedDataTable_ should implement interface _java.lang.Comparable_. You can sort the empty row to be the last by method _public int compareTo(..)_
You can also sort _extendedDataTable_ by clicking on the table headers. Add property _sortBy_ to _rich:column_ elements:
<rich:extendedDataTable
value="#{task.taskList}"
var="item"
..>
<rich:column
sortBy="#{item.name}"
..>
If you click on the column header table is sorted by _sortBy_ value.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 2,
"tags": "sorting, datatable, richfaces, row"
}
|
Telegram: отправка ботом личного сообщения
Хочу в телеграмме присылать сам себе личные сообщения, просто перейдя по url с токеном и нужными параметрами. Это возможно? Вот получил токен и он рабочий, и сделал следующий запрос:
Но к сожалению в ответ приходит:
{"ok":false,"error_code":400,"description":"[Error]: Bad Request: channel not found"}
P.S. Пожалуйста, не пинайте если вопрос слишком глупый) Сообщения будет слать роутер))
|
Сначала создали бота.
После этого создали чат и добавили бота в него :
* заходишь к боту на страницу
* нажимаешь на верхний бар, на название
* дальше опции -> add to group
* и выбираешь любой чат
А потом уже можно скриптом получить id чата через getUpdates (история бота), тут можно почитать <
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 0,
"question_score": 2,
"tags": "telegram bot"
}
|
Java Date strange behaviour
I have very strange behaviour of Java Date class:
System.out.println(new Date().toGMTString());
long l = 1332452310L;
Date d = new Date(l);
System.out.println(d.toGMTString());
Gives me
22 Mar 2012 22:00:42 GMT
16 Jan 1970 10:07:32 GMT
Why this happens?
|
your long l is the time in seconds, you need to make it the time in milliseconds:
long l = 1332452310L * 1000L;
|
stackexchange-stackoverflow
|
{
"answer_score": 9,
"question_score": -2,
"tags": "java, date"
}
|
Fatal error : Call to a member function getBackendModel() on null in app/code/core/Mage/ImportExport/Model/Import/Entity/Customer.php on line 425 M-1
I got error while importing the customer using CSV in the admin.
|
Magento checks all attributes in the CSV file before importing. And if there are some attributes that are either not assigned to attribute set or have no backend model defined, then Magento throws an error like the error which you are getting.
You need to make sure that your custom customer attributes are assigned to a set. Otherwise, the following code will remove your attributes from the array which will trigger the above error during the import:
> app/code/core/Mage/Eav/Model/Entity/Abstract.php
if (!$attribute->isInSet($setId)) {
unset($attributes[$code]);
}
Please let me know if it helped.
|
stackexchange-magento
|
{
"answer_score": 1,
"question_score": 3,
"tags": "magento 1.9, admin, csv, customer csv"
}
|
Different Font Faces in same Web Application
The context here is a web application delivered through the browser.
My question is: is it ever okay to have different font faces or a single application? To me it looks obvious but not egregious.
|
Yes, mixing different fonts and typography is perfectly fine, so long as it is done tastefully. My approach to mixing different fonts is to give each font a purpose or a voice. The App would have a particular voice and the fonts would correspond to its personality. While things requiring input from the user would have a different font/voice. Using that as a guideline can help making things consistent and help you keep track of all the typography being used.
Check out this tutorial by Hoefler & Frere-Jones Four Techniques for Combining Typefaces
Another good example of it in use by Mailchimp.
|
stackexchange-ux
|
{
"answer_score": 0,
"question_score": 0,
"tags": "website design, font, typography"
}
|
Laravel & Vue: Communication between different Vue components split by Laravel views
I am using Vue all over the place in my Laravel project. I have a couple of views, and a dozen components inside these views that I have registered in app.js. Inside these components I have more components. Now the fun part starts when I want one component to communicate with another. What is the most efficient way to exchange information between different Vue components given that these are seperated by different laravel views (via include)?
|
The proper way for many components across your project to update when there are state changes would be to use VueX.
VueX moves your entire app state, methods, etc. to a centralized location that your components can leverage.
<
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 2,
"tags": "laravel, vue.js, components, communication"
}
|
Checking the DB_LINK Connection
I just created a DB link using the following query in oracle:
CREATE DATABASE LINK LINK_NAME
CONNECT TO DB_USERNAME
IDENTIFIED BY DB_USERNAME'S_PASSWORD
USING 'SERVICE_NAME';
and i'm able to see few more infos like owner,db_link,username,host,created details when viewed from sql developer.
How to use `SELECT` query in order to check the link connectivity to that `DB_USERNAME` or kindly suggest me a way to check the same ..
|
It's simple:
select * from dual@LINK_NAME
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "sql, database, oracle"
}
|
More info on Conjuncture of Terros (Terras)
In answering a coding problem called "Conjuncture of Terros", there was scant information on the series.
**What is the origin of this series?** and what might applications may use it?
See original problem
Terros number sequence
t(0) = n
t(1) = n
if t(n-1) is even
t(n) = t(n-1)/2
else
t(n) = (3*t(n-1) + 1)/2
Web search of "Terros" only led to some ADHD related sites.
[Edit]
@Palec provides a corrected spelling for Riho Terras
|
I would recommend searching for the Collatz Conjecture (also called 3n+1 problem). It's a more common name. A little explanation though:
You start with natural number $n$. If it's even, you go to $\frac{n}{2}$. If it is odd, you go to $3n+1$, which then will be even of course. Then repeat this process again and again. The Terros sequence is pretty much a modified Collatz sequence, just that you skip the even number $3n+1$ and directy go to $\frac{3n+1}{2}$. The interesting aspect is to find out where this sequence goes in the end. The conjecture states that for any starting point you end up in the circle $1\rightarrow4\rightarrow2\rightarrow1$. However this is not yet proven.
PS: For Terros the circle would of course be $1\rightarrow2\rightarrow1$.
|
stackexchange-math
|
{
"answer_score": 3,
"question_score": 1,
"tags": "sequences and series"
}
|
Does git clone include commit comments too?
I'm backing up git hub and bitbucket.
Does git clone include commit comments too?
if I do a git log in the directory, I'm able to see commit history. How do I see commit comments
|
Of course.
When you clone you get all the commits + tags + notes + messages.
Type a `git log` and you will see it all
In git you have the option to add notes as well as comments, you will get athem all as well.
* **To view history (log):**
git log
* **To view all branches:**
git branch -a
* **To view all tags:**
git tag -l
* **If you wish to see all your current branches log history:***
git log --oneline --decorate --graph
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "git"
}
|
Create elevated token with SetTokenInformation returns error 87
I am trying to create an elevated token with `SetTokenInformation`, but it fails and keeps returning error code 87.
This is my code:
#include <Windows.h>
int main()
{
HANDLE currentProcessToken, newTok;
OpenProcessToken(GetCurrentProcess(), TOKEN_DUPLICATE, ¤tProcessToken);
DuplicateTokenEx(currentProcessToken, TOKEN_ALL_ACCESS, nullptr, SecurityImpersonation, TokenPrimary, &newTok);
CloseHandle(currentProcessToken);
TOKEN_ELEVATION elev = { 1 };
BOOL setTokenInfo = SetTokenInformation(newTok, TokenElevation, &elev, sizeof(TOKEN_ELEVATION));
DWORD error = GetLastError(); // is 87 which is "the parameter is incorrect"
return 0;
}
|
`TokenElevation` is valid information class only for `GetTokenInformation` function. you can query are `TokenIsElevated` but you can not set it. `NtSetInformationToken` return `STATUS_INVALID_INFO_CLASS` in this case. the `SetTokenInformation` convert this error to `ERROR_INVALID_PARAMETER`. original `NTSTATUS` error code you can got by calling `RtlGetLastNtStatus()`. and anyway you can not "elevate" already existing token. this is by design
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": -2,
"tags": "c++, windows, winapi, access token, elevation"
}
|
The derivative of $2^{x+1}$ in the point $-3$
They ask me to compute the derivative of $2^{x+1}$ in the point $-3$. Since the function is continous in that point, all I have to do is to compute the lateral derivatives. The left one first:
$$\lim_{x \to -3^-} \frac{2^{x+1} - \frac{1}{4}}{x+3}$$
I've tried to solve this limit using this formula:
$$\frac{a^{u(x)} - 1}{u(x)} = \ln{a}$$ But the result seems to be incorrect. How should I solve that limit?
|
$$\lim_{x \to -3^-} \frac{2^{x+1} - \frac{1}{4}}{x+3} = \lim_{x \to -3^-} \frac{2^{x+1}\frac{2^2}{2^2} - \frac{1}{4}}{x+3} = \lim_{x \to -3^-} \frac{\frac{2^{x+3}}{4} - \frac{1}{4}}{x+3} =$$ $$= \frac{1}{4}\lim_{x \to -3^-} \frac{2^{x+3}- 1}{x+3} = \frac{1}{4}\ln{2}$$
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 1,
"tags": "limits, derivatives"
}
|
How to display a window on a secondary display in PyQT?
I am developing an application; which will run on a system with 2 displays. I want my PyQt app to be able to automatically route a particular window to the second screen.
How can this be done in Qt? (either in Python or C++)
|
Use QDesktopWidget to access to screen information on multi-head systems.
Here is pseudo code to make a widget cover first screen.
QDesktopWidget *pDesktop = QApplication::desktop ();
//Get 1st screen's geometry
QRect RectScreen0 = pDesktop->screenGeometry (0);
//Move the widget to first screen without changing its geometry
my_Widget->move (RectScreen0.left(),RectScreen0.top());
my_pWidget->resize (RectScreen0.width(),RectScreen0.height());
my_Widget->showMaximized();
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 6,
"tags": "python, qt, user interface, pyqt"
}
|
Real Analysis. Topologically homogeneous sets.
> A set $X \subset \mathbb{R}^{n}$ is said _topologically homogeneous_ when given $a,b \in X$ there is a homoemorphism such that $h(a) = b$. Prove that, for all $n \in \mathbb{N}$, the space $\mathbb{R}^{n}$ and the sphere $S^{n}$ are topologically homogeneous. Show that $[0,1]$ is not topologically homogeneous.
I know that if $M, N$ are homeomorphic metric spaces, then $M$ is topologically homogeneous iff N is too. Maybe it help.
For $\mathbb{R}^{n}$, I think in any function of the form $x \to x + \alpha$ with $\alpha$ fixed, since are Lipschitz functions.
For $S^{n}$, maybe an aplication that change the base, but I don't know to explain this function.
For $[0,1]$ I don't have any idea.
|
Hint on $X=[0,1]$: Both $X\backslash\\{0\\}$ and $X\backslash\\{1\\}$ are connected. Is this true for any other point of $X$?
Consider $S^n$ to be the subset of $\mathbb{R}^{n+1}$ consisting of all points a unit distance from the origin of $\mathbb{R}^{n+1}$. Let $P,Q\in S^n$. In $R^{n+1}$ consider the intersection of the plane $OPQ$ ($O$ being the origin of $\mathbb{R}^{n+1}$) and $S^n$. The intersection is a circle. Rotate $\mathbb{R}^{n+1}$ about the line through $O$ with direction vector $\vec{OP}\times\vec{OQ}$ by a sufficient angle to move $P$ to $Q$. Restricted to $S^n$ this will be a homeomorphism mapping $S^n$ onto $S^n$ taking $P$ onto $Q$.
For $\mathbb{R}^n$ a simple translation by $\vec{PQ}$ will do.
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 1,
"tags": "real analysis, metric spaces"
}
|
Chinese remainder theorem for non-prime / non-coprime moduli
If I want to find some number $x$ where it leaves a remainder when divided by some prime $p$, and another remainder when divided by some prime $q$, and so on, I can use the Chinese Remainder Theorem.
However, what about when $p$ and $q$ are not prime nor coprime?
|
To use your example, trying to solve:
$$x\equiv 10\pmod{24}\\\x\equiv 18\pmod{64}$$
You take each in terms of its prime factors:
$$x\equiv 10\pmod {3}\\\ x\equiv 10\pmod{8}\\\x\equiv 18\pmod {64} $$
Note that $x\equiv{18}\pmod {64}$ implies $x\equiv 10\pmod 8$, so we are left with:
$$x\equiv 10\pmod {3}\\\x\equiv 18\pmod {64}$$
which is a pair of equations with coprime moduli.
You can always do this. Prime factorization is hard, however, so if you wanted an algorithm, you'd want to come up with a more general way than just prime-factorization. There are ways, but I'd have to call them up from memory. But the general gist is that you need to always reduce the problem to the co-prime case, and some way to check for contradictions that rule out solutions.
|
stackexchange-math
|
{
"answer_score": 7,
"question_score": 8,
"tags": "elementary number theory, chinese remainder theorem"
}
|
What are the advantages and disadvantages of becoming a werewolf?
Before I decide whether or not I would like to become a werewolf, I'd like to know what I'll have to deal with. Whether this means being stronger, or having an appetite for human flesh, what are the advantages and disadvantages associated with becoming a werewolf?
I'm particularly interested in if there are any difference between the different races when they become werewolves. For instance, is there any difference between if an orc becomes a werewolf, to if a Khajiit becomes a werewolf?
|
While in regular form, there isn't a whole lot of difference between werewolves and non-werewolves, but when you transform, you get a ton of benefits and drawbacks:
### Benefits
* Increased max health by 100 (non-regenerating)
* Increased max stamina by 100
* Faster sprint speed
* Wolves no longer attack you
* Committing crimes in beast form don't count against your normal form
* Immunity to all diseases, including vampirism (also cures vampirism if you have it)
* Special, werewolf-only abilities like howls
### Drawbacks
* No looting (when a werewolf)
* No inventory or equipment access (when a werewolf)
* No talking (when a werewolf)
* People either run away from you, cower, or attack you (no friendly humanoid NPCs) (when a werewolf)
* If someone sees you transform, it's automatically a crime
* No rested bonus
* If caught transforming in public it's 1,000 gold bounty to pay
|
stackexchange-gaming
|
{
"answer_score": 24,
"question_score": 35,
"tags": "the elder scrolls v skyrim"
}
|
Retrieving the COM class factory for component with CLSID
i am getting following Pop Up Message Box when i try to save a transaction in a windows application
> Unhandled exception has occured in your application.If you click Continue the application will ignore this error and attempt to continue. if you click Quit, the application wil close immediately.
>
> Retrieving the COM class factory for component with CLSID {7E4A7632-4A0C-BAB6-AO7DACOA765B} failed due to following error:80040154
Please note i have build my application in x86 environment and my windows application is also installed in windows xp 32 bit machine.
In my code the above clsid is used for class that was com component and converted in to the Interop Assembly.
Kindly let me know as to how resolve the same on the installed machine.
|
I think the misunderstanding is about what the interop assembly does. You said "converted into", but that is not at all what happened. The interop is simply the glue required between .Net and COM, like .Net class and function declarations. It doesn't do any real work - the function calls eventually need to go into the COM library, which has to be properly installed and registered.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": ".net, windows, winforms, interop, c# 2.0"
}
|
Change element button to image
I want to ask how to change an element button to an image using javascript when it's clicked? For example, from Submit button to an image of checked.
|
I use `svg` for demo, you can change it into `<img src="
var button = document.getElementsByTagName("button")[0];
button.addEventListener('click', function() {
button.innerHTML =`<svg width="50" height="50"></svg>`
});
<button>click</button>
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "javascript, html, vue.js"
}
|
Are input checkbox/radio/select vulnerable from XSS?
If i submit an input checkbox or radio or select, that have fixed content, can it be vulnerable from XSS? If yes, how? How to prevent?
|
XSS can happen when some elements of your page are generated using user-inputted information.
Look at the following snippet:
<input type="checkbox" value="<?php echo $variableContainingUserInput; ?>" />
If your user entered the following string:
" /> <script> window.location = "maliciouswebsite.com"; </script>
The resulting HTML would look like this:
<input type="checkbox" value="" /> <script> window.location = "maliciouswebsite.com"; </script>" />
This would, in fact, redirect the user to the malicious website in question.
In short, ANYTHING that is user-submitted could be dangerous if it ends up on any page of your site.
Here is a similar question on SO.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "php, input, xss"
}
|
How to multiply Vectors with Double?
I'm trying to make a sprite move back and forth with this equation here:
SpriteTexture sprite;
Vector2 position;
Vector2 p1 = new Vector2(0, 100),
p2 = new Vector2(0, 0);
double currentTime = 0, timestep = 0.01;
...
protected override void Update(GameTime gameTime)
{
position = currentTime * p1 + (1 - currentTime) * p2;
currentTime += timestep;
if (currentTime >= 1 || currentTime <= 0)
{
timestep *= -1;
}
}
I keep getting the error: "Operator '*' cannot be applied to operands of type 'double' and Microsoft.Xna.Framework.Vector2"
|
Try using `Vector2.Multiply` or converting your double to a float, and multiplying the `Vector2` by the `currentTime`
**1.**
position = Vector2.Multiply(p1, (float)currentTime) +
Vector2.Multiply(p2, (float)(1 - currentTime));
**2.**
position = (p1 * (float)currentTime) + (p2 * (float)(1 - currentTime));
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "c#, xna"
}
|
How to create alias with a caret^ command?
I have a workflow that first check `git diff` for specific file and then add it to stage.
git diff ..
^diff^add
I want to give these command a alias but this one doesn't work
alias da="^diff^add"
command not found: ^diff^add
|
You can't do it that way. History substitution (i.e. the handling the `^` and `!`) is done before alias expansion.
Use `fc -s` instead:
$ alias da='fc -s diff=add'
$ echo git diff
git diff
$ da
echo git add
git add
|
stackexchange-unix
|
{
"answer_score": 4,
"question_score": 2,
"tags": "bash, alias, history expansion"
}
|
Remove previous view controller text from back button
I would like to remove the "previous view controller's text" from my back button. As you can see on the example, i have "corals anatomy" that I would like to remove and have only "Back" if possible, even removing the chevron.
I have tried many like:
navigationItem.backBarButtonItem?.title = "Test"
navigationItem.backBarButtonItem = UIBarButtonItem(title: "Test", style: .Plain, target: nil, action: nil)
navigationItem.leftBarButtonItem?.title = "Test"
None of these worked.
Any ideas?
|
You can customise the backbar buttonItem by setting the leftBarButtonItem of a navigationItem in viewDidLoad() like below
override func viewDidLoad() {
super.viewDidLoad()
let backButton:UIBarButtonItem = UIBarButtonItem(title: "Back", style: UIBarButtonItemStyle.Done, target: self, action: "backBtnAction:")
self.navigationItem.leftBarButtonItem = backButton
}
@IBAction func backBtnAction(sender:UIBarButtonItem)
{
//your code here
}
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "ios, swift"
}
|
Java: How write a cast that specifies both a superclass and an interface?
I have something like this going on in my Java program:
void f(Object o) {
g(o);
}
<T extends MySuperClass & MyInterface> void g(T x) {
...;
}
How can I cast o so that this works? There seems to be no way to specify both a base class and an interface in variable declarations without using generics. I don't think generics will work here, because o is being created dynamically using reflection, so its actual class is not known at compile time.
(Yeah, I know this is a weird thing to want to do. But I actually do need functionality from both the superclass and the interface. I guess I could do all of the type checking at runtime with instanceof, but that just seems so Java 1.4...)
|
It seems to be there is no way to invoke a "raw" generic method. But you can create an object of raw type (the following conversion is, obviously, unsafe):
void f(Object o) {
Caster<?> c = new Caster();
g(c.cast(o));
}
class Caster<T extends MySuperClass & MyInterface> {
public T cast(Object o) {
return (T) o;
}
}
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 2,
"tags": "java, interface, casting, generics, superclass"
}
|
Proving a statement of the form $P\rightarrow(\lnot Q\lor \lnot R)$.
**Not looking for a proof of my question, only an answer to my question below.**
**Question:** I want to assume that $P$ is true for this proof, then if I assume that $Q$ is also true and conclude that $R$ is not true, does that prove this statement? Do I also have to prove that if $R$ is true then $Q$ is not? Thank you for the help.
For reference the logical form of the statement: Suppose $f:[a,b]\rightarrow\Bbb{R}$ is not constant on $[a,b]$, then $f$ is not continuous or $f([a,b])⊄\Bbb{Q}^c$.
|
You're right.
This is because $\lnot Q\lor\lnot R$ is equivalent to $Q\to \lnot R$. There is no need to prove $R\to\lnot Q$ if you prove the latter (due to the symmetry of $\lor$).
Also: $$\begin{align} P\to(\lnot Q\lor\lnot R)&\equiv (\lnot P)\lor((\lnot Q)\lor(\lnot R))\\\ &\equiv ((\lnot P)\lor(\lnot Q))\lor(\lnot R)\\\ &\equiv (\lnot(P\land Q))\lor\lnot R \\\ &\equiv (P\land Q)\to \lnot R.\end{align}$$
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 1,
"tags": "real analysis, logic, proof theory"
}
|
How can I determine why my trigger does not run?
create database triggers;
use triggers;
create table if not exists Customers(
custID INT unsigned not null auto_increment,
age int,
name varchar(30),
primary key(custID)
);
delimiter //
create trigger age_verify
before insert on customers
for each row
if new.age < 0 then set new.age = 0;
end if; //
insert into Customers
values (101, 27, 'James'),
(102, -40, 'Ammy'),
(103, 32, 'Ben'),
(104, -39, 'Angela');
select * from Customers;
For some reason my trigger in MySQL workbench does not run and when I run select * from customers it prints the negatives still and does not update the value. How can I debug this?
|
Your trigger is syntactically incorrect. Multiple-statement trigger code **must** be enclosed with BEGIN-END block:
delimiter //
create trigger age_verify
before insert on customers
for each row
BEGIN
if new.age < 0 then
set new.age = 0;
end if;
END //
DELIMITER ;
But in your particular case you do not need in BEGIN-END and DELIMITER, use simple
CREATE TRIGGER age_verify
BEFORE INSERT ON customers
FOR EACH ROW
SET NEW.age = GREATEST(NEW.age, 0);
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "mysql, sql, database, triggers, workbench"
}
|
JSON to struct conversion
This is the struct I have:
type Resource struct {
Name string `json:"name"`
Ranges struct {
Range []struct {
Begin int `json:"begin"`
End int `json:"end"`
} `json:"range"`
} `json:"ranges,omitempty"`
Role string `json:"role,omitempty"`
Type string `json:"type"`
Scalar Scalar `json:"scalar,omitempty"`
}
I don't know how to make fields in the JSON not `null`. For example, struct Range like that:
{
"name": "cpus",
"ranges": {
"range": null
},
"type": "SCALAR",
"scalar": {
"value": 1
}
}, {
"name": "mem",
"ranges": {
"range": null
}
|
That changes struct is resolved my problem:
type Resource struct {
Name string `json:"name"`
Ranges *Ranges `json:"ranges,omitempty"`
Role string `json:"role,omitempty"`
Type string `json:"type"`
Scalar *Scalar `json:"scalar,omitempty"`
}
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "json, go"
}
|
How to get accounts where their contacts has no email address?
I need to report on all accounts, whom have not a single contact with email.
e.g., an account may have any number of contacts, if neither of the contacts has an email, I want to see that in a report.
The regular filters don't provide me such - if I select a filter with: `email not to` \- I will get these accounts that have a contact with no email - but it does not ignore the contacts that do have an email. so if an account has 5 contacts, where one does not have an email - it will show on that report.
How to avoid that?
|
This is easily done with standard reporting using the relatively new feature for cross filters. Create an accounts report than add a cross filter for accounts without contacts, and then add a sub-filter that they must have an email.
**Example** !Cross Filter
|
stackexchange-salesforce
|
{
"answer_score": 8,
"question_score": 6,
"tags": "reporting"
}
|
ASP.NET MVC + Unity 2.0: lazy loading dependency properties?
What i want Unity 2.0 to do is to instantiate what i need by getting the new properties from the configurations all the time, a bit hard to explain.
Basically this is what i want to do:
global.asax
container.RegisterType<IBackendWrapper, BackendWrapper>(new InjectionProperty("UserIdent", (HttpContext.Current.Session == null ? new UserIdent() : HttpContext.Current.Session["UserIdent"] as UserIdent)));
What i want this to do is that whenever someone needs an IBackendWrapper, unity should then get the Session["UserIdent"] and populate the BackendWrapper with that information.
Right now unity only loads this information once and it always returns a new UserIdent even when i have an User ident stored in the session. Is there a way to get this behavior in Unity 2.0? or is it supported by another IoC framework like NInject?
|
Yes, it's supported in Unity. You need to register `UserIdent` with an `InjectionFactory` so it's evaluated on each resolve.
container
.RegisterType<UserIdent>(new InjectionFactory(c =>
{
return HttpContext.Current.Session == null
? new UserIdent()
: HttpContext.Current.Session["UserIdent"] as UserIdent;
}));
container
.RegisterType<IBackendWrapper, BackendWrapper>(
new InjectionProperty("UserIdent", new ResolvedParameter<UserIdent>())
);
The way you were registering it, `HttpContext.Current.Session` was being evaluated at the time you did the registration which is presumably in Global.asax before your session was set up.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 3,
"tags": "c#, .net, asp.net mvc 3, dependency injection, unity container"
}
|
Generation of an array of Random numbers with defined Min, Max, Mean and Stdev with given number of elements and error level
I'd like to generate an array of Random numbers with defined Min, Max, Mean and Stdev with given number of elements and error level. Is there such a library in C, C++, PHP or Python to do so? Please kindly advise. Thanks!
|
The Boost C++ random number library may do some of what you want, certainly you can with some distributions select the modal value of the distribution. That's all I've needed in my own code, so I've never investigated further. The library doesn't generate arrays - you would typically use a C++ `std::vector` to contain the results of random number generation.
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": -1,
"tags": "c++, python, statistics, generator"
}
|
How can I identify edible berries/fruit from poisonous?
How can I identify edible berries/fruit in the wide and avoid the poisonous varieties? Is there a general guideline that can be followed or is specific to each plant?
|
Eating berries and mushrooms is not recommended since there is no general pattern to identify poisonous ones (unless you're an expert on that topic). Even having a book with pictures of edible berries can be tricky as some poisonous ones are disguised as their edible counterparts.
Plants, on the other hand, should not be edible if the sap is milky. Milky sap often means poison. Take, for instance, Euphorbia which can look like cacti and trick you. So check the sap.
With insects it's easier. Not eating the flashy coloured, smelly or slow unwary moving ones is the rule of thumb here.
|
stackexchange-outdoors
|
{
"answer_score": 24,
"question_score": 42,
"tags": "survival, food, plants, foraging, edible"
}
|
What is the origin of the custom to have kids find the afikoman?
The instructions for _yachatz_ in every _hagadah_ that I have seen say to break the middle matzah in two (though, the thin paper hagadah I used in elementary school said, "break in half") and put the bigger piece (the school hagadah said "bigger half". It was only years later that I realized this is impossible!) away for the _afikoman_.
No instruction I have seen said anything about hiding it or having kids look for it and then "bargain" for a present or prize in order to return it.
So, when and why did this custom originate? Is there any Rav who may have been against this custom, perhaps, because of the scenario I mentioned or some other reasons? Personally, I felt extremely uncomfortable with the price bargaining, esp. on a Yom Tov. It sounded like the afikoman was a business deal.
|
The custom is mentioned in the Chok Yaakov on Shulchan Aruch O.C. 472 s.v. 2 who suggests a hint from the Talmud (although he doesn't actually suggest this is what the Talmud _means_ ) and says the purpose is to keep the children engaged and awake until then.
The Chabad custom is to not do the stealing. The Lubavitcher Rebbe writes that the reason is to not give the children a taste of the "thrill" of stealing.
An alternative for your to consider (the custom in my family, actually): The _adult_ does the hiding, and the "prize" is pre-arranged (lots of siblings, I suggest that all who are awake to search and do so be eligible). This has all the benefit without the attendant downsides.
|
stackexchange-judaism
|
{
"answer_score": 3,
"question_score": 4,
"tags": "passover, passover seder hagada"
}
|
Bootstrap form-group
I got two inputs inside a form-group, from bootstrap framework. My problem is if the first name gives error, the second name will give aswell the same error that gives on first name, and that is not what I want, how can I can avoid this problem?
<form id="containerForm" class="form-horizontal">
<div class="form-group">
<label class="col-xs-3 control-label">First name</label>
<div class="col-xs-4">
<input required type="text" class="form-control" name="firstName" placeholder="First name" />
</div>
<label class="col-xs-3 control-label">Last name</label>
<div class="col-xs-4">
<input required type="text" class="form-control" name="lastName" placeholder="Last name" />
</div>
</div>
</form>
|
This is not a complete answer but there are more post on Stackoverflow.com about this item.
Anyway as I always do I advise you to use server-side validation
But just to get you going see this example:
<
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "forms, twitter bootstrap"
}
|
Get state of TicTacToe board in Q-Learning
I'm just getting into reinforcement learning and q-learning, and I wanted to try and create a Tic-Tac-Toe AI. With a Q-Table, I need to find the "state" of the board, and I was having trouble finding a way to do this.
For extra clarification, a state is a number that represents the current board, including the value of each of the nine squares.
A board that looks like:
[[0, 0, 0],
[0, 0, 0],
[0, 0, 0]]
would be state 0, as it is the first board. Beyond this, I am not sure how to calculate the state of the board based on the array.
[EDIT] I'm coming here because I honestly don't know where to start; I can't find anything on the web, and if you dislike my question you could at least tell me why.
|
I think you need something like this.
import numpy as np
max_number = 10
L = [[1, 0, 0],
[0, 0, 0],
[0, 5, 0]]
L_1d = sum(L, [])
print(L_1d)
# [1, 0, 0, 0, 0, 0, 0, 5, 0]
degrees = max_number ** np.arange(len(L_1d))
print(degrees)
# [ 1 10 100 1000 10000 100000 1000000 10000000 100000000]
state = L_1d @ degrees
print(state)
# 50000001
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": -2,
"tags": "python, arrays, numpy, reinforcement learning, q learning"
}
|
How to get logged user name in MS Access 2007?
I want to get logged username in MS Access 2007, I wrote that code
txt = ENVIRON("username")
But it gives me the username of windows, I already create a users table tblUser
Please help
|
Solution :
in code button login i add a variable
Private Sub login_Click()
Dim TempID As TempVars
...
TempVars!TempID = Me.Username.Value
..
..
End Sub
Then in the other form i put a textbox Property Sheet of textbox -> Name 'txtwelcome', Control Source -> Expression Builder : [TempVars]![TempID]
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -2,
"tags": "database, ms access, vba"
}
|
ANT - JavaFX complex build.xml
I have a shared repository containing 5 .java files. ("d:rep/trunk/src")
I have a test folder for a JavaFX project, where I test the new codes by changing the files in the "src/" and running the JavaFX by compiling them from NetBeans. (d:test/JavaFXproject/src/gui/")
I am looking for the command which I could use to run all the JavaFX package possibly with the help of ant.
|
So after a lot of trying I finally figured out how to mix the .bat file and the ANT in an easy way:
SET sourceFolder= D:\REPOSITORY\.....
SET testFolder= D:\TEST\....src\
SET testRunFolder = D:\\TEST\...
SET excludeFiles = build.bat
robocopy %sourceFolder% %testFolder% /e /xf %excludeFiles%
echo Copy has finished
cd %testFolder%
ant -f %testRunFolder% jfxsa-run
echo Build has finished
This script is now copy the files to the right place and send them to compile and run.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "java, svn, ant, javafx, compilation"
}
|
forward proxy with apache
I need to setup apache to be able to do following (if possible):
When i requesting < i need to get content from < Main thing is i don't need to be redirected, but i need that on localhost domain request i can get content that was actually taken from google.com and browser still stay at localhost domain (i think apache can do that behind the scene)
|
This sounds like a job for ProxyPass
ProxyPass / "
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "apache, proxy"
}
|
Remove padding from qt4 application
I'm looking forward to remove padding completly:
!webkit qt
See that ugly space beetween a `qtwebkit element` and the window.
The layout is only a `vbox`, and inside it lives the `webkit view`,
I tried with:
vbox->setSpacing(0);
But no results.
|
spacing is a space between widgets in layout. You need to set contents margins with `setContentsMargins` method. Margins define space beetween container edge and layout content.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "qt4"
}
|
Как выпилить w3support.net из выдачи google
Дико бесит, что при поиске какой-то нужной инфы, половина выдачи гугла ведет на этот сайт, который, по сути, является переведенным на русский с помощью google translate, stackoverflow.com. Может есть какой-то способ в настройках google убрать его из выдачи. В идеале user-script или плагин который при заходе на w3support перекидывал бы на оригинальную тему на стеке.
|
Да, у google недавно появились такие возможности. Можно прямо зайти на страницу настроек и внести туда нужный сайт. Это уже работает на google.com, но вроде еще не работает на google.ru.
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 4,
"question_score": 2,
"tags": "google"
}
|
where are Android Chrome bookmarks?
What is the path of the bookmarks file for Chrome in Android 4.1.2? eg is it in the /sdcard/data directory or somewhere else?
|
As far as I know, they are stored under:
`data/data/com.android.chrome/app_chrome/default/bookmarks`
|
stackexchange-android
|
{
"answer_score": 2,
"question_score": 2,
"tags": "4.1 jelly bean, chrome for android"
}
|
How to give a value of class after using cut function with R
I would like to change a class defined by two values in brackets by the mean value of the corresponding classes. Here is the situation: I am using "cut" to split a variable into 10 classes.
data$classe_Ta<-cut(data$Ta,10,include.lowest = TRUE)
table(data$classe_Ta)
The result gives:
> [-12.4,-7.81] (-7.81,-3.25] (-3.25,1.31] (1.31,5.87] (5.87,10.4] (10.4,15] (15,19.6] (19.6,24.1] (24.1,28.7] (28.7,33.3]
59 490 2783 6028 7561 7051 5090 1400 211 15
I would like to replace [-12.4,-7.81], (-7.81,-3.25] ...in my data frame by the mean of each class; which means by -10.105, -5.53....which needs to be calculated for each class. Any suggestions in how to do that would be much appreciated. Thanks in advance!
|
We could use `str_extract` to extract all the numeric elements, convert the string to `numeric`, get the `mean`.
v1 <- sapply(str_extract_all(levels(data$classe_Ta),
"-?[0-9]+(\\.[0-9]+)?"), function(x) mean(as.numeric(x)))
data$Mean <- v1[as.numeric(data$classe_Ta)]
### data
set.seed(24)
data <- data.frame(Ta = sample(-50:100, 20, replace=TRUE))
data$classe_Ta<-cut(data$Ta,10,include.lowest = TRUE)
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "r, class, cut"
}
|
Getting JSON for Angular 2 from HTTP remote server fails, but succeeds localy
I'm trying to read a JSON file using htttp.get in Angular2.
When I use a file stored **localy** on my project, **it works OK**.
But - when I use a **remote server** , with **exactly** the same file, I get the following error:
> **404 - Not Found Collection 'undefined' not found**
Browsing to ` , I can see the file on any browser.
Here is my typescript code for getting the file:
private url = '../my.json'; <--- This works
private url = ' <--- This throws the error
return this.http.get(this.url)
.map(this.extractData)
.catch(this.handleError);
Thanks in advance.
|
`Not found collection` error suggest that you have used `angular-in-memory-web-api` before. You need to remove everything related to that from your project, that would equal removing from `imports` in your `NgModule` the equal of the following:
InMemoryWebApiModule.forRoot(InMemoryDataService)
so that you are able to use external api and db.
Otherwise your code shouldn't change, but if you want, following **this tutorial** should help you.
|
stackexchange-stackoverflow
|
{
"answer_score": 13,
"question_score": 4,
"tags": "angular, angular http"
}
|
file size validation without a gem in ruby on rails
I am new to ruby on rails. How to validate the size of a file uploaded with file_field form without using paperclip, carrierwave or other gems in ruby on rails?
|
To do this, you will have to write a custom validation in your model (the model which has the file), as follow:
validate :image_size_conformance
private
def image_size_conformance
errors[:image] << "should be less than 500KB" if image.size > <the max size you want>
end
Note that the `:image` in `errors[:image]` should be the name you are calling your `image` column ( well, I guess this will naturally be `image`).
Also note that the validation example I have above only checks for the size. You can use it as a guide to write validation for any other property you want. Hope this helps...
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -1,
"tags": "ruby on rails"
}
|
How to configure DNS to point main domain at Firebase hosting, but not subdomain
I currently have a website hosting on CPanel which consists of subdomain.example.com and example.com. I'd like to keep the subdomain hosted where it is, but move the main domain to be hosted with Firebase. I'm struggling to work out the required DNS changes to make this work.
If it is relevant, the domain was purchased from 123-reg and points to custom nameservers on my CPanel server.
I read this answer, but I've also read that Firebase no longer allows CNAME records and has to be A records.
Would it work to have an A record pointing to the IP addresses supplied by Firebase and a CNAME record for the subdomain pointing to the server where it is currently hosted?
|
You need to create two A records:
* domain.com -> Public IP address of your first server
* sub.domain.com - Public IP address of your second server
|
stackexchange-serverfault
|
{
"answer_score": 2,
"question_score": 0,
"tags": "domain name system"
}
|
Setting oninput event with JavaScript
The HTML5 `oninput` event is supported by some modern browsers, including Firefox 3.X
However, strangely, it only seems to work with inline JavaScript:
<input id = "q" oninput="alert('blah')">
When I try to set it using JavaScript code, it doesn't fire.
var q = document.getElementById("q");
q.oninput = function(){alert("blah");};
Is this just a bug in Firefox, or is there some reason this happens?
|
After downloading FireFox v3.6.27 and doing some test and search. I found my previous answer was wrong.
What I got is:
> the oninput event property is supported in Firefox from version 4.
So to add a event listener in this case, you can do either
<input id = "q" oninput="alert('blah')">
or
q.addEventListener('input', function(){alert("blah");}, true);
But I prefer the later way. You can find reasons in addEventListener.
Also a similar function in IE attachEvent.
|
stackexchange-stackoverflow
|
{
"answer_score": 19,
"question_score": 14,
"tags": "javascript, html, firefox, dom events"
}
|
Explanation for the assumption of the proof
$(x+y)^r < x^r + y^r$ whenever $x$ and $y$ are positive real numbers and $r$ is a real number with $0 < r < 1$.
In the solution it says it is safe to assume that $x+y=1$. I don't see any reason why this is the case... Why is it safe to assume $x+y=1$? If so how does this help proving this statement?
Thanks!
|
It is safe because you can divide both sides of the inequality by $(x+y)^r$, then substitute $x'=\frac{x}{x+y}, y'=\frac{y}{x+y}$ and have the same inequality with $x'+y'=1$. It looks like it helps by making the LHS be $1$, but without seeing the proof it is hard to comment further on how it helps.
|
stackexchange-math
|
{
"answer_score": 7,
"question_score": 5,
"tags": "inequality, discrete mathematics"
}
|
Stop an Increment
I have the Y axis increasing very few frames with the following line:
Bullets.center = CGPointMake(Airplane.center.x, Airplane.center.y + Y);
How can I stop increasing Y when an if statement is true?
|
Basically, I'd say "don't add Y if the statement is true", but I may be misunderstanding your question, it seems quite simple. A ternary operator in the CGPointMake will take care of it:
Bullets.center
= CGPointMake(Airplane.center.x, Airplane.center.y + (CONDITION ? 0 : Y));
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -6,
"tags": "ios, objective c, cgpoint"
}
|
Alternate elements of a vector with multiple NAs
I have a character vector in R, and want to make a new vector with multiple NAs between the elements of the character vector. To simplify, the character vector is:
cv <- c( "A", "B", "C" )
Let's say we just want 3 NAs (actually need much more). Desired output vector would be:
"A", NA, NA, NA, "B", NA, NA, NA, "C", NA, NA, NA
I'm guessing this has been asked before, but it's very difficult to search for. I've tried various permutations and combinations of rep and rbind with no success. Be gentle; my first question :-)
|
Use `sapply` to concatenate c(NA, NA, NA) to each element of `cv` so that for each element of `cv` we get a 4-vector. `sapply` will arrange these into a 4 x n matrix (where n is the length of `cv`) and `c` on the left will unravel that matrix into a vector.
c(sapply(cv, c, rep(NA, 3)))
## [1] "A" NA NA NA "B" NA NA NA "C" NA NA NA
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 3,
"tags": "r, vector"
}
|
Not able to find roots of linear 2nd order homogeneous dif. equation
I am trying to find the roots of the differential equation $y''+7y'+6y=0$.
I assume the following:
$$ y=e^{rx} \\\ y'=r*e^{rx} \\\ y''=r^2*e^{rx}. $$ Then I substitute that into the dif. equation: $$ r^2*e^{rx}+7*(r*e^{rx})+2*e^{rx}=0 \\\ e^{rx}*(r^2+7r+2)=0. $$ And I end up with the following quadratic equation which I need to find the roots of: $$ r^2+7r+2=0. $$
It's impossible to factor, so I tried to use the quadratic formula but end up with wrong results for r: $$ r=((-7+\sqrt{7^2-4*1*2})/(2*1))=-0.298 \\\ r=((-7-\sqrt{7^2-4*1*2})/(2*1))=-6.702. $$ I used the same method for all other linear 2nd order homogeneous differential equations where I got correct results. But this time, I messed up.
What did I do wrong?!
|
Your original equation is: $$y''+7y'+6y=0$$
After you substitute $e^{rx}$ you write:
$$r^2e^{rx}+7re^{rx}+\color{red}{2}e^{rx}=0$$
The $\color{red}{2}$ should be a $\color{green}{6}.$
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 1,
"tags": "ordinary differential equations, roots, quadratics"
}
|
Type FBSessionState does not conform to protocol AnyObject
Hi guys trying to convert objective c facebook custom login to swift so I am creating a NSDictionary to store the status and session , but I am not able to add FBSessionState object in NSDictionary My Code is below
FBSession.openActiveSessionWithReadPermissions(permission, allowLoginUI: allowLogin, completionHandler: { (session , status, error) -> Void in
var dict : NSDictionary = NSDictionary ()
dict.setValue(status, forKey: "status")
})
I get Type FBSessionState does not conform to protocol AnyObject error
|
I am not sure but maybe NSDictionary does not accept enum value. I suggest you to use 'Dictionary' instead of `NSDictionary`
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "facebook, swift, xcode6"
}
|
Setting a padding / margin with jQuery
How can I set a padding with multiple values using jQuery?
This doesn't work:
$('#el').css({ 'padding': [top, right, bottom, left] });
|
Space-separated values as a strings.
$('#el').css({ 'padding': '1px 2px 3px 4px' });
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -1,
"tags": "javascript, jquery, css"
}
|
Error when try to run my project in cmd
I have a structure code like this :
!enter image description here
I want to run my program using mcd using javac, like this : javac ListenerZipFile.java. The result like :
!enter image description here
Why i can't run my program?
|
There are 2 problems here.
1. Incorrect directory location for compiling packed classes.
2. classpath no set correctly.
Consider you have, source_dir = D:\~\~\src, jar_location = D:\~\~\lib and package is com.example then your steps to compile are:
* cd to $source_dir
* $source_dir> set classpath=.;jar_location
* $source_dir> javac com\example\Examples1.java or $source_dir> javac com\example\\*.java
As per path shared, command to compile should be :
cd C:\ListenerZipfile\src
javac -cp .;C:\ListenerZipfile\lib\*.jar com\sigma\main\ListenerZipFile.java
Command to run java program with above path:
java -cp .;C:\ListenerZipfile\lib\*.jar com.sigma.main.ListenerZipFile
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "java, javac"
}
|
Should I use a separate table to store image file names?
I am learning about database design and I'm writing a Java GUI program with a back-end database. The main table in my database stores a different product in each row. I have some columns such as: product_id (PK), price, stock_quantity, etc. I also have eight columns that store the names of the file names for that product's images: img_file_1, img_file_2 ... img_file_8. The Java program uses those file names to find the images to display on the screen for that product.
Is this poor design? Should I be storing these file names in their own table, and adding a foreign key to that table in my main table?
The program works fine as is, but I want to make sure I am learning good habits.
|
If each image has a specific purpose then this would be OK but your column names should be more specific, such as img_thumbnail, though I would still use a separate table with columns that carry information about each images use.
The better design, especially if the images do not have specific well differentiated uses, is to follow first normal form and have the images in a separate table. This allows cleaner storing of extra data about the images should you need to later, and so forth.
|
stackexchange-dba
|
{
"answer_score": 4,
"question_score": 6,
"tags": "database design"
}
|
How to keep the reference to an array after manipulation?
How do I keep the reference to an array after an items is appended?
**Updated code example** , because the prior example didn't seem to be clear enough.
class ViewController: UIViewController {
var numbers = Numbers.singleton.numbers
override func viewDidLoad() {
print(numbers.count)
Numbers.singleton.add(1)
print(numbers.count) // prints 0
print(Numbers.singleton.numbers.count) // prints 1
}
}
class Numbers {
static let singleton = Numbers()
var numbers: [Int]!
private init() {
numbers = []
}
func add(number: Int) {
numbers.append(number)
}
}
|
Arrays in Swift don't have "references". They are structs, and a struct is a value type. Your (badly named) `arrayRef` is a separate _copy_ , not a reference to `self.array`.
Moreover, there is no good reason to want to do what you (seem to) want to do. To have two simultaneous references to a mutable array would be unsafe, since the array can be changed behind your back. The Swift design is sensible; use it, don't subvert it.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "ios, arrays, swift"
}
|
Running against Edge on selenium-standable server
I am trying to run Edge in selenim-standalone server on my Mac.
I’ve followed the CLI command to install but when I try to with wdio project I get the following error:
ERROR webdriver: org.openqa.selenium.SessionNotCreatedException: Unable to create new service: EdgeDriverService
Started my server using this command:
selenium-standalone start --drivers.chrome.version=98.0.4758.80 --drivers.chrome.baseURL=
I have not had much luck finding another person having the same issue.
* Server is running with node 14
* Wdio project is running with node 16
any thoughts on what it might be?
|
Issue resolved.
I ended up running the install command in node v16 and that worked. I did have to delete selenium-server jar file the first time because it was corrupt. Though I re-ran the install command again it worked.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "selenium, selenium webdriver, microsoft edge, webdriver io"
}
|
What does ‘play the pill’ mean?
There was the following sentence in Maureen Dowd’s article titled “Taxing Times for Obama” in the New York Times May 18 issue. -
> “Asked about that on Thursday, Obama might have tried a little **J.F.K. wit** to dismiss the ridiculous assertion. Instead, he **played the pill** , as he too often does, huffily telling reporters, “Well, I’ll let you guys engage in those comparisons, and you can go ahead and read the history, I think, and draw your own conclusions.”
What does “play the pill” mean? I was unable to find this expression as an idiom in any of Cambridge, Oxford and Merriam Webster Dictionary, nor the incidence in Google N Gram.
At the same time, what does ‘J.F.K. wit’ mean? What is it like for example?
|
A _pill_ is “a disagreeable or tiresome person,” often because he is a square (overly conventional) or a Debbie Downer (overly negative).
_Playing the pill_ means that he chose the role of a pill, rather than somebody witty and charismatic – like former president John F. Kennedy. It's not idiomatic, but merely colorful language.
|
stackexchange-english
|
{
"answer_score": 5,
"question_score": 2,
"tags": "meaning, idioms"
}
|
lxml-html read produces empty list Python 3.6.4
I am trying to read the two line elements for STRaND-1 from this link: < so I can track it from a ground station I'm building. I don't really understand how to use the xtree.xpath command an I'd like to learn how. I'm trying the following code that I found from a similar question asked on here a while ago:
import numpy as np
from lxml import html
import requests
line_number = 50
for word in range(0,5):
page = requests.get(" % word)
tree = html.fromstring(page.text)
print (tree.xpath("//b/text()")
This should print the code between the elements of the html page right? How do I just print from a certain line? Expecially when there is no html prefix before the text that I want?
Thanks for your time.
|
Try below solution to get required data:
import requests
url = "
response = requests.get(url)
page_content = response.text
all_lines = [line.strip() for line in page_content.split("\n")]
for index, line in enumerate(all_lines):
if line == "STRAND-1":
first_value = all_lines[index + 1]
second_value = all_lines[index + 2]
break
print(first_value, "\n", second_value)
Output:
1 39090U 13009E 18037.58367953 .00000016 00000-0 21168-4 0 9998
2 39090 98.5328 245.5663 0008674 331.4360 28.6349 14.35009671259097
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 3,
"tags": "python, python 3.x, parsing, xpath, lxml"
}
|
How can I use variables as field names in POST/PATCH request body in Javascript?
async onSubmitConditionDuration() {
var param = (this.state.health_condition+"_personal_age")
try {
axios.patch(URL,
{
param: this.state.condition_duration, //param is a variable that represents a field name at the endpoint(URL)
})
.then((response)=>{
console.log(response.status);
})
.catch((errors) => {
console.log(errors);
})
}
catch(errors){
console.log(errors);
}
}
I'm trying to have field names as variable in the json body of my request so that fields can be dynamically updated based on variables' values. By using the above syntax ,the patch request fails to update the field represented by the value stored in 'param'.
How can this be done in Javascript?
I'm working in a react native app
|
You can use the `[]` syntax:
var param = (this.state.health_condition+"_personal_age")
var object = {
[param]: this.state.condition_duration,
}
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 2,
"tags": "javascript, rest, react native"
}
|
replace action attribute value in form
I am trying to change/replaced the action attribute in a form but am having a problem with the selector. I want to change the action to ShoppingCart.asp?recal=Y
Here is the markup for the form.
<form onsubmit="if (typeof(Update_Hidden_State_Fields)=='function') Update_Hidden_State_Fields(); if (this.submitted) return false; else {this.submitted=true; return true;}" action="ShoppingCart.asp" name="form" method="POST">
Here is the Jquery I have so far.
$("[name='form']")
.attr('action', function(jj,ww){
return ww.replace('ShoppingCart.asp','ShoppingCart.asp?recal=Y');})
|
$("[name=form]").attr("action", "ShoppingCart.asp?recal=Y");
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "jquery"
}
|
How to resize the UITabBarController in iOS?
I used `UITabBarController` in my iOS app. As you know , that `UITabBarController's` size is fix the screen of below. I want to resize that `UITabBarController` with some CGRect because i don't want to fix the screen size.
Is there anyway to do like that?
Thanks in advance.
|
You can update the size, by accessing tab bar frame -
CGRect tabBarFrame=self.tabBar.frame;
// Update the frame values
tabBarFrame.origin.y =;
tabBarFrame.origin.x =;
tabBarFrame.size.hieght =;
tabBarFrame.size.width =;
self.tabBar.frame = tabBarFrame;
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "ios, uitabbarcontroller"
}
|
What was the first chess engine that could beat the world champion on a standard desktop?
What was the first chess engine that could beat the world chess champion when running on a standard desktop playing at standard speeds (i.e. not blitz chess)? For concreteness, say a $1000 PC.
|
Deep Blue) was a super computer. In the 2006 match, Kramnik was defeated by Deep Fritz) that everybody could buy.
> In a November 2006 match between Deep Fritz and world chess champion Vladimir Kramnik, the program ran on a computer system containing a dual-core Intel Xeon 5160 CPU, capable of evaluating only 8 million positions per second, but searching to an average depth of 17 to 18 plies in the middlegame thanks to heuristics; it won 4–2.[31][32]
(source)
|
stackexchange-chess
|
{
"answer_score": 15,
"question_score": 13,
"tags": "engines, human versus machine"
}
|
Grass Particle System
I recently watched the grass essentials video from andrew price at blender guru and he said that it would be easier to use objects of grass in a particle system rather than strands. How would you get your object and put it in a particle system?
|
!Render Tab
In the particles tab go down to the " **Render** " section.
Then Select the option " **Group** " and select the group you want to use.
|
stackexchange-blender
|
{
"answer_score": 3,
"question_score": 1,
"tags": "particles"
}
|
connecting to redistogo gives error:-
Trying to connect to redis thru the following redistogo credentials gives error.
var redisClient = require('redis').createClient({
host: 'birdeye.redistogo.com',
port: 1222,
db: 'redistogo',
pass: '012345c2f2402f7878588dd5fb129'
});
Getting error:-
Error Error: Redis connection to 127.0.0.1:[object Object] failed - getaddrinfo ENOTFOUND
|
var redisClient = require('redis').createClient( 1234, 'birdeye.redistogo.com', {detect_buffers: true});
connects.
> redis.createClient(port, host, options)
>
> Create a new client connection. port defaults to 6379 and host defaults to 127.0.0.1. If you have redis-server running on the same computer as node, then the defaults for port and host are probably fine. options in an object with the following possible properties:
from node_redis
|
stackexchange-stackoverflow
|
{
"answer_score": -1,
"question_score": 0,
"tags": "connection, redis, redistogo"
}
|
How to preview page when doing javascript developement with Vim
I'm learning to do javascript development with Vim I would like to know how other people do to preview the result of your javascript code I can of course manually launch and refresh a browser but there must be an automatic way
|
I use xdotool[1] to automate the "switch focus to browser, hit f5" part. All this is in a shell script, say reload.sh, and I call it from vim by mapping like this:
:nmap <C-L> :!reload.sh<CR>
reload.sh (untested, you may need to massage it a bit):
#!/bin/sh
WID=`xdotool search "Mozilla Firefox" | head -1`
xdotool windowactivate --sync $WID
xdotool type f5
[1] <
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "javascript, vim"
}
|
Using Array Values in Mysql Query
I have a query to select a limited result based on a set parameter:
$query = $this->db->query ("
SELECT
p.product_id,
p.quantity
FROM {$this->prefix}product p
LEFT JOIN {$this->prefix}product_to_category pc
ON (p.product_id = pc.product_id)
WHERE pc.category_id = '3'
AND p.status = '1'
ORDER BY p.quantity DESC
LIMIT 0, 4");
This returns the 4 products with the highest quantity in stock where the product's `category_id` = 3.
I'd like to have this use an array of category id's as opposed to a static one. ie:
`$categories = array(2, 6, 22, 33, 34, 83, 220, 222, 886, 897);`
Is this possible?
|
You can convert the array to a string and use that in your query. Please note that the below assumes that $categories are already safe and wont contain malicious input. If this is not the case you'll need to clean the input.
$categoriesClause = implode(",",$categories);
$query = $this->db->query ("
SELECT
p.product_id,
p.quantity
FROM {$this->prefix}product p
LEFT JOIN {$this->prefix}product_to_category pc
ON (p.product_id = pc.product_id)
WHERE pc.category_id IN ($categoriesClause)
AND p.status = '1'
ORDER BY p.quantity DESC
LIMIT 0, 4");
|
stackexchange-stackoverflow
|
{
"answer_score": 7,
"question_score": 3,
"tags": "php, mysql, sql, arrays"
}
|
Key encyption, front-end back-end question
I have a front end which has some api credentials which are needed to receive information for the front-end. I also want to store these credentials in a database so that the user does not need to enter these api credentials with every log in, rather the api credentials are 'there'. How should these api keys be stored in the back end and then de-crypted in the front-end?
|
> How should these api keys be stored in the back end and then de-crypted in the front-end?
If the credentials are to be stored in a database as encrypted, maybe you could use the database-native feature to encrypt the data as the simplest option. That depends on the database used.
Transport between backend and frontend should be encrypted using the https.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "django, database, encryption, secret key"
}
|
Delete line from 2D array in Python
I'm have a 585L, 2L numpy array in Python. The data is organized like in this example.
0,0
1,0
2,1
3,0
4,0
5,1
...
I would like to create an array deleting all the lines where 0 is present on the seconds column. Thus, the final result pretended is:
2,1
5,1
I have read some related examples but I'm still struggling with this.
|
Since you mention your structure being a numpy array, rather than a list, I would use numpy logical indexing to select only the values you care for.
>>> import numpy as np
>>> x = [[0,0], [1,0], [2,1], [3,0], [4,0], [5,1]] # Create dummy list
>>> x = np.asarray(x) # Convert list to numpy array
>>> x[x[:, 1] != 0] # Select out items whose second column don't contain zeroes
array([[2, 1],
[5, 1]])
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 2,
"tags": "python, arrays, multidimensional array"
}
|
postfix default alias used even when I have other aliases
I tried adding a rule to /etc/aliases which would send a message to /dev/null if it was sent to a particular alias:
fooname: /dev/null
I have postfix set up with a default address for a particular domain in my /etc/postfix/virtual file:
@mydomain.com realuser
I have multiple domains mapped to this server. I've found that if I send a message to "[email protected], [email protected], [email protected], [email protected]" I will receive the first, second, and fourth messages, but I won't receive the third.
The upshot is that entries in /etc/aliases don't seem to short circuit the email sending.
How do I send messages for particular aliases to /dev/null while still keeping the default alias?
|
Sorry to answer my own question again, but after a couple hours of struggle I figured out what to do:
First, I added the following to the main.cf:
smtpd_recipient_restrictions = check_recipient_access hash:/etc/postfix/access_usernames, permit_mynetworks, reject_unauth_destination
Then I added entries like the following to the access_usernames file:
badaddress@ REJECT
Then I did "postmap access_usernames" and "postfix reload".
The access_usernames file can contain any number of email addresses to reject and it seems to work fine with the default alias!
|
stackexchange-unix
|
{
"answer_score": 2,
"question_score": 3,
"tags": "alias, postfix"
}
|
IFTTT & Raspberry pi: Assigning value from terminal to IFTTT web request
I made a Webhook Applet in IFTTT, which would send me a mail when "print" action triggers
In the URLs JSON body I can give values like this
curl -X POST -H "Content-Type: application/json" -d '{"value1":"9"}'
What I want to do is find my public ip address and pass it as value1.
I found my IP by
value1=$(dig +short myip.opendns.com @resolver1.opendns.com)
echo $value1
How can I pass value1 to above URL
I tried
'{"value1":"$value1"}'
'{"value1":{{$value1}}}'
'{"value1":{{value1}}}'
P.S: I have zero basic knowledge in shell script. This is the first time i'm doing it
|
Expressions inside single quotes do not get expanded in the shell, they are taken as literal. That means, if you store your IP address in a variable called `ip` like this:
ip=$(dig +short myip.opendns.com @resolver1.opendns.com)
and you put that in single quotes, it won't get expanded:
echo '$ip'
$ip
whereas if you put it in double quotes, it will get expanded:
echo "$ip"
192.80.136.233
So, you need double quotes, but that will cause a problem because you need double quotes around your JSON strings, so you need to escape those by prefixing them with backslashes. So, you want:
curl -X POST -H "Content-Type: application/json" -d "{\"value1\":\"$ip\"}"
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "shell, raspberry pi, ifttt"
}
|
ActiveMQ-CPP prefetchSize 3.2.2
So far I am unable to get the prefetch size to function.
I have tried:
`mySession->createQueue([quename]?consumer.prefetchSize=5);
tcp://localhost:61616?prefetchPolicy.all=5`
I am using the cms::Connection and cms::Consumers. Would I have to switch over to the activemq::core?
Thanks
|
The version you are using is to old, the v3.2.4 should address the application of destination options, and I think you need to go to v3.4.0 if you want to use prefectchPolicy.all
The other option is to cast the connection to an ActiveMQConnection and set the policy options directly before creating the consumer.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "activemq cpp"
}
|
how to get the categories for a single post in a hierarchical way
The question is simple.
Imagine that I have a post named 'Single Post' which is inside the category 'sub-cat' which is a child of 'parent-cat' which is a child of 'super-cat'. What I need to do is to display all the related categories within the post page in the following order:
super-cat > parent-cat > sub-cat > Single Post
|
<?php
the_category( ' > ', 'multiple', $post->ID);
echo ' > ';
the_title();
?>
This works correctly when the post is in just one category. But if it's in multiple categories, or if the category parents are also selected — in your case, if the post is also in super-cat and parent-cat — then it displays those categories twice.
So this is probably not going to do it for you.
I suspect some of the breadcrumb type plugins might have solved this though.
|
stackexchange-wordpress
|
{
"answer_score": 3,
"question_score": 1,
"tags": "categories, hierarchical"
}
|
array on mips from C to MIPS?
B[8] = A[i–j];
how do you use the arrays while trying to convert into MIPS the above C expression? i thought something like :
lw $t0, 16 ($s7)
sub $t1, $s3, $s4
lw $t2, $t1 ($s6)
considering that
$s6 holds A
$s7 --- B
$s3 ---- i
and $s4 -- j
but am not sure about how to do the calculationg to actually get on A [i-j]
any suggestion?
|
Well, first off, `16($s7)` is wrong. Assuming that B and A are arrays of 32-bit integers, the offset is `8 * 4 = 32`.
Next, simply add `$t1` and `$s6` and load from there.
lw $t0 32($s7)
sub $t1 $s3 $s4
add $t1 $s6 $t1
lw $t2 0($t1)
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "mips"
}
|
std::endl, is there an equivalent in Python? (return + flush)
In C++, `std::endl` is used to add a return and flush the string. In Python, there is no need to use this special functionality, except for specific uses.
One of the uses that may justify its use is when the output is redirected to a file, for example:
outfile = open("output_file.txt", 'a')
sys.stdout = outfile
print("Something")
In this case, the file does not show its content unless the file is closed (`outfile.close()`) or manually flushed (`outfile.flush()`).
If an equivalent of `std::endl` from C++ exists in Python, it could both write the line and flush the file.
I doubt that this functionality exists, but I ask this question to be sure.
Thanks :)
|
`os.linesep` is the platform-dependent line separator. If you want something shorter, you can give it an alias when you import it, e.g.:
from os import linesep as endl
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": -4,
"tags": "python, c++, endl"
}
|
mysql Join table
I'm trying to join these tables:
table1 table2 table3
-------------------------------------------------
table1Id table2Id table3Id
name table1Id table2Id
name2 name3
How do I join these 3 tables?
for example something like this: PS. Example is not working
SELECT table1.name, table2.name2 , table3.name3 from table3
left join on(table2.table2Id=table3.table2Id)
left join on(table1.table1Id=table2.table1Id) group by table1.table1Id
|
The table name must be specified after `left join`. Also there is no need to use `group by` in this scenario.
SELECT table1.name, table2.name2 , table3.name3
from table3
left join table2
on table3.table2Id = table2.table2Id
left join table1
on table2.table1Id = table1.table1Id
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "mysql, sql, select, left join"
}
|
Cannot change Numpy array's value?
I write a simple code list below:
data = np.array([[1,1,1],[2,3,4]])
xdata = [i + 0.1 for i in data[0]]
print(xdata)
data[0] = xdata
print(data)
But the result I get in console i
[1.1, 1.1, 1.1]
[[1 1 1]
[2 3 4]]
While I expect it to be
[1.1, 1.1, 1.1]
[[1.1 1.1 1.1]
[2 3 4]]
Why I can't change the value in NumPy array this way?
|
Create your array like this
data = np.array([[1,1,1],[2,3,4]], type=np.float64)
and it should work. Since you create the array with only integers, its data type becomes np.int64, which means that it can only hold integers.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "python, numpy"
}
|
Firebase Auth Anonymous Sign in possible error cases
When signing in an anonymous user with firebase on Android, the `signInAnonymously` method currently returns a Task. This Task holds an AuthResult, which can be used to check if the user authentication was successful via the `.isSuccessful` method. However, the Firebase docs also handle the error case when the authentication was not successful, see example firebase auth repo. Now I wonder what could be possible errors for an unsuccessful login when using the `signInAnonymously` method?
Already checked some docs but couldn´t find any pieces of information about this.
|
> This Task holds an AuthResult, which can be used to check if the user authentication was successful via the .isSuccessful method.
It's always recommended to check if the Task is not successful instead of assuming that everything works fine.
> Now I wonder what could be possible errors for an unsuccessful login when using the signInAnonymously method?
A common Exception for an unsuccessful sign-in might have the following message:
> This operation is restricted to administrators only.
This FirebaseAuthException occurs when you forgot to enable Anonymous Authentication in the Firebase Console.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "android, firebase, kotlin, error handling, firebase authentication"
}
|
Two different usages of なんぞに?
I'm reading a manga in which I've come across the following exchange (for context the second character, B, has just beaten up A in a fight):
> A: ...
>
> B: !!
My understanding of was always that it could be used similar to "Why", so the first comment it simply something along the lines of "Bastard, idiot, why...", but I've no idea how it then functions in the response from B.
|
directly after a noun is a variation of //, used to make light of something and express a negative/derogatory feeling. It does not contain the meaning of _why_. sounds old-fashioned and is typically heard in fictional old man's speech.
In this conversation, is a derogatory word and even strengthens it, so it's okay to translate as "a bastard like you". B repeated to emphasize the irony that A was defeated by that "bastard." ("And you are defeated by that bastard!")
meant _why_ in archaic Japanese (see examples from a ), but it's almost never used in that way in modern Japanese.
|
stackexchange-japanese
|
{
"answer_score": 4,
"question_score": 6,
"tags": "meaning"
}
|
How to limit execution time of a function call?
There is a socket related function call in my code, that function is from another module thus out of my control, the problem is that it blocks for hours occasionally, which is totally unacceptable, How can I limit the function execution time from my code? I guess the solution must utilize another thread.
|
I'm not sure how cross-platform this might be, but using signals and alarm might be a good way of looking at this. With a little work you could make this completely generic as well and usable in any situation.
<
So your code is going to look something like this.
import signal
def signal_handler(signum, frame):
raise Exception("Timed out!")
signal.signal(signal.SIGALRM, signal_handler)
signal.alarm(10) # Ten seconds
try:
long_function_call()
except Exception, msg:
print "Timed out!"
|
stackexchange-stackoverflow
|
{
"answer_score": 51,
"question_score": 97,
"tags": "python, multithreading"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.