INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
how to replace value in a string based on value in another column in excel
enter image description here
I want to replace the 'AA' in column B with corresponding values in Column A. How can I achieve that. I am looking for following results:
Column A
Bill
Invoice
Column B
ABAACD EFAAGH
ABAACD EFAAGH
Result
ABBILLCD EFBILLGH
ABINVOICECD EFINVOICEGH
|
In cell C1 use this formula and copy it down:
=SUBSTITUTE(B1,"AA",A1)
Check out the SUBSTITUTE function for more information.
_This answer was originally posted as acomment by @tigeravatar: feel free to repost this answer as your own, and leave me a comment so I'll delete this copy. This kind of answer has been stipulated for questions with no answers, but issue solved in the comments._
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "excel"
}
|
Flex: detect end of move function
I need to create an animation and provide some results of the move function at the END of the animation. However, i am not able to control the output till the move function is completed
I tried the isPlaying- that doesn't seem to detect that the animation is completed... so continues to output resukts before the animation is complete
sample code I tried
private function mvbut():void{
var mv:Move= new Move;
mv.xFrom=Math.random()*300;
mv.yFrom=Math.random()*200;
mv.xBy=200;mv.yBy=300;
mv.duration=1000;
mv.target=button1;
mv.play();
AddinDataGrid(i); //function to output final x,y values
i++;
|
Add an event listener
var move:Move = new Move()
move.addEventListener(EffectEvent.EFFECT_END, function ...);
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 1,
"tags": "apache flex, animation"
}
|
Rerender a panel in a simulation
I am new to Java GUI and trying to build a simulator. In every step in the simulation I want to update a panel in the frame. This planel displays a BufferedImage read from a unique buffer created in every step in the simulation.
How can I update the image in every step.
|
You should draw it on its Graphics that was passed as parameter on paintComponent.(You should extends JPanel for it)
Every step, you generate the new image. And call repaint to your JPanel draw the new Content on its Graphics.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "java, image, swing, rendering"
}
|
Adding a Node in the third level in a TreeView in C#
> An unhandled exception of type 'System.ArgumentOutOfRangeException' occurred in System.Windows.Forms.dll.
This is my line of code:
View.Nodes[View.Nodes.IndexOf(Node)].Nodes[View.Nodes.IndexOf(Node2)].Nodes.Add(Title3);
"View" is a TreeView.
I wonder how to add a node in the third level.
|
View.Nodes[View.Nodes.IndexOf(Node)].Nodes[View.Nodes.IndexOf(Node2)].Nodes.Add(Title3);
`View.Nodes.IndexOf(Node)` is the index of a node in the first level. You are indexing all levels with an index determined from the first level. I'm not sure if this is what you wanted. Maybe try this:
var firstLevelNodes = View.Nodes;
var secondLevelNodes = firstLevelNodes[firstLevelNodes.IndexOf(nodeInFirst)].Nodes;
var thirdLevelNodes = secondLevelNodes[secondLevelNodes.IndexOf(nodeInSecond)].Nodes;
...
thirdLevelNodes.Add(...);
In one line this would be pretty long:)
PS: you can write a function to do this, maybe with a predicate array to select the nodes in each level.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "c#, exception, treeview"
}
|
Return BsonDocument in ApiController
I'm working on an API in ASP.NET MVC 4, I'm using MongoDB as a backend.
Due to MongoDB storing and returning BSON objects, and MVC4 returning JSON objects, I figured that it would be rather easy to simply return the BSON on the rest calls.
This didn't work, so I found the `.toJson()` method on th `BsonDocument` class, converts the BSON object to a JSON-string representation. Unfortunately when I return this string through my `ApiController`, MVC apparently thinks it should re-serialize the string as JSON, which the browser can't interpret.
So I would like to ask if there is a way to disable the JSON serialization for a specific `ApiController` method?
My current workaround is to de-serialize the JSON returned from `.toJson()` before returning it such that it will be serialized again, but this seems rather wasteful.
|
Presumably you have a schema associated with your application and the resource your api controller is attempting to return. By forcing it to use json, you are ignoring many of the benefits of the WebApi by completely sidestepping content negotiation. What if your client wants xml or yaml or ...
The issue you are experiencing is that WebApi doesn't know how to serialize a BsonDocument. So, you could write a ModelBinder for it such that it knows how to deal with it. Alternatively, and alluding to my first paragraph, create strongly typed entity/resource classes and since both MongoDB and WebApi already know about these types, they'll be able to work with them natively.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 10,
"tags": "c#, asp.net mvc, mongodb, mongodb .net driver"
}
|
In pair programming, what is each role named, and why?
I've heard the person at the keyboard named the "driver", and the other person named the "navigator". I've imagined rally car racers, where the person at the wheel just _cannot_ keep up with _everything_ that's happening, and they _must_ have the help of the "navigator", who's shouting volumes and volumes of directions at them to, literally, keep them "out of the weeds", much like a person at the keyboard is kept "on course" by the person in the second chair.
What are the more/most commonly accepted terms for the two roles in pair programming, and (if it's not obvious) are they borrowed from any earlier professions?
|
The driver (or less commonly pilot) has hands on with the keyboard and is right there, banging out the code.
The navigator (or observer, or less commonly co-driver or co-pilot) is sitting alongside with the reference documents making sure the code is going the right way.
The navigator has a better perspective of what's coming up, and isn't just worrying about the mechanics of typing away.
|
stackexchange-softwareengineering
|
{
"answer_score": 5,
"question_score": 9,
"tags": "pair programming, etymology"
}
|
How to put a vertical line with derivative
Dear All in attached image how I can put a vertical line with derivative .Any command for this please?
 should print some data to the printer that is associated with my server.
(In short, my clients will send some data to my WebAPI service, and a printer in my domain (server domain) should print it.)
I host the service in IIS and use PrintManager to print the data. But, it seems we should not do that because the web services hosted in IIS should not actually communicate with local hardware (it seems to not be a recommended approach).
While there are many tutorials about self hosting WCF or WebAPI, I am trying to find out if I can use self hosting in this case.
Can i self host my WebAPI application in a Windows service so that the service will have rights to access the printer?
|
Self-hosting is the ability to host your Web API in an environment you control (WinForms, Console, Windows Service etc).
So, in short, Yes, you can self-host Web API solutions and you would do it with some code similar to the following:
var config = new HttpSelfHostConfiguration("
config.Routes.MapHttpRoute(
"API Default", "api/{controller}/{id}",
new { id = RouteParameter.Optional });
using (HttpSelfHostServer server = new HttpSelfHostServer(config))
{
server.OpenAsync().Wait();
Console.WriteLine("Running on port 8080 - Press Enter to quit.");
Console.ReadLine();
}
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 2,
"tags": "c#, .net, asp.net web api, windows services, self hosting"
}
|
CSS not loaded correctly inside Project
I want to use `glyphicon glyphicon-info-sign`
For this I am using below code
<link rel="stylesheet" href="
And this is working for me.
When I copy CSS from above URL and create one `bootstrap.min.css` file in my Project inside `css` folder and use below code
<link rel="stylesheet" href="css/bootstrap.min.css"/>
But it's not working. I am getting below error on console 
You can download Bootstrap from < and copy font folder to your project.
Or fix the path in CSS file by replace all `../fonts/` with full path `
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "html, css, twitter bootstrap"
}
|
Initialization of vector variables in default constructor?
How do I initialize private string variables _name_ and _age_ in my constructor to "John", and 30?
class Name_pairs
{
public:
Name_pairs();
Name_pairs(string name_cons, double age_cons);
vector <string> read_names() {return name;};
vector <double> read_ages() {return age;};
void print();
void sort();
private:
vector <string> name;
vector <double> age;
};
Name_pairs::Name_pairs()
: name(), age()
{}
The usual :private_variable(default value) doesn't work. Sorry if noobish question, first time encountering classes.
|
you try to initialize the vector name with a string. These are 2 different data types. As billz already suggested, you won't need a vector of strings for a name_pair (or your class naming is misleading for billz and for me). If you would declare name as a string, you could use the constructor's initialization list again.
...
private:
string name;
double age;
};
Name_pairs::Name_pairs(string name_cons, double age_cons)
: name(name_cons), age(age_cons)
...
When you have just named your class ambigous and you really need a vector of strings in your class and you only get strings as constructor parameters, you will have to add those strings in the constructors body into your vectors.
Name_pairs::Name_pairs(string name_cons, double age_cons)
{
name.push_back(name_cons);
age.push_back(age_cons);
}
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "c++, class, vector, constructor"
}
|
Which webservices are used in android development?
I am new at this platform could anyone tell me which webservice i should use in android?
|
I think Rest-Services are best alternative of all.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -1,
"tags": "android, web services"
}
|
Should I learn OpenGL 1.5?
I want to start learning OpenGL with a book I have since a long time ago (Beginning openGL Game Programming) and it uses OpenGL 1.5 so my question is, should I learn OpenGL using this book and then learn a higher version? or should I start learning a higher version at once? are the same core concepts applied to higher versions?
|
**No.** Modern OpenGL and OpenGL 1.5 have very little in common. It's better to learn the modern OpenGL directly. Here is a good online tutorial for that: Learning Modern 3D Graphics Programming.
|
stackexchange-gamedev
|
{
"answer_score": 13,
"question_score": 2,
"tags": "opengl"
}
|
Calculate the integral: $\int\frac{\cos^5(t)}{(\sin(t))^{\frac{1}{3}}}dt$
I am in need of support from the community to help me in figuring out the calculation for the following integral: $$\int\frac{\cos^5(t)}{(\sin(t))^{\frac{1}{3}}}dt$$
my approach: $$\cos^5(t) = \cos(t)\left(\frac{1+\cos(2t)}{2}\right)^2 = \frac{1}{4}\bigl[\cos(t)(1+2\cos(2t)+\cos^2(2t))\bigr]$$
Then simplifying the integral:
$$\frac{1}{4}\left[\int \frac{\cos(t)}{(\sin(t))^{\frac{1}{3}}}+2\int\frac{\cos(2t)}{(\sin(t))^{\frac{1}{3}}}+\int\frac{\cos^2(2t)}{(\sin(t))^{\frac{1}{3}}} \right]dt$$
Using $u$ substitution for the first integral as $u = \sin(t)$ and $du = \cos(t)\,dt$
First integral: $\frac{1}{4}\int u^{-\frac{1}{3}}\,du = \frac{1}{4}\left[\frac{3u^{\frac{2}{3}}}{2} \right]$
I'm stuck on the second integral as I cannot make way on how to substitute to get rid of $t$and $2t$ respectively, any ideas?
|
Substitue $u = \sin t \implies \mathrm{d}u = \cos t \mathrm{d}t$ $$ \int\frac{\cos^5(t)}{(\sin(t))^{\frac{1}{3}}}\mathrm{d}t = \int\frac{\cos^4(t)}{(\sin(t))^{\frac{1}{3}}} \cos t\mathrm{d}t = \int\frac{(1-u^2)^2}{u^{\frac{1}{3}}}\mathrm{d}u = \int (u^{-\frac13} -2u^{\frac53}+u^{\frac{11}{3}})\mathrm{d}u$$
|
stackexchange-math
|
{
"answer_score": 8,
"question_score": 2,
"tags": "calculus, integration, trigonometric integrals"
}
|
Using Apple's Internet Sharing with the second nic on my MacPro
I want to plug a laptop into my server instead of using a switch.
When I check the button on my MacPro OSX 10.5.8 to share my internet connection on my second nic, it warns that it may affect other computers on the network and to contact my system administrator. Is this just a warning to keep the uninitiated at bay, or is there something with bonjore that may cause problems?
|
You can do it, it's just a safety warning for people that may not understand what they are doing.
|
stackexchange-serverfault
|
{
"answer_score": 0,
"question_score": 0,
"tags": "networking, apple, bonjour"
}
|
Depend on abstractions, not on concretions
For example I want to write my project without any frameworks but with ready-made libraries, not to reinvent bicycle.
But of course within evolution of project I will write my own classes that could be moved out of the project, for example it would be `\Acme\Framework` namespace. And my project files with domain layer will be placed under `\Acme\ProjectName` namespace.
So at the point I want to use Symfony's `HttpFoundation` component to deal with http layer. And I need to inject `Request` class into the controllers. But SOLID principles say that classes need to depend on abstractions instead of concretions.
Does it mean I need to create class `\Acme\Framework\Request` that depends on Symfony's `Request` and use it? Or I can use Symfony's `Request` as is.
What about the best practices in this case?
_Excuse me for my english, if it hurts you_
|
What it means is that you generally need to depend on generic interfaces. Taking your HttpFoundation Request example, you could wrap it into PSR-7 adapter and make your controller accept `Psr\Http\Message\ServerRequestInterface`. Now it doesn't depend on specifics of Symfony's HttpFoundation, and is able to work (with some additional effort, of course) with other frameworks that use PSR HTTP message interfaces, like Zend Expressive (there must be many more at this point).
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "php, dependency injection, structure"
}
|
Access user home folder outside sandbox
I'm working on a app which will not be submitted to the AppStore and am trying to open a file which the user has downloaded using Safari Download Manager.
This plugin mentions all files are downloaded inside `~/Media/Downloads`.
I've tried just using `NSString`'s `stringByExpandingTildeInPath`, but it will map to /Media/Downloads inside the application sandbox.
Question is: how can I tilde-expand that path so it maps to the actual folder?
Thanks!
|
I assume that by "Safari Download Manager" you mean that you already have a jailbroken phone. If so, the easiest way is to just install something like iFile and find out what the path is.
I'm assuming that it's something like /var/mobile/Media/Downloads. Then, there are two easy things you can do:
* Hard-code "/var/mobile" to expand a tilde at the beginning of the string.
* Find out the username you want the homedir for (probably "mobile") and try expanding ~mobile/Media/Downloads.
* Find the username, and get the homedir with a call to getpwnam() or so (assuming it exists on iOS).
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "iphone, cocoa touch, ios, jailbreak"
}
|
What is the difference between using bower and npm for adding angular module?
I am trying to add a new angular module. <
I noticed that there are 2 ways to add an angular module. One is using bower. The other is using npm.
$ npm install angular-animate
//add dependency
angular.module('myApp', [require('angular-animate')]);
$ bower install angular-animate
<script src="/bower_components/angular-animate/angular-animate.js"></script>
angular.module('myApp', ['ngAnimate']);
What is the difference between the 2 methods? What are the pros and cons of each method?
|
bower is load the modules in browser end this bower modules will use only in front end you cant use it in backend. npm is load the modules in backend as well you can us it in back end and front end by using require or import
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "angularjs, npm, bower, angular module"
}
|
Issue while formatting date in c#
I'm passing TextBox DateTime value to Entity Model in api and formatting datetime into CultureInfo("en-GB", true) while saving data into database.
It is showing day as a month and month as a date.
Here is my code:
IFormatProvider FormatDate = new System.Globalization.CultureInfo("en-GB", true);
Convert.ToDateTime(user.DOB, FormatDate);
I'm passing date "08-04-2019" which is dd-MM-yyyy format, into user.DOB through api.
user.DOB showing Day = 4 and Month = 8 you can check it in the below image...
;
Convert.ToDateTime(user.DOB, FormatDate);
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "c#, datetime format"
}
|
Find the time taken by the man to reach his office given the following conditions?
> Walking from Home at $3$/$4$ th of this usual speed, a man reaches his office $20$ minutes late.Had the person walked at $4$/$3$ of his usual speed,find the time taken by the man to reach his office.
options: a)$45$min b)$90$min c)$70$min d)$100$min
My Approach:
I approached this problem using a simple formula taught by my sir to solve these types of problems:
Distance=$3$/$4$ . $4$/$3$($20$+q) / ($4$/$3$ - $3$/$4$)=$12$/$7$ . ($20$+q)
I am getting no Ans towards this problem.Can Anyone give me the hint Why or any other approach that would be helpful.
|
**Hint** :
Walking at $\frac34$ of his usual speed he will need $\frac43$ of the time that is usually needed to reach his office.
So denoting the time usually needed with $t$ we find that $$\frac43t=t+20\text{minutes}$$
Walking at $\frac43$ of his usual speed he will need $\frac34$ of the time that is usually needed to reach his office.
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 0,
"tags": "algebra precalculus"
}
|
Use a class from byte array without reflection?
I've instrumented my class using ASM and processed it like this
public class MyClassLoader extends ClassLoader {
...
byte[] classBytes = ... //the class is of type com.mypackage.Test
Class clazz = defineClass("com.mypackage.Test", classBytes, 0, classBytes.length);
resolveClass(clazz);
com.mypackage.Test test =(com.mypackage.Test) clazz.newInstance();
However I get ClassCastException on the last line:
java.lang.ClassCastException: com.mypackage.Test cannot be cast to com.mypackage.Test
The workaround is to use reflection:
Object test = clazz.newInstance();
test.getClass().getMethods()[0].invoke(test, null); //invoke some method - successfully
Am I using using wrong classloader or something?
|
`Class.newInstance` is a reflective call.
Typically what you would do in these situations is have the class loader be a child of the class loader that loaded the existing code. Have the implementation class implement an interface from your code's class loader. Use `Class.asSubclass` such that the `Class` is a known subtype of your interface. Construct an instance of the implementation class through `Class.getConstructor.newInstance`.
Using this technique you are not dependent upon using reflection to pick out a method, although it does require a no-args constructor.
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 0,
"tags": "java, reflection, classloader"
}
|
Electron Dialog closing refreshes my current page
I have an electron app.
It uses Bootstrap v4, Electron v2 amongst some other node modules.
I have a button which opens an electron dialog, the user selects a folder, and at this point, my application BrowserWindow appears to refresh.
I don't want this refresh to occur. I have created a test case which shows this behaviour. No doubt I have made a simple error, please can take a look at this repo to show the test case which reproduces my problem.
<
|
The problem was I am writing a log.txt file to the directory which is being watched by the electron-reload module.
When I write a new record to the log, the file changes, and causes my application to reload! Makes sense - but the combination of my logging & active reload isn't working nicely together.
I have solved it by simply removing electron-reload.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 2,
"tags": "html, css, node.js, bootstrap 4, electron"
}
|
Change the third comma with : regex
I want to change the third comma in this string using regex in notepad ++
145, 45, 67, 688
With a ":" Like this :
145, 45, 67: 688
I tried this
(?:,)(,)*
I think I am missing something
|
If the third comma is always the last, you can check for the end of the string/line with `$`:
,(?=[^,]*$)
Demo: <
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "regex"
}
|
File Read/Write in Python
The code below works for updating my json file but it unnecessarily opens the file twice, once to read and then to write. I tried opening it with 'r+' instead of 'r', but then it appended the revised json instead of replacing the original file. 'w+' also didn't work - the file couldn't be read.
Any thoughts or ideas for how to update without opening the file twice?
with open(shared_file_path,'r') as json_file:
data = json.load(json_file)
if data[param] != value:
data[param] = value
with open(shared_file_path,'w') as json_file:
json.dump(data, json_file)
|
That's already a good way to do it. The "w" also deletes the existing file so that you don't have to worry about existing data when you add new stuff. If you want to do it without reopening, you could seek to the beginning and truncate the file
with open(shared_file_path,'r+') as json_file:
data = json.load(json_file)
if data[param] != value:
data[param] = value
json_file.seek(0)
json_file.truncate()
json.dump(data, json_file)
But opening twice is fine. Its not an expensive operation.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "python, python 3.x"
}
|
Rainbow, telling a friend
We know The rainbow is a bad Omen. Is one allowed to tell a friend when he sees one, in order to allow him to make a Bracha or should he hold back as it is a bad sign?
|
Per Mishna Brura (229:1), when one sees a rainbow he should not inform a friend about it, but rather make a bracha and keep it to himself.
|
stackexchange-judaism
|
{
"answer_score": 10,
"question_score": 7,
"tags": "halacha, blessing, weather, natural phenomenon"
}
|
How to convert Word (doc) to PDF from Windows command line?
Anyone know how to convert word files (.doc) to PDF using the command line in Windows?
We were using the service of OpenOffice, but in documents that have many tables and images, it ends up ruining much formatting.
|
"winword.exe" "C:\My Files\doc1.doc" /mFilePrintDefault
Provided you have quiet PDF printer as default.
Also, try LibreOffice offspring from OpenOffice.org. It is based on go-ooo which had no problems with OLE metrics in Office.
|
stackexchange-superuser
|
{
"answer_score": 10,
"question_score": 27,
"tags": "windows, command line, microsoft word, pdf, conversion"
}
|
Is it possible to have two keys in the same class?
I have a question. I don't really know if it's possible. I'm working on an MVC application and part of the model look like this:
public class EmployeeNewspaper
{
public string Name { get; set; }
[Key]
public string Appendage { get; set; }
public string SourceInformationName { get; set; }
}
So my question is: Is it possible to have two keys in the same class? Or what can I do? I need to have the name and the appendage unique. Is it possible?
|
Thanks @Charle I was actually looking for composite key and the answer is:
public class EmployeeNewspaper
{
[Key][Column(Order = 0)]
public string Name { get; set; }
[Key][Column(Order = 1)]
public string Appendage { get; set; }
public string SourceInformationName { get; set; }
}
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": -1,
"tags": "c#, asp.net mvc, entity framework, key"
}
|
Make inserted DOM node not affected by CSS
I'm trying to develop a Firefox addon/Chrome extension. How to insert a new DOM node to arbitrary place of arbitrary page without being affected by its CSS?
Take a look at this demo: < If the web page modify the style of all div under certain node in some way (`display: none` as example), and I inserted my div to it without knowing that `display` is modified, my div will not behave as I expect.
One solution I can think of is to override all standard CSS styles with default value, which is unacceptable. Is there more elegant way to do this, for example, `document.createElement('div', false)`, where the second argument indicates to the browser that this node does not inherit any CSS style from ancestors.
|
You can embed your own css to the DOM element that you are appending.
So for the DOM element you can add css for just that DOM that will override any other as inline CSS preceeds others
<
var s = document.createElement('style')
s.textContent = 'div { display: none }'; // problematic CSS
document.head.appendChild(s);
// expect to show a black block, but will not show due to the CSS style above
var d = document.createElement('div');
d.style.backgroundColor = 'black';
d.style.width = '100px';
d.style.height = '100px';
d.style.display = 'block'; // here
document.body.appendChild(d);
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 2,
"tags": "javascript, html, css, dom"
}
|
How to control max-width using divs within another div?
Right now I am creating a website and I have text boxes style close to each other each using a unique div. When I resize the browser the divs over lap each other so I was thinking of using max-width to keep everything together. I have successfully used this code
html {
min-width: 1000px;
max-width: 1000px;
margin: 0 auto;
height: 100%;
}
to keep the max-width at 1000px but my text boxes are ignoring this and just doing their own thing. I tried to create a div to control all my divs but it is not working. Any help would greatly be appreciated.
HTML: < CSS: <
|
Your `<div class="wrapper">` was closed incorrectly the closing bracket needs to be at the bottom of your code for the elements to adapt the `min-width`.
`<div class="wrapper"> <img src="images/LOGO.png"/> <ul class="menu"> <li><a href="../menu.html">Menu</a></li> <li><a href="../map.html">Map</a></li> <li><a href="../info.html">Store Info</a></li> <li id="no-link">Order Now</li> </ul> /* other html code needs to be here */ </div> /*This </div> needs to be after your blocks */`
`div.wrapper { width: 120%; min-width: 1000px; height: auto; position: relative; left: -10%; margin-top: 17% }`
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "html, css"
}
|
Red language executable also opening up a console
I compiled an executable using following simple code (from Red language websites) in Red language:
Red [title: "test" needs: 'view]
view [
below
button
field
text "Red is really pretty easy to program."
text-list
check
]
I used following command:
red -c myprog.red
It was created without any error. However, when I run it there are 2 problems:
1. The application window does not have the title given above ("test").
2. A console window also opens that closes only after the application is shut down. It will be better if such a window does not open at all and only application window opens.
I am working on Windows-7. Where is the problem and how can these be solved? Thanks for your help.
|
Use
red -c -t Windows myprog.red
and the compilat is specifically for Windows
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 2,
"tags": "user interface, console, rebol, red"
}
|
Massive holding open of TCP/IP sockets
I would like to create a server infrastructure that allows 500 clients to connect all at the same time and have an indefinite connection. The plan is to have clients connect to TCP/IP sockets on the server and have them stay connected, with the server sending out data to clients randomly and clients sending data to the server randomly, similar to a small MMOG, but with scarcely any data. I came up with this plan in comparison to TCP polling every 15-30 seconds from each client.
My question is, in leaving these connections open, will this cause a massive sum of server bandwidth usage at idle? Is this the best approach without getting into the guts of TCP?
|
TCP uses no bandwidth when idle, except maybe a few bytes every so often (default is 2 hours) if "keep-alive" is enabled.
500 connections is nothing, though `epoll()` is a good choice to reduce system overhead. 5000 connections might start to become an issue.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 3,
"tags": "sockets, tcp"
}
|
RestClient работает, а HttpClient не работает | C#
Есть запрос на получение картинки. Я проверил его в Postman и скопировал сгенерированный код в C#:
var client = new RestClient();
var request = new RestRequest(" Method.GET);
request.AddHeader("referer", "
IRestResponse response = client.Execute(request2); // 200 OK
Он работает прекрасно, но я хочу использовать HttpClient.
Я пытался сделать так, однако получаю ошибку 520:
var client2 = new HttpClient();
var request2 = new HttpRequestMessage(HttpMethod.Get, "
request2.Headers.Add("referer", "
var response2 = await client.SendAsync(request2); // 520 error
**Код почти 1 в 1, что не так?**
P.S. у меня такое уже не первый раз, что RestClient работает, а строчка в строчку написанный HttpClient - нет.
|
Всё, разобрался. Дело в User-Agent. Насколько я понимаю в RestClient он передаёться по умолчанию.
Просто добавил
request2.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.128 Safari/537.36");
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "c#, rest, httpclient"
}
|
building an object in javascript using properties from another object
What I am trying to do is create an object which has x number of properties in it along with y number of properties from another object I retrieve from calling another method. Is this possible to do?
ie Here is my pseudo code. Basically I want mydata to include all the properties from the object I get back from getMoreData() Maybe this is not possible but I have no idea how to do it if it is :(
var mydata =
{
name: "Joe Soap",
dob: "01-01-2001",
otherData: {
hasCat: true,
hasDog : false
}
var otherData = getMoreData();
for(var prop in otherData)
{
create additional property in mydata for prop;
}
}
function getMoreData()
{
var moreData =
{
middleName: "tom",
location: "uk"
}
return otherData;
}
|
You can't declare variables or use other statements like `for` in the middle of an object literal. You need to define the basic object first, and then add properties afterwards:
var mydata = {
name: "Joe Soap",
dob: "01-01-2001",
otherData: {
hasCat: true,
hasDog : false
}
};
var otherData = getMoreData();
for(var prop in otherData) {
mydata[prop] = otherData[prop];
}
Also your `getMoreData()` function needs to return the `moreData` variable, not `otherData`:
function getMoreData() {
var moreData = {
middleName: "tom",
location: "uk"
}
return moreData;
}
Demo: <
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "javascript"
}
|
Can't run JUnit in Eclipse Indigo
I create simple Java Application project with `src` and `test` folders. `src` folder consists of the class which I test and `test` folder consists of the class where I describe test. When I start testing, using JUnit 4 I get: **Could not find the main class: org.eclipse.jdt.internal.junit.runner.RemoteTestRunner. Program will exit.** error. All JAR files are presented in my project.
What did I miss in my project?
|
That is a class that is part of the Eclipse plugin, it sounds like you have a corrupted installation of Eclipse. Try with a fresh installation.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "java, eclipse, junit"
}
|
How to show User current Location - GPS
I followed the following tutorial to embed Maps to my application.
Later on I have added a button, and when the user clicks on it, I will show the user their current location; here's my code:
-(void)showUserLocation {
self.mapView.showsUserLocation=YES;
}
But, when the map is pointed to Russia, and my user location is in London how can I move the map to my userlocation ?
**In detail:** When I click the button `Show User current location`, it draws the blue dot on the map. But it doesn't take me to that point. If the map is pointed to Russia, and my user location is in London, how can I move the map to point to my user location?
|
Take a look at this MKMapView method: setCenterCoordinate:animated:
MKUserLocation *location = self.mapView.userLocation;
[self.mapView setCenterCoordinate: CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longutde) animated:YES];
This should be preferably be implemented using this MKMapViewDelegate method: mapView:didUpdateUserLocation
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "iphone, objective c"
}
|
Запуск функции точно по минутам
У меня таймер запуска функции каждые две минуты. Подскажите как сделать запуск функции без учета секунд.
while True:
print(datetime.now())
minutesToSleep = 2 - datetime.now().minute % 2
time.sleep(minutesToSleep * 60)
Вывод
2019-05-10 11:24:23.695966
2019-05-10 11:26:23.696057
Надо
2019-05-10 11:24:23.695966
2019-05-10 11:26:00
2019-05-10 11:28:00
|
Почему люди так не хотят гуглить? Подобный вопрос есть на всемирном stackoverflow.
<
Вкратце, надо вставить вот эту функцию.
from datetime import datetime, timedelta
def roundTime(dt=None, roundTo=60):
if dt == None : dt = datetime.datetime.now()
seconds = (dt.replace(tzinfo=None) - dt.min).seconds
rounding = (seconds+roundTo/2) // roundTo * roundTo
return dt + timedelta(0,rounding-seconds,-dt.microsecond)
roundTime(datetime.datetime.now())
Input:
> 2019-05-10 10:14:05.975842
Output:
> 2019-05-10 10:14:00
|
stackexchange-ru_stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "python 3.x"
}
|
Default location of Error Log Elasticsearch
I need to find the default location for the Elasticsearch error log for Ubuntu. When I start the service it states it is okay but when I ask for the service this comes up:
Loaded: loaded (/usr/lib/systemd/system/elasticsearch.service; enabled; vendo
Active: inactive (dead) since Thu 2017-11-23 05:49:46 CST; 3min ago
Docs:
Main PID: 81608 (code=exited, status=0/SUCCESS)
I need to figure out why this is happening but I don't know where the error log is located. I haven't been on this computer in a few years and I did not change it from the default location.
|
try `journalctl -u elasticsearch.service -xe` first.
If this is not good look at /usr/lib/systemd/system/elasticsearch.service file, work out where the config is and find the log.
If _that_ doesn't work install lsof and search for the log in the list of open file
|
stackexchange-stackoverflow
|
{
"answer_score": 9,
"question_score": 4,
"tags": "ubuntu, elasticsearch"
}
|
Scala: How to use function as a parameter?
I have a function:
sigma(x: Int, y: Int, z: Int, a: Int)(f: (Int, Int, Int, Int) => Double): Double
I need to set it as a parameter of another function:
bigPi(x: Int, y: Int, z: Int, a: Int)('Here should be sigma'):Double
How to define a type of sigma correctly and use it as an argument of bigPi?
|
def sigma(x:Int, y:Int, z:Int, a:Int)(f:(Int,Int,Int,Int) => Double):Double = 1.1
def bigPi(x: Int, y: Int, z: Int, a: Int)(
f: (Int,Int,Int,Int) => ((Int,Int,Int,Int) => Double) => Double
):Double = 2.2
bigPi(1,2,3,4)(sigma)
The IntelliJ IDE says there are unnecessary parentheses but the compiler says otherwise.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "scala, function"
}
|
How to call an api before loading the DOM in Store Vuex?
I want to Execute a function before loading the DOM to fetch the data from an API, I know that in vue it is with before Create but how do I do it in the VUEX store?
|
In VueX you execute asynchronous code in "actions". So you create an action and call it either from the `beforeCreate` lifecycle hook or wherever you want to put it.
To call an action you can either use `this.$store.dispatch('getMatches')` or you can map an action to your components method block:
methods: {
...mapActions([
'getMatches'
])
},
beforeCreate() {
this.getMatches();
}
Usually actions also start with lowercase letters, since they're methods.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": -1,
"tags": "vue.js, vuejs2, vuex"
}
|
Unboxing - Recording voice when there's other louder noises (cutting, ripping)
So I often film unboxing and teardown videos for Youtube, and have so many issues with recording my voice clearly. Typically the waveform I get has severe peaks due to noises when cutting/ripping/opening packages, or dropping tools, etc, which make amplifying my voice difficult as it's stuck in between these peaks. I'm guessing all I can do to stop this is speak more closely and directly into the Microphone and try to reduce 'unboxing noise', but any other tips or secrets you guys have would be appreciated! I have a Blue Yeti mic set to condenser, and can't always speak directly into it, or at least I often forget which is probably the main issue.
|
Context is king here. If you are seeing your mouth and the unboxing action, then you need to hear both.
If we are only seeing the unboxing action, then you record only the sound of the unboxing action (with the vision) and to the dialogue as a voiceover. This way, you will have much more control over the relative levels.
Don't try and use something like a yeti, you will best be served by a headset mic or a lavalier. The closer to your mouth the capsule is, the better the ratio of dialogue to production effects will be.
|
stackexchange-sound
|
{
"answer_score": 5,
"question_score": 2,
"tags": "voice, background, youtube"
}
|
Not finding substring in a group regular expression
I'm trying to find a substring that looks like `"3/4"` (any number 0-9 for the numerator and denominator). However, the text that I am trying to parse may contain only a `"/4"` if its 1/4. In those cases, I don't care about the `"/"` and only want the denominator. My current regular expression is `"[0-9?\\/0-9]"` but it returns `'3/4'` one by one, when I wanted it grouped instead.
Does anyone have a fix for this?
Thanks so much!
|
I think you want to use the pipe to create an or:
([0-9]\/[0-9])|\/([0-9])
The downside of this approach though would be that you'd need to validate if group 1 or 2 returned a match... so if you had a full fraction you'd get a result in the first group, if you matched a denominator, the denominator would show up in the second group.
Might make more sense to:
([0-9]*\/[0-9])
And then check the length of each match back, and strip out the '/' if you have to.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "java, regex"
}
|
Is there a way to inject a try catch inside a function?
Maybe some of you know about AOP, in some languages using AOP can lead you to be able to inject code after, before, or while a method is executing,etc.
What I want is to apply the same in Javascript, I am currently working on a massive app which has more than 300 ajax calls, and every time I need to do some change on the catch statement on them, I have to modify them one by one which is very tedious.
What I want to do is something like :
functionName.before("try {")
functionName.after("} catch(ex){
//dostuff
}")
Is it possible? I know there are things like .call, or the arguments object inside every function..which seem pretty meta-function (AOP) functionalities.
|
Not with `before` and `after`, but a `wrap` will work:
Function.prototype.wrapTry = function(handle) {
var fn = this;
return function() {
try {
return fn.apply(this, arguments);
} catch(e) {
return handle(e);
}
};
};
Then use it like
var safeFunction = functionName.wrapTry(doStuff);
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "javascript, aop, function composition, method modifier"
}
|
Why do some photographers cover up the brand-name on their camera?
I have a professional photographer friend. He works for news agencies. He covers up the brand name on his cameras.
!Camera
This was the only photo I could find from him with his camera but it shows the coverings.
|
There are several reasons:
* For media in particular, this prevents a logo from appearing in media. Events are often covered by multiple photographers and filmed which means that some people working may end up in the media too. Think of a _making of_ video for example.
* Logos and brands are usually avoided because they may be misinterpreted as en endorsement or be seen as unpaid advertisement.
* To reduce attention. When photographing in poor or dangerous areas, the less easily someone can recognize you have expensive equipment, the better. In many places I've been asked by strangers _how much does your camera cost?_ and always feel uncomfortable answering them as it often equals months or years of salary for them. It also makes me feel they were asking me if they should rob me :(
|
stackexchange-photo
|
{
"answer_score": 41,
"question_score": 23,
"tags": "professional"
}
|
Reference request: what is the relation between classical r-matrices and quantum R-matrices?
I learned from a professor that $$ R=Id+(q-1)r+ o(q-1), $$ where $R$ is a quantum $R$-matrix and $r$ is the corresponding classical $r$-matrix. Here $o(q-1)$ denotes a term of the form $A(q-1)^2$, where $A$ doesn't depend on $q$ and $A$ is some matrix.
Are there some references about this fact? Thank you very much.
|
Are there some references about this fact?
Yes, the best references are:
V.G. Drinfeld, Quantum Groups, in Proc. of the Int. Conf. of Mathematicians (Berkeley, 1986)
V.G. Drinfeld, Sov. Math. Dokl.28 (1983) 667
M. Jimbo, Lett. Math. Phys. 10 (1985) 63, ibid. 11 (1986) 247
M. Jimbo, Commun. Math. Phys. 102 (1986) 537
E. K. Sklyanin, Funct. Anal. Appl. 16(1983) 263; ibid. 17 (1984) 273
L.D. Faddeev, N.Yu. Reshetikhin and L.A. Takhtadzhyan, Quantization of Lie Groups and Lie Algebras, in Algebraic Analysis, vol. I, (Academic Press, 1988), p. 129
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 1,
"tags": "representation theory, mathematical physics"
}
|
How can I view the desktop?
Right now I have to minimize all windows one by one to get to the desktop. Is there a way to directly view the desktop?
|
I personally like to use `Hot corners` to show the desktop.
To do this, first install devilspie with:
sudo apt-get install devilspie
Then create a script file with:
io.elementary.code ~/minimize.ds
(or some other text editor) and inside that file paste the following content:
(if
(begin
(not(is(application_name) "wingpanel")))
(if
(begin
(not(is(application_name) "plank")))
(begin
(minimize)
(quit))
))
save and exit the text editor.
Then open `Preferences/Desktop/Hot corners`, select `Personalized order` for one of the corners and in the `Execute custom command` text box paste the following:
devilspie /home/<user>/minimize.ds
Replace `<user>` with your user name, so it looks like this (I've selected the bottom right corner):
!enter image description here
After that, moving the mouse to that corner should show you the desktop.
|
stackexchange-elementaryos
|
{
"answer_score": 17,
"question_score": 19,
"tags": "keyboard shortcuts, desktop"
}
|
Coin change,dynamic programming revisited
I am having tough time in understanding the logic behind this problem, This is classical Dynamic Programming Problem
Coin Change is the problem of finding the number
of ways of making changes for a particular amount of cents, n,
using a given set of denominations d1,d2,..dm;
I know how the recursion works,Like taking the mth coin or not.But I don't understand what does '+' do between the two states.
**For eg**
C(N,m)=C(N,m-1)+C(N-dm,m)
^
|
Question might be stupid but I still would like to know so that I can have better understanding.Thanks
|
Well , you haven't written your state right! Coin Change:
Let C(i,j) represents the number of ways to form j as a sum using only i coins (from i to 1).
Now to get a recursive function you have to define transitions or change in state or may be just expressing the given expression in the terms of lower values!!
There are 2 **independent** ways in which I can represent this state that are
1) Lets pick up the i th coin , Then what happens ? I need denomination j-Denomination[i] with i-1 coins if repetition is not allowed . i.e. C(i,j)= C(i-1,j-Denominations[i])
But wait , we are missing some ways i.e. when we do not take the current coin
2) C(i,j)=C(i-1,j)
Now as both of them are independent and exhaustive , These both of these state makes up the total number of ways!!!
C(i,j)=C(i-1,j)+C(i-1,j-Denominations[i])
I will leave the recurrence when repetition allowed for you!
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "dynamic programming"
}
|
Shortest way to compare 2 dates in dd/mm/yyyy format
can anyone suggest the neatest way to do this comparison? I need to test if a date provided in dd/mm/yyyy format is less than a fixed date, e.g 01/05/2009 - I know I can convert these to unix time format using strtotime, then make the comparison, but I'm curious if there is a quicker way to do it - many thanks, just looking for a hint to improve my code!
|
There's probably not a shorter way code wise, and I wouldn't bother optimizing this unless you're sure it's a bottleneck.
However, as long as you're sure it will always be the exact same format (including 2 digits for month and day and with 0s) you should be able to reorder the string to put the year first, then the month, and then the day, and then just compare the strings.
However, I'm not sure this would be faster than just letting the libraries convert to unix time and then comparing those.
If you can change the format that the dates are stored in, you could define them as yyyy/mm/dd and then just compare the strings.
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 3,
"tags": "php"
}
|
Is there any difference between "take something up with someone" and "bring something up with someone"?
Could you tell me if there is there any difference between _take something up with someone_ and _bring something up with someone_? For example:
> We are going to **take** the issue **up** with the boss.
>
> We are going to **bring** the issue **up** with the boss.
|
Bringing something up is like discussing a topic. It could be about anything.
Taking something up can be a bit more contentious, suggesting here that the issue may be _with_ the boss himself, something he did, a disagreement over a decision he made, etc.
|
stackexchange-ell
|
{
"answer_score": 1,
"question_score": 1,
"tags": "difference, phrasal verbs"
}
|
Runtime error when deleting a row in Worksheet_Change
I have a problem with this code:
Private Sub Worksheet_Change(ByVal Target As Range)
If Target Is Nothing Then Exit Sub
MsgBox Target.Value
End Sub
After I enter text to some cell I get a message box, but if I try to delete the row where I just entered a text, I get an error:
> Run-time error '13': Type mismatch
How can I fix this error? Why the condition doesn't catch it?
|
When you delete row as a result the whole row is `target` object in your procedure. Therefore your macro is not able to return value of the row.
What programmers usually do is additional condition which is checked before your message box:
If Target.Count =1 Then
'your messagebox here
End If
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "excel, vba"
}
|
Prevent "FLUSH TABLES" query from being replicated
We have a master-master replication setup for one of our databases. Some automated backup software will issue a "FLUSH TABLES" command before commencing with a backup, but this command gets replicated to the other DB server. When a certain set of conditions occurs that includes a write query to a table, there seems to be a dead-lock condition that results which causes more queries to be unable to either read or write.
To alleviate this situation, is it possible to exclude all "FLUSH TABLES" commands from being replicated to a MySQL slave?
|
Try something this on the Master in a single DB session to see if this helps:
SET sql_log_bin = 0;
FLUSH TABLES;
SET sql_log_bin = 1;
This prevents the `FLUSH TABLES;` command from entering into the binary logs on the Master. Therefore, `FLUSH TABLES;` should never see the light of day on the Slave.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 3,
"tags": "mysql, replication"
}
|
How to replace all pixels of some color in a bitmap in Rebol?
Let's say I have a picture, I want to create some variations by changing a color. How to do this ?
I don't want to apply color filter to a picture, I want to change pixels color pixel by pixel by testing a color pixel if it is let's say red, i want to turn it to blue.
|
In Rebol images are also series, so you can use most of the series functions to change/find rgb colors etc.
i: load %test.png
type? i
image!
first i
255.255.255.0 (the last value is alpha)
change i 255.0.0.0 ;change the first rgba value to red
view layout [image i] ;you can see the upper-left pixel is now red
you can dump all rgba values in an image:
forall i [print first i]
you can also change a continues part:
change/dup head i blue 100 ;change first 100 pixels to blue
you can also work on i/rgb and i/alpha, these are binary values (bytes) and you can use copy to get a part of an image:
j: copy/part at i 100x100 50x50 ;copy from 100x100 to 150x150 to a new image.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "rebol"
}
|
Azure functions throwing error when trying to debug on MacOS
Trying to debug an Azure functions project. On the mac clicking F5 and starting the debug.
And the output is this :
[2021-07-25T08:47:57.429Z] Cannot create directory for shared memory usage: /dev/shm/AzureFunctions
[2021-07-25T08:47:57.434Z] System.IO.FileSystem: Access to the path '/dev/shm/AzureFunctions' is denied. Operation not permitted.
Value cannot be null. (Parameter 'provider')
Has anybody encountered this before and know how to fix this ? I tried running visual studio code with administrator permissions like this : sudo open ./Visual\ Studio\ Code.app
Also tried to mkdir the /dev/shm directory but it just keeps giving this error. What should I do ?
|
Solution was adding --verbose mode and see the logs. The problem was that azure didn't support node version 15. Downgraded nodejs to version 13.12.0 and it worked.
|
stackexchange-stackoverflow
|
{
"answer_score": 7,
"question_score": 4,
"tags": "macos, azure, azure functions"
}
|
Execute stored procedure in button
I have a drop down list binded to a stored procedure sp_selectyear that shows the distinct years from a column in a table
ex: 2010 2011 2012
I want to execute another stored procedure sp_deleteyear on a button that deletes those rows/records based on the year selected in the drop down list. How would I do this?
Do I need to set the output parameter for sp_selectyear?
|
You can actual get the id from dropdownlist using c# by SelectValue property and then you can pass at as normal parameter to your store procedure like this;
CREATE PROC sp_selectyear
(
@yearId (your datatype)
)
AS
DELETE FROM [TableName]
WHERE [ColiD] = @yearId
**NOTE:** you don't need to use the OUTPUT parameter. It can be handled using normal parameter.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "asp.net, sql, ado.net"
}
|
Html Link references
Hi I am new to HTML and CSS and am studying as much as I can however I cannot find a good explanation for the link tag that references the CSS file and what each element means.
Can anyone advise or point me in the right direction?
<link type="text/css" rel="welcome" href="welcome.css.scss" />
|
the link tag is an html element that is explained here: <
type - the content type of link
rel - This attribute describes the relationship from the current document to the anchor specified by the href attribute
href - the anchor where the link is pointing to.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "html, css"
}
|
What is the difference between load_digits() and fetch_mldata("MNIST Original")
I would like to know the difference between
from sklearn import datasets
dataset = datasets.fetch_mldata("MNIST Original")
and
from sklearn.datasets import load_digits
tempdigits = load_digits()
How is these two related to MNIST dataset?
|
sklearn comes with a few small standard datasets that do not require to download any file from some external website. load_digits includes around 1800 samples of size 8X8 from the UCI ML dataset:
<
fetch_mldata downloads the MNist dataset from < which contains 70000 samples of size 28x28 pixels
So basically the datasets downloaded are different.
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 4,
"tags": "python, machine learning, scikit learn, dataset, mnist"
}
|
Merging multiple feature classes into one using Python
So I have feature classes from an ArcGIS database that I renamed using this Python code: !enter image description here
But now I have to merge all the feature classes that are output from this into one feature class named OSRS_ORN_NER. I'm not really sure how I should assign the inputs and outputs when I'm using the arcpy.Merge_management() tool. This is all I have right now: !enter image description here
|
Merge tool expect you a list of feature classes as the input. so you shouldn't put it in a loop.
First build a list of feature classes in loop:
#l is a list of featureclasses with absolute path
l = []
for r in rows:
# r is a featureclass like "D:\FDB.gdb\input1"
l.append(r)
arcpy.Merge_management(l, "D:\FGDB.gdb\Merged")
|
stackexchange-gis
|
{
"answer_score": 1,
"question_score": 0,
"tags": "arcgis desktop, python, arcgis 10.1, merge, feature class"
}
|
Does magic find also affect non magic items
> **Possible Duplicate:**
> What does increased magic find do?
Does MF affect the chance of a non magic item (white) to be better. Like balanced and thick instead of broken?
|
Given that the stat specifically say that it increases the chance of finding magic items, as opposed to just saying "increases the chance of finding items" I would say that it only affects the chance to find magic or greater items.
|
stackexchange-gaming
|
{
"answer_score": 2,
"question_score": 0,
"tags": "diablo 3"
}
|
SVN authorization failed
I cannot checkout from my SVN repo with the following configuration on Ubuntu:
svnserve.conf:
[general]
anon-access = none
auth-access = write
password-db = passwd
authz-db = authz
[sasl]
authz content:
[aliases]
[groups]
[/procode]
kompi = rw
tlevi = rw
[/procode/code]
david = rw
test = rw
passwd content:
[users]
david = aaa
adam = aaa
levi = aaa
test = aaa
my repo is located in /home/kompi/business
I start svnserver with: svnserve -d -r /home/kompi/business --log-file /home/kompi/svnservelog.txt
version is: svnserve, version 1.6.12 (r955767)
and contains a procode subdirectory. I try to checkout with tortoiseSVN, with every user, but I always get an Authorization failed error.
|
The real problem was that I used the same checkout URL I used with SVN+SSH
svn+ssh://servername/home/kompi/business/procode
But when you use svnserve, the root of the url becomes your repo, so the correct URL will be:
svn://servername/procode
|
stackexchange-serverfault
|
{
"answer_score": 0,
"question_score": 0,
"tags": "ubuntu, svn, svnserve"
}
|
scope problems - exiting out of loop
I have the following code in javascript:
var continueloop = true;
while (continueloop === true) {
main()
}
and
function main() {
//do some stuff here
continueloop = false;
}
setting continueloop's value to false inside the main function does not cause the while loop to stop. I suspect that it might have to do with javascript's function scoping, but I could be mistaken could someone explain to me what I have to change in order to get the desired effect with the continueloop variable accessible to the scope of the main() function?
thanks!
|
Why don't you just return if it should continue? It's cleaner and you won't run into any scope problems either.
var continueloop = true;
while (continueloop === true) {
continueloop = main();
}
function main() {
//do some stuff here
return false;
}
// or
while(main());
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 2,
"tags": "javascript, scope"
}
|
Weird notation in Bartok's Microcosmos, Book 1, No. 9
In Bartok's Microcosmos Book 1, Number 9, I found these notes floating between the staves, without any lines.
 says:
> 9. The rhythmic feeling of the suspensions should be emphazised by some energetic movement such as tapping with the foot in the places marked by rhythmic signatures between the staves.
>
So, just tap your foot for these beats.
|
stackexchange-music
|
{
"answer_score": 9,
"question_score": 8,
"tags": "notation, bartok, mikrokosmos"
}
|
HTTP::Tiny like FTP handling
I have a module (`Alien::GSL`) which I am working on. Currently it uses `LWP::Simple` to do three calls, an FTP directory listing, an FTP file download and an HTTP file download. The problem is that for only a few calls, `LWP::Simple` has a rather large dep. chain. I tried quickly to switch to `HTTP::Tiny` but as the name should have told me, it dies on FTP requests (anonymous).
Does anyone have any suggestions for lightweight a FTP module. Preferably a lightweight HTTP/FTP module. If not then `LWP::Simple` works.
|
libnet's `Net::FTP` only requires the IO modules (standard with perl from 5.004), and itself is pretty lightweight. Libnet only supports FTP, NNTP, SMTP and POP3 however, so you can't use it for HTTP.
Maybe you can use it in combination with `HTTP::Tiny`?
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 2,
"tags": "perl, http, ftp"
}
|
Remove header image in NSIS installer
I understand that NSIS uses the installer icon (or `MUI_ICON`) as the header image by default. And that using `MUI_HEADERIMAGE` without specifying `MUI_HEADERIMAGE_BITMAP` uses the default `Contrib\Graphics\Header\nsis.bmp`
But is it possible to not display a header image altogether? (Aside from the option of specifying a blank (all-white) image as `MUI_HEADERIMAGE_BITMAP`)
|
!define MUI_HEADERIMAGE
!define MUI_HEADERIMAGE_RIGHT
!define MUI_CUSTOMFUNCTION_GUIINIT HideHeaderImage
!include MUI2.nsh
!insertmacro MUI_PAGE_COMPONENTS
!insertmacro MUI_PAGE_INSTFILES
!insertmacro MUI_LANGUAGE English
Function HideHeaderImage
!if "${MUI_SYSVERSION}" >= 2.0
ShowWindow $mui.Header.Image 0
!else
GetDlgItem $0 $hwndParent 0x416
ShowWindow $0 0
!endif
FunctionEnd
Alternatively you could edit one of the UIs in ${NSISDIR}\Contrib\UIs\modern*.exe with Resource Hacker to move the image control offscreen and then use MUI_UI or MUI_UI_HEADERIMAGE in your script to select your new UI file.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 2,
"tags": "nsis"
}
|
Publishing a paper in an academic conference being someone who works in the industry
I have been working in the industry of software engineering for 5 years so far. Lately, I am planning to take a PHD, I am interested in software architecture and quality, something that started fascinating me after experiencing failing/successful projects because of bad/good architecture mainly.
After doing some search about the matter, I see that most of PHD positions demand some publications so my plan B is to get something published to have the courage to email some possible advisors, especially that my master thesis was done in artificial intelligence, something that would be funny to tell a software-architecture-advisor about.
My question is, would an academic conference accept a paper written by me, alone, no advisor and no university to belong to?
Thank you all.
|
There is no requirement that a person be employed in academia to publish papers or submit them to academic venues, including conferences. Papers are supposed to be reviewed for their own qualities and insights, not the position or reputation of the authors (though some abuses occur).
But before submitting to any venue, you should spend some effort looking at the sorts of things that get published there, so that you style isn't too different and the quality of your results is at a similar level as that of successful submissions. There is no real bar, but, like most things, first attempts aren't always successful.
You don't even need to associate yourself with your employer for this. _Independent Researcher_ is fine as an "affiliation".
* * *
You should, however, also explore whether your assumptions about how to get accepted are valid. It would probably be worth the effort to talk to some potential advisors and see if your current qualifications are sufficient.
|
stackexchange-academia
|
{
"answer_score": 1,
"question_score": 0,
"tags": "conference, industry, independent researcher, software, publishability"
}
|
Making 2 dynamic TextViews not overlap
I have been working on an app that shows statuses about a server. I have a CardView for each server, with a RelativeView inside. On the left is an image, aligned to the cards left. In the middle, I have a TextView, aligned to the image right. On the right, I have a TextView, aligned to the right of the card.
Basically, my issue is, without using a LinearLayout, how can I make it so the middle TextView does not overlap the right TextView, preferably in the layout's XML? The text in both views is dynamically long, making a LinearLayout not very preferable.
Here is a diagram of the Layout to help you picture what I'm talking about. Sorry for the external link, it was getting reformatted in the post.
|
I figured out how to do it programatically. Simply, you want to subtract the widths and padding of the surrounding views from the size of the container view, and set the leftover value to the text view's width. Here is an example:
int view_length = personViewHolder.container.getWidth() - personViewHolder.container.getPaddingStart() - personViewHolder.container.getPaddingEnd();
view_length = view_length - personViewHolder.object_to_left.getWidth() - personViewHolder.object_to_left.getPaddingStart() -personViewHolder.object_to_left.getPaddingEnd();
view_length = view_length - personViewHolder.object_to_right.getWidth() - personViewHolder.object_to_right.getPaddingStart() - personViewHolder.object_to_right.getPaddingEnd();
personViewHolder.view_to_set_width.getLayoutParams().width = view_length;
personViewHolder.view_to_set_width.invalidate();
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "java, android"
}
|
Trying to write a recursion function in racket
I'm trying to write a regular recursion function and a tail-recursion function which takes four arguments and evaluates the sum of `ax^2 + b` for `x` from `q` to `r`.
This is what I have so far and it is not working, can I get some information on what is wrong with my code?
(define (sumof a b q r)
(define (sum)
(+ (* (expt q 2) a) b))
(if ( = q r)
0
(+ (+ q 1) (sum))))
|
Here's the correct way to call the recursion:
(define (sumof a b q r)
(define (sum q) (+ (* (expt q 2) a) b))
(if (= q r)
0
(+ (sum q)
(sumof a b (+ q 1) r))))
You should pass along the parameter that changes at each iteration, that's cleaner than capturing it from the defining environment. And notice how the `sumof` function must call itself for iterating. As a side note, your function is _not_ tail-recursive. A proper tail recursion would look like this:
(define (sumof a b q r)
(define (sum x) (+ (* a x x) b))
(let loop ((q q) (acc 0))
(if (= q r)
acc
(loop (+ q 1) (+ (sum q) acc)))))
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "recursion, scheme, racket, tail recursion"
}
|
Calling actionresult from view
This is my ActionResult()
public ActionResult pay()
{
return View();
}
[HttpPost]
public ActionResult mytry()
{
return View();
}
and this is my view pay.chtml
@using (Html.BeginForm("mytry", "Home"))
{
<table>
<tr>
<td align="center">
<input type="button" value="submit" />
</td>
</tr>
</table>
}
I am not able to call the mytry() action result from here. How to do it?
|
In order to submit your form, you must use `<input type="submit" />` or `<button type="submit">` Try the following:
@using (Html.BeginForm("mytry", "Home", FormMethod.Post))
{
<table>
<tr>
<td align="center">
<input id="btnSubmit" type="submit" value="Submit" />
</td>
</tr>
</table>
}
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "asp.net mvc, asp.net mvc 3"
}
|
Mac OS X 10.5 show suffix default
Does anybody know how you can make files show their suffix on default in finder. Currently I have to open the info window for each file and deselect "Hide extension".
Greetings elhombre
|
Sorry did search with the wrong term (suffix) I should have looked for extension. So here the answer:
Go in Finder to Finder/preference/Advanced/Show all file extensions
|
stackexchange-superuser
|
{
"answer_score": 2,
"question_score": 0,
"tags": "macos, mac, file extension"
}
|
How can I print definition of a symbol without evaluation in Scheme?
If I want to print function definition for a symbol, what should I do?
|
If I understand correctly, you want a function `print-function` such that after
(define (foo x) (cons x x))
it will behave as
> (print-function foo)
(lambda (x) (cons x x))
Standard Scheme doesn't have a facility for that. The reason is Scheme implementations may, and generally do, compile functions into a different representation (bytecode, machine code).
Some Schemes may keep the function definition around; check your implementation's manual.
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 8,
"tags": "printing, scheme, symbols"
}
|
Suppose that f(x), g(x), and h(x) are polynomials with integer coefficients such that f(x)=g(x)h(x).
Suppose that $f(x), g(x)$, and $h(x)$ are polynomials with integer coefficients such that $f(x)=g(x)h(x)$.
Suppose that $p$ is a prime number and $r$ is an integer such that $f(r)\equiv 0 \pmod p$.
Then prove that $g(r) \equiv 0 \pmod p$ or $h(r)\equiv 0\pmod p$.
I am not sure , If can I use the identity that if $p|ab$ then $p|a$ or $p|b$ for this question?
Could you please help me with that ?
|
$f(r)=g(r)h(r)$ is just writing the integer $f(r)$ as the product of two integers $g(r)$ and $h(r)$. So the polynomials don't really matter, and you can use the result that you stated.
|
stackexchange-math
|
{
"answer_score": 2,
"question_score": 0,
"tags": "number theory, elementary number theory"
}
|
ngIf for iterating through two different Arrays
I have this piece of code:
<tr ng-repeat="row in someController.searchResults"
ng-class="{'selected': tableRow.selected}"
ng-click="selectRow(tableRow)" >
In this piece of code I'm iterating through `searchResults` array.
I need to add a condition (want to do it with **ngIf** ).
* If the condition is **true** I'll iterate through `someController.searchResults`
* If condition is **false** I want to iterate through another Array e.g: `someController.someOtherSearchResults`
How can I achieve that?
|
You can use plain javascript in the `ng-repeat` attribute, like so:
<tr ng-repeat="row in (someController.importantBoolean ? someController.searchResults : someController.someOtherSearchResults)"
ng-class="{'selected': row.selected}"
ng-click="selectRow(row)" >
</tr>
See the following plunker for an example: <
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "angularjs, angular ng if"
}
|
Complexity class, logarithms
I'm trying to show that $$\log_{a}(n) \in \theta(\log_{b}(n))$$ with $a,b > 0$
To prove it, I use the 'limit' theorem :
$$g \in \theta(f) \Leftrightarrow \lim_{n \to +\infty} \frac{g(n)}{f(n)}=c$$ with $c$ real constant. But after that, I get $\log_a$ over $\log_b$ and I don't know how to go on...
|
Use the fact that $(\log_a n)(\log_b a)=\log_b n$. That should help.
|
stackexchange-math
|
{
"answer_score": 0,
"question_score": 0,
"tags": "limits, proof writing, computational complexity"
}
|
How to set imshow scale
I'm fed up with matplotlib in that it's so hard to plot images in specified size.
I've two images in 32*32, 20*20 sizes. I just want to plot them in its original size, or in proportion to its original size.
After reading quite a few posts at SO, the code I'm using now is
plt.autoscale(False)
plt.subplot(1, 2, 1);
plt.imshow(img_blob[0, 0, :, :], cmap='gray',
interpolation='nearest', extent=[0, 32, 0, 32])
plt.subplot(1, 2, 2);
plt.imshow(output_blob[0, 0, :, :], cmap='gray',
interpolation='nearest', extent=[0, 20, 0, 20])
plt.show()
But the two images are still displayed in the same size.
!enter image description here
I've tried figsize
plt.subplot(1, 2, 2, figsize=(2.0, 2.0));
But apparently there's no figsize attribute.
Is it possible to make the two subplots in different size?
|
There is also an alternative to `imshow` you could use if the image proportions are very important ... there is something called `figimage` which displays a completely non-resampled image to your figure. Working with it is somewhat painstaking - it doesn't do much behind the scenes to make your life easier - but it can be useful for certain circumstances. Here is something using your example
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0,1,20)
z1 = x[:,np.newaxis] * x
y = np.linspace(0,1,32)
z2 = y[:,np.newaxis] * y
fig = plt.figure(figsize=(2,1))
plt.figimage(z1, 25, 25, cmap='gray') # X, Y offsets are in pixels
plt.figimage(z2, 75, 25, cmap='gray')
plt.show()
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 7,
"tags": "python, matplotlib"
}
|
How to create "static items" in clipit?
There are a few Q&As about clipit on this site, but information about _how_ to use some of its features remains elusive.
The documentation speaks of being able to maintain and use a list of "static items", but I cannot work out **how to create the static items** themselves. (Perhaps this is related to a previous question -- lacking a useful answer -- about how to use "actions" in clipit.)
If someone has worked this out, it would be good to know. (I'm on 16.04 LTS, FWIW.)
|
Right click the Clipit icon in the toolbar and select _Manage History_. A pop-up will appear titled Manage History.
Then choose the copied item from the list in the pop-up that you want to make static and click the _Edit_ button at the bottom. Another pop-up will appear titled Editing Clipboard.
At the bottom left there will be a check box to make the item static, then click the OK button and that's it.
|
stackexchange-askubuntu
|
{
"answer_score": 6,
"question_score": 1,
"tags": "clipboard, clipboard manager"
}
|
How to spilt a string based on two condition javascript regex
I'm struggling a clean way to split the below variable in the clean way
var x = "3/13/20,2179,5232,17660,3/14/20,2727,6391,21157,3/15/20,3499,7798,24747,3/16/20,4632,9942,27980"
The above string is separated with date and it's associated value, The result of split method should result into like this
arr[0] = ['3/13/20','2179','5232','17660']
arr[1] = ['3/14/20','2727','6391','21157']
Looking for regex pattern which can bring the above result
I know that these will not work, is there any built-in function available to achieve this stuff
.split("/");
.split(",");
|
Split by commas which are followed by `\d+\/` (the beginning of a date), then split by commas on each item:
var x = '3/13/20,2179,5232,17660,3/14/20,2727,6391,21157,3/15/20,3499,7798,24747,3/16/20,4632,9942,27980';
const arr = x
.split(/,(?=\d+\/)/)
.map(str => str.split(','));
console.log(arr);
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 0,
"tags": "javascript, regex"
}
|
Virtual function of derived class calls that of base class
#include <iostream>
using namespace std;
class Widget {
public:
int width;
virtual void resize() { width = 10; }
};
class SpeWidget :public Widget {
public:
int height;
void resize() override {
//Widget::resize();
Widget* th = static_cast<Widget*>(this);
th->resize();
height = 11;
}
};
int main() {
//Widget* w = new Widget;
//w->resize();
//std::cout << w->width << std::endl;
SpeWidget* s = new SpeWidget;
s->resize();
std::cout << s->height << "," << s->width << std::endl;
std::cin.get();
}
Derived class (SpeWidget) virtual function (resize()) wants to call that in base class (Widget). Why does the above code have segment fault. Thank you!
|
The commented out code is right.
Widget::resize();
Your substitute code is wrong.
Widget* th = static_cast<Widget*>(this);
th->resize();
Think about it: You are calling a virtual function through a _**pointer to the base class**_. What happens when you do that with any virtual function? It calls the most derived version. In other words, endless recursion.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "c++, virtual functions"
}
|
Proving $\bigcup \mathcal{P}(\mathcal{A})=\mathcal{A}$
I'm working on operations on collections of sets and I've run aground.
I'm trying to prove that if $\mathcal{A}$ is a collection of sets $\mathcal{A}_i, i=1,2,...$, then $$\bigcup{\mathcal{P}(\mathcal{A})}=\mathcal{A}$$ But how do I write the notation for the power set of a collection of sets? They are sets of sets, so $\\{\mathcal{A}, \\{\mathcal{A}_1\\},...\\{\mathcal{A}_1,\mathcal{A}_2\\},...\\}$... But how do I write that notationally?
|
1. For any $a\in A$, we have $a\in \\{a\\}\subseteq A$; hence $a\in \bigcup \mathcal{P}(A)$.
2. For any $a\in \bigcup \mathcal{P}(A)$, there is some $B\in \mathcal{P}(A)$ with $a\in B$. But then $a\in B\subseteq A$, so $a\in A$.
The nature of the elements of $A$ are irrelevant; in your case they happen to be sets but it doesn't matter.
|
stackexchange-math
|
{
"answer_score": 5,
"question_score": 3,
"tags": "elementary set theory, notation"
}
|
Updating MongoDB Document Not Working
I'm simply trying to update a specific field in a document I have for a MongoDB database.
I have the below code:
$connection = new MongoClient("private");
$collection = $connection->testdb->deliveries;
// Use the ID to generate the actual MongoID
$realmongoid = new MongoId($id);
$cursor = $collection->findOne(array('_id' => $realmongoid));
So all that works perfectly fine, but when I try to update a specific field in my document with this code:
$arrayWithDriverInfo = array("filledBy" => $_SESSION['username']);
$cursor->update($arrayWithDriverInfo);
It doesn't work. I get this message: Fatal error: `Call to a member function update() on array in...`
What is going on here?
|
Try using the **`$set`** operator in your **update** as follows
<?php
$connection = new MongoClient("private");
$collection = $connection->testdb->deliveries;
$obj = $collection->findOne();
$id = "55711efed0103b1598140076";
$realmongoid = new MongoId($id);
$arrayWithDriverInfo = array("filledBy" => $_SESSION['username']);
$collection->update(
array( '_id' => $realmongoid ),
array( '$set' => $arrayWithDriverInfo )
);
$obj = $collection->findOne();
var_dump($obj);
?>
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "php, mongodb, mongodb query"
}
|
Passing string which is the name of entity/perisistance class in createcriteria of hibernate
I have to dynamically load tables for which I was passing through controller and when I have to write hibernate peristance logic of suppose createCriteria, I gave:
getSession().createCriteria( Class.forName(tableName)).list()
where tableName is a string which would contain the name of the class. Even then I was unscessful and getting ClassNotFound Exception. It works for
`getSession().createCriteria(Book.class).list()` which I feel is hardcoding in my case. Please help regarding with which I could dynamically call tables.
|
Are you passing the exact classname? Like com.myproject.Myclass or you are just writing the table name???? You should use the complete classname to use with Class.forName(..) method.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "ajax, database, spring, hibernate"
}
|
Desktop application Use IPP QBO API 3.0
I have a desktop windows application that wants to use the intuit IPP QBO API 3.0 to interface with the quickbooks online to create invoice, customer, etc.
As the document said, I need to a add the app in my developer account. But when try to Create New QuickBooks API App, it didn't give the desktop app option. It asked me to fill all the url informations which really for an online web applicaiton.
Where to register the desktop app for the intuit IPP QBO API 3.0?
**Update:**
With all the helpful information provided in the answers, I ended up a small library DesktopIppOAuth to my project. The library uses OWIN to selfhost web api 2.0 and redirect the oauth callback to the library itself. By using that library I don't need to setup a separated site to receive the callback and get the token.
|
There is no way to register for a desktop app. You need to enter some test/non-specific urls in those fields for getting development tokens.
Then, you need to set these tokens in our sample apps- < OR
on developer playground to generate the keys. Go to Manage My Apps->Your app> Test Connect To App
Set all these keys in your desktop app and then you can make calls to the QBO API.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "sdk, desktop, intuit partner platform, intuit"
}
|
Different way to solve $|x-3|<|2x|$
I know two ways I can solve $|x-3|<|2x|$
1. By squaring both sides
2. By interpreting the inequality as a statement about distances on the real line.
Question: How can I solve this inequality algebraically, but without squaring?
Thanks!
|
By a discussion based on the sign rule for the absolute value:
$$t\ge0\implies|t|=t,t\le0\implies |t|=-t.$$
Here you have three cases
$$\begin{align}x\le0&\implies |x-3|<|2x|\equiv -x+3<-2x\\\ 0\le x\le3&\implies |x-3|<|2x|\equiv -x+3<2x\\\ x \ge3&\implies |x-3|<|2x|\equiv\ \ \ x-3<2x.\end{align}$$
Then you solve the three inequations and match the solutions against the three sub-domains.
|
stackexchange-math
|
{
"answer_score": 4,
"question_score": 1,
"tags": "inequality, absolute value"
}
|
how to replace a space with the name of a file, to build a route?
I'm trying to make a copy of all the existing files in a folder to another folder. but I have problems with the names that have that blank
folder
-- new file.txt---->the problem
-- file2.txt
-- file3.csv
i apply this mybatch.bat
set FECHA=%date%
set FECHA=%FECHA:/=%
set FILE=D:\BACKUPS
for %%i in (*) do (
copy %cd%\%%i %FILE%\${%%~ni// /_}_%DATE%%%~xi
)
try to replace the blanks with "_" the following code, in a route
${%%~ni// /_}
but this does not run, it just comes out as string
D:\BACKUPS\${%%~ni// /_}_090519.txt
i want this
D:\BACKUPS\new_file_090519.txt
|
Given the PowerShell tag, here is a solution. When you are satisfied that the copy will be done correctly, remove the `-WhatIf` from the `Copy-Item` cmdlet.
Get-ChildItem -File -Path 'C:/src/t/sv' |
ForEach-Object {
Copy-Item -Path $_.FullName `
-Destination "C:/src/t/sv2/$($_.BaseName -replace ' ','_')_$(Get-Date -format 'ddMMyy')$($_.Extension)" -WhatIf
}
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "bash, shell, powershell, unix, cmd"
}
|
AsyncTask newbie issue
I cant figure out why the variable "vysledek" stays unchanged after calling the void "Send" from activity. I probably doesnt fully understand the way AsyncTask works. Thanks for help.
public class Tools{
public String vysledek;
public void Send() {
Poslat Poslat = new Poslat();
Poslat.execute();
}
private class Poslat extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
vysledek = "something I want it to be";
}
@Override
protected void onPostExecute(String result){
vysledek = "something I want it to be 2";
}
}
I want that the Activity that called "Send" have the variable already. So i guess it has to wait for it to finish. I tried to do the waiting like this:
while (Tools.vysledek.equals(""))
{ }
But that causes crash.
|
Timing. The asnc task happens on another thread. But when the OS switches to that thread is up to the OS. It should happen quickly (next few hundred ms), but it won't necessarily be immediate, so if you immediately check for it you may or may not see it changed. The correct place to put code that requires the async task to have run is in onPostExecute.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "java, android, class, android asynctask"
}
|
Can replication\save conflicts be identified in Xpages
If I know a notes document opened in Xpages has created a replication\save conflict duplicate document and then search for the document ID in Xpages then both (or all) the documents are shown in an Xpage set up with a specific Notes view in my application. But is there any way I can tell which one is the parent document and which one(s) are the replication response documents? I need to be able to see this on the Xpages front end and not just in the Notes database backend.
|
If you create a view with `@IsAvailable($Conflict)` as the selection formula, you can identify conflicts. They have a $REF field which maps to the parent document.
Because XPages allows us to have multiple datasources on an XPage, it should be feasible to open the conflict have dominoDocument datasources for the conflict and the parent document (the non-conflict).
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "xpages"
}
|
Regex that works on regex101 does not work in Groovy
I have the following regex
def formula = math:min(math:round($$value1$$ * $$value2$$) )
def m = formula =~ /\$\$\w+\$\$/
println m.group(1)
Above should ideally print `$$value1$$`.
Now this regex for the following string works fine on regex101.com but same does not work on Groovy. Ideally it should find two groups $$value1$$ and $$value2$$ using Matcher API, but it does not.
Is there anything wrong in this regex?
|
Assuming `formula` is:
def formula = 'math:min(math:round($$value1$$ * $$value2$$) )'
I think you just want:
List result = formula.findAll(/\$\$\w+\$\$/)
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "regex, groovy"
}
|
Laravel 5 comment block
I found before few months some video on Laracast which explain comment blocks can replace some functionality in Laravel 5. I think it was different way of defining properties or something like that, it was new feature in Laravel 5, but I can't find now that video, anyone know about it?
|
I think you saw a video about annotations in Laravel 5. Route annotations and Event annotations. They are in laracasts.com, but this worked for Laravel 5 alpha version. I don't think it's useful now.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "laravel 5, comments"
}
|
Infinite field $F$ with at least two finite subfield
Can you give an example of infinite field $F$ such that $F$ has at least two finite subfield?
|
Take the field of rational functions of $\mathbb{F}_q(X)$, where $q=p^n, n>1$. We have $\mathbb{F}_{p^k}$ for all $k \mid n$ as finite subfields.
|
stackexchange-math
|
{
"answer_score": 3,
"question_score": 0,
"tags": "abstract algebra, field theory"
}
|
How to mutate all queries of a model in only one location in laravel?
I have a app where each user has your own customer. These customers can store tickets, and the users can see only the tickets that belogns to his customer.
Can I "intercept" all the queries with this where clause? I dont want put this logic everytime that I need to do a query.
|
Thanks to user3158900's help. I found this: Query Scopes - Laravel
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "php, laravel"
}
|
use UMD library in angular 2/4
I have library (Tus.io) thats compiled to UMD. i need it in my Angular2/4 project. when i install it with npm ( **npm install tus-js-client** ) and import it ( **var tus = require("tus-js-client");** ) the error i get is:
Failed to compile.
/home/***/src/app/manageVideos/Partials/add.component.ts (8,17):
Module '../../../../node_modules/tus-js-client/dist/tus.js'
was resolved to '/home/***/node_modules/tus-js-client/dist/tus.js',
but '--allowJs' is not set.
/home/***/src/app/manageVideos/Partials/add.component.ts (9,11): Cannot find name 'require'.
|
The simplest solution to your problem is to install the TypeScript declarations:
npm install @types/tus-js-client --save-dev
And to import it like this:
import * as tus from "tus-js-client";
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 2,
"tags": "javascript, angular, requirejs, umd"
}
|
How many consecutive integers to ensure one has digit sum divisible by 19?
How many consecutive positive integers are at least required, such that there is always a number in such a sequence whose sum of digits is divisible by 19?
|
The minimum $N$, such that ANY sequence of $N$ consecutive positive integers contains a number whose digit sum is divisible by 19, is:
> 199.
Proof:
1. Firstly, we can easily find a lower bound on $N$:
> Among all the integers from $1$ up to $198$, there is no number with digit sum divisible by 19, because to get a sum of 19 we need at least two 9s and a 1 among the digits. So $N\geq199$.
2. Following on from the above statement, notice that
> any string of consecutive integers from $100k$ to $100k+99$ contains numbers with all possible digit sums modulo 19: where $D(\cdot)$ means digit sum, we have $$D(100k)=D(k),D(100k+1)=D(k)+1,\cdots,D(100k+9)=D(k)+9,D(100k+19)=D(k)+10,D(100k+29)=D(k)+11,\cdots,D(100k+89)=D(k)+17,D(100k+99)=D(k)+18.$$
3. And it is clear that
> any string of 199 consecutive positive integers must contain a string from $100k$ to $100k+99$ for some $k$, whether it be the last 100, the first 100, or somewhere in between.
|
stackexchange-puzzling
|
{
"answer_score": 9,
"question_score": 3,
"tags": "mathematics, logical deduction, number theory"
}
|
Background image not showing in Safari
I am working on a responsive design and the class "bgMainpage" is having a background image but it is not showing on Safari on all the devices. I have applied background size cover as it is what the client wants. I have added browser specific CSS too and I am not sure what else to do so that it shows up in Safari too. Chrome, FF, IE show the image just fine. Any ideas ?
Project Link
CSS :
.bgMainpage{
background:url("../images/bg.jpg") no-repeat scroll right top #000000;
-o-background-size: cover;
-moz-background-size: cover;
-webkit-background-size:cover;
background-size: cover;
}
|
I converted the image format from jpeg to gif and it worked. So the final CSS is :
.bgMainpage{
background:url("../images/bg.gif") no-repeat scroll right top #000000;
-o-background-size: cover;
-moz-background-size: cover;
-webkit-background-size:cover;
background-size: cover;
}
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 32,
"tags": "html, css, safari, responsive design"
}
|
Restricting the generic type parameter to System.Enum
I have a generic type that should be specified with an `Enum` type (actually, it's one of several specified enums, but I'll settle for `System.Enum`).
Of course the compiler balks at code like:
class Generic<T> where T : Enum {}
with a _"Constraint cannot be special class 'System.Enum'"_ exception.
The only solution I've been able to come up so far is using the static type initializer to inspect the type parameter and throw an exception if it is not, in fact, an Enum, like this:
class Generic<T>
{
static Generic()
{
if (typeof(T).BaseType != typeof(Enum))
throw new Exception("Invalid Generic Argument");
}
}
which at least gives me runtime security that it wont we used with a non-enum parameter. However this feels a bit hacky, so is there a better way to accomplish this, ideally with a compile-time construct?
|
You can use Jon Skeet's Unconstrained Melody project to do this.
Using Unconstrained Melody you would write:
class Generic<T> where T : IEnumConstraint
Which would accomplish the same thing.
More info about Unconstrained Melody with usage examples.
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 6,
"tags": "c#, generics, enums"
}
|
get CultureInfo from a Currency Code?
I need to get the System.Globalization.CultureInfo for different Currency Codes.
Examples: EUR, GBP, USD
Currently I am doing the following inside a switch statement based on this 3 letter currency code, obviously this is not the way to do it:
var ci = new System.Globalization.CultureInfo("en-US");
Anyone have a clean way to achieve the same results using the currency code's instead?
|
Short: That's not possible. EUR for example would map to de-DE, fr-FR, nl-NL and other countries. There is no mapping from Currency to culture, because multiple countries share currencies.
|
stackexchange-stackoverflow
|
{
"answer_score": 13,
"question_score": 9,
"tags": "asp.net, .net"
}
|
Evaluating $\lim\limits_{n\to\infty}(a_1^n+\dots+a_k^n)^{1\over n}$ where $a_1 \ge \cdots\ge a_k \ge 0$
Need to find $\lim\limits_{n\to\infty}(a_1^n+\dots+a_k^n)^{1\over n}$ Where $a_1\ge\dots\ge a_k\ge 0$
I thought about Cauchy Theorem on limit $\lim\limits_{n\to\infty}\dfrac{a_1+\dots+a_n}{n}=\lim a_n$ and something like what happen if all $a_i=0$ or $a_1=\dots=a_k$, but may be something I am thinking wrong?
Maybe it is too simple but I am not getting it; please help.
|
Note that $$a_1=[a_1^n]^{1/n}\leq [a_1^n+\cdots+a_k^n]^{1/n}\leq [ka_1^n]^{1/n}=k^{1/n}a_1$$ and apply squeeze theorem.
|
stackexchange-math
|
{
"answer_score": 7,
"question_score": 3,
"tags": "limits"
}
|
Rails: How can I render multiple objects to JSON?
I am trying to render multiple objects as JSON. This is my render call:
render :json => {:widget => @widget.to_json(:include => :foo),
:updated => Time.now.to_i}
I have to use to_json because of the include, and the addition updated so I know when the last call was made. The problem is that the to_json is rendered as a String instead of the object structure of the widget.
How do I get the full object structure of the widget and the updated information?
|
Move the `:include => :foo` into your Widget model.
class Widget < ActiveRecord::Base
def as_json(options = {})
super options.merge(:include => :foo)
end
end
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 3,
"tags": "ruby on rails, json"
}
|
MySQL: refer to SELECT subquery alias in WHERE
Is there an easier way to write an SQL query if I want to refer to SELECT subquery in WHERE part of the query?
This is my code:
SELECT
SUM(x) AS test,
(SELECT SUM(y) FROM other_table) AS sub_test,
(test + sub_test) AS total_sum
FROM my_database
WHERE
test <> 0 AND sub_test <> 0
The code is just for illustration :) It works if I put the subquery instead of alias like:
SELECT
SUM(x) AS test,
(SELECT SUM(y) FROM other_table) AS sub_test,
(SUM(x) + (SELECT SUM(y) FROM other_table)) AS total_sum
FROM my_database
WHERE
SUM(x) <> 0 AND (SELECT SUM(y) FROM other_table) <> 0
But writing the whole subquery xx times is a bit awkward since the subquery is not just a plain "SELECT (SUM(..))"... If I want to change something in subquery I have to change it xx times and hope that I changed all of them..
|
Use `HAVING` clause over `WHERE`. And
Use user variables on the values just computed on the precious column expressions.
SELECT
@sx:=SUM(x) AS test,
(SELECT @sy:=SUM(y) FROM other_table) AS sub_test,
(@sx + @sy) AS total_sum
FROM my_database
HAVING
-- SUM(x) <> 0 AND (SELECT SUM(y) FROM other_table) <> 0
test <> 0 AND sub_test <> 0
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 2,
"tags": "mysql, sql"
}
|
How bin mapping is constructed?
I can't find the detailed description of how bin mapping is constructed in lightgbm paper. I have several questions about bin mapping.
1. Is it static or dynamic? That is, during the growth of nodes, does the bin mapping change?
2. Does the number of bins of each feature dimension equal? For example, for one hot feature, does the number of bins equal to 2?
3. For real-valued feature, are the split points of bins uniformly distributed? Or any principles to find the split points of bins?
|
1: Bins are a form of preprocessing : each variable is converted to discrete values before the optimization. It is specific to your training data and does not change.
2: There is a parameter you can tune to set the maximum number of bin. But of course if your feature only has 5 different values there will be only 5 bins. So you can have different number of bins per feature.
3: The split points for the bins are not chosen by equal width, they are chosen by frequency : If you set 100 bins, the split points will be chosen such as each bin contains approximately 1% of all your training points (it could be more or less depending if you have equal values). This process is similar to the pandas qcut function.
Hope I have covered your questions.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "lightgbm"
}
|
The newly created daemon process has a different context than expected. Java home is different. Change Java Home
Error Msg
> "
The newly created daemon process has a different context than expected. Java home is different.
Expecting: 'E:\Downloads\And_Std_2\android-studio-ide-173.4819257-windows32\android-studio\jre' but was: 'C:\Program Files\Java\jre1.8.0_181'.
Please configure the JDK to match the expected one.
> "
Android Studio was working well. It hanged suddenly. When I closed and Restarted it. The Error apparead. I have checked the path. It is same. jdk location. But still error is not removing. **Android Studio 3.1.3**
|
I had the same problem, but luckily I found a solution.
You have to set the JAVA_PATH variable like this.
**Step 1**
Windows 7 – Right click My Computer and select Properties > Advanced
Windows 8 – Go to Control Panel > System > Advanced System Settings
Windows 10 – Search for Environment Variables then select Edit the system environment variables
**Step 2**
Click the Environment Variables button.
**Step 3**
Under System Variables, click New.
**Step 4**
In the Variable Name field, enter C:\android-studio\jre (The path to the Java version that comes with Android Studio)
**Step 5**
Click OK and Apply Changes as prompted
**Step 6**
Restart your computer and it will work.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 2,
"tags": "android studio, android gradle plugin, build.gradle"
}
|
Problems with a git repo in Sharepoint documents library shared as drive
My team is trialling the use of Sharepoint Online and Teams to replace a public network drive for our docs and work files. I'm running into a problem when trying to use git: creating the repo with `git init` works, but adding and committing files fails with an error:
fatal: cannot use .git/info/exclude as an exclude file
The repo in question is a very simple one, just 4 small files in a directory a couple of levels down from the root.
Are there known problems with using git on a shared document library, mapped as a network drive? I had a look at the list of limitations, and it doesn't seem like there should be problems.
At a previous job I had git repos in my OneDrive for Business, and it mostly worked fine (although I ran into intermittent sync glitches).
|
I would recommend using Azure DevOps or GitHub to host your repositories rather than a SharePoint document library. Microsoft recommend syncing SharePoint document libraries using the OneDrive for Business application rather than mapping a library to a network drive.
|
stackexchange-sharepoint
|
{
"answer_score": 0,
"question_score": 0,
"tags": "sharepoint online, document library, mapped folder"
}
|
How to create single table for owned types
Tell me please how to generate single db table for owned types. Here my model
public class Price
{
public string OrderId { get; set; }
public Money Money { get; set; }
public Error Error { get; set; }
public PriceType PriceType { get; set; } // enum
[ConcurrencyCheck]
public DateTimeOffset UpdatedOn { get; set; }
}
public class Money
{
public string Currency { get; set; }
public decimal Amount { get; set; }
}
public class Error
{
public ErrorType Type { get; set; }
public string Message { get; set; }
}
|
Use [ComplexType] attribute for Money and Error classes <
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": -1,
"tags": "c#, entity framework"
}
|
How to read the unitary matrix of a quantum circuit in ProjectQ?
I would like to read the unitary matrix of a quantum circuit in ProjectQ. Is there any way to do it?
|
Most quantum circuit building softwares, including ProjectQ, do not have any convenience features that explicitly serve this purpose due to the potential overhead of calculating and storing the unitary as the number of qubits increases. The best solution is to create your own function that recovers the unitary. The general idea (software non-specific) is to:
1. Create your quantum function
2. Iterate through each operation and obtain the matrix representation
3. Multiply each unitary to get the final unitary representation of the circuit
|
stackexchange-quantumcomputing
|
{
"answer_score": 1,
"question_score": 5,
"tags": "programming, projectq"
}
|
Calling "Click()" method of an element returns undefined, although the element definitely exists
I'm trying to call the click() method of a file input with a specific id, but the function call returns undefined and basically, nothing happens. I've replicated the situation here: <
It's very simple:
**HTML**
<input id="hiddenFileInput" type="file" multiple="multiple" accept="image/*" >
**Javascript**
document.getElementById('hiddenFileInput').click();
alert(document.getElementById('hiddenFileInput').click());
I try calling the click() method on the element, which doesn't work. I then call alert() to print what the function returns when it's called. It returns "undefined." I'm obviously doing something wrong, but what exactly?
|
You can't emulate click on `input type=file`. It's forbidden. It works only inside another onclick handler. The user must click on something to open the dialog.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "javascript, file, input, click, undefined"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.