INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
matrix class C++ as matlab operator overload
I have a class that defines a matrix of dimensions mxn like this:
class Matrix{
protected:
int m;
int n;
double* mat:
public:
// accessors, constructors, destructors, etc.
void assignvalue(int, int, double);
}
Right now if I need to assign a value on position i,j I have a function assignvalue that takes the positions i, j and does the magic and assigns a double value to that position. However, it would be really nice if I could assign a value like you do in matlab or in R.
mymatrix(i,j) = 1.0;
Can you give me a hint on what operator(s) I need to overload? Thanks.
|
Assuming your `m` represents the height of your Matrix and `n` represents the width, overloading `operator()` this way should do the trick:
double& Matrix::operator()(size_t i, size_t j)
{
return mat[i*m+j];
}
const double& Matrix::operator()(size_t i, size_t j) const
{
return mat[i*m+j];
}
This way, you can write something like this:
void f(Matrix & mymatrix ) {
mymatrix(2, 3) = 5.0; // Calls the first function
// ...
}
void f(Matrix const & m) {
double a = m(1, 5); // Calls the second one
//...
}
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "c++, overloading, operator keyword, numerical methods"
}
|
MySQL: Search range of strings with slash
I have a varchar field with the following data:
Interface
Gig1/0/1
Gig1/0/3
Gig1/0/5
Gig1/0/10
Gig1/1/11
I am trying to do a search (BETWEEN).
Select * from test1 where Interface Between "Gig1/0/1" and "Gig1/0/5"
Returns all the records except for Gig1/1/11
|
What about using the substring_index function?
select substring_index(fieldname,'/',-1) as v from tablename where v between 1 and 5
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "sql, mysql"
}
|
File storage not working. Laravel 5
I'm trying to save a `.txt` file in a folder named `txts` inside my public folder but the method i'm using is not working:
$txt_nombre = 'nomina_'. $extras['desde'] .'_'. $extras['hasta'] .'.txt';
$txt_contenido = '';
foreach ($personal as $per) {
$txt_cadena = 'BNC ' . $per->cuenta_nomina . ' ' . $per->netos . ' ' . $per->cedula_identidad;
$txt_contenido .= $txt_cadena . "\n";
}
Storage::put('public/txts/'. $txt_nombre, $txt_contenido);
It doesn't even throw an error, my function keeps running but the file is not being saved. Any idea why?
|
According to the Documentation
> By default, the public disk uses the local driver and stores these files in storage/app/public.
Looking at your code, assuming that you haven't changed default configuration, your file should be created in `storage/app/public/public/txts/` folder.
I am not sure how Laravel's Storage abstraction handles non-existing folders so you might want, for test, try using just `Storage::put('file.txt', "content")` and see if it's being created in `storage/app/public` folder
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 2,
"tags": "laravel"
}
|
RMySQL cannot insert new data
I try to insert new data to MySQL using RMySQL. Only for this case I always fail and always get the same warning message. The message was:
Warning message:
In value[[3L]](cond) : corrupt resultSet, missing fieldDescription
Although it just a warning, I never find my data show on MySQL.
Complete code and warning message shown as below:
 [ line : 1 ]. & Please, add query in lieu of "select age from Customers". [ line : 9 ]. :)
Maybe, it'll works fine.
[ Sorry, for my bad English. ]
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "r, rmysql"
}
|
What happens if the upload key is lost when using Google Play App Signing?
If I use Google Play App Signing and I lose the upload key, what happens?
|
I'm glad you asked, there is no need to worry if you lose the upload key. You can generate a new one. From Google's documentation:
> When you use Google Play App Signing, if you lose your upload key, or if it is compromised, you can contact Google to revoke your old upload key and generate a new one. Because your app signing key is secured by Google, you can continue to upload new versions of your app as updates to the original app, even if you change upload keys.
|
stackexchange-stackoverflow
|
{
"answer_score": 24,
"question_score": 14,
"tags": "android, google play, signing"
}
|
Mhchem with hydrated compounds
I would like to get hydrated compounds with the leading number NOT subscripted, as shown here, but using `mhchem` instead of `chemmacros`. In particular, I already tried the accepted solution to that question (add more space in front of the numbers) and it does not work.
\usepackage[utf8]{inputenc}
\usepackage{mhchem}
\begin{document}
\ce{SrCl2 \cdot 6H2O}
\ce{SrCl2 \cdot 6H2O}
\ce{SrCl2 \cdot 6 H2O}
\end{document}
Outputs: 
I'm trying to use remote desktop on my laptop (running Fedora) to my desktop (also running Fedora) on the same local network.
I configured Remote Desktop on my desktop via System -> Preferences -> Remote Desktop, verified that the port is open by nmap, and attempted to connect from my laptop via vinagre (also tried appending :5900 for the port, and using the ip address). In all cases, the connection fails with a popup that says "Connection closed\n Connection to host was closed."
EDIT: I am able to use vinagre from the desktop to remote desktop into itself, just not from one machine to the other. I tried vncviewer and a similar problem occurs (`unable connect to socket: No route to host (113)`)
|
It sounds like the firewall settings on your desktop (the machine you're trying to connect to) have not been configured properly. Use the Firewall Settings tool (System > Administration > Firewall) to ensure that you have TCP port 5900 open. Start the tool, choose Other ports, and verify that TCP 5900 is in the list. If it's not, add it, and try your process again.
(Also, the port worked from the desktop machine to itself because the loopback network device is already trusted by the default firewall configuration.)
|
stackexchange-superuser
|
{
"answer_score": 1,
"question_score": 0,
"tags": "linux, remote desktop, fedora"
}
|
.NET partial class' accessibility over multiple files
If I have the core of a class defined in one file as "public partial" and I wish to create additions to this in another file, what is the difference between defining "public partial" again in my second file or just defining "partial"?
What happens if I define "private partial" in my second file?
|
You can duplicate the class modifiers or leave them out in one file, but you'll get a compiler error if they're specified in different files as different access levels.
From The C# Programming Guide.aspx):
> The following keywords on a partial-type definition are optional, but if present on one partial-type definition, cannot conflict with the keywords specified on another partial definition for the same type:
>
> * public
> * private
> * protected
> * internal
> * abstract
> * sealed
> * base class
> * new modifier (nested parts)
> * generic constraints
>
|
stackexchange-stackoverflow
|
{
"answer_score": 8,
"question_score": 2,
"tags": "c#, .net, partial classes"
}
|
Untouched Create React App experiences Flash of Unstyled Content
After initializing a new CRA I noticed a FOUC issue out of the box.
 angle between the negative $x$ axis and your ray? Then the angle between the positive $x$ axis and your ray is 228° counteclockwise or 132° clockwise.
|
stackexchange-math
|
{
"answer_score": 2,
"question_score": 0,
"tags": "trigonometry"
}
|
Can Dwarf Fortress be run in console mode?
I don't want to start up an X server at all, I just want to play on a text console. Is this possible?
|
Yes. You need to change the print mode to TEXT
Linux/OS X users may also use PRINT_MODE:TEXT for primitive ncurses output.
[PRINT_MODE:TEXT]
This is located in the `./df/data/init/init.txt` file.
|
stackexchange-gaming
|
{
"answer_score": 16,
"question_score": 13,
"tags": "dwarf fortress, linux"
}
|
Использование встроенных методов ЯП в С4 ЕГЭ
Не снимут ли баллы за использование встроенных в язык программирования функций (`sort`, `reverse`, `include?`, и т. п.) вместо написания собственных, если требуется написать:
> Эффективную, в том числе и по используемой памяти, программу
|
Я сдавал ЕГЭ в прошлом году и писал C4 на Cи, используя как раз `qsort()`. Разумеется, мне его почти не засчитали, разумеется я поехал на апелляцию и там доказывал, что не верблюд (причём проверяющие _буквально_ просто смотрели, что мой код не такой, как в эталонном решении, и говорили — «у вас ошибка»). Доказал.
Если оно вам надо — пишите хоть на Brainfuck, но я бы порекомендовал писать всю программу самому на Паскале, чтобы у проверяющих не было вопросов, а если какие и будут, то убедить их в своей правоте будет _куда проще_.
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "информатика"
}
|
How do I make a copy of a table within SQL Server Enterprise Manager?
This is one of those "I probably should know this, but I don't" questions. How do I make a copy of a table in Enterprise Manager? Not export the data into a different database, just make a copy of the table within the _same database_. At this point, I don't care whether the data comes with or not, but the table definition should definitely be duplicated.
If I do Ctrl+C on a selected table and paste the results into a text editor, it gives me a Create Table statement that looks promising, but I can't for the life of me find any place to run that statement.
Edit: note that I'm asking about **SQL Server Enterprise Manager.** This is NOT the same thing as "SQL Server Management Studio". There's no "New Query" button, neither in the top left corner nor anywhere else. In fact, the word 'query' does not occur anywhere in EM except on the Tools menu, and there it's a link to Query Analyzer.
|
If you're talking 2000 enterprise manager: Tools -> Query analyzer Will give you a place to execute the query.
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 5,
"tags": "sql, sql server"
}
|
Google Analytics event not firing
My Google Analytics event isn't firing on my webpage. Below is my code. It opens the url in a new tab just fine, and there are no errors in the console. But when I go to Google Analytics -> Real-Time -> Events my goal has no activity. It's using Universal Analytics because when I view page source I see analytics.js.
<a href=" onclick="ga('send', 'MyEvent', 'Click');" target="_blank">under construction </a></p>
If it helps, my Goal setup is:
Category - MyEvent
Action - Click
Use the Event value as the Goal Value for the conversion - Yes
|
you are missing the hit type property.
ga('send', 'event', [eventCategory], [eventAction], [eventLabel], [eventValue], [fieldsObject]);
Full documentation is here
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "javascript, google analytics, dom events"
}
|
Why does "find" produce string type?
I'm a learner, I work in Python 3.7.
As I understand, the find function is supposed to indicate an index position of a string.
It does just that when my input is a straight string like
myString='Blabla<body>blabla'.
now
myString.find('<body>')
returns 6. Awesome. But when I import the string from a webpage, I get the error
TypeError: argument should be integer or bytes-like object, not 'str'
I could not agree more, but I do not get why the argument is `str` in the first place.
My code:
import ssl, urllib.request
url = '
response = urllib.request.urlopen(url)
Content = response.read()
startposition = Content.find('<body>')
print(startposition)
|
`Content` is of type `bytes`, so the argument to `Content.find` must be `bytes` or `int`, but `'<body>'` is of type `str`. So, you got mismatched types.
How to fix: convert the `str` to `bytes`:
Content.find(b'<body>')
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "python, python 3.x"
}
|
Web to case form fields pre-populated from another page
We have a Web to case form implemented in the force.com sites. This form has is being triggered from another VF page, with some parameters. One of the parameters holds the **Id** to another object from where I am fetching the values and feeding Web2Case form fields with it using VF remote objects. Now,
* if user doesn't change any of the **preloaded** fields and post the form **it works fine**
* but if the user changes any of the **preloaded** values in the form and post it, the case doesn't show the updated values instead it shows preloaded value(s).
> **Screenshot with original values**
 equivalent?
