_id
stringlengths 2
6
| partition
stringclasses 3
values | text
stringlengths 4
46k
| language
stringclasses 1
value | title
stringclasses 1
value |
---|---|---|---|---|
d9501 | train | which version of AOP are you using? does the error occur if you set the AOP url to apexofficeprint.com/api?
if you set the debugging to local from the AOP components settings, you should receive a JSON, if you send it to [email protected] we would gladly help you out with this issue.
EDIT: Bug on version 3.0, issue was fixed from version 3.1. | unknown | |
d9502 | train | I looked into this a little deeper the basic problem is that gevent.spawn() creates greenlets not processes (all greenlets run in a single OS thread).
Try a simple:
import gevent
from time import sleep
g = [gevent.spawn(sleep, 1) for x in range(100)]
gevent.joinall(g)
You'll see the time this takes is 100s. Which proves the point above.
You are really looking for multithreading which can be found in the threading module.
Have a look at the the question at: How to use threading in Python?. For a little how to.
---update---
Here is a quick example of how you might do this:
threads = [threading.Thread(target=sleep, args=(1,)) for x in range(10)]
[thread.start() for thread in threads]
[thread.join() for thread in threads] | unknown | |
d9503 | train | This sounds like a scope issue to me. I would need to see more of your code to be sure but let's assume that there is an instance of Notification that is created in RequestService. You can't directly access the variable no_emails. You would access like this:
// here is the instance of notification
Notification someNotifacation = new Notification();
// call the getter method to get the value
if(!someNotification.no_emails)
{
...
}
A: If this is ASP.NET MVC, you can put the no_emails variable in the Action parameter list, and MVC will bind it for you to the POSTed form value. However, the parameter name and the name attribute on the form must match. Here, you have name="emails", so you will need to change it to match the parameter name you use.
but you have a Spring attribute which makes me think this is not ASP.NET MVC? | unknown | |
d9504 | train | Zam, this should be quite easy. You just need to create a new calculated field that calculates the average for ALL sales rep.
Let me walk you through it:
I used your data table and then added it to my PowerPivot (Excel 2013). Then I created those calculated measures:
1. Sales Average:
=AVERAGE(SalesData[SalesGP])
2. Sales Average ALL -- this will calculate the average for ALL rows in the table and will be used in other calculations. Notice I used the first calculated field as the first parameter to make this flexible:
=CALCULATE([Sales Amount Average],ALL(SalesData))
3. Sales Comparison to Average. I wasn't sure what is your goal, but I made this one a bit more complex as I wanted to display the performance in percentage:
=IF([Sales Amount Average] > 0, [Sales Amount Average] / [Sales Average ALL] -1)
Basically, what this does is that first it checks if their an existing calculation for a sales representative, if so then it divides Sales Average for a given sales representative by the average sale amount for ALL sales representatives. And then I subtract 1 so the performance can be easily grasped just by looking at the percentages.
To make it easy-to-understand, I decided to use bar charts in conditional formatting instead of stand-alone pivotchart -- I believe it does exactly what you need:
In the picture above, the first table represents your data. The second table is the actual powerpivot table and shows what I have described.
Hope this helps!
EDIT
I didn't want to make things over-complicated, but should you want to remove the percentage total from Grand Totals row, use this calculation instead for the percentage comparison:
=IF(HASONEVALUE(SalesData[SalesRep]),
IF([Sales Amount Average] > 0,
[Sales Amount Average] / [Sales Average ALL] -1),
BLANK()
)
EDIT - ADDED AVERAGE COMPARISON FOR WORKGROUPS
To calculate the performance per workgroup instead of ALL sales representative, add those two measures:
4. Sales Average per Workgroup
=CALCULATE(AVERAGE(SalesData[SalesGP]),ALL(SalesData[SalesRep]))
This will calculate the average sale per workgroup (don't get confused with using SalesRep in ALL function, it's related to filter context).
5. Sales Diff to Average per Workgroup
=IF(HASONEVALUE(SalesData[SalesRep]),IF([Sales Amount Average] > 0, [Sales Amount Average] - [Sales Average per Workgroup]),BLANK())
This simply calculates the difference between average sale of given sales rep and the average sale per workgroup. The result could then look like this:
I have uploaded the source file to my public Dropbox folder. | unknown | |
d9505 | train | Changed Kernel: conda_tensorflow2_p38 | unknown | |
d9506 | train | I've been using mgwt/phonegap only a few months, so I'm definitely not an expert, but so far no major stumbling blocks. I like GWT, as it is well documented, robust and supported, although mgwt is a bit less so. There's an active google forum at https://groups.google.com/forum/?fromgroups#!forum/mgwt. Maybe if you have some more specific question, I or someone on that forum could answer it. | unknown | |
d9507 | train | Well, that code is OK. So this should mean your not including your JS correctly.
I just copied your code and pasted ( I just modified the begining of the script to hide all tabcontents)
var tabcontent = document.getElementsByClassName("tabcontent");
for (i = 0; i < tabcontent.length; i++) {
tabcontent[i].style.display = "none";
}
function openCity(evt, cityName) {
// Declare all variables
var i, tabcontent, tablinks;
// Get all elements with class="tabcontent" and hide them
tabcontent = document.getElementsByClassName("tabcontent");
for (i = 0; i < tabcontent.length; i++) {
tabcontent[i].style.display = "none";
}
// Get all elements with class="tablinks" and remove the class "active"
tablinks = document.getElementsByClassName("tablinks");
for (i = 0; i < tablinks.length; i++) {
tablinks[i].className = tablinks[i].className.replace(" active", "");
}
// Show the current tab, and add an "active" class to the button that opened the tab
document.getElementById(cityName).style.display = "block";
evt.currentTarget.className += " active";
}
<div class="tab">
<button class="tablinks" onclick="openCity(event, 'London')">London</button>
<button class="tablinks" onclick="openCity(event, 'Paris')">Paris</button>
<button class="tablinks" onclick="openCity(event, 'Tokyo')">Tokyo</button>
</div>
<!-- Tab content -->
<div id="London" class="tabcontent">
<h3>London</h3>
<p>London is the capital city of England.</p>
</div>
<div id="Paris" class="tabcontent">
<h3>Paris</h3>
<p>Paris is the capital of France.</p>
</div>
<div id="Tokyo" class="tabcontent">
<h3>Tokyo</h3>
<p>Tokyo is the capital of Japan.</p>
</div> | unknown | |
d9508 | train | If you are absolutely sure the list is three elements long, you could use
readText :: [Text] -> MyRecord
readText [rOne, rTwo, rThreeText] = MyRecord {..}
where rThree :: Int = read rThreeText
Still, you might wish to make the pattern matching exhaustive, just in case:
readText :: [Text] -> MyRecord
readText [rOne, rTwo, rThreeText] = MyRecord {..}
where rThree :: Int = read rThreeText
readText _ = error "readText: list length /= 3" | unknown | |
d9509 | train | You should have a service or something that will be updated like below :
private void refresh() {
startService(new Intent(this, UpdaterService.class));
}
then Refresh :
mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout);
mSwipeRefreshLayout.setOnRefreshListener(this);
mSwipeRefreshLayout.post(new Runnable() {
@Override
public void run() {
mSwipeRefreshLayout.setRefreshing(true);
refresh();
}});
//here refreshed Item
//getLoaderManager().initLoader(0, null, this);
if (savedInstanceState == null) {
refresh();
}
and your onRefresh() should contain the same method refresh(). | unknown | |
d9510 | train | Please check your expected output. I believe there are some mistakes.
Here is a tidyverse option:
library(tidyverse)
df %>%
gather(key, value, -Month, -Records) %>%
group_by(Month, key, value) %>%
summarise(freq = n()) %>%
mutate(freq = freq / sum(freq)) %>%
unite(col, key, value, sep = ".") %>%
spread(col, freq)
## A tibble: 12 x 13
## Groups: Month [12]
# Month V1.F V1.T V2.A V2.B V2.C V3.W V3.X V3.Y V3.Z V4.Maybe V4.NO
# <fct> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
# 1 1/1/… 0.4 0.6 0.2 0.6 0.2 0.4 0.2 0.3 0.1 0.4 0.3
# 2 10/1… 0.5 0.5 0.4 0.2 0.4 0.3 0.1 0.3 0.3 0.3 0.3
# 3 11/1… 0.4 0.6 0.3 0.4 0.3 0.2 0.2 0.2 0.4 0.3 0.4
# 4 12/1… 0.8 0.2 0.1 0.2 0.7 0.2 0.2 0.1 0.5 0.5 0.3
# 5 2/1/… 0.7 0.3 0.3 0.3 0.4 0.1 0.3 0.3 0.3 0.2 0.5
# 6 3/1/… 0.6 0.4 0.3 0.2 0.5 NA 0.2 0.4 0.4 0.4 0.4
# 7 4/1/… 0.4 0.6 0.3 0.5 0.2 0.2 0.2 0.4 0.2 0.4 0.3
# 8 5/1/… 0.4 0.6 0.3 0.5 0.2 0.2 0.2 0.2 0.4 0.6 0.2
# 9 6/1/… 0.4 0.6 0.3 0.2 0.5 0.3 0.1 0.4 0.2 0.5 0.3
#10 7/1/… 0.4 0.6 0.3 0.6 0.1 0.1 0.2 0.6 0.1 0.2 0.2
#11 8/1/… 0.6 0.4 0.5 0.2 0.3 0.5 NA 0.3 0.2 0.4 0.4
#12 9/1/… 0.3 0.7 0.1 0.8 0.1 0.3 0.3 0.2 0.2 0.4 0.3
## ... with 1 more variable: V4.YES <dbl>
A: Here is an alternative approach which uses the table() and prop.table() functions from base R and dcast() for reshaping to wide format. Unfortunately, I am not fluently enough in dplyr so I resort to data.table for grouping.
library(data.table)
library(magrittr)
setDT(df)[, lapply(.SD, function(.x) table(.x) %>% prop.table %>% as.data.table) %>%
rbindlist(idcol = TRUE), .SDcols = V1:V4, by = Month] %>%
dcast(Month ~ .id + .x)
Month V1_F V1_T V2_A V2_B V2_C V3_W V3_X V3_Y V3_Z V4_Maybe V4_NO V4_YES
1: 1/1/2017 0.4 0.6 0.2 0.6 0.2 0.4 0.2 0.3 0.1 0.4 0.3 0.3
2: 10/1/2017 0.5 0.5 0.4 0.2 0.4 0.3 0.1 0.3 0.3 0.3 0.3 0.4
3: 11/1/2017 0.4 0.6 0.3 0.4 0.3 0.2 0.2 0.2 0.4 0.3 0.4 0.3
4: 12/1/2017 0.8 0.2 0.1 0.2 0.7 0.2 0.2 0.1 0.5 0.5 0.3 0.2
5: 2/1/2017 0.7 0.3 0.3 0.3 0.4 0.1 0.3 0.3 0.3 0.2 0.5 0.3
6: 3/1/2017 0.6 0.4 0.3 0.2 0.5 0.0 0.2 0.4 0.4 0.4 0.4 0.2
7: 4/1/2017 0.4 0.6 0.3 0.5 0.2 0.2 0.2 0.4 0.2 0.4 0.3 0.3
8: 5/1/2017 0.4 0.6 0.3 0.5 0.2 0.2 0.2 0.2 0.4 0.6 0.2 0.2
9: 6/1/2017 0.4 0.6 0.3 0.2 0.5 0.3 0.1 0.4 0.2 0.5 0.3 0.2
10: 7/1/2017 0.4 0.6 0.3 0.6 0.1 0.1 0.2 0.6 0.1 0.2 0.2 0.6
11: 8/1/2017 0.6 0.4 0.5 0.2 0.3 0.5 0.0 0.3 0.2 0.4 0.4 0.2
12: 9/1/2017 0.3 0.7 0.1 0.8 0.1 0.3 0.3 0.2 0.2 0.4 0.3 0.3 | unknown | |
d9511 | train | go build builds everything (that is, all dependent packages), then produces the resulting executable files and then discards the intermediate results (see this for an alternative take; also consider carefully reading outputs of go help build and go help install).
go install, on the contrary, uses precompiled versions of the dependent packages, if it finds them; otherwise it builds them as well, and installs under $PATH/pkg. Hence I might suggest that go install sees some outdated packages which screw the resulting build.
Consider running go install ./... in your $GOPATH/src.
Or may be just selective go install uri/of/the/package for each dependent package, and then retry building the executable. | unknown | |
d9512 | train | Autocommit mode means that each statement implicitly begins and ends the transaction.
In your case, if autocommit is off:
*
*The client will implicitly start the transaction for the first statement
*The BEGIN will issue a warning saying that the transaction is already started
*The ROLLBACK will roll back all four statements
When autocommit is on, only the c and d are rolled back.
Note that PostgreSQL has no internal AUTOCOMMIT behavior since 8.0: all autocommit features are relied upon the clients.
A: By default, PostgreSQL has autocommit on, meaning that each statement is handled as a transaction. If you explicitly tell it to start a transaction, as in your example, those items are in a new transaction.
In your example, A and B would be committed, C and D would be rolled back.
A: When autocommit is on psycopg just sends everything to the PostgreSQL backend without trying to manage the transaction for you. If you don't use BEGIN/COMMIT/ROLLBACK then every .execute() call is immediately executed and committed. You can do your own transaction management by issuing BEGIN/COMMIT/ROLLBACK commands. Obviously in autocommit mode you can't call conn.commit() or conn.rollback() because psycopg is not keeping track of the transactions but just sending anything you .execute() straight to the backend.
In your example A and B would be committed, C and D would be rolled back. | unknown | |
d9513 | train | You really only need to save the user_id in order to reference all of the other attributes.
I like to use options_for_select and pass it a two dimensional array when I'm saving an id. The first value will be what the user sees. The second value will be what I actually save. In this case, I'm guessing that you'd like the user to see a username but you'd like to actually save the user_id.
That would look something like:
<%= f.select :user_id, options_for_select(User.choices) %>
and then in user.rb:
def self.choices
choices = []
User.find_each { |u| choices << [u.username, u.id] }
choices
end
You don't need to save both values because you can always access any attribute saved on user with the id.
EDIT:
per your comment, you actually don't need a select box at all. Just set them in your orders controller create action:
@order.username = current_user.username
@order.user_id = current_user.id
if @order.save
# etc
Again, though, you don't really need to save the username if you have the user_id as a foreign key. With a foreign key you'll always be able to take an instance of order and say order.user.username and get the appropriate username for that user_id. | unknown | |
d9514 | train | Try with this code in your controller
this.childQuestionId = function(req, res, next){
try{
var userObj = {
'questionId' : req.params.questionId,
'score' : req.params.score,
//'time' : req.params.time
'time' : new Date().toISOString()
};
var childupdate = new childQuiz();
childupdate.quiz.push(userObj);
childupdate.save(function(err){
if(err) return next(err);
console.log("Data saved successfully");
res.send(childupdate);
});
}catch(err){
console.log('Error While Saving the result ' +err);
return next(err);
}
}
A: MongoDB save() function accepts 2 parameters, document and data, but in your code, you use a callback function. Should you check it out?
https://docs.mongodb.com/manual/reference/method/db.collection.save/#db.collection.save | unknown | |
d9515 | train | I have a var which is an index of one of the divs above, lets say it equals 2, so it's the one with 3.jpg as a background.
...
Now, I'm trying to get the index of the next div with class "slide", which index is greater than my var and which has no "background" in "style".
What you need for that literal requirement is a combination of eq, nextAll, filter, and (if you really want the index) index.
var index = $(".slide").eq(startingIndex).nextAll(".slide").filter(function() {
return $(this).attr("style").indexOf("background") === -1;
}).index();
That will give you the element's index relative to its siblings (all of them).
But if you just want the element, use first instead:
var nextSlideWithoutBackground = $(".slide").eq(startingIndex).nextAll(".slide").filter(function() {
return $(this).attr("style").indexOf("background") === -1;
}).first();
Actually, you could use :gt but it's a pseudo-selector so it may not be any better than using nextAll. Here's what it would look like, though:
var index = $(".slide:gt(" + startingIndex + ")").filter/*...and so on...*/ | unknown | |
d9516 | train | Firefox loads the children within the scene from a .GLB file in the opposite order of all other browsers. This is detrimental if you plan on manipulating the contents such as alpha maps, etc... of a .GLB object using Three.js.
I figured out the issue by loading a simple .GLB object into a project and it worked in Firefox just fine. So why wouldn't my more complicated object that utilized alpha maps work in Firefox?
Eventually I noticed that the children array of the GLTF scene was in the reverse order while running in Firefox thus causing my code to not match the indexes of the children. | unknown | |
d9517 | train | It seems to be a case of using improperly initiialized/uninitialized variables.
After I added the following line:
for(int i = 0; i < ARRAYSIZE; i++){
c[i] = 0;
aSumArr[i] = 0;
bSumArr[i] = 0;
binaryNumber[i] = 0; // add this line
}
I was no longer able to reproduce the issue. | unknown | |
d9518 | train | The problem you're describing can be solved by "advertising" an address for each broker over the internet via advertised.listeners
telnet and nc check that port is open (listeners config), but cannot check that the brokers bootstrap correctly back to the client, you can instead use kafkacat -L -b <bootstrap> for that, which will return a list of brokers in the cluster, and connecting to each of those should be possible from where you want to run the client
If you have multiple brokers behind your single WAN address, they'll have to advertise / forward separate ports for full connectivity
Alternative solutions include the Kafka REST Proxy
In either case, adding SSL to the connection should be done | unknown | |
d9519 | train | allfiles = glob.glob('*.csv')
allfiles.sort(key= lambda x: int(x.split('_')[1].split('.')[0]))
A: You can't do that with glob, you need to sort the resultant files yourself by the integer each file contains:
allfiles = glob.iglob('*.csv')
allfiles_sorted = sorted(allfiles, key=lambda x: int(re.search(r'\d+', x).group()))
Also note that, i've used glob.iglob instead of glob.glob as there is no need to make an intermediate list where an iterator would do the job fine.
A: Check with natsort
from natsort import natsorted
allfiles=natsorted(allfiles)
A: os.listdir() will give the list of files in that folder and sorted will sort it
import os
sortedlist = sorted(os.listdir())
EDIT: just specify key = len to count the length of an element
sorted(os.listdir(),key = len)
A: This is also a way to do that. This algorithm will sort with length of file name string.
import glob
all_files = glob.glob('*.csv')
def sort_with_length(file_name):
return len(file_name)
new_files = sorted(all_files, key = sort_with_length )
print("Old files:")
print(all_files)
print("New files:")
print(new_files)
Sample output:
Old files:
['file1.csv', 'file101.csv', 'file102.csv', 'file2.csv', 'file201.csv', 'file3.csv']
New files:
['file1.csv', 'file2.csv', 'file3.csv', 'file101.csv', 'file102.csv', 'file201.csv'] | unknown | |
d9520 | train | The :link pseudo class applies to the link even when you are hovering over it. As the style with the id is more specific it overrides the others.
The only reason that the :hover style overrides the :link style at all is that it comes later in the style sheet. If you place them in this order:
a:hover { color: red; }
a:link { color: blue; }
the :link style is later in the style sheet and overrides the :hover style. The link stays blue when you hover over it.
To make the :hover style work for the black link you have to make it at least as specific as the :link style, and place it after it in the style sheet:
a:link { color: blue; }
a:hover { color: red; }
#someID a:link { color: black; }
#someID a:hover { color: red; }
A: There's an order issue, as explained in W3Schools:
Note: a:hover MUST come after a:link
and a:visited in the CSS definition in
order to be effective!!
Note: a:active MUST come after a:hover
in the CSS definition in order to be
effective!!
http://www.w3schools.com/CSS/css_pseudo_classes.asp | unknown | |
d9521 | train | Your thinking is correct. In some cases, for example, all the root entities reference one or two instances of another entity. It might be faster to do 2 or 3 small selects instead of a denormalized one (i.e. with joins)
There is a way to make this convenient in almost all cases: batch-size. If you set this attribute in both the entities and the collections to your usual page size, you'll get a constant number of small selects (one per entity type).
A: Select N+1 will become bigger and bigger problem once your application will have enough data in it.
Generally loading data is much cheaper then another trip to the data base. So if you can - you obviosly should avoid it.
As for loading additional data. If you are thinkg that you will load property values that are not going to be used you can use NHibernate 3.0 lazy loaded property feature.
So overall Select N+1 should be avoided.
A: I am not sure if you know about another option
In your mappings add
<list name="MyItems" batch-size="10">
or
<bag name="MyItems" batch-size="10">
If you have 10 Items, you only need two queries instead of 11. For 20 items, you need
three instead of 21 and so on. This will cut out about 90 percent of your queries. | unknown | |
d9522 | train | Use the NET Framework DateTime structure and its properties instead
If DateTime.Now.Day = 13 And DateTime.Now.Month = 9 Then
Console.WriteLine("Happy Birthday!")
End If
As hinted below in the comments, you are mixing calls to the VB6 compatibility library (Month(Now) from Microsoft.VisualBasic.dll) and calls to DateTime structure (Date alias), but the DateTime structure doesn't have a shared member called Day, instead it has a shared property named Now and from this property you can extract the Day value.
If you insist in using the Microsoft.VisualBasic compatibility library then your code should be
If Day(Now) = 13 And Month(Now) = 9 Then
..... | unknown | |
d9523 | train | use the id not the name of the input fields
e.g. var tipologia_auto = $("#tipologia_auto_1").val();
A: Ok, thank you! I need also to store these concatenated values into one field that will be saved into the MySql Database. | unknown | |
d9524 | train | Given class X and Y, what's the most idiomatic approach to creating instances of each other's class?
The most idiomatic approach, given your example code, is to not use type classes in the first place when they're not doing anything useful. Consider the types of the class functions:
class HasPoints a where
getPoints :: a -> Int
class (HasPoints a) => CardPlayer a where
getHand :: a -> Hand
viewHand :: a -> TurnIsComplete -> Hand
hasBlackjack :: a -> Bool
busts :: a -> Bool
What do they have in common? They all take exactly one value of the class parameter type as their first argument, so given such a value we can apply each function to it and get all the same information without needing to bother with a class constraint.
So if you want a nice, idiomatic DRY approach, consider this:
data CardPlayer a = CardPlayer
{ playerPoints :: Int
, hand :: Hand
, viewHand :: TurnIsComplete -> Hand
, hasBlackjack :: Bool
, busts :: Bool
, player :: a
}
data Dealer = Dealer
data Player = Player Cash
In this version, the types CardPlayer Player and CardPlayer Dealer are equivalent to the Player and Dealer types you had. The player record field here is used to get the data specialized to the kind of player, and functions that would have been polymorphic with a class constraint in yours can simply operate on values of type CardPlayer a.
Though perhaps it would make more sense for hasBlackjack and busts to be regular functions (like your default implementations), unless you really need to model players who are immune to the standard rules of Blackjack.
From this version, you can now define a HasPoints class alone if you have very different types that should be instances of it, though I'm skeptical of the utility of that, or you can apply the same transformation to get another layer:
data HasPoints a = HasPoints
{ points :: Int
, pointOwner :: a
}
However, this approach quickly becomes unwieldy the further you nest specializations like this.
I would suggest droping HasPoints entirely. It only has one function, which just extracts an Int, so any code that handles HasPoints instances generically might as well just use Ints and be done with it.
A: In general, it's impossible to declare all instances of a class to also be instances of another class without making type checking undecidable. So your proposed definition will only work with UndecidableInstances enabled:
{-# LANGUAGE FlexibleInstances, UndecidableInstances #-}
instance (CardPlayer a) => HasPoints a where
getPoints = getPoints . getHand
Although it's possible to go that route, I'd suggest refactoring the code as follows instead:
data Hand = ...
handPoints :: Hand -> Int
handPoints = ...
data Dealer = Dealer Hand
data Player = Player Hand Cash
class CardPlayer a where
getHand :: a -> Hand
...
instance CardPlayer Dealer where ...
instance CardPlayer Player where ...
playerPoints :: (CardPlayer a) => a -> Int
playerPoints = handPoints . getHand | unknown | |
d9525 | train | Part of the problem is that you are using formatted html text, which includes the "extra space."
For example, your first html text line includes <p> </p> tags.
This code creates two green-background labels, each the same width, each with no height constraint:
class ViewController: UIViewController, UIScrollViewDelegate {
override func viewDidLoad() {
super.viewDidLoad()
let firstLabel = UILabel()
firstLabel.backgroundColor = .green
firstLabel.numberOfLines = 0
firstLabel.translatesAutoresizingMaskIntoConstraints = false
let secondLabel = UILabel()
secondLabel.backgroundColor = .green
secondLabel.numberOfLines = 0
secondLabel.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(firstLabel)
view.addSubview(secondLabel)
let g = view.safeAreaLayoutGuide
NSLayoutConstraint.activate([
// first label 40-pts from top, 20-pts on each side
firstLabel.topAnchor.constraint(equalTo: g.topAnchor, constant: 40.0),
firstLabel.leadingAnchor.constraint(equalTo: g.leadingAnchor, constant: 20.0),
firstLabel.trailingAnchor.constraint(equalTo: g.trailingAnchor, constant: -20.0),
// second label 40-pts from bottom of first label, 20-pts on each side
secondLabel.topAnchor.constraint(equalTo: firstLabel.bottomAnchor, constant: 40.0),
secondLabel.leadingAnchor.constraint(equalTo: g.leadingAnchor, constant: 20.0),
secondLabel.trailingAnchor.constraint(equalTo: g.trailingAnchor, constant: -20.0),
])
var htmlTxt = "<p><font color=\"#cd1719\">V/. </font>…The Word of the Lord.<br><b></b><font color=\"#cd1719\">R/. </font><b>Thanks be to God.</b></p>"
if let attributedString = try? NSAttributedString(htmlString: htmlTxt, font: UIFont(name: "Avenir-Roman", size: 24.0), useDocumentFontSize: false) {
firstLabel.attributedText = attributedString
//cell.detailLbl.attributedText = attributedString
}
htmlTxt = "<font color=\"#cd1719\">V/. </font>…The Word of the Lord.<br><b></b><font color=\"#cd1719\">R/. </font><b>Thanks be to God.</b>"
if let attributedString = try? NSAttributedString(htmlString: htmlTxt, font: UIFont(name: "Avenir-Roman", size: 24.0), useDocumentFontSize: false) {
secondLabel.attributedText = attributedString
//cell.detailLbl.attributedText = attributedString
}
}
}
The output:
The difference between the two? For the second label, I removed the <p> </p> tags before processing the html with your extension.
Your second html text defines it as h6 ... here's the output with that string:
Again, the difference between the two is that I removed the h6 tag before processing the html.
You'll probably need to modify your extension to remove the paragraph tags, or set a paragraph style that would ignore them. | unknown | |
d9526 | train | I got it working. This is what I did:
In your custom template file /yourtheme/woocommerce/content-product.php you will change the a href.
Code that generated the new permalink (using the current selected category):
// HOOK FOR CORRECT ACTIVE SIDEBAR ELEMENT WHEN PRODUCT HAS MULTIPLE CATEGORIES
if(get_query_var('product_cat') == ""){
$product_categries = get_the_terms( $post->ID, 'product_cat' );
foreach ($product_categries as $category) {
$cur_cat = $category->slug;
}
$custom_cat = $cur_cat;
}else{
$custom_cat = get_query_var('product_cat');
}
$custom_permalink = get_permalink(5).$custom_cat."/".basename(get_permalink());
I also check if a category is set (because there is none if you are viewening "All Products", in this case I loop through the Products and get their category to use it in the permalink).
The get_permalink with the id 5 is basically my shop-page, so it stays dynamic when you change the permalink from your shop. Don't like hardcoded stuff here because it's already an ugly hack.
Place this code before the a href that wraps your Product, in my case this was on line 42 (Woocommerce V2.0.10).
Then change this a href from
<a href="<?php the_permalink(); ?>">
to
<a href="<?php echo $custom_permalink; ?>">
I hope this will help you when you face the same issue! | unknown | |
d9527 | train | I had this problem in rails. It was cors as mentioned above.
The rails server won't show logs so it looks like axios isn't sending the request at all.
Thankfully it's an easy fix.
For rails add this to your gemfile:
gem 'rack-cors'
Then add this to config/initializers/cors.rb
Rails.application.config.middleware.insert_before 0,Rack::Cors do
allow do
origins 'localhost:8080'
resource '*',
headers: :any,
methods: [:get, :post, :put, :patch, :delete, :options, :head]
end
end
Note: Update orgins to the origin of your front end app.
A: With the help from Soleno, I found out that it was AdBlock what was blocking the request. | unknown | |
d9528 | train | Interfaces in Go are very different from interfaces in Java.
In Java a class has to formally agree to implement an interface:
public class Foo implements iFoo
In Go a user type implements an interface by simply doing so.
A function or property can then define what is expected:
func DoSomething(r io.Reader) {
buf := make([]byte, 128)
n, err := r.Read(buf)
...
}
The DoSomething function can be passed anything that implements the Read function found in the io.Reader interface, without the thing knowing or caring about the interface. It is the responsibility of the caller to make sure it is passing in something that implements the interface. This is checked at compile time.
We can take this a step further. We can define our own interface:
type MyInterface interface {
io.Reader // Include Reader interface
Seek(int) error // Include my own function
}
func DoSomething(r MyInterface) {
buf := make([]byte, 128)
n, err := r.Read(buf)
...
}
Go is also different in that it doesn't have a class or object type. Any user declared type, whether it be based on an integer, string, struct, array, slice, channel, etc. can have methods attached to it.
Go also doesn't have typical class-like inheritance you're normally used to, but it does have a couple of things that are pretty close.
Redeclared type:
type Num int
func (n Num) Print() {
print(n)
}
type Number Num
func (n Number) Print() {
Num(n).Print()
}
Anonymous fields:
type Foo struct {
sync.Mutex
}
func main() {
f := Foo{}
f.Lock()
// ...
f.Unlock()
}
A: Polymorphism
Interfaces enable functions to have a 'placeholder' parameter which can take different structs as an argument. For example, if structs Man, Woman, Child implement interface Human, then a method with the parameter Human can take any of the structs Man, Woman, Child as an argument. Hence, the interface parameter can 'morph' into any struct passed as an argument as long as it implements all functions defined in the interface.
This is important because interfaces are the only way of achieving Polymorphism in Go, since it doesn't have inheritance. So if Man 'extended' Human (by having it as an anonymous field), any method that used Human as an argument, would not be able to take Man as an argument.
My confusion stemmed from the fact that inheritance is also a way of achieving Polymorphism in Java, and I assumed that was the case here as well. I stand corrected!
A: If supertype X is an interface, whoever is maintaining the code knows at once that it has no method implementations. If supertype Y is an abstract class, whoever is maintaining the code has to check whether there are method implementations. So it's a documentation/maintenance/readability thing.
A: Classes can inherit and implement from multiple class files.
Unless I misinterpreted:
public class MyClass extends MySuperClass implements MyInterface, MySecondInterface
The point of interfaces is to allow for a completely abstract class. So abstract that there isn't a single method defined.
I would use an interface when I need to create several abstract classes with the same basic structure. I would then be able to create instances of classes which extend the abstract class, which in turn would implement the interface.
This is done with the interface java.util.Collection and some classes like java.util.ArrayList and java.util.Stack implement that interface. This way you can store all kinds of lists' items in a Collection. This is why ArrayList has a method to addAll(Collection<? extends E> c).
You could say it is like being backwards compatible with simpler objects. | unknown | |
d9529 | train | I clear the GL_COLOR_BUFFER_BIT only when initializing the window
That's your problem right there. It's idiomatic in OpenGL to always start with a clear operation of the main framebuffer color bits. That is, because you don't know the state of your window main framebuffer when the operating system is asking for a redraw. For all you know it could have been all replaced with cat pictures in the background without your program knowing it. Seriously: If you have a cat video running and the OS felt the need to rearrange your window's main framebuffer memory this is what you might end up with.
Is there a way to do what i want without having to store all the point coordinates and then clearing the whole screen and redrawing only the lines?
For all intents and purposes: No. In theory one could come up with a contraption made out of a convoluted series of stencil buffer operations to implement that, but this would be barking up a very wrong tree.
Here's something for you to try out: Draw a bunch of triangles like you do, then resize your window down so there nothing remains, then resize it back to its original size… you see where the problem? There's a way to address this particular problem, but that's not what you should do here.
The correct thing is to redraw everything. If you feel that that's to slow you have to optimize your drawing process. On current generation hardware it's possible to churn out on the order of 100 million triangles per second. | unknown | |
d9530 | train | You could do it inline when building the string.
$(function() {
var people = [];
$.getJSON('data2.json', function(data) {
$.each(data, function(i, f) {
var tblRow = "" + "" +
f.name + "" + "" +
f.title + "" + "" +
f.company + "" + "" + "" +
(f.exclude_email == "No" ? '' : f.email) + "" + "" + "" + "" +
f.comment + "" + "" + ""
$(tblRow).appendTo("#userdata tbody");
if (f.exclude_email == "No") this.hide(email);
});
});
});
A: This worked! Thank you!
$(function() {
var people = [];
$.getJSON('data2.json', function(data) {
$.each(data, function(i, f) {
var tblRow = "" + "" + f.name + "" + "" + f.title + "" + "" + f.company + "" +
"" + "" + (f.exclude_email == "Yes" ? '' : f.email) + "" + "" + "" + "" + f.comment + "" + "" + ""
$(tblRow).appendTo("#userdata tbody");
});
});
}); | unknown | |
d9531 | train | I think this could help you recognising bluetooth devices and managing them.
[BroadcastReceiver]
public class AndroidBluetooth : BroadcastReceiver
{
private static BluetoothDevice _bluetoothDevice;
private readonly BluetoothAdapter _bluetoothAdapter;
public BluetoothSocket _bluetoothSocket;
public readonly IntentFilter _intentFilter;
public AndroidBluetooth()
{
_bluetoothAdapter = BluetoothAdapter.DefaultAdapter;
_intentFilter = new IntentFilter();
_intentFilter.AddAction(BluetoothDevice.ActionFound);
_intentFilter.AddAction(BluetoothDevice.ActionNameChanged);
_intentFilter.AddAction(BluetoothDevice.ActionBondStateChanged);
_intentFilter.AddAction(BluetoothDevice.ActionPairingRequest);
_intentFilter.AddAction(BluetoothDevice.ActionAclConnected);
_intentFilter.AddAction(BluetoothDevice.ActionAclDisconnected);
_intentFilter.AddAction(BluetoothDevice.ActionAclDisconnectRequested);
_intentFilter.AddAction(BluetoothAdapter.ActionDiscoveryStarted);
_intentFilter.AddAction(BluetoothAdapter.ActionDiscoveryFinished);
_intentFilter.AddAction(BluetoothAdapter.ActionRequestEnable);
Xamarin.Forms.Forms.Context.RegisterReceiver(this, _intentFilter);
}
public override void OnReceive(Context context, Intent intent)
{
try
{
BluetoothDevice item = null;
string action = intent.Action;
switch (action)
{
case BluetoothDevice.ActionPairingRequest:
try
{
//You can set device pin by default to avoid asking.
int pin = intent.GetIntExtra(BluetoothDevice.ExtraPairingKey, 1234);
_bluetoothDevice.SetPin(ASCIIEncoding.UTF8.GetBytes(pin.ToString()));
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine(e.ToString());
}
break;
case BluetoothDevice.ActionBondStateChanged:
break;
case BluetoothDevice.ActionFound:
//Bluetooth device found
/*/
/ Here you can make a list for preparing popup
/*/
break;
case BluetoothDevice.ActionNameChanged:
break;
case BluetoothAdapter.ActionDiscoveryFinished:
//Occurs when scan is finished
/*/
/ Launch desired popup
/*/
break;
case BluetoothDevice.ActionAclConnected:
//Bluettoth device is connected
break;
case BluetoothDevice.ActionAclDisconnected:
//Device is disconnected
break;
case BluetoothDevice.ActionAclDisconnectRequested:
break;
}
}
catch (Exception ex)
{
Logger.WriteException(ex);
System.Diagnostics.Debug.WriteLine(ex.ToString());
}
}
} | unknown | |
d9532 | train | Maybe you would like to try something like this
<script>
// Sending and receiving data in JSON format using POST mothod
//
xhr = new XMLHttpRequest();
var url = "http://your.url.com/streams/1/sign";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var json = JSON.parse(xhr.responseText);
console.log(json.username + ", " + json.password)
}
}
var data = JSON.stringify({"username":"YOURUSERHERE","password":"YOURURLHERE"});
xhr.send(data);
</script>
But I really do not know how to print out answer in php from their server after you post it.
I just know how to send it. | unknown | |
d9533 | train | On my machine if I run "Node Command Prompt" a 2nd time, it opens a 2nd window.
If you want to do the same thing, the shortcut that Node installs just runs:
C:\Windows\System32\cmd.exe /k "C:\Program Files\nodejs\nodevars.bat"
so you should be able to run that, assuming your node install location is Program Files\nodejs.
A: Open your environment variables config, and add these 2 directories to Path variable.
C:\Program Files\nodejs\
C:\Users\your_user_name\AppData\Roaming\npm
And then every time you open a regular cmd window, the node.js commands will be available to you. | unknown | |
d9534 | train | call function isFeatureEnabled inside an async function during mount (before/after your wish)
example -
export const isFeatureEnabled = async (nameOfTheFeature) => {
return new Promise((resolve) => {
bulletTrain.init({
environmentID: BULLET_TRAIN_ENV_ID
});
bulletTrain.hasFeature(nameOfTheFeature)
.then((featureFlag) => {
if (featureFlag[nameOfTheFeature].enabled) {
resolve(true);
}
})
.catch(err => resolve(false));
});
}
...
componentDidMount() {
this.checEnabled();
}
...
const checkEnabled = async () => {
const flag = await isFeatureEnabled('feature1');
this.setState({f1enabled: flag});
}
...
render() {
return (<div>{this.state.f1enabled ? <p>feature1 is enabled</p> : null}</div>)
}
If isFeatureEnabled is in the same file keep it outside class component or else keep it in another file and export the function.
A: I would suggest you not to use await keyword in render instead use componentDidMount and constructor for this and use state object to check:
constructor(props){
super(props);
this.state = { isFeatEnabled: false };
}
componentDidMount(){
this.setState({isFeatEnabled:isFeatureEnabled('feature1')})
}
Now in the render:
render() {
return (<div>{this.state.isFeatEnabled && <p>feature1 is enabled</p>}</div>)
};
And remove the async from the method.
A: You can't use promise at there, the proper way:
import React, { useEffect, useState } from 'react'
import bulletTrain from '../somewhere'
import BULLET_TRAIN_ENV_ID from '../somewhere'
export default function featureComponent({ featureName }) {
const [featureEnabled, setFeatureEnabled] = useState(false)
useEffect(() => {
bulletTrain.init({
environmentID: BULLET_TRAIN_ENV_ID
})
bulletTrain
.hasFeature(featureName)
.then(featureFlag => {
if (featureFlag[featureName].enabled) {
setFeatureEnabled(true)
}
})
.catch(err => setFeatureEnabled(false))
}, [featureName])
return <div>{featureEnabled && <p>{featureName} is enabled</p>}</div>
}
Append isFeatureEnabled function re-use answer below:
import React, { useEffect, useState } from 'react'
import isFeatureEnabled from '../somewhere'
export default function featureComponent({ featureName }) {
const [featureEnabled, setFeatureEnabled] = useState(false)
useEffect(() => {
const checkAndSetEnabled = async () => {
const enabled = await isFeatureEnabled(featureName)
setFeatureEnabled(enabled)
}
checkAndSetEnabled()
}, [featureName])
return <div>{featureEnabled && <p>{featureName} is enabled</p>}</div>
} | unknown | |
d9535 | train | /apache-sermfino_conf/cherry.jks" />
</sec:keyManagers>
<sec:trustManagers>
<sec:keyStore type="JKS" password="password"
file="A:/apache-ser/truststore.jks" />
</sec:trustManagers>
<sec:cipherSuitesFilter>
<!-- these filters ensure that a ciphersuite with export-suitable or
null encryption is used, but exclude anonymous Diffie-Hellman key change
as this is vulnerable to man-in-the-middle attacks -->
<sec:include>.*_EXPORT_.*</sec:include>
<sec:include>.*_EXPORT1024_.*</sec:include>
<sec:include>.*_WITH_DES_.*</sec:include>
<sec:include>.*_WITH_AES_.*</sec:include>
<sec:include>.*_WITH_NULL_.*</sec:include>
<sec:exclude>.*_DH_anon_.*</sec:exclude>
</sec:cipherSuitesFilter>
</http:tlsClientParameters>
<http:client AutoRedirect="true" Connection="Keep-Alive" />
</http:conduit>
===============================================================================
<wsdl:portType name="ServicesPortType">
<wsdl:operation name="PostXml">
<wsdl:input message="tns:PostXml" />
<wsdl:output message="tns:PostXml" />
</wsdl:operation>
</wsdl:portType>
<wsdl:binding name="ServicesSoap12Binding" type="tns:ServicesPortType">
<soap12:binding style="document"
transport="http://schemas.xmlsoap.org/soap/http" />
<wsdl:operation name="PostXml">
<soap12:operation soapAction="PostXml" style="document" />
<wsdl:input>
<soap12:body use="literal" />
</wsdl:input>
<wsdl:output>
<soap12:body use="literal" />
</wsdl:output>
</wsdl:operation>
</wsdl:binding>
<wsdl:service name="ServicesPortTypeService">
<wsdl:port binding="tns:ServicesSoap12Binding" name="ServicesSoap12Endpoint">
<soap12:address location="http://localhost:9000/PostXml" />
</wsdl:port>
</wsdl:service>
A: The first one configuration is for the http client not for the server side.
You can find the configuration example here[1]
[1]http://cxf.apache.org/docs/jetty-configuration.html
A: I was able to configure apache-camel-2.19.4 with camel-config.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:camel="http://camel.apache.org/schema/spring"
xmlns:cxf="http://camel.apache.org/schema/cxf" xmlns:context="http://www.springframework.org/schema/context"
xmlns:httpj="http://cxf.apache.org/transports/http-jetty/configuration"
xmlns:sec="http://cxf.apache.org/configuration/security" xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:cxfcore="http://cxf.apache.org/core"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd
http://camel.apache.org/schema/cxf http://camel.apache.org/schema/cxf/camel-cxf.xsd
http://cxf.apache.org/configuration/security http://cxf.apache.org/schemas/configuration/security.xsd
http://cxf.apache.org/transports/http/configuration http://cxf.apache.org/schemas/configuration/http-conf.xsd
http://cxf.apache.org/transports/http-jetty/configuration http://cxf.apache.org/schemas/configuration/http-jetty.xsd
http://cxf.apache.org/core http://cxf.apache.org/schemas/core.xsd
">
<cxf:cxfEndpoint id="my-endpoint-http"
address="http://localhost:8080/test"
endpointName="tns:endpointName1" serviceName="tns:endpointServiceName1"
wsdlURL="myService.wsdl" xmlns:tns="myServiceWsdlNamespace">
<cxf:properties>
<entry key="allowStreaming" value="true" />
<entry key="autoRewriteSoapAddressForAllServices" value="true" />
</cxf:properties>
</cxf:cxfEndpoint>
<cxf:cxfEndpoint id="my-endpoint-https"
address="https://localhost:8443/test"
endpointName="tns:endpointName1" serviceName="tns:endpointServiceName1"
wsdlURL="myService.wsdl" xmlns:tns="myServiceWsdlNamespace">
<cxf:properties>
<entry key="allowStreaming" value="true" />
<entry key="autoRewriteSoapAddressForAllServices" value="true" />
</cxf:properties>
</cxf:cxfEndpoint>
<camelContext xmlns="http://camel.apache.org/schema/spring">
<route id="my-endpoint-http-route" streamCache="true">
<from uri="cxf:bean:my-endpoint-http?dataFormat=MESSAGE" />
<to uri="direct:myServiceDirect" />
</route>
<route id="my-endpoint-https-route" streamCache="true">
<from uri="cxf:bean:my-endpoint-https?dataFormat=MESSAGE" />
<to uri="direct:myServiceDirect" />
</route>
<route id="all" streamCache="true">
<from uri="direct:myServiceDirect" />
<log message="headers1=${headers}" />
</route>
</camelContext>
<cxfcore:bus/>
<httpj:engine-factory bus="cxf">
<httpj:engine port="8443">
<httpj:tlsServerParameters secureSocketProtocol="TLSv1">
<sec:keyManagers keyPassword="skpass">
<sec:keyStore password="changeit" file="src/test/resources/certificate-stores/localhost-keystore.jks" />
</sec:keyManagers>
<!--
<sec:trustManagers>
- <sec:keyStore resource="certs/serviceKeystore.jks" password="sspass" type="JKS"/> -
<sec:keyStore password="changeit" file="src/main/resources/certificate-stores/cacerts" />
</sec:trustManagers>
-->
<sec:cipherSuitesFilter>
<sec:include>.*_WITH_3DES_.*</sec:include>
<sec:include>.*_WITH_DES_.*</sec:include>
<sec:exclude>.*_WITH_NULL_.*</sec:exclude>
<sec:exclude>.*_DH_anon_.*</sec:exclude>
</sec:cipherSuitesFilter>
<!-- <sec:clientAuthentication want="true" required="false"/> -->
</httpj:tlsServerParameters>
</httpj:engine>
</httpj:engine-factory>
</beans>
With this you should be able to access:
*
*http://localhost:8080/test?wsdl
*https://localhost:8443/test?wsdl
The file src/test/resources/certificate-stores/localhost-keystore.jks should contain a generated key pair (use KeyStoreExplorer) and the pair saved with keyPassword(skpass) key password and password(changeit) for the keystore file password. | unknown | |
d9536 | train | To find the position of a pixel is a simple concept with a complex execution. I've written some code here that takes a BufferedImage and searches through it for a pixel of a specific color.
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import java.io.IOException;
public class pixelSearch {
public static void main(String[] args) {
//I don't know where you're getting your image but i'll get one from file
File image = new File("image.bmp");
try {
BufferedImage imageToSearch = ImageIO.read(image);
Color colorToFind = new Color(255,255,255); //define color to search for with RGB vals 255,255,255
//for more information on constructing colors look here: http://docs.oracle.com/javase/7/docs/api/java/awt/Color.html
int[] pixelCoordinates = pSearch( colorToFind, imageToSearch ); //search for the pixel
System.out.println("Found pixel at (" + pixelCoordinates[0] + "," + pixelCoordinates[1] + ")."); //display coordinates
} catch (IOException e) {
System.out.println(e.toString());
}
}
private static int[] pSearch ( Color c, BufferedImage pic ){
int cVal = c.getRGB(); //get integer value of color we are trying to find
int x1 = 0;
int y1 = 0;
int x2 = pic.getWidth();
int y2 = pic.getHeight();
int[] XArray = new int[x2-x1+1]; //create an array to hold all X coordinates in image
int iterator = 0;
while (iterator <= x2) {
XArray[iterator] = x1 + iterator;
iterator++;
}
int [] YArray = new int[y2-y1+1]; //create an array to hold all Y coordinates in image
iterator = 0;
while (iterator <= y2) {
YArray[iterator] = y1 + iterator;
iterator++;
}
//next we iterate throug all the possible coordinates to check each pixel
for (int yVal : YArray) {
for (int xVal : XArray) {
int color = pic.getRGB(xVal, yVal); //get the color of pixel at coords (xVal, yVal)
if (color == cVal) { //if the color is equal to the one we inputted to the function
int[] cPos = {xVal, yVal}; //store the coordinates
return cPos; //return the coordinates
}
}
}
int[] returnVal = {-1,-1}; //if we didn't find it return -1, -1
return returnVal;
}
} | unknown | |
d9537 | train | You'll need to calculate this yourself. Here's a quick way to see how long it takes for the response to arrive:
private long mRequestStartTime;
public void performRequest()
{
mRequestStartTime = System.currentTimeMillis(); // set the request start time just before you send the request.
JsonObjectRequest request = new JsonObjectRequest(URL, PARAMS,
new Response.Listener<JSONObject>()
{
@Override
public void onResponse(JSONObject response)
{
// calculate the duration in milliseconds
long totalRequestTime = System.currentTimeMillis() - mRequestStartTime;
}
},
new Response.ErrorListener()
{
@Override
public void onErrorResponse(VolleyError error)
{
long totalRequestTime = System.currentTimeMillis() - mRequestStartTime;
}
});
requestQueue.add(request);
} | unknown | |
d9538 | train | This is by design. The winrt::array_view is an adapter that tells the underlying API that the bound array or storage has the appropriate binary layout to receive the data efficiently (typically via a memcpy) without some kind of transformation. std::vector<bool> does not provide that guarantee and thus cannot be used. You might want to try something else like a std::array or some other contiguous container.
A: Ugly workaround instead of using vector<bool>:
int32_t buttons = rawController.ButtonCount();
int32_t switches = rawController.SwitchCount();
int32_t axis = rawController.AxisCount();
std::unique_ptr<bool[]> buttonsArray = std::make_unique<bool[]>(buttons);
std::vector<GameControllerSwitchPosition> switchesArray(switches);
std::vector<double> axisArray(axis);
uint64_t timestamp = rawController.GetCurrentReading(winrt::array_view<bool>(buttonsArray.get(), buttonsArray.get() + buttons), switchesArray, axisArray);
A: Each element in std::vector<bool> occupies a single bit instead of sizeof(bool) bytes.It does not necessarily store its elements as a contiguous array and thus doesn't contain data() method.I have a working code, but it is not the optimal solution.You can try to create bool array by using bool b[] method.
bool buttonsArray[]{ rawController.ButtonCount(), false };
std::vector<GameControllerSwitchPosition> switchesArray(rawController.SwitchCount(), GameControllerSwitchPosition::Center);
std::vector<double> axisArray(rawController.AxisCount(), 0.0);
uint64_t timestamp = rawController.GetCurrentReading(buttonsArray, switchesArray, axisArray); | unknown | |
d9539 | train | The client module is not completely loaded when the extension try to load the client module.; Execution of client is occurred twice (Watch the output carefully).
So Test in client.py and Test in the extension module are referencing different objects.
You can workaround this by extracting classes in a separated module. (Say common.py) And import common in both client.py and extension module.
See a demo. | unknown | |
d9540 | train | I haven't solved the issue using my own code.The plugin suggested by Minzkraut (thank you!) is just too cheap, powerful and easy to use.
However the reason for my problem might have just been not setting Write access to External (SDCard) in the Player settings, but I am not sure about that. | unknown | |
d9541 | train | It is quite simple to do with a single query. As a bonus, the query will be updatable, not duplicated, and simple to use:
SELECT mammals.ID, mammals.Sex, mammals.id_code, mammals.date_recorded
FROM mammals
WHERE mammals.id_code In
(select id_code from
(select distinct id_code, sex from [mammals]) a
group by id_code
having count(*)>1
);
The reason why you see a sub-query inside a sub-query is because Access does not support COUNT(DISTINCT). With any other "normal" database you would write:
SELECT mammals.ID, mammals.Sex, mammals.id_code, mammals.date_recorded
FROM mammals
WHERE mammals.id_code In
(select id_code
from [mammals]
group by id_code
having count(DISTINCT Sex)>1
); | unknown | |
d9542 | train | Problem is, you set overflow: hidden on a parent container:
<div class="socialmediabuttons">
....
</div>
Remove that style and the comment box should reappear. Note that you need to change other styles as well as it will break the hairlines around the social media buttons (but it is doable).
EDIT
Try something along the lines of:
.socialmediabuttons {
border-bottom: 1px solid #CCCCCC;
border-top: 1px solid #CCCCCC;
+ height: 26px;
margin-bottom: 25px !important;
margin-left: 20px;
- overflow: hidden;
padding: 5px 0 3px;
} | unknown | |
d9543 | train | Probably you didn't link with the library. You should add this -lexpat to the compiler`s command line. For example:
g++ main.cc -lexpat -o exe
A more advanced (and more easy to use, when you get up to speed) option would be to use pkg-config as e.g. $(pkg-config --libs expat). | unknown | |
d9544 | train | Gunicorn doesn't recognize the argument --log-file-. The Procfile you shared with us doesn't contain anything like that, but I'm going to assume that it actually contains something like
web: gunicorn tutorial_two.wsgi --log-file-
since the error message specifically mentions that argument and this is almost a correct Procfile for Gunicorn. The problem is that --log-file should get an argument -. Those things shouldn't be attached together.
Modify your Procfile to add a space, e.g.
web: gunicorn tutorial_two.wsgi --log-file -
A: Well, this is rather implied. The gunicorn program takes the --log-file - argument given in the Procfile. May be something like this is the right solution.
web: gunicorn tutorial_two.wsgi; --log-file - | unknown | |
d9545 | train | In order to geocode any phisical address, or get its coordinates , you should use a geocoding API, being google maps api v3 the most popular, which by the way gives you a free starting point of up to 2500 daily requests.
There is a bunch of documentation and starting guides, the best are the google maps's own.
Of course you can geocode on PHP or Javascript. Its really easy.
A: As other answer mentioned it is possible using google maps api, you can read more and get your own API KEY (More info and Get api key).
What you need is API key from google. This will help you fetching coordinates from given address.
I have made a little demonstration how it works it might be useful for other SO users.
By using following address
https://maps.googleapis.com/maps/api/geocode/json?address=YOUR_ADDRESS&key=YOUR_API_KEY
It will return you JSON formatted results with coordinates.
Now we need to build a tiny address form and pass it it to PHP script to return us the results
HTML Address form
<form action="index.php" method="post">
Enter Address:<br>
<input type="text" name="address">
<input type="submit">
</form>
PHP code
if (isset($_POST["address"]))
{
$addressInput = $_POST["address"];
$address = str_replace(" ", "+", $addressInput);
} else
{
// stack-overflow office address as default
$address = "110+William+St,+28th+Floor+New+York,+NY+10038";
}
echo "Latitude and Longitude for address : " . str_replace("+", " ", $address) . '<br>';
$json = file_get_contents('https://maps.googleapis.com/maps/api/geocode/json?address=' . $address . '&key=PUT_YOUR_OWN_API_KEY');
$data = json_decode($json, true);
//var_dump($data);
$getLat = $data['results'][0]['geometry']['location']['lat'];
$getLng = $data['results'][0]['geometry']['location']['lng'];
echo 'latitude ' . $getLat . ', longitude ' . $getLng;
The above working code can be tested on this link.
Moving theses data to mysql database or what ever you want to use it for, is left to you.
A: You'll probably use JavaScript for getting location of the user; not PHP. You can use HTML5 Geolocation for the purpose.
If you need to map the users location, pass the coordinates obtained using the HTML5 Geolocation API to Google Maps.
You may also need Modernizr to determine your users browser supports HTML5 Geolocation API. | unknown | |
d9546 | train | Ohai!
I think you actually want to use the PowershellOut Mixin found here in the Powershell cookbook.
Chef resources rarely return values, but that's what heavy-weight resources are for!
If you have the powershell cookbook, you can do this:
include Chef::Mixin::PowershellOut
cmd = powershell_out!('command')
cmd.stdout #=> ...
cmd.stderr #=> ...
A: We actually came across this exact issue and solved it by writing our own Mixlib to get the exit code from a powershell script. Example:
# get the result object (and exit code) from the code execution:
result = Mixlibrary::Core::Shell.windows_script_out(:powershell, mycode)
exit_status = result.exitstatus
@carpNick is planning on open-sourcing this perhaps as soon as this week....at the moment it only handles powershell, but we plan on implementing support for other types as well (bash, win modules, etc.) -- which should be fairly easy to add on support for others.
We are currently using it in-house and it works great. I'm sure Chef will want to review Nick's excellent code once he gets it out there. We are just waiting on legal to tell us what open-source license to use.
Ask Nick for more details... @carpnick | https://github.com/carpnick | unknown | |
d9547 | train | I do this:
use MooseX::Declare;
my $class = class {
has 'foo' => (is => 'ro', isa => 'Str', required => 1);
method bar() {
say "Hello, world; foo is ", $self->foo;
}
};
Then you can use $class like any other metaclass:
my $instance = $class->name->new( foo => 'foo bar' );
$instance->foo; # foo-bar
$instance->bar; # Hello, world; foo is foo-bar
etc.
If you want to dynamically generate classes at runtime, you need to create the proper metaclass, instantiate it, and then use the metaclass instance to generate instances. Basic OO. Class::MOP handles all the details for you:
my $class = Class::MOP::Class->create_anon_class;
$class->add_method( foo => sub { say "Hello from foo" } );
my $instance = $class->new_object;
...
If you want to do it yourself so that you can waste your time debugging something, perhaps try:
sub generate_class_name {
state $i = 0;
return '__ANON__::'. $i++;
}
my $classname = generate_class_name();
eval qq{
package $classname;
sub new { my \$class = shift; bless {} => \$class }
...
};
my $instance = $classname->new;
A: Here is a version which works:
#!/usr/bin/perl
use strict;
use warnings;
my $class = 'Frew';
{
no strict 'refs';
*{ "${class}::INC" } = sub {
my ($self, $req) = @_;
return unless $req eq $class;
my $data = qq{
package $class;
sub foo { print "test!\n" };
1;
};
open my $fh, '<', \$data;
return $fh;
};
}
my $foo = bless { }, $class;
unshift @INC, $foo;
require $class;
$class->foo;
The @INC hook gets the name of the file (or string passed to require) as the second argument, and it gets called every time there is a require or use. So you have to check to make sure we're trying to load $classname and ignore all other cases, in which case perl continues down along @INC. Alternatively, you can put the hook at the end of @INC. This was the cause of your recursion errors.
ETA: IMHO, a much better way to achieve this would be to simply build the symbol table dynamically, rather than generating code as a string. For example:
no strict 'refs';
*{ "${class}::foo" } = sub { print "test!\n" };
*{ "${class}::new" } = sub { return bless { }, $class };
my $foo = $class->new;
$foo->foo;
No use or require is necessary, nor messing with evil @INC hooks.
A: For a simple example of how to do this, read the source of Class::Struct.
However, if I needed the ability to dynamically build classes for some production code, I'd look at MooseX::Declare, as suggested by jrockway.
A: A Perl class is little more than a data structure (usually a hashref)
that has been blessed into a package in which one or more class
methods are defined.
It is certainly possible to define multiple package namespaces in one
file; I don't see why this wouldn't be possible in an eval construct
that is compiled at run-time (see perlfunc for the two different
eval forms).
#!/usr/bin/perl
use 5.010;
use strict;
use warnings;
use Data::Dumper;
eval q[
package Foo;
sub new {
my ( $class, %args ) = @_;
my $self = bless { %args }, $class;
return $self;
}
1;
];
die $@ if $@;
my $foo = Foo->new(bar => 1, baz => 2) or die;
say Dumper $foo; | unknown | |
d9548 | train | You should use your artifactid, rather than hard-coding the file name.
<build>
<finalName>${project.artifactId}</finalName>
</build>
A: Just add this to your pom.xml:
<build>
<finalName>TataWeb</finalName>
</build>
A: well, its not the Maven Way. Maven does have a version attribute.. use it.
A: You can avoid the version appeneded to the war file name by doing a "clean compile package" instead of "clean install". | unknown | |
d9549 | train | If you're going to use jQuery UI, why not let it help you.
Example: https://jsfiddle.net/Twisty/wfqv3orm/
HTML
<div id="dialog1">
</div>
JavaScript
$(function() {
var dialog1 = $("#dialog1");
dialog1.empty();
var header = $("<h5>", {
class: "dialog-header"
}).text("By buffer").appendTo(dialog1);
$("<button>", {
id: "toggle-buffer-btn",
class: "btn btn-default btn-sm"
}).appendTo(dialog1);
dialog1.find("button").append($("<i>", {
id: "toggle-icon",
class: "fa fa-circle"
}));
$("<input>", {
type: "text",
id: "radius",
class: 'btn btn-default btn-sm'
}).prop('disabled', true).appendTo(dialog1);
$("<span>", {
id: "help-label",
style: "margin-bottom: 2em;"
}).html("Click and drag mouse to create buffer").appendTo(dialog1);
$("<input>", {
type: "checkbox",
id: 'polygon-buffer'
}).appendTo(dialog1);
$("<label>", {
id: "polygon-buffer-label",
for: "polygon-buffer"
}).html("By polygon").appendTo(dialog1);
dialog1.controlgroup();
var val;
});
Little bit faster to just build and append elements all at once in my opinion. | unknown | |
d9550 | train | You have to use @media queries. So let's say you have a <div> that should take up only 50% of the web page and then you need to show it full width once it enters mobile phone, say 640px width:
div {
width: 50%;
}
@media screen and (max-width: 640px) {
div {
width: 100%;
}
}
A: You can do it with @media queries, e.g.:
div {
width: 50%;
height: 100px;
border: 1px solid;
}
@media (max-width: 568px) { /* adjust to your needs */
div {width: 100%}
}
<div></div>
A: you must use @media for that like this :
@media screen and (min-width: 769px) {
/* STYLES HERE */
}
@media screen and (min-device-width: 481px) and (max-device-width: 768px) {
/* STYLES HERE */
}
@media only screen and (max-device-width: 480px) {
/* STYLES HERE */
} | unknown | |
d9551 | train | Create an wrapper class based on IFilterProvider that returns the global FilterProviders.Providers.GetFilters() result, like this:
public class FilterProvider
: IFilterProvider
{
#region IFilterProvider Members
public IEnumerable<Filter> GetFilters(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
{
return FilterProviders.Providers.GetFilters(controllerContext, actionDescriptor);
}
#endregion
}
Then, adjust the constructor in your classes that require the dependency.
public class MyBusinessClass
: IMyBusinessClass
{
public MyBusinessClass(
IFilterProvider filterProvider
)
{
if (filterProvider == null)
throw new ArgumentNullException("filterProvider");
this.filterProvider = filterProvider;
}
protected readonly IFilterProvider filterProvider;
public IEnumerable<AuthorizeAttribute> GetAuthorizeAttributes(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
{
var filters = filterProvider.GetFilters(controllerContext, actionDescriptor);
return filters
.Where(f => typeof(AuthorizeAttribute).IsAssignableFrom(f.Instance.GetType()))
.Select(f => f.Instance as AuthorizeAttribute);
}
}
Next, configure your DI container to use FilterProvider concrete type as the default.
container.Configure(x => x
.For<IFilterProvider>()
.Use<FilterProvider>()
);
If you need to override the default and provide your own IFilterProvider, now it is just a matter of creating a new concrete type based on IFilterProvider and swapping what is registered in the DI container.
//container.Configure(x => x
// .For<IFilterProvider>()
// .Use<FilterProvider>()
//);
container.Configure(x => x
.For<IFilterProvider>()
.Use<NewFilterProvider>()
);
Most importantly, there is no service locator anywhere in this pattern. | unknown | |
d9552 | train | Please change your column names in database L/C from to LC_Fromand L/C T0 = LC_To
I thing then i would not get any error .
private void button1_Click(object sender, EventArgs e)
{
con=new SqlConnection(@"Data Source=sqlserver;Initial Catalog=Position_List;Integrated Security=False;User ID=administrator;Password=;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False");
con.Open();
cmd = new SqlCommand("INSERT INTO Table (Name, Dwt, Built, Position, Area, LC_from, LC_to, Contact) Values (@Name, @Dwt, @Built, @Position, @Area, @LC_from, @LC_to, @Contact)", con);
cmd.Parameters.Add("@Name", nametxt.Text);
cmd.Parameters.Add("@Dwt", dwttxt.Text);
cmd.Parameters.Add("@Built", builttxt.Text);
cmd.Parameters.Add("@Position", postxt.Text);
cmd.Parameters.Add("@Area", areatxt.Text);
cmd.Parameters.Add("@LC_from", lcftxt.Text);
cmd.Parameters.Add("@LC_to", lcttxt.Text);
cmd.Parameters.Add("@Contact", contxt.Text);
cmd.ExecuteNonQuery();
con.Close();
}
A: as adviced in comments and other answers,i also recommend you to change columnnames with /'s as it will give further unexpected erros.Though i can give another quick fix,ie In SQL Server, identifiers can be delimited using square brackets, e.g.
SELECT [table/1] ...
in you case,pls try using
cmd = new SqlCommand("INSERT INTO Table (Name, Dwt, Built, Position, Area, [L/C from], [L/C to], Contact) Values (@Name, @Dwt, @Built, @Position, @Area, @L/C from, @L/C to, @Contact)", con);
cmd.Parameters.Add("@Name", nametxt.Text);
hope this helps. | unknown | |
d9553 | train | maybe you mean this
char const * const words = "dog";
for (int i = 0; i < strlen(words); ++i)
{
char c = words[i];
}
now of course in c++ code you should realy be using std::string
A: You are consistently missing the second *.
Ignoring the const stuff, you are declaring a char** word, which is a pointer to a pointer to a single char. You won't get a word or many words into that, and casting just hides the problem.
To get "dog" accessible through such a pointer, you need to take an extra step; make a variable that contains "dog", and put its address into your word.
A: Short answer:
Your program has undefined behavior. To remove the undefined behavior use:
char const * word = "dog";
for (int i = 0; i < std::strlen(word); ++i)
{
char c = word[i];
}
or
char const * word = dog;
char const * const *words = &word;
for (int i = 0; i < std::strlen(*words); ++i)
{
char c = (*words)[i];
}
Long answer:
You are forcing a cast from char const* to char const* const* and treating the location of memory that was holding chars as though it is holding char const*s. Not only that, you are accessing memory using an out of bounds index.
Let's say the string "dog" is held in some memory location as (it takes four bytes that includes the null character) and give it an address.
a1
|
v
+---+---+---+----+
| d | o | g | \0 |
+---+---+---+----+
You can treat the address a1 as the value of a pointer of type char const*. That won't be a problem at all. However, by using:
words = (char const * const *)"dog";
You are treating a1 as though it is holding objects of type char const*.
Let's assume for a moment that you have a machine that uses 4 bytes for a pointer and uses little endian for pointers.
words[0] evaluates to a pointer. Its value will be:
'd' in decimal +
256 * 'o' in decimal +
256*256 * 'g' in decimal +
256*256*256 * '\0' in decimal.
After that, you truncate that value to char, which will give you back the character d, which is not too bad. The fun part (undefined behavior) begins when you access words[1].
words[1] is same as *(words+1). words+1 evaluates to a pointer whose value is the address a2.
a2
|
v
+---+---+---+----+
| d | o | g | \0 |
+---+---+---+----+
As you can see, it points to memory that is beyond what the compiler allocated for you. Dereferencing that pointer is cause for undefined behavior. | unknown | |
d9554 | train | There is a developer guide showing how to implement tabbed activities/fragments http://developer.android.com/guide/topics/ui/actionbar.html
It's very important to follow new solution, because the method using TabActivity is deprecated since API level 13. | unknown | |
d9555 | train | Your background image doesn't have an alpha channel. This makes the PHP GD library do all of it's copying operations without using an alpha channel, instead just setting each pixel to be fully opaque or transparent, which is not what you want.
The simplest solution to this is to create a new image of the same size as the background that has an alpha channel, and then copy both the background and face into that one.
$baseImage = imagecreatefrompng("../../var/tmp/background.png");
$topImage = imagecreatefrompng("../../var/tmp/face.png");
// Get image dimensions
$baseWidth = imagesx($baseImage);
$baseHeight = imagesy($baseImage);
$topWidth = imagesx($topImage);
$topHeight = imagesy($topImage);
//Create a new image
$imageOut = imagecreatetruecolor($baseWidth, $baseHeight);
//Make the new image definitely have an alpha channel
$backgroundColor = imagecolorallocatealpha($imageOut, 0, 0, 0, 127);
imagefill($imageOut, 0, 0, $backgroundColor);
imagecopy($imageOut, $baseImage, 0, 0, 0, 0, $baseWidth, $baseHeight); //have to play with these
imagecopy($imageOut, $topImage, 0, 0, 0, 0, $topWidth, $topHeight); //have to play with these
//header('Content-Type: image/png');
imagePng($imageOut, "../../var/tmp/output.png");
That code produces this image: | unknown | |
d9556 | train | td not closed properly
<table border="1" style="margin-top: 5px">
<thead>
<tr>
<th>rid</th>
<th>ciname</th>
<th>dId</th>
<th>ReqName</th>
<th>ReqType</th>
<th>bus</th>
<th>Req test</th>
<th>no trace</th>
<th>p r</th>
</tr>
</thead>
<tbody data-bind='foreach: gifts'>
<tr>
<td><span data-bind='text: reqid' /></td>
<td><span data-bind='text: ciname' /></td>
<td><span data-bind='text: did' /></td>
<td><span data-bind='text: reqname' /><td>
^^
<td><span data-bind='text: reqtype' /><td>
^^
<td><span data-bind='text: bus' /><td>
^^
<td><span data-bind='text: reqtest' /><td>
^^
<td><span data-bind='text: notrace' /><td>
^^
<td><span data-bind='text: pr' /></td>
</tr>
</tbody>
</table>
Use
http://jsfiddle.net/g3j94273/1/
A: Your tags are not properly closed, you need to convert some of the <td> to </td>
<table border="1" style="margin-top: 5px">
<thead>
<tr>
<th>rid</th>
<th>ciname</th>
<th>dId</th>
<th>ReqName</th>
<th>ReqType</th>
<th>bus</th>
<th>Req test</th>
<th>no trace</th>
<th>p r</th>
</tr>
</thead>
<tbody data-bind='foreach: gifts'>
<tr>
<td><span data-bind='text: reqid' /></td>
<td><span data-bind='text: ciname' /></td>
<td><span data-bind='text: did' /></td>
<td><span data-bind='text: reqname' /></td>
<td><span data-bind='text: reqtype' /></td>
<td><span data-bind='text: bus' /></td>
<td><span data-bind='text: reqtest' /></td>
<td><span data-bind='text: notrace' /></td>
<td><span data-bind='text: pr' /></td>
</tr>
</tbody>
</table> | unknown | |
d9557 | train | Seems like OFFSET and FETCH would be more succinct here:
DECLARE @N int = 2,
@Date date = '20210716';
SELECT LogID, etime
FROM dbo.MYTABLE
WHERE etime >= @Date
AND eTime < DATEADD(DAY, 1, @Date)
ORDER BY etime ASC
OFFSET @N-1 ROWS FETCH NEXT 1 ROWS ONLY;
A: Imo the way you're doing it now is a really good way and you could stick with it. Again imo: the nested SELECT are not as nice as common table expressions. I would rewrite and parameterize the code something like this
declare @param int=3;
with
dr_cte(logid, etime_dt, drnk) as (
select logid, Cast(etime as date),
dense_rank() over(partition by cast(etime as date) order by etime desc)
from #MYTABLE),
serial_cte(logid, etime_dt, drnk, serial) as (
select *, row_number() over (order by etime_dt desc)
from dr_cte
where drnk=1)
select *
from serial_cte
where serial=@param;
[EDIT] It could be made a tiny bit more concise (or maybe it's the same?) by using TOP 1 WITH TIES in the dr_cte. Then the WHERE condition in the second CTE could be removed. Afaik this code is equivalent
declare @param int=2;
with
dr_cte(logid, etime_dt) as (
select top 1 with ties logid, Cast(etime as date)
from #MYTABLE
order by row_number() over(partition by cast(etime as date) order by etime desc)),
serial_cte(logid, etime_dt, serial) as (
select *, row_number() over (order by etime_dt desc)
from dr_cte)
select *
from serial_cte
where serial=@param;
[Edit 2] It could also be done by OFFSET paging.
declare @param int=3;
with
dr_cte(logid, etime_dt) as (
select top 1 with ties logid, Cast(etime as date)
from #MYTABLE
order by row_number() over(partition by cast(etime as date) order by etime desc))
select *
from dr_cte
order by etime_dt desc
offset @param-1 rows fetch next 1 rows only; | unknown | |
d9558 | train | Looks like the system was the culprit - I changed the open_table_cache to 400 and my php application is no longer having any issues preparing statements, even after the nightly backups of the databases. Looking at older mysql documentation, mysql 5.6.7 had a table_open_cache setting of 400, so when I upgraded to mariadb 10.3.13 that default setting was changed to 2000 which is when I started having problems.
Not quite sure what the following is telling me, but might be of interest ....
su - mysql
-bash-4.1$ ulimit -Hn
100
-bash-4.1$ ulimit -Sn
100
-bash-4.1$ exit
logout
[~]# ulimit -Hn
4096
[~]# ulimit -Sn
4096 | unknown | |
d9559 | train | PXE is your only realistic hope:
Some on-site assistance is needed to press F12 at Bios before Windows XP boot:
A) On PC-A, setup DHCP server that refer DHCP-client to PXE server that download Linux ISO from a web server (of course all three can be a Windows machine in the same LAN segment onsite)
B) reboot PC-B onsite to reboot machine and press F10-F12 to choose Boot-options
C) then choose network-boot (PXE-Boot)
further reading : https://www.vercot.com/~serva/
guide: https://youtu.be/nnxgFpUr1Og?t=39
Note: Make sure you have enabled proxyDHCP and not DHCP Server
A: I would try with something like these:
*
*Clonezilla, which works by replicating a previously prepared disk image to one or more computers booted inside a network segment
*Cobbler, which works like a provisioning server for Linux based machines
Of those options, I have used Clonezilla with success. As long as the prepared base image doesn't change too frequently, the main time consuming tasks would be related with configuring the Clonezilla server and building that seed image.
I did a basic test of Cobbler and it worked fine in my environment, being this a way that would be more apt to deal with requirement changes.
Please also note that both options require some network configuration, like DHCP server settings that work with the PXE protocol.
Also, for your requirement, someone, a human being, would be needed to execute one or more of these tasks:
*
*Properly enable network booting in the BIOS of each of the 800+ machines, unless it has already be done before
*Boot the machines to install the new operating system
The network booting option, based on the PXE specification, should be supported by the motherboard of those machines and have higher booting priority than other devices, like CD drives, hard drives, etc.
Another thing to consider for the couple of options I'm suggesting, is how are those 800+ distributed across the country. The more disperse they are, the more cumbersome this task will be. Quite contrary, if there are few places were those machines are located, the more feasible this task will be; for example, by preparing and testing a server, computer or laptop that you then carry to each of those few places and installing the new operating system.
Regarding the option to boot using the public Internet to reach a remote deployment server, I don't know about how that could be done; in fact, for me that would be something quite interesting to learn about. If something like this is possible, another variable to note is the hardware compatibility of the destination machines, because as far as I know, protocols like PXE do some kind of multicast or broadcast in the local network segment and I presume those 800+ machines don't have recent motherboards with advanced firmware that could support more modern boot protocols.
That's all for now. | unknown | |
d9560 | train | You need to add an event listener to the img tag called load. Then in the callback you can call drawImage with the provided img element.
You can do something like this - I have added one stackoverflow image for representation:
const canvas = document.getElementById("canvas");
const context = canvas.getContext("2d");
const image = document.getElementById("image");
context.fillStyle = "lightblue";
context.fillRect(0, 0, 1000, 750);
image.addEventListener('load', e => context.drawImage(image, 0, 0));
<img id="image" src="https://stackoverflow.blog/wp-content/themes/stackoverflow-oct-19/images2/header-podcast.svg" height="100px"></img>
<canvas id="canvas" width="1000" height="750"></canvas>
From the documentation: Drawing an image to the canvas
I hope this helps! | unknown | |
d9561 | train | *
*iterate over the file
*for each line check the first character
*
*if the first character is either '[' or '{' start accumulating lines
*if the first character is either ']' or '}' stop accumulating lines
a_s = []
b_s = []
capture = False
group = None
with open(path) as f:
for line in f:
if capture: group.append(line)
if line[0] in '{[':
capture = True
group = a_s if line[0] == '{' else b_s
elif line[0] in '}]':
capture = False
group = None
print(a_s)
print(b_s)
Relies on the file to be structured exactly as shown in the example.
A: This is what regular expressions are made for. Python has a built-in module named re to perform regular expression queries.
In your case, simply:
import re
fname = "foo.txt"
# Read data into a single string
with open(fname, "r") as f:
data = f.read()
# Remove newline characters from the string
data = re.sub(r"\n", "", data)
# Define pattern for type A
pattern_a = r"\{(.*?)\}"
# Print text of type A
print(re.findall(pattern_a, data))
# Define pattern for type B
pattern_b = r"\[(.*?)\]"
# Print text of type B
print(re.findall(pattern_b, data))
Output:
['this is text for athis is text for athis is text for athis is text for a']
['this is text for bthis is text for bthis is text for bthis is text for b']
A: Read the file and split the content to a list.
Define a brackets list and exclude them through a loop and write the rest to a file.
file_obj = open("content.txt", 'r')
content_list = file_obj.read().splitlines()
brackets = ['[', ']', '{', '}']
for i in content_list:
if i not in brackets:
writer = open("new_content.txt", 'a')
writer.write(i+ '\n')
writer.close()
A: f1=open('D:\\Tests 1\\t1.txt','r')
for line in f1.readlines():
flag=0
if line.find('{\n') or line.find('[\n'):
flag=1
elif line.find('}\n') or line.find(']\n'):
flag=0
if flag==1:
print(line.split('\n')[0]) | unknown | |
d9562 | train | The core thing to remember is that when you instantiate a Module class, you are creating a callable object, i.e. something that can behave like a function.
In plain English and step by step:
*
*When you write something like add5 = Add(5), what you are doing is assigning an "instance" of the PyTorch model Add to add5
*More specifically, you are passing 5 to the Add class's __init__ method, and so its value attribute is set to 5.
*PyTorch Modules are "callable" meaning you can call them like functions. The function you call when you use an instance of a Module is that instance's forward method. So concretely, with our add5 object, if we pass a value, x = 10, by writing something like add5(10) it is like we ran x + add5.value, which equals 10 + 5 = 15.
Now putting this together, we should view the Sequential interface for building neural network models that don't have branching structures as just sequentially invoking each of the instantiated Modules' forward methods.
Omitting the definition of Add and focussing just on calculator as a series of computations we have the following (I've added the comments to show you what you should think of at each step)
calculator = nn.Sequential(
# given some input tensor x...
Add(3), # run: x = x + self.value with self.value = 3
Add(2), # run: x = x + self.value with self.value = 2
Add(5), # run: x = x + self.value with self.value = 5
)
Now we can see that it's reasonable to expect that if we pass the value 1 (albeit wrapped up as a PyTorch Tensor) we are just doing 1 + 3 + 2 + 5 which of course equals 11. PyTorch returns us back the value still as a Tensor object.
x = torch.tensor([1])
output = calculator(x)
print(output) # tensor([11])
Finally, Add(3)(5)* works for exactly this same reason! With Add(3) we are getting an instance of the Add class with the value to add being 3. We then use it immediately with the somewhat unintuitive syntax Add(3)(5) to return the value 3 + 5 = 8.
*I think you intended the capitalised class name, not an instance of the class
A: You understand it right, the Sequential class in a nutshell just calls provided modules one by one. Here's the code of the forward method
def forward(self, input):
for module in self:
input = module(input)
return input
here, for module in self just iterates through the modules provided in a constructor (Sequential.__iter__ method in charge of it).
Sequential module calls this method when you call it using () syntax.
calculator = nn.Sequential(
Add(3),
Add(2),
Add(5),
)
output = calculator(torch.tensor([1]))
But how does it work? In python, you could make objects of a class callable, if you add __call__ method to the class definition. If the class does not contain this method explicitly, it means that it possibly was inherited from a superclass. In case of Add and Sequential, it's Module class that implements __call__ method. And __call__ method calls 'public' forward method defined by a user.
It could be confusing that python uses the same syntax for the object instantiation and function or method call. To make a difference visible to the reader, python uses naming conventions. Classes should be named in a CamelCase with a first capital letter, and objects in a snake_case (it's not obligatory, but it's the rule that better to follow).
Just like in you example, Add is a class and add is a callable object of this class:
add = Add(torch.tensor([1]))
So, you can call add just like you have called a calculator in you example.
>>> add = Add(torch.tensor([1]))
>>> add(2)
Out: tensor([3])
But that won't work:
>>> add = Add(torch.tensor([1]))
>>> add(2)(1)
Out:
----> 3 add(2)(1)
TypeError: 'Tensor' object is not callable
That means that add(2) returns a Tensor object that does not implement __call__ method.
Compare this code with
>>> Add(torch.tensor([1]))(2)
Out:
tensor([3])
This code is the same as the first example, but rearranged a little bit.
--
To avoid confusion, I usually name objects differently: like add_obj = Add(1). It helps me to highlight a difference.
If you are not sure what you're working with, use functions type and isinstance. They would help to find out what's going on.
For example, if you check the add object, you could see that it's a callable object (i.e., it implements __call__)
>>> from typing import Callable
>>> isinstance(add, Callable)
True
And for a tensor:
>>> from typing import Callable
>>> isinstance(add, torch.tensor(1))
False
Hence, it will rase TypeError: 'Tensor' object is not callable in case you call it.
If you'd like to understand how python double-under methods like init or call work, you could read this page that describes python data model
(It could be a bit tedious, so you could prefer to read something like Fluent Python or other book) | unknown | |
d9563 | train | Note: for a TLDR, skip to the end.
Your problem is a very interesting textbook case as it involves multiple facets of Postgres.
I often find it very helpful to decompose the problem into multiple subproblems before joining them together for the final result set.
In your case, I see two subproblems: finding the most popular product for each month, and finding the least popular product for each month.
Let's start with the most popular products:
WITH months AS (
SELECT generate_series AS month
FROM generate_series(1, 12)
)
SELECT DISTINCT ON (month)
month,
prod,
SUM(quant)
FROM months
LEFT JOIN sales USING (month)
GROUP BY month, prod
ORDER BY month, sum DESC;
Explanations:
*
*WITH is a common table
expression,
which acts as a temporary table (for the duration of the query) and
helps clarify the query. If you find it confusing, you could also opt
for a subquery.
*generate_series(1, 12) is a Postgres function which generate a series of integers, in this case from 1 to 12.
*the LEFT JOIN allows us to associate each sale to the corresponding month. If no sale can be found for a given month, a row is returned with the month and the joined columns with NULL values. More information on joins can be found here. In your case, using LEFT JOIN is important, as using INNER JOIN would exclude products that have never been sold (which in that case should be the least popular product).
*GROUP BY is used to sum over the quantities.
*at this stage, you should -potentially- have multiple products for any given month. We only want to keep those with the most quantities for each month. DISTINCT ON is especially useful for that purpose. Given a column, it allows us to keep the first iteration of each value. It is therefore important to ORDER the sales by sum first, as only the first one will be selected. We want the bigger numbers first, so DESC (for descending order) should be used.
We can now repeat the process for the least popular products:
WITH months AS (
SELECT generate_series AS month
FROM generate_series(1, 12)
)
SELECT DISTINCT ON (month)
month,
prod,
SUM(quant)
FROM months
LEFT JOIN sales USING (month)
GROUP BY month, prod
ORDER BY month, sum;
Conclusion (and TLDR):
Now we need to merge the two queries into one final query.
WITH months AS (
SELECT generate_series AS month
FROM generate_series(1, 12)
), agg_sales AS (
SELECT
month,
prod,
SUM(quant)
FROM months
LEFT JOIN sales USING (month)
GROUP BY month, prod
), most_popular AS (
SELECT DISTINCT ON (month)
month,
prod,
sum
FROM agg_sales
ORDER BY month, sum DESC
), least_popular AS (
SELECT DISTINCT ON (month)
month,
prod,
sum
FROM agg_sales
ORDER BY month, sum
)
SELECT
most_popular.month,
most_popular.prod AS most_popular_prod,
most_popular.sum AS most_pop_total_q,
least_popular.prod AS least_popular_prod,
least_popular.sum AS least_pop_total_q
FROM most_popular
JOIN least_popular USING (month);
Note that I used an intermediate agg_sales CTE to try and make the query a bit clearer and avoid repeating the same operation twice, although it shouldn't be a problem for Postgres' optimizer.
I hope you find my answer satisfactory. Do not hesitate to comment otherwise!
EDIT: although this solution should work as is, I would suggest storing your dates as a single column of type TIMESTAMPTZ. It is often much easier to manipulate dates using that type and it is always good practice in case you need to analyze and audit your database further down the line.
You can get the month of any date by simply using EXTRACT(MONTH FROM date). | unknown | |
d9564 | train | The authentication has changed from mysql V8, you must use a compatible client and server.
BTW it's a bug : https://bugs.mysql.com/bug.php?id=91828
Here is a workaround without uninstalling the new workbench.
The most probable case is having an old server with a new workbench:
*
*get the server version
From a SQL cli tool:
SHOW VARIABLES LIKE "%version%";
or from a cli connected on the server:
$ mysql -v
It should show a version < 8.0, in my case 5.1.73
*Get the mysqlWorkbench for a version <8.0:
You cannot install the msi if you already have a workbench V8.0, so you have to choose a portable installation form a zip file here:
https://dev.mysql.com/downloads/workbench/6.1.html
Select the version 6.2.5 (last before v8.0) zip version
Unzip
Close the workbench v.8 (it lock any other workbench launch)
Launch the V6.2.3 version of workbench, it should works.
A: This is probably because of a mismatch in the versions of MySQL servers.
Check the version of the MySQL server you are trying to connect to, and the version you have installed on the computer you are using, they have to be the same.
A: The reason of this warning is version problem. If you have installed mysql server version <= 5.1 and your remote server mysql version is greater than that you will face this problem. I recommend you to install 5.7 or greater in both your local and remote server. This problem will be fixed.
A: Fortunately there is an easy way around this. Use the old MYSQL ADMINISTRATOR tool as shown below. In my case I was trying to open a MySQL 5.1 database for a clients WordPress installation with MySQL Workbench 8 and that did not work out :).
ALl credits goes to https://www.urtech.ca/2019/01/solved-bad-handshake-mysql-workbench-failed-to-connect-to-sql/
Follow this link for the details
https://www.urtech.ca/2019/01/solved-bad-handshake-mysql-workbench-failed-to-connect-to-sql/ | unknown | |
d9565 | train | You would do this with ajax. To understand what to do in your controller you have to understand the fundementals of an ajax call. jQuery makes this pretty easy.
<script>
$(function() {
jQuery.ajax({
type: method,
dataType: 'json',
url: url,
data: data,
error: function(jqXHR, textStatus, errorThrown) {
// Do something to handle the error
},
success: function(data, textStatus, jqXHR) {
// Do something else on successful validation
}
});
});
</script>
The type is the HTTP method (eg. 'POST').
The url is the the route to get you to the controller which will give you a response.
The data is the form data to be sent.
More documentation is at https://api.jquery.com/jQuery.ajax/
The success function is executed if the HTTP response code is in the 200's.
If you send an HTTP response code in the 400's or 500's, the javascript in the error function will be executed. This can be used to show an error in your modal dialog.
You can modify the HTTP response code in a controller by using the following code:
$this->getResponse()->setStatusCode(400);
where 400 is the HTTP response code (see http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html for more info about HTTP response codes)
Then, to send data back with the response, return a JsonModel in the controller instead of a ViewModel
return new JsonModel($array);
where $array is the data you want to send back to the browser.
If you end up doing this a lot, you might investigate the zf2 class \Zend\Mvc\Controller\AbstractRestfulController.
A: if you want try for validation before submit form (send data to server) . may be better use client side validation .
http://www.rayfaddis.com/blog/2013/05/27/jquery-validation-with-twitter-bootstrap | unknown | |
d9566 | train | You could use something like this:
SELECT t.SalesDate,
PreviousWorkingDay = d.CAL_DATE
FROM mytable t
CROSS APPLY
( SELECT c.CAL_DATE
FROM D_Calendar AS c
WHERE c.CAL_DATE < t.SalesDate
AND c.DayIsWorkDay = 1
ORDER BY c.CAL_DATE DESC OFFSET 1 ROWS FETCH NEXT 1 ROW ONLY
) AS d;
It uses OFFSET 1 ROWS within the CROSS APPLY to get the penultimate working day
A: This is how i implemented the idea from @SMor:
SELECT
SalesAmount
,SalesDate
FROM mytable t
JOIN D_Calendar c ON t.Date = c.CAL_DATE
WHERE SalesDate <= (SELECT
MIN(t1.CAL_DATE) as MinDate
FROM
(SELECT TOP 2
[CAL_DATE]
FROM [DWH_PROD].[cbi].[D_Calendar]
WHERE CAL_DAYISWORKDAY = 1 AND CAL_DATE < DATEADD(dd,0,DATEDIFF(dd,0,GETDATE()))
ORDER BY CAL_DATE DESC
) t1)
Thank you for your ideas and recommendations!
A: You can use a ROW_NUMBER() OVER(ORDER BY CAL_DATE desc) getting get the top 2 rows then take the row with number 2.
Example:
-- setup
Declare @D_Calendar as Table (CAL_DATE date, DayIsWorkDay bit)
insert into @D_Calendar values('2022-07-27', 1)
insert into @D_Calendar values('2022-07-28', 1)
insert into @D_Calendar values('2022-07-29', 1)
insert into @D_Calendar values('2022-07-30', 0)
insert into @D_Calendar values('2022-07-31', 0)
insert into @D_Calendar values('2022-08-01', 1)
Declare @RefDate DateTime = '2022-08-01 10:00'
-- example query
Select CAL_DATE
From
(Select top 2 ROW_NUMBER() OVER(ORDER BY CAL_DATE desc) AS BusinessDaysBack, CAL_DATE
from @D_Calendar
where DayIsWorkDay = 1
and CAL_DATE < Cast(@RefDate as Date)) as Data
Where BusinessDaysBack = 2
From there you can plug that into your where clause to get :
SELECT
SalesAmount
,SalesDate
FROM mytable t
WHERE SalesDate <= (Select CAL_DATE
From (Select top 2 ROW_NUMBER() OVER(ORDER BY CAL_DATE desc) AS BusinessDaysBack, CAL_DATE
from D_Calendar
where DayIsWorkDay = 1
and CAL_DATE < Cast(getdate() as Date)) as Data
Where BusinessDaysBack = 2)
Change the 2 to 3 to go three days back etc | unknown | |
d9567 | train | maybe you forgot to link jquery
jQuery(document).ready(function(){
var clickElem = $('a.accord-link');
clickElem.on('click', function (e) {
e.preventDefault();
var $this = $(this),
parentCheck = $this.parents('.accord-elem'),
accordItems = $('.accord-elem'),
accordContent = $('.accord-content');
if (!parentCheck.hasClass('active')) {
accordContent.slideUp(400, function () {
accordItems.removeClass('active');
});
parentCheck.find('.accord-content').slideDown(400, function () {
parentCheck.addClass('active');
});
} else {
accordContent.slideUp(400, function () {
accordItems.removeClass('active');
});
}
});
});
.container .content {}
hr,
.borderedbox {
border-color: #D7D7D7;
}
.inspace-5 {
padding: 5px;
}
.imgl {
margin: 0 15px 10px 0;
clear: left;
}
.imgr {
margin: 0 0 10px 15px;
clear: right;
}
.fl_left,
.imgl {
float: left;
}
.fl_right,
.imgr {
float: right;
}
.borderedbox {
border: 1px solid;
border-color: darkgray;
}
.accord-tab-box {
padding-top: 40px;
padding-bottom: 20px;
}
.accordion-box {
margin-bottom: 20px;
}
.accord-elem {
margin-bottom: 20px;
}
.accord-title {
padding: 16px 14px;
border: 1px solid #dbdbdb;
position: relative;
}
.accord-title h5 {
padding-right: 48px;
}
.accord-title h5 i {
color: #007aff;
font-size: 20px;
vertical-align: middle;
margin-right: 12px;
}
a.accord-link {
display: inline-block;
position: absolute;
width: 46px;
height: 100%;
top: 0;
right: 0;
border-left: 1px solid #dbdbdb;
background: url('/Content/MyTemplate/images/add.png') center center no-repeat;
transition: all 0.2s ease-in-out;
-moz-transition: all 0.2s ease-in-out;
-webkit-transition: all 0.2s ease-in-out;
-o-transition: all 0.2s ease-in-out;
}
.accord-elem.active a.accord-link {
background: url('/Content/MyTemplate/images/substract.png') center center no-repeat;
}
a.accord-link.opened {
background: url('/Content/MyTemplate/images/substract.png') center center no-repeat;
}
.accord-content {
display: none;
padding: 22px;
border: 1px solid #dbdbdb;
border-top: none;
overflow: hidden;
}
.accord-content span.image-content {
display: inline-block;
float: left;
width: 68px;
height: 68px;
border-radius: 50%;
-webkit-border-radius: 50%;
-moz-border-radius: 50%;
-o-border-radius: 50%;
margin-right: 22px;
background: #007aff;
}
.accord-content span.logo-content {
display: inline-block;
float: left;
width: 110px;
margin-right: 15px;
}
.accord-content span.image-content i {
color: #fff;
font-size: 30px;
text-align: center;
width: 100%;
line-height: 68px;
vertical-align: middle;
}
.accord-content span.logo-content i {
color: #fff;
font-size: 30px;
text-align: center;
width: 100%;
line-height: 68px;
vertical-align: middle;
}
.accord-elem.active .accord-content {
display: block;
}
.why-convertible-box {
padding-top: 60px;
}
.why-convertible-box h1 {
margin-bottom: 10px;
}
.why-convertible-box h1 span {
font-weight: 600;
}
.why-convertible-box h1 i {
color: #0a9dbd;
margin-left: 10px;
}
.why-convertible-box p {
margin-bottom: 15px;
}
.why-convertible-box p a {
color: #0076f9;
font-weight: 700;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="accord-tab-box">
<div class="container">
<div class="row">
<div class="col-md-6">
<div class="accordion-box">
<div class="accord-elem">
<div class="accord-title">
<h5><i class="fa fa-money fa-fw"></i>Software Development</h5>
<a class="accord-link" href="#"></a>
</div>
<div class="accord-content">
<p>IT related have a team of software developers who are skilled in Open source Java, Spring, Hibernate, Struts, GWT; DotNet framework and have written many web based systems:<br />• Requisition system<br />• Tender management system <br />•
Invoice tracking system<br />• Our team has more than 20 years experience in Software development life cycle. Reference sites: <br />• KZN Department of Works;<br />• KZN Department Of Education;<br />• EC DEDEAT;<br /><br />• Neha Shipping;<br
/><br />• SJS Consulting<br /> </p>
</div>
</div>
</div>
</div>
</div>
</div>
</div> | unknown | |
d9568 | train | I found that the property to adjust is the AudioDeviceController.VolumePercent property. The following code implements this:
MediaCapture mediaCapture = new MediaCapture();
var captureInitSettings = new MediaCaptureInitializationSettings
{
StreamingCaptureMode = StreamingCaptureMode.Audio
};
await mediaCapture.InitializeAsync(captureInitSettings);
mediaCapture.AudioDeviceController.VolumePercent = volumeLevel;
I confirmed that this code works on Desktop and HoloLens. It changes the system level, so it's automatically persisted, and would affect all apps. | unknown | |
d9569 | train | I'm not completely sure I understand you correctly, but if your first question is how to change element X when clicking on element Y, you need something along the lines of:
legendRect.on("click", function() {
gbars.transition()
.duration(500)
.style("display", "block")
// etc...
}
As for changing the fill on click, try:
gbars.on("click", function() {
d3.select(this)
.attr("fill", "white");
} | unknown | |
d9570 | train | You're looping from 1 to n:
for (int row = 1; row <= n; row++){
for (int col = 1; col <= n; col++){
Indexes begin at 0, not at 1. The loops should be from 0 to n-1:
for (int row = 0; row < n; row++){
for (int col = 0; col < n; col++){
(This same error may likely be in other places than just the first line that threw the exception.) | unknown | |
d9571 | train | I would do a for loop with the sample sizes I am interested in, as follows:
sizes <- c(10, 20, 30, 40, 50, 60, 70, 80, 90, 100)
results <- c()
for (size in sizes) {
subset <- sample_n(data, size)
lm_fit <- lm(subset$response ~ subset$predictor)
conf <- confint(lm_fit, level = 0.95)
results <- rbind(results, c(size, lm_fit$coefficients[1], conf[1,1], conf[1,2]))
}
You may plot the results as follows:
library(ggplot2)
ggplot(data = results, aes(x = size, y = mean)) +
geom_point() +
geom_errorbar(aes(ymin = lower, ymax = upper))
where geom_errorbar helps to show the confidence interval.
A: Thank you! This sent me in the right direction. New to RStudio, so it is not always easy to know where to look for solutions. I ended up with the code below.
calculate_mean_ci_M <- function(data, subset_sizes){
mean <- mean(RandomM$Value[1:subset_sizes])
sem <- sd(RandomM$Value[1:subset_sizes]) /sqrt(subset_sizes)
ci <- sem * qt(c(0.025, 0.975), df = subset_sizes-1)
return(data.frame(subset_sizes = subset_sizes, mean = mean, ci_lower = mean - ci[1],
ci_upper = mean + ci[1]))
}
subset_sizes <- c(20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140,
150, 160, 170, 180, 190, 200, 210, 220, 230, 240, 250, 260,
270, 280, 290, 300, 310, 320, 330, 340, 350, 360, 370,
380, 390, 400, 410, 420, 430, 440, 450, 460, 470, 480, 490, 500,
510, 520, 530, 540, 550, 560, 570, 580, 590, 600, 610, 620, 630,
640, 650, 660, 670, 672)
mean_ci_data_M <- map(subset_sizes, calculate_mean_ci_M, data = data) %>%
bind_rows()` | unknown | |
d9572 | train | An empty JSON string looks like this:
[]
That is 2 characters.
Your error-detection will not work because it checks for 1 or less characters.
Change
if (strlen($test) < 2) {
$error = json_last_error();
}
To
if (strlen($test) == 2) {
$error = json_last_error();
}
And your error-detection should work.
If you are unable to resolve the problem that is indicated in the JSON error, please update us with the error.
A: Lesson learnt, there should always be some distrust in debugging tools (netbeans watches etc).
I created the error check when seeing a random '{' as the output (don't know why netbeans displayed it like this).
It was the javascript that was broken in a line such as
var a=<?php echo $thejsonstuff ?>
and I attempted the php debug from netbeans results first. | unknown | |
d9573 | train | As it turned out, ComIntern and Remy were right. I had completely misunderstood the whole stdcall and safecall interfaces.
The .ridl file now looks like this:
....
interface ILCCAMQM_Application: IDispatch
{
[id(0x000000C9)]
int _stdcall Connect(void);
[id(0x000000CA)]
int _stdcall Disconnect(void);
[propget, id(0x000000CC)]
HRESULT _stdcall Connected([out, retval] VARIANT_BOOL* Value);
[id(0x000000CB)]
HRESULT _stdcall OpenProject([in] BSTR aFolderOrAlias, [out, retval] ILCCAMQM_Project** Value);
};
....
And the generated ...TLB.pas file looks like this:
....
// *********************************************************************//
// Interface: ILCCAMQM_Application
// Flags: (4416) Dual OleAutomation Dispatchable
// GUID: {EDD8E7FC-5D96-49F1-ADB7-F04EE9FED7B5}
// *********************************************************************//
ILCCAMQM_Application = interface(IDispatch)
['{EDD8E7FC-5D96-49F1-ADB7-F04EE9FED7B5}']
function Connect: SYSINT; stdcall;
function Disconnect: SYSINT; stdcall;
function Get_Connected: WordBool; safecall;
function OpenProject(const aFolderOrAlias: WideString): ILCCAMQM_Project; safecall;
property Connected: WordBool read Get_Connected;
end;
// *********************************************************************//
// DispIntf: ILCCAMQM_ApplicationDisp
// Flags: (4416) Dual OleAutomation Dispatchable
// GUID: {EDD8E7FC-5D96-49F1-ADB7-F04EE9FED7B5}
// *********************************************************************//
ILCCAMQM_ApplicationDisp = dispinterface
['{EDD8E7FC-5D96-49F1-ADB7-F04EE9FED7B5}']
function Connect: SYSINT; dispid 201;
function Disconnect: SYSINT; dispid 202;
property Connected: WordBool readonly dispid 204;
function OpenProject(const aFolderOrAlias: WideString): ILCCAMQM_Project; dispid 203;
end;
....
And the OpenProject now works from my internal unit test (written in delphi) as well as from Excel-VBA.
Now I am struggling with properties to set and get through Excel VBA as well as through an OleVariant in delphi. But I will have to put that in another Q. | unknown | |
d9574 | train | You can render this with:
{{ form.Container_id }}
In your form you should first pop the container_id from the kwargs, like:
class ObjectEditForm(forms.ModelForm):
class Meta:
model = Object
fields = ['TestField']
def __init__(self, *args, **kwargs):
# first pop from the kwargs
self.Container_id = kwargs.pop('container_id', None)
super(ObjectEditForm, self).__init__(*args, **kwargs)
Use the context over the form
That being said, it is a bit strange that you pass this to the form, and not add this to the context data. You can simplify your view a lot to:
class ObjectUpdateView(UpdateView):
template_name = 'manage/object_form.html'
pk_url_kwarg = 'object_id'
form_class = ObjectEditForm
def get_success_url(self):
#...
def get_context_data(self, **kwargs):
objectid = self.kwargs['object_id']
object = Object.objects.get(id = objectid)
context = super().get_context_data()
context.update(container_id=object.container_id)
return context
Django automatically fetches a single element based on the pk_url_kwarg [Django-doc]. You only need to set it correctly, so here that is the object_id.
In that case, we can simply render this with:
{{ container_id }}
and you do not need to store this in the form. | unknown | |
d9575 | train | The apparent discrepancy is most likely[1] between the number of columns in your data set and the number of predictors, which may not be the same if any of the columns are factors. You used the formula method, which will expand the factors into dummy variables. For example:
> head(model.matrix(Sepal.Width ~ ., data = iris))
(Intercept) Sepal.Length Petal.Length Petal.Width Speciesversicolor Speciesvirginica
1 1 5.1 1.4 0.2 0 0
2 1 4.9 1.4 0.2 0 0
3 1 4.7 1.3 0.2 0 0
4 1 4.6 1.5 0.2 0 0
5 1 5.0 1.4 0.2 0 0
6 1 5.4 1.7 0.4 0 0
So there are 3 predictor columns in iris but you end up with 5 (non-intercept) predictors.
Max
[1] This is why you need to provide a reproducible example. Often, when I get ready to ask a question, the answer becomes apparent while I take the time to write a good description of the issue. | unknown | |
d9576 | train | holder.layout2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
/* if(clicktime=true)*/ if(clicktime==true) {
Toast.makeText(getContext(), "datachanged", Toast.LENGTH_SHORT).show();
notifyDataSetChanged();
updateData(dataList1);
mAdapter.notifyDataSetChanged();
clicktime=false;
}
/* if(clicktime=false)*/ if(clicktime==false){
Toast.makeText(getContext(), "datachanged", Toast.LENGTH_SHORT).show();
notifyDataSetChanged();
updateData1(dataList);
mAdapter.notifyDataSetChanged();
clicktime=true;
}
}
});
A: To check equivalency in Java, you need to use double equals. Or, you can just put if(clicktime) for true
if(!clicktime) for false | unknown | |
d9577 | train | Not tested, but it should work (edited after comments)
lapply(mylist, write, "test.txt", append=TRUE, ncolumns=1000)
A: Format won't be completely the same, but it does write the data to a text file, and R will be able to reread it using dget when you want to retrieve it again as a list.
dput(mylist, "mylist.txt")
A: I saw in the comments for Nico's answer that some people were running into issues with saving lists that had lists within them. I also ran into this problem with some of my work and was hoping that someone found a better answer than what I found however no one responded to their issue.
So:
@ali, @FMKerckhof, and @Kerry the only way that I found to save a nested list is to use sink() like user6585653 suggested (I tried to up vote his answer but could not). It is not the best way to do it since you link the text file which means it can be easily over written or other results may be saved within that file if you do not cancel the sink. See below for the code.
sink("mylist.txt")
print(mylist)
sink()
Make sure to have the sink() at the end your code so that you cancel the sink.
A: depending on your tastes, an alternative to nico's answer:
d<-lapply(mylist, write, file=" ... ", append=T);
A: Another way
writeLines(unlist(lapply(mylist, paste, collapse=" ")))
A: Here's another way using sink:
sink(sink_dir_and_file_name); print(yourList); sink()
A: Here is another
cat(sapply(mylist, toString), file, sep="\n")
A: I solve this problem by mixing the solutions above.
sink("/Users/my/myTest.dat")
writeLines(unlist(lapply(k, paste, collapse=" ")))
sink()
I think it works well | unknown | |
d9578 | train | I don't know where you get the dynamic ids, but you could actually maybe put them in the providers array and use dependency injection like you would with injection tokens. If it is possible to create a factory method for the ids of course
Service
export class Item3Service {
constructor(
@inject(LOCALE_ID) private locale: string) {}
}
app.moudle.ts
@NgModule({
providers: [
{ provide: LOCALE_ID, useFactory: () => window.navigator.language}
]
})
Edit
Since the ids are part of your route, I would do it like this
Component
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { MyServiceService } from '../my-service.service';
@Component({
selector: 'app-routed',
templateUrl: './routed.component.html',
styleUrls: ['./routed.component.scss']
})
export class RoutedComponent implements OnInit {
constructor(private route: Router, private myService: MyServiceService) { }
ngOnInit(): void {
this.myService.setUrl(this.route.url)
}
}
Service
import { Injectable } from '@angular/core';
import { ReplaySubject, Observable } from 'rxjs';
import { share, switchMap } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class MyServiceService {
private _url$: ReplaySubject<string> = new ReplaySubject<string>(1);
private _mydata$: Observable<string>;
get myData$() { return this._mydata$.pipe(share()); }
constructor() {
this._mydata$ = this._url$.pipe(
switchMap(url => {
const parsedUrl = this.parseUrl(url);
return this.callBackend(parsedUrl)
})
)
}
setUrl(url: string) {
this._url$.next(url);
}
private callBackend(parsedUrl): Observable<string> {
// call backend
}
private parseUrl(url: string): number[] {
// parse ids
}
}
A: It's better for your Service to be stateless, it will bring down the complexity of your app and spare you some issues and debugging and it's just not necessary in your case because you can always get item1Id and item2Id from your activated route, so let the activated route hold the state of your application (in this case the state is what Item1Id and Item2Id are selected) and create a stateless service that you can call from anywhere and that holds the logic of your Item API.
Here is how I envision your service to be (Keep in mind that this is just an example to take into consideration since I don't know exactly your semantics and use cases)
ItemService
export class ItemService {
constructor(private http: HttpClient) {}
getList(item1Id: string, item2Id: string) {
/* Call to Get List endpoint with Item1Id and Item2Id */
}
getDetails(item1: string, item2: string, item3: string) {
/* Call to Get Details endpoint with Item1Id and Item2Id and Item3Id */
}
}
Then you can use this service everywhere, as long as you have access to the ActivatedRouteSnapshot or ActivatedRoute
Example Use in Resolver for Route item1/:item1Id/item2/:item2Id
export class ItemResolver implements Resolve<any> {
constructor(private itemService: ItemService) {}
resolve(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<any> {
return this.itemService.getList(route.params['item1Id'], route.params['item2Id']);
}
}
Example Use in Component for Route item1/:item1Id/item2/:item2Id to get Item 3 details
export class HelloComponent {
constructor(private route: ActivatedRoute, private itemService: ItemService) {}
getDetails(item3Id) {
this.route.params.pipe(
take(1),
map(({ item1Id, item2Id }) => {
console.log(this.itemService.getDetails(item1Id, item2Id, item3Id))
})
).subscribe();
}
}
Here is a working StackBlitz demonstrating this : https://stackblitz.com/edit/angular-ivy-h4nszy
You should rarely use stateful services (unless it's really necessary and even in that case I recommend using something like ngrx library to manage your state) with the information that you have given though, you really don't need to be passing parameters to the constructor of your service, you should keep it stateless and pass the parameters to your methods. | unknown | |
d9579 | train | So do I get that correct that the link is supposed to send the form? That will not work, as a link on its own is not able to trigger a submit. You need an input of type submit.
<input type="submit" class="btn btn-success" value="Login"> | unknown | |
d9580 | train | In this bit of code:
await imagemin(
[`tmp/${fileSlug}.${fileType}`],
'/tmp',
{ use: [ imageminWebp({quality: 50})] });
It looks like you're building a different string to the tmp file than you did when you built tmpFilePath. It's missing the leading slash. Any reason why you wouldn't use this instead?
await imagemin(
[tmpFilePath],
'/tmp',
{ use: [ imageminWebp({quality: 50})] }); | unknown | |
d9581 | train | The Windows version of the APOPT solver crashed and wasn't able to find a solution. However, the online Linux version of APOPT is able to find a solution. Get the latest version of Gekko (v1.0.0 pre-release) available on GitHub. This will be available with pip install gekko --upgrade when the new version is published but for now you need to copy the source to Lib\site-packages\gekko\gekko.py. After updating gekko, switch to remote=True as shown below.
import numpy as np
from gekko import GEKKO
# Define matrices A,A_eq, and vectors b, b_eq for the optimization
def Optimise_G(t,ob, jofbuses, q, qc, s, oa, k, l, T, G_next, C, Y, G_previous, G_max, G_min):
Mbig_1 = T*C
Mbig_2 = C
nb_phases = len(G_next)
b_max = len(t)
no_lanegroups = len(q)
A_eq = np.zeros(((nb_phases+1)*b_max + 1, (3*nb_phases+3)*b_max+nb_phases))
for i in range(nb_phases):
A_eq[0][i] = 1
#B_eq = np.zeros(((nb_phases+1)*b_max + 1, 1))
B_eq = np.zeros((nb_phases+1)*b_max + 1)
B_eq[0] = C - sum(Y[0:nb_phases])
counter_eq = 0
# G(i)=Ga(i,b)+Gb(i,b)+Gc(i,b)
for b in range(b_max):
for i in range(nb_phases):
counter_eq = counter_eq + 1
A_eq[counter_eq][i] = 1
A_eq[counter_eq][nb_phases*(b+1)+ i] = -1
A_eq[counter_eq][nb_phases*b_max + nb_phases*(b+1) + i] = -1
A_eq[counter_eq][2*nb_phases*b_max + nb_phases*(b+1) + i] = -1
# ya(b)+y(b)+y(c)=1
for b in range(b_max):
counter_eq = counter_eq + 1
A_eq[counter_eq][3*nb_phases*b_max + nb_phases + b] = 1
A_eq[counter_eq][(3*nb_phases+1)*b_max + nb_phases + b] = 1
A_eq[counter_eq][(3*nb_phases+2)*b_max + nb_phases + b] = 1
B_eq[counter_eq] = 1
A = np.zeros((no_lanegroups + (2*3*nb_phases+4)*b_max, (3*nb_phases+3)*b_max+nb_phases))
B = np.zeros(no_lanegroups + (2*3*nb_phases+4)*b_max)
counter = -1
# Sum Gi (i in Ij)>=Gj,min
for j in range(no_lanegroups):
counter = counter + 1
for i in range(k[j], l[j]+1):
A[counter][i-1] = -1
B[counter] = -C*qc[j]/s[j]
# ya(b)G_lb(i)<=Ga(i,b), yb(b)G_lb(i)<=Gb(i,b), yc(b)G_lb(i)<=Gc(i,b)
for b in range(b_max):
for i in range(nb_phases):
counter = counter + 1
A[counter][nb_phases*(b+1)+i] = -1
A[counter][3*nb_phases*b_max + nb_phases + b] = G_min[i]
B[counter] = 0
counter = counter + 1
A[counter][nb_phases*b_max + nb_phases*(b+1) + i] = -1
A[counter][(3*nb_phases+1)*b_max + nb_phases + b] = G_min[i]
B[counter] = 0
counter = counter + 1
A[counter][2*nb_phases*b_max + nb_phases*(b+1) +i] = -1
A[counter][(3*nb_phases+2)*b_max + nb_phases + b] = G_min[i]
B[counter] = 0
# ya(b)Gmax(i)>=Ga(i,b), yb(b)Gmax(i)>=Gb(i,b), yc(b)Gmax(i)>=Gc(i,b)
for b in range(b_max):
for i in range(nb_phases):
counter = counter + 1
A[counter][nb_phases*(b+1) +i] = 1
A[counter][3*nb_phases*b_max + nb_phases + b] = -G_max[i]
B[counter] = 0
counter = counter + 1
A[counter][nb_phases*b_max + nb_phases*(b+1) + i] = 1
A[counter][(3*nb_phases+1)*b_max + nb_phases + b] = -G_max[i]
B[counter] = 0
counter = counter + 1
A[counter][2*nb_phases*b_max + nb_phases*(b+1) +i] = 1
A[counter][(3*nb_phases+2)*b_max + nb_phases + b] = -G_max[i]
B[counter] = 0
# (1-yc(b))t(b)<=(T-1)C+sum(Gi(1:l(jofbuses(b))))+sum(Y(1:l(jofbuses(b))-1))
for b in range(b_max):
counter = counter + 1
A[counter][0:l[jofbuses[b]-1]] = -np.ones((1,l[jofbuses[b]-1]))
A[counter][(3*nb_phases+2)*b_max+nb_phases+b] = -t[b]
B[counter] = -t[b] + (T-1)*C + sum(Y[0:l[jofbuses[b]-1]-1])
# (T-1)C+sum(Gi(1:l(jofbuses(b))))+sum(Y(1:l(jofbuses(b))-1))<=yc(b)t(b)+(1-yc(b))Mbig_1
for b in range(b_max):
counter = counter + 1
A[counter][0:l[jofbuses[b]-1]] = np.ones((1,l[jofbuses[b]-1]))
A[counter][(3*nb_phases+2)*b_max+nb_phases+b] = -t[b] + Mbig_1
B[counter] = Mbig_1 - (T-1)*C - sum(Y[0:l[jofbuses[b]-1]-1])
# -Mbig_2(1-yb(b))<=db(b)=right-hand side of Equation (6)
for b in range(b_max):
counter = counter + 1
constant = q[jofbuses[b]-1]/s[jofbuses[b]-1]*(t[b] - (T-1)*C + sum(G_previous[l[jofbuses[b]-1]:nb_phases]) + sum(Y[l[jofbuses[b]-1] -1:nb_phases]))+ (T-1)*C + sum(Y[0:k[jofbuses[b]-1]-1]) - t[b]
A[counter][0:k[jofbuses[b]-1]-1] = -np.ones((1,k[jofbuses[b]-1]-1))
A[counter][(3*nb_phases+1)*b_max + nb_phases + b] = Mbig_2
B[counter] = constant + Mbig_2
# db(b)<=Mbig_2 yb(b)
for b in range(b_max):
counter = counter + 1
constant = q[jofbuses[b]-1]/s[jofbuses[b]-1]*(t[b] - (T-1)*C +sum(G_previous[l[jofbuses[b]-1]:nb_phases]) + sum(Y[l[jofbuses[b]-1] -1:nb_phases]))+ (T-1)*C + sum(Y[0:k[jofbuses[b]-1]-1]) - t[b]
A[counter][0:k[jofbuses[b]-1]-1] = np.ones((1,k[jofbuses[b]-1]-1))
A[counter][(3*nb_phases+1)*b_max + nb_phases + b] = -Mbig_2
B[counter] = -constant
#Lower Bound LB
LB_zeros = np.zeros(3*b_max*(nb_phases+1))
G_min = np.array(G_min)
LB = np.append(G_min, LB_zeros)
#Upper Bound UB
UB = np.ones(3*b_max)
G_max = np.array(G_max)
for i in range(3*b_max+1):
UB = np.concatenate((G_max,UB))
xinit = np.array([(a+b)/2 for a, b in zip(UB, LB)])
sol = MINLP(xinit, A, B, A_eq, B_eq, LB ,UB, t, ob, jofbuses, q, qc, s, oa, k, l, T, G_previous, C, Y, G_previous)
def objective_fun(x, t, ob, jofbuses, q, qc, s, oa, k, l, T, G_next, C, Y, G_previous):
nb_phases = len(G_next)
b_max = len(t)
no_lanegroups = len(q)
obj = 0
obj_a = 0
obj_b = 0
G = x[0:nb_phases]
for j in range(no_lanegroups):
delay_a = 0.5*q[j]/(1-q[j]/s[j]) * (pow((sum(G_previous[l[j]:nb_phases]) + sum(G[0:k[j]-1]) + sum(Y[l[j]-1:nb_phases]) + sum(Y[0:k[j]-1])),2) + pow(sum(G[l[j]:nb_phases]) + sum(G_next[0:k[j]-1]) + sum(Y[l[j]-1:nb_phases]) + sum(Y[0:k[j]-1]),2))
obj = obj + oa*delay_a
obj_a = obj_a + oa*delay_a
for b in range(b_max):
delay_b1 = x[(3*nb_phases+1)*b_max + nb_phases + b]*(q[jofbuses[b]-1]/s[jofbuses[b]-1] * (t[b] - (T-1)*C + sum(G_previous[l[jofbuses[b]-1]:nb_phases]) + sum(Y[l[jofbuses[b]-1] -1:nb_phases])) + (T-1)*C - t[b] + sum(Y[0:k[jofbuses[b]-1]-1]))
delay_b2 = x[(3*nb_phases+2)*b_max + nb_phases + b-1]*(q[jofbuses[b]-1]/s[jofbuses[b]-1] * (t[b] - (T-1)*C - sum(Y[0:l[jofbuses[b]-1]-1])) + T*C + sum(G_next[0:k[jofbuses[b]-1]-1]) + sum(Y[0:k[jofbuses[b]-1]-1]) - t[b])
delay_b3 = sum(x[nb_phases*b_max + nb_phases*b:nb_phases*b_max + nb_phases*b+k[jofbuses[b]-1]-1]) - q[jofbuses[b]-1]/s[jofbuses[b]-1]*sum(x[2*nb_phases*b_max + nb_phases*b:2*nb_phases*b_max + nb_phases*b +l[jofbuses[b]-1]])
delay_b = delay_b1+delay_b2 +delay_b3
obj = obj + delay_b*ob[b]
obj_b = obj_b + delay_b*ob[b]
return obj
def MINLP(xinit, A, B, A_eq, B_eq, LB ,UB, t, ob, jofbuses, q, qc, s, oa, k, l, T, G_next, C, Y, G_previous):
nb_phases = len(G_next)
b_max = len(t)
## First Solver: IPOPT to get an initial guess
m_IPOPT = GEKKO(remote = True)
m_IPOPT.options.SOLVER = 3 #(IPOPT)
# Array Variable
rows = nb_phases + 3*b_max*(nb_phases+1)#48
x_initial = np.empty(rows,dtype=object)
for i in range(3*nb_phases*b_max+nb_phases+1):
x_initial[i] = m_IPOPT.Var(value = xinit[i], lb = LB[i], ub = UB[i])#, integer = False)
for i in range(3*nb_phases*b_max+nb_phases+1, (3*nb_phases+3)*b_max+nb_phases):
x_initial[i] = m_IPOPT.Var(value = xinit[i], lb = LB[i], ub = UB[i])#, integer = True)
# Constraints
m_IPOPT.axb(A,B,x_initial,etype = '<=',sparse=False)
m_IPOPT.axb(A_eq,B_eq,x_initial,etype = '=',sparse=False)
# Objective Function
f = objective_fun(x_initial, t, ob, jofbuses, q, qc, s, oa, k, l, T, G_next, C, Y, G_previous)
m_IPOPT.Obj(f)
#Solver
m_IPOPT.solve(disp = True)
####################################################################################################
## Second Solver: APOPT to solve MINLP
m_APOPT = GEKKO(remote = True)
m_APOPT.options.SOLVER = 1 #(APOPT)
x = np.empty(rows,dtype=object)
for i in range(3*nb_phases*b_max+nb_phases+1):
x[i] = m_APOPT.Var(value = x_initial[i], lb = LB[i], ub = UB[i], integer = False)
for i in range(3*nb_phases*b_max+nb_phases+1, (3*nb_phases+3)*b_max+nb_phases):
x[i] = m_APOPT.Var(value = x_initial[i], lb = LB[i], ub = UB[i], integer = True)
# Constraints
m_APOPT.axb(A,B,x,etype = '<=',sparse=False)
m_APOPT.axb(A_eq,B_eq,x,etype = '=',sparse=False)
# Objective Function
f = objective_fun(x, t, ob, jofbuses, q, qc, s, oa, k, l, T, G_next, C, Y, G_previous)
m_APOPT.Obj(f)
#Solver
m_APOPT.solve(disp = True)
return x
#Define Parameters
C = 120
T = 31
b_max = 2
G_base = [12,31,12,11,1,41]
G_max = [106, 106, 106, 106, 106, 106]
G_min = [7,3,7,10,0,7]
G_previous = [7.3333333, 34.16763, 7.1333333, 10.0, 2.2008602e-16, 47.365703]
Y = [2, 2, 3, 2, 2, 3]
jofbuses = [9,3]
k = [3,1,6,4,1,2,5,4,2,3]
l = [3,2,6,5,1,3,6,4,3,4]
nb_phases = 6
oa = 1.25
ob = [39,42]
t = [3600.2, 3603.5]
q = [0.038053758888888886, 0.215206065, 0.11325116416666667, 0.06299876472222223,0.02800455611111111,0.18878488361111112,0.2970903402777778, 0.01876728472222222, 0.2192723663888889, 0.06132227222222222]
qc = [0.04083333333333333, 0.2388888888888889, 0.10555555555555556, 0.0525, 0.030555555555555555, 0.20444444444444446,0.31083333333333335, 0.018333333333333333, 0.12777777777777777, 0.07138888888888889]
s = [1.0, 1.0, 1.0, 1.0, 0.5, 1.0, 1.0, 0.5, 0.5, 0.5]
nb_phases = len(G_base)
G_max = []
for i in range(nb_phases):
G_max.append(C - sum(Y[0:nb_phases]))
Optimise_G(t,ob, jofbuses, q, qc, s, oa, k, l, T, G_previous, C, Y, G_previous, G_max, G_min)
The APOPT solver is successful and returns an integer solution.
APMonitor, Version 1.0.0
APMonitor Optimization Suite
----------------------------------------------------------------
--------- APM Model Size ------------
Each time step contains
Objects : 2
Constants : 0
Variables : 48
Intermediates: 0
Connections : 96
Equations : 1
Residuals : 1
Number of state variables: 48
Number of total equations: - 105
Number of slack variables: - 0
---------------------------------------
Degrees of freedom : -57
* Warning: DOF <= 0
----------------------------------------------
Steady State Optimization with APOPT Solver
----------------------------------------------
Iter: 1 I: 0 Tm: 0.00 NLPi: 1 Dpth: 0 Lvs: 3 Obj: 1.64E+04 Gap: NaN
Iter: 2 I: -1 Tm: 0.00 NLPi: 2 Dpth: 1 Lvs: 2 Obj: 1.64E+04 Gap: NaN
Iter: 3 I: 0 Tm: 0.00 NLPi: 3 Dpth: 1 Lvs: 3 Obj: 1.81E+04 Gap: NaN
Iter: 4 I: -1 Tm: 0.01 NLPi: 6 Dpth: 1 Lvs: 2 Obj: 1.64E+04 Gap: NaN
--Integer Solution: 2.15E+04 Lowest Leaf: 1.81E+04 Gap: 1.68E-01
Iter: 5 I: 0 Tm: 0.00 NLPi: 4 Dpth: 2 Lvs: 1 Obj: 2.15E+04 Gap: 1.68E-01
Iter: 6 I: -1 Tm: 0.01 NLPi: 4 Dpth: 2 Lvs: 0 Obj: 1.81E+04 Gap: 1.68E-01
No additional trial points, returning the best integer solution
Successful solution
---------------------------------------------------
Solver : APOPT (v1.0)
Solution time : 4.670000000623986E-002 sec
Objective : 21455.9882666580
Successful solution
---------------------------------------------------
If you need to use remote=False (local solution) on Linux then the new executable will be available with the new release of Gekko. There are some compiler differences and it appears that the Windows FORTRAN compiler that creates the local apm.exe is not as good as the Linux FORTRAN compiler that creates the local apm executable. Those executables are in the bin folder: Lib\site-packages\gekko\bin of the Python folder. | unknown | |
d9582 | train | You can use DismissAction, because PresentationMode will be deprecated. I tried the code and it works perfectly! Here you go!
import SwiftUI
struct MContentView: View {
@State private var presentNavView1 = false
var body: some View {
NavigationView {
List {
NavigationLink(destination: NavView1(), isActive: self.$presentNavView1, label: {
Button(action: {
self.presentNavView1.toggle()
}, label: {
Text("To NavView1")
})
})
}
.navigationTitle("Home")
}
}
}
struct NavView1: View {
@Environment(\.dismiss) private var dismissAction: DismissAction
@State private var presentNavView2 = false
var body: some View {
List {
NavigationLink(destination: NavView2(), isActive: self.$presentNavView2, label: {
Button(action: {
self.presentNavView2.toggle()
}, label: {
Text("To NavView2")
})
})
Button(action: {
self.dismissAction.callAsFunction()
}, label: {
Text("Back")
})
}
.navigationTitle("NavView1")
}
}
struct NavView2: View {
@Environment(\.dismiss) private var dismissAction: DismissAction
var body: some View {
VStack {
Text("NavView2")
Button(action: {
self.dismissAction.callAsFunction()
}, label: {
Text("Back")
})
}
.navigationTitle("NavView2")
}
}
struct MContentView_Previews: PreviewProvider {
static var previews: some View {
MContentView()
}
} | unknown | |
d9583 | train | You should actually be using the first approach and you can access the child elements refs in the parent
class Parent extends Component {
clickDraw = () => {
// when button clicked, get the canvas context and draw on it.
const ctx = this.childCanvas.canvas.getContext('2d');
ctx.fillStyle = "#00FF00";
ctx.fillRect(0,0,275,250);
}
render() {
return (
<div>
<button onClick={this.clickDraw}> Draw </button>
<Child ref={(ip) => this.childCanvas = ip}/>;
</div>
);
}
}
class Child extends Component {
constructor() {
super();
this.canvas = null;
}
componentDidMount() {
const ctx = this.canvas.getContext('2d');
// draw something on the canvas once it's mounted
ctx.fillStyle = "#FF0000";
ctx.fillRect(0,0,150,75);
}
render() {
return (
<canvas width={300}
height={500}
ref={canvasRef => this.canvas = canvasRef}>
</canvas>
);
}
}
You can only use this approach is the child component is declared as a class.
A: If it cannot be avoided the suggested pattern extracted from the React docs would be:
import React, {Component} from 'react';
const Child = ({setRef}) => <input type="text" ref={setRef} />;
class Parent extends Component {
constructor(props) {
super(props);
this.setRef = this.setRef.bind(this);
}
componentDidMount() {
// Call function on Child dom element
this.childInput.focus();
}
setRef(input) {
this.childInput = input;
}
render() {
return <Child setRef={this.setRef} />
}
}
The Parent passes a function as prop bound to Parent's this. React will call the Child's ref callback setRef and attach the childInput property to this which as we already noted points to the Parent. | unknown | |
d9584 | train | This might fix the issue.
e.Graphics.DrawImage(img, e.MarginBounds);
or
e.Graphics.DrawImage(img, e.PageBounds);
or
ev.Graphics.DrawImage(Image.FromFile("C:\\My Folder\\MyFile.bmp"), ev.Graphics.VisibleClipBounds); | unknown | |
d9585 | train | try this
<!DOCTYPE html>
<html>
<body>
<?php
$row = "A1 Header";
$compulsary = FALSE;
$mutable = TRUE;
$included = FALSE;
if ($compulsary == FALSE and $mutable == TRUE) {
echo "<textarea style=background-color:yellow; name=\"message\">Please Enter</textarea><br>";
} elseif ($compulsary == FALSE and $mutable == FALSE) {
echo "'".$row."'";
} elseif ($compulsary == True and $mutable == True) {
echo "<textarea style=background-color:yellow; name=\"message\">Please Enter</textarea><br>";
} else {
echo "'".$row."'";
}
?>
</body>
</html>
A: You can do like this:
<!DOCTYPE html>
<html>
<body>
<?php
$row = "A1 Header";
$compulsary = FALSE;
$mutable = TRUE;
$included = FALSE;
if ($compulsary == FALSE and $mutable == TRUE) {
echo "<textarea style='background-color:yellow;' name='\"message\"'>Please Enter</textarea><br>";
}
elseif ($compulsary == FALSE and $mutable == FALSE){
echo $row;
}
elseif ($compulsary == TRUE and $mutable == TRUE) {
echo "<textarea style='background-color:yellow;' name='\"message\"'>Please Enter</textarea><br>";
}
else {
echo $row;
}
?>
</body>
</html>
A: I think you have a syntax error. Try this:
echo "'\"$row\"'"; | unknown | |
d9586 | train | Use of mysqli is quite simple actually just need to call the query function of a mysqli object, equivalent would be:
//Instantiate mysqli db object
$sqli = new mysqli('host', 'user', 'password', 'db');
if ($sqli->connect_error)
die ("Could not connect to db: " . $db->connect_error);
//Make query
$sqli->query("SHOW FIELDS FROM $table") or die("Some error " . $sqli->error);
$sqli->close(); | unknown | |
d9587 | train | You would need to do this:
myReader.GetString(0);
However, there is a bit more that needs done here. You need to leverage the ADO.NET objects properly:
var sql = "select BillNumber from BillData";
using (SqlConnection cn = new SqlConnection(cString))
using (SqlCommand cmd = new SqlCommand(sql, cn))
using (SqlDataReader rdr = cmd.ExecuteReader())
{
rdr.Read();
MessageBox.Show(rdr.GetString(0));
}
A: SqlDataReader myReader = null;
SqlCommand myCommand = new SqlCommand("select BillNumber from BillData", cn);
cn.Open();
myReader = myCommand.ExecuteReader();
myReader.Read();
MessageBox.Show(myReader["BillNumber"].ToString());
cn.Close();
A: When you just want one return value, you can use ExecuteScalar() like this:
SqlCommand myCommand = new SqlCommand("select BillNumber from BillData", cn);
cn.Open();
string return_value = myCommand.ExecuteScalar().ToString();
MessageBox.Show(return_value);
cn.Close(); | unknown | |
d9588 | train | --secondsLeft updates the variable. To check if the next decrement will be 0, use if (secondsLeft - 1 == 0)
Each tick is decrementing the variable twice.
Additionally, this will trigger the "Completed" text on 1, not 0. Below is a better way to handle this:
-(void) updateCountdown {
int hours, minutes, seconds;
secondsLeft--;
if (secondsLeft == 0) {
[tktTimer invalidate];
countDownlabel.text = @"Completed";
return;
}
NSLog(@"secondsLeft %d",secondsLeft);//every time it is printing 9,7,5,3,1 but should print 9,8,7,6,5,4,3,2,1,0
hours = secondsLeft / 3600;
minutes = (secondsLeft % 3600) / 60;
seconds = (secondsLeft %3600) % 60;
countDownlabel.text = [NSString stringWithFormat:@"%02d:%02d:%02d", hours, minutes, seconds];
}
A: //sweet and simple way to perform timer with easy and understandable code
DECLARE
int seconds;
NSTimer *timer;
//in viewDidLoad method
seconds=12;
timer=[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(GameOver) userInfo:nil repeats:YES ];
-(void)GameOver
{
seconds-=1;
lblUpTimer.text=[NSString stringWithFormat:@"%d",seconds];//shows counter in label
if(seconds==0)
[timer invalidate];
}
THANK YOU | unknown | |
d9589 | train | Your code has already consumed the first two columns from the stream and the position of the stream is past those columns. In turn, it isn't necessary to call ignore to move the stream position past those columns. Besides ignore ifstream provides some additional functions that you may find useful. | unknown | |
d9590 | train | I believe that the real answer is that you can't. The file path won't be sent by the browser for security reasons. The file name will be sent, however I don't believe it gets sent without an actual upload.
The closest you could come, afaik, would be to forcibly kill the connection just when the upload starts. That would net you the filename with little actual transferred data, but it doesn't sound like it would be useful to you.
Alternatively, a signed Java applet might get you closer to a solution that you'd want. | unknown | |
d9591 | train | Your loop control variable i is incremented by one in the for loop:
for(i=0; i<40; i++)
and then by a further 3 by:
i=i+3;
So i is overall incremented by 4 in each iteration. Pointer arithmetic accounts for the size of the object pointed to. Here you are pointing to a 32 bit (4 byte) integer, and incrementing by 4 each time, so the address is incremented by 4 x 4 = 16 bytes.
You should have:
for( i = 0; i < 10; i++ )
{
int* temp = mem_allocate + i ;
// i=i+3; REMOVE THIS!
...
Note that the cast was unnecessary; mem_allocate was already an int* as is the type of the expression mem_allocate + i.
Your code is flawed in other ways, unrelated to the question you have asked - specifically the ill-advised modification of mem_allocate - if you modify it, any attempt to free it will be invalid.
Consider:
#include <stdint.h>
#include <stdlib.h>
int main()
{
const int n = 1024;
uint32_t* mem_allocate = malloc( n * sizeof(*mem_allocate) ) ;
for( int i = 0; i < n; i++ )
{
mem_allocate[i] = 0xAAAAAAAAu;
}
free( mem_allocate ) ;
return 0 ;
}
As you can see you made a simple thing unnecessarily complicated. | unknown | |
d9592 | train | Assuming you don't care about HTML-encoding characters that are special in HTML (e.g., <, &, etc.), a simple loop over the string will work:
string input = "Steel Décor";
StringBuilder output = new StringBuilder();
foreach (char ch in input)
{
if (ch > 0x7F)
output.AppendFormat("&#{0};", (int) ch);
else
output.Append(ch);
}
// output.ToString() == "Steel Décor"
The if statement may need to be changed to also escape characters < 0x20, or non-alphanumeric, etc., depending on your exact needs.
A: HttpUtility.HtmlEncode does that. It resides in System.Web.dll though so won't work with .NET 4 Client Profile for example.
A: using LINQ
string toDec(string input)
{
Dictionary<string, char> resDec =
(from p in input.ToCharArray() where p > 127 select p).Distinct().ToDictionary(
p => String.Format(@"&#x{0:D};", (ushort)p));
foreach (KeyValuePair<string, char> pair in resDec)
input = input.Replace(pair.Value.ToString(), pair.Key);
return input;
} | unknown | |
d9593 | train | I didn't have a solution, just a workaround.
Windows Vista onwards has an inbuilt command called clip that takes the output of a command from command line and puts it into the clipboard. For example, ipconfig | clip.
So I made a function with the os module which takes a string and adds it to the clipboard using the inbuilt Windows solution.
import os
def addToClipBoard(text):
command = 'echo ' + text.strip() + '| clip'
os.system(command)
# Example
addToClipBoard('penny lane')
# Penny Lane is now in your ears, eyes, and clipboard.
As previously noted in the comments however, one downside to this approach is that the echo command automatically adds a newline to the end of your text. To avoid this you can use a modified version of the command:
def addToClipBoard(text):
command = 'echo | set /p nul=' + text.strip() + '| clip'
os.system(command)
If you are using Windows XP it will work just following the steps in Copy and paste from Windows XP Pro's command prompt straight to the Clipboard.
A: Looks like you need to add win32clipboard to your site-packages. It's part of the pywin32 package
A: You can use pyperclip - cross-platform clipboard module. Or Xerox - similar module, except requires the win32 Python module to work on Windows.
A: Not all of the answers worked for my various python configurations so this solution only uses the subprocess module. However, copy_keyword has to be pbcopy for Mac or clip for Windows:
import subprocess
subprocess.run('copy_keyword', universal_newlines=True, input='New Clipboard Value ')
Here's some more extensive code that automatically checks what the current operating system is:
import platform
import subprocess
copy_string = 'New Clipboard Value '
# Check which operating system is running to get the correct copying keyword.
if platform.system() == 'Darwin':
copy_keyword = 'pbcopy'
elif platform.system() == 'Windows':
copy_keyword = 'clip'
subprocess.run(copy_keyword, universal_newlines=True, input=copy_string)
A: The simplest way is with pyperclip. Works in python 2 and 3.
To install this library, use:
pip install pyperclip
Example usage:
import pyperclip
pyperclip.copy("your string")
If you want to get the contents of the clipboard:
clipboard_content = pyperclip.paste()
A: You can also use ctypes to tap into the Windows API and avoid the massive pywin32 package. This is what I use (excuse the poor style, but the idea is there):
import ctypes
# Get required functions, strcpy..
strcpy = ctypes.cdll.msvcrt.strcpy
ocb = ctypes.windll.user32.OpenClipboard # Basic clipboard functions
ecb = ctypes.windll.user32.EmptyClipboard
gcd = ctypes.windll.user32.GetClipboardData
scd = ctypes.windll.user32.SetClipboardData
ccb = ctypes.windll.user32.CloseClipboard
ga = ctypes.windll.kernel32.GlobalAlloc # Global memory allocation
gl = ctypes.windll.kernel32.GlobalLock # Global memory Locking
gul = ctypes.windll.kernel32.GlobalUnlock
GMEM_DDESHARE = 0x2000
def Get():
ocb(None) # Open Clip, Default task
pcontents = gcd(1) # 1 means CF_TEXT.. too lazy to get the token thingy...
data = ctypes.c_char_p(pcontents).value
#gul(pcontents) ?
ccb()
return data
def Paste(data):
ocb(None) # Open Clip, Default task
ecb()
hCd = ga(GMEM_DDESHARE, len(bytes(data,"ascii")) + 1)
pchData = gl(hCd)
strcpy(ctypes.c_char_p(pchData), bytes(data, "ascii"))
gul(hCd)
scd(1, hCd)
ccb()
A: You can use the excellent pandas, which has a built in clipboard support, but you need to pass through a DataFrame.
import pandas as pd
df=pd.DataFrame(['Text to copy'])
df.to_clipboard(index=False,header=False)
A: I think there is a much simpler solution to this.
name = input('What is your name? ')
print('Hello %s' % (name) )
Then run your program in the command line
python greeter.py | clip
This will pipe the output of your file to the clipboard
A: Here's the most easy and reliable way I found if you're okay depending on Pandas. However I don't think this is officially part of the Pandas API so it may break with future updates. It works as of 0.25.3
from pandas.io import clipboard
clipboard.copy("test")
A: Actually, pywin32 and ctypes seem to be an overkill for this simple task. tkinter is a cross-platform GUI framework, which ships with Python by default and has clipboard accessing methods along with other cool stuff.
If all you need is to put some text to system clipboard, this will do it:
from tkinter import Tk # in Python 2, use "Tkinter" instead
r = Tk()
r.withdraw()
r.clipboard_clear()
r.clipboard_append('i can has clipboardz?')
r.update() # now it stays on the clipboard after the window is closed
r.destroy()
And that's all, no need to mess around with platform-specific third-party libraries.
If you are using Python 2, replace tkinter with Tkinter.
A: Widgets also have method named .clipboard_get() that returns the contents of the clipboard (unless some kind of error happens based on the type of data in the clipboard).
The clipboard_get() method is mentioned in this bug report:
http://bugs.python.org/issue14777
Strangely, this method was not mentioned in the common (but unofficial) online TkInter documentation sources that I usually refer to.
A: Solution with stdlib, without security issues
The following solution works in Linux without any additional library and without the risk of executing unwanted code in your shell.
import subprocess
def to_clipboard(text: str) -> None:
sp = subprocess.Popen(["xclip"], stdin=subprocess.PIPE,
stdout=subprocess.PIPE)
sp.communicate(text.encode("utf8"))
Note that there multiple clipboard in Linux, the you use with the Middle Mouse (Primary) and yet another that you use pressing STRG+C,STRG+V.
You can define which clipboard is used by adding a selection parameter i.e. ["xclip", "-selection", "clipboard"].
See the man xclip for details.
If you using Windows, just replace xclip with clip.
This solution works without Tkinter, which not available some Python installations (i.e. the custom build I am currently using).
A: For some reason I've never been able to get the Tk solution to work for me. kapace's solution is much more workable, but the formatting is contrary to my style and it doesn't work with Unicode. Here's a modified version.
import ctypes
from ctypes.wintypes import BOOL, HWND, HANDLE, HGLOBAL, UINT, LPVOID
from ctypes import c_size_t as SIZE_T
OpenClipboard = ctypes.windll.user32.OpenClipboard
OpenClipboard.argtypes = HWND,
OpenClipboard.restype = BOOL
EmptyClipboard = ctypes.windll.user32.EmptyClipboard
EmptyClipboard.restype = BOOL
GetClipboardData = ctypes.windll.user32.GetClipboardData
GetClipboardData.argtypes = UINT,
GetClipboardData.restype = HANDLE
SetClipboardData = ctypes.windll.user32.SetClipboardData
SetClipboardData.argtypes = UINT, HANDLE
SetClipboardData.restype = HANDLE
CloseClipboard = ctypes.windll.user32.CloseClipboard
CloseClipboard.restype = BOOL
CF_UNICODETEXT = 13
GlobalAlloc = ctypes.windll.kernel32.GlobalAlloc
GlobalAlloc.argtypes = UINT, SIZE_T
GlobalAlloc.restype = HGLOBAL
GlobalLock = ctypes.windll.kernel32.GlobalLock
GlobalLock.argtypes = HGLOBAL,
GlobalLock.restype = LPVOID
GlobalUnlock = ctypes.windll.kernel32.GlobalUnlock
GlobalUnlock.argtypes = HGLOBAL,
GlobalSize = ctypes.windll.kernel32.GlobalSize
GlobalSize.argtypes = HGLOBAL,
GlobalSize.restype = SIZE_T
GMEM_MOVEABLE = 0x0002
GMEM_ZEROINIT = 0x0040
unicode_type = type(u'')
def get():
text = None
OpenClipboard(None)
handle = GetClipboardData(CF_UNICODETEXT)
pcontents = GlobalLock(handle)
size = GlobalSize(handle)
if pcontents and size:
raw_data = ctypes.create_string_buffer(size)
ctypes.memmove(raw_data, pcontents, size)
text = raw_data.raw.decode('utf-16le').rstrip(u'\0')
GlobalUnlock(handle)
CloseClipboard()
return text
def put(s):
if not isinstance(s, unicode_type):
s = s.decode('mbcs')
data = s.encode('utf-16le')
OpenClipboard(None)
EmptyClipboard()
handle = GlobalAlloc(GMEM_MOVEABLE | GMEM_ZEROINIT, len(data) + 2)
pcontents = GlobalLock(handle)
ctypes.memmove(pcontents, data, len(data))
GlobalUnlock(handle)
SetClipboardData(CF_UNICODETEXT, handle)
CloseClipboard()
paste = get
copy = put
The above has changed since this answer was first created, to better cope with extended Unicode characters and Python 3. It has been tested in both Python 2.7 and 3.5, and works even with emoji such as \U0001f601 ().
Update 2021-10-26: This was working great for me in Windows 7 and Python 3.8. Then I got a new computer with Windows 10 and Python 3.10, and it failed for me the same way as indicated in the comments. This post gave me the answer. The functions from ctypes don't have argument and return types properly specified, and the defaults don't work consistently with 64-bit values. I've modified the above code to include that missing information.
A: I've tried various solutions, but this is the simplest one that passes my test:
#coding=utf-8
import win32clipboard # http://sourceforge.net/projects/pywin32/
def copy(text):
win32clipboard.OpenClipboard()
win32clipboard.EmptyClipboard()
win32clipboard.SetClipboardText(text, win32clipboard.CF_UNICODETEXT)
win32clipboard.CloseClipboard()
def paste():
win32clipboard.OpenClipboard()
data = win32clipboard.GetClipboardData(win32clipboard.CF_UNICODETEXT)
win32clipboard.CloseClipboard()
return data
if __name__ == "__main__":
text = "Testing\nthe “clip—board”: "
try: text = text.decode('utf8') # Python 2 needs decode to make a Unicode string.
except AttributeError: pass
print("%r" % text.encode('utf8'))
copy(text)
data = paste()
print("%r" % data.encode('utf8'))
print("OK" if text == data else "FAIL")
try: print(data)
except UnicodeEncodeError as er:
print(er)
print(data.encode('utf8'))
Tested OK in Python 3.4 on Windows 8.1 and Python 2.7 on Windows 7. Also when reading Unicode data with Unix linefeeds copied from Windows. Copied data stays on the clipboard after Python exits: "Testing
the “clip—board”: "
If you want no external dependencies, use this code (now part of cross-platform pyperclip - C:\Python34\Scripts\pip install --upgrade pyperclip):
def copy(text):
GMEM_DDESHARE = 0x2000
CF_UNICODETEXT = 13
d = ctypes.windll # cdll expects 4 more bytes in user32.OpenClipboard(None)
try: # Python 2
if not isinstance(text, unicode):
text = text.decode('mbcs')
except NameError:
if not isinstance(text, str):
text = text.decode('mbcs')
d.user32.OpenClipboard(0)
d.user32.EmptyClipboard()
hCd = d.kernel32.GlobalAlloc(GMEM_DDESHARE, len(text.encode('utf-16-le')) + 2)
pchData = d.kernel32.GlobalLock(hCd)
ctypes.cdll.msvcrt.wcscpy(ctypes.c_wchar_p(pchData), text)
d.kernel32.GlobalUnlock(hCd)
d.user32.SetClipboardData(CF_UNICODETEXT, hCd)
d.user32.CloseClipboard()
def paste():
CF_UNICODETEXT = 13
d = ctypes.windll
d.user32.OpenClipboard(0)
handle = d.user32.GetClipboardData(CF_UNICODETEXT)
text = ctypes.c_wchar_p(handle).value
d.user32.CloseClipboard()
return text
A: If you don't like the name you can use the derivative module clipboard.
Note: It's just a selective wrapper of pyperclip
After installing, import it:
import clipboard
Then you can copy like this:
clipboard.copy("This is copied")
You can also paste the copied text:
clipboard.paste()
A: Use pyperclip module
Install using pip pip install pyperclip.
*
*https://pypi.org/project/pyperclip/
Copy text "Hello World!" to clip board
import pyperclip
pyperclip.copy('Hello World!')
You can use Ctrl+V anywhere to paste this somewhere.
Paste the copied text using python
pyperclip.paste() # This returns the copied text of type <class 'str'>
A: This is an improved answer of atomizer. Note that
*
*there are 2 calls of update() and
*inserted 200 ms delay between them.
They protect freezing applications due to an unstable state of the clipboard:
from Tkinter import Tk
import time
r = Tk()
r.withdraw()
r.clipboard_clear()
r.clipboard_append('some string')
r.update()
time.sleep(.2)
r.update()
r.destroy()
A: In addition to Mark Ransom's answer using ctypes:
This does not work for (all?) x64 systems since the handles seem to be truncated to int-size.
Explicitly defining args and return values helps to overcomes this problem.
import ctypes
import ctypes.wintypes as w
CF_UNICODETEXT = 13
u32 = ctypes.WinDLL('user32')
k32 = ctypes.WinDLL('kernel32')
OpenClipboard = u32.OpenClipboard
OpenClipboard.argtypes = w.HWND,
OpenClipboard.restype = w.BOOL
GetClipboardData = u32.GetClipboardData
GetClipboardData.argtypes = w.UINT,
GetClipboardData.restype = w.HANDLE
EmptyClipboard = u32.EmptyClipboard
EmptyClipboard.restype = w.BOOL
SetClipboardData = u32.SetClipboardData
SetClipboardData.argtypes = w.UINT, w.HANDLE,
SetClipboardData.restype = w.HANDLE
CloseClipboard = u32.CloseClipboard
CloseClipboard.argtypes = None
CloseClipboard.restype = w.BOOL
GHND = 0x0042
GlobalAlloc = k32.GlobalAlloc
GlobalAlloc.argtypes = w.UINT, w.ctypes.c_size_t,
GlobalAlloc.restype = w.HGLOBAL
GlobalLock = k32.GlobalLock
GlobalLock.argtypes = w.HGLOBAL,
GlobalLock.restype = w.LPVOID
GlobalUnlock = k32.GlobalUnlock
GlobalUnlock.argtypes = w.HGLOBAL,
GlobalUnlock.restype = w.BOOL
GlobalSize = k32.GlobalSize
GlobalSize.argtypes = w.HGLOBAL,
GlobalSize.restype = w.ctypes.c_size_t
unicode_type = type(u'')
def get():
text = None
OpenClipboard(None)
handle = GetClipboardData(CF_UNICODETEXT)
pcontents = GlobalLock(handle)
size = GlobalSize(handle)
if pcontents and size:
raw_data = ctypes.create_string_buffer(size)
ctypes.memmove(raw_data, pcontents, size)
text = raw_data.raw.decode('utf-16le').rstrip(u'\0')
GlobalUnlock(handle)
CloseClipboard()
return text
def put(s):
if not isinstance(s, unicode_type):
s = s.decode('mbcs')
data = s.encode('utf-16le')
OpenClipboard(None)
EmptyClipboard()
handle = GlobalAlloc(GHND, len(data) + 2)
pcontents = GlobalLock(handle)
ctypes.memmove(pcontents, data, len(data))
GlobalUnlock(handle)
SetClipboardData(CF_UNICODETEXT, handle)
CloseClipboard()
#Test run
paste = get
copy = put
copy("Hello World!")
print(paste())
A: also you can use > clipboard
import clipboard
def copy(txt):
clipboard.copy(txt)
copy("your txt")
A: If (and only if) the application already uses Qt, you can use this (with the advantage of no additional third party dependency)
from PyQt5.QtWidgets import QApplication
clipboard = QApplication.clipboard()
# get text (if there's text inside instead of e.g. file)
clipboard.text()
# set text
clipboard.setText(s)
This requires a Qt application object to be already constructed, so it should not be used unless the application already uses Qt.
Besides, as usual, in X systems (and maybe other systems too), the content only persist until the application exists unless you use something like parcellite or xclipboard.
Documentation:
*
*QGuiApplication Class | Qt GUI 5.15.6
*QClipboard Class | Qt GUI 5.15.6
See also: python - PyQT - copy file to clipboard - Stack Overflow
A: import wx
def ctc(text):
if not wx.TheClipboard.IsOpened():
wx.TheClipboard.Open()
data = wx.TextDataObject()
data.SetText(text)
wx.TheClipboard.SetData(data)
wx.TheClipboard.Close()
ctc(text)
A: The snippet I share here take advantage of the ability to format text files: what if you want to copy a complex output to the clipboard ? (Say a numpy array in column or a list of something)
import subprocess
import os
def cp2clip(clist):
#create a temporary file
fi=open("thisTextfileShouldNotExist.txt","w")
#write in the text file the way you want your data to be
for m in clist:
fi.write(m+"\n")
#close the file
fi.close()
#send "clip < file" to the shell
cmd="clip < thisTextfileShouldNotExist.txt"
w = subprocess.check_call(cmd,shell=True)
#delete the temporary text file
os.remove("thisTextfileShouldNotExist.txt")
return w
works only for windows, can be adapted for linux or mac I guess. Maybe a bit complicated...
example:
>>>cp2clip(["ET","phone","home"])
>>>0
Ctrl+V in any text editor :
ET
phone
home
A: Use python's clipboard library!
import clipboard as cp
cp.copy("abc")
Clipboard contains 'abc' now. Happy pasting!
A: You can use winclip32 module!
install:
pip install winclip32
to copy:
import winclip32
winclip32.set_clipboard_data(winclip32.UNICODE_STD_TEXT, "some text")
to get:
import winclip32
print(winclip32.get_clipboard_data(winclip32.UNICODE_STD_TEXT))
for more informations: https://pypi.org/project/winclip32/
A: On Windows, you can use this. No external dependencies neither have to open sub-process:
import win32clipboard
def to_clipboard(txt):
win32clipboard.OpenClipboard()
win32clipboard.EmptyClipboard()
win32clipboard.SetClipboardText(txt)
win32clipboard.CloseClipboard()
A: My multiplatform solution base on this question:
import subprocess
import distutils.spawn
def clipit(text):
if distutils.spawn.find_executable("xclip"):
# for Linux
subprocess.run(["xclip", "-i"], input=text.encode("utf8"))
elif distutils.spawn.find_executable("xsel"):
# for Linux
subprocess.run(["xsel", "--input"], input=text.encode("utf8"))
elif distutils.spawn.find_executable("clip"):
# for Windows
subprocess.run(["clip"], input=text.encode("utf8"))
else:
import pyperclip
print("I use module pyperclip.")
pyperclip.copy(text)
A: you can try this:
command = 'echo content |clip'
subprocess.check_call(command, shell=True)
A: Code snippet to copy the clipboard:
Create a wrapper Python code in a module named (clipboard.py):
import clr
clr.AddReference('System.Windows.Forms')
from System.Windows.Forms import Clipboard
def setText(text):
Clipboard.SetText(text)
def getText():
return Clipboard.GetText()
Then import the above module into your code.
import io
import clipboard
code = clipboard.getText()
print code
code = "abcd"
clipboard.setText(code)
I must give credit to the blog post Clipboard Access in IronPython. | unknown | |
d9594 | train | That is not necessary - if your application has no more references to the HashMap, then it will be garbage collected automatically at some point in the future.
If you really have a huge hash map that you want to get rid off to avoid its memory consumption trigger GC cycles after doSomething completes, you can call System.gc(), but this is in general neither needed nor a recommended practice.
A: Calling .clear on a HashMap doesn't remove it from memory; it simply clears it of preexisting mappings and so the object will still exist in memory.
Since Scala runs on the JVM, I would imagine that it will get collected by the garbage collector at some point in the future (assuming that there are no existing-references to associations). The JVM manages its own memory, thus freeing the programmer of the burden of manually-managing memory.
A: The binding associations ceases to exist when the scope in which it was created ceases to exist (when a given call to doSomething returns). That removes one reference to the HashMap and once there are none left, the value is garbage and subject to reclamation at an unspecified time in the future (possibly never / not before the JVM exits). | unknown | |
d9595 | train | A delete operation should have a business meaning. For example, just because someone deleted a product from the inventory collection, does not mean it should be deleted from users invoices.
If there is a real need for a delete. You can always define an index in RavenDB and update the entities containing that aggregate root ID.
A: I do not know if DDD speaks to your problem directly but the proposed "solution" may lie in Domain Events / Messaging. If the related aggregate is in the same bounded context a domain event may suffice else you may need messaging infrastructure to communicate with another bounded context.
What happens when you receive the 'deleted' event is another story and possibly your domain experts can help. As alluded to by @Dmitry S. you may need to denormalize the related aggregate data into a value object so that you have enough information to keep the main aggregate consistent. When processing the 'deleted' event then you may want to set some indicator on your main aggregate or update the data somehow to reflect the deletion.
A: Why would you ever delete an aggregate? You might want to Expire() it or Suspend(). Deactivate(), Disable(), Ban(), Cancel(), Finish() or Archive(). But what benefit would you get from loosing your data with Delete()?
If you really need that (possibly due to legal purposes) maybe some EvaporaitonService should be created and it would find all related aggregates and whipe all references. | unknown | |
d9596 | train | You can avoid this by using the insomnia plugin | unknown | |
d9597 | train | Firstly your arguments to replace() are the wrong way around. Secondly, you need to actually set the value after making the replacement. Lastly you'll also need to provide another function argument to hover() that sets the original image back on mouseout. Try this:
$(".navbar-nav li a").hover(function() {
$(this).children("img").prop('src', function(i, src) {
return src.replace('static', 'hover');
})
}, function() {
$(this).children("img").prop('src', function(i, src) {
return src.replace('hover', 'static');
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="navbar-nav">
<li class="active">
<a href="#">
<img src="images/static/personal_information.png" class="img-responsive center-block">
<span>Personal<br> Information</span>
</a>
</li>
</ul>
A: You are replacing src code, but not assigning it back.
$(".navbar-nav li a").hover(function(){
var newSrc = $(this).children("img").attr('src').replace('hover','static');
$(this).children('img').attr('src', newSrc)
});
A: Why are you targeting <a>, then select its child <img>? Why not apply that to the image directly?
$(".navbar-nav li a img").hover(function(){
$(this).attr('src') = $(this).attr('src').replace('hover','static');
}); | unknown | |
d9598 | train | In the UI, you should add, click,doubleclick or hover:
plotOutput("plot1", click = "plot_click")
And in the Server will be input$plot_click, X and Y coordinates
Here a Shiny explanation:
https://shiny.rstudio.com/articles/plot-interaction.html
And I wrote for you a simple example:
library(shiny)
library(ggplot2)
library(MASS)
ui<- shinyUI(
fluidPage(
plotOutput("grafica", hover="clickGrafica"),
tableOutput("miverbatini")
)
)
server<- shinyServer(function(input,output) {
output$grafica <- renderPlot({
ggplot(mpg,aes(x=cty, y=hwy)) +
geom_point()
})
output$miverbatini <- renderTable({
nearPoints(mpg,input$clickGrafica, threshold = 10) # near points 20
})
})
shinyApp(ui, server) | unknown | |
d9599 | train | Check this link - http://code.google.com/mobile/afma_ads/docs/ it explains it all (well most of it to get started!)
I went on a similar path looking for a ad serving support in my android app - eventually I settled for Mobclix - I am happy :-) Check the question I had posed at Serving Ads in Android App - | unknown | |
d9600 | train | accuracy: 0.9925; val_accuracy: 0.8258
Clearly the model is overfitted,
*
*Try using regularization techniques such as L2,L1 or Dropout, they will work.
*Try to Collect More data(Or use data augumentation)
*Or search for other Neural Network Architectures
*The best method is plot val_loss v/s loss
r = model.fit(x_train, y_train, validation_data=(x_test, y_test), epochs=15)
import matplotlib.pyplot as plt
plt.plot(r.history['loss'], label='loss')
plt.plot(r.history['val_loss'], label='val_loss')
plt.legend()
and check the point where loss and val_loss meet each other and then at the point of intersection see the number of epochs (say x) and train the model for x epochs only.
Hope you will find this useful.
A: Model is overfitted...use dropout layer.. I think it will help
Model.add(Dropout(0.2)) | unknown |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.