INSTRUCTION
stringlengths
25
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
ImportError only when I use docker I can run a script fine without docker, but when I have to use docker I run it and I get an import error: no module named c.H. In my docker container, I can do: python import c.H Everything works fine. But the second I try to run script.py, I get the import error that there is no module named c.H I do not get this error when I don't use docker.
it's possible that the python version you are using inside the container is different from the python version the script is using. And different version of python may have different packages installed. You could check the python version the script is using from the shebang line. The shebang line should look something like the following: #!/usr/bin/env python
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 5, "tags": "python, docker" }
Should I use a simple delay or an exponential backoff I have a distributed system that basically executes processes (not OS processes, just stuff that needs to be done). after a few unsuccesful tries (timeouts) it notifies a failure. I want to continue trying to execute the process afterwards in the background and the question is: should i use a bigger timeout period? or an increasingly bigger timeout (getting bigger and bigger each try) * There are many reasons for a process to fail, mainly network problems.
It depends on the reason for the failure to do something on the first attempt. If it is due to potential overload / temporary exhaustion of some resource, you might want to try some exponential back off strategy. The reason being, that continuous attempts to acquire that what you want could make things even worse and thus will probably never lead to success. If you are basically waiting for something to happen or be available e.g. a port being open or a file being there ("polling" basically), you might just want to wait for fixed periods of time. This is somewhat oversimplified, but may give some basic ideas. Just make sure that you thoroughly test whatever strategy (or combination thereof) you choose, to make sure that it (obviously) actually works and also does not worsen anything.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 0, "tags": ".net, architecture, timeout" }
reading a datafile to array/list Aim: Reading a data file(numerical values), creating array/list Problems: each digits are formed as array, instead I need the whole value as one array/list Input data file (1.txt) : 2 columns are separated by a tab gap 0.85787 0.8E-03 0.8578 45.8E-03 0.857878 5.8E-03 0.657878 2.3E-03 ..... ...... crs = open("1.txt","r") for line in crs: x = line.split() k=str(x[0]) # string to avoid spacing problem v=str(x[1]) print k[0] k[0] lists ONLY the first digits ie., 0 0 0 0 0 but my requirements are to store 0.85787 in k[0] .... 0.657878 in k[3] .... and 0.8E-03 in v[0] ...... 2.3E-03 in v[3] .... and use it further, importantly NO empty spaces/gaps. Please suggestions are welcome.
If you need to create separate lists for the two columns of your data the simplest way is to simply create the lists before you start the loop, then append to them as you loop through the file: k = [] v = [] with open("1.txt", "r") as crs: for line in crs: x = line.split() k.append(x[0]) # use float(x[0]) if you want numbers rather than strings v.append(x[1]) A more "Pythonic" (but perhaps more difficult to understand) solution is to use a generator expression and the `zip` function to create the two lists simultaneously: with open("1.txt", "r") as crs: k, v = zip(*(line.split() for line in crs))
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "python 2.7" }
iPhone: Displaying custom view when notification is fired I am trying to display a custom view once a notification is fired on the iPhone. By that I mean, once the UILocalNotification alert pops up and the user presses the action button, right now it shows my main view but I'd rather have it show a different view. How do I accomplish that? Don't necessarily need code, just the general steps to accomplish this. Thanks.
- (void)application(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification This is the method that gets fired once you click the action button on an alert dialog that was triggered by a UILocalNotification. Just had to show the view from there.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "iphone, objective c, xcode" }
accessing a positional parameter through a variable I'm trying to access a positional parameter using a variable. i.e. if I define a variable as 1, I want to access the 1st positional parameter, if I define it as 2 I want to access the 2nd positional parameter. example: bash script.bash arg1 arg2 arg3 var=2 echo $var // will only echo no. 2 ??? // insert your command to echo the 2nd positional parameter (arg2) can this be done?
Do [[ "$var" -eq "1" ]] && echo "$1" #for positional parameter 1 and so on or you could do it like below : #!/bin/sh var=2 eval echo "\$${var}" # This will display the second positional parameter an so on **Edit** > how do I use this if I actually need to access outside of echo. for example "if [ -f \$${var} ]" The method you've pointed out it the best way: var=2 eval temp="\$${var}" if [ -f "$temp" ] # Do double quote then #do something fi
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "bash, shell, positional parameter" }
How can I solve " module 'pandas' has no attribute 'scatter_matrix' " error? I'm trying to run `pd.scatter_matrix()` function in Jupyter Notebook with my code below: import matplotlib.pyplot as plt import pandas as pd # Load some data iris = datasets.load_iris() iris_df = pd.DataFrame(iris['data'], columns=iris['feature_names']) iris_df['species'] = iris['target'] pd.scatter_matrix(iris_df, alpha=0.2, figsize=(10, 10)) plt.show() But I'm getting `AttributeError: module 'pandas' has no attribute 'scatter_matrix'`. Even after executing `conda update pandas` and `conda update matplotlib` commands in Terminal, this is still occurring. I executed `pd.__version__` command to check my pandas version and it's `'0.24.2'`. What could be the problem?
This method is under `pandas.plotting` \- docs and `pandas.plotting.scatter_matrix`: from pandas.plotting import scatter_matrix scatter_matrix(iris_df, alpha=0.2, figsize=(10, 10))
stackexchange-stackoverflow
{ "answer_score": 66, "question_score": 35, "tags": "python 3.x, pandas" }
Parsing and appending a link I have a link as input below,i need to parse this link and append "/#c/" as shown below,any inputs on how this can be done? INPUT:- OUTPUT:-
" although I suspect your real problem is something else "com/#/c/".join(" may be slightly more applicable to your actual problem statement (which I still dont know what that is) my_link = " print re.sub("\.(com|org|net)/",".\\1/#/c/",my_link) maybe more of what your actually looking for ... that urlsplit solution of @JonClements is pretty dang sweet too
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "python" }
How to create a Concrete WSDL in tibco I have created a WSDL (Abstract) for a SOAP web service. I have to use this WSDL in the SOAP Request Reply. But in the Service port of SOAPRequestReply, I have to specify a Concrete WSDL. So if there is any way to create a Concrete WSDL. Let me know if any other information is required.
Create a Service (using service pallets) with your WSDL(Abstract), you will have to setup the operation(s) and transport type (HTTP or JMS). Once you have done that, go to the WSDL tab. You should be able to save a Concrete WSDL out. Hope this help :P
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 1, "tags": "soap, wsdl, tibco" }
と言ってました and は confusion I am confused by a very specific sentence in the lesson I'm currently on and haven't found any examples online or anywhere in my textbook. I'm trying to figure out how to correctly say "Robert said his mother is a good cook." The only way I can figure is to use the particle twice... but I don't know if this is okay? ― **** **** Would I omit one of the ’s in this case?
> ― Your usage of is perfectly fine. The quoted part is an embedded "sentence", so you don't have to worry about two 's. For the same reason, it's usually better to place between and . without is a little clumsy as a sentence (see ). > ― **** > Robert said his mother is a good cook.
stackexchange-japanese
{ "answer_score": 3, "question_score": 3, "tags": "grammar, particles" }
How to remove kernel installed using dpkg command? I am using i386 architecture of Ubuntu 12.04,I downloaded latest kernel 3.12.7 from < & installed it using dpkg -i. Installation was all good, but after 40-50 minutes it freezes. So, I would like to revert changes. How to uninstall the latest kernel 3.12.7 which I downloaded using dpkg command ? Here's my `dpkg -l | grep "linux-[a-z]*-" !enter image description here
Just use apt or your favorite package manager to search and uninstall the packages. apt-get remove packagename Or use Software Center or Synaptic package manager and search for linux 3.12
stackexchange-askubuntu
{ "answer_score": 0, "question_score": 0, "tags": "12.04, kernel, dpkg" }
Qt creator HTML5 project -lsqlite3 I've download the Ubuntu SDK to make apps. Building a native app went great in QtCreator. But now I'm trying to build an app using QtCreator with HTML5. So I made a new project and chose HTML5 as project template and simply build it. It gives me the following error: /usr/bin/ld: cannot find -lsqlite3 collect2: ld returned 1 exit status I'm assuming it cannot find sqlite3 library. But again I'm new using this SDK. What is the best thing to do to solve this problem?
Install the SQLite 3 development package (`libsqlite3-dev` ![Install libsqlite3-dev]( and your linker should be able to link your binary with `sqlite3` lib.
stackexchange-askubuntu
{ "answer_score": 3, "question_score": 2, "tags": "application development" }
Infinite loop when generating URL of GET request with Requests library My goal is to generate the URL of a GET request to an API. The following code results in the error message "The program took too long to finish. Check your code for infinite loops." import requests query_params = { 'apikey': 'API_KEY', 'phrase': 'fiscal cliff' } endpoint = ' response = requests.get(endpoint, params = query_params) request_url = response.url print request_url
This is not the code producing the error you complain of. Not only is there no infinite loop (indeed no loop in your code at all), running the code works in so far as it results in a 401 response (because the request requires authentication).
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "python, python requests" }
EXCEL - Substract two 24hr time format cells with seconds and miliseconds Okay, so I have two cells: Start End 11:31:37.644 11:31:51.269 I'd like to subtract the two and return the remaining time which should equal something around 14 seconds. Edit for more information: My values I'm inputting are like so: 113137.644 113151.269 and I have a custom formatter set to: `00\:00\:00.000` to display what you see at the very top.
You need to use the `MID` function to grab each section of the time, like this: =MID(A1,1,2)&":"&MID(A1,3,2)&":"&MID(A1,5,2)&"."&MID(A1,8,3) This will change `113137.644` to `11:31:37.644`. You can then do the math on it like this (all in one cell, but broken up here for readability): =TEXT(MID(B1,1,2)&":"&MID(B1,3,2)&":"&MID(B1,5,2)&"."&MID(B1,8,3), "hh:mm:ss.000") - TEXT(MID(A1,1,2)&":"&MID(A1,3,2)&":"&MID(A1,5,2)&"."&MID(A1,8,3),"hh:mm:ss.000") That should give you `0.000157697`. Change the field's custom format to `hh:mm:ss.000` to give you `00:00:13.625`.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "excel, time" }
Instantiating classes using Object Initializers I'm still quite new to C#, so I apologize if my title does not use the correct terms. This question is merely a curiosity on my part but is it possible to turn this code var folderPicker = new FolderPicker(); folderPicker.SuggestedStartLocation = PickerLocationId.ComputerFolder; folderPicker.FileTypeFilter.Add("*"); into something like this var folderPicker = new FolderPicker() { SuggestedStartLocation = PickerLocationId.Desktop; FileTypeFilter.Add("*"); } I tried it but VS19 doesn't like it. I'm just not sure if my syntax is wrong or if it's just not possible. Thank you for any help you provide.
You are probably looking for Object Initializers. This way you can assign initial values to the parameters of the object when using any constructor. Important to note, you can only do **assignment** but no function invocation using the above method. Also note that you should use `,` instead of `;` to separate the expressions inside the curly braces, and omit the one after the last expression. An example would be like: var Cat = new Animal(){ Type = AnimalTypes.Cat, Name = "Cecil", Age = 3 };
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 0, "tags": "c#, uwp" }
How to retrieve a Date of Exported Files from the Data Loader tool Is there a way to find out the Date of the exported files ("Data") from Salesforce? I meant, when was the time the data was exported from Salesforce.
This is available by way of the Event Monitoring API. This is a paid feature, so you'll need to contact your account executive. It allows you to access the logs to see which user performed any particular query, accessed a particular page or record, etc. You can also request a Log Analysis of User Activities, again a paid feature. Either of these features would allow you to determine which data was exported by a given user, the tool that was used, and so on.
stackexchange-salesforce
{ "answer_score": 3, "question_score": 1, "tags": "data loader, dataloader.io" }
Mongoose update by date without time I'm using mongoose 4.7.x and mongodb 3.2. I want to search all date without time. E.g `update all obj with this date 2016-12-14`. In my database I have multiple datetime like this : 2016-12-14 00:00:00.000Z 2016-12-14 00:00:00.000Z 2016-12-14 01:00:00.000Z 2016-12-14 01:00:00.000Z 2016-12-14 02:00:00.000Z 2016-12-14 02:00:00.000Z I tried this : var query = {date: new Date('2016-12-14')}; var doc = {name: 'TEST'}; var options = {multi: true}; Model.update(query, doc, options, function(err, result){ console.log('All data updated') }); But this will just update all fields with time 00:00:00 because `new Date()` will returns the datetime. How can I do to search all fields with a certain date without time ? I can change the model if it's necessary.
You can do it in between a range of dates. Use `$gte` for the lower range, and `$lt` for the higher one (which is the next day) to keep it from selecting the next day at 00:00:00 hours. var query = { date: { $gte: new Date('2016-12-14'), $lt: new Date('2016-12-15') } }; var doc = {name: 'TEST'}; var options = {multi: true}; Model.update(query, doc, options, function(err, result){ console.log('All data updated') }); All documents between 2016-12-14 00:00:00.000Z and 2016-12-14 23:59:59.999Z will be updated.
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 1, "tags": "javascript, node.js, mongodb, date, mongoose" }
Missing Keyword in JOIN syntax I have searched the site before asking the question but havn't come across something related. I am sure this is a ridiculously basic error, i have only been studying Oracle SQL from 0 computer background for around 4 months. I am planning to take the 1z0-051 end of this month so going over all the chapters. In this clause I am trying to get the name, title, salary, department and city of employees who have a salary higher than the average salary of the lowest paid position (CLERK). I keep getting Missing Keyword though? SELECT e.first_name, e.last_name, j.job_title, e.salary, d.department_name, l.city FROM employees e JOIN jobs j WHERE salary > (SELECT AVG(salary) FROM employees WHERE job_id LIKE '%CLERK%' ) ON e.job_id = j.job_id JOIN departments d ON e.department_id = d.department_id JOIN locations l ON d.location_id = l.location_id ORDER BY salary
You have `JOIN`-`WHERE`-`ON` sequence which is wrong. Should be something like this (assuming `WHERE` is **not** a part of your joining condition): FROM employees e JOIN jobs j ON e.job_id = j.job_id .... .... WHERE e.salary > (SELECT AVG(salary) FROM employees WHERE job_id LIKE '%CLERK%') ORDER BY ...
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 2, "tags": "sql, oracle, ora 00905" }
How can I modify pasted text? Is it possible to intercept and modify text that gets pasted into a textarea? If intercepting isn't possible, can I modify it after being pasted? (Without modifying the already present text in the textarea.)
With jQuery: jQuery(function($){ $('#your_element').bind('paste', function(event){ event.preventDefault(); var clipboardData = event.originalEvent.clipboardData.getData('text/plain'); console.log(clipboardData); }); } }); Works in IE and Webkit. With Firefox you might have to use this: <
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 3, "tags": "jquery, html, dom" }
wordpress child theme multiple child theme wp_enqueue_scripts I can't get my wp_enqueue_scripts working for multiple child style sheets. I have add_action( 'wp_enqueue_scripts', 'theme_enqueue_styles' ); function theme_enqueue_styles() { wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' ); wp_enqueue_style( 'child-style', get_stylesheet_directory_uri() . '/style.css', get_stylesheet_directory_uri() . '/anthony.css', array('parent-style') ); } I'm not too familiar with php. How do I include multiple stylesheets?
You should only call one stylesheet each time you use `wp_enqueue_style()` // start the function called theme_enqueue_styles function theme_enqueue_styles() { // enqueue 3 stylesheets, call wp_eunqeue_style for each file wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' ); wp_enqueue_style( 'child-style', get_stylesheet_directory_uri() . '/style.css') ; wp_enqueue_style( 'anthony-style', get_stylesheet_directory_uri() . '/anthony.css' ); } // Call the wp_enqueue_scripts action on the created function add_action( 'wp_enqueue_scripts', 'theme_enqueue_styles' );
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "php, wordpress" }
Regex lookahead more than one element Is it possible to use a lookahead to establish whether one or more characters does/doesn't exist when those characters do not _immediately_ follow the lookahead assertion? e.g. Given regex similar to this: ([abc])([def])([ghi]) could I, say, only allow the 'i' in the third group as a match if there was an 'a' in the first group?
You can use a lookbehind assertion (unless you're targeting JavaScript where they are not supported by the regex engine): ([abc])([def])([gh]|(?<=a.)i)
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "javascript, regex, regex lookarounds" }
Swapping buffers multiple times in one function (OpenGL and C++) I'm using an OpenGL display function that contains the following lines of code: glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glMatrixMode(GL_MODELVIEW); //Draw some stuff glMatrixMode(GL_PROJECTION); glPopMatrix(); glMatrixMode(GL_MODELVIEW); glPopMatrix(); glutSwapBuffers(); However, I'm applying this code multiple times throughout the function. What I want to happen is for it to draw something, respond to the user's input, draw something else, respond to the user's input again and finally draw one last thing. Is it considered acceptable practice to call "glutSwapBuffers" multiple times in the same function? If it's not a huge problem, is there a way to make it properly display the final drawing? It draws the first two pictures that I want it to, but the third time the screen just stays white.
Usually you make a loop check for input at the beginning of the loop and then update variables and then draw once depending on those variables and restart the loop. if no input comes in then the variables that don't depend on time will remain the same and what you draw will remain the same.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "c++, opengl, buffer, swap" }
HTML text field input -> site on my page I have a problem with my HTML-Website. I would like to have a text field which generates a link after entering and pressing a button from the input. For example, in the text field is "development" and by pressing the button should my browser go to "www.laurensk.at/development". I don´t have the code for that...
I've understood your question, you can do it using JQuery or Javascript $("#btnGoto").click(function(){ window.location="www.laurensk.at/"+$("#txtPage").val(); }); I hope this will help you.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": -3, "tags": "html" }
How to split path with slashes? I have a requirement for adding and splitting path in my app.I want to work with this app on windows and linux.Here is my code to add paths path = os.path.join(dir0,dir1,dir2,fn) But when i am splitting with slashes i am facing problems .Because the path in windows like: dir0\dir1\dir2\fn the path in linux like dir0/dir1/dir2/fn Now how can i split the path with single code(with out changing the code while using other platform/platform independent)
Use os.path.split. It is a system independent way to split paths. Note that this only splits into `(head, tail)`. To get all the individual parts, you need to recursively split `head` or use `str.split` using `os.path.sep` as the separator.
stackexchange-stackoverflow
{ "answer_score": 9, "question_score": 4, "tags": "python" }
PL/SQL: Select function result with multiple rows from dual How do I select a function result with multiple rows from dual in PL/SQL? SELECT multipleRowsFunction() AS multiple FROM dual; or BEGIN SELECT multipleRowsFunction() INTO multiple FROM dual; END; Are there any alternatives to DUAL for this purpose?
Depending on your function, your best bet is select * from table(multipleRowsFunction); In a PL/SQL block, you do not need `select ... from dual`; just write begin multiple := multipleRowsFunction; end;
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "oracle, plsql" }
*char value changing on the function I'm trying to use a function with an *char. //the function void init_player(struct player *_player, int pos_x, int pos_y, char *sprite){ printf(" %s",sprite); _player->pos_x = pos_x; _player->pos_y = pos_y; strncpy(_player->player_sprite, sprite, sizeof(100)); } When I print the function before using the funcion it is all right. //the call struct player array_player[3]; char *str = "img/dragon_verde.bmp"; printf("%s",str); init_player(array_player[0],0,0,str); Here are the print results: Before function: img/dragon_verde.bmp After function : )!Sjdnm (something like that after function, can't copy it) I hope you understand my English.
You have a problem here: init_player(array_player[0],0,0,str); It should be: init_player(&array_player[0],0,0,str); **Note that if you had enabled compiler warnings (and paid attention to them) you would have noticed the mistake immediately.**
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "c, string, char" }
Providing permission to specific user to access NFS share I have two machines between which I need to share a folder. On server1, I have the user 'appuser' that needs to access (read/write/delete) on this share. On server2, 'root' accesses this share and writes to it. I have the following in /etc/exports on server1: /home/app-share 999.999.99.99/28(rw,insecure,sync,no_root_squash) where the number is the IP address. How can I change this to allow 'appuser' access?
NFS doesn't have share-level permissions. Access to the file on a NFS share follows normal *nix permissions.
stackexchange-superuser
{ "answer_score": 1, "question_score": 0, "tags": "linux, network shares, nfs, export" }
Chrome interpreting jpg resource as Document Consider the following image at: < I have a controller rendering this image and transferring it with image/jpeg MIME. Chrome is throwing the warning: > Resource interpreted as Document but transferred with MIME type image/jpeg. Why would an image be interpreted as a document and why would Chrome throw such a warning?
add the proper doctype to your pages, something like <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" " and then start your HTML with <html xmlns=" Regards, M.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 5, "tags": "image, google chrome, mime types" }
Show index page if $_GET["page"] isn't set I'm making a CMS with functions to add your own pages. However, I'm stuck. As you can see, I've posted my code below. This code creates the pages which have been put in the database. Problem is, I want to show the index page if $_GET['page'] isn't set. Index page is ID 1. The user cannot delete ID 1 from the backend. $stmt = $dbConnection->prepare('SELECT * FROM paginas'); $stmt->execute(); $result = $stmt->get_result(); if(mysqli_num_rows($result) > 0) { while ($row = $result->fetch_assoc()) { if(isset($_GET['page']) && $_GET['page'] == $row['name']) { ?> // content content... <?php } else { ?> // show ID 1 content... <?php } } } else { echo "The user has not created any pages yet!"; } How can I do this?
This should work: if (isset($_POST["page"]) && !empty($_POST["page"])) { if($_GET['page'] === $row['name']){ print_r($row); // show data specific to id if page is set } }else{ //echo "Page is not set"; if($row['id'] == 1){ //show data of id=1 if page is not set print_r($row); } }
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 1, "tags": "php" }
PHP - time adjust I have a set of time in this format. 01:00:04 How can I adjust the time to deduct 4 second from it? Was trying to parse it but is the a quick way to do it using datetime or something? Thanks, Tee
You can use `strtotime()` like this : strtotime("-4 seconds", $reference_time); which will return the timestamp you need.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 1, "tags": "php" }
Are there specific optimizations for the Ubuntu Server kernel? I liked to install Debian using the netinst images, which installed a base system and allowed me to install additional packages as I wanted. I have searched for something similar in Ubuntu, and the Ubuntu Server images are very similar to Debian netinst, at least I have not noticed any difference. But today I was struggling with my desktop freezing with heavy I/O operations, and while searching for a solution, I have found that the default disk scheduler is set to `deadline`, which is a better choice for servers, but is probably a bad choice on a desktop. The problem seems to have been solved by setting it to `cfq`. I don't know what is the default scheduler for Ubuntu Desktop, though. Does the Ubuntu Server kernel receive specific optimizations for servers? Wouldn't installing the package `ubuntu-desktop` on a Ubuntu Server result in an identical system as Ubuntu Desktop?
See < > What's the difference between the kernels linux-image-server and linux-image-generic? What architecture is linux-image-server? Which one should I use? > > Note: Since 12.04, there is no difference in kernel between Ubuntu Desktop and Ubuntu Server since linux-image-server is merged into linux-image-generic. If you are using an older version of Ubuntu Server, see explanation below: > > The linux-image-server package is a meta package that will install the latest Server kernel version, while the linux-image-generic package is a meta package for the latest Desktop kernel version. The server guide includes some details on the changes made in the Server kernel. > > linux-image-server is used for both architectures x86 and amd64. > > Which one you should use will depend on the type of system you have. If you have a 64 bit processor you can use the amd64 architecture, or the x86 architecture. However, if your processor is 32 bit you can only use the x86 kernel.
stackexchange-askubuntu
{ "answer_score": 1, "question_score": 0, "tags": "kernel" }
Suppose that a random variable X has the Bernoulli distribution, find the cdf Suppose that a random variable X has the Bernoulli distribution with parameter p = 0.7. (See Definition 3.1.5.) Sketch the c.d.f. of X. My attempt: So I have that the formula for the c.d.f. of a rv X is $F(x)=Pr(X\le x)$ for $-\infty<x<\infty$ Then, obviously: $$F(x=0)=Pr(X\le 0)=0$$ $$F(x=1)=Pr(X\le 1)=1$$ Then using the fact that it has a bernoulli distribution with parameter p=0.07, I think this means that $P(X=1)=0.7$ I have an equation that says: $P(X=x)=F(x)-F(x^{-})$ so $$P(X=x)=F(x)-F(x^{-})$$ $$P(X=x)=Pr(X \le x)-Pr(X<x)$$ $$P(X=1)=Pr(X \le 1)-Pr(X<1)$$ $$0.7=1-Pr(X<1)$$ $$Pr(X<1)=0.3$$ So I think the c.d.f. would be 0 before x=0, then jump to 0.3, and then at x=1 it would jump up to 1. Is this correct?
A Bernouli random variables can realise just two discrete values: success $1$ and failure $0$. With a success parameter of $0.7$, this means the piecewise function is: $$\mathsf P(X=x) =\begin{cases}0.3 & : x=0 \\\ 0.7 & : x=1 \\\ 0 & : \text{otherwise}\end{cases}$$ You wish to find the CDF formula, $\mathsf P(X\leqslant x)$. > So I think the c.d.f. would be 0 before x=0, then jump to 0.3, and then at x=1 it would jump up to 1. Yes. The function is continuous _except_ at two step discontinuities: $$\mathsf P(X\leq x) =\begin{cases} 0 & : x<0 \\\ 0.3 & : 0\leqslant x < 1 \\\ 1 & : 1\leqslant x\end{cases}$$ If you plot it, it will look like a staircase.
stackexchange-math
{ "answer_score": 0, "question_score": 0, "tags": "probability" }
Eclipse is invisible in system tray I just installed Eclipse, but I got a problem, after I minimize the Eclipse than it's not visible on system tray. I also check the ALT+Tab but there also isn't visible. I had to kill the process and restart. How can I fix this?
Finally I figure it out: I removed the eclipse: sudo apt-get --purge remove eclipse sudo apt-get autoclean I installed again: sudo apt-get install eclipse And it's working now. I have no idea why didn't work before, case I have deleted the old ubuntu(10.04) and I installed the 12.04 from scratch.
stackexchange-askubuntu
{ "answer_score": 0, "question_score": 3, "tags": "eclipse, system tray" }
FFMPEG Directshow Multiple Audio Capture Is it possible to capture multiple audio devices using ffmpeg dshow? I am trying to capture my desktop using gdigrab along with mic and speaker audio using dshow. I have tried using the following command but it doesn't work: ffmpeg -f dshow -i audio="Stereo Mix (Realtek High Definition Audio)" -f dshow -i audio="Microphone Array (Creative VF0800)" -f gdigrab -framerate 10 -video_size 1920x1080 -draw_mouse 1 -i desktop screen.avi It only captures audio from the first mentioned audio device. Am I missing some options in the above command?
Finally, I figured out that I need to merge the two audio streams. I used amerge to combine those two streams into one and map them to the output. Here is a fully functional script which is able to do the task that I want. ffmpeg -f dshow -i audio="Stereo Mix (Realtek High Definition Audio)" -f dshow -i audio="Microphone Array (Creative VF0800)" -f gdigrab -framerate 10 -video_size 1920x1080 -draw_mouse 1 -i desktop -filter_complex "[0:a][1:a]amerge=inputs=2[a]" -map 2 -map "[a]" screen.avi
stackexchange-superuser
{ "answer_score": 3, "question_score": 6, "tags": "windows, audio, ffmpeg, directshow" }
Untrained Network Giving 80% Accuracy I have a two class classification problem and my neural network prior to training predicts with an accuracy of 80%. After training i have an accuracy of 75%. Can you tell me how this is possible?
If your class imbalance is roughly 4:1, then a network that always predicts the more frequent class would have an accuracy of 80%. (That's why accuracy alone is an insufficient metric: for binary classification, you should use ROC and PRC curves. There are also more holistic scalar metrics such as MCC) Let's say your positive samples are the frequent class. Without training, a random network might always output positive (80% accuracy). In this case, you'd only have true positives and false positives. After training, the network might start to also predict negatives; then you'll start getting true and false positives in addition to true and false negatives, which could yield a lower accuracy.
stackexchange-datascience
{ "answer_score": 4, "question_score": 2, "tags": "machine learning, neural network, deep learning" }
Truth set for the following formula $\forall x R(x, x) \land R(a, b)$? I have this exercise: > Let $R$ be a binary relation. For each of the following formulas, define a truth set over a universe of size at least 3 satisfying it. > > Example: a truth set over a universe of size at least $3$ for the formula $\forall x R(x, x) \land R(a, b)$ is the set {(a, b), (a, a), (b, b), (c, c)} over the universe {a, b, c}. > > 1. $R(a, b) \land R(b, c)$ > > 2. $\forall x R(x, x)$ > > 3. $\exists x \forall y R(x, y) \land \forall z (z, x)$ > > I am not sure about my solutions, that's why I am asking. 1. {(a, b), (b, c)} 2. {(a, a), (b, b), (c, c)} 3. {(a, a), (a, b), (a, c), (b, a), (c, a)} In this last case, the couples depend of course on the value chosen for $x$, which in my case is $a$. We don't have to repeat $(a, a)$ for both cases. Are my solutions correct?
Yes, you are correct. Well, the third is correct if the statement is $\exists x \Big(\forall y R(x, y) \land \forall z R(z, x)\Big)$, and you have chosen $a$ as the existent example of $x$. (You could have chosen $a$, $b$, $c$, or any combination of at least one of the three).
stackexchange-math
{ "answer_score": 2, "question_score": 1, "tags": "elementary set theory, relations, solution verification, predicate logic" }
sed -e '$!d' not working as expected? When I run: sudo /usr/local/nginx/sbin/nginx -t I get back: nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful I just want the last line so I run: sudo /usr/local/nginx/sbin/nginx -t | sed -e '$!d' But I get back the same as without sed.
Your command possibly outputs to stderr instead of stdout. To redirect stderr to stdout: sudo /usr/local/nginx/sbin/nginx -t 2>&1 | sed -e '$!d' If you only want the last line of your output, you can also use `tail -n 1` instead of `sed`.
stackexchange-unix
{ "answer_score": 13, "question_score": 10, "tags": "sed, io redirection" }
How do I change the shape of a button in MUI using theme? So the documentation on `Button` component has various sections and also a Codesandbox linked at < However, there is nowhere mentioned how to change the shape of a button if needed. ![enter image description here]( I am using Google Material Sketch file and I want the buttons to be rounded ![enter image description here]( How can I do that using the `theme` object so that in my entire app the `Button` component are always rounded?
There is a global border radius shape value in the theme. You can change it like this: const theme = createMuiTheme({ shape: { borderRadius: 8, }, }) Alternatively, if you are only interested in the button style: const theme = createMuiTheme({ overrides: { MuiButton: { root: { borderRadius: 8, }, }, }, }) Or, you could target the global class name of the button: .MuiButton-root { border-radius: 8px; }
stackexchange-stackoverflow
{ "answer_score": 45, "question_score": 17, "tags": "javascript, reactjs, material design, material ui" }
How to take the first n element from an infinite Generator List? I have this infinite generator: def infiniList(): count = 0 ls = [] while True: yield ls count += 1 ls.append(count) Is there a way to take the first n elements? I mean an easy way, I did: n = 5 ls = infiniList() for i in range(n): rs = next(ls) > Output: print(rs) [1, 2, 3, 4]
`itertools.islice` does exactly that, though in your example you need to be careful to not repeatedly yield a reference to the same object that keeps getting modified: def infiniList(): count = 0 ls = [] while True: yield ls[:] # here I added copying count += 1 ls.append(count) # or you could write "ls = ls + [count]" and not need to make a copy above import itertools print(list(itertools.islice(infiniList(), 5)))
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "python" }
Correcting the following question (of Thomae function) and solving the correct version of it. The question say: let $f$ be the Thomae function given below: ![enter image description here]( And let $g(x)= \int_{0}^{x} f(t)dt$. Prove that $g'(x) = f(x)$ iff $x \in \mathbb{Q}.$ I was told that the question contain a mistake, but I do not know what is it, could anyone tell me it please?
Instead of $x\in\mathbb Q$, it should be $x\in[0,1]\setminus\mathbb Q$. The function $g$ is the null function and therefore $g'$ is the null function too. And $f(x)=0$ if and only if $x\in[0,1]\setminus\mathbb Q$.
stackexchange-math
{ "answer_score": 1, "question_score": 0, "tags": "real analysis, calculus, integration, derivatives" }
UML Drawing of Presentation Logic, Screen Navigation, Validation How do you draw presentation logic, screen navigation and validation logic of controls in UML? When a new screen is needed or existing screen is modified, I use MS Paint to get the new screen layout approved. I find myself in this situation of how best to draw presentation logic, screen navigation and validation logic of controls. I currently use Activity Diagram and Sequence Diagram, and put the hyperlink next to the controls and put a link between these two (control and hyperlink). Please let me know how can I improve upon and represent these pieces in a better way. I work in windows based application.
Notwithstanding whether it belongs here or not, a couple of possibilities: * IFML, the Interaction Flow Modeling Language. Recently adopted UML notation for modelling user interface flow & content * Jesse James Garrett's visual vocabulary which covers similar ground, albeit isn't endorsed by the OMG or any other standards body afaik. hope that helps.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 2, "tags": "winforms, uml, ui design" }
DBM or SQLite in PHP 5.x We have a client whose site is hosted on a server (I don't want to disclose hosting company name) which does not provide DB functionality. We have developed a very simple CMS based site but out implementation uses MySQL. I read somewhere that there are DB like functionality built-in in PHP. I have never used them. What are these and how reliable are they? What is more advisable to user the DBM functionality or to use the SQLite functionality? For SQLite do we have to make any changes to php.ini file? If _yes_ then this is _out of bounce_ for us as the hosting provider does not give us access to php.ini file. TIA
Sqlite is shipped as default with PHP 5.2.x. I would prefer SQLite because it supports nearly the same sql commands like MySQL and is realy fast. Altough there is a nice GUI for SQLite for Firefox provided as Plugin. (SqliteManager).
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "php, sqlite, content management system, dbm" }
Jquery и динамический value Добавляю форму ввода $('#performer_name_field').append(form_name1+form_name2+form_name3+form_button); form_name1 имеет id=name1 Как получить результат ввода данных в поле #name1.value при нажатии на кнопку оправки результата? Поиграть с .on? $(document).on("click", "#performer_name_field_button", function(event){ alert(123); });
А в чем сложность, собственно? <
stackexchange-ru_stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "jquery" }
Orientation not changing to portrait, iOS game Am new to Xcode, using version 8, and have a small game done. The problem I am facing is that the orientation is in landscape, which I can't get to portrait, in the simulator and on device. Tried the following : 1. Changing Device Orientation under Deployment Info to Portrait, 2. Adding 'Portrait' under Supported interface orientations in the Info.plist file. Maybe I m missing out on something that I may have overlooked. Could somebody shed some light on this?
Well, just found this out. I am using cocos2D framework, which has the 'startUpOptions' Dictionary object (in AppDelegate.m) that need to be specified if the game needs to be in 'Portrait' mode thus: [startUpOptions setObject:CCScreenOrientationPortrait forKey:CCSetupScreenOrientation];
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "ios, objective c, cocos2d iphone" }
Forward request to specific site between squid proxys I have two proxys (With SQUID), each one with different ISP's, Say Proxy 1: IP 1.1.1.1, port 8080, with ISP A. Proxy 2: IP 2.2.2.2, port 1080, with ISP B I'm having problems with the navigation in certain sites with ISP B (Proxy 2), so I want to redirect only the requests that match those sites to the Proxy 1. It's that possible? I have maybe a clue with cache_peer, but i dont know if its possible. Can you guide me a little? Thanks a lot!
this is completely possible. You need an acl matching those domains, a cache_peer pointing to the sibling and a cache_peer_access that match you acl with cache_peer. Or you could do a cache_peer with a cache_peer_domain. You choose That's all.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "redirect, proxy, navigation, squid, sites" }
Apache 2.4 - multiple WSGI Virtual Hosts (different ports) hangs after few requests from one to another on Windows 10 I'm trying to host two different apps on different Virtual Hosts with different ports on Windows 10. Problem is that apache completely hangs after few requests from one app to another. Hosting them on one Virtual Host with different paths seems to solve the problem, and so does disabling requests. Both apps are Python Flask web servers. ### httpd.conf Listen 80 Listen 3000 ServerName localhost <VirtualHost *:80> WSGIScriptAlias / F:\path\to\server.wsgi <Directory F:\path\to> Require all granted </Directory> </VirtualHost> <VirtualHost *:3000> WSGIScriptAlias / F:\another\path\to\server.wsgi <Directory F:\another\path\to> Require all granted </Directory> </VirtualHost> AcceptFilter http none AcceptFilter https none
Seems that i found the solution: If you using C modules in your apps then add this line inside VirtualHost WSGIApplicationGroup %{GLOBAL} Slow page loading on apache when using Flask <
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "python, windows, apache, flask" }
What am I? Feel welcomed to answer > Hi! > > I am big business you should better not skip > > If I'm used longer you're in a relationship > > Also, I feel odd when there are 2k human beings > > My absence might hurt anothers feelings _Who/What am I? Can you figure it out?_
My guess is > A Handshake I am big business you should better not skip > Even the biggest of businesses follow the norm of a handshake greeting. (unless another norm replaces it, like Japan's bowing greet, but even that one can include a handshake) If I'm used longer you're in a relationship > A prolonged handshake turns into hand holding, a common gesture of couples. Also, I feel odd when there are 2k human beings > Greeting a crowd is normal, but handshaking a crowd can be quite awkward My absence might hurt anothers feelings > A first meeting without a handshake might be considered rude to the other person Title: > We are _welcomed_ to try, which hints to something done as a greeting, also hinted by the `Hi!` at the start of the riddle
stackexchange-puzzling
{ "answer_score": 6, "question_score": 9, "tags": "riddle, mathematics, word, wordplay, rhyme" }
What is docker host URL I recently changed my MAC and installed docker with `Docker version 20.10.8, build 3967b7d` and deployed some of SpringBoot Apps... they are accessible with localhost:port but not with below mentioned Docker HOST URLs like 1. gateway.docker.internal:port 2. host.docker.internal:port In my old MAC I was able to access Docker container with URL `gateway.docker.internal`... Old Laptop is no more with me so cant put old Docker version... I did `docker inspect ... | grep Address` also but the IP coming out of the command is also not working. It just waits there forever. But what is the Docker HOST URL or IP for Docker version mentioned above.
From @Amrut Prabhu How to access host port from docker container The simplest option that worked for me was, I used the IP address of my machine on the local network(assigned by the router) You can find this using the ifconfig command e.g ifconfig en0: flags=8863<UP,BROADCAST,SMART,RUNNING,SIMPLEX,MULTICAST> mtu 1500 options=400<CHANNEL_IO> ether f0:18:98:08:74:d4 inet 192.168.178.63 netmask 0xffffff00 broadcast 192.168.178.255 media: autoselect status: active and then used the inet address. This worked for me to connect any ports on my machine.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "docker" }
Why we need to place Semicolon manually after this.. View Why we need to place Semicolon manually? after this anyView.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(){ //Do something Here } }) /// here will be an Error if we not place Semicolon ... Why Eclips not placing ; here? } I just want to make my concept clear....
You need the semicolon to complete the `anyView.setOnClickListener()` statement. Most of the time, Eclipse does not automatically complete your code statements for you - it cannot read your mind what was the code you intended to write. What can be confusing is that the argument to `setOnClickListner()` is an anonymous inner class instance created inline and the syntax is a mixture of class definition and method calling.
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "android" }
How to set formatProvider property in Serilog from app.config file I know that it's possible to setup Serilog sinks in app.config file (AppSettings section) and it's pretty simple with scalar types, but how to be with complex ones (IFormatProvider etc.). Does anybody know how to deal with that and is it possible at all? I'm trying to simulate this example ILogger logger = new LoggerConfiguration() .Enrich.WithExceptionDetails() .WriteTo.Sink(new RollingFileSink( @"C:\logs", new JsonFormatter(renderMessage: true)) .CreateLogger(); but using app.config only.
You can use something like JsonRollingFile for this. <configuration> <appSettings> <add key="serilog:using:Json" value="Serilog.Sinks.Json" /> <add key="serilog:write-to:JsonRollingFile.pathFormat" value="C:\Logs\myapp-{Date}.jsnl" /> </appSettings> </configuration>
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "serilog" }
Does the Parappa the Rapper anime actually have any rapping? I watched the Parappa the Rapper anime several years ago, given that it was one of my favorite video games. However, I quickly discovered a fatal flaw: there was no actual rapping!! The producers instead decided to make it a children's show. How do you make an anime about a rapping dog with no actual rapping?! I only watched a few episodes before I dropped it. But if there actually is some rapping somewhere in the show, it would at least be worth my time to watch that. Does Parappa (or anyone else) rap at any point in the series?
The anime is about Parappa, not about rapping. So there's no really rapping, if I remember correctly.
stackexchange-anime
{ "answer_score": 2, "question_score": 6, "tags": "parappa the rapper" }
Can we always find the infimum and supremum of a sequence? I've found in my book that: $$\liminf_{n\to\infty} \ x_{n} = \sup\\{\inf\\{x_{k}:k\geq n \\}:n \in \mathbb{N}\\}$$ $$\limsup_{n\to\infty} \ x_{n} = \inf\\{\sup\\{x_{k}:k\geq n \\}:n \in \mathbb{N}\\}$$ If $X_n=\\{x_{k}:k\geq n \\}$ we define $s_n=\inf X_n$. I understand that $s_n$ is an increasing sequence but how are we sure that we will be able to find the supremum and that this will be the same as the limit of $\liminf_{n\to\infty} \ x_{n}$? Thanks
Firstly you need to be working in the affinely-extended real line, so that supremum and infimum of any sequence always exist. $\def\nn{\mathbb{N}}$ Let $y_n = \sup(\\{ x_k : k \in \nn_{\ge n} \\})$. By definition $\limsup_{n\to\infty} x_n = \lim_{n\to\infty} y_n$. But $(y_n)_{n\in\nn}$ is a decreasing sequence and hence by monotone convergence theorem (suitably extended to the extended real line) we get: $\lim_{n\to\infty} y_n = \inf(\\{ y_n : n \in \nn \\})$. Similarly for limit inferior.
stackexchange-math
{ "answer_score": 1, "question_score": 0, "tags": "limsup and liminf" }
SSRS 2008 row color expression changes 0 value cell I have an expression that changes the background color of a row based on an active status of "Active". Everything works well except that other cells with a value of 0 get set to my inactive color. So if I am setting my conditional based on the word "Active" then why are the cells on active rows with a 0 value getting set as well? !Grid example
I am still unsure why this was happening but, I fixed it by adding a conditional on my grouping column. It looked for a 0 value and set my background to Nothing. This was done at the row level already but had no affect. I had to set the column also for it to work.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "ssrs 2008" }
object convert to string in javascript **Input :** I have one object like below .Its converted to another format var a={ "p1":"1", "p2":"2" . . . "p1000":"1000" } **Output :** I need to covert above object to like this output format p1=1 p2=2 . . . p1000=1000
> You can iterate on object and then concatenate the string var a = { "p1":"1", "p2":"2","p1000":"1000" } var format = ""; for(var i in a) { format += i + " = " + a[i] + ' \n'; } console.log(format):
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -5, "tags": "javascript" }
Can PostgreSQL be used with an on-disk database? Currently, I have an application that uses Firebird in embedded mode to connect to a relatively simple database stored as a file on my hard drive. I want to switch to using PostgreSQL to do the same thing (Yes, I know it's overkill). I know that PostgreSQL cannot operate in embedded mode and that is fine - I can leave the server process running and that's OK with me. I'm trying to figure out a connection string that will achieve this, but have been unsuccessful. I've tried variations on the following: jdbc:postgresql:C:\myDB.fdb jdbc:postgresql://C:\myDB.fdb jdbc:postgresql://localhost:[port]/C:\myDB.fdb but nothing seems to work. PostgreSQL's directions don't include an example for this case. Is this even possible?
Postgres databases are not a single file. There will be one file for each table and each index in the data directory, inside a directory for the database. All files will be named with the object ID (OID) of db / table / index. The JDBC urls point to the database name, not any specific file: jdbc:postgresql:foodb (localhost is implied) If by "disk that behaves like memory", you mean that the db only exists for the lifetime of your program, there's no reason why you can't create a db at program start and drop it at program exit. Note that this is just DDL to create the DB, not creating the data dir via the init-db program. You could connect to the default 'postgres' db, create your db then connect to it.
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": 0, "tags": "postgresql, jdbc, firebird, embedded database" }
見える versus 見られる Which one is correct? 1. 2.
The first one is most likely the one you want. Here is how to think about the difference between the two: is used when the scene naturally enters your eyes, describing your ability to see. * I can see with glasses on. * It's a clear day so I can see far off into the distance. * These letters are too small for me to see clearly. is used to show potential based on some condition. * I don't have a Blu-ray player so I can't watch the movie. It can sometimes be a difficult distinction to make when thinking about it in terms of English. In my experience the former is much more common than the latter. Note that vs is a similar case.
stackexchange-japanese
{ "answer_score": 7, "question_score": 6, "tags": "meaning" }
angular2 - how to build with cli - main.bundle.js shows all secrets I have a angular2 app hosted on s3 with a flask api authenticated with JWT. This is how I build for dev env: ng build -dev if I go to: and I view the file I see way too much un-encrypted JS functions and logic about the website my comments etc.. Why does that happen? This is way too scary... How do I fix? Thanks
For your dev enviroment, it should be OK to see your code for debugging purposes. When you deploy to your prod environment, use following command `ng build --prod`
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "angular" }
powershell rename-item replace with variables incrementing I'm trying to use the output of a `Get-Childitem | Where-Object` to rename a group of files but instead of rename with a constant name I want to rename with a group of variables, and I'm use the operator `-replace` to find where in the string is what I want to change. Example: nane_01 -> name_23 name_02 -> name_24 they are not with the same final digit this is the code I'm using for test: $a = 0 $b = 1 $Na= 2 $Nb= 3 Get-Childitem | Where-Object {$_.name -match "_0[1-9]"} | rename-item -Newname { $_.name -replace "_{0}{1}","_{2}{3}" -f $a++,$b++,$Na++,$Nb++ } -Whatif I can't find how to make incremental variable work with the `-replace` operator
1. Specify the scope of variables explicitly, otherwise a local copy would be discarded on each invocation of the rename scriptblock. 2. Search/replace string of `-replace` operator are separate parameters, so format them separately using parentheses around each one (otherwise PowerShell will try to apply `-f` to `$_.name`). $script:a = 0 $script:b = 1 $script:Na= 2 $script:Nb= 3 Get-Childitem | Where-Object {$_.name -match "_0[1-9]"} | rename-item -Newname { $_.name -replace ("_{0}{1}" -f $script:a++,$script:b++), ("_{0}{1}" -f $script:Na++,$script:Nb++) } -Whatif Or just use one variable: $script:n = 0 Get-Childitem | Where-Object {$_.name -match "_0[1-9]"} | rename-item -Newname { $_.name -replace ("_{0}{1}" -f $script:n++,$script:n++), ("_{0}{1}" -f $script:n++,$script:n++) } -Whatif
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "powershell, variables, replace, rename item cmdlet" }
How can I route using controller without adding the id in the url? The url right now is `website.com/profile/1/edit` but I wanted to just only show `website.com/profile` I have tried using the route web.php `Route::resource('profile', 'ProfileController');` and `Route::get('profile', 'ProfileController@edit');`
You can create some route like that : Route::get('my_profile','ProfileController@myProfile'); And the function like that : public function myProfile (){ $user = Auth::User(); if($user){ /* Your code and redirect */ } else{ return back(); } } Don't forget this : `use Auth;` in above of file
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -2, "tags": "laravel, laravel 5" }
sweeping out colMeans and rowMeans To sweep out colMeans, rowMeans and mean from columns, rows and observations respectively I use the following code: a <- matrix(data=seq(from=2, to=60, by=2), nrow=6, ncol=5, byrow=FALSE) b <- matrix(data=rep(colMeans(a), nrow(a)), nrow=nrow(a), ncol=ncol(a), byrow=TRUE) c <- matrix(data=rep(rowMeans(a), ncol(a)), nrow=nrow(a), ncol=ncol(a), byrow=FALSE) d <- matrix(data=rep(mean(a), nrow(a)*ncol(a)), nrow=nrow(a), ncol=ncol(a), byrow=FALSE) e <- a-b-c-d colMeans can be sweep out by using this command a1 <- sweep(a, 2, colMeans(a), "-") Is there any single command to sweep out colMeans, rowMeans and mean? Thanks in advance.
What do you think `e`should look like in this example? Perhaps your line should be `e <- a-b-c+d` so that `e` has zero mean. The following code produces the same result as your calculation using `b`, `c`, and `d` (with your arithmetic progression example, a matrix of 0s). Change `+`to `-` if you insist. e <- t(t(a) - colMeans(a)) - rowMeans(a) + mean(a)
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "r" }
sentence construction: Nothing could be further from the truth > Nothing could be further from the truth. What's the structure of this sentence? Is it an idiom? Is it short for > Nothing could be further (than it) from the truth. "It" is what you said, or someone's opinion, and the like.
> Nothing could be further from the truth. This is an idiom and defined as > used to say that something is absolutely not true > I know you think I don't care, but nothing could be further from the truth. To follow the structure of your original example, we could say > Nothing could be further than it **is** from the truth.
stackexchange-ell
{ "answer_score": 1, "question_score": 0, "tags": "sentence construction" }
Sort dictionary by another list or dictionary I need **sort** my dictionary by another element who determine your order. unsorted_dict = {'potato':'whatever1', 'tomato':'whatever2', 'sandwich':'whatever3'} This sorting can come as a list or a dictionary, whichever is easier. ordination = ['sandwich', 'potato', 'tomato'] Dictionary after sort: sorted_dict = {'sandwich':'whatever3', 'potato':'whatever1', 'tomato':'whatever2'}
You can use an `OrderedDict` like this: from collections import OrderedDict sorted_dict = OrderedDict([(el, unsorted_dict[el]) for el in ordination]) What it does is create a list of tuples (pairs) using the `ordination` as first element and the value in `unsorted_dict` as second, then the `OrderedDict` uses this list to create a dictionary ordered by insertion. It has the same interface as a `dict` and introduces no external dependencies. EDIT: In python 3.6+ an ordinary `dict` will preserve insertion ordering as well.
stackexchange-stackoverflow
{ "answer_score": 10, "question_score": 11, "tags": "python, sorting" }
Disable calendar on input field on radio button select I have a input box with ui calendar on it. I want to `disable` the `input` box so that the calendar doesn't open on user `focus` of mouse to the input field. I have used `$('#enddate').attr('readonly', true);` to disable the input box, but still the calendar opens on clicking the input box. The code snippet that I have used is as follows: $('.starttime').click(function(){ atype=$('input:radio[name=startdate]:checked').val(); if(atype==2){ $('#enddate').attr('readonly', true); } else $('#enddate').attr('readonly', false); });
try this man: < **extra** in this demo - < (from date will not open the calendar because its `disabled` and to field will and I reckon thats what you want `:)` I hope your DOM and rest Jquery is correct! Hope it helps the cause! **code** $("#enddate").prop("disabled",true); to enable $("#enddate").prop("disabled",false);
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "jquery, jquery ui" }
How to recover deleted text inside Mac OS X sticky notes I use sticky notes to record some information. I deleted this info by accident. Is it recoverable?
As far as I know, the content for your stickies notes is stored in $HOME/Library/StickiesDatabase. If you are using Time Machine, or some other mechanism to do back-ups for your data that include this database, then you can try restoring an older version of this database to recover your data. Because of the way the Stickies app maintains its data (in a database), without access to some previous version of the database file, there's really no way to reliably recover Stickies notes.
stackexchange-superuser
{ "answer_score": 5, "question_score": 3, "tags": "macos, mac, osx snow leopard, sticky notes" }
Creating ArcMap toolbar button from model tool? Using Arc 10.3.1 ModelBuilder, I've just successfully created my first tool, which is stored in a toolbox within "My Toolboxes". I run the tool by opening the Arc Toolbox button, dropping down to the tool and double-clicking it. Now I'd like to make a toolbar button from my tool. I envision running the tool by simply clicking the new button rather than scrolling down through the Arc Toolbox dropdown. I've read through the book "Getting to Know ArcGIS Modelbuilder", plus a web search, plus the ESRI help documents. Nothing I've seen helps... In summary, how do I convert a tool to a toolbar button?
You need to go to Customize> Customize Mode on the Menu bar, in ArcMap. From there, click the commands tab, and select "Geoprocessing Tools" in the category list. Then browse to your toolbox containing the model and select it. This brings in the model to the commands. Now you can place it in a toolbar.
stackexchange-gis
{ "answer_score": 3, "question_score": 4, "tags": "arcgis desktop, modelbuilder, arcgis 10.3, toolbar" }
creating a set of paths using raphael js and animate together I have a gauge pointer that I need to add an arrow at the end, I was able to do it, the only problem is not a set and when the pointer is rotating my arrow is not following its position any ideas guys I know this is a newbie question. This is the script $(function(){ var r = Raphael("gauge", 200, 200); var g = r.gauge(0, 180); g.bg(r.circle(100, 100, 100).attr({fill:'','stroke-width': '0'}), [100, 100]); g.pointer(r.rect(0, 0, 90, 8).attr({fill: '#fff', 'stroke-width': '0'}), [90, 4]); g.arrow(r.path('M 15,20 0,10 15,0 z').attr({fill: '#fff', 'stroke-width': '0'}).translate(0, 90), [0, 20]); setInterval(function(){ var percent = Math.floor(Math.random()*100); g.move(percent); }, 3000); }); and you can preview it here <
See the working fiddle (Quick Fix): < I don't know if this is the best solution, What I did is instead of creating a path & translating it, I have created the path directly at the required position. The reason for the behavior is if you look at the source code of the `move` method, it takes the pointer & applies transform method for rotation on the pointer, which overrides the translate method you called. ### Alternative Solution < Here I removed the rectangle & directly built an arrow using path.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "javascript, jquery, html, raphael" }
Line plot with factor variables in R How can I make R draw lines between two observations according with factor variables? I have two 'time' points, early and late, coded as categorical plotdata <- structure(list( x = structure(1:2, .Label = c("early", "late"), class = "factor"), y = 1:2 ), .Names = c("x", "y"), row.names = c(NA, -2L), class = "data.frame" ) I only get kind of a bar plot: plot(plotdata) I also tried coding the variables as 0 and 1, but then I get a continuous axis with.
Let's say your data is d <- structure(list(x = structure(1:2, .Label = c("early", "late"), class = "factor"), y = 1:2), .Names = c("x", "y"), row.names = c(NA, -2L), class = "data.frame") d # x y # early 1 # late 2 With base R plot(as.numeric(d$x), d$y, type = "l", xaxt = "n") axis(1, labels = as.character(d$x), at = as.numeric(d$x)) With ggplot2 library(ggplot2) ggplot(d, aes(x = x, y = y)) + geom_line(aes(group = 1))
stackexchange-stackoverflow
{ "answer_score": 6, "question_score": 1, "tags": "r, plot" }
Watchkit: watchos2 reply from sendMessage is very slow I am working with watchOS2 app. My watch app performs some NSURLSession tasks(which is quite fast) and sends reply to the phone using Watch Connectivity. I am using `sendMessageData` to send request to phone and reply is sent after performing required tasks. But the response takes a lot of time to reach the watch. Is there any other approach which will give a faster response. I had seen a similar question in: Why sending message from WatchKit extension to iOS and getting back a reply is so slow? In the answer it is said that "sendMessage is much more expensive method than other communication API those are provided by WCSession". Which other communication APIS are faster?
If you need to get an immediate reply from the other side, then sendMessageData with a replyHandler is the best you are going to find.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "ios, watchos 2, watchconnectivity" }
fluid not crossing a vertical effector boundary I have the "H" shaped mesh (converted from Text object) Collider Effector that is allowing fluid to pass through the verticals, but as the mesh fills the fluid never crosses into the horizontal part midway up the "H". I tried to add another inflow inside that area, and indeed nothing is flowing. Yet from looking at the faces I see no solid or blockage in this section. I'm about a month into fluid simulations and believe I understand many of the impediments (Surface Thickness >= 0.5, domain substeps and particle size appropriate, etc). I include the blend file and pray that you geniuses can smack some sense into me ;-) ![]( ![enter image description here](
Your "H" collision object needs to have normals orientated inside (red face orientation outside, blue inside) ... or your Domain is huge with very low Resolution Divisions ... or always good to Select all and Apply Scale ... or all of those :) ![enter image description here](
stackexchange-blender
{ "answer_score": 2, "question_score": 0, "tags": "fluid simulation" }
how to disable tap-on-click (touchpad) on windows I don't find the settings. I went to the mouse settings, but there aren't any touch-pad related settings. It shows up as a PS2 mouse. The device manager doesn't show up any further devices so I'm not sure how to install further device drivers. I also don't really know the exact hardware in my PC nor how to find that out. My question is mostly how to find out myself what to do. I guess I need to install something. Why doesn't it do that automatically? I tried already Synaptics because that seems like a quite common driver, however, the setup failed with some error, so I guess it is the wrong driver - but again, I'm not sure how to figure that out. On Linux, I would probably do something like `lspci` or `lsusb` \- but not sure what I have to do on Windows.
In short, there is not a native Windows command that does the same as `lspci` or `lsusb`. Your alternative on windows is `msinfo32` and extracting the vendor and product ID, highlighted below, from the Plug and Play device field: !enter image description here You can then use these to lookup what the device is online, this is what Windows does itself. A search for the highlighted device ID above tells me its a Cherry CyMotion / eVolution Series Keyboard. * * * If a device looks like the following in `msinfo32`: !enter image description here Then the device manufacturer did not apply for a registered Vendor ID thus not allowing Windows, or yourself to deduct what the device might be and Windows has reverted to a default driver. This is why manufactures, such as ASUS, have a website dedicated to looking up drivers for the built in devices based on the Laptops serial number. You can read more on the Plug & Play Architecture and Driver support here.
stackexchange-superuser
{ "answer_score": 2, "question_score": 3, "tags": "windows, windows 8, touchpad" }
How do you filter based on css class in Angular.js? I'm trying to filter my results based on a css class and can't seem to think of the easiest/best way to do that. Here's my plunker example Essentially by clicking on a link, I would like my filtered results to only show items where the "in_red" class is used.
Instead of filtering by class, filter by the actual property of the object. After all the class _is_ set based on the name property. One solution would be to use a custom filter function: ng-repeat="friend in friends | filter:filterFriends" Where filterFriends would be something like: function(friend) { if ($scope.filterOnRed === true) { return friend.name.substring(0,1) == 'J'; } else { return friend.name.indexOf($scope.searchText) != -1; } }
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "css, angularjs, filter" }
Graphics2D: Drawing black on white? I'm sure this is a very stupid question but I can't find the answer, I'm not experienced with the Java2D API. I'm trying to create an image and write it to GIF or PNG, and I want it to use a black pen on a white background. If I don't set any colors, I get white on black. If I use setPaint() (intended for subsequent draw operations) I get the whole canvas repainted with that color. The following sample renders the whole thing black. The sample is in Scala but you get the idea. Feel free to answer in Java! val bi = new BufferedImage(200, 400, BufferedImage.TYPE_BYTE_BINARY ) val g = bi.createGraphics g.setBackground(Color.WHITE) g.setPaint(Color.BLACK) g.draw(new Rectangle(10, 10, 30, 20))
The setBackground) method is/was only for use with the clearRect) method. Fill the rectangle with the background colour before painting: int width = 200; int height = 400; BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_BINARY); Graphics g = image.createGraphics(); g.setColor(Color.WHITE); g.fillRect(0, 0, width, height); g.setColor(Color.BLACK); //ready for drawing
stackexchange-stackoverflow
{ "answer_score": 39, "question_score": 18, "tags": "java, graphics" }
Android Studio Backup Source to Repository Recently I stuck with too many Android projects old/new NOT backed up, except manually copy/paste to second hard drive. As I am developing in C# too, in Visual Studio I connect to Microsoft small team(free) repository and commit changes so, I'am secure. I tried Android Studio Git before, it's free it's working but it's public. My apps are for business and cannot be public. GitHub has private from $7/month which is more than I paid for cloud hosting. I am considering building my own repository. Any thoughts and idea maybe. Thanks.
Use < . It allows you to keep private repositories for free
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 1, "tags": "android, git, repository" }
What is the risk with electronic contract notes in India? When you sign up for online commodity trading in India (and maybe even equities), if you opt for the convienience of electronic contract note, you are asked to sign a declaration that states: > I am aware of risk involved in dispensing with the physical contract note, and do hereby take full responsibility for the same What is the risk of choosing electronic notes over physical ones?
1. The risk that you don't see it. It might end up in your spam folder, the email server might fail etc. A physical note may have a delivery receipt (courier company's counterfoil or post details) but it's very difficult to ensure delivery with e-contract-notes. 2. The risk that the note is modified before it gets to you. Physical contract notes are usually printed, and you are likely to notice modifications. E-notes can be changed (many such notes are sent as HTML in a non-encrypted zip file). Many brokers do digitally sign notes nowadays but it is no longer required. But I think the regulation is a vestige of the past, and has mainly to do with 1) above, i.e. that they can't ensure delivery. There's no standard contract note format, or even a standard delivery mechanism either.
stackexchange-money
{ "answer_score": 2, "question_score": 1, "tags": "india, trading, stock markets, risk, online trading" }
Parsing JSON before iOS5 Since it seems that `NSJSONSerialization` class is only available in iOS 5.0+ (NSJSONSerialization Class Reference), is there another option to parse JSON objects prior that version? Thanks
Have a look at JSONKit. I've used it prior to iOS5 and it has better performance, and is easier to use than SBJSON.
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "ios, json" }
Moving through mutiple iFrames using XPath & C# I need to get a data element out of a table, which is nested within two iframes. The frames appear as: <iframe id="appContent" frameborder="0" name="appContentFrame" src="/controller.aspx" style="height: 0px; width: 1319px;"> //.... <iframe id="childFrame" frameborder="0" src="javascript:"";" onload="AjaxDocument.registerFrames('childFrame');" name="childFrame"> I am trying to select both of the frames by using: driver.SwitchTo().Frame("appContent"); driver.SwitchTo().Frame("childFrame"); The calls worked the first time I used them, however when I call them a second time, after I load a new webpage, they can not be found. I used these same calls earlier in the program where I was inputting data on another webpage with the same named iframes. Is it possible the reason why I can not call them again is because both set of calls are within the same scope of code?
The possible reason is because you are not switching back to the parent. When you are done working inside first `iframe` do a `driver.SwitchTo().DefaultContent()` which will take you back to the previous frame and do the same for the upper layer of `iframe` once more. **Edit** Finding correct API doc on C# is painful. However, these are the most concise definitions of two important methods used for switching frames. driver.SwitchTo().ParentFrame(); > Select the parent frame of the currently selected frame. driver.SwitchTo().DefaultContent(); > Switches to the element that currently has the focus, or the body element Refer to this
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 2, "tags": "c#, html, iframe, xpath, selenium webdriver" }
Plotting resolvent of the matrix I'm trying to reproduce resolvent plot of circulant matrix, page 59 of Mark Embree's slides ![plot of matrix resolvent]( Straightforward solution below, relying on `ComplexPlot3D` is below. It works for some matrices, but for this one it fails. Is there a more robust way to plot the resolvent? n = 5; A = IdentityMatrix[n]; A = A[[2 ;;]]~Join~{First[A]}; ii = IdentityMatrix[n]; A // MatrixForm ComplexPlot3D[Norm@Inverse[z*ii - A], {z, -2 - 2 I, 2 + 2 I}]
Here is a solution using the default `Norm`: resolvent=Inverse[z*ii-A]; aux[zz_?NumericQ]:=Block[{z=zz},Norm[resolvent]]; Plot3D[aux[x+I*y],{x,-2,2},{y,-2,2},PlotPoints->100]
stackexchange-mathematica
{ "answer_score": 4, "question_score": 4, "tags": "matrix, linear algebra, complex, visualization" }
Clean with progress bar I need to wipe a disk on my PC, so I have made a batch file that basically creates a partition, and cleans it using command `DISKPART clean all`. I want to output a progress bar of that somehow, does anyone know how to do that?
Unfortunately, `DISKPART` doesn't provide any incremental output that could be used to provide a progress bar of any sort. Before starting the operation you may simply want to warn the user with an Echo statement: echo Cleaning disk. This may take a bit. Please wait...
stackexchange-superuser
{ "answer_score": 3, "question_score": 2, "tags": "batch file" }
http client post async in c# I've looked at this example to do a post request in F# but I'm wondering how to do the same using an async post request type Authentication = new() = {} member this.RequestToken() = use client = new HttpClient() client.PostAsync " printfn "requestToken" **Edit** comparable C# code as per request in the comments. var body = "some data"; using (var client = new HttpClient(new HttpClientHandler { UseProxy = false })) { var response = await client.PostAsync(" new StringContent(body, Encoding.UTF8, "application/xml")); var content = await response.Content.ReadAsStringAsync(); }
For F# asynchronous code, you need to use an `async` computation expression and `Async.AwaitTask` to convert from C#'s `Task<_>` type to F#'s `Async<_>`. I suggest you look up some documentation about F# async workflows. type Authentication = new() = {} member this.RequestToken() = async { use client = new HttpClient() let! response = client.PostAsync " |> Async.AwaitTask let! content = response.Content.ReadAsStringAsync() |> Async.AwaitTask return content }
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "asynchronous, f#, httpclient, c# to f#" }
5 volts to breadboard not working I am trying to verify I have power and verify positive and negative wires from cyberpower plug. I can't get this led to light up. I am going to attach two pictures one of the breadboard setup and one of the power module. The power module has a sliding switch that I have set to 5 volts. The resistor is 680 ohm the power unit is up to 1300 mA. The long leg of the led is plugged in next to the resistor. I have switched the black and red from positive to negative on the board. I know this is probably a dumb question but we all have to start somewhere. Thanks Mark ![breadboard setup]( ![power unit](
Well one multi - meter later I discovered that the 5 on the slider of the power supply must have been .5 because when set to 4.5 higher up the scale the multimeter shows 5 volts and everything works. I now have a esp8266 running from a nodemcu .9 devboard running an mqtt client working off the breadboard power subscribing and publishing. which was todays goal. Thanks everyone.
stackexchange-stackoverflow
{ "answer_score": -1, "question_score": -2, "tags": "arduino, led" }
Using AdMob solely for House Ads I am updating one of my iOS apps to include Ads. However, I would only like to show own ads on contracts I sell to local companies. I believe AdMobs is a good enough for that since I can add my own "House ads", but I would like to "disable" AdMob to show any other ads from what I choose to show. Is this possible? Or should I do this any other way, and if so.. how? (Any frameworks or services I can use?) _**EDIT_** To make my question a bit more clear: I believe I cannot use AdMob solely for house-ads, so how can I achieve using an external "partner" for house-ads only. Can it be done in the code for AdMobs, or should I use an other framework/partner?
It sounds like you're looking for a product like DoubleClick for Publishers where you can manage your own inventory. DFP is also integrated with AdMob, so you can use the AdMob SDK to send requests to your DFP network.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 3, "tags": "ios, admob, ads" }
push to string and separate values I have `arr = [1,2,3,4,5..etc]` str = '' arr.each do|a| str << a end I need `str='1,2,3..etc'` Instead of `str='123'` in short I need add separator between values
You should use `Array#join` method. arr = [1,2,3,4,5..9] arr.join(',')
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 0, "tags": "ruby on rails, ruby" }
Explain instability in Numerics so that I can understand and answer this question that involves roots of a equation I found this question in my math book: > **Instability.** For small **|a|** the equation **(x - k)^2 = a** has nearly a double root. > Why do these roots show **instability**? I read and belive I understood the part in my book about stability and instability but it said nothing about equations, only algorithms. I guess I don't understand the question and probably understand stability. So please explain so that I can learn this properly
Ignore the $k$, that's basically irrelevant. The point is really that if $a,b$ are small positive numbers, then $|\sqrt{a}-\sqrt{b}|$ is much larger than $|a-b|$. You can see this with a linear approximation: $\sqrt{b} \approx \sqrt{a} + \frac{b-a}{2\sqrt{a}}.$ So $|\sqrt{a}-\sqrt{b}| \approx \frac{|a-b|}{2 \sqrt{a}}$. Thus the error in the _input_ basically gets divided by $2 \sqrt{a}$ in the _output_. This is a small number, so the error in the output is much larger than the error in the input. This is what we mean by numerical instability.
stackexchange-math
{ "answer_score": 1, "question_score": 0, "tags": "algorithms, numerical methods, stability in odes" }
WhatsApp URL scheme Can't get the Whatsapp url scheme to work. Something as simple as whatsapp://send?text={{Hello World!}} sends me to the last chats window where I can select a group/contact and I get a prepopulated chat window with the text. But the abid parameter never does anything to avoid the contact selection. I am using Launch Center Pro and am retrieving the abid with their [contact-abid] prompt a described here: < Example url: whatsapp://send?text={{test}}&abid=119 Can anyone confirm that this actually still works? Am I missing something? Thanks! Sandro
Whatsaap have withdrawn it support for url scheme to send text or open particular chat in the latest version. Earlier it was possible. Only thing now you can do is open the app/ navigate to contact page.
stackexchange-apple
{ "answer_score": 2, "question_score": 1, "tags": "ios, url, whatsapp.app" }
Replacing background image javascript Is there a way to change the background-image style with javascript? i currently have: if($(".stLarge").attr.backgroundImage = " { console.log('hello'); $('.stLarge[backgroundImage=" "url(/images/facebook.png)"; } It's getting inside the if statement but not executing the image change. Any idea what i have done wrong? Thanks in advance
`BackgroundImage` is a property of the `style` object within Element Objects and not an attribute. You can change and read css properties with jQuery `.css()` method. var imgUrls = [' '/images/facebook.png'] var $jq = $(".stLarge"); if($jq.css('background-image').indexOf(imgUrls[0]) > -1){ $jq.css('background-image', 'url("' + imgUrls[1] + '")'); }
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 0, "tags": "javascript, css, background image" }
Publish office VSTO addin into office store Is that possible to publish an office add in (created for desktop outlook using vsto and I guess it works only on windows) in office store? How to generate an xml manifest for it? PS addin just customizes UI and doesn't need any web resources Or probably there is a simple way to migrate to outlook App? without hosting any code on my server
It is not possible, VSTO have to be deployed via an EXE installation package. Only apps for office (also call "office add-ins") can be published into the office store. Apps for office contains a Manifest + webpage, VSTO contains only dlls. To run a Apps for office, user needs to have Internet, conversely VSTO add-ins is fully functional without internet connection. To know more about VSTO see here To know more about App for office see here
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 3, "tags": "c#, vsto, office addins" }
django cutom image name on upload I need create a image upload with django, the problem is, django always saving in a global project(called linkdump) folder, I want save it on the project folder(linktracker). setting.py: STATIC_URL = '/static/' model: class Link(models.Model): link_description = models.CharField(max_length=200) link_url = models.CharField(max_length=200) link_image = models.ImageField(upload_to= './static/') def __str__(self): return self.link_description class Admin: pass now in the view: <img src="{% static link.link_image %}" alt="{{ link.link_description }}"> it returns and the upload is in the project folder(linkdump), not inside the app.
You can specify a function to return a custom path for the ImageField: def get_upload_path(instance, filename): return 'your/custom/path/here' class Link(models.Model): . . . link_image = models.ImageField(upload_to=get_upload_path) Now you can use information from the model instance to build up the path to upload to. Additionally, you don't want to use the {% static %} template tag to specify the path to the image. You would just use the `.url` property of the field: <img src="{{ link.link_image.url }}" alt="{{ link.link_description }}" />
stackexchange-stackoverflow
{ "answer_score": 1, "question_score": 0, "tags": "django, image uploading" }
Drag and Drop на jquery Здравствуйте. Имеется такой код: $("body").on('dragenter', function(event){ event.preventDefault(); event.stopPropagation(); $(".main_text").html('Отпустите файл'); }); $("body").on('dragleave', function(event){ event.preventDefault(); event.stopPropagation(); $(".main_text").html('Перетащите изображение для загрузки'); }); $("body").on("drop", function(event) { console.log(1); event.preventDefault(); $(".main_text").html('Начало загрузки...'); var file = event.dataTransfer.files[0]; $(".main_text").html(file.name); }); Первые два события работают, а событие drop просто открывает файл, вместо того , чтобы отобразить его имя. Подскажите, что я делаю не так?
Сделал хоть и костыль, но он работает. Вместо всей этой ерунды добавляем <input type="file" class="input_hiden"> Задаем ему стиль: .input_hiden{ position: absolute; z-index: 9999999999999; top: -880%; left: 0px; opacity: 0;} Я выставляю ему размер через js $(".input_hiden").css('height', $(window).height()); $(".input_hiden").css('width', $(window).width()); И все, вы прекрасны! Drag and Drop работает, не забудьте добавить обработчик :)
stackexchange-ru_stackoverflow
{ "answer_score": 1, "question_score": 1, "tags": "javascript, jquery" }
How to determine the radius of convergence if the Taylor series cannot be written in a neat way? I am trying to evaluate the radius of convergence of Taylor series centered at zero of function $$f(z)=\frac{\sin(3z)}{\sin(z+\pi/6)}$$ I guess the answer should be $\pi/6$ because the function will not be bounded if $x$ approaches $\pi/6$. And it is easy to show that $f$ is convergent for all $z$ with norm less than $\pi/6$ because the denominator will not reach zero. However, outside the circle with radius $\pi/6$ there do exist points that makes $f$ converge. So I am confused whether I get the right answer. Usually for a simple power series, if we determine the radius of convergence we will have the series diverge for all $z$ outside the circle. So I am really not sure what is the situation here.
The power series will diverge outside the disk of radius $\frac\pi6$ centered at $0$. That doesn't mean the function isn't defined there. "Usually for a simple power series..." This is the usual. Consider the function $f(z)=\frac1{1-z}$. Its power series centered at $0$ is $\sum\limits_{n=0}^\infty z^n$, with radius of convergence $1$, even though $f(z)$ is defined when $|z|>1$. Outside the disk of convergence, these functions have different power series with different centers.
stackexchange-math
{ "answer_score": 2, "question_score": 4, "tags": "complex analysis, convergence divergence, taylor expansion" }
MySQL fallback query if no results I have this query that selects 10 related videos to the given video from `videos` table. I want `always to have 10 results` so if this query fails to get results or there are less than 10 results another query with less where conditions will be executed. I was counting the rows in `php` before, making another query and merging the results. It was so slow and the code got too long. I know it is better and faster to do in SQL. I'm using `PDO` with `php`. How can I combine them? First query (main one): select * from videos where FROM_UNIXTIME(published) BETWEEN DATE_SUB(FROM_UNIXTIME(:published), INTERVAL 6 MONTH) AND DATE_ADD(FROM_UNIXTIME(:published), INTERVAL 6 MONTH) and video_name != :video_name ORDER BY RAND() limit 10"; Second query(fallback): select * from videos ORDER BY RAND() limit 10
You can combine them with `UNION` and to do "parent" `SELECT` again with `LIMIT`: SELECT * FROM ( SELECT * FROM videos WHERE FROM_UNIXTIME(published) BETWEEN DATE_SUB(FROM_UNIXTIME(: published), INTERVAL 6 MONTH) AND DATE_ADD(FROM_UNIXTIME(: published),INTERVAL 6 MONTH) AND video_name != : video_name ORDER BY RAND() LIMIT 10 UNION SELECT * FROM videos ORDER BY RAND() LIMIT 10 ) t LIMIT 10 This will give you 10 records at the end without need of any PHP logic. Not sure what will be performance with such SQL.
stackexchange-stackoverflow
{ "answer_score": 4, "question_score": 4, "tags": "php, mysql, pdo" }
What does this notation stand for when describing a code? This code has appeared in some online course material. I understand the $(5, 4, 3)$ refers to (length, num codewords, distance) but no explanation of the $Z_2^5$ notation is given: > One $(5,4,3)$ code in $Z_2^5$ is given as below: > > $C_3 = \pmatrix{0, 0, 0, 0, 0\\\0,1,1,0,1\\\1,0,1,1,0\\\1,1,0,1,1}$
$Z_2^5$ means that you are working in $GF(2)^5$. $GF(2)$ is the Finite Field with two elements: 0 and 1 with the addition and multiplications defined: $0 + 0 = 0\\\ 0 + 1 = 1\\\ 1 + 0 = 1\\\ 1 + 1 = 0$ It is equivalent to XOR. $0 \times 0 = 0\\\ 0 \times 1 = 0\\\ 1 \times 0 = 0\\\ 1 \times 1 = 1$ It is equivalent to AND. the $ ^5$ is the dimension of the space (or the size of the vectors). Here you are using a space of dimension 5, hence 5 coordinates. $(0,1) \in Z_2^2\\\ (0,1,0) \in Z_2^3\\\ (0,1,0,1,1) \in Z_2^5$ The _exponent_ notation represent the Cartesian product of the spaces: $Z_2 \times Z_2 = Z_2^2\\\ Z_2 \times Z_2 \times Z_2 \times Z_2 \times Z_2 = Z_2^5$
stackexchange-crypto
{ "answer_score": 12, "question_score": 5, "tags": "notation, coding theory" }
Looping through an Array in bash I am currently attempting to create a bash script that will check inside of each users /Library/Mail folder to see if a folder named V2 exists. The script should create an array with each item in the array being a user and then iterate through each of these users checking their home folder for the above captioned contents. This is what I have so far: #!/bin/bash cd /Users array=($(ls)) for i in ${array[@]} do if [ -d /$i/Library/Mail/V2 ] then echo "$i mail has been upgraded." else echo "$i FAIL" fi done
Populating your array from the output of `ls` is going to make for serious problems when you have a username with spaces. Use a glob expression instead. Also, using `[ -d $i/... ]` will similarly break on names with spaces -- either use `[[ -d $i/... ]]` (the `[[ ]]` construct has its own syntax rules and doesn't require quoting) or `[ -d "$i/..." ]` (with the quotes). Similarly, you need to double-quote `"${array[@]}"` to avoid string-splitting from splitting names with spaces in two, as follows: cd /Users array=(*) for i in "${array[@]}"; do if [[ -d $i/Library/Mail/V2 ]]; then echo "$i mail has been upgraded." else echo "$i FAIL" fi done That said, you don't really need an array here at all: for i in *; do ...check for $i/Library/Mail/V2... done
stackexchange-stackoverflow
{ "answer_score": 5, "question_score": 2, "tags": "arrays, macos, bash, loops, if statement" }
Отправка простого запроса на сервер раз в 3 секунды Идея такова, мне нужно быть постоянно онлайн в одном вебсервисе, но желания держать комп включенным целый день желания нет. Чтобы быть онлайн мне достаточно посылать на сервер простой запрос раз в 3 сек и он будет думать что я онлайн. Собственно вопрос: возможно ли это реализовать на PHP? То есть я захожу запускаю `index.php`, а он (именно серверная часть,а не клиентская) в бесконечном цикле посылает `webrequest` к заданному серверу. На сколько это реализуемо?
Почему нет? Вполне реализуемо, `set_time_limit(0)` и вперед, только сервер все равно нужен будет ;) Ну и порекомендовал бы как-то сделать, чтобы можно было выключать этот сервис, может быть еще подумать о защите от запуска параллельных этих "сервисов", но это уже другое ;)
stackexchange-ru_stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "apache, php" }
controller not actualize string interpolation I got a problem My hellow.component.html is: <form> <input ng-model="hello" type="text"> </form> <p>{{hello}}</p> and hellow.component.ts is: import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-hellow', templateUrl: './hellow.component.html', styleUrls: ['./hellow.component.css'] }) export class HellowComponent implements OnInit { hello:string =''; constructor() { } ngOnInit() { } } Can you answer If I write something in input, {{hello}} string interpolation is not actualized by controller. Can you help me with this matter? also tried with: <input [(ngModel)]="hello" type="text"> Thank you, a lot.
When using the `ngModel` within tags, you'll also need to supply a name attribute so that the control can be registered with the parent form under that name. Try this. <form> <input name="hello" [(ngModel)]="hello" type="text"> </form> <p>{{hello}}</p>
stackexchange-stackoverflow
{ "answer_score": 0, "question_score": -1, "tags": "angular, string interpolation" }
How can I implement an alias in .htaccess in Apache configuration? How can I implement an alias in .htaccess in Apache configuration? Thank U) Alias /static "/var/www/core/static" <Location "/static"> SetHandler None # </Location>
You can't use `Alias` in an htaccess file. You can do something similar using mod_rewrite but you _can not alias to a folder outside of the document root_. That means, in your example, if `/var/www/core/static` isn't in your document root, then you can't link to it. The htaccess file is a "per directory" context, and has no way of knowing anything that is outside of the document root. The mod_rewrite way works something like this: RewriteEngine On RewriteRule ^static/(.*)$ /core/static [L] Assuming that `/core/static` is inside your document root. If not, there's nothing you can do with an htaccess file.
stackexchange-stackoverflow
{ "answer_score": 3, "question_score": 1, "tags": "apache, .htaccess" }
How do I turn off auto date formatting in openoffice writer? Open office inside tables is changing things like the following to dates: * 6/10 * 9/10 How do I turn this annoying thing off if I/m trying to do scale stuff?
Try right clicking the cell(s) choosing number format and checking something other than date. I couldn't replicate the behaviour you describe.
stackexchange-superuser
{ "answer_score": 1, "question_score": 1, "tags": "formatting" }
Attach headers to servo wires? I have these 3 wires coming from a servo motor. They're very thin and flimsy and despise staying in a breadboard. ![enter image description here]( Is it possible to add headers to these wires to make them easier to put in a breadboard? (Like the attached image) And if so, where would one procure such a thing? ![enter image description here](
What I do in situations like that is get some of those breadboard hookup wires, like you have in your second photo, cut them in the middle (giving yourself two wires, each with a bare end, and a end with a plug on them). Strip the bare end, and then solder it to the servo motor wires. Before commencing soldering, slip some heat-shrink tubing onto the wire. Once the wires are soldered together, move the heat-shrink tubing over the join and shrink it (with a hair-dryer, or heat gun). You now have a plug for your breadboard which is designed to be mechanically strong, and the heat-shrink tubing over the join protects it from being flexed too much. You could put some thicker heat-shrink over all three wires, to give additional stability.
stackexchange-arduino
{ "answer_score": 3, "question_score": 0, "tags": "electronics, wires" }
Chain rule for ordinary derivative of function of two variables? How does this type of chain rule work? I don't see how it makes sense. f is a function of x and y. df/dx = _d_ f/ _d_ x + _d_ f/ _d_ y * dy/dx Normal "d" is ordinary derivative, italicized "d" is partial derivative.
It is called total derivative and it is just a **special case for the chain rule** with $$f=f(t,x(t),y(t),...)$$ More precisely, total derivative is a special case of composition $f\circ g:\mathbb{R}\to\mathbb{R} $ with $f:\mathbb{R^n}\to\mathbb{R}$ and $g:\mathbb{R}\to\mathbb{R^n}$. In this particular case we have $$f(x,y(x))\implies \frac{df}{dx}=\frac{\partial f}{\partial x}\frac{\partial x}{\partial x}+\frac{\partial f}{\partial y}\frac{\partial y}{\partial x}=\frac{\partial f}{\partial x}+\frac{\partial f}{\partial y}\frac{dy}{d x}$$
stackexchange-math
{ "answer_score": 1, "question_score": 1, "tags": "partial derivative, chain rule" }
Combining multiple data types in pandas DataFrame I want to combine columns in a dataframe depending on whether the data is numeric or not, for example: import pandas as pd import numpy as np x = {'a':[1,2], 'b':['foo','bar'],'c':[np.pi,np.e]} y = pd.DataFrame.from_dict(x) y.apply(lambda x: x.sum() if x.dtype in (np.int64,np.float64) else x.min()) This gives the desired output, but it seems like there should be a nicer way to write the last line--is there a simple way to just check if the number is a numpy scalar type instead of checking if the dtype is in a specified list of numpy dtypes?
Rather than do a apply here, I would probably check each column for whether it's numeric with a simple list comprehension and separate these paths and then concat them back. This will be more efficient for larger frames. In [11]: numeric = np.array([dtype in [np.int64, np.float64] for dtype in y.dtypes]) In [12]: numeric Out[12]: array([True, False, True]) _There may be an`is_numeric_dtype` function but I'm not sure where it is.._ In [13]: y.iloc[:, numeric].sum() Out[13]: a 3.000000 c 5.859874 dtype: float64 In [14]: y.iloc[:, ~numeric].min() Out[14]: b bar dtype: object Now you can concat these and potentially reindex: In [15]: pd.concat([y.iloc[:, numeric].sum(), y.iloc[:, ~numeric].min()]).reindex(y.columns) Out[15]: a 3 b bar c 5.859874 dtype: object
stackexchange-stackoverflow
{ "answer_score": 2, "question_score": 2, "tags": "python, numpy, pandas" }
Removing line breaks from log files I'm trying to extract some information from a log file and need to remove the line breaks from it, in order to handle it easily, here is an example of the needed result : input file : 02/01/2018 08:18:14 ANR0407I Session 63121 started for administrator ADMIN_CENTER (DSMAPI) (Tcp/Ip SAP-DOC(52499)).SESSION: 63121) Output should be : 02/01/2018 08:18:14 ANR0407I Session 63121 started for administrator ADMIN_CENTER (DSMAPI) (Tcp/Ip SAP-DOC(52499(SESSION: 63121)
You could use `sed` to join lines to the previous one if they start with a sequence of blank (space or horizontal tab) characters: sed -e :a -e '$!N;s/\n[[:blank:]]\{1,\}/ /;ta' -e 'P;D' file.log This is a minor variation of the example **40\. Append a line to the previous if it starts with an equal sign "="** from Sed One-Liners Explained, Part I: File Spacing, Numbering and Text Conversion and Substitution * * * If the 'blocks' are separated by one or more blank lines (you don't show enough of the log to know whether this is the case) then a simpler alternative would be to use `awk` in _paragraph mode_ : awk -vRS= '{$1=$1} 1' file.log which reads in whole paragraphs and then re-formats them with the default (single space) output separator.
stackexchange-askubuntu
{ "answer_score": 1, "question_score": 1, "tags": "files, text processing, file format" }
I hate the high taxes in NYC. Should I incorporate in or move to another state? I'm in NYC currently and make a good living doing remote web development work and I get a 1099 at end of year. My taxes take about 35% of my paycheck. I was thinking about incorporating in another state or moving to reduce this amount. I've read some states have NO income tax, but I'm unsure, does that mean federal too? I hear Puerto Rico is another possible U.S. tax haven too. Which state/locale has the best tax rate for a self-employed individual like me?
I do not know if this is something that is relevant, but I have a friend doing the following: 1. Incorporate a company in Singapore or Luxembourg, where there is limited income tax. 2. Make your clients pay to the company. 3. Give yourself a job in your company and relevant amount of shares in the company. Take less money as your salary and more money as dividends. I do not know the complete legal implications, but taking the money as dividends may reduce the percent tax that you have to pay on your income. A thing to note is that while my friend lives in US, he may not be an American citizen (nor am I). I have heard that Americans have to pay tax on income from outside the country, which may change your case. This is by no means a legal advice, and I would recommend you talking to a lawyer about this before taking an action.
stackexchange-money
{ "answer_score": -9, "question_score": 34, "tags": "united states, taxes, income tax, state income tax, form 1099" }