I can't seem to find an equivalent in Nancy for System.Web.HttpContext.Current.Server.MapPath() in the Nancy framework.
I just want to load a textfile relative to the application service.
I see this in the assembly
using Nancy;
using System;
namespace Nancy.Hosting.Self
{
public class FileSystemRootPathProvider : IRootPathProvider, IHideObjectMembers
{
public FileSystemRootPathProvider();
public string GetRootPath();
}
}
I'm not sure how to use.
update: I just figured out anything I need to load can just be read/written from the bin/relase/ directory. Is that the assumed way to do it in a Nancy Self Hosting environment? I guess that would make sense.
|
You can take a dependency on `IRootPathProvider` and use that to call `GetRootPath()` that will give you the root of your application and you can add from there (I would recommend using `Path.Combine`)
|
stackexchange-stackoverflow
|
{
"answer_score": 11,
"question_score": 14,
"tags": "c#, path, hosting, nancy"
}
|
Unable to log in to ADFS using FireFox 30.0
I try to login to ADFS using Firefox 30.0. SP sends auth request. ADFS shows error:
> Server Error 401 - Unauthorized: Access is denied due to invalid credentials. You do not have permission to view this directory or page using the credentials that you supplied.
Other browsers and other versions of firefox are working.
|
Firefox disabled NTLMv1 authentication by security reasons since version 30.0. It recommends to upgrade NTLM to version 2. But NTLMv2 is supported only on Windows platform. Read <
**Workarounds:**
1) To login using ADFS with NTLMv1 and FF 30 and higher you should to configure FF. Open settings page **about:config**. Set _network.negotiate-auth.allow-insecure-ntlm-v1_ = _true_.
2) To don't use NTLMv1 in ADFS you can change the local authentication type to "Forms-based authentication".
See <
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "firefox, authentication, adfs"
}
|
How to scale two game objects with different scale sizes proportionally?
I have two game objects, one for main canvas and other for editor (a dummy version).
The scale for main go is 1, 1, 1 and other one (dummy) is .3, .3, .3. What I want to do is scale the main gameobject proportionally based on the scale percent that the user sets to dummy go, how I can do this?
|
DummyGameObject.transform.localScale = CanvasGameObject.transform.localScale * 0.33f; //or
DummyGameObject.transform.localScale = CanvasGameObject.transform.localScale / 3;
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "unity3d, canvas, transform, scale, gameobject"
}
|
Why can't I install the Pino twitter client in 12.04?
I did a search for Pino the twitter client and it comes up but when I click more info it says here is a screen shot of it here:
!enter image description here
|
It looks like Pino hasn't been updated in almost two years (since January 2011). It was only officially available in Ubuntu 11.10 Oneiric., and is not included in 12.04. That's why you get the "not found" error.
You can install it from this PPA:
* Open a terminal with `Ctrl-Alt-T`
* Type/paste: `sudo apt-add-repository ppa:fabriziosm/ppa-testing`
* Then type/paste: `sudo apt-get update`
* Close the terminal.
Now open Software Center, and search for Pino. You should now see an `Install` button. Install Pino; I tried it on 12.04 and it appears to work.
> _Related:_ Are PPA's safe to add to my system and what are some "red flags" to watch out for?
|
stackexchange-askubuntu
|
{
"answer_score": 2,
"question_score": 3,
"tags": "12.04, software center"
}
|
Display numbers lacking 2's
Display numbers from one to one-hundred (in increasing order), but number 2 shouldn’t appear anywhere in the sequence. So, for example, the numbers two (`2`) or twenty-three (`23`) shouldn't be in the sequence.
Here is an example output, with newlines separating the numbers:
1
3
4
5
6
7
8
9
10
11
13
14
15
16
17
18
19
30
31
33
34
35
36
37
38
39
40
41
43
44
45
46
47
48
49
50
51
53
54
55
56
57
58
59
60
61
63
64
65
66
67
68
69
70
71
73
74
75
76
77
78
79
80
81
83
84
85
86
87
88
89
90
91
93
94
95
96
97
98
99
100
|
# 05AB1E, 6 bytes
тLʒ2å_
Try it online!
**Explanation**
тL # push [1 ... 100]
ʒ # filter, keep only elements that
2å_ # does not contain 2
|
stackexchange-codegolf
|
{
"answer_score": 13,
"question_score": 24,
"tags": "code golf, sequence, kolmogorov complexity"
}
|
Weighted hinge loss function
I am defining my vanilla hinge loss as:
def hinge(y_true, y_pred):
return tf.maximum(0., 1- y_true*y_pred)
I'm training an SVM to predict an event. And my `y` values are `1` if it's that class or `-1` if it's not that class. My class is imbalanced that I have much more `-1` than `+1`.
Hence, I'd like to weight the loss `+1` to be higher penalty. But I'm not how exactly I'd change my hinge loss. The best I can think of is,
X = (# of non event samples) / (# of event samples)
if(y_true*y_pred > 0):
return tf.maximum(0., 1- y_true*y_pred)*X
This means, if I have a 100 non-event and 10 event, then `X` = 100/10 = 10. The loss is then `hingeloss*10` if `y_true = 1`.
Is this right or is there a better way to do this?
|
How about:
def hinge(y_true, y_pred):
return tf.multiply((11/9+y_true)*9/2,tf.maximum(0., 1- y_true*y_pred))
The logic here is that we want to multiply by 10 if `y_true` is 1, and by 1 if it is -1 . You can check that when `y_true` is -1, `(11/9+y_true)*9/2` evaluates to 1, and when it is 1, it evaluates to 10. If you are interested in knowing how to derive the 11/9 in the expession, it is the result of solving the linear equation for the desired shift s:
10(s + (-1))=1(s+1).
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "python, tensorflow, machine learning, loss function"
}
|
Does the Android OpenCV binary have data persistence functions?
I'd like to be able to persist matrices to disk. The c,c++ version of OpenCV supports with with the function cvWrite. I don't wee an equivalent function for the Android binary. Are there any other options?
|
In C/C++ you have the full API on all supported platforms:
XML/YAML Persistence
XML/YAML Persistence (C API)
Android Java API does not export the persistence API, but some classes provide Save/Load methods for their configurations.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "android, opencv"
}
|
Get Twig start of day date_modify
I am trying to get the start of today's date and time in Twig. I found that you can get the start of the current week by doing the following:
`{{ now | date_modify('monday this week')|date('d-m-y H:i:s') }}`
So I assume there will be a way to do this for the start of today. So far, I have tried:
`{{ now | date_modify('start of day')|date('d-m-y H:i:s') }}`
`{{ now | date_modify('start of today')|date('d-m-y H:i:s') }}`
Which resulted in:
> PHP Warning: DateTime::modify(): Failed to parse time string (start of day) at position 0
>
> PHP Warning: DateTime::modify(): Failed to parse time string (start of today) at position 0
I would like to know:
1. What is the correct syntax to ask this?
2. Where can I find a list of these strings?
3. Any alternatives to passing in strings
Thank you.
|
you can find those strings here: <
So I think what are you looking for is this: `{{ now | date_modify('today') | date('d-m-y h:m:s') }}`
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 2,
"tags": "php, twig"
}
|
How to access request.FILES from django admin form submission?
@receiver(pre_save, sender=Document, dispatch_uid='question_save_signal')
def log_save_question(sender, instance, using, **kwargs):
p = instance
Here is the code I use to intercept saving in django admin. From inside this function, I would need to access request.FILES to access new files that were just selected in an ImageField and are being submitted. How would you do it ?
|
When you have a pre_save function, the properties are already set to the object, however it is not saved to the db yet. So if your Document Model has an attribute `image`, you should be able to access it through: `instance.image`
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 2,
"tags": "python, django, django forms, django admin"
}
|
Execute dynamic SQL queries
I need to execute a `SQL` like bellow inside a `SP`.
DECLARE
@varSearchQ VARCHAR(100),
@varFieldName VARCHAR(100),
@varTableName VARCHAR(100),
@Sql VARCHAR(Max)
SET @varSearchQ='000'
SET @varFieldName='varConsoleID'
SET @varTableName='FF.ConsoleDT'
SET @Sql = N'SELECT ' + @varFieldName + '
FROM ' + @varTableName + '
WHERE ' + @varFieldName + ' LIKE %' + @varSearchQ + '%'
I found a way like `EXEC sp_executesql @Sql`. But I'm getting errors.
|
Try this
> You Should Use `Print` for Debugging Statments
Create proc MYPROC
as
BEGIN
DECLARE
@varSearchQ VARCHAR(100),
@varFieldName VARCHAR(100),
@varTableName VARCHAR(100),
@Sql VARCHAR(Max)
SET @varSearchQ='000'
SET @varFieldName='varConsoleID'
SET @varTableName='FF.ConsoleDT'
SET @Sql = N'SELECT ' + @varFieldName + '
FROM ' + @varTableName + '
WHERE ' + @varFieldName + ' LIKE ''%' + @varSearchQ + '%'''
print (@Sql)
EXEC (@Sql)
END
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": -4,
"tags": "sql server"
}
|
How to disable default % applying behaviour in Excel?
Whenever I insert % symbol at the end of a string in a cell it will automatically convert to percent format, i.e. the value is divided by 100. I want to disable the auto convert to % type and only string is allowed. How will I do that?
|
There is no mechanism to set the cell value datatype as number, string, percentage as fixed depends on the user data. Prefixing `'` works for only one cell. User have to prefix all the cell value with `'` that is not the ideal approach. If the column is set to general then the appends `%` at the end of any value then it will be converted to percent not to string. User again have to modify the cell datatype.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "excel"
}
|
Cold Break with a False Bottom
Historically, I've cooled my wort with a immersion chiller and siphoned it off to the carboy once it gets down to a reasonable temperature. I recently installed a false bottom and ball valve. This works well and the elbow attached to the ball valve avoids most of the hop material (whole leaf), but I am seeing a good bit of cold break going into the carboy, which i could avoid with the siphon. Am I missing something here? Would whirl pooling work (i'd think not, since the material would just collect in the center of the false bottom and go through the screen)?
I don't have a huge problem with the cold break, but my main purpose of installing the false bottom was to limit the trub from transferring.
**Edit** : here is a shot of the latest batch after draining through the false bottom: <
|
Cold break in the fermenter is not a problem. It's even been cited as a yeast nutrient.
|
stackexchange-homebrew
|
{
"answer_score": 3,
"question_score": 3,
"tags": "equipment, racking"
}
|
HTC Mail: Move Messages Between Folders, Not Synced on IMAP Server
I'm seeing some odd behavior on Android...running 2.2 on HTC Incredible.
I have an IMAP account configured through the built in "Mail" program. First of all, when you send messages from this program, it copies them to a local "Sent" folder, and there is no way to specify a remote IMAP folder for this (e.g. "INBOX.Sent"). So then, I try to move messages manually between the local "Sent" and the IMAP "INBOX.Sent" folder, and it appears to work fine, but when I check from another IMAP client (e.g. Thunderbird), I don't see the messages in "INBOX.Sent".
Has anyone else run into this? Any idea how to resolve?
|
Sounds like it's just not copying sent messageinto your mailbox at all, only keeping them locally. I would assume that's just a shortcoming of the app and you'd need to use a different one that supports that feature. The default client is very basic and buggy. Have you considered using Gmail? You can configure it (through the web) to get mail from an IMAP account, and then you could use the Gmail app (which is very good).
|
stackexchange-android
|
{
"answer_score": 1,
"question_score": 1,
"tags": "email, imap"
}
|
Convert a stack trace to a value
I want to get `Throwable.getStackTrace()` result as a value in Ceylon. Java interface has printStackTrace) method with parameter PrintWriter, but Ceylon Throwable interface has not. How can i get it?
|
Similar to `java.lang.Throwable.printStackTrace(PrintWriter)`, Ceylon's language module has the top-level function `void printStackTrace(Throwable, Anything(String))`. You provide the exception and a function which accepts a `String`.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "stack trace, ceylon"
}
|
How to create Profile when signup new user with Parse.com REST API
When I use the signup endpoint parse REST api to create new user, I would like to create a profile for this user in 1 call. I have a pointer relation to profile in User table. Is this possible? My current workaround is after user created successfully, then I do another call to create profile, then I update the pointer link to User table, so that's 3 call total. I would like to do 1.
Thanks.
curl -X POST \
-H "X-Parse-Application-Id: xxx" \
-H "X-Parse-REST-API-Key: xxx" \
-H "Content-Type: application/json" \
-d '{"username":"cooldude6","password":"p_n7!-e8","phone":"415-392-0202"}' \
|
One option is - to use **CloudCode** module. Take a look on this functions **beforeSave/afterSave/...**. Create Profile/other Objects & Save.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 2,
"tags": "rest, parse platform"
}
|
How can I tell if a helmet will be comfortable before buying?
Barring taking a helmet on a 50-mile ride before buying it:
Some kinds of chin straps, for example, won't stay tight, and some kinds of cages aren't comfortable no matter how I adjust them. What should I look for?
This isn't a product recommendation question (although that would be nice). I'm interested in knowing what features to look for.
Alternately, is there anything I can do to an existing helmet to make it more comfortable on longer rides?
(If it'll help, I ride for commuting, running errands, and touring; aero or ultra-light features are appreciated but aren't a priority, but ventilation is important.)
|
Put one on your head, adjust it to fit, and then try to slide it off your head in all directions. If you feel any pressure points or hot spots, you then need to determine if that will be alleviated by the little bits of foam included with most helmets, or if you need a different size or model of helmet.
As far as long-ride wear-ability is concerned, when you try on a helmet you need to be very aware of places the hard foam contacts your head. You also need to be aware of the weight of the helmet and ventilation when you start thinking about long rides. In most cases, for rides longer than about 2 hours, a more expensive (read: lighter and more ventilated) helmet will be more comfortable IF and only if it fits ok on your head.
|
stackexchange-bicycles
|
{
"answer_score": 4,
"question_score": 7,
"tags": "safety, helmets"
}
|
Facebook review required for iOS apps that have the SDK just for app install ads?
I have an app in the Appstore for a few months now. To use App Install optimized Facebook ads, I decided to integrate The Facebook SDK. But apart from running Ad Campaigns on Facebook, I am _not_ using any of the functionalities offered by the Facebook SDK. i.e. I am not using Facebook login and the services used with Facebook Login.
I noticed that the Facebook app is in Sandbox Mode and I need to set it to Public to use Facebook App Install advertising. I can set it to public right away, which is good.
But there is also a Facebook review submission button on the same page and there is a not-so-clear statement on the page saying Facebook needs to review "some" of the integrations before going live.
If I am using the SDK just for Facebook Ads with my "iOS App", do I still need to have my app reviewed by Facebook?
Cheers,
Taner
|
If you are not requesting to use any of the permissions, you do not need to have your app reviewed.
The only thing you need to do the enable it to be used for advertising is to set it to be Public. This will not really do anything in your case.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "ios, facebook, sdk, facebook ads api"
}
|
How to make md-select 100% width?
I use last version angular. This is material design code:
<md-grid-tile>
<md-select placeholder="Favorite food" [(ngModel)]="selectedValue" name="food">
</md-select>
</md-grid-tile>
I try to set `width: 100%`for `md-select. But it does not work.
|
This will solve your problem.
<md-grid-tile>
<md-select placeholder="Favorite food"
[(ngModel)]="selectedValue"
name="food"
[style.width]="'100%'">
</md-select>
</md-grid-tile>
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 3,
"tags": "angular, angular material, angular material2"
}
|
limit the decimal place in javascript is not working for 4.45678765e-6
every time i use the Math.round(4.45678765e-6 * 10000)/10000 it gives me a 0 value but if i remove the e-6 it gives the correct answer 4.4567 what shoul i do? here's my code. the value has the power of 10 something like this 4.45678765x10^-6.
<html>
<script type="text/javascript">
var x = Math.floor (4.45678765 * 10000)/10000;
document.write (x);
</script>
</html>
is it even possible to limit the decimal places if the value has an exponent?
|
`4.45678765e-6` is `0.00000445678765`, that number with only five digits after decimal point is `0.00000` so JavaScript is giving you the correct result.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "javascript"
}
|
How can I run Test-DbaNetworkLatency without password prompt?
I am running `Test-DbaNetworkLatency -SqlCredential sa` in `powershell` to measure sql server network latency. It prompts input password each time I run the command. I am planning to schedule a cronjob on my server to run this command regularly so I am looking for a way to avoid typing password each time. Can anyone tell me how I can achieve that in powershell?
|
You will need to create a credential object for the function. The function info shows `Windows and SQL Authentication supported. Accepts credential objects (Get-Credential)`
$password = ConvertTo-SecureString "Password" -AsPlainText -Force
$creds = New-Object System.Management.Automation.PSCredential ("sa", $password)
Test-DbaNetworkLatency -SqlCredential $creds
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "powershell, dbatools"
}
|
how to display datetime type to this format: date("F j, Y, g:i a");?
I used `datetime` type in my table but I don't know how to display this using this format:
date("F j, Y, g:i a");
to have it look like: November 9, 2012, 9:17 am
I've tried
echo date("F j, Y, g:i a", $row["date"]);
but I'm getting this error:
> Notice: A non well formed numeric value encountered in C:\wamp\www\crud_exer\content.php on line 69
What should I do?
|
You should do this way:
echo date("F j, Y, g:i a", strtotime($row["date"]));
PHP: date - Manual
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 0,
"tags": "php, mysql, datetime, non well formed"
}
|
How display point values on LineChart Java/JavaFX
How display in all points values on Line Chart Java/JavaFX:
 {
setPrefSize(15, 15);
final Label label = createDataThresholdLabel(priorValue, value);
getChildren().setAll(label);
toFront();
}
From there you can start to pull away the parts you dont need.
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": -1,
"tags": "java, javafx, jfreechart"
}
|
Check if session doesn't exist php
I have the following php code :
<?php
if (!(session_id('password')) || !(session_id('user_name'))) {
header("Location: ../../"); /* Redirect browser */
}
?>
Which should check if session doesn't exist, and if it doesn't, the user redirects, the problem is that this condition is always true, even when the session does exists, my question is how can I fix it?
|
Try with `$_SESSION` like
<?php
if (!isset($_SESSION) || !isset($_SESSION['password']) || !isset($_SESSION['user_name'])) {
header("Location: ../../"); /* Redirect browser */
}
?>
|
stackexchange-stackoverflow
|
{
"answer_score": 7,
"question_score": 2,
"tags": "session, php"
}
|
Why does `LogisticRegression` take target variable of type `object` without any error?
Am using basic `LogisticRegression` on data for which the target variable is `multiclass`.
I was expecting `LogisticRegression` to give some error when the `fit()` was called. But it didnt.
Does `LogisticRegression` handle such case by default? If yes, what transformations are applied to the target variable?
ddf = pd.DataFrame(
[[1,2,3,4, "Blue"],
[4,2,3,4, "Red"],
[5,2,8,4, "Red"],
[2,7,3,9, "Green"],
[7,6,7,4, "Blue"]], columns=['A','B','C','D','E']
)
ddf
X = ddf[['A', 'B', 'C', 'D']]
y = ddf['E']
lr = LogisticRegression()
lr.fit(X, y)
preds = lr.predict(X)
print(preds)
Gives the output: `['Blue' 'Red' 'Red' 'Green' 'Blue']`
|
Scikit-learn is able to handle string labels for all the classifiers by default, internally it creates a LabelEncoder object, have a look at the code here. String-class labels are encoded to integer values.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "scikit learn, logistic regression, sklearn pandas, multiclass classification"
}
|
Process.start() in a loop doesn't maintain FIFO
I want to print pdf files in a foreach loop which doesn't maintain FIFO. Applied even lock and semaphore using concurrent queue. But, sometimes misses the sequence. How can I make printing process maintaining confirm FIFO and Thread-safe? My code is as follows,
foreach(string pfile in printdoc)
{
ProcessStartInfo info = new ProcessStartInfo();
info.Verb = "print";
info.CreateNoWindow = true;
info.FileName = pfile;
info.WindowStyle = ProcessWindowStyle.Hidden;
Process p = new Process();
p.StartInfo = info;
p.Start();
}
|
You need the previous one to finish before you start the next itteration. Throw a `p.WaitForExit()` on the end to wait for the print to finish before queuing the next one.
foreach(string pfile in printdoc)
{
ProcessStartInfo info = new ProcessStartInfo();
info.Verb = "print";
info.CreateNoWindow = true;
info.FileName = pfile;
info.WindowStyle = ProcessWindowStyle.Hidden;
//You can shorten your existing code to a single line using Process.Start(
Process p = Process.Start(info);
p.WaitForExit();
}
For thread safety it depends on what kind of collection `printdoc` is, the easiest solution is to use a `BlockingCollection<string>` and make your foreach in to `foreach(string pfile in printdoc.GetConsumingEnumerable())`
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "c#, .net"
}
|
Angular Querybuilder in a single textbox with auto suggestion of next query
I'm planning to build a query builder using Angular
The feature is like to have a textbox which keep autopopulating the suggestions
**[Field + Operator + Value] + (Keyword) + ...**
Eg - _Name = 'Technosaviour' OR Age > 2_
The **autocomplete** should give suggestion of fields like [Name, Age]
Then [=, >, <, >=, etc]
Then [Techno, Saviour, Technosaviour]
Then the autocomplete should suggest [And, Or]
**Before jumping into full blown coding can anyone suggest any existing libraries available ?**
Eg - advance search (using JQL) in jira.
Similar to this < but limited to a single textbox
|
I did a POC on the project. Made it work to some extent, feel free to use it or improve it.
**Github link** <
: bad magic number [file=170175.ldb]
and
...I0511 07:15:51.797087 621 database.go:71] Alloted 433MB cache to /Users/lukeollett/Library/Ethereum/chaindata
Fatal: blockchain db err: leveldb/table: corruption on table-footer (pos=1829964): bad magic number [file=170175.ldb]
|
In the end after trying `geth updatedb` and `geth upgradedb` which oculd never connect to databse, I just removed the database `geth removedb` and reopened Mist and I am currently redownloading the block chain.
|
stackexchange-ethereum
|
{
"answer_score": 4,
"question_score": 4,
"tags": "mist"
}
|
Show that f is a symmetric relation on A
I am learning about relations and I come across this exercise. And I don't understand the problem. Let me first state the problem here:
Let $f: A \rightarrow A$ be a function for which $f(f(x))=x$ for all $x\in A$. Show that $f$ is a symmetric relation on $A$.
First, I know that, to show that $f$ is a symmetric relation on $A$. I want to show that: for all $a,b \in A$ $aRb \rightarrow bRa$. Then, I will do:
Given that $aRb$, I fix arbitrary $a,b \in A$, then, I will know that $f(f(a))=a$. Then I am lost... I must have did something wrong. I would appreciate if you can give me a hint because I've stuck on this for a while.
Many thanks!
|
$aRb$ in your case means $f(a) = b$.
Now apply $f$ on both sides and you will get $a=f(f(a)) = f(b)$
Thus it holds $f(b)=a$ which is $bRa$
|
stackexchange-math
|
{
"answer_score": 0,
"question_score": 1,
"tags": "functions, relations, equivalence relations"
}
|
Windows Phone: Call an Async method in OnNavigatedTo
In my WP8 app, I want to call an Async method when the page is navigated to.
I thought about marking the **OnNavigatedTo** method with **async** keyword to be like this:
async protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
await myAsyncMethod();
}
is there a better approach to achieve this, is there a problem in labeling **OnNavigatedTo** with async ?
|
Nope this is exactly what you should be doing. Mark OnNavigatedTo as async and then execute whatever you need to execute.
|
stackexchange-stackoverflow
|
{
"answer_score": 7,
"question_score": 6,
"tags": "c#, windows phone 8, windows phone"
}
|
Split Excel column with XML inside
Is there a way to break an Excel column containing XML into several columns like this:
BEFORE
| Apples | Pears | XML |
| ------ | ----- | ---------------------------------|
| 35 | 18 | <Plums>34</Plums><Figs>19</Figs> |
| 86 | 55 | <Plums>12</Plums><Figs>62</Figs> |
| 99 | 12 | <Plums>18</Plums><Figs>23</Figs> |
AFTER
| Apples | Pears | Plums | Figs |
| ------ | ----- | ----- | ---- |
| 35 | 18 | 34 | 19 |
| 86 | 55 | 12 | 62 |
| 99 | 12 | 18 | 23 |
The original table comes from an SQL Server that stores XML in a text column. If the XML column contained comma-separated values, I'd tell Excel to do Text to Columns. Is there a similar feature for XML?
|
In addition to Text manipulation in Excel there are two other options.
1. You could use VBA to parse the XML. You could either use string functions to look for tags or actually use XML parsers to walk the content (see this question on SO for more info).
2. You can use the XML Source feature in Excel (see here for an overview). The easiest way to use this is to load in an XML file. Excel will automatically try and create an XML map for the loaded data and load it into a table. For it to really work well though you need to create a schema.
For your data I added a root element and saved this in a file:
<Fruits>
<Plums>34</Plums><Figs>19</Figs>
<Plums>12</Plums><Figs>62</Figs>
<Plums>18</Plums><Figs>23</Figs>
</Fruits>
Loaded into Excel this creates the following table:
!enter image description here
|
stackexchange-superuser
|
{
"answer_score": 4,
"question_score": 5,
"tags": "microsoft excel, microsoft excel 2010, xml"
}
|
iOS: Blocks, main queue, and retain cycles
I have the following call within my app:
dispatch_async(dispatch_get_main_queue(), ^{
self.emptyView.hidden = [self.recordsData count];
[self finishedRefreshing];
});
which led me to believe that since we are accessing an ivar, a retain cycle would be created. But since I don't see the block being captured within self I figured I'd be ok. This then led me to believe we've been over using the weakself pattern as our typical convention is never to actually assign a block as an ivar. I still feel I'm missing something, are there other ways to create a retain cycle without assigning the block to self? I'm not sure why I'm having such a hard time grasping this concept but any good reading sources are also appreciated.
|
The "cycle" part does seem to be overlooked when people worry about retain cycles. In your code, the block is managed by GCD, your objects don't own it, so there is no retain cycle.
> we've been over using the weakself pattern
It does seem the case that a lot of people think "aargh! Blocks! Make a `weakSelf`"!
The retain cycles happen when an object owned by the block (so, a strong reference to the object or one of its ivars) itself owns the block (so the block is copied to a property or ivar).
The typical case is when you've made an object such as a custom alert view that has a completion handler block, and within the block you do something with the object itself (e.g. remove the view from its superview).
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 0,
"tags": "ios, objective c blocks"
}
|
Validation of a random forest
I am a complete newbie in this area and I am probably doing something wrong. I am trying to use `randomForest` in `R` for a regression and I am using the `iris` dataset. I want predict the `Sepal.Length` from the `Petal.Width` and the `Sepal.Length`. I want to test it with cross validation and I got confused. Here is my example.
data <- iris
k = 5
n=floor(nrow(iris)/k)
error=rep(NA,k)
for (i in 1:k){
s1=((i-1)*n+1)
s2=(n*i)
sub=s1:s2
train=iris[-sub,]
test=iris[sub,]
model=randomForest(Sepal.Length~Sepal.Width+Petal.Length,data=train,mtry=1,ntree=501,importance=TRUE)
prediction=predict(model,newdata=test[,-1])
error[i]= roc.area(test[,1],prediction)
}
Questions
1. Is the ROC a good choice for a regression model?
2. How can I get the accuracies for every fold and for the entire model?
|
> Is the ROC a good choice for a regression model?
AuROC is not a suitable figure of merit for regression models. A better typical choice would be e.g. mean squared error, in your case `sqrt (mean ((test$Sepal.Length - prediction)^2))`
> How can I get the accuracies for every fold and for the entire model?
Your `error[i]= error (test$Sepal.Length, prediction)` is one possibility. I usually prefer to store the predicitions rather than the surrogate models' performance as that allows to look at different figures of merit afterwards, allowing better insight.
If you store the error, you need to take into account that in general test sample size can vary a bit across folds and you need to take care to properly average them ($\sqrt a + \sqrt b \neq \sqrt{a + b}$) - which depends on the figure of merit you decided to use.
|
stackexchange-stats
|
{
"answer_score": 1,
"question_score": 1,
"tags": "r, cross validation, random forest"
}
|
How can I make a custom Notification?
I have been struggling in these last two days to find a way to make a custom android notification. I have passed by the remote views solution but this solution is very limited to changing the layout only. What I need is to put a custom view(other than text views, image views, and these typical views that are usually seen in a notification) in a notification. Is that possible?
|
> but this solution is very limited to changing the layout only
I do not know what you mean by this. The `RemoteViews` can certainly have more than a layout manager (e.g., `LinearLayout`); otherwise, it would pointless.
> What I need is to put a custom view(other than text views, image views, and these typical views that are usually seen in a notification) in a notification. Is that possible?
You are welcome to try whatever `RemoteViews` supports, minus the `AdapterView` subclasses (e.g., `ListView`). Interactive widgets, such as buttons, will be unreliable, particularly on Android 1.x/2.x, as vendor customizations to the notification tray sometimes prevent interactive widgets from working properly.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "android, notifications"
}
|
Java User's Name and Reverse Order
I am writing a code for class and I can't seem to find the error. Every time I run the code through Dr. Java, I am hit with a NullPointer exception.The code is supposed to take a users input and reverse the order of it. Any help? This is the code:
import java.util.Scanner;
public class LoopsProgram
{
public static void main (String [] args)
{
Scanner stringScanner = new Scanner (System.in);
System.out.println ("What is your name?");
String nameOfPerson = stringScanner.nextLine();
System.out.println(nameOfPerson);
int lengthOfName = nameOfPerson.length ();
char beginning = nameOfPerson.charAt(lengthOfName);
for (int i = lengthOfName-1; i > 0; i--) {
beginning = nameOfPerson.charAt(i);
System.out.print(beginning);
}
}
}
|
`char beginning = nameOfPerson.charAt(lengthOfName);` \- you are trying to access the 5th index, where as it will have index from 0 to 4. That's why you are getting errors.
Try this below code:
import java.util.Scanner;
class Test{
public static void main (String [] args)
{
Scanner stringScanner = new Scanner (System.in);
System.out.println ("What is your name?");
String nameOfPerson = stringScanner.nextLine();
System.out.println("Name : "+nameOfPerson+" & length : "+nameOfPerson.length());
int lengthOfName = nameOfPerson.length();
String result = "";
for (int i = lengthOfName-1; i >= 0; i--) {
result+=nameOfPerson.charAt(i);
}
System.out.println(result);
}
}
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -4,
"tags": "java, loops"
}
|
Angular js $window.open not working in .success for mobile browser
I'm working with Angularjs and I got a problem. The function $window.open(/somewhere) works perfect on pc browsers and mobile browser. But there's 1 case it doesn't work. Please help to look below:
$window.open(" // OUTSIDE OF REQUEST - no problems
$https({
type: "GET",
url: "backendURL",
data: jsonData,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
$window.open(" //This doesn't work.
},
error: function(msg) {
//alert(error);
}
});
Note that this is just happen with mobile browser : chrome and safari (I didn't test for others) So I think maybe someone has experience with this. Please please please help and advise.
Thanks ...
|
I found this solution online, hope it will help you. do `var win = window.open();` before the callback function, then inside `.success`, change url by doing `win.location = url;`. This should do the trick.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 3,
"tags": "javascript, ios, angularjs, jquery mobile, window.open"
}
|
How to get just the text from a ComboBox SelectedItem?
I made a WPF GUI in visual studio, and am manipulating it with PowerShell. I'm currently working out how to change data with the GUI elements, and am getting stuck on the a ComboBox. Here's the relevant code:
$testVar=$WPFcombobox.SelectedItem.ToString()
Write-Host $testVar;
And here's the output:
> System.Windows.Controls.ComboBoxItem: test123
I want to get back just
> test123
I also tried `$testVar=$WPFcombobox.SelectedItem`
but got the same result.
I also tried `$testVar=$WPFcombobox.SelectedItem.Text.`
and get nothing. If I add `.ToString()` after that, I get a "null-value" error.
I know I could just make a new variable and chop off the irrelevant part, but if there's a better way to get my desired output I would rather just do that.
|
Assuming `$WPFComboBox` is the name of your control:
$TestVar = $WPFComboBox.Text
Write-Host $TestVar
No need to find the selected item. The selected item's value is assigned "automatically" to the `ComboBox.Text` property.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "xml, wpf, xaml, powershell"
}
|
Why are some of the lower leaves on my cactus turning brown?
I have a cactus standing on my windowsill and for years it seemed pretty healthy, but last month its leaves started to turn a light brown-pinkish, kind of like a salt stone lamp. They also look a bit dry, but don't feel very different. Some of the other leaves are starting to look purple as well.
* It hasn't been moved for about five years.
* I don't really water it regularly, just when I remember it or when it looks dry.
* I live near Munich, and yes, we did have _a bit_ weird weather pattern lately. (Four weeks ago it was still snowing, and now it's about 30°C, 86°F.)
What's wrong and is there something I can do?
/more water, or just leave it alone, and it will probably do okay for a while.
If you do want to help it or have it look greener, you can cut off the lower, dead leaves, allowing for more ventilation, and repot it.
|
stackexchange-gardening
|
{
"answer_score": 1,
"question_score": 2,
"tags": "leaves, cactus, damage"
}
|
Confusion between "operator==" or "operator LPCTSTR"
I have this small piece of code:
CString temp = _T("Temp");
if(_T("Temp") == temp)
{
....
}
Now, here since there is a `friend opeartor==` function in `CString` class the `operator==` is getting invoked. But there is also a `operator LPCTSTR` defined for `CString`. So my question is why this operator is not used instead of `operator==`? If for a moment if we assume there is no `friend operator==` then will `operator LPCTSTR` will be used? what does the language rules say about this case?
|
Calling the overloaded operator== is an exact match, compared to operator LPCTSTR which requires a user defined conversion. An exact match is preferred over a user defined conversion.
Yes, if operator== is not there, then the next best candidate (and of course viable) is operator LPCTSTR which will be called for compatible arguments.
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 1,
"tags": "c++, winapi, operators"
}
|
Security implications of allowing remote desktop
I recently purchased an iPhone and downloaded the RDP Lite application, which allows me to remote into my home computer. Typically, I've always used LogMeIn for remoting and always had the built-in Windows option disabled.
Now, what's to stop someone from running some sort of brute-force login attack on the administrator account of my machine? Are there safeguards in place to prevent this?
|
Here's a good document on some of the attacks and mitigations. It's a bit dated, but interesting. In addition to changing your port, you should also change the name of your Administrator account and set up a honey pot) dummy account.
|
stackexchange-superuser
|
{
"answer_score": 4,
"question_score": 4,
"tags": "security, remote desktop"
}
|
static web site authoring and modularity
I have been working creating a new project static web site and was wondering what's the correct way to reuse the header, footer etc into a HTML base that can be "imported" and reused in all pages. Currently I replicate all the code and this is not really a good thing. Using JQuery and dynamic divs for this simple use-case is an overkill I believe.
The website I have been working on is this: <
|
You can try server side include (SSI). <
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "html, web"
}
|
Why does tensorflow take more GPU RAM than the model file?
I have a tensorflow model saved as a protocol buffer format as `model.pb` which is `184 MB`. When I load it using a session, I see that the process hogs `11 GB` of GPU RAM. Why is that?
|
Tensorflow uses all the GPU memory by default to minimize memory fragmentation (see the documentation). You can prevent this behavior by using the allow_growth config option:
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
session = tf.Session(config=config, ...)
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "python, tensorflow"
}
|
Is it possible to do redirects in Shopify with wildcards?
We want to be able to do something like allow a user to type "website.com/0431", where 0431 corresponds to a specific products manual and redirects to it. Is this possible with Shopify?
|
You can set up redirects in Shopify. There is a redirect setup mechanism built right into the Admin. Online Store -> Navigation -> URL Redirects.
|
stackexchange-stackoverflow
|
{
"answer_score": -3,
"question_score": 2,
"tags": "shopify, liquid"
}
|
How can $\sqrt{100+\sqrt{6156}}+\sqrt{100-\sqrt{6156}}$ be equal to $18$?
According to this answer, when $\sqrt{m}$+$\sqrt{n}$ is rational, then $\sqrt{m}$ and $\sqrt{n}$ are rational.
But $\sqrt{100+\sqrt{6156}}+\sqrt{100-\sqrt{6156}} = 18 \in \mathbb{Q}$.
So that would imply $\sqrt{100+\sqrt{6156}}$ and $\sqrt{100-\sqrt{6156}}$ both rational. However, the former is $9 + \sqrt{19}$ and the latter is $9 - \sqrt{19}$, both irrational.
Where is the mistake here?
Thanks.
|
The problem is that the proof of what you linked is actually equivalent to $m-n$ being rational which isn't correct here
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 4,
"tags": "field theory, irrational numbers"
}
|
How can I filter by an array which is contained as a value of a struct
Below is the data structure which I'm storing in an array called **arrayEV** I'm pretty sure I can filter by the eventname in the top array. However I'm not sure how to filter the arrays by things in the subarray [heatlane] so I only want the main arrayEV to show up when a condition is met by something in the [heatlane]
struct events {
var eventnumber:Int
var eventname:String
var swimmers:[heatlane]?
}
struct heatlane{
var heat:Int
var lane:Int
var age:Int
var swimmer:String
var team:String
var seedTime:String
var finalsTime:String
}
|
There's no difference in approach in filtering by simple property (like `Int`) or more complex one (like `Array` or others). You should just pass condition by which elements should be filtered.
If you would like to filter events and have only these which event's name starts with "A" you'd write:
let prefixedWithA = events.filter{ $0.eventname.hasPrefix("A") }
If you would like to filter events that have swimmer whose name is prefixed with "A" you'd write:
let hasSwimmerPrefixedWithA = events.filter{ $0.swimmers?.contains(where: {$0.swimmer.hasPrefix("A")}) ?? false }
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "arrays, swift, dictionary, multidimensional array"
}
|
openLDAP cn=config doesn't seem to be configured correctly
I'm new to LDAP's, but have an openLDAP config which I have moved to using olc instead of the slapd.conf.
When I run the command
`ldapsearch -H ldap:// -x -s base -b "" -LLL "configContexts"`
I get the empty result `dn:`
Does this suggest the config isn't working? I was unable to use the `-H` to authenticate until I imported an ldif setting `{1}to * by dn.exact=gidNumber=0+uidNumber=0,cn=peercred,cn=external,cn=auth manage by * break` into `olcDatabase={0}config` under `olcAccess`, so I think that was done correctly. But now that I add other ACL's, none of them seem to take.
Is the empty result from the configContexts command a concern?
This is all to get something like the following to work so I can set admins over the LDAP.
`{3}to * by dn.exact=uid=myadminaccount,dc=domain,dc=com manage by * break`
|
You probably want to query attribute _configContext_ (without trailing 's').
Provided you access control rules allow the bound entity to read it the result looks like this:
$ ldapsearch -H ldap://-s base -b "" -LLL "configContext"
dn:
configContext: cn=config
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "openldap"
}
|
Evaluate $\int_0^1 \frac{1}{\sqrt x+\sqrt {(1-x)}}dx$
Evaluate $I=\int_0^1 \frac{1}{\sqrt x+\sqrt {(1-x)}}dx$.
I applied $x=\sin^2\theta$,that makes $I=\int_0^{\pi/2} \frac{\sin2\theta}{\sin\theta+\cos\theta}d\theta$,but the further proceedings makes $I$ quite tedious.
I need to know is there some elegant transformation which can simplify the calculations.
Any suggestions are heartily welcome
|
Hint:
$$\sin2\theta=(\sin\theta+\cos\theta)^2-1$$
and $\sin\theta+\cos\theta=\sqrt2\sin\left(\dfrac\pi4+\theta\right)$
Use Integral of $\csc(x)$
|
stackexchange-math
|
{
"answer_score": 6,
"question_score": 3,
"tags": "real analysis, integration, definite integrals, linear transformations"
}
|
Solving error about NavigationLinkSet when packaging a community using 2GP
In a Community that I am trying to package using 2GP with:
sfdx force:package:version:create
after eliminating several errors I am now getting this one:
> These entities are not supported: [NavigationLinkSet]
There is a `CommunityTemplateDefinition` included, and that can have a collection of `NavigationLinkSet` (according to CommunityTemplateDefinition). But there are no references to `navigationLinkSet` or `NavigationLinkSet` in the source. And we do want to distribute the community template as well as the LWCs and Apex etc.
(There is a `NavigationMenu` containing `navigationMenuItem` which look closely related.)
Is `CommunityTemplateDefinition` packageable? Any suggestions about what the problem is here and how to solve?
|
Communities are not packageable for 2GP packages.
As an unlocked package yes you can package up the ExperienceBundle (there are some known issues with ExperienceBundle as well on known issue site so do not recommend it as of today) but not as a 2GP yet.
The only recommended way to package communities is via the "Bolt Solution" which allows you to distribute your template. The Bolt solution is done via the org. Check the help article here
Carefully review the limitations of the Managed Package with Bolt Solution, specifically around upgradability. You will note that upgradability is not supported and there is a need for configuration of the Template.
I usually recommend customers to distribute Bolt Solution via a Separate Extension Package because of the limitations around upgradability.
|
stackexchange-salesforce
|
{
"answer_score": 3,
"question_score": 5,
"tags": "community, managed package, metadata api, second generation packaging, 2gp"
}
|
Invalid TLD/Registration Period Supplied for Domain Registration in WHMCS API on ipad
I am using WHMCS API for one of my application. Now when users oders a domain related product from my control panel, which is communicating with the WHMCS through the API from IPAD it is showing the error
"Invalid TLD/Registration Period Supplied for Domain Registration".
I searched and found that the error is usually because of some mistakes like Registration periods not specified for the selected domain etc. But this application works correctly on every other desktop browsers and the domain is registered successfully.
|
Normally that message means you've not selected a period for which you've entered a price in the domain pricing section - a common mistake of it defaulting to 1 year, and the TLD requiring a 2 year minimum
If you're only seeing it on one browser/device, then it's likely an issue with the device/browser and you should bin it immediately and get something that follows standards ;)
Alternatively you might find specifically selecting a period rather than letting the browser say it's selected one but hasn't done so will fix the issue.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "whm, whmcs"
}
|
error while configuring the iis server ( HTTP error 500.19 )
I am trying to configure IIS local server but I get the following error while accessing the site:
`The requested page cannot be accessed because the related configuration data for the page is invalid`
**_Details_**
Module: IIS Web Core
Notification: BeginRequest
Handler: Not yet determined
Error Code: 0x80070005
Config Error: Cannot read configuration file due to insufficient permissions
Logon Method: Not yet determined
Logon User: Not yet determined
|
This problem occurs for one of the following reasons:
You are using IIS 7.0 on a computer that is running Windows Vista. Additionally, you configure the Web site to use UNC Passthrough authentication to access a remote Universal Naming Convention (UNC) share.
The IIS_IUSRS group does not have the appropriate permissions for the ApplicationHost.config file, for the Web.config file, or for the virtual/application directories of IIS.
Click here for details and methods for solving the problem.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "asp.net, visual studio, iis, asp.net web api"
}
|
Visual Studio Code not honoring .gitignore in git tab
I've appropriately configured a .gitignore file and put it in the base directory of my project, but when I go to the git tab of Visual Studio Code it does not ignore the folder that I'm trying to ignore and therefore is suggesting that there are changes for 4000+ files that I don't care about (the folder that I'm trying to ignore is a virtual environment for python).
Has anyone else successfully gotten the git tab to ignore changes using the .gitignore file?
|
Gitignore doesn't affect the files which are **already** tracked.
To stop tracking a file that is currently tracked, use `git rm --cached <dir>`. It removes the file from the staging area entirely, but doesn't delete the directory from disk; instead leaves the directory as it is.
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 2,
"tags": "git, gitignore"
}
|
how to append timezone to Datepipe's tranform function?
I want to convert UTC time to specific timezone using angular `DatePipe`.
Without appending timezone, `transform` method converts UTC to local time which i don't want. here's the code.
punch_time = this.datepipe.transform('2021-02-05T06:03:40.574000Z', 'shortTime');
above code gives output of `11:33 AM`. which is local time. instead i want to get time in specific timezone for example `UAE - Dubai` time.
How to do this?
|
Angular `datePipe` accepts a `timezone` parameter. But instead of trying to send the ISO8601 timezone abbreviations, I've found sending the time offset required work without any issues.
Try the following
punch_time = this.datepipe.transform('2021-02-05T06:03:40.574000Z', 'shortTime', '+4000');
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "angular, typescript, date pipe"
}
|
Calculate payment for retirement in Excel
Georgia McBeal is trying to save for her retirement. She believes she can earn 10% on average each year on her retirement fund. Assume that at the beginning of each of the next 40 years, Georgia will allocate x pounds to her retirement fund. If at the beginning of a year Georgia has y pounds in her fund, by the end of year, it will grow to 1.1y pounds.
How much should Georgia allocate to her retirement fund each year to ensure that she will have £1 million at the end of 40 years?
|
The **PMT function** will help you with this question:
* Rate: Yield, in this case 10% annually
* Nper: Amount of periods, since Georgia is only contributing annually, it will be 40 periods
* PV: Present Value is 0, as Georgia has currently nothing saved up
* FV: Future Value is the amount she is trying to save up, in this case £1MM
* Type: 1, which indicates that the amount is contributed at the beginning of the year
> =PMT(10%;40;0;1000000;1)
Georgia will have to save £2,054.01 per year in order to reach her savings goal.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -1,
"tags": "excel, excel formula"
}
|
error resolving localhost while running java servlets in eclipse's browser
I am new to java servlets. I have installed apache-tomcat-9.0.0.M21.
When I run the project containing servlet in eclipse browser, sometimes I get the error- **Error resolving 'localhost': Name or service not known.**
Other times the error is - **Error resolving 'localhost' : Temporary failure in name resolution.**
This project runs fine in my web browser.
Also, after I add `<servlet>...</servlet>` and `<servlet-mapping>...<servlet-mapping>` in web.xml, I get the error - **Server Tomcat v9.0 Server at localhost failed to start.**
One more thing, I use Ubuntu operating system (if it has to do something with the question).
Please help. I googled for the solution but I am not able to resolve the error.
|
Try adding the below to your `/etc/hosts` file.
`127.0.0.1 localhost`
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "java, eclipse, tomcat, servlets"
}
|
doctype declaration is causing internet explorer to throw a SSL warning
IE is throwing an error "do you want to view only the webpage content that was delivered securrely." On investigation, removing the doctype removes the error. There are no other calls to http content in the page.
How can I declare the doctype with a https connection or in some other way get around IE's problem? This is my doctype statement:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "
I don't get any warnings in any other browsers, just IE.
|
The actual cause of this was the http:// codebase calls in the js calls to flash. i changed these to https and the warnings went away.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "internet explorer, ssl, doctype"
}
|
How to determine the date of Starting day of current and last week in python ?
I need to find the date of the starter day of current and last week.
Here, business day of a week starts from SUNDAY. So, for today the date I want is to be "07-16-2017" as "mm--dd--yyyy" format. I can get today's date easily from `datetime.datetime.now().strftime ("%Y-%m-%d")` but from the sysdate I have to pull out the starter day of the week.
I need the starter day's date for last week as well.
There is no default method for week information in datetime. Is there any other method in any package in python to determine the required information ?
|
You can use `calendar.firstweekday()` to check what the first day of the week is on that computer (0 is Monday, 6 is Sunday).
1) Let's say that `firstweekday` returned `1` (Sunday). Then you can use
date.today() - datetime.timedelta(days=date.today().isoweekday() % 7)
to compute the date of the last Sunday.
2) Let's say that `firstweekday` returned `0` (Monday).
date.today() - datetime.timedelta(days=date.today().isoweekday() % 7 - 1)
to compute the date of the last Monday.
Hope this gives you some direction.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 4,
"tags": "python, date, datetime"
}
|
Why and how does the assassin end up using Tyrion's blade?
In _Game of Thrones_ , is it ever explained why the assassin who attempts to kill Bran (he finds Catelyn Stark and tries to kill her as well, only to be killed by Bran's direwolf) uses Tyrion's blade in his attack, as identified by Littlefinger?
Tyrion claims he's innocent, despite the damning evidence. And really, it makes little sense that anyone other than Jamie and Cersei Lannister would be the culprits.
So why and how does the assassin end up using Tyrion's blade?
|
Because it has never been Tyrion's blade. You said despite the damning evidence but what evidence? Are we really trusting Littlefinger?
That's what Tyrion said in his defense:
> It was not my dagger. How many times must I swear to that? Lady Stark, whatever you may believe of me, I am not a stupid man. Only a fool would arm a common footpad with his own blade.- source
And in "The Dragon and the Wolf":
> **ARYA** : You told our mother this knife belonged to Tyrion Lannister. But that was another one of your lies. It was yours.
And he said nothing in defense about the dagger.
And it's already been discussed who sent the killer in the similar question:
Who sent the assassin to kill Bran Stark?
So it might be possible that behind the scenes Joffrey contacted Littlefinger for this murder attempt and as he is, he made this convoluted plot. But we didn't get the clear answer yet.
|
stackexchange-movies
|
{
"answer_score": 36,
"question_score": 19,
"tags": "plot explanation, game of thrones"
}
|
"Error": "401 - No API Key entered or API key incorrect." on each HTTP Azure function
I get this error below on each azure http function even when I create new default one. "Error": "401 - No API Key entered or API key incorrect." Not sure what is up. Anyone has ideas?
|
When your function has "Function" or "Admin" authorization, you have to provide APIkey defined for that function. Just add it as "code" Query parameter to your request.

Can I use `WP_Query` to only query posts less than (or greater than) a given post ID?
$filtered_query_args = array(
'post_type' => 'projects',
'order' => $prev_next=='next' ? 'DESC' : 'ASC',
'orderby' => 'ID',
// ID <= $post->ID
);
I've been digging around in the codex with no luck.
I can of course do this conditionally within the loop, but it would be much cleaner if I could use `WP_Query` directly.
|
I ended up using something like this:
function filter_where( $where = '' ) {
global $post, $prev_next;
$the_ID = $post->ID;
$where .= " AND wp_posts.ID ";
$where .= $prev_next=='next' ? "< $the_ID" : "> $the_ID";
return $where;
}
add_filter( 'posts_where', 'filter_where' );
$nextProjQuery = new WP_Query( $filtered_query_args );
remove_filter( 'posts_where', 'filter_where' );
|
stackexchange-wordpress
|
{
"answer_score": 1,
"question_score": 1,
"tags": "php, wp query, posts where"
}
|
how to get phyiscal path of windows service using .net?
I have to get the absolute path of a windows service in a .Net Admin application. I am using ServiceController of .Net as shown below.
ServiceController serviceController = new ServiceController(serviceName);
But I don't see any property here to get the absolute path of the .exe of the service. Is there anyway to get this programmatically.
|
You can get this using WMI, which requires an assembly reference to System.Management:
using System.Management;
class Program
{
static void Main(string[] args)
{
Console.WriteLine(GetPathOfService("eventlog"));
Console.ReadLine();
}
public static string GetPathOfService(string serviceName)
{
WqlObjectQuery wqlObjectQuery = new WqlObjectQuery(string.Format("SELECT * FROM Win32_Service WHERE Name = '{0}'", serviceName));
ManagementObjectSearcher managementObjectSearcher = new ManagementObjectSearcher(wqlObjectQuery);
ManagementObjectCollection managementObjectCollection = managementObjectSearcher.Get();
foreach (ManagementObject managementObject in managementObjectCollection)
{
return managementObject.GetPropertyValue("PathName").ToString();
}
return null;
}
}
|
stackexchange-stackoverflow
|
{
"answer_score": 16,
"question_score": 16,
"tags": ".net, windows services, administration, servicecontroller"
}
|
DynamoDB : UUID vs combination Natural ID + timestamp
Assume a model dealing with users. Users are stored in a table called `Users`. Every user is uniquely identified by some natural identifier (partition key). Every user may have zero or more reports stored in the `Reports` table.
I can think of two ways to design the `Reports` table:
1. A partition key consisting of a UUID
2. A partition key consisting of the user natural identifier and, a sort key consisting of a timestamp when the report was created
With a timestamp precision at milliseconds level, it is safe to assume that no more than one report can be generated for a given user during the same millisecond (second precision should also be safe).
What is the recommended approach?
|
It depends on the distribution of reports per user. If it is typical for users to have very few reports each (say < 100 each) or if all users will have almost the same number of reports then you can go with user ID and time stamp.
But if you expect that some users will have a lot more reports that the majority then you should opt for UUID with a GSI for looking up records by user id.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "amazon dynamodb"
}
|
Combining trailer tail lamp and turn signal onto one wire
I am looking to attach a light to my tow vehicle that will be powered when towing via a 12V wire.
I also will have a 2nd wire that will supply 12V when the turn signal is turned on. At this point, I am not sure this is even possible but what I am looking for is when 12V is supplied to the turn signal, the light will flash in sync with the turn signal. Of course this is now backwards, because 12V would mean ON and 0V would mean OFF. So there needs to be some delay or some way of detecting when the turn signal has received 0V and not received 12V within a certain time period, that it would default back to the light being on.
|
> I am looking to attach a light to my tow vehicle that will be powered when towing via a 12 V wire.
I wouldn't tow via a 12 V wire. But I assume you just got your word order mixed up.
!schematic
simulate this circuit - Schematic created using CircuitLab
_Figure 1. Car circuit._
In a car the light switch provides a path to ground when in the off position.
* When lights are switched on current flows through the lamp from left to right.
* If the turn signal is switched on it puts 12 V on both sides of the lamp so it turns off. It will blink in anti-phase with the lights on the car. (This may be a problem for the guy behind.)
* If lights are off and the turn signal given the lamp will blink in unison with the vehicle.
!schematic
simulate this circuit
_Figure 2. An additional relay is required to have the same effect on a single wire feeding the trailer._
|
stackexchange-electronics
|
{
"answer_score": 3,
"question_score": 1,
"tags": "wiring, light"
}
|
Passing an argument to a callback block
I'm writing a simple callback for a gem I'm working on. Please note that due to certain architectural constraints, I can't use the ActiveSupport `define_callbacks` method for this specific case.
Right now, I have something like this:
def self.after_data_transcoding(&block)
define_method :_after_data_transcoding_callback { block.call }
end
So an use case is similar to this:
class MyClass
after_data_transcoding do
end
end
The actual call is done by `instance.send(:_after_data_transcoding_callback)`.
The code so far works great. I would have liked to go one step further and be able access the response as a block argument:
class MyClass
after_data_transcoding do |response|
# Do something with the response
end
end
However, I haven't had much success. Any thoughts on how I should proceed?
|
Turns out this was easier than I thought.
define_method(:_after_data_transcoding_callback) { |response|
block.call(response)
}
instance.send(:_after_data_transcoding_callback, response)
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "ruby, block"
}
|
Is there any way to inherit the existing TLD definition for particular JSP Tag?
I am planning to extend the basic html input tag provided by Spring to incorporate more features into it. I did similar kind of exercise in past for Struts too. At that point of time I had to create a tld file with the attributes that I introduced plus all the attributes available in the parent tag.
This is bit tiresome and repetitive so the question is that Is there anyway to inherit the existing TLD definition for particular JSP Tag?
Or any shortcut?
|
I don't think there is an option to **inherit** a TLD definition.
The shortest solution, i think, will be to inherit the tag class and change the tld to your new (derived) class.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 5,
"tags": "jsp, tags"
}
|
Calculation of prob. distribution
= \sum_z p(w\mid z, \theta, \beta)\,p(z\mid \theta, \beta)$$
so you might want $p(w\mid z, \theta, \beta)= p(w\mid z, \beta)$ and $p(z\mid \theta, \beta)=p(z\mid \theta)$ for all $z, \theta, \beta$ to get your original expression.
* * *
As a counter-example to your original expression, suppose the following combinations are equally likely
w θ β z
0 0 0 0
0 0 0 1
0 1 0 0
1 1 0 1
0 0 1 1
1 0 1 0
1 1 1 0
1 1 1 1
Then $\mathbb{P}(w=0\mid \theta=0, \beta=0)= \frac{2}{2}=1$
But $\mathbb{P}(w=0\mid z=0, \beta=0)\,\mathbb{P}(z=0\mid \theta=0)+\mathbb{P}(w=0\mid z=1, \beta=0)\,\mathbb{P}(z=1\mid \theta=0) $ $ =\frac{2}{2}\times\frac{2}{4}+\frac{1}{2}\times\frac{2}{4}=\frac34$ which is different
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 0,
"tags": "calculus, probability"
}
|
Yii2-user, dektrium-yii2-user, Yii2 Populate a dropdown in yii2
I am pretty sure that there is a better way to populate the array, needed for the dropdown:
<?php
$items2 = [Yii::$app->user->identity->id => Yii::$app->user->identity->username ]; ?>
<!--...some html -->
<?= $form->field($model, 'idUser')->dropDownList($items2,['Item' => ''])?>
already try:
$item2 = ArrayHelper::map(Yii::$app->user->identity::find()->all(), 'id', 'name');
reason, I want to display 'name' but submit 'value'='id'.
|
Should be this
<?= $form->field($model, 'idUser')->
dropDownList(ArrayHelper::map(Yii::$app->user->identity->find()->all(),
'id', 'username'), ['prompt'=>'Select...'])?>
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "yii2, yii2 user"
}
|
How to create an Apple 'Associated Domain File' without an extension
According to Apple's documentation, I need to add a file to my website called _apple-app-site-association_ **without an extension** in order to utilize App Clips:
> To add the associated domain file to your website, create a file named apple-app-site-association (without an extension).
However, I can't seem to accomplish that. According to iPage support, it's not possible to have a file without an extension.
**Question:** Is it truly necessary for this file to be without an extension, or is there an acceptable extension I can use? What would you recommend I do, here, since iPage says it's not possible?
Thank you!
|
I solved the problem by uploading the file via FTP (FileZilla).
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "server, apple appclips"
}
|
python3 mysql.connector - get results/output from cursor
my sql commands are working for instance to truncate table - but my load data command isn't actually inserting any records - how can I confirm py is reading my input file correctly or at all?
cursor.execute("LOAD DATA LOCAL INFILE '/home/user/mongo_exported_users.csv' INTO TABLE tbl.users IGNORE 1 LINES")
row_count = cursor.rowcount
for i in range(row_count):
line = cursor.fetchone()
print(line)
mydb.close()
print("Done")
The output of the fetchone is just None for all rows so IDK whats going on!
|
MySQL transactions have to be managed by `commit`. add the below line before closing the connection.
`mydb.commit()`
or
you can make `autocommit` just after the connection as shown below
`mydb.autocommit = true`
This should do the job
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "python 3.x, mysql python"
}
|
Dictionary of Dataframes select name of the dataframe
I am using Python.
I have a dictionary of Dataframes. Each dataframe has a name in the dictionary and I can reference it correctly no problem.
I am trying to take that name and add it as a column across every row. I am having a rough time doing this.
|
You can simply assign the name string to a new column for each DataFrame:
import pandas as pd
frames = {
'foo': pd.DataFrame({'a': [1, 2], 'b': [3, 4]}),
'bar': pd.DataFrame({'a': [9, 8], 'b': [7, 6]})
}
for name, df in frames.items():
df['name'] = name
print(df, '\n')
Gives:
a b name
0 1 3 foo
1 2 4 foo
a b name
0 9 7 bar
1 8 6 bar
Demo
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 2,
"tags": "python, python 3.x, pandas, dictionary, dataframe"
}
|
Further to refer to time
May I use _further_ to refer to time? For instance: _I'll do it further_
Thank you
|
You can use _further_ for time, but not in that sentence. The word _further_ is a comparative, so it means _more distant than something else_ , or _later than something else_. Your sentence only refers to one time in the future, so you can't use _further_. (Strangely, _later_ is a comparative which doesn't suffer from this restriction.)
So, for example, you cannot say:
> Further down that road is a meadow with a zebra in it;
you would need to say
> Down that road is a meadow with a zebra in it.
But you could say:
> If you go down that road a mile or two, you'll see a beautiful lake, and further down you'll find a meadow with a zebra in it.
And in reference to time, you could say:
> We will have the apps for doctors up tomorrow, but the ones for patients will only come online further on.
|
stackexchange-english
|
{
"answer_score": 0,
"question_score": 0,
"tags": "single word requests, word usage, grammaticality, american english, time"
}
|
Why are BOOLEAN type columns problematic in relational database design?
I've been working mostly with Oracle for the past few years, and am quite used to seeing single character varchar columns used as boolean values.
I can also see (per stack overflow answers), that suggested type for MySQL is TINYINT.
Now I've taken on my little side project - using DerbyDB, and it supports BOOLEAN columns, but not until after version 10 or so.
So, the question is, why is it so hard to incorporate a BOOLEAN column while designing a relational database? Am I missing something, or is it just pushed down the to-do list as unimportant, since you can use another column type meanwhile?
|
Tom Kyte pretty much echoes your last sentence in this blog entry:
> "It just isn't a type we have -- I can say no more and no less. ANSI doesn't have it -- many databases don't have it (we are certainly not alone). In the grand scheme of things -- I would say the priotization of this is pretty "low" (thats my opinion there)."
He's speaking from the Oracle perspective, but it applies to any relational RDBMS.
|
stackexchange-stackoverflow
|
{
"answer_score": 7,
"question_score": 14,
"tags": "mysql, sql, oracle, derby"
}
|
How to Iterate over the list and convert the datatype
Below is my list
`list_a = ['20.3', '6.74', '323','a']`
Code is below
try:
list_a = map(float, list_a)
except ValueError:
pass
for i in list_a:
print (i)
Expected result
`[20.3, 6.74, 323,'a']`
|
You can use following:
list_a = ['20.3', '6.74', '323','a']
for i,v in enumerate(list_a):
try:
x=float(v)
list_a[i]=x
except:
pass
This would be working for your scenario.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "python, list"
}
|
Does there exist an infinite set S that is closed under infinite unions but not finite unions?
Does there exist an infinite set $S$ of sets, such that for every infinite subset $I$ of $S$, $\bigcup I \in S$, but $S$ is not closed under finite unions?
|
Let $$S=\\{\,A\subseteq \Bbb N\mid 1\in A\,\\}\cup \\{\\{2\\},\\{3\\}\\}.$$ Then $\\{2\\}\cup\\{3\\}\notin S$, but every infinite union will contain $1$ and be $\in S$.
|
stackexchange-math
|
{
"answer_score": 7,
"question_score": 2,
"tags": "elementary set theory"
}
|
Nuvoton NUC120 Communication via Build in USB
I just bough NUC120, and there is nothing less than expected. What sparked my interest is, as stated on page 17-18 on the datasheet, It able to do UART communication. So far, I only use the USB port to uploading the firmware via ISP using NuMicro ISP Programming Tools. I've noticed (correct me if I'm wrong) that its the same concept with Arduino boards, where the USB port can be used to both programming and communication. I have do my research for several days, but still can't find how to do serial communication between Nuvoton and PC, since when I do programming using NuMicro, I use "USB" connection type, and on my PC, there is no COM PORT listed.
My question, Is it possible to do serial communication via Nuvoton USB port? If its possible, can you please point me where to look?
Thanks in advance. Please tell if I should add more details about this question.
|
You can find the examples in the BSP documentation. Look for samples of USBD_VCOM. To be able to communicate with your PC, you have to install the driver of Virtual COM manually
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "serial port, arm"
}
|
Is captcha on nth login attempt is really stops bots?
I have a requirement to show google reCaptcha on 2nd attempt on login screen.
But frankly speaking I consider it not the way to stop bots.
Because on server side I cannot tell whether this is the first or second login attempt unless the user chooses to send some kind of cookie along with the request so I can identify which number of login attempts he is trying - hence HTTP protocol is stateless in nature.
And I believe bots are not stupid to send some cookie that make the server figure out any information about them.
I heard about some sophisticated solutions like a js script to run on the login page load to generate some id and then to send this id to the server and make the server to check this id, but still an intelligent-enough bot can simulate all this actions. but this is not what I am asking about.
Any advice?
|
Storing the number of failed logins in the session or in the cookie does not work. As you pointed out, the attacker can simply delete the cookie. A better way is to keep the number of failed login attempts on the server, corresponding to the user name or the IP address used. If someone enters the wrong credentials, you increment the counter for that IP address or for that username on the server. This way the client can not alter it.
|
stackexchange-security
|
{
"answer_score": 4,
"question_score": 2,
"tags": "captcha"
}
|
Android Studio, gradle plugin and gradle version information missing
It seems this is not updated anymore:
<
Where can I find this now?
|
This is the closest result I could get.
<
Hope this helps.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "android, android studio, android gradle plugin"
}
|
Tocloft and List of Figures: Get rid of title and begin right at the top
I am using `tocloft` to create an List of Figures. Now I would like to get rid of title and the list of figure should begin right at the top after the chapter title. I know the following is not a minimal example, but it should be understandable.
In the preamble I have this:
\usepackage{tocloft}
\renewcommand{\cftfigpresnum}{Abb. }
\settowidth{\cftfignumwidth}{Abb. 10\quad}
%\setlength{\cftfignumwidth}{2cm}
\renewcommand\cftfigfont{\footnotesize}
\renewcommand{\cftfigdotsep}{\cftnodots}%punkte im abb. verzeichnis.
\cftpagenumbersoff{figure}
\setlength{\cftfigindent}{0pt}
And between begin and end
\begin{document}
% in between there are many figures...
\renewcommand\listfigurename{}
\chapter{Abbildungsnachweise}
It should begin here.
\listoffigures
\end{documen}
!Example of output
|
Instead of calling `\listoffigures`, use
\makeatletter
\@starttoc{lof}% Print List of Figures
\makeatother
directly, or remove the header construction suggested by `tocloft`:
{\makeatletter
\let\@cftmakeloftitle\relax
\listoffigures% Print List of Figures
\makeatother}
The latter (perhaps preferred) solution stems from the definition if `\listoffigures` in `tocloft.sty` (note the `\@cftmakeloftitle` that is not needed, since you're providing your own):
\renewcommand{\listoffigures}{%
\@cfttocstart
\par
\begingroup
\parindent\z@ \parskip\cftparskip
\@cftmakeloftitle
\if@cfttocbibind
\@cftdobiblof
\fi
\@starttoc{lof}%
\endgroup
\@cfttocfinish}
\fi
|
stackexchange-tex
|
{
"answer_score": 7,
"question_score": 4,
"tags": "spacing, table of contents, tocloft"
}
|
Extract part of a git repository?
Assume my git repository has the following structure:
/.git
/Project
/Project/SubProject-0
/Project/SubProject-1
/Project/SubProject-2
and the repository has quite some commits. Now one of the subprojects (SubProject-0) grows pretty big, and I want to take SubProject-0 out and set it up as a standalone project. Is it possible to extract all the commit history involving SubProject-0 from the parent git repository and move it to a new one?
|
See <
I think you need something like
git filter-branch --subdirectory-filter Project/SubProject-0 --prune-empty -- --all
in a clone of the repository.
|
stackexchange-stackoverflow
|
{
"answer_score": 40,
"question_score": 35,
"tags": "git, repository, extract"
}
|
How to set JQuery Mobile datebox popup at the center of window?
I'm using JQM datebox as following now:
<input name="startTime" id="startTime" type="text" data-role="datebox" data-options={"mode": "datebox"}>
But the datebox doesn't pop up at the center of window.
How can I to do it?
|
You can force the Position of the PopUp: <
Example 1 (<
`<input name="startTime" id="startTime" type="text" data-role="datebox" data-options='{ "mode": "datebox", "popupPosition": "window"}' />`
Example 2:
<input name="startTime" id="startTime" type="text" />
<script>
$("#startTime").datebox({
mode: "datebox",
popupPosition: "window"
});
</script>
This will force it to center in browser window. You can also center over another element by it's ID if you want.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "jquery mobile, datebox"
}
|
Does a Firbolg lose their invisibility granted by the Hidden Step trait if a creature they summon attacks or deals damage?
The description of the firbolg trait Hidden Step states (VGtM, p. 107):
> As a bonus action, you can magically turn invisible until the start of your next turn or until you attack, make a damage roll, or force someone to make a saving throw. Once you use this trait, you can't use it again until you finish a short or long rest.
If you summon a creature and command it to attack and deal damage for you, does that count as you making an attack/damage roll, and therefore breaking your invisibility?
Or does the fact that your summon is its own creature mean that you didn't make any rolls that would break your invisibility (though your summon did, while having no invisibility)?
|
### You and a creature you summon are different creatures.
Hidden Step stipulates that it ends if _you_ do any of the things:
> or until **you** attack, make a damage roll, or force someone to make a saving throw.
Since a creature you summon is a creature that is not you, your invisibility does not end if the creature does one of the things.
|
stackexchange-rpg
|
{
"answer_score": 9,
"question_score": 6,
"tags": "dnd 5e, racial traits, summoning, firbolg"
}
|
What would be the possible cause of an IE extension not loading?
I have created a simple IE extension. When I run regasm it successfully registers and when I go into "manage add-ons", there it is.
BUT, when I try to put it on someone else's PC, it successfully registers but does not show up when I go into manage add-ons.
I can only get it to work on my PC.
I'm running windows 8.1. It has been tried on another similar 8.1 setup.
It has been compiled to .NET 4.0 which is on the other PCs.
I have tried emptying my PATH variable to see if that made a difference and it still worked on mine.
I have installed VS on the target PC and compiled it on there.
Every time it registers fine appears in regedit, but not in IE add-on manager.
I'm using IE 11.
Any ideas anybody?
|
Doh - figured it out in the end. There was another registry entry that needed to be added manually:
On 32 bit windows:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\explorer\Browser Helper Objects
On 64 bit windows:
HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Explorer\Browser Helper Objects
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "internet explorer, dll"
}
|
Error in Github when I do "git push origin master" (error: src refspec master does not match any)
My branch in the Github repository is "master". In the terminal I did:
**git branch**
and the output is:
*** main**
**my-temporary-work**
I wanted to push a file to Github and I used:
**git add exploratory_analysis.ipynb**
**git commit -m "New version"**
**git push origin master**
The "git add" and "git commit" commands work. However, the last command (i.e., "git push origin master") does not work, and I get this error:
**error: src refspec master does not match any**
**error: failed to push some refs to '[email protected]:NAME-OF-USER/REPOSITORY-NAME.git'**
That is, it looks like I cannot push any code from my laptop to Github. How can I fix it?
|
I faced the same issue some days ago. If you created a new repository nowadays(2020) then the default branch in `main` on GitHub.
you can check on GitHub now in your repository branches.
so that's why you need to run
git push origin main
instead of
git push origin master
Goodluck with more details you can watch video
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "linux, git, github"
}
|
What happens when we improve a suggested edit?
> **Possible Duplicate:**
> How do suggested edits work?
When going through the Suggested Edit queue, with my > 3K reputation on SuperUser, what happens if I select the `Improve` button and edit it? Does the edit go into effect right away since I have the reputation? Does it need the extra person to vote on it since I accessed it from the Review queue? Does it throw itself back into the queue as an entirely different suggested edit?
|
If you "improve" a suggested edit and no one else makes a bigger change to the post by improving the edit also then it's equivalent to you editing the post, since you have enough reputation.
The post gets instantly approved and no one else needs to vote on it.
|
stackexchange-meta
|
{
"answer_score": 2,
"question_score": 0,
"tags": "support, suggested edits, review, improve edit"
}
|
How can I get size of array after innerHTML.split?
I got a string "Testing - My - Example" And I want to split it with " - ". like this:
variable = innerHTML.split(" - ");
how do i get the size of the array?
|
`variable.length`
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "javascript, innerhtml"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.