INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
MySQL - Know the next ID
There are a few questions about this on SO, but none of them applies here. The questions are all about knowing an ID before inserting a row (and the answers are all "insert your stuff, then get the ID"). In my case, I don't want to insert anything, I just want to know the current state of an auto increment column.
* I have a table with an auto increment column.
* If I add a row, it will get id = 1.
* If I delete this row and add another one, the table will have only 1 entry, but it will get id = 2.
I want to know which ID will be used next by this column.
Since I can't rely on the table to know this, I searched in the information_schema table, but didn't find such data.
Is there a place where the next (or current) auto increment value is stored ?
|
You can look it up by doing a query like :
SHOW TABLE STATUS WHERE `Name` = 'table_name'
In the result you get a column named Auto_increment. This is the value you are looking for.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "mysql"
}
|
US SMS transactional notification opt-out requirements
This is probably on the borderline of being a programming question, but this is really about technology choice at the end of the day.
I am trying to work out what functionality the system should support in the USA, distributing receipt notifications for payments via email and SMS, regarding SMS opt-out. Is it mandatory that for transactional SMSs the user should be able to 'unsubscribe from all communications'? To stress: this is ONLY transactional SMSs (receipts)
|
Twilio developer evangelist here.
If you're considering this because you are building a service using Twilio, then you need not worry about building this functionality. Twilio handles opt out messages for you.
If you are only delivering transactional SMS messages and think that opt outs should not apply, I encourage you to get in touch with Twilio support to discuss this in more detail.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "sms, twilio"
}
|
how to i can to find webhook address in my telegram bot?
I create a bot in telegram and set webhook in my domain address. Now i want to change my domain bot i forget page of webhook in my website. Is there a way I can find my robot's webhook address?
my website create by asp.net mvc!
|
<
You could try the `getWebhookInfo` method. It returns the URL along with other information.
Ref doc here.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "asp.net, asp.net mvc, telegram bot, telegram webhook"
}
|
x64 C++/CLI assemblies still reference to x86 .NET libraries
My development environment is Visual Studio 2010. I'm using managed code in my C++ project, compiling with `/CLI` flag and adding `/FU` with .NET DLLs.
When I'm compiling with 32-bit target machine everything goes right, but when compiling to 64-bit, it seems that the compiler still uses the x86 .NET DLLs.
Additionally, the relative path in **Project Properties -> Common Properties -> Framework and References -> (System) Assembly reference properties -> Relative Path** (uneditable) is pointing to an x86 file.
Is there a solution?
|
This is entirely normal and **not** a problem. Reference assemblies are only used by the compiler to retrieve metadata, the declarations of the types in the assembly. The equivalent of .h files in native C++. Those declarations do _not_ depend on the target architecture.
Architecture dependency is resolved at runtime. For .NET Framework assemblies that contain native code (mscorlib.dll, System.Data.dll, PresentationFramework.dll), the correct assembly is retrieved from a different GAC subdirectory. The GAC_32 subdirectory contains assemblies with 32-bit native code, GAC_64 for 64-bit, GAC_MSIL has the assemblies that contain pure IL and therefore have no architecture dependency.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": ".net, visual studio 2010, c++ cli, 32bit 64bit"
}
|
Dbcontextoptions unable to understand
I didn't understand this statement why using " : " colon sign is it inheriting base function or some thing else. I get confused on ":base(option) {}" it doesn't make sense
public ApplicationDbContext(DbContextOptions options) : base(options) {}
|
In order to explain what is happening, first I'm going to make a few assumptions:
**1)** The class in which your constructor code
`public ApplicationDbContext(DbContextOptions options) : base(options) {}`
resides in is called " _ApplicationDbContext_ ".
**2)** ApplicationDbContext inherits directly from the " _DbContext_ " class. Which makes DbContext the **base** class of ApplicationDbContext.
" **: base** " means ' _call the constructor of the base class when the constructor of ApplicationDbContext is called._ '
" ** _: base(options)_** " means ' _call the constructor of the base class using the passed parameter of the type DbContextOptions called "options", when the constructor of ApplicationDbContext is called_.'
The " **:** " symbol is part of the C# syntax to specify the calling of a base method.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "entity framework, dbcontext, radix"
}
|
Joomla, display different templates for each article
I have 2 Joomla templates installed on my site, I would like one of the pages to use the one template and the rest of the site to use the other template.
Is this possible?
|
This is for Joomla 1.5 it may be different in Joomla 1.0.
Yes it is possible, if the page is linked to a menu item.
Goto the Template manager (Extension/Template manager)
Select the template you want to use for all your pages and set it as default.
Open the template you want for the one pages. You will see a block "Menu assignment" in there select the option "Select from list" and then select the Menu Item your page is linked to and save.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "templates, joomla"
}
|
Got Questionmarks during updating into SQL
When am going to make an update into my data base from hosted application online .. i got into whole cells of updated Row .. Question marks '???' .. is that conflict with language .. cauz i write into Arabic and update also into Arabic . but if i Wrote into English Update Success .. and for notice . inserting by Arabic or English is Successful .. but only into Updating English Success and Arabic Alphabetic converts to '?????' questionmarks and iam using .. SQL Server 2008 of Microsoft Visual Studio 2010
|
To preserve caracter encoding in your oracle or MSSQL database, use a 'N' in front of your text values:
UPDATE yourTable SET yourcolumn = N'newtext';
:-)
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 2,
"tags": "sql, sql server, sql server 2008, encoding"
}
|
Can I override a globally defined API in a C++/MFC project?
I need to ensure that message boxes are shown only if my app is running in an interactive desktop. So I was thinking, can I override ::MessageBox and AfxMessageBox with my own implementation (from a C++/MFC project, compiled with VS 2008)?
PS. I do not need global hooks. This needs to work only from my app's code. For instance, if somewhere in the code I have `::MessageBox(...);` it should let me call my own method instead of linking to the system API.
|
The default MessageBox (actually MessageBoxA or MessageBoxW) is defined as an export, so unfortunately you can't just define a local version to link in first. If you have access to all the source that uses MessageBox it's simple to redefine the MessageBox macro after including windows.h though:
#include <windows.h>
#undef MessageBox
#define MessageBox MyMessageBox
If you have 3rd party binaries or something where you don't compile the code this wouldn't work of course.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "c++, winapi, visual studio 2008"
}
|
Captive portal login using google apps
I have portal login page which is developed by PHP and there is in another side free radius server run into Ubuntu machine the authentication occurred by MySQL database and every thing go fine when registered user trying to access the internet, he must insert username and password. after that this user will authenticate using a free radius server. now I want users to be able to log in using google apps where I can insert users there . I installed the google authenticator in ubuntu machine and it can generate QR code successfully , but how can I use it . in another word , I have g suit account and domain where I can insert the users who can log in to my captive portal . how can I do that and why I must use google authenticator because I don't know how can I using it in my system because google authenticator only generate QR code that means every body can log in to my portal and I don't want that I hope I explained my problem clearly
|
I hope I have understood your question correctly. Basically, you want to authenticate the user in Freeradius by using google authenticator.
You can't directly pass the QR code to Freeradius but you can do is once the user is authenticated using QR code on the web you can generate unique username and password based on QR code session and insert that values into radcheck and pass same username and password in the authentication request.
This is very generic approach to social media authentication on captive portal using Freeradius
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "freeradius, google authenticator, captiveportal"
}
|
Looking for a css selector that selects all childs after nth child
Is there any css selector available that selects all childs AFTER a specific child?
For instance, I have a parent that has 10 child elements. I want to hide all child elements coming after the 4th child.
Is there any selector that lets me select all childs after the 4th one?
I know I can do the reverse i.e. : Hide all and only show the first 4 ones but I was wondering if the reverse is possible.
My current sollution:
.parent .child {
display: none;
}
.parent .child:nth-child(-n+4){
display: block;
}
My desired sollution:
.parent .child {
display: block;
}
.parent .child*some selector that selects all after the 4th child*{
display: none;
}
My expected outcome:
**_Fiddle_**
|
You can do it like this:
.parent .child:nth-child(n+5){
display: none;
}
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "css, css selectors"
}
|
CentOS how to delete files in |MOUNT_POINT|
When I was looking for big files that were using a lot of space on my CentOS VM, I noticed the following:
/home/|MOUNT_POINT|/backup/11-17-14/custom/home/user1.tar.gz
/home/|MOUNT_POINT|/backup/11-17-14/custom/home/user2.tar.gz
/home/|MOUNT_POINT|/backup/11-17-14/custom/home/user3.tar.gz
/home/|MOUNT_POINT|/backup/11-17-14/custom/home/user4.tar.gz
/home/|MOUNT_POINT|/backup/11-17-14/custom/home/user5.tar.gz
/home/|MOUNT_POINT|/backup/11-17-14/custom/home/user6.tar.gz
I would like to delete these backup files, however I see no `/home/backup/`, nor `/backup/` and I can't enter the `|MOUNT_POINT|` directory itself. What can I do?
|
Some possibilities:
To `cd` into the directory, use one of the following:
* `cd '/home/|MOUNT_POINT|'`
* `cd /home/\|MOUNT_POINT\|`
To remove the stuff:
rm /home/\|MOUNT_POINT\|/backup/11-17-14/custom/home/user?.tar.gz
|
stackexchange-serverfault
|
{
"answer_score": 3,
"question_score": 0,
"tags": "centos, mount"
}
|
How to set up Incoming Connection over modem for offline Windows 7 system
I have a Windows 7 computer that will be offline except for a modem connection.
From a previous question I have worked around an error setting up the Incoming Connection. (The RemoteAccess service could not start unless a network connection was already established)
However when I remove the network connection and reboot, the connection does not persist. From the previous answer, I'm hoping that if I can find a way to intialize the TCP stack when the computer boots up, despite there being no network connection available, my modem's Incoming Connection will show up as a network connection and I'll be able to dial in.
How to get the stack to initialize properly, or how to otherwise work around this problem?
|
You should be able to add a loopback adapter to the machine to enable the functionality you're looking for:
* Start / `hdwwiz.exe`
* Choose "Install the hardware that I manually select from a list (Advanced)"
* Choose "Network adapters"
* Choose "Microsoft" in the "Manufacturer" pane and "Microsoft Loopback Adapter" in the "Network Adapter:" pane
* Complete the installation
Once the loopback adapter is installed you may need to assign a static IP address to get the functionality you're looking for w/ Routing and Remote Access.
|
stackexchange-serverfault
|
{
"answer_score": 5,
"question_score": 4,
"tags": "windows, networking, windows 7, modem"
}
|
jquery capturing text of selected id
If I have id's of the form: `t_*` where * could be any text, how do I capture the click event of these id's and be able to store the value of * into a variable for my use?
|
Use the **_starts with_** selector `^=` like this:
$('element[id^="t_"]').click(function(){
alert($(this).attr('id'));
});
Where `element` could be any element eg a `div`, `input` or whatever you specify or you may even leave that out:
$('[id^="t_"]').click(function(){
alert($(this).attr('id'));
});
**Update:**
$('[id^="t_"]').click(function(){
var arr = $(this).attr('id').split('_');
alert(arr[1]);
});
**More Info:**
* <
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "javascript, jquery, dom"
}
|
python logger, disable log for some modules
Is it possible to disable logs for some modules in my project? I have this log_config.ini:
[loggers]
keys=root
[handlers]
keys=stream_handler
[formatters]
keys=formatter
[logger_root]
level=DEBUG
handlers=stream_handler
[handler_stream_handler]
class=StreamHandler
level=INFO
formatter=formatter
args=(sys.stderr,)
[formatter_formatter]
format=%(asctime)s %(name)-4s %(levelname)-8s %(message)s
|
[logger_modulename]
handlers=null_handler
propagate=0
qualname=modulename
level=NOTSET
[handler_null_handler]
class=NullHandler
level=NOTSET
Do not forget to add `null_handler` and `modulename` under `handler` and `loggers` sections.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -1,
"tags": "python, logging"
}
|
What do production game systems pack into the attribute fields in WebGL?
It looks like you can pass in multiple things in the vertex buffer in addition to the position, such as color. What are a list of all the attributes used by production game systems in complex environments? What is a good example? Some things that come to mind:
* velocity/torque
* mass/density
* temp/energy
* emission/absorption
Is there a common set of things?
|
Though the per-vertex attributes are very game specific, I am listing down a few based on categories.
1. Geometric data
* Position
* Normals
* Texture coordinates (multiple, based on number of textures)
* Tangent, Bitagent (For normal map calculations)
* Joint weight (joint id, weight)
* Joint transform matrix (transformation matrix for joints)
* level of details (tessellation)
2. Material data
* Vertex color
* reflection value
* refraction value
* Various light info (Emissive, ambient and other methods)
3. Physics data
* mass / density
* force
* velocity
4. Particle data
* index
* age
* lifetime
* size
* velocity
* angular velocity
Please feel free to keep updating this space.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "graphics, opengl es, shader, webgl"
}
|
python class method that receives an object of its class
I want to create a Square class that has method to calculate the distance from another Square. Here is how I have defined it:
class Square:
def __init__(self, _x: int, _y: int):
self.x = _x
self.y = _y
def distance(self, _other_square: Square) -> int:
pass
The `_other_square` is an object of type `Square`. This gives me an Unresolved reference 'Square' error.
Is there a way to get around it?
|
Change the function definition to this:
def distance(self, _other_square: 'Square') -> int:
pass
The type hint is now a `str` instance which will be resolved after the module has been loaded, and therefore the `Square` type is defined. See here for all details.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 2,
"tags": "python, class method"
}
|
R getting mean for every nth row
is there a more elegant way of getting a mean for current to prior nth row? For example,
x=replicate(3, rnorm(20))
what I want is to get a mean of the column 2 for each row + 2 rows prior. The way I currently would do this is to 1) create an empty column 2) loop through each row and get values from prior 2 rows, mean it, then store it in the new column. It's tedious so I'm wondering if there is cleaner, faster method? thanks in advance. ahdee
|
Try `filter` \- what you are doing is a rolling mean.
filter(x[,2], rep(1/3,3), sides=1)
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "r, matrix, apply, sapply"
}
|
Как правильно сравнивать pointer и integer?
Следующая ошибка:
`[bcc32c Error] bcbl.cpp(47): comparison between pointer and integer ('int' and 'const char *')`
Код:
String str = "text,text";
if (str[5] == ",") // ошибка
в чем я неправ и как правильно сравнивать?
|
Нужно сравнивать `char`.
String str = "text,text";
if (str[5] == ',')
Причина такова:
Вот это `str[5]` == `char`, а вот это `","` == `const char*`, но `','` == `char`.
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "c++builder"
}
|
Reading an xml file through a java program
I have an file which contain XML tags and the name of the file is abc.xml,I just want to know which is the best IO technique that I should use to read that xml file means memory mapped IO , buffered reader and which one is fastest to read xml file through a java program.
|
There are two main schools of parsing XML files: using SAX and JAXP. SAX is a stream oriented parsing technique. It means that you read a file tag after tag and can't go backward. It's quite simple and fast but using it to realize more advanced tasks might be difficult. JAXP on the other hand represents the document as an object tree (DOM structure). It's slower and needs more memory but it's often easier to use in complex manipulation of XML files. Knowing both techniques is the software-engineer's 'must know'.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "java, io"
}
|
For loop to search for word in string
I can't seem to find the syntax needed for the for loop in this method. I am looking to iterate through the words in the string `suit`.
EDIT: one thing to note is that cardArray is a ArrayList.
public String getSuit(int card){
String suit = cardArray.get(card);
for (String word : suit){
if (word.contains("SPADES")){
suit = "SPADES";
}
}
return suit;
}
|
You could use
for (String word : suit.split(" ")) {
to split on every space character (U+0020).
Alternatively:
for (String word : suit.split("\\s+")) {
This splits on every sequence of whitespace character (this includes tabs, newlines etc).
|
stackexchange-stackoverflow
|
{
"answer_score": 11,
"question_score": 8,
"tags": "java"
}
|
Pattern in lua with anchors not matching
Why this does not match? I want to match the exact pattern 2 letters followed by 3 numbers
s = "dd123"
for w in string.gmatch(s, "^%a%a%d%d%d$") do
print(w)
matched = true
end
|
If you just want to see if a string matches a pattern, use `string.match` instead.
s = "dd123"
print(string.match(s, "^%a%a%d%d%d$")) -- dd123
`string.gmatch` is for finding all matches in a string, and doesn't work correctly with `^` and `$`.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "lua, lua patterns"
}
|
Testfor items in hopper 1.12.2!
For a system I need a hopper check and check which type of wool is inside the hopper so I tried this: (I execute the command in chat while I was standing on top of the hopper)
/testforblock ~ ~-1 ~ minecraft:hopper -1 {Items:
{Slot:0b,id:"minecraft:wool",Count:1b,Damage:0s}}
Output:
> The Block at 3 50 20 did not have the required NBT keys
So I looked on internet but it still didn't work, so can anyone tell me what I am doing wrong? I need help with the DataTag, but if anything else is wrong tell me.
 and I've got this problem where the jobs I create always stay in "STARTING" status after execution.
Here's the command, pretty straightforward:
DEL /F /Q \\server\share\*.*
IF NOT ERRORLEVEL 0 GOTO EndError
EXIT 0
:EndError
EXIT %ERRORLEVEL%
At first I did not have the `EXIT` statements, so I thought that was it. But alas, it's still doing it. Mind you, I'm FORCE STARTING this specific job to test it. It is part of a box, but I'm not starting the box itself, I want to test the jobs piece by piece.
Any ideas ?
|
job cannot connect to the AutoSys service on a machine where job should be started. Restart or configure service (agent).
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "cmd, autosys"
}
|
Pointer triangle in C#
I have a simple quastion. I have this C# code:
static void Main(string[] args)
{
int num1, i, j, x, y;
Console.WriteLine("enter number");
num1=int.Parse(Console.ReadLine());
for (i=1; i<=num1; i++){
for (j=1; j<i+1; j++) {
Console.Write(i);
}Console.Write("\n");
}
for (x=num1; x>=0; x--){
for (y=0; y<x; y++) {
Console.Write(x);
}Console.Write("\n");
}
Console.ReadLine();
}
!enter image description here The middle line is repeat twice
Which print triangle from numbers. The problem is that the middle line is repeated twice. My question is how can I change the loop, so the middle line numbers will repeat twice? Wish for help, thanks!
|
Because both for loops include `num1` as an inclusive condition:
for (i=1; i<=num1; i++){
// num1 is the last number in this loop
}
for (x=num1; x>=0; x--){
// num1 is the first number in this loop
}
Change the first loop to stop BEFORE `num1`:
for (i=1; i<num1; i++){
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "c#, for loop, geometry"
}
|
Sublime Text 2 Mac Removing Folders on Close
I use Sublime text 2 as my IDE at both work and home. On a windows machine sublime remembers all the folders in the left had column when the programme is closed ect.
However on my mac using sublime removes the folders as soon as that window is closed.
Does anyone know how to fix this?
|
This option should be under Sublime Text 2 -> Preferences -> Settings – Default
!enter image description here
// Exiting the application with hot_exit enabled will cause it to close
// immediately without prompting. Unsaved modifications and open files will
// be preserved and restored when next starting.
//
// Closing a window with an associated project will also close the window
// without prompting, preserving unsaved changes in the workspace file
// alongside the project.
"hot_exit": false,
// remember_open_files makes the application start up with the last set of
// open files. Changing this to false will have no effect if hot_exit is
// true
"remember_open_files": false,
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 2,
"tags": "sublimetext2"
}
|
returncode of command in a pipline
The following script runs on Solaris using _/bin/ksh_ and on Linux using _/bin/sh_
cmd | tee -a cmd.log | tail
exit $?
The output of _cmd_ is saved in a file _cmd.log_ and the last lines are displayed on `stdout`.
The purpose of `exit $?` was to exit the script with the return code of _cmd_. Of course this
does not work because `$?` holds the return code of the last command in the pipeline which is
`tail`.
Workaround (I will omit all cleanup activities) :
{ cmd; echo $? > error.file; } | tee -a cmd.log | tail
exit `cat error.file`
But is there another way to get the returncode of _cmd_ and to avoid the creation of a file like _error.file_?
|
Try this:
(cmd; echo $? 1>&2) | tee -a cmd.log | tail
Or, if you want to redirect STDERR to tee:
exec 3>&1; (cmd 2>&1; echo $? >&3 3>&-)| tee -a cmd.log; exec 3>&-
|
stackexchange-unix
|
{
"answer_score": 1,
"question_score": 4,
"tags": "linux, bash, shell script, solaris, ksh"
}
|
What do I with the sampling period when I inverse $\mathcal Z$-transform?
> Given the input $$e(kT_s) = {0.4, 0.8,1.2, - 0.9}, \quad k = 0,1,2,3$$
>
> and transfer function $$T\left(z^{-1}\right)=\frac {z^{-1}-0.8z^{-2}}{1-1.1z^{-1}+0.3}$$ Find the output $Y(kT_s),\quad k=0,1,2,3$
(I don't know why $0.3$ and $1$ haven't been added).
Starting with the inverse transform I found $$T(k)=\frac{1}{1.3}\left(\frac{1.1}{1.3}\right)^{k-1}u(k-1)-\frac{0.8}{1.3}\left(\frac{1.1}{1.3}\right)^{k-2}u(k-2)$$
I'm not sure if that is correct as I'm not so familiar with $\mathcal Z$-transform. Anyway, I don't have a sampling period in $T(k)$. Do I just put a $T_s$ next to $k$? Do I ignore $T_s$ and do the following? $$Y(0)=T(0)E(0)$$
$T(0)=0$ so $Y(0)=0$, but why am I given $0.4$ for $E(0)$? This has to be wrong. $$Y(1)=T(1)E(1)=\frac{1}{1.3}0.8=10.4 $$ etc etc.
|
There should probably be a $z^{-2}$ term with the $0.3$. It looks like a typo.
Once you've transformed to the $z$ domain (or discrete-time), and are not interested in transforming back to the continuous-time domain, there is no real need to carry the $T_s$. Just refer to $e[k], y[k]$, etc.
|
stackexchange-dsp
|
{
"answer_score": 2,
"question_score": 2,
"tags": "discrete signals, sampling, z transform, homework"
}
|
Distribution of this random variable
What family of distributions does the following cdf belong to? I know this is a dumb question but I've searched for quite a while online coming up empty.
$F(x) = \begin{cases} e^{-x^{-\alpha}} & x > 0 \\\ 0 & x \leq 0 \end{cases} $
for $\alpha > 0$
|
This is a Fréchet distribution and is related to the Weibull distribution and the Gumbell distribution through the Fisher–Tippett–Gnedenko theorem. All are encountered in the context of extreme value theory.
|
stackexchange-math
|
{
"answer_score": 2,
"question_score": 2,
"tags": "probability distributions"
}
|
Why is the empty set finite?
On page 25 of _Principles of Mathematical Analysis (ed. 3)_ by Rudin, there is the definition (excluding the irrelevant parts for this question):
> **Definition 2.4:** For any positive integer $n$, let $J_n$ be the set whose elements are the integers $1,2,...,n$; let $J$ be the set consisting of all positive integers. For any set $A$, we say:
>
> (a) $A$ is finite if $A \thicksim J_n$ for some $n$ (the empty set is also considered to be finite).
I am unsure why the empty set is considered to be finite. Given the defintion, for the empty set to be finite, then $\emptyset \thicksim J_n$ for some $n$.
The issue is for equivalence, there has to exist a one-to-one mapping of $\emptyset$ onto $J_n$. $\emptyset$ has no elements to correspond and since the definition requires $n \in J$, $J_n$ will always have at least one element.
Thus, my question: Why is the empty set considered finite?
|
That definition is a (rare) example of Rudin doing things inefficiently. He could have defined $J_n$ for each non-negative integer $n$ to be the set of non-negative integers less than $n$, so that $J_0=\varnothing$, $J_1=\\{0\\}$, $J_2=\\{0,1\\}$, etc. Then he could have defined a set $A$ to be finite if and only if $A\sim J_n$ for some $n\in\Bbb N$ (where $\Bbb N$ includes $0$). This is essentially the usual set-theoretic definition stripped of some set-theoretic detail that would be out of place here.
|
stackexchange-math
|
{
"answer_score": 15,
"question_score": 9,
"tags": "general topology, relations, equivalence relations"
}
|
Azure Web Job writes files in a website's directory
I attached a Web Job to my Azure website. The webjob prepares a file and I want to save it on a proper folder in the website.
`Environment.CurrentDirectory` run on the script returns a path under a Temp directory: `Temp\jobs\triggered\WEBJOBNAME\q0uwrohv.x5e`
I tried to go down on the directory tree:
string path = Path.Combine(Environment.CurrentDirectory, @"..\..\..\..\..\Data")
But it doesn't work:
C:\DWASFiles\Sites\WEBSITENAME\Temp\jobs\triggered\WEBJOBNAME\q0uwrohv.x5e\..\..\..\..\..\Data
How to make and save files from WebJob to a particular path?
I don't want to use blob store.
|
The path for the root of your Azure Web Site is (usually) `d:\home\site\wwwroot`. `d:\home` is also stored in an environment setting called `%HOME%`.
To get more insight on the different paths you can use on your site go to: ` there' you'll have the **Debug Console** where you can browse through your site and **Environment** to see all the environment variables you can use.
Your WebJob will have access to the same paths/environment as your Web Site.
For more information on this administration site go to: <
|
stackexchange-stackoverflow
|
{
"answer_score": 26,
"question_score": 15,
"tags": "azure webjobs"
}
|
Present tense for future events
Why does it sound perfectly natural to say _Our flight leaves tomorrow at 6pm_ but weird to say _It rains tomorrow at 6pm_? What kind of scenario, if any, could make the _rain_ sentence sound natural?
|
In continuation with the surety-prediction advocated in the other responses, you might also argue that we never know with a 100% confidence that the flight actually leaves at 6pm tomorrow.
The technically correct usage would be (and because the flight schedule is _present_ ) -
> "The flight is scheduled to leave at 6pm tomorrow."
>
> "As per the schedule, the flight leaves at 6pm tomorrow."
But for all purposes of common usage, the sentence you quoted in the question suffices for audience communication.
Regarding your query for the rain situation, the only situation where it would sound appropriate, was it coming from a soothsayer, an oracle or a psychic predicting tomorrow's weather. I guess it is within their business obligations to use such sentences to sound mighty-sure and give themselves an aura of invincibility against nature's vagaries.
|
stackexchange-english
|
{
"answer_score": 5,
"question_score": 6,
"tags": "future, present tense"
}
|
how to Add multiple component in parent component with Angular6
In **parent.component.html**
I have the following HTML
<button type="button" class="btn btn-secondary (click)="AddComponentAdd()">Address</button>
<app-addresse *ngFor="let addres of collOfAdd" [add]="addres"></app-addresse>
and in **parent.component.ts**
private collOfAdd: Array<AddresseComponent> = [];
AddComponentAdd() {
this.collOfAdd.push(AddresseComponent);
}
and in **addresse.component.ts**
@Input() add: string;
How do I make the component `<app-addresse>` appear several times in the parent component by clicking the button present in parent component?
|
I have created a stackblitz for your question please check the below url: <
In this reference you can find hello.component loaded multiple times on click of button.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "angular, typescript, components, angular6"
}
|
Keep the Div at the Bottom of the Page with an Image in it to the right
I am trying to attempt a DIV that should be placed at the bottom right corner of a page with a close button at the top-right corner in that DIV
I have the following markup with me
<div id="message">
<p>Some Message</p>
<span class="shut">
</span>
</div>
I have defined the CSS as follows
#message{
position:fixed;
bottom:0;
height:320px;
width:310px;
background: #453fefe;
padding: 10px 20px;
border-radius: 5px;
}
.shut {
background: transparent url('shutig.png') 0 0 no-repeat;
position: absolute;
top: 4px;
right: 4px;
}
Unfortunately I don't achieve what I am looking for. What's the right way to do it?
|
You have the invalid background color, which makes the CSS not work expectedly. Also the close button can't be rendered because you did not set an explicit size for it.
#message{
position:fixed;
bottom:0;
right:0;
height:120px;
width:210px;
background: #45fefe; /* you set #453fefe which is an invalid color */
padding: 10px 20px;
border-radius: 5px;
}
.shut {
background: transparent url(' 0 0 no-repeat;
position: absolute;
top: 4px;
right: 4px;
width:20px;
height:20px;
}
## Demo.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "html, css"
}
|
Numerical number pattern. and if then else in octave / matlab
I'm trying to get a numerical repeating number pattern like this **1,2,3,4,1,2,3,4,1,2,3,4...** I'm using Octave 3.8.1 which is like matlab
I tried
t=20 %note this number will vary
a=mod(x,5)
but **a is 1,2,3,4,0,1,2,3,4,0,1,2,3,4**
I know I can do odd and even numbers using the code below
for ii=1:20 %note this number will vary
if mod(ii,2)==0
%number is even
else
%number is odd
end
end
But how can I do it with 4 separate number choices of 1,2,3,4
|
>> t=20 %note this number will vary
t = 20
>> maxValue=4; %repeat the numbers 1..maxValue
>> x=0:t-1 %I think this is what you meant to do...
x =
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
>> a=mod(x,maxValue)+1 %cycle through 0..3 and add 1
a =
1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 1,
"tags": "matlab, octave, numerical methods, sequences, sequential"
}
|
Euler equation and conservation of angular momentum (rigid body)
I am a beginner in this field.
Just ask a simple question which confuses me.
Please consider the following:
1. Conservation of angular momentum about fixed point $o$: $\dot{H}_o = M$.
$M$: the total external torque applied to the body about $o$.
2. Euler equation: $I\dot{\omega}+\omega\times I \omega = M$.
$I$: moment of inertia in matrix form (suppose diagonal $I$ for simplicity.)
* * *
My question: If there is no external torque ($M=0$), then from 1., we know $\dot{H}_o=0$ and by $H=I\omega$, we know $\dot{\omega}=0$ (Due to rigid body, $I$ is constant).
However, by 2., if $M=0$, $I\dot{\omega}=-\omega\times I \omega $. So $\dot{\omega}\ne 0$.
It confuses to me. Where am I wrong?
|
The first equation is valid in the space frame of reference while the second one (Euler's equation) is valid in the body frame of reference.
So, in the case of zero torque the (physical ie as expressed in space frame of reference) angular velocity vector of a rigid body vector is indeed constant. But $\omega$ in Euler's equations refer to the angular velocity vector expressed in the (moving) body frame of reference. And because the frame of reference is moving the description of the vector is non-constant.
|
stackexchange-physics
|
{
"answer_score": 1,
"question_score": 2,
"tags": "angular momentum, rotational dynamics, conservation laws, rigid body dynamics, angular velocity"
}
|
How much did the Highschool DxD anime adapt the light novel?
I finished watching season 3 of Highschool DxD and I want to read the LN. I don't know where to start reading. How much did the Highschool DxD anime adapt the light novel, and did the anime adapt the LN well?
|
Season 1: Volumes 1 and 2
Season 2: Volumes 3 and 4
Season 3 episodes 1-9: Volumes 5,6 and 7
Season 3 episodes 10-12: Original
Ovas and Specials: Half of volume 8 and original
The most likely future:
Season 4: Volumes 9 and 10. The way these 2 volumes work it should be this way
I watched the anime and read the light novels.
About your second question yes, it was very well adapted. Season 3 was a mess though so I'd advise you to read it. Just for Koneko it's worth it. It's nice having her fall for Issei and enter mating season. Koneko in the heat is the best Koneko :)
|
stackexchange-anime
|
{
"answer_score": 2,
"question_score": 6,
"tags": "high school dxd"
}
|
French characters encoding issues è is displayed as è in java
I am using a html form to input strings in French. When I read the strings on the server side (Java), some French characters don't get displayed properly.
For example,
è has turned to è
I am testing this feature in two servers. This is working in one (local windows server), but the issue is happening in the remote server with the same code.
Could you please provide some clues as to where I should look ?
Form header
<form accept-charset="UTF-8" method="post" name="dd_add_cat_form" id="dd_add_cat_form">
HTML header in both servers
< HTTP/1.1 200 OK
< Server: Apache-Coyote/1.1
< RlogId: wf.rbcbq672%3F%3CVB%28USD5%3E44-13eb39c8a7e
< Cache-Control: no-cache
< Pragma: no-cache
< Content-Type: text/html;charset=UTF-8
< Content-Length: 2619
< Date: Fri, 17 May 2013 17:49:40 GMT
|
Probably the default charset on the two servers is different.
Then there is some code that is decoding using the default char set which matches in one case and not in the other. Look in the java code for something decoding with the default character code.
For example:
byte[] bytes = ....;
String s = new String(bytes); // uses the default
but this one doesn't use the default
String s = new String(bytes, "UTF-8"); // uses the supplied charset
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "java, html, apache, http, httprequest"
}
|
shell script running infinitely
i have a shell script `run.sh`.
cd elasticsearch-1.1.0/
./bin/elasticsearch
cd
cd RBlogs/DataFetcher/
mvn clean install assembly:single;
cd target/
java -jar DataFetcher-0.0.1-SNAPSHOT-jar-with-dependencies.jar
Here if second line(`./bin/elasticsearch`) executes it runs infinite time, so the next lines will not execute. So what i need is to perform the next lines after 10 seconds. But
cd elasticsearch-1.1.0/
./bin/elasticsearch
sleep 10
cd
cd RBlogs/DataFetcher/
mvn clean install assembly:single;
cd target/
java -jar DataFetcher-0.0.1-SNAPSHOT-jar-with-dependencies.jar
This also will not execute next lines because `./bin/elasticsearch` will not complete its execution in 10seconds. So how can i solve this problem? Please help.
|
Adding `&` at the end of `./bin/elasticsearch` will cause the process to run in a subshell, freeing the current shell up for the next commands.
./bin/elasticsearch &
Change this in your second version of the script and things should run like you want them too.
More information can be found from `man bash`
If a command is terminated by the control operator &, the shell
executes the command in the background in a subshell.
The shell does not wait for the command to finish, and the return status is 0.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -1,
"tags": "shell, unix"
}
|
Group bounds for layer gradient style
I have two layers; one with a gradient style on it directly, and one inside a group with the exact same gradient style applied. However, the gradient's range is the entire canvas, instead of the bounds of the shape(s) inside it. Here's a picture:
!Two shapes with gradients. One inside a group
Is there anyway to constrain the bounds of the gradient to the shapes inside of the group instead of the entire canvas? All other layer styles respect the layer bounds. One solution I've found is to use a mask on the group. However, that gets tedious with multiple shapes very quickly as you have to get the aggregate of the shapes and reapply the mask for every change.
|
Masking is one way to go.
Another way to go is to convert your layer group to a smart object (`right-click` the layer group and select `Convert to Smart Object`) and then applying the layer styles to the smart object. You can of course, at any time edit the smart object (`right-click` the smart object and select `Edit Contents`) which will open as a layer group with each layer inside of it).
|
stackexchange-graphicdesign
|
{
"answer_score": 1,
"question_score": 1,
"tags": "adobe photoshop, layer style"
}
|
Append a text File inside a Zip
I have zip file inside a Text file (file.txt inside a file.zip) and I would like to append to this file another text file file.txt outside the zip file. How can I do this? Is there a solution?
I've tried to add Append =>1 parameters to IO::Compress::Zip but the file inside the zip been overwritten ..
use IO::Compress::Zip qw(zip $ZipError) ;
$filenameToZip = 'file.txt';
zip $filenameToZip => "file.zip",Append => 1
or die "zip failed: $ZipError\n";
Do I need to decompress the zip file, append/merge the two TXT file's and compress the file again? Or is there a better solution?
|
I would recommend using the Archive::Zip module rather than the lower-level module. Unless you know otherwise, I would expect IO::Compress::Zip to know how to do Zip-style compression, but not how to manipulate a Zip archive file.
The documentation for IO::Compress::Zip says:
> This module provides a Perl interface that allows writing zip compressed data to files or buffer.
>
> The primary purpose of this module is to provide streaming write access to zip files and buffers. It is not a general-purpose file archiver. If that is what you want, check out Archive::Zip.
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 1,
"tags": "perl"
}
|
Best way to store multiple passwords into Database
In my database I've a field for the user password (User.UserPassword), I'm using SHA1 algorithm to hash the user input and then I hash it with a salt. Ok, that's fine.
But now I'm authenticating CIFS users too. One protocol of CIFS is NTLMv1, which uses MD4 16 bits (very insecure) for my Samba Java Server.
I can't convert MD4 to SHA1 or compare those hash results. So, I need to save two hashs or compare them. So, I can:
* Save the MD4 hash into User.UserPasswordMD4.
* Save the MD4 hash into some other table, like ExternalAuthenticators
* Save the user full text password and convert it (Blargh)
* Spring Security (I don't know how to do it, yet)
* Your option goes here...
Can anyone help me?
|
Looks like you should store somewhere that RC4 hash, because both client and server should do the same actions on challenge bytes and than server should compare results.
* Saving plain text password - bad idea, forget about it.
* If you save it as PasswordMD4 in database - it not add security more then PC4 by self.
* Saving in other table - no different with previous variant.
* Spring security - don't know how it can be apply here.
You can store important or all DB data on encrypted partition, but it degrade performance a little.
I can suggest store RC4 password into SHA-1 field, but encrypted. 3DES will be enough, maybe with some salt. You already should have salt somewhere for your SHA-1 hash. When you need RC4 hash, simple decrypt value from DB, subtract (or XOR) salt and do usual authentication procedure.
And don't use NTLM v1, it is old and unsecure.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 2,
"tags": "java, authentication, ntlm, cifs"
}
|
Property of function: why only subset relation for intersection?
I'm reading a text book about functions. They present a set of properties of functions, one of them:
> Given $f: A \to B$, the following properties hold for any $C_1, C_2 \subseteq A$
>
> a) $f(C_1 \cup C_2) = f(C_1) \cup f(C_2)$
>
> b) $f(C_1 \cap C_2) \subseteq f(C_1) \cap f(C_2)$
>
> ...
The author then adds a remark:
> Part b) only gives a subset relation. The reason is: having $y \in f(C_1)$ and $y \in f(C_2)$ does not necessarily mean that $y$ is the image of the same element. Since $f$ can be many-to-one, it is possible to have $x_1 \in C_1 - C_2$ and $x_2 \in C_2 - C_1$ such that $f(x_1) = f(x_2) = y$.
There is also an example and I understand in general what is meant, but I can't wrap my head around why we have an 'equals' in the a) property but only a subset-equals in the b) property.
|
Consider the function $x^2$ and let $C_1= \\{ 0, 1, 2, \ldots \\}$ and $C_2= \\{ 0, -1, -2, \ldots \\}$.
$C_1 \cap C_2 = \\{ 0 \\}$ and $f(0)= 0^2=0$. Thus: $f (C_1 \cap C_2)= \\{ 0 \\}$.
But $f(C_1)=f(C_2) = \\{ 0, 1, 4, \ldots \\}$.
|
stackexchange-math
|
{
"answer_score": 2,
"question_score": 1,
"tags": "functions, discrete mathematics, elementary set theory"
}
|
Como pegar valor do Form - Java - Swing
Criei um formulário no `Java` com interface `Swing`, neste tem um campo `textfield` **Texto** e um botão **Enviar** , no código do botão preciso atribuir o valor `informado` no `textfield` a um variável do tipo `String`, qual a função para isto ?
|
Edit: Não tinha visto os comentários, foi mal.
O seguinte código deve funcionar:
`String s = textField.getText()`
E a partir daí tu trata `s` como for necessário.
Caso surjam mais dúvidas a respeito do `TextField`, segue a documentação: <
Abraço
|
stackexchange-pt_stackoverflow
|
{
"answer_score": 2,
"question_score": 2,
"tags": "java, swing"
}
|
Insert new row unless ONE of the values matches another row?
I'm trying to insert new rows into a MySQL table, but only if one of the values that I'm inserting isn't in a row that's already in the table.
For example, if I'm doing:
insert into `mytable` (`id`, `name`) values (10, `Fred`)
I want to be able to check to see if any other row in the table already has `name = 'Fred'`. How can this be done?
Thanks!
**EDIT**
What I tried (can't post the exact statement, but here's a representation):
INSERT IGNORE INTO mytable (`domain`, `id`)
VALUES ('i.imgur.com', '12gfa')
WHERE '12gfa' not in (
select id from mytable
)
which throws the error:
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE '12gfa' not in ( select id from mytable)' at line 3
|
First of all, your `id` field should be an `autoincrement`, unless it's a foreign key (but I can't assume it from the code you inserted in your question).
In this way you can be sure to have a unique value for `id` for each row.
If it's not the case, you should create a primary key for the table that includes **ALL** the fields you don't want to duplicate and use the `INSERT IGNORE` command.
Here's a good read about what you're trying to achieve.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "mysql, sql"
}
|
Sort by dateTime in scala
I have an RDD[org.joda.time.DateTime]. I would like to sort records by date in scala.
**Input** \- sample data after applying collect() below -
res41: Array[org.joda.time.DateTime] = Array(2016-10-19T05:19:07.572Z, 2016-10-12T00:31:07.572Z, 2016-10-18T19:43:07.572Z)
**Expected Output**
2016-10-12T00:31:07.572Z
2016-10-18T19:43:07.572Z
2016-10-19T05:19:07.572Z
I have googled and checked following link but could not understand it -
How to define an Ordering in Scala?
Any help?
|
If you collect the records of your RDD, then you can apply the following sorting:
array.sortBy(_.getMillis)
On the contrary, if your RDD is big and you do not want to collect it to the driver, you should consider:
rdd.sortBy(_.getMillis)
|
stackexchange-stackoverflow
|
{
"answer_score": 9,
"question_score": 6,
"tags": "scala, apache spark, rdd"
}
|
Branch.io returns {} when use Branch.getInstance().setIdentity("your_user_id");
I am getting BranchSDK: `returned {}` as response when i use `Branch.getInstance().setIdentity("your_user_id");`
|
if you want a branch instance back use this method
`Branch branch = Branch.getAutoInstance(context,"your branch key");`
as per the docs
> Singleton method to return the pre-initialised, or newly initialise and return, a singleton object of the type Branch.
After that use can use singleton Branch object throughout your appp
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -2,
"tags": "android, branch.io, referrals"
}
|
How center unordered list with bullets?
I'm new to web programming and I can't figure out, how to place not only text, but also the unordered list bullets in the center? Here is code:
<div style="text-align:center;">
<h2 style="margin-top:43px;" class="text-center">Important years of life and work:</h2>
<ul >
<li>cat nip</li>
<li>laser pointers</li>
<li>lasagna</li>
</ul>
</div>
And here is the pic, to show you what I mean: . It is also not being broken by something else (passively). It just breaks on its own; this is called the middle voice, and while it is expressed by the active verb form in English, it has to be the passive form in Latin.
Second, the English present continuous has no direct counterpart in Latin, you just have to translate it as the present. Using the present participle might seem an obvious solution, but that is not idiomatic in Latin. (All of which is just as well, because no passive present participle exists in Latin.)
So that would leave us with: **rota disicitur**.
But thirdly I think that _disicere_ is a strange verb to translate “break.” Your wheel does not just break. It is driven asunder, smashed to pieces, scattered! I would instead go with _frangere_ or _confringere_ , so we end up with: **rota confringitur**.
|
stackexchange-latin
|
{
"answer_score": 12,
"question_score": 6,
"tags": "english to latin translation, translation check"
}
|
What is the use of explicitly calling EvaluatePacket?
I noticed that many examples of C code for communicating via MathLink with the Mathematica kernel first pass an EvaluatePacket call to Mathematica, like this:
WSPutFunction(lp, "EvaluatePacket", 1);
WSPutFunction(lp, "Plus", 2);
WSPutInteger(lp, 8);
WSPutInteger(lp, 3);
WSEndPacket(lp);
while (WSNextPacket(lp) != RETURNPKT)
WSNewPacket(lp);
int result;
WSGetInteger(lp, &result);
Thus far I have not been able to find out the purpose of the call to EvaluatePacket. Leaving out the statement `WSPutFunction(lp, "EvaluatePacket", 1L);` seems to work fine. Can somebody tell me a bit more about the use of EvaluatePacket?
|
I do not know why it works if no packet is explicitly given, but section 2.3.1 of the old MathLink tutorial is a useful read.
It says,
> Everything that you send to the kernel should be wrapped in a packet head.
Then it details the effect of various packet types. For example, both `EvaluatePacket` and `EnterExpressionPacket` should contain an expression, but the former will not run the main loop, while the latter will.
Thus, I would not omit the packet name even if it does appear to work without it.
|
stackexchange-mathematica
|
{
"answer_score": 2,
"question_score": 2,
"tags": "mathlink or wstp"
}
|
Compiling Fortran 77 with an external library using a Makefile
I have main program `Engine.f` that calls functions/external in `LIB.f`. Unlike C++ and Java there is no include in the main program so it will be possible to compile.
How does my Fortran comiler know that there is another library which I use?
I'm using photran from Eclipse.
The MAKE file:
.PHONY: all clean
# Change this line if you are using a different Fortran compiler
FORTRAN_COMPILER = gfortran
all: src/Engine.f
$(FORTRAN_COMPILER) -O2 -g \
-o bin/Engine.exe \
src/Engine.f
clean:
rm -f bin/Engine.exe *.mod
errors that I get when I compile:
undefined reference to (name of function in **LIB.f**)
|
.PHONY: all clean
all: Engine.exe
# Change this line if you are using a different Fortran compiler
FORTRAN_COMPILER = gfortran
FORTRAN_FLAGS=-O2 -g
%.o: src/%.f
$(FORTRAN_COMPILER) $(FORTRAN_FLAGS) -c $<
Engine.exe: Lib.o Engine.o
$(FORTRAN_COMPILER) $(FORTRAN_FLAGS) \
-o bin/Engine.exe \
Lib.o Engine.o
clean:
rm -f *.o *.mod
In FORTRAN 77, the compiler "just" needs the function to be supplied in a `.o` file at link time. You can test the Makefile below, it should do what you want.
Modern versions of Fortran use module files to structure libraries, if you ever upgrade to that.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "makefile, compilation, fortran, dependencies"
}
|
How to search substring in python?
I want to search through a text file and output substrings that match the user input, but when my program searches each line I want it to only search the characters between the "|" character and the end of the line. But I keep getting the following error:
|
You should use slices. Just replace `,` with `:` in your code:
y = line[char_pos:x]
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "python, file, find"
}
|
PHP Mistake - Whats wrong here?
could anybody tell me please whats wrong with this code ? I get an PHP mistake and cant finde the reason why.
What I want to do is, in the author.php if the author.php is shown as the author php of an person that is subscriber, I want to redirect. If an author.php is shown of any other roles, show it.
$curauth = (get_query_var('author_name')) ? get_user_by('slug', get_query_var('author_name')) : get_userdata(get_query_var('author'));
if ( get_user_role($curauth->ID) === 'subscriber' ):
wp_redirect( '
endif;
|
From the official _code reference_ :
> wp_redirect() does not exit automatically, and should almost always be followed by a call to exit;
So, you need to call **exit** after the redirect:
$curauth = (get_query_var('author_name')) ? get_user_by('slug', get_query_var('author_name')) : get_userdata(get_query_var('author'));
if ( get_user_role($curauth->ID) === 'subscriber' ):
wp_redirect( ' );
exit; //here!
endif;
|
stackexchange-wordpress
|
{
"answer_score": 0,
"question_score": 0,
"tags": "redirect, author"
}
|
From a static dictionary of strings, infer a type/interface describing the dictionary precisely, using string literals for value types
I have a static dictionary:
const myDict = {
1: "one",
2: "two"
}
The default inferred type for this is `Record<1 | 2, string>`.
I would like to derive a type that only accepts the exact string literals assigned to `myDict` properties:
type T = {
1: typeof "one",
2: typeof "two"
}
How can I derive such type? Typing the original dictionary (so `typeof myDict` would equal to my desired type) would work the best for me.
* * *
I know I can assert the type via `as` keyword:
const myDict = {
1: "one" as typeof "one",
2: "two" as typeof "two"
}
but this workaround is very impractical and prone to error with large dictionaries. What would be a better approach?
|
You can accomplish this using a const assertion.
const myDict = {
1: "one",
2: "two",
} as const
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "typescript, dictionary, type inference, mapped types"
}
|
How to get hold of a http-only cookie value in Next.js?
I am developing a web app using Next.js and I used HTTP-only cookies to manage authentication. I set a cookie called token using the following code. I used an npm package called cookie for this
res.setHeader(
"Set-Cookie",
cookie.serialize("token", data.jwt, {
httpOnly: true,
maxAge: 60 * 60 * 24,
sameSite: "strict",
path: "/",
})
);
Now when I use `console.log(req.headers.cookie);` it logs a cookie like `_ga=GA1.1; token=jnsjndjsnjd` this. So my question is how can I get hold of the second cookie called token. When I do `console.log(req.headers.cookie.token)` it says undefined.
|
I was able to find the solution. We need to parse the cookie using `cookie.parse`, so we can access the token cookie as `req.headers.cookie.token`.
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 2,
"tags": "javascript, node.js, cookies, next.js, cookie httponly"
}
|
How to change windows decoration and scrollbar size in Windows 8?
It is possible to have look&feel of Windows 7 in Windows 8 in Desktop mode?
Primary I would like to change windows decoration and e.g. scroll bar look&size and overall GUI controls look&feel, is that possible?
|
Use this Theme to get the Windows 7 Look:
!enter image description here
<
You can get Aero Glass with this DLL:
<
|
stackexchange-superuser
|
{
"answer_score": 0,
"question_score": 0,
"tags": "windows 8"
}
|
Can I emit debug symbols from my Delphi application that Process Explorer can use?
I'm investigating a performance issue with my application written in Delphi 2010. Does Delphi emit symbols that Process Explorer can use when viewing the currently running threads so I can see the function names?
I've blocked out the name of my executable, but you can see it only gives me the memory address of the function, and I'd like to have the resolved function name if possible (like I have for ole32.dll and ntdll.dll because I am using the MS symbol server).
I know this can be done for VC++ applications and WinDbg...can it be done with Delphi applications and Process Explorer?
!enter image description here
|
Yep, what you need to do is make sure the project is compiled with debug info and that the linker emits a _detailed_ map file (project link options). Not sure, but you may also have to check the "include remote debug symbols" on the linker options.
When you have that, you can use a utility to convert the map to the dbg format that ProcessExplorer uses.
We do this at work whenever we need to get a stack trace on a hung thread on one of our testservers.
The Map2Dbg utility we use: <
|
stackexchange-stackoverflow
|
{
"answer_score": 19,
"question_score": 19,
"tags": "delphi, debugging, winapi"
}
|
Parent background over child's
I was wondering maybe there is any way I can do this with CSS.
I have the parent div, and child one. The child is always going to have a background-color, and I want to switch additional class in data loading case. So when data is loading, parent div will have the background image and color (probably rgba with transparency). The reason I want to do this with parent is I don't know the exact number of childen, or resulting height, so loading overlay div seems not to be a good idea...
< here is fiddle, where it can be seen that child's background is over parents
.parent{
background: url(' no-repeat scroll 0% 0% / contain #FFF;
z-index:10000;
position:relative;
}
.child{
width:300px;
height:300px;
background-color: rgba(0,250,250,.7);
}
|
You can do this with a pseudo element which would have to be removed once the loading has finished (but that's another issue). Here I used a hover to show it on and off.
**JSfiddle Demo**
**HTML**
some content
**CSS**
.parent {
position: relative;
}
.parent:after {
position: absolute;
content:"";
top:0;
left:0;
bottom:0;
right:0;
background: url(' no-repeat scroll 0% 0% / contain #FFF;
}
/* temp hover state for demo purposes*/
.parent:hover:after {
display:none;
}
.child {
width:300px;
height:300px;
background-color: rgba(0, 250, 250, .7);
}
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 2,
"tags": "css, html"
}
|
XAML formatting error when using <Style>
I have noticed in a few places that XAML code sometimes formats incorrectly like the third code block on this question.
Am I doing something wrong or is this a bug with the code formatting?
You can also see the issue on this question in the question and the second code block on the accepted answer.
**Update:** It appears this is an issue with the content of `<Style>` tags.
|
This is a known bug in prettify.js: Issue 280: Code in <Style>-Tags is not highlighted as XML when using lang-xml
> The reason is that both HTML and XML are parsed using the same lexer:
>
> <
>
> which detects <style> and <script> tags inside the markup
|
stackexchange-meta_stackoverflow
|
{
"answer_score": 4,
"question_score": 9,
"tags": "bug, syntax highlighting"
}
|
How to fadeIn text in vegaswalk background gallery
Hello i'm playing around with the vegas background script and would like to add a caption to each of the backgrounds using the "vegaswalk" function. all working fine but i would like to add a fadeIn on the div id="marketingText", is it possible? the text needs to fade in each time.
$('body').bind('vegaswalk',
function(e, bg, step) {
if(step == 0) {
$('#marketingText').text("new dialog title 1");
}
if(step == 1) {
$('#marketingText').text("new dialog title some different text 2");
}
if(step == 2) {
$('#marketingText').text("new dialog title more text 3");
}
if(step == 3) {
$('#marketingText').text("new dialog title and some more 4");
}
}
);
i've tried the following
$('#marketingText').hide().fadeIn(3000).text("new dialog title 4");
|
Try like:
var $mark= $('#marketingText');
var textsArr = [ // Array of texts
"new dialog title 1",
"new dialog title some different text 2",
"new dialog title more text 3",
"new dialog title and some more 4"
];
$('body').bind('vegaswalk', function(e, bg, step) {
$mark.hide().text( textsArr[step] ).fadeIn(1000);
});
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "javascript, jquery"
}
|
MySQLdump to directory with WinSCP or similar
On my CentOS VPS server I currently backup all my hosted website files via an automated SFTP session using a script. I use WinSCP for this. Unfortunately, this does not include a backup of the MySQL databases which I have about 20 of.
Is it best to run a scheduled dump of the databases into a folder and then ftp this over, or can I use WinSCP to dump them, individually, on-the-fly into a folder during a session? I would prefer the latter option.
If so, how do I achieve this?
I want to end up with a working backup of my databases, on my local Windows PC, that can be reinstated if required.
Thanks in advance
|
You can use the WinSCP command `call` to run the `mysqldump`, before you start the download (i.e. before the `get` or `synchronize` command).
For examples see:
<
You may need to increase a session timeout (15s default) to allow the `call` to finish in time.
* * *
Alternatively you can run the `mysqldump` using a more appropriate tool, like `plink` (from PuTTY suite), before you start WinSCP script:
<
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 4,
"tags": "mysql, shell, winscp"
}
|
c# Expression lambda to vb.net
After using converters (Redgate, Telerik, ...) I can not turn this expression c # to vb.net
if (afterItemRemoved != null)
{
cacheItemPolicy.RemovedCallback = x => afterItemRemoved(
x.CacheItem.Key,
(T)x.CacheItem.Value);
}
I have tried without success the following expressions (Reflector 8.5 de RedGate y converter.telerik.com)
If (afterItemRemoved IsNot Nothing) Then
cacheItemPolicy.RemovedCallback = x => afterItemRemoved.Invoke(x.CacheItem.Key, DirectCast(x.CacheItem.Value, T))
End If
If afterItemRemoved IsNot Nothing Then
cacheItemPolicy.RemovedCallback = Function(x) afterItemRemoved(x.CacheItem.Key, DirectCast(x.CacheItem.Value, T))
End If
|
Looking at the documentation for RemovedCallback we can see that the required delegate signature is a `void` method (A `Sub` in VB.Net) (see CacheEntryRemovedCallback).
So the lambda expression needed has to be a "Sub Lambda" not a "Function lambda"
If afterItemRemoved IsNot Nothing Then
cacheItemPolicy.RemoveCallback =
Sub(x) afterItemRemoved(x.CacheItem.Key, DirectCast(x.CacheItem.Value, T))
End If
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "c#, vb.net, lambda, expression"
}
|
Why does white vinegar taste better when at restaurants?
Just got back from dinner, where I had some decent fish and chips with white vinegar, and a thought came to me: At restaurants, I've found the white vinegar there helps to accentuate the flavour of the dish, mainly French fries. But when trying to do the same thing at home, the taste is more like I had just thrown on water as opposed to vinegar.
Barring that I'm imagining things (and it's entirely possible), I wonder if anyone else can shed some light on this at all?
|
According to a quick search on Google, there are two other types of vinegar served in fish and chips shops along with malt vinegar.
The first (and my best guess) is onion vinegar -- which is white vinegar that has been used to pickle onions. This is clear, but at minimum contains onions and salt, and perhaps sugar and other pickling spices. (I should note that the recipe I linked to uses malt vinegar to pickle the onions, but you could certainly achieve the same result with white vinegar.)
The second vinegar is actually called non brewed condiment, and isn't actually vinegar. It's ascetic acid, water, and a bit of caramel coloring. The coloring would make it brown, but it wouldn't have the malt flavor.
|
stackexchange-cooking
|
{
"answer_score": 8,
"question_score": 8,
"tags": "food science, vinegar, restaurant mimicry"
}
|
how to get the gridview cell's value while export gridview to pdf using iTextSharp
Currently I try to export an gridview (include an image each row) to PDF file. I find out that PdfPTable table = new PdfPTable(TotalColumns) can help me modify and insert the image to the column. like "table.AddCell(image);"
but how do i insert the gridview (each row)'s each cell's value in to that? (without using findcontrol)
thanks a lot.
|
it's asp.net webforms, right? here is the sample about converting a gridview to pdf using iTextSharp: [^]
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "c#, asp.net mvc, datagridview, itext, cells"
}
|
Automatically fixing bad indentation (Scheme-Lisp)
Let's say I make this code with bad formatting: is there an emacs command that can automatically fix indentation? I know this question has been asked a few times before, but all the answers I've seen seem very technical (I'm a CS noob).
(define (count-until x y list1)
(define (iter list1 score)
(if (eq? (car list1) x)
(iter (cdr list1) (+ score 1))
(iter (cdr list1) score)))
(iter list1 0))
|
Select the whole code (e.g. by pressing `C-Space` at the start and using cursor keys to get to the end) and run `indent-region` (bound to `C-M-\` in my Emacs).
|
stackexchange-emacs
|
{
"answer_score": 1,
"question_score": 0,
"tags": "indentation, scheme"
}
|
Is there an automatically scrolling, time-delayed Unix pager command?
I'd like to view output of big commands slowed down, like a slideshow with e.g. automatic, 500ms delay between each scroll. What is the simplest way to achieve this?
|
A simple solution using `bash`:
function scroll
{
while read -r ; do echo "$REPLY" ; sleep ${1:-0.5} ; done
}
# Usage
long_command | scroll [delay]
`delay` is optional and defaults to `0.5`.
Exit with `Ctrl`+`C`
|
stackexchange-superuser
|
{
"answer_score": 9,
"question_score": 10,
"tags": "unix, less, pager"
}
|
Labour Model - Resource Allocation based off Product Forecasts
at my company, we have a product level forecast that we run through a model which pulls out an hours number for our retail outlets.
We do this by binning various products into categories and give them a time value lets call this `tmv` (timed minute values). So product `coffee` gets a `tmv` of 0:50 s per quantity.
we then do a simple `product` * `tmv` and aggregate up while accounting for certain constraints, such as minimum hours required to run a shop floor, management hours and so forth.
when I inherited this beast, it was all written in excel which I ported into SQL and Python, although a lot of work has gone into it, there is little statistical modeling, optimization, or basic ML applied. Although, I'm not sure what could be done to better optimize this.
I wonder what more to-date tech companies do to allocate their work-force in a retail environment.
|
This problem can be converted to a mathematical model and be solved using the approaches which are admissible with respect to the conditions of the problem. Generally, in optimization, limited resources allocated to some demands while optimizing (minimizing/maximizing) the objective function. So to successfully model your problem you need to verify the followings:
* Variables (can be the number of a specific product to be produced)
* Constraints ( demands should be satisfied, limitations on the available resources)
* The objective function (Maximizing the profit, minimizing the wasted time on the production line, etc.)
After defining the mentioned concepts, the mathematical model, which needs to cover as many details as it can, should be written. The solving approach depends on the type of objective function and constraints that you have in the model. In this link, you can find a set of examples for mathematical modeling of real-life problems.
|
stackexchange-or
|
{
"answer_score": 3,
"question_score": 6,
"tags": "optimization"
}
|
Increase number of Loop Cuts - Apple Magic Mouse
how can I increase the number of Loop Cuts with my Apple Magic Mouse. Normally it is with the scroll wheel, but that does not work with the Magic Mouse. And I know that I can change the number of cuts afterwards, but sometimes the cuts then are unproportional. Even if I set the cut right in the middle by clicking the left mouse button.
!enter image description here
|
You can use the keyboard (both the top row and the numpad work) to type the number of cuts.
The current number of cuts is displayed in the _Header_ , where you can also see the result of modal numinput expressions (modal numinput will be added in 2.7, and is already in development versions):
!enter image description here
|
stackexchange-blender
|
{
"answer_score": 6,
"question_score": 6,
"tags": "edit mode"
}
|
Packaging with Pyinstaller - PyQt5 setStyle ignored
I'm actually have an similar issue as described here after update python, pyistaller, pyqt5, pyqt5-tools. Before I got the desired **"Windows Vista-style"** without `app.setStyle('windowsvista')` when I run the compiled stand-alone executable.
Now I got the Windows **"Classic-style"** instead. If I start the application in PyCharm it will use the desired **"Windows Vista-style"**.
Currently installed on Win7 64bit:
Python : 3.6.4
PyInstaller: 3.3.1
PyQt5 : 5.10
pyqt5-tools: 5.9.0.1.2 ( _update to 5.9.1.1 doesn't work_ )
Does anyone have any idea why PyInstaller ignored the style?
|
The error seems to have been fixed in a unmerged branch of PyInstaller. More information can be found on the GitHub pull request conversation, but reinstalling PyInstaller using `pip install fixed the same style issue for me on Mac.
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 6,
"tags": "pyqt5, pyinstaller"
}
|
What is the Best Practice? Browser extension store JSON data
I am creating a browser extension which retrieves data from a JSON feed. I would like to store this data locally to prevent having to fetch the feed to often. The feed will eventually have over 100 results and the call is made on every new website that is visited, in the end I need an array with the results.
I am not sure at all on how to do this, but I guess (wild guess) that I have two options:
**Option 1:** Store it all with chrome.storage.sync.set, will I be able to do this with such a large array? And only refresh from feed every week.
or
**Option 2:** Write my array to a local file containing the entire array. And only refresh from feed every week.
Does anyone have any ideas on how to do this? Are both options actually possible? Which would be best?
|
You can use < to save your data. Usually the local storage is enough. Sync is used when you need to sync saved data across different user profile instances (when user logged in chrome with same account on desktop and notebook for example)
Also you can store data via file using filesystem api or webstorage api like IndexedDB or WebSQL - <
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "arrays, json, google chrome extension, store, browser extension"
}
|
Convert date value into three separate date parts (day, month, year)
I have three dropdown lists for day, month, and year respectively. I insert them in the database in one date column by combining the values and converting it to date. Now I have to retrieve them again into their respective dropdown lists.
DAY values(1~31)
Month values (Jan-Dec)
Year values (1990-2017)
I use this code when I insert them in the table:
userInfoDTO.Birthday = DateTime.Parse(String.Format("{0}/{1}/{2}", dropMonth.SelectedValue, dropDay.SelectedValue, dropYear.SelectedValue));
|
You can try something like this:
DateTime birthDay; // initialize with the DateTime Field from database
dropMonth.SelectedValue = birthDay.Day;
dropDay.SelectedValue =birthDay.Month;
dropYear.SelectedValue = birthDay.Year;
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "c#, asp.net"
}
|
How to find out what program is sending emails
I have linux (debian) box which is running fine. However I have problem I need to find out what program is sending emails when i use "mail" command. Or for that matter when a PHP script is sending emails with mail() function I need to know what program is sending those emails.
How can I find out?
Ps: To clear, I'd like to know what program is invoked when I (or a program) use the "mail" command.
There are 2-3 MTA's installed on my server but I can't find out which one is responsible for sending mail.
|
**What you're asking how to do:**
`dpkg -S /path/to/mail`
/path/to/mail/ can be found using `which mail`, provided that `mail` is in your path.
_Minor Note:_
Mail also be sent out using `sendmail` instead of `mail`.
**What you should do:**
Look at your maillog, likely `/var/log/maillog` or `/var/log/mail.log` the daemon name should be there.
|
stackexchange-serverfault
|
{
"answer_score": 3,
"question_score": 6,
"tags": "linux, email, debian, configuration"
}
|
Sketching weird Exponential graph
The formula of the line is -
$$ y = 1 + 2^{-x} $$
Sketch the graph and show clearly whether it passes through the point $ (1,1) $
When $X = 0$ , $y =2$, so the $y$ intercept is at $y = 2$ .
When $X = 1$, $Y = 1.5$ , this shows that it does not pass through the point $(1,1)$
When $X = 3$ , $Y = 1.125$.
However when $X = 1000, 10000,100000$ All $Y$ values is $1$,
So how do I go about sketching this graph ? I'm a little confuse . Thanks for the help !
|
Test out a few points. You'll see as x approaches infinity, y approaches 1. As for the other side of the graph, you can see that it just continues increasing, getting very steep very quickly. Here is small section of the graph: , with a naming convention similar to "edits_xxxxxxxxxxx", each of which represents a particular action (called as transaction) done in HDFS such as append file, delete file, etc.,
Edits file/segment is updated first (on the disk) and then the in-memory (in RAM) metadata of the NN is updated. Thereafter this in-memory data will be served to the needy clients.
Courtesy: Hadoop - The definitive guide.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "hadoop, mapreduce, hdfs, bigdata"
}
|
AWK command to display Header, Transform and Footer?
I have used the below command,
awk 'BEGIN{print "Header"};{FIELDWIDTHS ="3 4 3"}{print $1"|"$2"|"$3"
|"};END{print "Footer"}' file8
Actual -
Header
1234567890|||
234|5678|901|
345|6789|012|
098|7654|321|
Footer
Expectation -
Header
123|4567|890|
234|5678|901|
345|6789|012|
098|7654|321|
Footer
|
Your first line is coming out wrong because the action `{FIELDWIDTHS ="3 4 3"}` doesn't get applied until after the first line has been read and parsed.
If you move the `FIELDWIDTHS` definition inside the `BEGIN` block it will work as intended:
awk 'BEGIN{print "Header"; FIELDWIDTHS ="3 4 3"}{print $1"|"$2"|"$3"|"};END{print "Footer"}' file8
Note that `FIELDWIDTHS` might only be supported in GNU Awk (`gawk`).
|
stackexchange-unix
|
{
"answer_score": 1,
"question_score": 0,
"tags": "awk"
}
|
How to open a jar file in a Cocoa App
I am trying to execute a jar in my Cocoa app. My research tells me I should use `NSTask`. However, I am only able to get `system()` to work. E.g.:
// This works
system("cd /path/to ; /usr/bin/java -jar file.jar");
But this doesn't work:
// This does not work
NSTask *task = [[NSTask alloc] init];
[task setLaunchPath:@"/usr/bin/java"];
[task setArguments:[NSArray arrayWithObjects: @"-jar", @"/path/to/test.jar", nil] ];
[task launch];
I get a class not found Java exception when I run my app because it cannot find its dependencies.
|
There is no general error in your code, I tried it out myself.
I assume that you have defined a **CLASSPATH** environment variable in your _.profile_ , _.bashrc_ or whatever, that is required to execute the Java file.
`system()` uses the shell to execute your command, and therefore the CLASSPATH is inherited by the `java` command.
`NSTask` on the other hand does _not_ use the shell, so `java` would not know about the CLASSPATH from your profile.
The solution would be to add `@"-cp", @"<your class path>"` to the arguments.
**UPDATE**
As it turned out in the discussion, the problem in this case was not the class path, but the _current working directory_. Adding
[task setCurrentDirectoryPath:@"/path/to"]
solved the issue.
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 0,
"tags": "objective c, cocoa"
}
|
When do you use a String over int
Hey I'm first year university learning the basics of Java. I was looking through a program that measures the average Rainfall within a year using Arrays. Within the constructor it uses `String year;` \-- why would you use `String` and not `int`? What exactly are `Strings` and what are they used for -- in simplicity**
I tried looking on the internet but there's such a huge variation and it's too complex for me to understand. I have only been learning about Java / CS for a couple months now in University.
|
Conventionally, you use the type that best fits your scenario.
* If you need to do math associated with a number, use a datatype capable of that, like `int`, `double`, `long`, `float`, etc.
* If you don't need to perform math on it, or you're using it as a label, then a `String` is acceptable.
(In all actuality, if you really wanted to do something with the date, such as subtract two years together, ideally you'd use an appropriate object for _that_ , as well.)
From what you describe, the years are only really meant as a column header, and nothing more is required of them, so a `String` is the only appropriate type to use.
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": -9,
"tags": "java, string"
}
|
how to print after the keyword from python?
i have following string in python
b'{"personId":"65a83de6-b512-4410-81d2-ada57f18112a","persistedFaceIds":["792b31df-403f-4378-911b-8c06c06be8fa"],"name":"waqas"}'
I want to print the all alphabet next to keyword "name" such that my output should be
waqas
Note the waqas can be changed to any number so i want print any name next to keyword name using string operation or regex?
|
First you need to decode the string since it is binary `b`. Then use `literal eval` to make the dictionary, then you can access by `key`
>>> s = b'{"personId":"65a83de6-b512-4410-81d2-ada57f18112a","persistedFaceIds":["792b31df-403f-4378-911b-8c06c06be8fa"],"name":"waqas"}'
>>> import ast
>>> ast.literal_eval(s.decode())['name']
'waqas'
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "python, regex, string, python re"
}
|
использование OneHotEncoding с группировкой
Есть данные:
,
'cat_feature': np.array([2, 1, 3, 1, 1, 2, 3, 2])}
d_test = pd.DataFrame(d_test)
|
In [25]: pd.get_dummies(d_test, columns=["cat_feature"]).groupby("id", as_index=False).max()
Out[25]:
id cat_feature_1 cat_feature_2 cat_feature_3
0 1 0 1 0
1 2 1 0 1
2 3 1 0 0
3 4 1 1 1
4 5 0 1 0
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 3,
"question_score": 2,
"tags": "python, pandas, dataframe, group by"
}
|
Update widthAnchor on Device orientation
I have this constraint in my controller for a view like this:
someView.widthAnchor.constraint(equalToConstant: view.bounds.width).isActive = true
Now I've added this constraint in `willLayoutSubviews` to update it on device rotation.
But it doesn't seem to update, even more like it adds another width constraint, which of course conflicts with the old width constraint.
Now I don't really know a proper solution to update this width constraint, but it seems to me like I need to remove the constraint first and then set it again.
Which if I test this like this:
someView.constraints.forEach {
someView.removeContraint($0)
}
This works like expected, only it deletes of course some constraints I don't want to delete... so also not a solution.
|
**Sol1**
hook the width constraint as `IBOutlet` and change it's constant in code like this
self.widthCon.constant = //value
self.view.layoutIfNeeded()
**Sol2**
delete the constraint with identifier
someView.constraints.forEach {
if $0.identifier == "set_id" {
someView.removeConstraint($0)
someView.widthAnchor.constraint(equalToConstant: view.bounds.width).isActive = true
}
}
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "ios, swift, constraints, nslayoutconstraint, nslayoutanchor"
}
|
How can I rename a Rails controller with a route?
I have a controller in a Rails 3 app named "my_store." I would like to be able to use this controller as is, except replacing "my_store" in all the URL's with another name. I do not want to rename the controller file, and all the references to it. Is there a clean way to do this with just a routing statement?
|
If you use RESTful routes:
resources :another_name, :controller => "my_store"
Otherwise:
match "another_name" => "my_store"
|
stackexchange-stackoverflow
|
{
"answer_score": 7,
"question_score": 4,
"tags": "ruby on rails, routes"
}
|
Let’s Encrypt で SSL証明書を自動更新したいのですが、cron設定する際のcertbotのパス指定について
****
sudo yum install certbot-nginx
cerbot
ls /usr/bin/
> certbot -> /usr/bin/certbot-2
> certbot-2
* * *
****
/etc/cron.d/hoge
* * *
****
CentOS7
Nginx
Let’s Encrypt
certbot
* * *
**Q1**
cron&& certbot renew
**Q2**
certbot
certbot -> /usr/bin/certbot-2
**Q3**
/etc/cron.d/hogecertbot
0 1 * * * /usr/bin/certbot renew && systemctl restart nginx
0 1 * * * /usr/bin/certbot-2 renew && systemctl restart nginx
|
> Q1
/etc/cron.d/hoge PATH
SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin ←:
MAILTO=root
0 1 * * * root /usr/bin/certbot renew && systemctl restart nginx
> Q2
`/usr/bin/certbot`
`/usr/bin/certbot` `/usr/bin/certbot-2`
rpm
$ rpm -ql certbot-nginx
> Q3
`/usr/bin/certbot`
/etc/cron.d/
.---------------- minute (0 - 59)
| .------------- hour (0 - 23)
| | .---------- day of month (1 - 31)
| | | .------- month (1 - 12) OR jan,feb,mar,apr ...
| | | | .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
| | | | |
* * * * * user-name command to be executed
|
stackexchange-ja_stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "centos, ssl, letsencrypt"
}
|
Will MTU increase affect all parties?
Will a Maximum Transfer Unit (MTU) increase for the ethernet interface on one device, `box-a` pictured below, in a LAN network also increase the MTU between each of the clients and `box-a`?
, I have to specify the full path to the file, whereas with gcc or g++, I do not have to if it is in the same directory as the code referencing it.
Is there a reason to why this is? And if so, is there a way to fix it?
|
The problem isn't that "XCode" doesn't accept a relative path. The problem is that your code has a different current working directory than you think. You can, as the comment says, use `chdir` to get to a place where your file is, or use a relative path that takes into account the currend working directory (you can use `getcwd()` to get the current working directory).
When you are using `gcc` or `g++` on the command line, _you_ are in control over what directory the final application runs in.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "c++, c, xcode"
}
|
Telnet connection to Android-x86 through VirtualBox
I successfully installed " **android-x86-2.2-generic** " in a VirtualBox machine. I took the iso from here: <
Everything is working properly, even the network (FYI: Bridge with PCnet-PCI II).
I'm using it to have a faster emulator (and it **really** is), and now I need to simulate SMS and Missing Call. Usually in AVD emulator I use a telnet session to localhost:5555/n. But in the VirtualBox, even if I connect to 192.168.1.4:5555/n nothing is working, only a black screen.
I don't even know if it is possible to use telnet on Android-x86... do you know? Is there an other way to simulate SMS and Missing Call without telnet connection?
|
The telnet control port is only available on the android sdk emulator. Android X86 is an actual OS build for devices (can be used also on virtual machines), and does not have this control interface available.
ADB bridge over network is however enabled on these builds, so you can connect the ADB from the host machine by using "adb connect IPADDRESS" command (where the IPADDRESS is the current IP address of the android x86 machine).
I recomend this blog entry on how to futher adapt the Android x86 running VM to be closer to an actual user device (e.g. phone).
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 4,
"tags": "android, android emulator, virtual machine, telnet, virtualbox"
}
|
Store token in LocalStorage
So, I'm trying to store the user token after the login authtentication, but something is wrong, here's my code:
fazerLogin(){
this.authloginService.logarConta(this.email, this.password).then((result)=>{
console.log(result)
localStorage.setItem('token', JSON.stringify({token: this.token}))
console.log(this.token)
this.navCtrl.navigateForward('home')
}
Heres the response data after the login:
{name: "MyName", email: "[email protected]", token: "ed814437611e187679e4719d87e9dfd6e1d8c819", message: "Success."}
email: "[email protected]"
message: "Success"
name: "MyName"
token: "ed814437611e187679e4719d87e9dfd6e1d8c819"
|
You would want to do it like:
localStorage.setItem('token', result.token)
Wherever you have defined this method: `logarConta()`
Give a proper return type to it, like:
logarConta() : {nmae: string, email: string, message: string, token: string} {
// your code
}
If this doesn't suit you, and you want to keep it as `Object` the use this instead:
localStorage.setItem('token', result['token'])
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 2,
"tags": "angular, typescript, ionic framework"
}
|
Removing index.php from url in codeigniter
I tried to remove index.php from url. I tried more links from linkden but have not worked. I tried following.
1.add .htaccess file with following data,
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* index.php/$0 [PT,L]
2.changed in config.php `$config['index_page'] = ''`;
3.activate `mod_rewrite`.
But still not working.
|
Make .htaccess file in root of project directory with following contents:
RewriteEngine on
RewriteCond $1 !^(index\.php|resources|robots\.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L,QSA]
modify application/config/config.php with following:
$config['index_page'] = '';
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": -1,
"tags": "php, .htaccess, codeigniter"
}
|
Quintic diophantine equation
How can I find non trivial primitive integer solutions, to the Diophantine equation $$a^4+b^4+c^4=d^5$$ Can anyone find me solutions to this equation?
Or if possible a parametric equation that generates solutions?
I would appreciate any help
Ive also simplified it to finding coprime integer solutions greater then 1 to the equation,$$xyz(x^2+y^2+z^2)=1250w^5$$ I don't know if that helps at all.
|
We can use the identity,
$$(2p-2q)^4+(2p+2q)^4+(4q)^4 = 2^5(p^2+3q^2)^2\tag1$$
One can then solve,
$$p^2+3q^2 = (a^2+3b^2)^k$$
for any $k$. For $k=5$, it is,
$$p =a^5 - 30 a^3 b^2 + 45 a b^4$$ $$q=b (5 a^4 - 30 a^2 b^2 + 9 b^4)$$
though $(1)$ has the common factor $2$.
|
stackexchange-math
|
{
"answer_score": 6,
"question_score": 8,
"tags": "diophantine equations"
}
|
Apacheds password pattern policy
I am trying to do user authentication using Apacheds Server. For that I am using Password Policy defined. Most of the authentication requirements are met using these policies, but one thing I am not able to do is password pattern. Is there a way to check if user password meets with particular pattern requirements. Requirements I need are:
* Uppercase character
* Lowercase character
* number
* special character
|
You need to provide a custom PasswordValidator to achieve this. See DefaultPasswordValidator if you need an implementation sample.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "ldap, apacheds"
}
|
How To Remove Spaces Between Characters In PostgreSQL?
I want to match two tables based on a specific column which is a card number, there are spaces between characters in some of card numbers in the second table like below:
'NES 123_4_5'
'MTS 678_9_0'
What i want is to remove the space between the characters and numbers and change it to following form:
'NES123_4_5'
'MTS678_9_0'
What would be the SQL query of function to do this?
|
simplest way - use REPLACE function
select REPLACE('NES 123_4_5', ' ', '')
Result - NES123_4_5
full list of string functions - <
|
stackexchange-dba
|
{
"answer_score": 7,
"question_score": 2,
"tags": "postgresql, postgresql 9.5, trim"
}
|
need a method to return the value of a specific bit of an int
I think I need a utility method like this:
public static short bitValue(int intNum, short pos)
{
short bitValue = 0;
//check pos bit (from right to left) in the intNum integer to see its value is 0 or 1
//And then update the bitValue for return
return bitValue;
}
I am doing research to learn how to do it now. If anyone of you guy have code in hand, please share with me. thanks
|
Just do a shift and mask:
return (short) ((intNum >> pos) & 1);
That's assuming you want a return value of 1 or 0, of course. If you want bit itself, still with the same value, you'll need to change your return type to `int` and use:
return intNum & (1 << intNum);
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 2,
"tags": "java"
}
|
How to use breakpoints in F# files in C#/F# MVC4?
I am in the middle of a rather large project that uses the `C#-F# MVC4 template`. The template breaks up the solution into two projects: `[ProjectName]Web` and `[ProjectName]WebApp`. All of the F# code resides in the latter.
I cannot debug the solution unless I hit `F5` from `Global.asax` in `[ProjectName]Web`. But this always misses the breakpoints I have set in my F# files in `[ProjectName]WebApp`.
Is there any way around this problem?
|
You will need to attach to an IIS process. Depending on what you are using this will be listed as either issexpress.exe or w3wp.exe in the debugger attach screen. To do this go to the menu Debug | Attach to process and select the process to attach. Once attached you can debug as per normal without going through F5.
Below is the screenshot of IIS express being listed in the debugger attach screen. Check 'Show processes from all users' if the said processes are not listed.
Hope this helps.
!enter image description here
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 2,
"tags": "f#, breakpoints"
}
|
VM Infrastructure client reporting an error in our HA/DRS Cluster
Our VM infrastructure client is reporting that one of the ESX hosts is reporting an error. The error is:
`"HA agent on esx2 in cluster Ha/DRS Cluster 1 in Datacenter has an error`
Has anyone experienced this? Thanks.
|
There's quite a few possible causes, that's a very generic error. Things like DNS being unavailable to the ESX server is an obvious one, but there's lots of possible issues.
You've not mentioned which version of ESX you're running, but I'd start with this list of VMware HA troubleshooting questions.
|
stackexchange-serverfault
|
{
"answer_score": 1,
"question_score": 1,
"tags": "vmware esx, infrastructure"
}
|
How to flatten object properties using linq
In our localization database we have the following objects:
public class Text
{
public string Key { get; set; }
public string LanguageId { get; set; }
public string Value { get; set; }
}
I need a Linq statment to flatten these records to a structure that has the LanguageIds as a property with the values like:
public class ...
{
public string Key { get; set; }
public string En { get; set; }
public string Ge { get; set; }
public string Fr { get; set; }
...
}
Of course this can be achieved by some elaborate “for each”-ing but there must be a slik Linq statement that does the trick in one go. Any Link Gurus out there?
|
Try the following:
var flattenTexts = texts
.GroupBy(x => x.Key)
.Select(x => new { Key = x.Key,
De = x.First(y => y.LanguageId == "De").Value,
En = x.First(y => y.LanguageId == "En").Value
});
You will need to know which languages you have of course...
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "c#, linq"
}
|
Initializing a 2 dimensional array of a class in another
I have a class say ABC and I have to initialize a 2 dimensional array of type ABC into another class. I am bad at objective C. Tried lots of ways, but facing some errors.
Here is ----- Class ABC ------
@interface ABC : NSObject{
int a;
}
@property (nonatomic, assign) int a;
@end
@implementation ABC
@synthesize a;
@end
Here is another class say XYZ where class ABC needs to be intialized:
\------ Class XYZ -----
@interface XYZ : UIView {
ABC *abc[16][16];
}
@property (nonatomic, retain) ABC *abc;
@end
@implementation XYZ
@synthesize *abc[16][16];
@end
Please suggest what could be the correct syntax of initialization. I am getting various errors everytime I try to initialize it.
|
If you want to use C style arrays (i.e. `ABC *abc[16][16]`), you’ll need to provide accessor methods in your XYZ class.
@class ABC;
@interface XYZ : NSObject
{
ABC *abc[16][16];
}
- (void)setABC:(ABC *)anABC atRow:(NSUInteger)row column:(NSUInteger)column;
- (ABC *)abcAtRow:(NSUInteger)row column:(NSUInteger)column;
@end
@implementation XYZ
- (void)setABC:(ABC *)anABC atRow:(NSUInteger)row column:(NSUInteger)column
{
[anABC retain];
[abc[row][column] release];
abc[row][column] = anABC;
}
- (ABC *)abcAtRow:(NSUInteger)row column:(NSUInteger)column
{
return abc[row][column];
}
- (void)dealloc
{
NSUInteger row, column;
for (row = 0; row < 16; row++)
for (column = 0; column < 16; column++)
[self setABC:nil atRow:row column:column];
[super dealloc];
}
@end
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "iphone, objective c"
}
|
How do you access the applications display name in windows phone 8.1 (Xamarin Forms)
I need to access the display name field stored in the Package.appxmanifest. I am developing in Xamarin Forms and am trying to access this from the windows phone 8.1 project through dependency injection.
To make it a little bit more clear this is the field I am trying to retrieve:
:
.
I'm not sure if the `Package.appxmanifest` file is still in the app that is installed on the device, if so, you could try to read it manually and extract it from there.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "c#, xamarin, windows phone 8.1, xamarin.forms"
}
|
using time intervals between sound failing flash as3
hi need to have a timer class that actually has very descent timming:
var playTimer:Timer = new Timer(1000);
playTimer.addEventListener(TimerEvent.TIMER,playhead);
playTimer.start();
function playhead(e:TimerEvent):void
{
for ( i = 0; i<myArray.length; i++)
{
soundArray[0].play();
break;
}
}
The above works but sadly the sound is not accurate, the sound playing is a clap like noise, theory i would presume it would clap on an even interval but it doesnt. any help would be apreciated
|
Not sure exactly what you are trying to do by playing a sound multiple times, based on the length of myArray, and then breaking.
But anyways, the the `play()` method of a `Sound` does accept parameters, and one of them is how many times you'd like to loop.
try this alone, without all that timer code etc :
sound.play(0,5);
The 0 cues it at the beginning of the sound, which is the default. the 5 specifies to loop 5 times.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -1,
"tags": "actionscript 3, flash, actionscript"
}
|
Flask official tutorial: what is 'e' in close_db(e=None)?
In Flask's tutorial[ [here]]( the definition for close_db included a default value for 'e=None'. But, this value isn't used in the function nor I can find reference anywhere.
def close_db(e=None):
db = g.pop('db', None)
if db is not None:
db.close()
Is there any specific reasons 'e=None' is explicitly stated?
|
You'll notice in the tutorial that in the `init_app` function, `close_db` is passed as an argument to `app.teardown_appcontext()`.
From the docstring for `teardown_appcontext`:
> When a teardown function was called because of an unhandled exception it will be passed an error object. If an `errorhandler` is registered, it will handle the exception and the teardown will not receive it.
So `e` refers to the error object, which is None by default. You can learn more about registering error handlers at this link.
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 6,
"tags": "python, flask"
}
|
Is it safe to use short bits from manual screwdriwer with electric drill?
Is it safe to use short bits (from manual screwdriver) with electric drill Ryobi R18PD3? Length of the hexagonal part (that fits into the drill) is 1.5cm. Original bits seems to be a bit:) longer.
Once properly set, bit sits firmly into the chuck of the drill- but bit does not reach the bottom of the chuck. 
|
stackexchange-diy
|
{
"answer_score": 5,
"question_score": 0,
"tags": "bits, drill bit"
}
|
JDBC capitalizing the table in my postgres query
I am running the following code
/**
* @param args
*/
public static void main(String[] args) throws SQLException {
System.out.println("starting");
org.postgresql.Driver driver = new org.postgresql.Driver();
DriverManager.registerDriver(driver);
Connection con = DriverManager.getConnection("jdbc:postgresql://localhost:5432/epcfe/", "postgres", "aap123!");
Statement st = con.createStatement();
st.executeQuery("select * from epcfeschema.PRODUCT");
System.out.println("done");
}
I keep getting `Exception in thread "main" org.postgresql.util.PSQLException: ERROR: relation "epcfeschema.product" does not exist`
If I create a table with the lowercase name product this works fine but I need it to work for tables with all caps. How do I keep JDBC from lowercasing my table?
|
If it's a hibernate issue, try this:
@Entity
@Table(name = "\"PRODUCT\"")
public class Product { // ...
Or better yet, make your life easy: log on to postgres and rename the table!
ALTER TABLE "PRODUCT" rename to product;
(Of course, other code may depend on the cap name...)
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 1,
"tags": "java, sql, postgresql, jdbc"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.