INSTRUCTION
stringlengths 25
999
| RESPONSE
stringlengths 0
999
| SOURCE
stringlengths 16
38
| METADATA
dict |
---|---|---|---|
How many different ways can you allocate money into 5 buckets
How many different ways can you invest $\$N,000$ into Y funds?
So for example if $N=20000$ and $Y=5$ we could have $(0,4000,1000,2000,13000)$
I know this has something to do with combinatorics but I am lost.
|
Investment are in multiple of 1000. $$ $$ Let investment in different funds are $x_1;x_2;x_3;x_4;x_5$ $$ $$ Number of ways is number of non negative integral solution of equation $$x_1+x_2+x_3+x_4+x_5=20$$ Number of ways are $$={24 \choose 20}$$ For more understanding of concept you can also refer <
|
stackexchange-math
|
{
"answer_score": 1,
"question_score": 0,
"tags": "combinatorics, combinations"
}
|
Can't log on to Domain Controller
I have a computer in a remote location (6 hour drive) on a BOVPN back to our home office. The remote computer is running XP Pro, DC is on Sever 03 all system 100% up to date. The user was logged in and everything was working fine. The user restarted and now can not log on to the system. Gets the "Domain controller can not be reached" error. I can ping the system, and connect with the remote registry, but I get challenged for a password even though I am logged in as an Admin. When I give it the login information for the admin accoutn, it tells me "Access is denied". Any advice for what I could try before I drive 6 hours?
|
You could have the remote user pull the network cable and login with his cached credentials.
I would use a windows password reset disk and reset the local admin password and then rejoin the domain.
All new systems get random passwords set to the local admin account which we keep in a database for cases such as this.
|
stackexchange-serverfault
|
{
"answer_score": 2,
"question_score": 0,
"tags": "windows xp, active directory, login"
}
|
Views in other DB performance
I have a question about views performance in SQL Server (2012+). Let's say I have 2 DBs on the same server and I create views in DB2 referencing tables in DB1, are there scenarios where the performance could be affected? I tested this with a locally installed DB and I could not see any performance issue, but I wonder if there's a risk of doing that in production. Any other concerns I should have doing that?
|
> Let's say I have 2 DBs on the same server and I create views in DB2 referencing tables in DB1, are there scenarios where the performance could be affected?
Queries and views that cross databases on the same SQL Server instance have no significant performance difference from queries and views within a single database.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "sql server"
}
|
How to make the first option of <select> selected with jQuery
How do I make the first option of selected with jQuery?
<select id="target">
<option value="1">...</option>
<option value="2">...</option>
</select>
|
$("#target").val($("#target option:first").val());
|
stackexchange-stackoverflow
|
{
"answer_score": 1065,
"question_score": 620,
"tags": "jquery, select"
}
|
Convert string into jQuery object and select inner element
I wonder if there is a way to convert string into jQuery object and select inner elements without injecting the whole string into DOM and manipulate it in there. Thanks.
If possible, please give me example of converting
<div id=a1></div>
<div id=a3></div>
And select a1 from the object variable.
|
This will create elements from the html and find the a1 element:
var element = $('<div id="a1"></div><div id="a3"></div>').filter('#a1').get(0);
|
stackexchange-stackoverflow
|
{
"answer_score": 26,
"question_score": 17,
"tags": "javascript, jquery, html, dom"
}
|
How to get array value from wordpress database get_results
Trying to echo the array value from my mysql query (inside Wordpress snippet)
function get_customer_gain() {
global $wpdb;
$users = $wpdb->get_results( "SELECT SUM(wp_wpdatatable_1.payback) FROM wp_wpdatatable_1");
foreach( $users as $user ) {
echo $user;
}
}
add_shortcode('customer_gain', 'get_customer_gain');
my var_dump is: array(1) { [0]=> object(stdClass)#3098 (1) { ["SUM(wp_wpdatatable_1.payback)"]=> string(6) "183320" } }
So basically im trying to echo that 183320 number
Any guidance would be appreciated.
Thanks
|
You have to use the correct syntax `$wpdb->get_results( $query, $type_of_result);`
check this out here
**EDIT FOR EXPLAINATION:**
$users = $wpdb->get_results( "SELECT SUM(wp_wpdatatable_1.payback) as sumed FROM wp_wpdatatable_1", ARRAY_A);
The `array_a` will retur associative array while by default it returns as object that cause problem
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 6,
"tags": "php, wordpress, code snippets"
}
|
Media Queries for responsive typography
I'm trying to find a way to make my typography responsive. My code will follow. Whenever I refresh in dev tools this doesn't seem to have the desired result. How can I get a good result to have text displayed well on phones, tablets and laptop/desktops?
@media only screen and (min-width: 320px)
{
html {line-height: 1.25em, font-size: 16px;}
h1{line-height: 1.25em, font-size:32px;}
h2{line-height: 1.15384em, font-size:26px;}
h3{line-height: 1.136363em, font-size:22px;}
h4{line-height: 1.111111em, font-size:18px;}
}
|
I use `rem` instead of `em` On my projects. The difference between them is that `rem` is looking always to the root of the document, in this case `html`.
Then on my css i have:
html {
font-size: 1rem;
@media (min-width: 320px) {
font-size: 1.2rem;
}
@media (min-width: 760px) {
font-size: 1.5rem;
}
}
That way all the `font-size` inside `<html>` will change in the right way.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "html, css, responsive design"
}
|
Extracting change in polygons in QGIS
I have 2 shapefiles with interlocking polygons (sadly not with any unique common denominator like fid), one with moved borders. I want to extract the changes made in one of the shapefiles (see picture for clarity) and wondered if that is somehow possible in QGIS

 or overlay_contains('before'))=0`
When used with rule-based styling, this is what you will get:
 weaving for .net?
I want to do trace logging in a program by weaving in proxies in the IL. What are some current frameworks that are good for this?
(Most of the ones I've Googled are either old or don't have documentation, that is why I ask.
|
The most common thing I've come across for doing this type of thing in .Net is PostSharp. It has been around for a while and is well-known. It has a specific example for how to inject logging on its website.
|
stackexchange-stackoverflow
|
{
"answer_score": 11,
"question_score": 4,
"tags": "c#, .net, aop"
}
|
Equivalent of gtk.window_set_default_icon in gtk3
I am trying to convert a python2 pyGTK program (Comix) to GTK3 python3 program.
I am not really familiar with GTK also for what does this mean about my understanding of the original program's logic. Anyway I have found a point where this function appears:
pixbuf = GdkPixbuf.Pixbuf.new_from_file(os.path.join(icon_path, '16x16/comix.png'))
gtk.window_set_default_icon(pixbuf)
and it throws an error reporting:
> AttributeError: 'gi.repository.Gtk' object has no attribute 'window_set_default_icon'
I have tried to find the equivalent function in GTK3 but to no avail. The function that causes the problem is the latter one (`gtk.window_set_default_icon()`).
So, how can I write this snippet in GTK3 in python3?
|
I think you misunderstand the function call. It is actually the window you call the function on. Example:
window = Gtk.Window()
window.set_default_icon(pixbuf)
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 2,
"tags": "python 3.x, gtk3"
}
|
updating properties of a class with dynamic references
Sorry for what is probably a very basic question. I have a vb.net class with properties defined as follows:
Private m_Property1 As String
Public Property Property1() As String
Get
Return m_Property1
End Get
Set(ByVal value As String)
If IsNothing(value) Then
m_Property1 = String.Empty
Else
m_Property1 = value
End If
End Set
End Property
I can then set the values as follows:
classname.Property1 = "myvalue"
How do I set the value of a property that is defined dynmically eg
Dim strPropertyName As String = "Property1"
Hope that makes sense.
Thanks, Josh
|
You would use reflection
Dim strPropertyName as string = "Property1"
Dim pi As PropertyInfo = myClass.GetType().GetProperty(strPropertyName)
pi.SetValue(myClass.GetType(), "some string", Nothing)
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "asp.net, vb.net, properties, class"
}
|
stop creating certain cases email to case
we use email-to-case but a lot of unwanted cases are been created, we want to know what is the best way to stop cases getting created when we receive emails from certain email addresses.
we don't use 'Accept email from' feature in email-to case settings.
we don't have access to outlook exchange server to create any filters.
|
This kind of the scenario can be handled using validation rule.
When email-to-case occurs, you can capture `Web Email Address` and based on this create a validation rule to throw some dummy error message.
This error message is consumed internally and it doesn't go to Admin or that user's emailId as an email.
_I have used this approach in my project and it served my purpose._
|
stackexchange-salesforce
|
{
"answer_score": 2,
"question_score": 4,
"tags": "email2case"
}
|
Is there any loss in performance converting a 'where' clause to a lambda?
Is there any different in performance for the following 2 queries. I'm just wondering what is the better of the two:
var res1 = (from a in _ctx.DataContext.Actions
join e in _ctx.DataContext.Events on a.EventId equals e.EventId
select a).Single(a => a.ActionId == actionId);
or
var res2 = (from a in _ctx.DataContext.Actions
join e in _ctx.DataContext.Events on a.EventId equals e.EventId
where a.ActionId == actionId
select a).Single();
|
There should not be any performance difference that is a result of the syntax used. The query syntax is just eye candy that gets converted to the same underlying code. The difference between the two is really just
_ctx.DataContext.Actions
.Join(_ctx.DataContext.Events, blah, blah, blah)
.Single(a=>a.ActionId == actionId);
vs.
_ctx.DataContext.Actions
.Join(_ctx.DataContext.Events, blah, blah, blah)
.Where(a=>a.ActionId == actionId)
.Single();
If there's a performance difference, I'd be very surprised. The only way to really tell is to run some tests. I personally prefer your second method or my first; as I do not like mixing query syntax with imperative syntax.
|
stackexchange-codereview
|
{
"answer_score": 6,
"question_score": 4,
"tags": "c#, .net, linq"
}
|
Getting return value from oracle function using SimpleJdbcCall
I have Oracle function defined as:
function get_user_by_term (inUserTerm number) return number;
Now I wan to call this function using Spring SimpleJdbCCall but not sure how I can read return value since I don't have out param in function. I can't change the Oracle function code.
Code I have so far in Java is:
SimpleJdbcCall simpleJdbcCall = new SimpleJdbcCall(dataSource)
.withSchemaName("SCHMA").withCatalogName("PKG_USER")
.withProcedureName("get_user_by_term");
Map<String, Object> inParamMap = new HashMap<String, Object>();
inParamMap.put("inUserTerm ", userTermId );
SqlParameterSource in = new MapSqlParameterSource(inParamMap);
simpleJdbcCall.execute(in);
|
After research I found following:
1. Instead of `withProcedureName()` method `withFunctionName()` method should be used.
2. Instead of `execute()` method use `executeFunction()` with return type parameter.
So complete code be like
SimpleJdbcCall simpleJdbcCall = new SimpleJdbcCall(dataSource)
.withSchemaName("SCHMA").withCatalogName("PKG_USER")
.withFunctionName("get_user_by_term");
Map<String, Object> inParamMap = new HashMap<String, Object>();
inParamMap.put("inUserTerm ", userTermId );
SqlParameterSource in = new MapSqlParameterSource(inParamMap);
Long userId = simpleJdbcCall.executeFunction(BigDecimal.class, in).longValue();
Hope this will help others too.
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 2,
"tags": "java, spring, oracle"
}
|
Can candlelight be in plural contrarily to light?
Can candlelight be in plural contrarily to light? I am wondering if candlelight can be plural when there is many candles contrarily to light, which is an uncountable word. What's the consensus on this?
|
### Not really, no.
In general, "candlelight" is an uncountable noun, just like "light" is. If you're reading a book by candlelight, it doesn't matter how many candles are generating the light.
However, there is the unit of measurement called "candelas" which measures the brightness of light (in general), and which is approximately equal to the brightness of a single candle's light. There's also the obsolete unit of luminous intensity called "candlepower" (plural form also being "candlepower", as in "this flashlight has a brightness of 50 candlepower").
|
stackexchange-ell
|
{
"answer_score": 20,
"question_score": 13,
"tags": "plural forms"
}
|
SQL error when using select into where not exists query
I'm trying to insert a table into another table,
insert into list2([PHONE])
select [column 0] + [column 1] as PHONE
from [list1]
where not exists (select * from list2
where list2.phone = [list1].phone)
but I'm getting an error:
` Msg 207, Level 16, State 3, Line 1 Invalid column name 'phone'. `
On `list2`, there are 2 columns, `phone` and `area code`. `phone` has the full phone number and `area code` has the area code.
On `list1`, there are also 2 columns, `column 0` which has the area code and `column 1` which is the first 6 digits of the phone number.
What am I doing wrong?
|
You're not allowed to reference column aliases you construct in the `SELECT` list from the `WHERE` clause:
insert into list2([PHONE])
select [column 0] + [column 1] as PHONE
from [list1]
where not exists (select * from list2
where list2.phone = [list1].[column 0] + [list1].[column 1])
Alternatively, you could place the construction of the `phone` column into a subquery within the `FROM` clause:
insert into list2([PHONE])
select PHONE
from (select [column 0] + [column 1] as PHONE from [list1]) l1
where not exists (select * from list2
where list2.phone = l1.phone)
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 2,
"tags": "sql server, select, insert, where clause"
}
|
How to prevent delete query in SQL
I have created a database through Entity Framework Code First Approach and My application is ready and running live . The problem is that I did not turned "False" on Cascade Delete at the time of creating database. Now if I delete any record from one table that is referenced with another table through foreign so all the record containing foreign key of deleted row is deleted from another table . Practically demonstration :
Let say I have a Table called Passenger:
ID Name CategoryID
1 ABC 1
CategoryID here is a foreign key
Here is the category Table
ID Name
1 Gold
Let say I run my query on category table
delete from Category where ID = 1
Now all the record from my Passenger Table is deleted . I want to restrict it. Is it Possible through SQL now ?
|
I suppose This is what you are looking for :
alter TRIGGER customers_del_prevent
ON dbo.customers
INSTEAD OF DELETE
AS
BEGIN
insert into dbo.log
values ('DELETE')
RAISERROR ('Deletions not allowed from this table (source = instead of)', 16, 1)
END
Hope this helps you. :)
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "sql, entity framework"
}
|
Is separate SharedAccessFilePolicy for each file is ok?
I am creating a time bound SAS for each requested file. To do that I am creating a new `SharedAccessFilePolicy` object as followings:
SharedAccessFilePolicy sasConstraints = new SharedAccessFilePolicy();
sasConstraints.SharedAccessExpiryTime = expirey;
sasConstraints.Permissions = SharedAccessFilePermissions.Read;
string sasBlobToken = file.GetSharedAccessSignature(sasConstraints);
SharedAccessFilePolicy sharedPolicy = new SharedAccessFilePolicy()
{
SharedAccessExpiryTime = expirey,
Permissions = SharedAccessFilePermissions.Read
};
**Question1:** Is it ok to create a new `SharedAccessFilePolicy` for each requested file?
**Question2:** Do we need to clean-up the `SharedAccessFilePolicy` objects that we have created or those would be destroyed automatically?
|
It's OK to create a new `SharedAccessFilePolicy` for each requested file like your code above, since they're all client-side operations actually. No server request happens in your code above.
You don't need to clean up `SharedAccessFilePolicy` objects above, since it's just a temporary variable to define the SAS access policy before generation.
Note that `SharedAccessFilePolicy` will be saved on server side only when you're using Stored Access Policies, but you're not using that feature in your code above.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "azure storage, azure files, azure sas"
}
|
thin slow in development when not using localhost
I switched to using thin in local development instead of webrick.
When I access `localhost:3000` it returns the page almost instantly just like webrick
But when I access `myapp.local:3000` the browser spins for 20 seconds or so on each request before rendering the page. I'm not sure what it's doing during that time - the rails log shows the page being generated almost instantly - it almost seems like the browser is doing name resolution during that time or something else.
In my `/etc/hosts` i have
`127.0.0.1 myapp.local`
In webrick there was no difference between accessing `myapp.local:3000` and `localhost:3000`.
But in thin there is the large difference mentioned above. Any theories? Much appreciated!
|
Look for the file /usr/lib/ruby/VERSION_OF_RUBY/webrick/config.rb and edit it. Replace/insert the following line as a new key of the General hash.
`:DoNotReverseLookup => true`
Restart webrick.
Otherwise try running sudo service avahi-daemon stop
See Webrick is very slow to respond. How to speed it up? for more details
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "ruby on rails, thin, webrick"
}
|
Licensing issue for RSA and Rijndael algorithms
I'm using .Net to build a commercial application, i.e. a secure chat application. This application is using RSA and Rijndael algorithms.
Do we need licenses for using RSA and Rijndael algorithms for commercial product?
|
No, you don't need any licenses for neither of them.
Patents for RSA have expired on September 21, 2000. Even before that, it was also released as public domain.
Rijndael was submitted to NIST as Federal Information Processing Standard for AES, and is officially declared by authors to be patent free.
|
stackexchange-softwareengineering
|
{
"answer_score": 10,
"question_score": 6,
"tags": "licensing, software patent, encryption, commercial"
}
|
Swagger UI hide AspNetCore.Mvc.ProblemDetails schema .net 5,6 and 7
How to hide `ProblemDetails` Schema (see bellow) in .net 5,6 and 7.

{
services.AddControllers().ConfigureApiBehaviorOptions(x => { x.SuppressMapClientErrors = true; });
...
}
|
stackexchange-stackoverflow
|
{
"answer_score": 8,
"question_score": 2,
"tags": "c#, asp.net, swagger, .net 5"
}
|
htaccess RewriteRule redirect a url containing +
I want to redirect a url such as `www.example.com/new+uploads` to another page using `htaccess`
What I have tried is:
RewriteRule ^new%2Buploads$ /index.php?iid=5
and
RewriteRule ^new+uploads$ /index.php?iid=5
neither of these work, if i remove the + sign, the rewrite works fine, i've searched multiple threads on here and google and I cant find anything explaining it!
|
RewriteRule ^new\+uploads$ /index.php?iid=5
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": ".htaccess, mod rewrite, uri"
}
|
Laravel 5 [PDOException] SQLSTATE[42000]: Syntax error or access violation:
> ** [PDOException] SQLSTATE[42000]: Syntax error or access violation: 1166 Incorrect column na me 'INTERESTED IN INTERNSHIP JOB '**
>
> **in this column INTERESTED IN INTERNSHIP JOB is radio button **
>
> **in this column SEX , INTERESTED IN INTERNSHIP JOB , AND ABOVE 18 ARE RADIO BUTTON **
public function up()
{
Schema::create('students',function(Blueprint $table)
{
$table-> increments('id');
$table-> char('FIRST NAME',50 );
$table-> char('LAST NAME',50 );
$table-> string('EMAIL',50 );
$table-> string('SEX',50);
$table-> string('INTERESTED IN INTERNSHIP JOB ',50);
$table-> text('SKILLS');
$table-> string('above18',50);
});
}
Please help me resolve the aforementioned error, as I am stuck.
|
One advice though never use uppercase for column names otherwise there can cross platform issues between windows(case-insensitive) and Linux(Case-sensitive)
<
**UPDATE**
change `'INTERESTED IN INTERNSHIP JOB '` to `'INTERESTED IN INTERNSHIP JOB'`
There is an additional space at the end of column name and `'`
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 2,
"tags": "php, mysql, laravel, laravel 4, laravel 5"
}
|
How can we provide Jackson annotations for java 17 record class
How can we create add field level annotations for java 17 record class?
record Rectangle(double length, double width) { }
|
yes we can use field level annotations (annotation with `@Target(ElementType.FIELD)` in the defination.
@JsonInclude(Include.NON_NULL)
record Rectangle(
@JsonProperty("lengthAlias") double length,
double width) { }
|
stackexchange-stackoverflow
|
{
"answer_score": 9,
"question_score": 6,
"tags": "java, json, java 17"
}
|
How can I use regex to strip the email address from a mailto tag?
I need to parse the email address from a `mailto` tag. I am looking for a way to do this via RegEx in C#.
### Example input:
<mailto:[email protected]>
### Example output:
[email protected]
|
In general, it's a very bad idea to use regular expressions for HTML parsing. Instead, take a look at the Html Agility Pack. For the specific input you provided, you may use:
`(?<=\<mailto:).*(?=\>)`
Here's a code sample:
var emailTag = "<mailto:[email protected]>";
var emailValue = Regex.Match(emailTag, @"(?<=\<mailto:).*(?=\>)").Value;
Console.WriteLine(emailValue);
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": -4,
"tags": "c#, asp.net, regex"
}
|
Do I need an api key to get last known location in Android with Google Play Services?
I just recently started learning Android and am working on small projects to learn the essentials I need for to work on a larger project I have coming up. I need to get the users last know location. I went through this tutorial, and it wouldn't connect to play services. Do I need an api key to get the last known location? And also what is the easiest way to implement location awareness in Android?
|
You need not to give any `API` key to fetch last known Location. `API key` is needed when integrating `Google Maps` in Android app. Android Location API using Google Play Services
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": -1,
"tags": "android, location, google play services"
}
|
BitmapDrawable() method deprecated
What can I use in replace of BitmapDrawable(), which is deprecated. I have the following code. I just want to clear the background of this view.
popupMessage = new PopupWindow(view, LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT);
popupMessage.setContentView(view);
// Clear the default translucent background
popupMessage.setBackgroundDrawable(new BitmapDrawable());
Thanks in advance!
|
`popupMessage.setBackgroundDrawable(null)` will clear the background.
From the documentation:
> Change the background drawable for this popup window. The background can be set to null.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "android, bitmap, background"
}
|
Printer friendly web pages question
How do I make printer friendly web page using css and php that strips out style attributes as well?
|
Printer friendly should be handled purely with a print media stylesheet.
You should avoid having style attributes in the first place. If you, for some reason, can't eliminate them then you can override them in the CSS with the sledgehammer of !important (unless they use !important themselves).
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "php, css"
}
|
Trying to figure out transforming on OGL ES 2.0 for Android
I am still learning the basics of OpenGL, but I am having trouble doing transformations.
I have a quad I want to move around, and apply a projection matrix onto. Is their a certain order the matrices must be multiplied? Does it matter if a matrix is on the left or right side of a multiplication (like with a matrix and a vector) with two matrices?
Doing identity matrix -> transformation matrix works, however if I try to multiply that by a projection matrix, the quad disappears.
|
while doing transformations the order of transformations sure does effect the final rendering. For example.. if you try to scale an object and do translate transformation on it the final rendering will be different when you reverese the same order.
It worked for you when you did the transformation with an Identity matrix 'coz when you do any Transformation using an Identity there will not be any change.
While do Transformation the order of Matrices is also important, change the order the final rendering changes.
If it helps please go through "OpenGL Superbible 5th editio". This will give you a fair knowledge on how transformation happen.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "android, opengl es 2.0"
}
|
Mascarar uma div com css
Em um site que estou desenvolvendo o topo (onde estão os menus) tem o fundo transparente e é fixo. Ou seja, o site roda por trás desse topo e o topo fica sempre fixo.
Mas como ele é transparante... o site acaba ficando atras do topo quando dou o scroll.
Existe alguma forma de deixar o site mascarado? Ou seja... onde esta o menu ele não aparece, veja a imagem para explica melhor:
.ready(function(){ $(document).scroll(function(){ if($(this).scrollTop() > 50){ //quando rolar mais de 50px muda a cor $('elemento_menu').css('color','blue'); //escolhe a cor que melhor contrastar } }); });`
|
stackexchange-pt_stackoverflow
|
{
"answer_score": 1,
"question_score": 2,
"tags": "css, html5"
}
|
jQuery: Creating multiple event listeners at once?
$( document ).on({
"mousewheel": scrollHandler,
"DOMMouseScroll": ("onmousewheel" in document) ? null : scrollHandler, // Firefox
"keydown": keyHandler,
"mousedown": function( e ) {
if( e.button === 1 ) {
e.preventDefault();
return false;
}
}
});
I know this code is listening for a scroll down, but I am really sure how it works. According to the documentation for on() the function accepts the arguments `.on( events [, selector ] [, data ], handler )`. However, in the example code I provided there is a hash being into the on() method. Which parameter is that supposed to be?
Is this code essentially creating multiple eventListeners at once or is there something else going on I do not understand?
|
In the format of the jQuery `.on()` method being illustrated the first parameter is a plain javascript object with the keys of the object being "event names" and their values being functions that are executed if an event of that type occurs. In your example, if a `mousewheel` event is detected, a function called `scrollHandler` will be called. If a `keydown` event is detected, a function called `keyHandler` will be called (etc etc).
This technique is merely a shortcut for having multiple `.on()` statements one after the other.
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "jquery"
}
|
How to lock scroll for all page?
I'm creating image slider, it's contains in big, 100% x 100%, absolute positioning popup div. And I need to block body scroll when slider is active. I tried overflow: hidden for body tag, in js - and it's not working, thereon I tried it in style.css, result was the same.
body {
position: relative;
overflow: hidden;
display: block;
}
So how to lock scroll for all page by css resources?
|
Use fixed positioning on your image
#myImage
{
position:fixed;
width:100%;
height:100%;
top:0px;
left:0px;
}
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 1,
"tags": "html, css"
}
|
How long before an app review shows up in iTunes Connect?
I've had a number of users review my app, but I'm not seeing those reviews in iTunes Connect. How long does it usually take for reviews to show up?
Also, the regions dropdown only contains USA. How do I see reviews from other regions?
|
I've found reviews generally show up within 24-48 hours. The drop down will only show countries that you have reviews for. So if only the US is showing then these are the only reviews that iTunes Connect knows about.
|
stackexchange-stackoverflow
|
{
"answer_score": 6,
"question_score": 6,
"tags": "ios, iphone, app store, app store connect"
}
|
Imports in distributable python scripts
I have a python project pypypy with 2 files: `__main__.py` and `foo.py`. In `__main__.py` I simply do import via `import foo`. It all works fine.
Now, I want to distribute it with pypi. After installing my module I'm execution it with `python -m pypypy`. When I do that, the import statement doesn't work anymore. However `import pypypy.foo` does the job.
Should I change all my imports before distribution or there is a better way?
|
Using absolute imports is strongly suggested as they work consistently across different python versions. Check this answer. In your case you should prefer using `import pypypy.foo`.
The reason it works in your dev environment might be because of PYTHONPATH manipulation. For example Pycharm automatically sets _Add content and source roots to PYTHONPATH_. Also when you run python it automatically adds current working directory to PYTHONPATH.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "python, python module, pypi"
}
|
Have root access, still permission denied upon using cat command
I was trying to install SSL certificate (GoDaddy), following their instructions for nginx on Centos. The zip that I downloaded from GoDaddy contains 3 files - A Primary cert, an intermediate cert and a PEM file.
I have root access for my Ubuntu VPS.
But when I use
sudo cat f84e19a2f44c6386.crt gd_bundle-g2-g1.crt >> coolexample.crt
I get
bash: coolexample.crt: Permission denied.
|
Try logging in as superuser with
sudo -s
and then try your command again without sudo in the beginning.
The reason why it doesn't work is because the redirection is done by the shell and not by cat. See this answer for more information: <
|
stackexchange-askubuntu
|
{
"answer_score": 3,
"question_score": 3,
"tags": "command line, bash, permissions, sudo"
}
|
HTML Email Background Color
I created a HTML mail and edit css. It's good now. But, i want give background color my window.
My code:
<body bgcolor="#f2f2f2" leftmargin="0" topmargin="0" marginwidth="0" marginheight="0">
But don't work. When i a table, my structure crash.
<table bgcolor="#f2f2f2">
--
My Email Structure
**
</table>
How can i fix it?
Tested browsers:
Firefox, Safari, Chrome.
Tested client:
Gmail
|
<table style="background-color: #f2f2f2;">
</table>
The bgcolor attribute of is **deprecated** in HTML 4.01.
A deprecated element or attribute is one that has been outdated.
Deprecated elements may become obsolete in the future, but browsers should continue to support deprecated elements for backward compatibility.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": -2,
"tags": "html, css, background, html email"
}
|
How to call FreeMarker directive from ftl template directly?
**Short Question** : Is it possible to call FreeMarker directive `FormatDirective.java` that implements `TemplateDirectiveModel` directly from my ftl like this:
<#assign formattedPhoneNumber = "com.myapp.utils.FormatDirective"?new(phoneNumber)>
**Detailed Question** : It's Spring MVC web app that has its views written with FreeMarker, there are no Java configs at all and I have only `FreeMarkerConfigurer` and `FreeMarkerViewResolver` beans properly defined and configured in `root-context.xml`.
I want to avoid Java configurations (like adding template to model or shared variables). And what is the proper way -in general- to get Java directives working ? I don't seem to find thorough tutorial or example.
Thanks
|
You could collect your frequently used directives and functions into something like `my-commons.ftl`:
<#assign format = "com.myapp.utils.FormatDirective"?new()>
...
then in your templates:
<#import "my-commons.ftl" as my>
...
<@my.format value=phoneNumber />
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "java, spring, model view controller, freemarker"
}
|
Does a timebased workflow remain in queue after the criteria has become false?
I do have a time based workflow set on leads and when we try to convert them it throws an error
> RECORD_IN_USE_BY_WORKFLOW, Unable to convert lead that is in use by workflow:
To overcome this i will be making an update on the record to make the entry criteria to fail in workflow.
My question is that when the time based workflow is put in a queue, will it be removed from queue if the criteria becomes false.
In my workflow i have the `Evaluation Criteria`
Evaluate the rule when a record is created, and any time it’s edited to subsequently meet criteria
|
Short answer, yes, if the object is in a time-based queue, and its criteria changes to no longer fire that rule, it will be removed.
Longer answer, ~~this article~~ details the common approaches to the problem you're seeing and may give you some ideas for other solutions to the problem.
|
stackexchange-salesforce
|
{
"answer_score": 5,
"question_score": 3,
"tags": "leads, exception, lead conversion, time dependent workflow"
}
|
Is there any tool/plugin for QGIS to easily select feature and edit attributes
I need to select polygons and change some attributes in a shapefile. I'm using Quantum GIS - I select the polygon, open attribute table and edit the attributes I want. I know there must be an easier and faster way to do this. I was thinking in some tool which when the feature is selectd pop-up a form with the respective attributes and lets you edit them.
|
The "Identify" tool will let you do this. There's a setting under Settings > Options > Map Tools tab > Open Feature Form, if a single feature is identified. Then just make sure your layer is editable, and click the feature with the identify tool.
|
stackexchange-gis
|
{
"answer_score": 13,
"question_score": 8,
"tags": "qgis, editing"
}
|
how to get "gen_server" 's local name?
It is possible to save the local name in gen_server's state, but I think since it is already stored in the gen_server, it is possible to fetch it.
How to do it?
|
If you start gen_server with command like this:
{ok,Pid} = gen_server:start_link({local, localName}, Module, Args, Options]).
you can obtain localName by command:
process_info(Pid, registered_name).
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "erlang"
}
|
How to implement a real time iOS7 blur effect in the UITableViewCell's background
I want the UITableViewCell's background to have an iOS7 blur effect. It's dynamic, means, while the cell is scrolling, its blurred background should change depend on the color below.
I found some relative topics.
iPhone SDK - Frosted Glass (iOS 7 Blur) Effect. It introduce GPUImage. It about still image, I didn't figure out how to make a dynamic one.
iOS 7 dynamic blur effect like in Control Center. It use UIToolbar as the background of cell, taking advantage of system built-in blur effect. It works great, but just the transparency is a little low. I have adjusted the alpha of tool bar, but it doesn't ideal.
|
Just like you said, there is possibility to use UIToolbar to get real-time blur. Here is a little class to get desired modification of appearance:
<
|
stackexchange-stackoverflow
|
{
"answer_score": 10,
"question_score": 2,
"tags": "ios, ios7"
}
|
ios 6 : background imageview in iPhone 5
In my iphone application I am using a background image bg.png (for retina size [email protected]). I updated xcode to 4.5. Now I need to arrange the UI for fit into iPhone 5 - 4 inch display. Since the frame height will become 568, I need to fix my background also having a height 568. I added a image named [email protected] in my app. But Iam not getting this image for iPhone 6 simulator in xcode. Is there any way to get this image? or how can I achieve this?
|
Try this dynamic code....
self.view.backgroundColor = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"bg.png"]];
or
This creates a memory leak. Either change initWithPatternImage to colorWithPatternImage, or assign your UIColor object to a variable and properly release it:
UIColor *color = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"bg.png"]];
self.view.backgroundColor = color;
[color release];
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 2,
"tags": "iphone, ios, uiimageview"
}
|
What is required for redirect_to to work?
I believe this is a super simple question for Ruby developers, although I am an expert in Java, but today is my first day in Ruby.
My code:
url="
redirect_to url
Error:
undefined method `redirect_to' for main:Object (NoMethodError)
Now, an educational guess is that I need to "require [some magical library]", but I search the web and stackoverflow:
"ruby redirect_to require" "ruby redirect_to doc" "ruby redirect_to lib" "ruby which library is redirect_to in" "ruby example code redirect_to" "ruby tutorial redirect_to" "open sesame"
and heck, nothing obvious which tells me this simple step to make a method call works. And it forced me to write this whole thing here.
Could you kindly give me a full piece of example code which can have the redirect_to method behave? Or better yet, tells me what keywords I should search for this kind of similar questions.
|
You can't just require something to get this because the very idea of a redirect doesn't make sense outside an "action". Only an action processes an HTTP request and sends a response*, and a redirect is a type of response. So as others have said, call this in an action and it will work. Call it anywhere else and it won't be defined because it is the action/controller system that defines it.
Since you come from Java, a reasonable analog would be to ask what you need to import to be able to call toUpperCase from a subclass of IOStream. !?
(* this is a bit of a lie, but true enough. There are a couple of non-action ways to respond to a request in rails, but `redirect_to` is part of `ActionController`.)
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "ruby on rails, ruby"
}
|
Set Netbeans Platform Application language
When I add
default_options="--branding ersyp -J-Xms24m -J-Xmx64m J-Duser.language=tr-J-Duser.region=TR"
code to my `appName.conf` file the NetBeans platform application language should be Turkish but when I run my application from NetBeans this file gets overwritten.
How can I prevent that from happening?
|
Add
run.args.extra=--locale tr
in the `project.properties` file of your Netbeans application (this file is in the `Important Files` folder of your project's module suite).
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 2,
"tags": "java, netbeans, bundle, netbeans platform"
}
|
Process Silverfast color raw scans in Lightroom
In SilverFast there are two main scan modes. One called raw which export a DNG file and one TIFF. In the DNG format I need to invert as part of the post process in Lightroom. Or I can go for TIFF format and let SilverFast do the 'magic'. I would prefer scanning in DNG format but i am not sure how I can best invert a color negative. Any advise?
|
Your question has two parts and each part has already be answered (at least partially). With a DNG image out of the scanner, you will have to invert the color. Then, regardless of the image format (DNG or TIFF), you will maybe observe a color cast.
**How to invert color in Lightroom**
You can have a look at this post : Is there any good method to invert a negative image (duplicated with a digital camera) in Lightroom?
Using Lightroom, go the Tone Curve adjustement section. Make sure **Linear** is selected (Point Curve) and that you are using the **Channel RGB**. Now invert the curve by moving the two extremes points.
!Original Picture
!Inverted Picture
**How to adjust the color**
Have a look at this question : I have scanned a film negative - how do I adjust the color using software?
If your inverted image has a color cast, the easiest way to correct it is by setting a neutral (gray) spot in the White Balance Selector.
|
stackexchange-photo
|
{
"answer_score": 0,
"question_score": 0,
"tags": "lightroom, scanning, presets"
}
|
Convert date time to unix_timestamp Scala
I need to get the minimum value from the Spark data frame and transform it. Currently, I just get this value and transform it using DateTime, however, I need it in the unix_timestamp format as the result. So how can I convert DateTime to unix_timestamp either using Scala functions or Spark functions?
Here is my current code which for now returns DateTime:
val minHour = new DateTime(df.agg(min($"event_ts"))
.as[Timestamp].collect().head))
.minusDays(5)
.withTimeAtStartOfDay())
I tried using Spark functions as well but I was not able to switch timestamp to start time of day (which can be achieved using DateTime withTimeAtStartOfDay function):
val minHour = new DateTime(df.agg(min($"event_ts").alias("min_ts"))
.select(unix_timestamp(date_sub($"min_ts", 5)))
.as[Long].collect().head)
|
`date_sub` will cast your timestamp to a date, so the time will be automatically shifted to the start of day.
df.show
+-------------------+----------+
| event_ts|event_hour|
+-------------------+----------+
|2017-05-01 00:22:01|1493598121|
|2017-05-01 00:22:08|1493598128|
|2017-05-01 00:22:01|1493598121|
|2017-05-01 00:22:06|1493598126|
+-------------------+----------+
df.agg(
min($"event_ts").alias("min_ts")
).select(
unix_timestamp(date_sub($"min_ts", 5)).alias("min_ts_unix")
).withColumn(
"min_ts", $"min_ts_unix".cast("timestamp")
).show
+-----------+-------------------+
|min_ts_unix| min_ts|
+-----------+-------------------+
| 1493164800|2017-04-26 00:00:00|
+-----------+-------------------+
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "scala, apache spark, apache spark sql"
}
|
picking and writing out some fractions of list with for-loop
There is a dataset as a `csv-file` which contains some tabular of data.
I want to pick out the fractions with the same number.
For example i have one list
a = [1,1,2,2,3,3,4,4,4,5,5,5,5,6]
and i want a loop, which writes `text-files` with the same numbers
file_1.txt contains `1,1`
file_2.txt contains `2,2`
file_3.txt contains `3,3`
file_4.txt contains `4,4,4`
file_5.txt contains `5,5,5,5`
file_6.txt contains `6`
I still have no real result, because so far everything is wrong.
|
A much cleaner approach would be to use `itertools.groupby` and `str.join`:
from itertools import groupby
for num, group in groupby(a):
filename = "file_%d.txt"%num
with open(filename, 'w') as f:
f.write(",".join(map(str, group)) + "\n")
Another important point is that you should always use the `with` statement when reading and writing to files.
* * *
Using `groupby` assumes that the data is already sorted. Another approach would be to use `collections.Counter`:
from collections import Counter
for num, count in Counter(a).items():
filename = "file_%d.txt"%num
with open(filename, 'w') as f:
f.write(",".join([str(num)]*count) + "\n")
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "python, loops, csv, for loop, writefile"
}
|
How to Execute Print Statement on Specific Timestamp in Python
I Just Want to Execute Print Statement in The Following Sequence
Here is My Code
Let's Assume The Following Time Stamp in Which Print Statement Should be Executed
t0 = 2022-01-25 12:00:00:000
t1 = 2022-01-25 12:00:00:050
t2 = 2022-01-25 12:00:00:100
t3 = 2022-01-25 12:00:00:150
t4 = 2022-01-25 12:00:00:200
With The Gap of 50 Milliseconds
Here is The Python Code
loop_start = 0
loop_end = 10
while loop_start < loop_end:
print('Hello World')
loop_start += (1/20)
So I Want to Print on Every 50 Milliseconds But According to The System Time Don't Want To Use Delay Here.
It will Only Print According to The Timestamp Mentioned Above
Please Help Me To Resolve This
Thank You.!
|
I've Solved This Through While Loop
loop_start = 0
loop_end = 10
start_time = (datetime.datetime.now(timezone.utc)).timestamp()
while loop_start < loop_end:
start_time += 0.05
while (datetime.datetime.now(timezone.utc)).timestamp() < start_time:
time.sleep(0.001)
print('Hello World')
loop_start += (1/20)
So Here It will Check That Current Time is Equal To The Time Which is Required If Yes Then Print Otherwise Wait Till The Required Time
Still There is a Minor Delay In This But Acceptable For Me It Resolved My Problem
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "python, datetime, timestamp"
}
|
Insert current date in datetime format mySQL
I'm having problems getting the date inserted properly into my database.
$date = date('m/d/Y h:i:s', time());
I use this format, and, it echoes out correctly, however, when, I insert
mysql_query("INSERT INTO table
(dateposted)
VALUES ('$date')");
it doesn't appear to work successfully, and, the time remains 00:00:00 If you could find the solution that would be great, thanks.
|
If you're looking to store the current time just use MYSQL's functions.
mysql_query("INSERT INTO `table` (`dateposted`) VALUES (now())");
If you need to use PHP to do it, the format it `Y-m-d H:i:s` so try
$date = date('Y-m-d H:i:s');
mysql_query("INSERT INTO `table` (`dateposted`) VALUES ('$date')");
|
stackexchange-stackoverflow
|
{
"answer_score": 253,
"question_score": 110,
"tags": "php, mysql"
}
|
Can i store a cursor.fetchone() in a variable
Hell guys just jumped in to python and i'm having a hard time figuring this out
I have 2 queries . . **`query1`** and **`query2`** now how can i tell
**`row = cursor.fetchone()`** that i am refering to **`query1`** and not **`query2`**
cursor = conn.cursor()
query1 = cursor.execute("select * FROM spam")
query2 = cursor.execute("select * FROM eggs")
row = cursor.fetchone ()
thanks guys
|
Once you perform the second query, the results from the first are gone. (The return value of `execute` isn't useful.) The correct way to work with two queries simultaneously is to have two cursors:
cursor1 = conn.cursor()
cursor2 = conn.cursor()
cursor1.execute("select * FROM spam")
cursor2.execute("select * FROM eggs")
cursor1.fetchone() #first result from query 1
cursor2.fetchone() #first result from query 2
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "python"
}
|
C#: is bitvector32 more efficient than bool for flags?
A bool requires 8 bits to store a flag: true or false. Bitvector32 allows you to store 32 flags in 32 bits. So 32 bool flags would be 256 bits.
However...
Bitvector32 requires you to declare an integer mask for each bit you want to address. That mask is an integer, or 32 bits -- 32 masks times 32 bits + 32 bitvector32 bits = 1056 bits for 32 flags.
What's the point of bitvector32 if the bitmasks more than offset the efficient storage of flags?
|
If I have up to 32 flags I need to test all at the same time, a BitVector32 is much more efficient:
if (bv & 0X...) ...
will test for several flags being "on".
if ((bv & 0X...) == 0) ...
tests for all the specified flags being off.
If I have a billion flags, I would rather play div and mod 32 to find which bitvector to use -- as opposed to using a lot of RAM.
(Actually, I would probably use a long or longlong, and not bother with `BitVector`.)
OTOH, for just a few flags, I would probably use the 1-byte thingies. Wasteful of a few bytes, but faster.
And if I need yes/no/maybe, a single bit won't do. (Ditto for M/F/...)
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": -2,
"tags": "c#, performance, flags"
}
|
Store data into neo4j from eclipse
I have a `gml` file that I read it with java in eclipse and I want to know how to store the result of the code below in `neo4j`:
TinkerGraph graph = new TinkerGraph();
GMLReader gml= new GMLReader(graph);
gml.inputGraph("/home/salma/Desktop/celegansneural.gml");
|
You can import graphml and other formats from the neo4j shell with the help of the following: <
Then just open the shell and use the command:
import-graphml -it /home/salma/Desktop/celegansneural.gml
The -t option tells it to import the node labels as well.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 2,
"tags": "java, eclipse, neo4j, tinkerpop, graphml"
}
|
Will a PowerShell script developed for a Windows 7 run on Win Server 2008 R2?
I have developed a large PowerShell script that has been refined on a Windows 7 64bit box and now I intend to run it on a Windows server 2008 r2. Assuming the PowerShell versions are the same, will there be any major issues with syntax in-between Win 7 and WS 2008 R2?
The script checks a lot of WMI and registry keys like `GWmi Win32_NetworkLoginProfile` and `Get-Itemproperty -Path Registry::HKLM\Software\Microsoft\"Windows NT"\CurrentVersion\winlogon\`
Most PowerShell information is driven towards managing servers so I assume I will be safe, but I want to see if you all can help me learn some lessons before I start banging my head against the wall. Thanks
|
There are no syntax differences between PowerShell on Windows 7 and PowerShell on Windows Server 2008 R2. You may encounter differences in existing services, WMI classes, and registry keys, though.
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 2,
"tags": "powershell, windows 7, windows server 2008 r2"
}
|
Highest root, highest weight and highest short root
Are highest root and highest short root the same? Are there some example to show that the highest root and the highest short are not the same? Are there some example to show that the highest root and the highest short are the same?
Are there some example for the highest weight of a representation of an Lie algebra is (respectively, is not) the highest root? Many thanks.
|
In an irreducible root system with two root lengths, the highest root is long, hence distinct from the highest short root. For example, in the root system $B_2$, the highest root is $2\alpha+\beta$, whereas the highest short root is $\alpha+\beta$. Of course, if the root system is simply laced (all roots are of the same length) then the two notions coincide.
Regarding your last question, for every integral dominant weight $\lambda$ there exists an irreducible representation with $\lambda$ as its highest weight. In particular, the highest weight of a representation need not be a root at all.
|
stackexchange-math
|
{
"answer_score": 5,
"question_score": 2,
"tags": "representation theory, lie algebras"
}
|
Are there any damaging effects to leaving the Raspberry Pi on all the time
I have a Raspberry Pi B+ hooked up to my router and I leave it on all of the time, it rarely gets switched off. Does this cause any damaging effects to the Raspberry Pi?
|
Provided you have no heat issues (check with `/opt/vc/bin/vcgencmd measure_temp`) you can leave your rPi running for all eternity. That's the beauty of the device paired with a well-written OS like raspbian which does not (or hardly) suffer from memory leaks etc.
|
stackexchange-raspberrypi
|
{
"answer_score": 13,
"question_score": 10,
"tags": "hardware"
}
|
How does TTL of package changes?
Consider a following scheme:
Server(TTL=64) <--> RouterA(TTL=64) <--> RouterB(TTL=64) <--> Desktop(TTL=128)
The Desktop sends a package to the Server, this package on the netowrk card of desktop has ttl equal to 128. What would be TTL of the package when it will pass RouterB - 127, 64 or 63 ?
Is there any way to test it? I'm using Linux and run command `ping google.com -t 100`, but I recieve only TTL of response.
|
The ttl(time to live) value will depend of the initial value of your ttl field(that is depending of your operatins system).
Here you can find some common values:
<
If you are using windows(not 95 version)127 will be your result because it is just one jump has happens, the ttl value change(decrease) on the way that a packes passes by one router or some devices betwenn 2 networks. On that way, once the packet get into router b, and it forwarded to router A, on that moment the ttl value is dereceased by one.
|
stackexchange-networkengineering
|
{
"answer_score": 4,
"question_score": 2,
"tags": "ipv4, packet path"
}
|
PDF content inside XML response file
I receive XML file that includes PDF content:
<pdf>
<pdfContent>JVBERi0xLjQKJaqrrK0KNCAwIG9iago8PCAvV.......
How can I save the content into PDF file?
I'm using C# 4.0
|
That string value is the PDF in base64. If you convert the base64 to a byte array you can just write that byte array to disk.
Convert.FromBase64String
var buffer = Convert.FromBase64String(xmlStringValue);
File.WriteAllBytes(yourFileName, buffer);
|
stackexchange-stackoverflow
|
{
"answer_score": 9,
"question_score": 0,
"tags": "c#, xml, pdf"
}
|
How to check if my computer has a usb-c that can be used for display port
So i have an old screen that i would like to connecto to my new Windows 10 computer.
This screen is ONLY VGA. So i want to buy a usb-c to VGA adapter. However ive read online that you have to have a Display port alternative usb-c port in your computer to support it.
My question is how do i check if my usb-c ports supports it?
|
According to your own link, the Type-C connector
> port Supports USB 3.1 Gen 2, **DisplayPort 1.2** , Thunderbolt 3 and also enables you to connect to an external display using a display adapter.
However, the adapter of your selection doesn't need any Display Port, nor any Tunderbolt functionality - it is a plain USB 3.0 to VGA converter. You don't need DP support to run your adapter and VGA monitor.
But I would strongly advise you to throw away your old VGA screen, and just buy a normal modern LED monitor 22" or 27". Some are under $100 these days. And you won't need any adapter for this. You will save money and waste less power. And preserve your vision.
|
stackexchange-superuser
|
{
"answer_score": 3,
"question_score": 4,
"tags": "windows 10, usb, usb c"
}
|
Why is intensity related to number of photons?
I have been reading up on Doppler broadening and have found a number of sources (for example here and here) which seem to be taking the number of photons in the range $[\nu,\nu+d\nu]$ to be the same distribution (Gaussian) as the power spectrum at that point. I cannot see how this can be true, since surly to get power from number of photons you need to times by $\nu$ meaning they won't have the same distribution. Please can someone shed some light on this for me?
|
You are quite right that the the power in the range $\nu$ to $\nu + d\nu$ should be done by having a term something like $n(\nu)\;h\nu$.
However because the change in wavelength (frequency) is very small as shown in one of your links, FWHM = 0.024 nm for a central wavelength of 388.9 nm, the assumption is made that $h\nu \approx h \nu_o$, ie all the photons have approximately the same energy. Thus the intensity is proportional to the number of photons arriving per second.
|
stackexchange-physics
|
{
"answer_score": 1,
"question_score": 2,
"tags": "optics, statistical mechanics, spectroscopy"
}
|
How to check if a record exists in the SQL Server database C# winform?
My windows form application is about Book Store. I would like to display PO numbers in a ComboBox which didn't have create a Good Received Note.
This is the structure of this two tables.
PO Table-

{
DynamicConnection con = new DynamicConnection();
con.mysqlconnection();
con.sqlquery("select PO_No from TBL_PO");
con.dataread();
while (con.datareader.Read())
{
cmbpono.Items.Add((int)con.datareader["PO_NO"]);
}
}
|
I would say as follows :
Change
con.sqlquery("select PO_No from TBL_PO");
to
con.sqlquery("select PO_No from TBL_PO where PO_No not in (select PO_No from GRN)");
|
stackexchange-stackoverflow
|
{
"answer_score": 3,
"question_score": 1,
"tags": "c#, sql server, winforms"
}
|
find folders in a tree and create a list with their paths
I have big folder tree and I need to make a list with the path of every folder named "arc". The folder tree is something like:
./tree
--> ./A
----> ./one
------> ./arc
--> ./B
--> ./C
----> ./two
------> ./arc
--> ./D
--> ./E
----> ./three
--> ./F
----> ./four
------> ./arc
My final list should be [/tree/A/one/arc, /tree/C/two/arc, /tree/F/four/arc] (note that arc is always in the fourth level of the tree)
I've been trying with the os.walk function but haven't been successful. Any help will be very appreciated.
|
final_list = [os.path.join(root,dir) for
root,dirs,files in os.walk("path/to/tree") for
dir in dirs if dir=="arc"]
`os.walk(path)` returns a list of tuples, containing:
(the root directory for this recursion,
a listing of all subdirectories in that root,
a listing of all the files in that root)
So we're going through `os.walk` and looking at all the `dirs` tuples, pulling each one and checking to see if it's `"arc"`. If it is, it's combining the `root` (which is something like `'path/to/tree/A/One'` with the dir name (which should always be `'arc'`) using `os.path.join` (which puts the OS-specific path separator between each argument), and adding that to the list comp.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "python"
}
|
How to generate a unique key for an array?
I'd like to generate a unique identifier based on the content of an array. My initial approach was to simply do:
$key = md5(json_encode($array));
However, I'd like to be absolutely sure that the key is unique and there is a remote possibility that two distinct arrays can produce the same md5 hash. Current idea is to do:
$key = base64_encode(json_encode($array));
This is guaranteed to be unique but produces quite a long key. Can I use sha512 or does this type of hash also have the same potential for key collision as md5? Is there any way to generate a shorter key than the base64 method which is 100% guaranteed to be unique?
To be 100% clear, my question is: **How can I generate the shortest possible 100% unique identifier for a set of data?**
|
If you want a 100% guaranteed unique key to match your content, then the only way is to use the full length of your content. You can use the json_encoded string as-is, or you could run it through base64_encode() or bin2hex() or similar if you want a string that doesn't have any "special" characters. Any hash function like md5, sha1, sha256 etc obviously cannot be 100% unique - because they have a fixed length, and due to the < there must necessarily be non-unique results for input content that is larger than the hash.
In practice, md5 and sha1 collisions have now been published, but stronger hash functions exist where no collisions are known or expected for a long time, so you could also look into using a modern hash algorithm and be fairly safe that you will not have any duplicates.
|
stackexchange-stackoverflow
|
{
"answer_score": 7,
"question_score": 3,
"tags": "php, hash collision"
}
|
How do I plot different parts of a same function?
Let's say that I got a complex function $f$ of a real variable $x$, i.e. $f(x)$. Suppose that I want to plot the real part of $f$, i.e. $\Re(f(x))$.
My question is: should I enclose `Re[f[x]]` in the command `ComplexExpand`? Or does `Re[f[x]]` already give the real part of $f$?
|
You will get the same values and plots with `Re[f[x]]`, `ComplexExpand[Re[f[x]]]`, or `Re[ComplexExpand[f[x]]]`, with or without `Evaluate`. However, the timing varies:
$HistoryLength = 0;
Clear["Global`*"]
f[x_] := Cos[I^x] Sin[I^x]
Plot[Evaluate@Re@f@x, {x, -5, 5}] // RepeatedTiming
 location/directory for opening a file in SQL Server 2008? E.g. when I go to File menu, then Open, then choose File, it brings up a window with my last location. On the left, I have 3 shortcuts: Desktop, My Projects, and My Computer. In SQL Server 2005, you could (apparently) add your own location shortcuts in the registry (according to this thread: < This method does not appear to work for 2008.
Any ideas?
|
When using SQL Server 2008 you need to use 100 instead of 90 in the path.
\HKCU\Software\Microsoft\Microsoft SQL Server\100\Tools\Shell\Open Find\Places\UserDefinedPlaces
Add one key Place0. Add two string values in Place0, Name and Path.
!enter image description here
!enter image description here
|
stackexchange-stackoverflow
|
{
"answer_score": 8,
"question_score": 2,
"tags": "sql server, sql server 2008"
}
|
rails block scope
I want to count entries in this block.Because of ruby block variable scope,I don't handle with this code.Is there any way to fix this?
arr_showcase.each do |entry|
@entry = ContestEntry.find_by_id(entry)
if @entry.view_in_showcase == true
@entry.view_in_showcase = false
@entry.save
entry_added_showcase += 1
else
@entry.view_in_showcase = true
@entry.save
entry_removed_showcase += 1
end
end
redirect_to :back, :notice => "#{entry_added_showcase} Desings added, #{entry_removed_showcase} Designs removed."
|
Where did you declare the `entry_added_showcase` and `entry_removed_showcase`? you have to initialize them outside the block.
entry_added_showcase = entry_removed_showcase = 0
arr_showcase.each do |entry|
@entry = ContestEntry.find_by_id(entry)
if @entry.view_in_showcase == true
@entry.view_in_showcase = false
@entry.save
entry_added_showcase += 1
else
@entry.view_in_showcase = true
@entry.save
entry_removed_showcase += 1
end
end
redirect_to :back, :notice => "#{entry_added_showcase} Desings added, #{entry_removed_showcase} Designs removed."
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "ruby on rails, ruby"
}
|
Is the Infini-Lift Lightspeed worth it?
In Tiny Tower, is the Infini-Lift Lightspeed worthwhile? It's fairly expensive at 499 Bux. Does it have any special features or is it just faster?
|
In a word: **Yes**
It is so incredibly fast. Even better, it's much easier to actually stop at the target floor (even if it's floor 2). For some reason, it's also easier to read the floor numbers. (Personally, I also think it looks better than the previous elevator, but that might just be me.)
It does take a while to save up for it, but I would definitely recommend it.
|
stackexchange-gaming
|
{
"answer_score": 13,
"question_score": 13,
"tags": "ios, tiny tower"
}
|
How to fix small holes/separation in caulk around bathtub?
I'm sure this is a relatively simple task but I've never done it before and want to make sure I get it right. There are some holes/separation appearing in the caulk between the bathtub and the wall around it. Here is a picture:
!holes in caulk
What would be the most appropriate way to fix this? Can I "patch" the holes with caulk or do I really need to remove what's there now and reapply? What type of caulk do I need? How do I make sure there is not moisture being sealed in? Also, what is the name of this type of material covering the wall around the inside of the tub/shower area? It feels thin and kind of plastic-y. I tried to describe it to someone and realized that I do not know what it's called.
|
This looks like this is one of those re-lined tubs. Get that caulked in as soon as possible. I don't mean to be an alarmist, but I am surprised that the sidewalls are set behind the tub's top edge, not over the tubs edge. The way this is now, relies only on the integrity of the caulk to keep the water out from the actual tub under the liner, where it would be trapped.
Would you be able to have the tub area redone?
If that is not possible, practically any hardware store, big or small will have a mildew resistant caulk that will take care of the immediate problem. Do remove the old caulk by carefully cutting the openings that are there bigger with out scratching the plastic tub or wall liner.
|
stackexchange-diy
|
{
"answer_score": 4,
"question_score": 11,
"tags": "bathroom, bathtub, caulking, caulk"
}
|
Issues updating values in a database table when a parameter contains % in the parameter name
I have a php website that contains a page where you can update values of various parameters contained within a database table. Recently a system admin added some new parameters that contain the % percentage sign at the start of the parameter name and my update function using $_REQUEST superglobal only updates the original parameters that contain alpha characters and new parameters do not update at all.
I need to know how to make a change to my code to support updating of all parameters in the table, no matter the name.
An example of parameters are as follows
|
Enclose in brackets:
$paramname = str_replace('%', '[%]', $paramname);
Or use escape:
$paramname = str_replace('%', '\%', $paramname);
$query = "UPDATE Parameters SET Value = '$value' WHERE ParamName = '$paramname' ESCAPE '\'";
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "php, sql, sql server"
}
|
Expected number of families of $5$ children with $3$ boys? at least $4$ boys?
There are $3,200$ families with $5$ children each. How many of them are expected to have:
a. $3$ boys?
b. at least $4$ boys?
|
Just so you understand better assume that the probability of having a boy is $p$, then that of having a girl is $1-p$. Therefore the probability of having 3 boys is $${{5}\choose{3}} p^3 \cdot (1-p)^{2} $$ Now, multiply this by the number of families to get the answer. Try to do part b on your own. As Jean Marie pointed out in the comments, read up on binomial distribution if you didn't get it.
|
stackexchange-math
|
{
"answer_score": 3,
"question_score": 0,
"tags": "probability"
}
|
How do i extract the satewise data of coronavirus cases in INDIA(name of sate, affected and dead) from this website(https://www.mohfw.gov.in/)
this is the code to extract the html data from the class where my data is located. but how do i extract the required data( **the state wise data** ) as it is not given in order website
import requests
import cloudscraper
from bs4 import BeautifulSoup
import re
import pandas as pd
import time
import datetime
scraper = cloudscraper.create_scraper()
html = scraper.get("
data = BeautifulSoup(html, 'html.parser')
li=data.find_all(class_='table-responsive')
li
|
How about you use pandas. It is organized and creates a df directly. Eg in your case:-
import requests
import pandas as pd
url = '
html = requests.get(url).content
df_list = pd.read_html(html)
df = df_list[-1]
print(df)
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "python, web scraping, beautifulsoup, data science"
}
|
How to access node.js site with direct url without mentioning port 8080 in aws ubuntu, Apache2
My node.js application is running on port 8080. I want to access it via url without mentioning port number in the URL. How will i achieve this?
for example : current : www.domainname.com:8080
Expected :www.domainname.com
Ubuntu os version: 16 Server : Apache2
Need help.
|
Use Nginx as a reverse proxy for your node js application and mentioned your port in nginx config file.(you can create new config file or you can use default one /etc/nginx/nginx.conf)
Install pm2 and Use pm2 tool to keep running your nodejs application in the background.
curl -sL | sudo bash -
sudo apt-get install -y nodejs
sudo npm install pm2@latest -g
pm2 start myapp.config.js (replace myapp.config.js with YOURAPP.js )
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "node.js, ubuntu, port"
}
|
Save graph objects in a list in R
I want to save several graph objects (igraph) in a list and then work with that list (calculating transitivity e.g.). Later I want to use that in a function.
g1<- sample_smallworld(dim=1, 1000, nei=3, p = 0.25)
g2<- sample_smallworld(dim=1, 1000, nei=3, p =0.25)
g3 <- sample_smallworld(dim=1, 1000, nei=3, p =0.25)
g <- c(g1,g2,g3)
length(g1)
length(g)
transitivity(g[1:10])
This was what I got:
> length(g1) [1] 10 length(g) [1] 30 transitivity(g[1:10]) Error in transitivity(g[1:10]) : Not a graph object
|
To create a list in r, it is `list()` function :
library(ggplot2)
n <- 10
df <- data.frame(x = rnorm(n), y = rnorm(n))
g1 <- ggplot(df, aes(x = x, y = y)) + geom_point() + ggtitle("Graph 1")
g2 <- ggplot(df, aes(x = x, y = y)) + geom_point() + ggtitle("Graph 2")
g3 <- ggplot(df, aes(x = x, y = y)) + geom_point() + ggtitle("Graph 3")
g <- list(g1,g2,g3)
g[[1]]
g[[2]]
g[[3]]
igraph object is more or less a ggplot object
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 1,
"tags": "r, igraph"
}
|
If i use redirect_to i'll get Redirected too much on browser
My goal is to redirect user to `index path` if true else show `new path`.
class PostsController < ApplicationController
before_action :check_condition, only: [:index, :new]
def check_condition
if true
redirect_to posts_path
else
redirect_to new_post_path
end
end
def index
@posts = Post.find()
end
def new
@new_post = Post.new(title: "test")
end
end
I keep getting error redirected too much on the browser when I go to index path or new path
|
At the moment, you redirect to `post_path` every time when the if-condition is true no matter if you are already on the `post_path`.
You only need to redirect unless you are already on the path to the expected method. That can be done by checking the current `action_name`:
def check_condition
if true
redirect_to posts_path unless action_name == 'index'
else
redirect_to new_post_path unless action_name == 'new'
end
end
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "ruby on rails, ruby"
}
|
Apply customization when the new project is loaded
I'm trying to apply customization settings to QGIS consistently at two moments:
1. When QGIS opens;
2. When new project (with some layers) is loaded.
My code:
from qgis.utils import iface
from qgis.core import QgsProject
def customize():
#some
#customization
#code
iface.initializationCompleted.connect(customize)
QgsProject.instance().legendLayersAdded.connect(customize)
At first moment code works well. But `legendLayersAdded` signal works only after I'm adding any other layer to an already loaded project.
Is there a signal emitted after any project (new one or existing with some layers) was loaded into QGIS?
|
I looked a bit more into the documentation, and apart for QgsProject, there are also QgisInterface signals:
> **newProjectCreated** Emitted when starting an entirely new project note This is similar to projectRead(); plug-ins might want to be notified that they’re in a new project.
> **projectRead** Emitted when a project file is successfully read note This is useful for plug-ins that store properties with project files.
Complete description e.g.: <
|
stackexchange-gis
|
{
"answer_score": 1,
"question_score": 1,
"tags": "pyqgis, qgis 3"
}
|
Rename files in different folders removing numbers from file names
I'm trying to remove numbers from file names stored in different folders. Specifically, I have 100 folders named: my_folder1, my_folder2, my_folder3,..., my_folder100. In each folder there are files named: my_folder1.txt for my_folder1, my_folder2.txt for my_folder2, my_folder3.txt for my_folder3, ...my_folder100.txt for my_folder100. I need the following output: my_folder.txt for my_folder1, my_folder.txt for my_folder2, my_folder.txt for my_folder3, ..., my_folder.txt for my_folder100. In other words I need to remove the numbers from file names in each folder. I used the following code:
>
> for file in `find . -name 'my_folder*.txt'`; do
> mv $file ${file/+([0-9]).txt/.txt}
> done
>
but the numbers are still there. Can anyone help me please?
Best
|
Are you looking for:
for file in */*.txt; do mv $file $(dirname $file)/my_folder.txt; done
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "unix"
}
|
WiFi repeater with a fallback source?
Let's say I have 2 broadband routers from different providers, let's call them Primary and Secondary. Can I set up a repeater in such a way that if Primary router looses power and/or internet connection the repeater would automatically switch to the Secondary router? I don't have any specific device in mind, just looking to buy one.
|
So the answer is to get a dual wan router and configure it to work with primary and fallback internet connections, pretty much out of the box solution.
|
stackexchange-superuser
|
{
"answer_score": 0,
"question_score": 1,
"tags": "networking, wireless networking, wifi configuration, repeater"
}
|
Find the sum of the series $\sum_{n=0}^{\infty} \frac{(x+2)^n}{(n+3)!}$
Find the sum of the series $\sum_{n=0}^{\infty} \frac{(x+2)^n}{(n+3)!}$ using the Taylor series of $e^{x+2 }$.
**Answer:**
$$ e^{x+2}=1+(x+2)+\frac{(x+2)^2}{2!}+\frac{(x+2)^3}{3!}+\ldots $$
Integrating, we get $$ \int e^{x+2} dx=x+\frac{(x+2)^2}{2!}+\frac{(x+2)^3}{3!}+\frac{(x+2)^4}{4!}+\ldots $$
Again integrating, we get
$$ \int e^{x+2} dx=\frac{x^2}{2}+\frac{(x+2)^3}{3!}+\frac{(x+2)^4}{4!}+\frac{(x+2)^5}{5!}+\ldots\\\ \Rightarrow \int e^{x+2} dx=\frac{x^2}{2}+(x+2)^3 \sum_{n=0}^{\infty} \frac{(x+2)^n}{(n+3)!}\\\ \Rightarrow \sum_{n=0}^{\infty} \frac{(x+2)^n}{(n+3)!}=\frac{\int e^{x+2} dx-\frac{x^2}{2}}{(x+2)^3} $$
**Is this the sum of the series ?**
|
Your approach is sound, but you should be clear about one thing: when you write $\int e^{x+2}\,\mathrm dx$, what you mean is $\int_0^xe^{t+2}\,\mathrm dt$.
|
stackexchange-math
|
{
"answer_score": 0,
"question_score": 1,
"tags": "calculus, integration, sequences and series"
}
|
UITableView inside UITableViewCell - didSelectRowAtIndexPath
I am making an interface which have UITableView with four custom UITableViewCell's. And every other UITableViewCell have also UITableView. This mean I have TableView inside a TableView.
Let me call first tableView - ParentTableView and nested tableView - ChildTableView. So I implemented method didSelectRowAtIndexPath on both tableView's. But when the app is running, only the method of the ChildTableView is being called. I need to know inside the ParentTableView, which cell is being tapped.
How can I transfer that information further from ChildTableView to ParentTableView.
This may be a silly question, but I can not find any reliable solution so far, so please help me.
Thank You in advance, kind Sir
|
First, I think nested table views is a bad idea. But I don't know your use case, so it might be an exception.
The table view controller class used inside a cell have its own `@protocol` definition and set the outer table view as its delegate. In the inner `didSelectRowAtIndexPath:` it can inform the outer table view about the selected `indexPath`, its own `indexPath` and any other information you might want to transmit.
|
stackexchange-stackoverflow
|
{
"answer_score": 4,
"question_score": 1,
"tags": "ios, objective c, uitableview, didselectrowatindexpath"
}
|
Execute application/x-executable file using python code
First of all, I'm new to coding and I''ve tried a lot to understand this problem but I'm stuck. So, I have an executable (application/x-executable) file that I need to run in python code(not from command prompt). In command prompt it is working by:
$ ./test
> add filename.xml
So, what I did is I used subprocess module and I guess it is working.
import subprocess
subprocess.call('./test')
Now I need to pass arguments, Im trying to
subprocess.run('add fielname.xml', shell=True)
It is giving the following error
/bin/sh: 1: add: not found
Appreciate any hint or help!
|
You can do it in this way
subprocess.run(["./test"],input=b"add filename.xml")
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "python, subprocess"
}
|
SQL Server manager alternative
I am currently using SQL Server Management Studio, which is way too heavy. I used to work with a different manager to connect to an Oracle database, but I don't recall the name. It was lightweight and allowed to edit values on the results grid. I don't need more than that, but the database is not on my local machine, if that is some sort of drawback.
If possible, I'd like for the tool to be free.
Have you got a recommendation for me?
I use Windows as the OS.
|
It must be DBVisualizer. It is light weight and it allows to edit the value and you would be able to connect to Oracle or SQLServer. It is available for free with limited features.
|
stackexchange-softwarerecs
|
{
"answer_score": 0,
"question_score": 0,
"tags": "windows, database, sql server"
}
|
Cold weather battery power
I've built a temperature sensor module that runs off of 4xAA batteries and sends data back to a computer via XBee. Works great, until the weather gets cold. At that point, the rechargeable AA batteries (I've tried duracell and eneloop) die very quickly. At 40 or so it seems like they can hardly muster the 3.3V needed to power the wireless.
This needs to be battery powered - running a wire to it isn't an option.
I'm trying plain old alkalines right now, but I was wondering if anyone had any tips on getting enough power out of batteries during the winter. Do I just need to double up and use 8 batteries? Do NiCad or LiPo cells work better than NiMH? Would switching to a different wireless module that can handle lower voltage solve the problem?
|
Are the batteries actually dead or will they start to work if the temperature is increased? Is the XBee on all the time or does it spend most of its time sleeping?
Assuming the batteries just need to be warmed -- if the XBee does not have to be on all the time you may be able to perform a startup sequence that consists of drawing current from the batteries to warm them up and then enabling the XBee.
A wide input range DC-DC converter would also enable you to startup at lower voltages.
One other note the XBees can be run at 3V. They also draw very low currents in the hibernate modes when run at 3V. I have some plots of duty-cycle and current draw for different operating modes at <
|
stackexchange-electronics
|
{
"answer_score": 5,
"question_score": 8,
"tags": "batteries, wireless"
}
|
jquery with if structure
How can I use jquery to bring up one of two different divs based on if a user is logged in or not?
For my wordpress site I have a menu item that I need to prompt the user to first log in or register (via my fancybox iframe), and if already logged in to instead bring up another div (to access posts). Both these options are set up, I just don't know how to structure the code as an IF structure or some sort of conditional code. Thanks for any help.
|
Don't use JQuery. Distinction between logged in users to visitors content must only be done on the **server side**. You don't want the server to send info addressed at logged users only, to visitors. That makes your login system highly penetrable - to say the least - as the info is already on the client-side and he can access it easily (e.g. simply by turning JS off or viewing page source).
The basic structure using WP built-in function would be:
<?php if (is_user_logged_in()): ?>
//logged user info
<?php else: ?>
//login form
<?php endif; ?>
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "jquery, wordpress, conditional statements"
}
|
Unable to run .net app with Mono - mscorlib.dll not found (version mismatch?)
I have a simple .net command line tool written and compiled under Windows, using .net 3.5SP1. I would like to run it on Linux using Mono.
I am using Ubuntu 12.04, and installed Mono Runtime using the Ubuntu software center. If I try to start my app in the terminal by doing:
mono MyApp.exe
I get the error:
> The assembly mscorlib.dll was not found or could not be loaded. It should have been installed in the 'usr/lib/mono/2.0/mscorlib.dll'.
If I navigate to that location, I see that it does not exist. However, there is `usr/lib/mono/4.0/mscorlib.dll` (and some more DLLs in the same folder).
So seemingly there is a version mismatch.
[in case it matters, `mono -V` shows `Mono JIT compiler version 2.10.8.1 (Debia 2.10.8.1-1ubuntu2)` ]
|
I got it to work by installing mono-complete:
sudo apt-get install mono-complete
After that, I had folders 2.0, 3.5, 4.0 and more under usr/lib/mono
|
stackexchange-stackoverflow
|
{
"answer_score": 94,
"question_score": 70,
"tags": "ubuntu, mono"
}
|
AttributeError: module 'cv2.cv2' has no attribute 'xfeatures2d' [Opencv 3.4.3]
I have opencv 3.4.3 installed (using `pip3 install opencv-python` and `pip3 install opencv-python-contrib`)
When I run a code containing this line:
`sift = cv2.xfeatures2d.SIFT_create()`
I got this error:
AttributeError: module 'cv2.cv2' has no attribute 'xfeatures2d'
Is `xfeatures2d` function not anymore supported by opencv 3.4.3?
|
The error message you have is related to the fact that the module `xfeatures2d` does not exist. It is not directly related to SIFT algorithm nor any algorithm in `xfeatures2d` (all will send that error). I suggest you to either reinstall `opencv-contrib-python`(pip install opencv-contrib-python) or if you are using anaconda or equivalent to re-install the two opencv package from another source repository. A last option consist to compile the full OpenCV ("regular" + contrib) by yourself if you are comfortable with it.
Hope it helps.
|
stackexchange-stackoverflow
|
{
"answer_score": 11,
"question_score": 6,
"tags": "python, opencv"
}
|
Preventing from Boomarks getting deleted
I have some code I want to run - but the bookmarks in Word keep getting deleted - I want it to "overwrite" the last Input not add it.
Dim NAME As Range
Set NAME = ActiveDocument.Bookmarks("Username").Range
NAME.Text = Me.TextName.Value
Dim Surname As Range
Set Surname = ActiveDocument.Bookmarks("UsernameSurname").Range
Surname.Text = Me.TextSurname.Value
Does anyone have an solution for this? Thanks.
|
Your code doesn't delete the bookmarks - it simply inserts content after them.
To _update_ the bookmarks, you might use, for example:
Call UpdateBookmark("Username",Me.TextName.Value)
Call UpdateBookmark("UsernameSurname",Me.TextSurname.Value)
coupled with:
Sub UpdateBookmark(StrBkMk As String, StrTxt As String)
Dim BkMkRng As Range
With ActiveDocument
If .Bookmarks.Exists(StrBkMk) Then
Set BkMkRng = .Bookmarks(StrBkMk).Range
BkMkRng.Text = StrTxt
.Bookmarks.Add StrBkMk, BkMkRng
End If
End With
Set BkMkRng = Nothing
End Sub
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "vba, ms word"
}
|
JQuery popup via a button toggle class
Hi I have a modal popup which has an `active class`, once this class is on the modal appears and once this class is off it disappears. I want a button to be able to be pressed and the modal appears and a close button in the modal which closes the modal. I am using JQuery so I have tried so far:
Jquery
<script>
$(document).ready(function(){
$("button").click(function(){
$(".modal").addClass(".active");
});
});
</script>
Html
<button>Modal</button>
Not active Modal Html
<div class="modal" id="modal-id">
</div>
Active modal html
<div class="modal active" id="modal-id">
</div>
|
You don't need to use dot before class name:
<script>
$(document).ready(function(){
$("button").click(function(){
$(".modal").addClass("active");
});
});
</script>
|
stackexchange-stackoverflow
|
{
"answer_score": 2,
"question_score": 0,
"tags": "javascript, jquery, html"
}
|
Why is there no * in this method declaration?
Here is the method declaration midway in Apple's documentation: Learning Objective-C: A Primer
- (void)insertObject:(id) anObject atIndex:(NSUInteger) index
Why is there no `*` right after `NSUInteger`. I thought all objects were pointer types and all strongly typed pointers had to have a `*` character after it.
|
`NSUInteger` is not an object type, it is a `typedef` to `unsigned int`.
The only reason that you would actually want to use a `*` in this context would be if you wanted to get the address of an int and store something in it. (Some libraries do this with error messaging). An example of this:
-(void) methodName: (NSUInteger *) anInt {
*anInt = 5;
}
NSUInteger a;
[obj methodName: &a]; //a is now 5
|
stackexchange-stackoverflow
|
{
"answer_score": 11,
"question_score": 1,
"tags": "iphone, objective c, pointers, ios"
}
|
Exit / disable edit mode after double click handled event
I'd like to display a dialog after a user clicks a cell in an Excel sheet. Something like this:
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
MsgBox "a cell was clicked!", vbOKOnly, "a click"
End Sub
It works perfectly fine. The problem is, after a double click edit mode is turned on and a formula is expected to be entered. How do I disable this behaviour?
I'd like to achieve pure functionality: ~ user clicks a cell ~ a dialog appears ~ user closes the dialog ~ a cell does NOT go into edit mode, the sheet looks exactly as it did before double click event.
|
You have to cancel the action with the variable given in argument:
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
MsgBox "a cell was clicked!", vbOKOnly, "a click"
'Disable standard behavior
Cancel = True
End Sub
Here is a dummy example:
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
Dim response As Variant
response = MsgBox("Are you sure you want to edit the cell?", vbYesNo, "Check")
If response = vbYes Then
Cancel = False
Else
Cancel = True
End If
End Sub
Note that you wouldn't have to set `Cancel` to `False` because it the default value (this is for the example purpose).
|
stackexchange-stackoverflow
|
{
"answer_score": 21,
"question_score": 13,
"tags": "excel, excel 2007, vba"
}
|
DataTable to the set of SQL queries
How can I convert data from DataTable to the set of SQL queries?
The problem is that I haven't connection with DB.
I've tried:
SqlDataAdapter dataAdapter = new SqlDataAdapter();
SqlCommandBuilder sqlCommandBuilder = new SqlCommandBuilder(dataAdapter);
dataAdapter.InsertCommand = sqlCommandBuilder.GetInsertCommand();
//Exception - The DataAdapter.SelectCommand property needs to be initialized.
dataAdapter.Update(_myDB, MenuTable);
dataAdapter.InsertCommand // contain commands
But it's not work, because I haven't connection! Any one have idea?
|
public static IEnumerable<string> GetInsertQueryFromDataTable(DataTable dataTable)
{
foreach (DataRow row in dataTable.AsEnumerable())
{
var s = new StringBuilder(string.Format("INSERT INTO {0} SET ", dataTable.TableName));
foreach (DataColumn v in dataTable.Columns)
{
var r = new StringBuilder(row[v.ColumnName].ToString());
r.Replace(@"\", @"\\");
r.Replace("\"", "\\\"");
s.AppendFormat("{0}=\"{1}\", ", v.ColumnName, r);
}
s.Remove(s.Length - 2, 1);
s.AppendLine(";");
yield return s.ToString();
}
}
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "c#, ado.net"
}
|
How to extract numbers from a string in Python?
I would like to extract all the numbers contained in a string. Which is better suited for the purpose, regular expressions or the `isdigit()` method?
Example:
line = "hello 12 hi 89"
Result:
[12, 89]
|
If you only want to extract only positive integers, try the following:
>>> txt = "h3110 23 cat 444.4 rabbit 11 2 dog"
>>> [int(s) for s in txt.split() if s.isdigit()]
[23, 11, 2]
I would argue that this is better than the regex example because you don't need another module and it's more readable because you don't need to parse (and learn) the regex mini-language.
This will not recognize floats, negative integers, or integers in hexadecimal format. If you can't accept these limitations, jmnas's answer below will do the trick.
|
stackexchange-stackoverflow
|
{
"answer_score": 688,
"question_score": 673,
"tags": "python, regex, string, numbers"
}
|
Can't use domain credentials, but server is part of the domain
I have added a server to my domain, but the domain credentials don't work on the server even though it offers the domain at login. The server has an entry in the AD, DNS, and DCHP; any suggestions?
All servers in the domain are running Win 2003 R2 x64. The server in question is an Edge server in a deployment of OCS 2007 Standard edition R2.
EDIT: Solution - Removed and reconnected it to the domain a few times, seems to have worked
|
If the server is edge, chances are it's out in your DMZ. You'll need to ensure that there's sufficient rules punched between the server and its domain controller, through the firewall.
If possible look at firewall traffic logs between that server and the DCs, and you should find some dropped traffic.
|
stackexchange-serverfault
|
{
"answer_score": 1,
"question_score": 0,
"tags": "domain controller, ms office communicator, credentials"
}
|
With OnKeyListener, what is the difference between return true and false?
What is the different between return `true` and `false` with `OnKeyListener`?
I look at the android official document here!.
However, I still dont get to truly understand it. Can anyone explain it to me more explicit on how `OnKeyListener` reach to those two returns?
|
The event will continue to _bubble up_ the container chain if you return `false`
> Returns True if the listener has consumed the event, false otherwise.
Because, if you think about it, what we do is to necessarily nest `view`s inside one another:
for example:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="
android:onClick="layoutClicked" >
<Button
android:id="@+id/button1"
android:onClick="myButtonClicked" />
</LinearLayout>
Imagine a click on the button, if you donT return `true`, `layoutClicked` will also fire after the `myButtonClicked` handler.
I think there is more explanation in this article
|
stackexchange-stackoverflow
|
{
"answer_score": 7,
"question_score": 4,
"tags": "android"
}
|
Is it a good idea to control notification (sound, new submissions and badge) inside your App
I currently trying to implement a way to turn on / off push notification sound , badge and alert via inside App. Is this good practice? I am trying to do that now, but the App acts strangely doing this. Any tips or suggestions are appreciated.
|
If your are talking about remote server push notification, it actually depends if your app is running or not.
If not running the notification enable/disable setting lies entirely in hand of user and you can just recommend changes and redirect user to settings app. It cannot be changed manually.
Push noti has a param about badge and sound which can be controlled by ur server. Also updating the badge count programmatically once app gets chance to execute is regular practice I.e. to clear pending noti.
If running you can handle the notification or badge update as well as sound however you want.
Please check for details <
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "ios, objective c, iphone"
}
|
Sanitize strings for unique legal symbols in R
I want to clean up strings so they can be parsed as unique legal symbols. I intend to clean up a lot of strings, so there is an undesirable risk of duplicated symbols in the output. It would suffice to take every illegal character and replace it with its base 32 encoding. Desired behavior:
sanitize("_bad_symbol$not*a&list%$('")
## [1] "L4bad_symbolEQnotFIaEYlistEUSCQJY"
I think all I need is a complete list of possible characters to `grep` for. I know about `letters` and `LETTERS`, but what about everything else?
Does a better solution already exist? Because I would love that.
**EDIT** : just found about `make.names()` from this post. I could go with that in a pinch, but I would rather not.
|
With `make.names()` and `make.unique()` together, the problem is solved.
make.unique(make.names(c("asdflkj#@#$", "asdflkj####")))
## [1] "asdflkj...." "asdflkj.....1"
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "r, symbols, gsub"
}
|
Does @Asynchronous have a Timeout
When i call a Method like this:
@Asynchronous
public void cantstopme() {
for(;;);
}
Would it run forever or would the Application Server kill it after a certain time?
|
Every time a method annotated `@Asynchronous` is invoked by anyone it will immediately return regardless of how long the method actually takes.
Each invocation should return a `Future` object that essentially starts out empty and will later have its value filled in by the container when the related method call actually completes.
For example:
@Asynchronous
public Future<String> cantstopme() {
}
and then call it this way:
final Future<String> request = cantstopme();
And later you could ask for the result using the Future.get() method with a specific timeout, i.e:
request.get(10, TimeUnit.SECONDS);
|
stackexchange-stackoverflow
|
{
"answer_score": 5,
"question_score": 4,
"tags": "java, jakarta ee, asynchronous, timeout, ejb"
}
|
DNN module sugestions needed, form/reg, pyment, emailing
i need a module that is kind of a cross between a registration module and a form module.
it need to allow for custom form fields to be saved to the DB and work as part of a flow such that once data is entered by the users they click next and see the data to confirm it is correct. at this point they should have the option to edit the data if they notice an error or continue to a payment page.
the payment page needs to have a module that can integrat with payment gateways liek paypal and accept credit cards. once credit card data is entered and the transaction is complete a custom email with a unique userNumber needs to be sent to the user.
i figure im lookign at three separate modules for this typeof work flow. but i hope since this is a standard type of register, pay, email confirm operation there may be a single module i can confugure to meet my needs.
thoughts? suggestions?
|
Have you looked at DNM RAD by DotNet Mushroom?
<
I have not had a use for this yet, but it is a module that I have on my short list in case the need comes up. They do state that they can work with pament gateways.
Good luck.
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 0,
"tags": "dotnetnuke, dotnetnuke 5"
}
|
sqlquery in R does not return all rows from query
I am executing below commands in R:
dbhandle <- odbcDriverConnect('driver={SQL Server};server=serveripaddress;database=DBName;uid=sa;pwd=pwd;')
FactActivity <- sqlQuery(dbhandle, "SELECT DimCourseID,DimPatientID FROM DWH.FactActivity", as.is=TRUE)
nrow(FactActivity)
In my database I have total **238634** rows but in R I am getting total rows = **237652**.
This is happening for all tables (I tried it for three tables).
Any idea what am I missing which is reducing no of rows in my resultset in R?
|
I had the same problem, couldn't solve it, eventually switched to using RJDBC with a Java driver to get around it.
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 6,
"tags": "sql, sql server, r, odbc"
}
|
anonymous function usefulness
Why not write the anonymous function content only instead of the anonymous function AND the anonymous function content?
|
I don't know if this even applies, since it is specific to Javascript and I don't see a Javascript tag, but....it's not uncommon to create+call an anonymous function at once. It's often done in the sake of preserving the global scope from variable pollution.
var x = 1;
(function(){
var x = 2;
})();
x == 1;
|
stackexchange-stackoverflow
|
{
"answer_score": 0,
"question_score": 1,
"tags": "lambda, anonymous function"
}
|
How to store the result of the expression into a variable in Windows batch script?
I have the windows batch script that replaces `\` by `_`.
I want to know what is needed to store the result of the replace expression into a variable?
Below is the script I have.
FOR /F "tokens=* delims=" %%x in (E:\Windows_Scripts\server.txt) DO (
Set "servername=%%x"
Set "Pattern=\"
Set "Replace=_"
call echo %%servername:%Pattern%=%Replace%%%
)
I want to store the result of the below expression
%%servername:%Pattern%=%Replace%%%
into a variable. How can this be done?
|
Set the variable at each iteration with the delayed expansion activated!!
@echo off
setlocal enabledelayedexpansion
Set "Pattern=\"
Set "Replace=_"
FOR /F "tokens=*" %%x in (server.txt) DO (
Set "servername=%%x"
Set "$output=!servername:%Pattern%=%Replace%!"
echo !$output!
)
|
stackexchange-stackoverflow
|
{
"answer_score": 1,
"question_score": 0,
"tags": "batch file, windows scripting"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.