_id
stringlengths 2
6
| partition
stringclasses 3
values | text
stringlengths 4
46k
| language
stringclasses 1
value | title
stringclasses 1
value |
---|---|---|---|---|
d14301 | val | It looks like your template substitution is not working. Have you tried either making sure you have a maven property appengine.sdk.version define, or substituting the placeholder with a fixed version of appengine-tools-sdk? | unknown | |
d14302 | val | Your pipeline executing agent doesn't communicate with docker daemon, so you need to configure it properly and you have three ways (the ones I know):
1) Provide your agent with a docker installation
2) Add a Docker installation from https:/$JENKINS_URL/configureTools/
3) If you use Kubernetes as orchestrator you may add a podTemplate definition at the beginning of your pipeline and then use it, here an example:
// Name of the application (do not use spaces)
def appName = "my-app"
// Start of podTemplate
def label = "mypod-${UUID.randomUUID().toString()}"
podTemplate(
label: label,
containers: [
containerTemplate(
name: 'docker',
image: 'docker',
command: 'cat',
ttyEnabled: true)],
volumes: [
hostPathVolume(hostPath: '/var/run/docker.sock', mountPath: '/var/run/docker.sock'),
hostPathVolume(hostPath: '/usr/bin/kubectl', mountPath: '/usr/bin/kubectl'),
secretVolume(mountPath: '/etc/kubernetes', secretName: 'cluster-admin')],
annotations: [
podAnnotation(key: "development", value: appName)]
)
// End of podTemplate
[...inside your pipeline]
container('docker') {
stage('Docker Image and Push') {
docker.withRegistry('https://registry.domain.it', 'nexus') {
def img = docker.build(appName, '.')
img.push('latest')
}
I hope this helps you | unknown | |
d14303 | val | You can disable edit text focus by using below code on your main layout
<AutoCompleteTextView
android:id="@+id/autotext"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:nextFocusLeft="@id/autotext"
android:nextFocusUp="@id/autotext" />
A: you can do this
clear focus from et1 and also request focus when it goes touch
et1.setOnEditorActionListener((v1, actionId, event) -> {
if (actionId == EditorInfo.IME_ACTION_DONE) {
et1.clearFocus();
et1.requestFocusFromTouch();
}
return false;
});
Suggestion : No need to hide keyboard when you click done editor option | unknown | |
d14304 | val | If you are using Chrome: Inspect > Application > Cookies > csrftoken | unknown | |
d14305 | val | It seems you want your Singleton to store a variable. Make a function that sets the variable and leave the constructor empty.
A: Don't use a default value in the constructor. For your singleton, just pass the default value of zero if you don't want to use it. Or, define two constructors, one without your argument, and one with it.
Also, if you want to use the constructor from another Form (or any other class), it cannot be defined as private. Define it as public instead.
public Form1(int number) : this() //call the default constructor so that InitializeComponents() is still called
{
test_number = number;
}
public Form1()
{
InitializeComponent();
} | unknown | |
d14306 | val | Start using DateTime class for date/time manipulation/compare :
If you change your code to this :
$currentDate = new DateTime();
$lessWeek = new DateTime("-1 week");
$plusWeek = new DateTime("+1 week");
$plus12Hour = new DateTime("+12 hour");
... then your IF statements will start to work.
A: You are doing the date comparisons completely WRONG. You're comparing date STRINGS, e.g. using some dates formatted the same way you're doing:
$plusWeek = '26-08-2013 8:30'; Aug 26th, 2013
$accSubs = '9-08-2013 10:45'; Aug 9th, 2013
Since these are strings, string comparison rules apply. That means the strings are compared character by character, and (string)26 is actually LESS than string(9), because 2 is smaller than 9.
You need to keep things as the raw timestamps, e.g. the strtotime() output:
$plusWeek = strtotime('2013-08-26 08:30'); // 1377527400
$accSubs = strtotime('2013-08-09 10:45').; // 1376066700
Comparing these integer values will work as you want.
The main problem is also that you're not formatted your data strings in "most significant data" order. If they were formatted with the year first, e.g.
yyyy-mm-dd hh:mm:ss
then a string comparison WOULD work as a side effect.
A: If you want to compare dates you have to compare arguments returned by strtotime() function, for example:
elseif(strtotime($plus12Hour) > strtotime($charQueueEnd)){ | unknown | |
d14307 | val | In your code, you can attempt to change the argument of the sort to be an array instead of an object, like this:
sort: [["Category","asc"],["another argument","desc"],[...]]
so the code :
Template.categories.lists = function() {
return lists.find({}, {
sort: [
["Category", "asc"],
["another argument", "desc"],
[...]
]
});
// return lists.find({}); // Works just the same
}
A: As per my understanding that is because default is to sort by natural order. More info can be found at this link | unknown | |
d14308 | val | This might work for you (GNU sed):
sed -i '4~4s/.*/another string/' file(s)
Starting at the 4th line and every 4 lines thereafter, replace the whole line with another string.
A: I'd use awk for this
awk '
NR % 4 == 0 {print "new string"; next}
{print}
' file > file.new && mv file.new file | unknown | |
d14309 | val | You can make a wrapper function which will call the two other functions like this:
function wrapperFunction(e){
p1movimentation(e);
p2movimentation(e);
}
function p1movimentation(e){
console.log("p1movimentation");
}
function p2movimentation(e){
console.log("p2movimentation");
}
<body onkeydown="wrapperFunction();"></body>
A: There's no way to do it.
Javascript is single-threaded. It can only do one thing at a time. Even when you attach multiple event listeners to something, javascript will still run each event listener one at a time. If another event fires while javascript is busy doing something, it won't go run the relevant code until it finishes what it's currently doing. The way javascript does this is referred to as the event loop.
To get your desired effect, you'll likely have to rethink what your two functions are doing. Maybe you need to split up the functions, so that the functions can take turns? e.g. onkeydown="p1move();p2move();p1cleanUp();p2cleanUp()". If you edit your question with the bodies of these functions, we might be able to help out more.
EDIT
I think I've figured out what the issue is here. You're relying on the fact that keydown is repeatedly fired as the user holds down a key, but the issue is if the user holds down a second key, then that second key starts repeatedly firing instead.
What you need to do instead is keep track of which keys are currently being held down. Then, you could, for example, make a game loop that runs every so often that'll check which keys are currently being pressed, and react accordingly.
In order to know which keys are currently being pressed, you'll need to listen to both the keydown event and the keyup event. (when keydown is fired, add the key to a list. When keyup is fired, remove the key from the list).
This stackoverflow answer explains the same thing but in a lot more detail. The question is referring to the same thing you're struggling with. | unknown | |
d14310 | val | I believe you are confusing data-types here. A phone number for instance, is not a number. But it's called a number! Yeah I know, because it has a lot of numbers in it, but still, it isn't a number... Why?
A phone number is indeed constructed of a set of numerals - the symbols that represent a number - but that doesn't make it a number yet. Compare letters and words; a word is constructed of a set of letters, but not every set of letters is a word. For example: dfslkwpdjkcnj is not a word, not in a language I know of at least... And if it would be a number, how would you add-up two phone numbers? Or how would you divide a phone number by another one? Would that be something like [grandma's phonenumber] / [mom's phonenumber] = [my phonenumber]?
So, to store a phone number in a database, a varchar would be a more suitable column type. For example international phone numbers start with either a + sign, or double zero (00). Both of them can not be stored in a numeral field type. The + isn't a numeral sign, or is used to designate a positive number, and will be cut off. Leading zero's in a number have no function at all, and will be cut off as well...
So bottom line; in your database, use a varchar to store a phone number, and use conversion functions to format a phone number to your liking. There are almost certainly a dozen of algorithms to be found to format a phone number to some kind of a standardized format.
Then back to your excel: your aren't creating an excel file, but a csv file, and you're giving it an excel mime-type. But that would be the same to give someone a cd and say it is a dvd. If you put the cd in a dvd player, it will almost certainly be able to play it, but it is mere luck then wisdom that it does.
Creating an excel file isn't as easy as setting the mime-type, as you can't expect the browser to know how to convert text to an excel file, as it does not know about excel's internals. So if you reaaally want to create an excel file, and set the data types of certain columns, use a library like phpExcel or any other available, if you don't want to create a library yourself that is.
A: have you tried expanding(stretching) phone column in your excel file? sometime if column is small and numbers are big, excel displays number like(1.23+09) this.
If stretching column does not work. you can convert numbers into string and then put them in excel file
sorry i can't add this in comment as i don't have privilege to comment yet.
A: If with your API you are able to format cells, that's what you would need to do. You are storing your phone number as a BigInt instead of as a String. I have always stored phone numbers as Strings.
Excel is interpreting your data correctly--as a number, not as text. If you wish to continue to store your phone number as a BigInt (which I don't recommend), you would need to convert it to a String before writing it out to Excel. Or, if your API permits, write it out to Excel as a number, but then apply cell formatting to bring it to the formatting you expect. | unknown | |
d14311 | val | Or you can query it with LINQ:
string message = String.Join(", ", from DataGridViewRow r in dataGridView1.Rows
where true.Equals(r.Cells["Column1"].Value)
select r.Cells["pk_pspatitem"].Value);
With pattern matching in C# 7.0 (comes with Visual Studio 2017)
string message = String.Join(", ", from DataGridViewRow r in dataGridView1.Rows
where r.Cells["Column1"].Value is true
select r.Cells["pk_pspatitem"].Value);
A: The delimiter will only show to separate multiple items. If there is only one then it will not show.
Try collecting all the values and then using the String.Join with the delimiter.
List<string> values = new List<string>();
foreach (DataGridViewRow row in dataGridView1.Rows) {
bool isSelected = Convert.ToBoolean(row.Cells["Column1"].Value);
if (isSelected) {
values.Add(row.Cells["pk_pspatitem"].Value.ToString());
}
}
string message = String.Join(", ", values);
MessageBox.Show(message);
A: String.Join is used to concatenate an array. You're just adding a string to another string. Use the standard concatenation operator, +.
message += ", " + row.Cells["pk_pspatitem"].Value.ToString();
Consider also that this will cause your message to start with a comma, which can be fixed like this:
MessageBox.Show(message.Substring(2));
Of course, you could convert the rows into an array and then use String.Join, but I don't see any value in that. | unknown | |
d14312 | val | Try passing '../components/Header'
Please let me know if it works. Thanks
A: Your .'./components/Header' path is right..
In your Header component folder there is no any styles.js but you are importing in index.js which is in Header folder.. The above error is regarding path to styles.js in header folders Index.js
Read the error carefully. They have mentioned original Path and target path.
Hope you get it. | unknown | |
d14313 | val | !! is just double !
!true // -> false
!!true // -> true
!! is a common way to cast something to boolean value
!!{} // -> true
!!null // -> false
A: Writing !! is a common way of converting a "truthy" or "falsey" variable into a genuine boolean value.
For example:
var foo = null;
if (!!foo === true) {
// Code if foo was "truthy"
}
After the first ! is applied to foo, the value returned is true. Notting that value again makes it false, meaning the code inside the if block is not entered. | unknown | |
d14314 | val | get method need to be grouped Ex : get/users & get/users/{id} will be
get/users/{id}
I do not agree with this. /get/users will be returning List<User> and get/users/{id} will return User that matches with {id}
remove put method & just use post Ex: post/users/0 add |
post/users/{id} update
Post should be used when you create a new resource. POST is not idempotent. Each time you call a post a new resource will be created.
e.g. Calling POST /Users will create a new User every-time.
PUT on other hands works like upsert. Create if the resource is not present and update/replace if present. Put is idempotent and doesn't change the resource's state even if it's called multiple times.
make a helper class for Jdbc Template and call it in the repository
classes to centralize the code
Helper classes help to separate the concerns and achieve single responsibility.
However, JdbcTemplate is a ready to use abstraction of JDBC. I don't see any point in creating Helper. You can create a DataAccessObject (DAO) or Repository which has-a JdbcTemplate. Like the two Dao shown below
public class UserDao {
@Autowired
private JdbcTemplate jdbcTemplate;
public User findUserById(String id){}
public void addUser(User user){}
}
// -------
public class BooksDao{
@Autowired
private JdbcTemplate jdbcTemplate;
public List<Book> getAllBooksByType(String type){}
public void Book getBookByName(String name){}
}
Now, your Dao objects can be called from Controller or if you need to modify data before/after DB operation, best is to have a Service layer between Controller and Dao.
Don't bother too much about recommendations or rules. Stick to the basic OOPS concepts. Those are really easy to understand and implement.
Always:
*
*Encapsulate data variables and methods working on those variables together
*Make sure your class has a Single Responsibility
*Write smaller and testable methods (if you can't write tests to cover your method, then something is wrong with your method)
*Always keep the concerns separate
*Make sure your objects are loosely coupled. (You are already using spring so just use the spring's auto-wiring) | unknown | |
d14315 | val | There is a PowerShell module called NetSecurity.
You can make a statement in powershell which can tell if the rule already exist or not.
Get-NetFirewallRule you can use this command to discover which firewall rules are already defined.
https://learn.microsoft.com/en-us/powershell/module/netsecurity/?view=win10-ps | unknown | |
d14316 | val | You can make use of Chrome's Developer Tools; no extension is required.
I made a +1 button example here: http://jsfiddle.net/rPnAe/.
If you go to that fiddle and then open Developer Tools (F12), then go to Scripts and expand Event Listener Breakpoints and lastly expand 'Mouse' and tick the 'click' checkbox, then whenever you click somewhere (which includes an event listener), the debugger will now break at the line of code which contains the listener function. | unknown | |
d14317 | val | I found the answer in the documentation: http://msdn.microsoft.com/en-us/library/gg680264%28v=pandp.11%29.aspx
Basically, there is a bug in the photo chooser which returns a temporary path. Microsofts recommendation is to copy the picture to isolated storage if you want to use it between app instances.
A: Application.GetResourceStream will return null for that path because the GetResourceStream method is looking for a resource within the application itself, not from the device.
To re-load the same image on resume from tombstoning simply persist the OriginalFileName property, and then use that to create a BitmapImage as follows:
string path = /* Load the saved OriginalFileName */;
var bitmap = new BitmapImage(new Uri(path, UriKind.Absolute));
myImageControl.Source = bitmap;
NOTE: The OriginalFileName property is already a string, so you don't need to call .ToString() on it. | unknown | |
d14318 | val | function getDays(earlierDate, laterDate) {
var dayNames = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
var elapsedDays = (laterDate - earlierDate) / 1000 / 60 / 60 / 24;
if (elapsedDays < 7) {
var dayArray = [];
for (i = 0; i <= elapsedDays; i++) {
dayArray.push(dayNames[(earlierDate.getDay()+i) % 7]);
}
return dayArray;
}
return dayNames;
}
And testing in the js console:
> getDays(new Date("03-01-2012"), new Date("03-01-2012"));
["Thursday"]
> getDays(new Date("03-01-2012"), new Date("03-05-2012"));
["Thursday", "Friday", "Saturday", "Sunday", "Monday"]
> getDays(new Date("03-01-2012"), new Date("03-05-2013"));
["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
A: var sevenDaysInMS = 604800000;
if (new Date(dTo - dFrom).getTime() >= sevenDaysInMS) {
$('.day_hid').attr(attrUnaviableDay, "true");
} else {
var dt = dFrom;
do {
var day = dt.getDay();
ActivateDaySelector(day);
dt.setDate(dt.getDate() + 1);
} while (dt <= dTo);
}
I think it is ok. What do you think ? | unknown | |
d14319 | val | try
if (typeof disabledFlag === 'undefined')
disabledFlag = false;
A: There are easier ways to do it than using ternaries or if else statements.
As far as your specific function goes, you could do something like this:
var toggleBlock = function() {
var disabledFlag = disabledFlag||false;
if(!disabledFlag){
//etc.
undefined is falsy, so it works with the logical || operator. That || operator makes the new var disabledFlag be set to disabledFlag (if it exists), and if not, it will set the var to false
This same concept is used in many different contexts. For example:
Situation 1 -
var obj = {hello: 'world'};
function fn(object) {
var object = object || {foo: 'bar'};
return object;
}
fn(obj) // ==> {hello: 'world'}
Situation 2 -
function fn(object) {
var object = object || {foo: 'bar'};
return object;
}
fn(objectThatDoesntExist); // ==> {foo: 'bar'}
In JavaScript libraries and module-pattern projects, this concept is used quite frequently in many different ways.
A: You don't need typeof
if (window.disabledFlag === undefined) window.disabledFlag = false;
A: you can check if a variable is undefined with the typeof keyword, like this:
if(typeof neverDeclared == "undefined") //no errors
if(neverDeclared == null) //throws ReferenceError: neverDeclared is not defined
take a look here for more info on typeof | unknown | |
d14320 | val | *If I want to do this with threads, how many should I create? 20 One for each request and let them all loose to do the job? Or should i create like 4 of them making at most 5 requests each?B: What if two threads are finished at the same time and wants to add info to the directory, can it lock the whole site(I'm using ASP.NET), or will it try to add one from thread A and then one result from Thread B? I have a check already today that checks if the key exists before adding it.
C:What would be the fastest way to this?
This is my code, depicting the loop which just shows that 20 requests are being made?
public void FetchAndParseAllPages()
{
int _maxSearchDepth = 200;
int _searchIncrement = 10;
PageFetcher fetcher = new PageFetcher();
for (int i = 0; i < _maxSearchDepth; i += _searchIncrement)
{
string keywordNsearch = _keyword + i;
ParseHtmldocuments(fetcher.GetWebpage(keywordNsearch));
if (GetPostion() != 201)
{ //ADD DATA TO DATABASE
InsertRankingData(DocParser.GetSearchResults(), _theSearchedKeyword);
return;
}
}
}
A: *
*.NET allows only 2 requests open at the same time. If you want more than that, you need to configure it in web.config. Look here: http://msdn.microsoft.com/en-us/library/aa480507.aspx
*You can the Parallel.For method which is very straightforward and handles the "how much threads" for you. Of course you can tweak it to set how much threads (or tasks) you want with ParallelOptions. Look here: http://msdn.microsoft.com/en-us/library/dd781401.aspx
*For making a thread-safe dictionary you can use the ConcurrentDictionary. Look here: http://msdn.microsoft.com/en-us/library/dd287191.aspx | unknown | |
d14321 | val | Try changing first part to:
@Override
public void onStateChanged(IntegratorState state) {
switch (state.getState()) {
case AWAITING_MENU_OPTION:
IntegratorHelper.showOptionsMenu(state, SitefMenuActivity.this);
break;
default:
Toast.makeText(getApplicationContext(), state.getState().name(),
Toast.LENGTH_LONG).show();
}
}
and second part:
public static void showOptionsMenu(IntegratorState state, Activity activity) {
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setTitle(state.getGatewayMessageExtra());
String[] strings;
strings = state.getGatewayMessage().split(";");
final List<String> options = Arrays.asList(strings);
builder.setAdapter(new MenuSaleAdapter(activity,
android.R.layout.simple_list_item_1, options),
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (which == options.size()-1) {
// Do a thing
} else {
// Do other thing
}
}
});
builder.create().show();
} | unknown | |
d14322 | val | I finally found the interface that seems to allow this: nsICookieManager removeAll()
Relevant C# interfaces / code for those using GeckoFX:
[Guid("AAAB6710-0F2C-11d5-A53B-0010A401EB10"),
ComImport,
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
interface nsICookieManager
{
void removeAll();
void remove(string aDomain, string aName, string aPath, bool aBlocked);
}
and Xpcom.GetService<nsICookieManager>("@mozilla.org/cookiemanager;1").removeAll(); in appropriate location. | unknown | |
d14323 | val | Did able to manage by setting csv for all Threads and Recycle on EOF = True and Stop at EOF to False.
When used No of threads to 3, It reaches 18 instead was expecting 9 only | unknown | |
d14324 | val | However, it will be imperative that I also send images along with the alerts
I might be misunderstanding your question, but the push notification framework doesn't support images. You can only send text, badges (the red numbers next to an app icon), or sounds (which must already be installed in the app bundle).
Perhaps you can use a third-party option to do it, but push.me wasn't really designed for automated comms, but for friend to friend IMs. You may have to create your own app to achieve this...I'm not sure of any third party app you could use. | unknown | |
d14325 | val | By a process of elimination, I would suggest it was: ACCESS_NETWORK_STATE as none of the others are specifically to do with the phone.
A: It turned out to be an issue with a bug where you need to at least specify a minimum SDK of 4:
Android permissions: Phone Calls: read phone state and identity
A: none of these are related to read phone call info. As it should be like .READ_PHONE_STATE(read phone call). I think it must be because of ACCESS_NETWORK_STATE. | unknown | |
d14326 | val | The difference is that in EF 4 entities were generated with piles of code that took care of change notification and lazy loading. Since then, the DbContext API with POCOs has become the standard.
If you want the same behavior as with the old 'enriched' entities you must make sure that lazy loading can occur by a number of conditions:
*
*The context must allow lazy loading. It does this by default, but you can turn it off.
*The navigation properties you want to lazy load must have the virtual modifier, because
*EF must create dynamic proxies. These proxies somewhat resemble the old generated entities in that they are able to execute lazy loading, because they override virtual members of the original classes.
The last (and maybe second) point is probably the only thing for you to pay attention to. If you create a new object by new, it's just a POCO object that can't do lazy loading. However, if you'd create a proxy instead, lazy loading would occur. Fortunately, there is an easy way to create a proxy:
ArticleTable newEntity= dbContext.ArticleTables.Create();
DbSet<T>.Create() creates dynamic proxies -
if the underlying context is configured to create proxies and the entity type meets the requirements for creating a proxy. | unknown | |
d14327 | val | A websocket is what you are looking for; however it is subject to some browser limitations and libraries may fall back to polling with Ajax if the browser doesn't support it.
Here is some reading for you so you can ask a more specific question in the future:
*
*http://en.wikipedia.org/wiki/WebSocket (general info)
*http://socket.io/ (NodeJS and browser client library) | unknown | |
d14328 | val | In your public void createDataBase() , you are using a Thread to copy your database in. Are you sure you have finished the copy before you try to access it? This is my working copy of the code which is very similar to yours you may want to see. Another thing is
byte[] mBuffer = new byte[1024];
try 4096 , I had problems with 1024 before.
A: Check that the table really exists in the database. Most likely, the actual database is empty, since you don't do anything in the onCreate function (where one should initialize the database). Instead, you probably one of the following:
Instead of passing SQLiteDatabase.CREATE_IF_NECESSARY to openDatabase, call your (currently unused) function createDataBase.
Alternatively, create the database in onCreate by copying over the data of the default database. For that, you'll need another function to convert your existing in-asset database to SQL commands. | unknown | |
d14329 | val | You need to create two subplots - one for each pie chart. The following code will do it (explanation in comments):
import matplotlib.pyplot as plt
# the same figure for both subplots
fig = plt.figure(figsize=(4,3),dpi=144)
# axes object for the first pie chart
# fig.add_subplot(121) will create a grid of subplots consisting
# of one row (the first 1 in (121)), two columns (the 2 in (121))
# and place the axes object as the first subplot
# in the grid (the second 1 in (121))
ax1 = fig.add_subplot(121)
# plot the first pie chart in ax1
cts = df1.Name.value_counts().to_frame()
ax1.pie(cts.Name)
# axes object for the second pie chart
# fig.add_subplot(122) will place ax2 as the second
# axes object in the grid of the same shape as specified for ax1
ax2 = fig.add_subplot(122)
# plot the sencond pie chart in ax2
cts = df2.Name.value_counts().to_frame()
ax2.pie(cts.Name)
plt.show()
This gives:
A: This would do a job. You can defined subplots using fig.add_subplot(row, column, position).
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(4,3),dpi=144)
ax = fig.add_subplot(121)
cts = df1.Name.value_counts().to_frame()
ax.pie(cts.Name)
ax = fig.add_subplot(122)
cts = df2.Name.value_counts().to_frame()
ax.pie(cts.Name)
A: You can use subplots:
import matplotlib.pyplot as plt
colors = {'water': 'b', 'fire': 'r', 'stones': 'gray'} # same color for each name in both pie
fig, axes = plt.subplots(1, 2, figsize=(4,3),dpi=144)
plt.suptitle("Big title")
for ax, df, title in zip(axes, (df1, df2), ('Title 1', 'Title 2')):
count = df.Name.value_counts().to_frame().sort_index()
ax.pie(count.Name, labels=count.index, colors=[colors[c] for c in count.index])
ax.set_title(title) | unknown | |
d14330 | val | Unfortunately the responses are not completely correct. In a 3G/4G network every device gets an IP address, but THAT's NOT the IP address that you see when going to sites like www.whatismyip.com. That's the address that the Telco presents to the external world, not the device IP address.
Telcos such AT&t, Verizon, Telefonica and similar assign a "private" IP address that is only valid in their network. This is similar to the internal IP address that you have in your phone when connect to the house wireless, but if you check in www.whatismyip.com you get the external IP address of your wireless router (You can check that those are different addresses). What Telcos do is known as NAT or PAT. The reason is that the current version of IP has a very limited number of available IP addresses, and all those million of devices cannot get public IP addresses (like the one you see in whatismyip.com). Actually several devices share that external IP address.
Unlike Android devices where you can get the IP that the telco assigned to the device, iOS does not present that information to the user (unless you jailbreak the device or have an App).
Although the address that whatismyip presents is not your real IP, it is the one that the external world recognizes so it suffices for most purposes.
A: What you see on whatismyip.com is the IP address you get from your mobile provider, on which it depends what kind op IP you get. Very often 3G networks are NATted, meaning that you get an IP address from the range 10.0.0.0/8 which cannot be reached from outside.
A: Using www.whatismyip.com should definitely give you the correct address?
What address did you get when it came back?
How did you verify if this was your iPhone's address? I assume you don't have a firewall installed on your iPhone? Hmm, other thing is your provider is doing some kind of filtering, NAT-ing, or other tomfoolery. If you don't mind me asking, what exactly are you trying to achieve here? Are you trying to run some kind of server-style app on your iPhone? Or do you just want to get a connection between the iPhone and a server - might be easier to initiate the connection from the iPhone side.
You should check if it's at your provider's IP block range - an online whois check should tell you that (www.whois.net).
How did you test whether this was your iPhone's address?
Other option is just to have your iPhone hit a server that you control (using 3G), and check the server logs.
Or just make things easier, and use an app to tell you - e.g. iStat:
http://bjango.com/iphone/istat/
which will give you your cell (3G) IP address as well.
Cheers,
Victor
A: There are two types of IP addresses:
Private IP address (your device IP that you get it from your home Wi-Fi router or from your Teleco provider router to speak to those two routers).
Public IP address (your home Wi-Fi router and/or from your Teleco provider router which they will use it to allow you to speak to another person on the Internet).
**NOTE: Without Public IP address, you cannot speak to people who are on the Internet.
Now both (your home Wi-Fi router or your Teleco Provider router)they have something called DHCP, or Dynamic Host Configuration Protocol. This protocol is used to allocate private IP address to anyone connected to local network (either home Wi-Fi or Teleco provider).
That means both (home Wi-Fi router and Teleco provider router) have one single IP address called Public IP address to allow you to speak to outside world, but first they need to give private IP address to able you to speak with them (your home Wi-Fi router and your Teleco provider router).
If your iOS connected to your home Wi-Fi, then you will have a Private IP address:
1- Go to settings.
2- Click on Wi-Fi.
3- List of Wi-Fi networks will be appeared.
4- Click on your Wi-Fi network name (known as SSID).
5- Click on the blue circle of the exclamation mark on the right side of your Wi-Fi name.
You will see your Private IP Address there very clearly.
Now if your iOS device is not connected to any Wi-Fi network, but it connected to your Teleco provider, then you cannot see your private IP address.
I am sure there is a way to see your Private IP address that you got it from your Teleco Provider DHCP. You have to search from internet or ruin your device by jailbreak it.
For the Public IP Address (no matter if you are connected to your home Wi-Fi or your Teleco Provider), go to your internet browser (e.x. google chrome) and type: "What is my ip address". The result will be between your hand in fractions of seconds!
Now Back to your question:
If you connected two iPhones to your PC and both have hotspot enabled, that means your PC USB ports will handle two IP Private addresses because your iPhones will act as your home Wi-Fi router.
if you have windows OS in your laptop, then go to windows CMD terminal and type:
ipconfig
the CMD prompt terminal will give you number of IP address, there are your two Private IP addresses from your iPhones.
Now if unidentified network message still there, open RUN in your windows OS and type [ ncpa.cpl ], it will take you to network connection setting section, right click on one of your iPhones networks and disable it, keeping the other enabled.
I hope it is crystal clear now.
A: When the phone is the hotspot for the Telecom cellular provider it actually being used as a Router therefor if you connect laptop to that hotspot you can open network setting on the laptop to view its tcp/ip settings and see the ip of the laptop and the ip of the Router which is the IP of your Phone.
The Ip is a private one, you can ping to it or do what ever you want.
Example of connecting Iphone to Mac Xcode wirelessly:
*
*share personal hotSpot from your phone.
*connect your laptop to your phone private network using wifi, search for the ssid you set in your phone and set a correct password.
*in Mac go to System prefences->Network->wifi connected->Advanced->Tcp/Ip
copy Router Ip - this is your Iphone private Ip.
In order to connect Xcode to Iphone wirelessly you first need to connect the phone with usb, open window->device and simulators, select your phone and set checkbox "connect via network"
Now if the phone is disconnected from the Mac and the private network is shared as explained, you know the phone Ip, then you can select the phone in Xcode (it remember phones that were connected), open window->device and simulators, select your phone , click on it to get menu of options, select "connect with ip", provide the ip you saw as "Router" previously.
Thats all, hope it'll help somebody. | unknown | |
d14331 | val | My problem seems like it's the same, despite the integration WSL is already enabled since installation.
In the windows shell:
> wsl docker --version
The command 'docker' could not be found in this WSL 2 distro.
We recommend to activate the WSL integration in Docker Desktop settings.
See https://docs.docker.com/docker-for-windows/wsl/ for details.
An option to resolve this problem is reinstalling Docker Desktop (https://learn.microsoft.com/en-us/virtualization/windowscontainers/manage-docker/configure-docker-daemon#how-to-uninstall-docker), but don't need to do this.
The steps below work for me (I found at https://github.com/docker/for-win/issues/7039).
Open windows shell (maybe as admin), and run:
> wsl -t docker-desktop
> wsl --shutdown
> wsl --unregister docker-desktop
Then go to windows services, stop the Docker Desktop Service, OR to do this running the command in windows shell as admin:
> Stop-Service -Name "com.docker.service"
And finally, restart the Docker Desktop App.
Test in the windows shell:
> wsl docker --version
Docker version 20.10.2, build 2291f61
A: For those still having issues with this, some of my symlinks magically vanished and no amount of reinstalling helped.
Make sure you have the following symlinks in your WSL2 installation:
$ ls -l /usr/bin/ | grep docker
lrwxrwxrwx 1 root root 56 Jul 14 13:01 com.docker.cli -> /mnt/wsl/docker-desktop/cli-tools/usr/bin/com.docker.cli
lrwxrwxrwx 1 root root 48 Jul 14 13:01 docker -> /mnt/wsl/docker-desktop/cli-tools/usr/bin/docker
lrwxrwxrwx 1 root root 56 Jul 14 13:01 docker-compose -> /mnt/wsl/docker-desktop/cli-tools/usr/bin/docker-compose
lrwxrwxrwx 1 root root 59 Jul 14 13:01 docker-compose-v1 -> /mnt/wsl/docker-desktop/cli-tools/usr/bin/docker-compose-v1
lrwxrwxrwx 1 root root 71 Jul 14 13:01 docker-credential-desktop.exe -> /mnt/wsl/docker-desktop/cli-tools/usr/bin/docker-credential-desktop.exe
lrwxrwxrwx 1 root root 50 Jul 14 13:01 hub-tool -> /mnt/wsl/docker-desktop/cli-tools/usr/bin/hub-tool
lrwxrwxrwx 1 root root 48 Jun 29 09:27 notary -> /mnt/wsl/docker-desktop/cli-tools/usr/bin/notary
A: WSL Integration under Resources was not showing for me.
I had to uncheck "Use the WSL2 based engine" under General settings, Apply, then Check it again, Apply, then WSL Integration showed up under resources and I could click the Ubuntu slider.
A: For me running the following command in wsl terminal worked
sudo apt-get update
apt-cache policy docker-ce
sudo apt-get install -y docker-ce
sudo apt-get install docker-compose
sudo apt-get upgrade
source- https://www.srcmake.com/home/fabric
A: I had this issue, for me running
$ ls -l /usr/bin/ | grep docker
showed all the correct symlinks as per this answer however I saw the following:
which docker
/mnt/c/Program Files/Docker/Docker/resources/bin/docker
The fix was to simply to set the PATH variable to have /user/bin as the first entry
PATH="/usr/bin:$PATH"
From the multitude of answers, it seems like there are many things that can cause this error, so your mileage may vary.
Another good thing to check is that Docker Desktop is actually running. If it isn't, which docker will result in the /mnt/c/... directory as above.
A: As Taylor wrote in his comment you need to connect from WSL to docker desktop.
In the image you attached there is a check box expose daemon on ...
Check this box.
Now you need docker cli, you can install Linux vm then install docker in that Linux vm you just installed.
Then run which docker and copy this file to your windows computer.
Copy the docker executable into /usr/local/bin on your WSL.
Now run the following in WSL
echo "export DOCKER_HOST=tcp://localhost:2375" >> ~/.bashrc
. ~/.bashrc
This worked for me on WSL 1.
Here is guide I found on the all process
A: Fabrício Pereiras answer was working for me, but I had to do it pretty often, which was still annoying.
Turns out the order of starting the systems is important too.
Start Docker first, then WSL2 after.
I don't start Docker Desktop with Windows and usually had opened a terminal in WSL already. Then Docker could not be found. Fabricios answer was working for me because I shutdown WSL2, then started it again when Docker was already running.
A: In my case, the integration was correctly set in the docker-app, WSL2 was correctly the default wsl, and I wasn't able to solve unregistering the wsl docker instance and restarting the docker service like mentioned in other answers.
After some time, I noticed that the command docker-compose successfully worked. The issue was limited to the docker command.
I looked for all docker commands in the directory usr/bin, that is the path where docker-compose is located (which docker-compose), so runnining ls -l /usr/bin | grep docker, I found
drwxrwxrwx 1 root root 48 Nov 29 10:59 docker
lrwxrwxrwx 1 root root 56 Nov 29 10:59 docker-compose -> /mnt/wsl/docker-desktop/cli-tools/usr/bin/docker-compose*
lrwxrwxrwx 1 root root 59 Nov 29 10:59 docker-compose-v1 -> /mnt/wsl/docker-desktop/cli-tools/usr/bin/docker-compose-v1*
lrwxrwxrwx 1 root root 71 Nov 29 10:59 docker-credential-desktop.exe -> /mnt/wsl/docker-desktop/cli-tools/usr/bin/docker-credential-desktop.exe*
lrwxrwxrwx 1 root root 50 Nov 29 10:59 hub-tool -> /mnt/wsl/docker-desktop/cli-tools/usr/bin/hub-tool*
For some weird reason, docker wasn't a symbolic link but a directory.
I solved removing the directory and re-creating manually the symbolic link:
rm -rf /usr/bin/docker
sudo ln -s /mnt/wsl/docker-desktop/cli-tools/usr/bin/docker /usr/bin/docker
A: I followed theses steps: https://learn.microsoft.com/en-us/windows/wsl/install-win10
Also, for docker into ubuntu, I enabled it in docker resources as a final step.
Settings > Resources > WSL Integration.
from: https://docs.docker.com/docker-for-windows/wsl/
A: Make sure that you have a distro that is compatible with wsl2:
https://ubuntu.com/wsl
A: I was experiencing the same issue with Ubuntu-20.04 (WSL2) and Docker Desktop (v4.11.1). For me, WSL integration and other flags are all set but still I was getting:
The command 'docker' could not be found in this WSL 2 distro.
I followed @r590 's method. I turned-off and then turned-on WSL Integration under:
Resources > WSL Integration
and then it worked for me.
A: You need to go to the docker desktop settings, and enable integration with your distro in "Resources -> WSL Integration".
A: I stuck with this error after remove Ubuntu 18.04 and install the 20.04.
Even with the WSL 2 enabled, I still face this error.
This is what works for me, go the Settings --> resource and toggle the "Ubuntu" then the error disappear :)
A: For me, nothing worked excepted : right click on running Docker icon (next to clock) and chose "Switch to Linux containers"
And here we go ! Now i can have the menu Settings > Resources > WSL integration.
A: Assuming you already have wsl 2 in your system, run powershell as admin:
run wsl --list --verbose which will give you a list of your wsl running processes:
> wsl --list --verbose
NAME STATE VERSION
Ubuntu-20.04 Running 1
Then to switch it with wsl --set-version <your proc> 2:
> wsl --set-version Ubuntu-20.04 2
Conversion in progress, this may take a few minutes...
For information on key differences with WSL 2 please visit https://aka.ms/wsl2
Conversion complete.
A: Sometimes the simplest solution is the most effective solution, if you are installing docker desktop for the first time make sure you restart windows for the effects to take change. This is not guaranteed to work but it is always worth a shot.
A: I was having the same issue, however, for me, I installed docker using a different Windows account (admin) because my default account (under a domain) is a standard user and has no admin access.
After installing docker, I started docker and got an error that I'm not part of the docker-users group so I started docker using the admin account that I have. Docker started but it's not able to see the WSL integration. Similar to the screenshot below.
What fixed it for me is to add the domain account to the docker-users and restart my machine. After that WSL is visible in the configuration.
# For local account
net localgroup docker-users "your-user-id" /ADD
# For domain account
net localgroup docker-users "DOMAIN\your-user-id" /ADD
A: I reboot my machine and docker stopped work. I reinstall docker-decktop and did all the suggestion and nothing work.
I found that I have a directory here /usr/bin/docker. I deleted it and then reinstall docker which fixed the issue.
A: In my case my distribution was running in WSL 1 mode
To check the WSL mode, run:
wsl.exe -l -v
To upgrade your existing Linux distro to v2, run:
wsl.exe --set-version (distro name) 2
To set v2 as the default version for future installations, run:
wsl.exe --set-default-version 2
A: You need to run the WSL console as Admin.
If not, the docker command may be not recognized.
A: Switch to linux containers in docker desktop then it will work. | unknown | |
d14332 | val | Problem solved by restarting Jupyter Notebooks. | unknown | |
d14333 | val | Obviously your "add to cart" button is only displaying when you hover the lower part of the box. That indicates only the bottom area is linked. Your "a" element might need to be "display:block" so it covers the entire block inside the brown rule. Hard to tell without seeing the actual site. Can you post URL?
AFTER EXAMINING YOUR CODE, HERE IS WHAT IS HAPPENING
The add-to-cart link is there, even when not hovered.
You do not see it b/c the CSS includes:
color: transparent;
background-color: transparent;
I would remove those parameters so the button is visible in gray and white. Looks nice and tells the user where to click to purchase the item.
You still have the hover effect that changes the button color to brown, but now the user clearly sees where to put their cursor.
If you want the button 'hidden' until the box is hovered, and then turn brown when hovering the box, add this to your CSS:
li:hover a.add_to_cart_button {
background-color: #f37020;
text-decoration: none;
color: #fff;
background-image: none;
}
A: Here is an example
$(document).ready(function () {
$(document).on('mouseenter', '.divbutton', function () {
$(this).find(":button").show();
}).on('mouseleave', '.divbutton', function () {
$(this).find(":button").hide();
});
});
.divbutton {
height: 140px;
background: #0000ff;
width:180px;
}
button{
padding: 4px;
text-align: center;
margin-top: 109px;
margin-left: 7px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="divbutton" ">
<button type="button" style="display: none;">ADD TO CART</button>
</div>
Or If you want to use only CSS
button {
display: none; /* Hide button */
}
.divbutton:hover button {
display: block; /* On :hover of div show button */
} | unknown | |
d14334 | val | This has been fixed on the following PR
https://github.com/soberman/ARSLineProgress/pull/36
The fix is to add CATransaction.commit() to the hide function. This was not my work.
func ars_hideLoader(_ loader: ARSLoader?, withCompletionBlock block: (() -> Void)?) {
guard let loader = loader else { return }
ars_dispatchOnMainQueue {
let currentLayer = loader.emptyView.layer.presentation()
let alpha = Double(currentLayer?.opacity ?? 0)
let fixedTime = alpha * ars_config.backgroundViewDismissAnimationDuration
CATransaction.begin()
CATransaction.setCompletionBlock(block)
let alphaAnimation = CABasicAnimation(keyPath: "opacity")
alphaAnimation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeOut)
alphaAnimation.fromValue = alpha
alphaAnimation.toValue = 0
alphaAnimation.duration = fixedTime
alphaAnimation.isRemovedOnCompletion = true
loader.emptyView.layer.removeAnimation(forKey: "alpha")
loader.emptyView.alpha = 0
loader.emptyView.layer.add(alphaAnimation, forKey: "alpha")
let scaleAnimation = CABasicAnimation(keyPath: "transform")
scaleAnimation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeOut)
scaleAnimation.fromValue = CGAffineTransform(scaleX: 1, y: 1)
scaleAnimation.toValue = CGAffineTransform(scaleX: ars_config.backgroundViewDismissTransformScale,
y: ars_config.backgroundViewDismissTransformScale)
scaleAnimation.duration = fixedTime
scaleAnimation.isRemovedOnCompletion = true
loader.backgroundView.layer.removeAnimation(forKey: "transform")
loader.backgroundView.layer.add(scaleAnimation, forKey: "transform")
CATransaction.commit()
}
ars_dispatchAfter(ars_config.backgroundViewDismissAnimationDuration) {
ars_cleanupLoader(loader)
}
} | unknown | |
d14335 | val | A) Change your query
query {
getProjet(id: "123") {
id
members(limit: 50) {
items {
firstname
}
}
}
B) Attach a Resolver
In the AWS AppSync console, at the right end side of the Schema section. Filter by UserConnection or similar find UserConnection.items and click Attach.
1) DataSource: UserTable0
2) Request mapping template: ListItems
{
"version" : "2017-02-28",
"operation" : "Scan",
"limit": $util.defaultIfNull(${ctx.args.limit}, 50),
"nextToken": $util.toJson($util.defaultIfNullOrBlank($ctx.args.nextToken, null))
}
Use the limit coming as an argument ctx.args.limit or if its null use 50.
3) Response mapping template
$util.toJson($ctx.result.items)
By doing this you can change how the underlying table is being scanned/fetched.
C) Paginate
Another solution would be to paginate at the application level and leave the 10 items limit.
Note: I may be missing other solutions.
Update: to use this solution together with Amplify Console.
Now, you can update your resolvers locally and use the Amplify CLI to push the updates into your account. Here’s how it works.
After creating your AWS AppSync API, you will now have a new empty folder called resolvers created in your Amplify project in the API folder. To create a custom resolver, create a file (i.e.
Query.getTodo.req.vtl) in the resolvers directory of your API project. The next time you run amplify push or amplify api gql-compile, your resolver template will be used instead of the auto-generated template. You may similarly create a Query.getTodo.res.vtl file to change the behavior of the resolver’s response mapping template.
<amplify-app>
|_ amplify
|_ .config
|_ #current-cloud-backend
|_ backend
|_ api
|_ resolvers
Query.getProject.req.vtl
Query.getProject.res.vtl
team-provider-info.json
More details, 11 Feb 2019 | unknown | |
d14336 | val | Combobox columns are numbered from (0) so you need to reference column 1 ;
Private Sub ProjectID_Change()
Me.Client_Name.Value = Me.ProjectID.Column(1)
End Sub
And as suggested move it to the AfterUpdate event. | unknown | |
d14337 | val | Answering only your first question:
val indexToSelect: Int = ??? //points to sortable type (has Ordering or is Ordered)
sorted = rdd.sortBy(pair => pair._2(indexToSelect))
What this does, it just selects the second value in the pair (pair._2) and from that row it selects the appropriate value ((indexToSelect) or more verbosely: .apply(indexToSelect)). | unknown | |
d14338 | val | var params = {Key: newFilename, ContentType: 'image/png', Body: fileStream};
http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#upload-property
A: Just put "contentType: multerS3.AUTO_CONTENT_TYPE " . It will work .
Ex:
var upload = multer({
storage: multerS3({
s3: s3,
bucket: 'some-bucket',
contentType: multerS3.AUTO_CONTENT_TYPE,
key: function (req, file, cb) {
cb(null, Date.now().toString())
}
})
})
Visit this link for more details https://github.com/badunk/multer-s3
A: This Helped me
storage: multerS3({
s3: s3,
bucket: "bucketname",
acl: "public-read",
contentType: multerS3.AUTO_CONTENT_TYPE,
key: function(req, file, cb) {
console.log("req.file", file);
cb(null, `${Date.now()}-${file.originalname}`);
}
}) | unknown | |
d14339 | val | It would be a lot easier if you used a concrete type. You'll probably want to use the encoding/csv package, here is a relevant example; https://golang.org/pkg/encoding/csv/#example_Writer
As you can see, the Write method is expecting a []string so in order to generate this, you'll have to either 1) provide a helper method or 2) reflect my_struct. Personally, I prefer the first method but it depends on your needs. If you want to go route two you can get all the fields on the struct an use them as the column headers, then iterate the fields getting the value for each, use append in that loop to add them to a []string and then pass it to Write out side of the loop.
For the first option, I would define a ToSlice or something on each type and then I would make an interface call it CsvAble that requires the ToSlice method. Change the type in your method my_struct CsvAble instead of using the empty interface and then you can just call ToSlice on my_struct and pass the return value into Write. You could have that return the column headers as well (meaning you would get back a [][]string and need to iterate the outer dimension passing each []string into Write) or you could require another method to satisfy the interface like GetHeaders that returns a []string which is the column headers. If that were the case your code would look something like;
w := csv.NewWriter(os.Stdout)
headers := my_struct.GetHeaders()
values := my_struct.ToSlice()
if err := w.Write(headers); err != nil {
//write failed do something
}
if err := w.Write(values); err != nil {
//write failed do something
}
If that doesn't make sense let me know and I can follow up with a code sample for either of the two approaches. | unknown | |
d14340 | val | You can check the return value of strtotime() to see if a date can be parsed:
if(strtotime($date) !== false) {
// valid date/time
}
This is also how to normalize all the dates, by storing them as the return value of strtotime().
A: Perhaps you could use strtotime()? | unknown | |
d14341 | val | Here's a way to empty all items arrays.
The idea is to use a predefined reducer method that can you can use recursively.
const reducer = (reduced, element) => {
// empty items array
if (element.items) {
element.items.length = 0;
}
// if element has children, recursively empty items array from it
if (element.children) {
element.children = element.children.reduce(reducer, []);
}
return reduced.concat(element); // or: [...reduced, element]
};
document.querySelector("pre").textContent =
JSON.stringify(getObj().reduce(reducer, []), null, " ");
// to keep relevant code on top of the snippet
function getObj() {
return [
{
"label": "parent",
"children": [
{
"label": "child1",
"children": [
{
"label": "child2",
"items": [
"item1",
"item2"
]
},
{
"label": "child3",
"items": [
"item1",
"item2",
"item3"
]
}
]
},
{
"label": "child4",
"items": []
},
{
"label": "child5",
"items": ["item1","item2"]
}
]
}
];
}
<pre></pre> | unknown | |
d14342 | val | I am assuming that you linked to the dbml file using the default properties. This means that, each time you start a debug session, the file will be copied into your output directory and changes made to it will only be seen for that session (i.e., "Copy -> Always").
If you want the changes to persist then right click the file -> properties -> Copy Never. By default the IDE assumes that you don't want to modify the original database, only a copy for debugging purposes. | unknown | |
d14343 | val | Programs started with COM are started by COM with the slash /a parameter. This means Automation is starting the program so it should load clean.
/a
Starts Word and prevents add-ins and global templates (including the
Normal template) from being loaded automatically. The /a switch also
locks the setting files.
https://support.microsoft.com/en-us/office/command-line-switches-for-microsoft-office-products-079164cd-4ef5-4178-b235-441737deb3a6 | unknown | |
d14344 | val | Looks like no library has built-in support to show data grouped by day, week, month and year, etc. So we are doing it ourselves. | unknown | |
d14345 | val | As per the HTML provided to click on the button with text as Content you can use the following line of code :
driver.find_element_by_xpath("//button[@class='search-vertical-filter__filter-item-button button-tertiary-medium-muted' and normalize-space()='Content']").click()
A: Try to use the following code:
driver.find_element_by_css_selector(".search-vertical-filter__filter-item-button.button-tertiary-medium-muted").click()
Hope it helps you! | unknown | |
d14346 | val | For your use case I would suggest you to use match_phrase query inside a bool query's should clause.
Something like this should work:
GET stackoverflow/_search
{
"query": {
"bool": {
"should": [
{
"match_phrase": {
"text": "Chief Information Security Officer"
}
},
{
"match_phrase": {
"text": "Chief Digital Officer"
}
}
]
}
}
}
A: This query would do it.
{
"query": {
"nested": {
"path": "positions",
"query": {
"bool": {
"must": [
{
"query_string": {
"default_field": "positions.companyname",
"query": "microsoft OR gartner OR IBM"
}
},
{
"bool": {
"should": [
{
"match_phrase": {
"positions.title": "chief information security officer"
}
},
{
"match_phrase": {
"positions.title": "chief digital officer"
}
}
]
}
}
]
}
}
}
}
}
match_phrase makes sure that the exact phrase is being searched. To match multiple phrases on the same field, use bool operator with should condition. | unknown | |
d14347 | val | You can find how to use FFT/DFT in this document :
Discretized continuous Fourier transform with numpy
Also, regarding your V matrix, there are many ways to improve the execution speed. One is to make sure you use Python 3, or xrange() instead of range() if you a are still in Python 2.. I usually put these lines in my Python code, to allow it to run evenly wether I use Python 3. or 2.*
# Don't want to generate huge lists in memory... use standard range for Python 3.*
range = xrange if isinstance(range(2),
list) else range
Then, instead of re-computing j/100 and i/100, you can precompute these values and put them in an array; knowing that a division is much more costly than a multiplication ! Something like :
ratios = np.arange(100) / 100
V = np.zeros(10000).reshape((100,100))
j = 0
while j < 100:
i = 0
while i < 100:
V[i,j] = v(values[j], values[i])
i += 1
j += 1
Well, anyway, this is rather cosmetic and will not save your life; and you still need to call the function v()...
Then, you can use weave :
http://docs.scipy.org/doc/scipy-0.14.0/reference/tutorial/weave.html
Or write all your pure computation/loop code in C, compile it and generate a module which you can call from Python.
A: You should look into numpy's broadcasting tricks and vectorization (several references, one of the first good links that pops up is from Matlab but it is just as applicable to numpy - can anyone recommend me a good numpy link in the comments that I might point other users to in the future?).
What I saw in your code (once you remove all the unnecessary bits like plots and unused functions), is that you are essentially doing this:
from __future__ import division
from scipy.integrate import quad
import numpy as np
import matplotlib.pyplot as plt
def func1(x,n):
return 1*np.sin(n*np.pi*x)**2
def v(x,y):
n = 1;
sum = 0;
nmax = 20;
while n < nmax:
[C_n, err] = quad(func1, 0, 1, args=(n), );
sum = sum + 2*(C_n/np.sinh(np.pi*n)*np.sin(n*np.pi*x)*np.sinh(n*np.pi*y));
n = n + 1;
return sum;
def main():
x_axis = np.linspace(0,1,100)
y_axis = np.linspace(0,1,100)
#######
# This is where the code is way too slow, it takes like 10 minutes when n in v(x,y) is 20.
#######
V = np.zeros(10000).reshape((100,100))
for i in range(100):
for j in range(100):
V[i,j] = v(j/100, i/100)
plt.figure()
plt.contour(x_axis, y_axis, V, 50)
plt.show()
if __name__ == "__main__":
main()
If you look carefully (you could use a profiler too), you'll see that you're integrating your function func1 (which I'll rename into the integrand) about 20 times for each element in the 100x100 array V. However, the integrand doesn't change! So you can already bring it out of your loop. If you do that, and use broadcasting tricks, you could end up with something like this:
import numpy as np
from scipy.integrate import quad
import matplotlib.pyplot as plt
def integrand(x,n):
return 1*np.sin(n*np.pi*x)**2
sine_order = np.arange(1,20).reshape(-1,1,1) # Make an array along the third dimension
integration_results = np.empty_like(sine_order, dtype=np.float)
for enu, order in enumerate(sine_order):
integration_results[enu] = quad(integrand, 0, 1, args=(order,))[0]
y,x = np.ogrid[0:1:.01, 0:1:.01]
term = integration_results / np.sinh(np.pi * sine_order) * np.sin(sine_order * np.pi * x) * np.sinh(sine_order * np.pi * y)
# This is the key: you have a 3D matrix here and with this summation,
# you're basically squashing the entire 3D structure into a flat, 2D
# representation. This 'squashing' is done by means of a sum.
V = 2*np.sum(term, axis=0)
x_axis = np.linspace(0,1,100)
y_axis = np.linspace(0,1,100)
plt.figure()
plt.contour(x_axis, y_axis, V, 50)
plt.show()
which runs in less than a second on my system.
Broadcasting becomes much more understandable if you take pen&paper and draw out the vectors that you are "broadcasting" as if you were constructing a building, from basic Tetris-blocks.
These two versions are functionally the same, but one is completely vectorized, while the other uses python for-loops. As a new user to python and numpy, I definitely recommend reading through the broadcasting basics. Good luck! | unknown | |
d14348 | val | Try this and see if it works,this is just fancy box bit though,the rest of your code seems fine
$("#lightboxlink").live('click', function(){
$.fancybox({
'autoDimensions' : false,
'width' : 'auto',
'height' : 'auto',
'href' : $(this).attr('href')
});
return false;
}); | unknown | |
d14349 | val | First of all, your method printSidesCount only needs to know that the list contains SideCountable objects. So giving its parameter the type List<Shape> is more specific than necessary. Give it a List<SideCountable> instead:
public void printSidesCount(List<SideCountable> sideCountables) {
for(int i=0; i < (); i++) {
System.out.println(sideCountables.get(i).getSidesCount());
}
}
Or even List<? extends SideCountable> which means "a list of some arbitrary unknown type that implements SideCountable":
public void printSidesCount(List<? extends SideCountable> sideCountables) {
for(int i=0; i < sideCountables.size(); i++) {
System.out.println(sideCountables.get(i).getSidesCount());
}
}
If not all shapes have a countable number of sides, then class Shape should not implement interface SideCountable. Instead, make classes Quad and Triangle implement interface SideCountable besides extending class Shape:
class Quad extends Shape implements SideCountable {
// ...
}
class Triangle extends Shape implements SideCountable {
// ...
}
And make class Circle extend Shape but not implement SideCountable:
class Circle extends Shape { // Not SideCountable
// ...
}
When you do it like this, the type system will help you:
*
*you can pass a List<Quad> or List<Triangle> to printSidesCount since those types implement SideCountable
*you cannot pass a List<Circle> to printSidesCount, which is good because trying to do this would not make sense for a list of circles | unknown | |
d14350 | val | The biggest problem that you are facing is that your team is (on purpose or in ignorance) obscuring their work, and hiding what they are doing. You need to improve visibility.
You say always, so I take it that you have some statistics.
Assuming that your team isn't spending the remainder of their capacity being unproductive (working on unplanned tasks, browsing social media sites, daydreaming), it seems that your team is under-planning. If this is the case, you should work to expose the unplanned tasks that are being carried out, and then add them, account for them, or if necessary, have the team stop doing them.
On the other hand, it is possible that your team is purposefully being unproductive, and there is no easy way to handle that. If this is what you are facing, I'd try to figure out why this is happening. Perhaps they are feeling overwhelmed and need an outlet, or they feel that they are doomed regardless of the effort and might as well have fun. This needs to be approached very delicately, though possibly quite forcefully, if nothing changes their mind.
The important thing to remember, is that the numbers and accounting are not the problem - they are only the symptom and indicator of a deeper one, which the Scrum Master should strive to solve.
A: I was pretty much in the same boat a few years back, except we would often end up with overcommitment instead, essentially due to the fractal nature of estimates.
In my current team we decided to take a different approach and just rely on Story Points and velocity to determine sprint commitment. We do break down stories into tasks and give tasks a rough man hours estimate, however we do it essentially as a pretext for discussion/exploration and to lift technical uncertainties. We don't try to sum up estimates and relate it to planned velocity in any way afterwards.
What we do as a team to prevent the (theoretical) Parkinson effect you describe is we always set ourselves an ambitious goal for the coming sprint. This typically means taking one or two "bonus" user stories more than what our velocity would typically allow us to do. This way we're always pushing things forward, challenging ourselves and, even assuming we at some point had a 35% commitment (which I'm not sure how you'd arrive at), the gap would quickly be filled to attain full team speed.
Through that experience, I came to the realization that not tracking task times (especially not getting into complex calculations involving Scrum ceremony times, external activities or meeting durations) and not living under the constant fear of failing to "correctly estimate" is liberating - it allows you to concentrate on what's really important : delivering business value. Shipping quality features is the first priority. Estimating is only a byproduct. Let average velocity be your guide to determine the rough amount of work you can commit to. Embrace potential failure, you'll never get it exactly right anyway.
With starting velocities being equal, I'd pick a team that is bad at estimating because of its surprising repeated productivity improvements over a team that is only improving its estimates (even eventually getting them close to perfectness) any day.
A: For our new team, we "forced" them to plan for the total number of available hours. I didn't force them to add hours to stories, we just took on more stories since there was more time left (and how do you justify to your PO what they will be doing for the other remaining hours?). We did however tell the PO about this strategy and that they wouldn't succeed.
So of course, they end up over-commiting the first few sprints. But then, they realize they need to estimate tasks much better. It took about 3 sprints to get much closer to the reality. Each retrospective was focused on finding out where stories were being underestimated (wrong tasks, missing tasks, underestimated tasks, unknown, etc.). From sprint to sprint, I could see the tasks being refined.
A: Sprint Capacity Planning consists of more than simply subtracting meetings from the Sprint duration. I usually use this calculation:
For a 2 week sprint, consider that you have only 9 working days (one day is lost to Scrum meetings). Multiply this number by the number of people on the team (let's say 7 in my example). So we now have 63 days.
For each person, subtract planned time out of the office (holidays, medical appointments, off-site meetings etc). Let's assume that we have no planned absences. So we still have 63 days.
For each person, consider that they can only be "In the zone" (ie: coding) for a certain number of hours per day. For a new team, I'll use 4 hours per day for the calculation. So we now have 4 * 63 = 252 hours. Compare this to the more simple 63 man days * 8 hours per day = 504 hours and you can see it's almost half.
Finally, I apply a 'mitigation factor' to allow for those distractions that always happen. I subtract 10%. So now, we have 227 hours and that's what we use for planning purposes.
The calculation is not massively scientific but, it seems to work out most of the time.
One final thing. I only use Sprint Capacity Planning when the team are new. Once we have an established velocity, we use that instead. It's faster and usually more accurate. | unknown | |
d14351 | val | The problem isn't with your code, but with your logic. Setting IDENTITY_INSERT, along with lots of other settings, is done on a per-session basis:
The Transact-SQL programming language provides several SET statements that change the current session handling of specific information.
(emphasis mine)
As soon as your connection is closed, your session is gone, and therefore the setting is also gone.
You'll need to refactor your code to include the setting of IDENTITY_INSERT so it is in the same session as the code that makes use of it. | unknown | |
d14352 | val | I just added a variable $result to query the SQL
$result = $conn->query($sql);
if($result->num_rows > 0) {
echo "<script>alert('WELCOME'+ $username)</script>";
include_once('../scanning/index.html'); | unknown | |
d14353 | val | The Python lxml module is a language-binding / wrapper for two C libraries.
For Windows they provide binary builds that include these libraries. Otherwise it will be pain and suffering getting it installed and running on Windows. Because it's Windows. "Developers, developers, developers".. (As lxml developers put it: "users of that platform usually fail to build lxml themselves")
Normally you should get the binary distribution when doing install through pip but in this case you don't.
*
*Try to pin an older version, maybe binaries are available for it:
pip install lxml==4.9.0
*Try to download the lxml binary distribution by Christoph Gohlke available here.
You can install the wheel file also via pip.
Sources:
*
*Where are the binary builds?
*Source builds on MS Windows | unknown | |
d14354 | val | I don't think you need writer2.writerow([column_info]).
Set delimiters to \t (delimiter='\t').
Instead of:
writer4.writerow([table.get_column_info()])
writer3.writerow([table.get_results()])
do:
for info in table.get_column_info():
writer4.writerow(info)
for result in table.get_results():
writer3.writerow(result) | unknown | |
d14355 | val | To directly draw on the screenshot returned by the driver:
WebDriver driver = new FirefoxDriver();
driver.get("http://www.google.com/");
// take the screenshot
byte[] img_bytes = ((TakesScreenshot)driver).getScreenshotAs(OutputType.BYTES);
BufferedImage img = ImageIO.read(new ByteArrayInputStream(img_bytes));
// add some text and draw a rectangle
Graphics g = img.getGraphics();
g.setColor(Color.red);
g.setFont(new Font( "SansSerif", Font.BOLD, 14));
g.drawString("My text", 10, 10);
g.drawRect(5, 5, 50, 50);
g.dispose();
// save the image
ImageIO.write(img, "png", new File("screenshot.png"));
If the targeted element is off-screen then you'll probably have to scroll it into the window beforehand:
((JavascriptExecutor)driver).executeScript("arguments[0].scrollIntoView(true);", element);
A: Nothing Much! Tweaking the code from the link provided by @andrucz
WebElement failedElement = driver.findElement(<locate your element>);
File screenShotFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
final BufferedImage image = ImageIO.read(screenShotFile);
Graphics g = image.getGraphics();
g.setFont(g.getFont().deriveFont(30f));
g.drawString("Failed because of this!!", failedElement.getSize().getX(), failedElement.getSize().getY()); //Top-left coordinates of your failed element
g.dispose();
ImageIO.write(image, "png", new File("test.png")); | unknown | |
d14356 | val | I have this script in the src/test/groovy in my Maven project so I added.
<dependency>
<groupId>org.apache.servicemix.bundles</groupId>
<artifactId>org.apache.servicemix.bundles.crimson</artifactId>
<version>1.1.3_2</version>
<scope>test</scope>
</dependency>
to my pom.xml
And I added -Dorg.xml.sax.driver=org.apache.crimson.parser.XMLReaderImpl to the VM Options: in the Run/Debug Configuration for the script.
This makes it work, but I would still like to know what I can used without having to add a dependency to get things in the test scope to run since things in the main scope work without this dependency. | unknown | |
d14357 | val | You can add some build variables to the build definition and then reference those in your build steps somewhere. For example, for your API_URL add a build variable with the same name and value. If you need the variable to be secret for any reason (passwords, etc.) just click the lock icon next to the value field.
Then add a new cmd task to your build and move it to the top to set your environment variables before you start your build. The way you reference the build variables is like this...
set API_URL=$(Build.API_URL)
In the UI it will look like this:
I added two cmd tasks to a test build just to show that it is working. The first one is used to set the environment variable and then I used the second to dump all the environment variables so I could see them. You can see in the build logs that it worked.
If you want to reference the build variables using something other than the command line you can find examples of the different ways to reference build variables here. There are also examples of how to use secret variables on that page.
EDIT:
Since you have some concerns about it not being available in your node app I tested it out in the console real quick to show that it will definitely work.
A: Using yaml config you can switch to script task and then do something like this:
- script: 'npm run'
workingDirectory: 'src'
displayName: 'npm run'
env:
{ API_URL: 'api.example.com' }
A: tehbeardedone's answer is great for the build machine, and the answer is similar for when running your app in an Azure app service, which I'm thinking is what you really need. This is for if you need your access to these .env files just previous to or after your app has started (post build).
*
*To the Azure portal we go.
*Navigate to your app service.
*Click "Configuration" under the "Settings" heading.
For each of the variables you'll need during a production run of your app you'll need to:
*Click "New application setting"
*Paste the name of the variable (exactly as it appears in your .env) into the "Name" field.
*Similarly, paste the value of the variable into the next field.
*Check the "deployment slot setting" checkbox. As nebulous as this field is, it's necessary. When I didn't do this, the app didn't have access to this variable after running the start command.
Restart your app. If you deployment when well, then your app should have access to the variables add in the manner specified above. | unknown | |
d14358 | val | When you got listitem collection, you could call listItems.get_count() to return items count.
Sample code:
<script type="text/javascript">
var clientContext = null;
var web = null;
ExecuteOrDelayUntilScriptLoaded(getListItemsCount, "sp.js");
function getListItemsCount() {
clientContext = new SP.ClientContext.get_current();
web = clientContext.get_web();
var list = web.get_lists().getByTitle("Child");
var camlQuery = new SP.CamlQuery();
this.listItems = list.getItems(camlQuery);
clientContext.load(listItems, 'Include(Id)');
clientContext.executeQueryAsync(function () {
alert(listItems.get_count());
},
function () {
alert('error');
});
}
</script> | unknown | |
d14359 | val | Hi I just figured it out!
if just by a a coincidence you're using LoadUserInfo that have a try / catch when you are trying to assign the values, hiding a null reference exception and doing the redirect without doing a re-throw
that got fixed just by creating a new List like this:
userSession.Roles = new List<string> {"your-role-here"}; | unknown | |
d14360 | val | You could make a table with one row and then ng-repeat the columns in that row. In each column you can then make a table with 4 rows and one column:
http://plnkr.co/edit/3xvdGC?p=preview (I reformatted your JSON data to be able to work with it)
However, this will give problems if the text of some table cells require multiple lines. To solve that you could just use multiple ng-repeat statements:
http://plnkr.co/edit/EUKNn5?p=preview
A: Write your html like this:
<body>
<table ng-controller="MyCtrl">
<tr>
<td ng-repeat="r in result">
<table border=1>
<tr>
<td>
{{r.date}}
</td>
</tr>
<tr>
<td>
{{r.result}}
</td>
</tr>
<tr>
<td>
{{r.time}}
</td>
</tr>
<tr>
<td>
{{r.reason}}
</td>
</tr>
</table>
</td>
</tr>
</table>
</body>
You will find a plunker here
Note that i reformated your json, dropped some data and left all the fancy formating to you.
A: You can just use ng-repeat multiple times for each label: http://jsfiddle.net/4HHc2/2/
After reformatting your json string as an array of results, you can just call each item as follows:
<td ng-repeat="d in data">{{d.date}}</td> | unknown | |
d14361 | val | There isn't any way to query this list, but you can find it here
List of Undocumented Stored Procedures in SQL Server | unknown | |
d14362 | val | Why not use a positioned pseudo element with a suitably applied border?
pseudo-elements are added to selectors but instead of describing a
special state, they allow you to style certain parts of a document
You may also want to use the semantic footer element (if appropriate)
footer {
background: black;
height: 200pt;
position: relative;
}
footer:after {
content: '';
position: absolute;
left: 30pt;
right: 30pt;
bottom: 25pt;
border-top: 1px solid white;
}
<footer></footer>
A: You're almost there. You don't need the width. Also, if you use position: absolute to position the element inside its parent, then you must also add position: relative or position: absolute to the parent itself.
By the way, if this white line is just for show, you might as well use a pseudo-element for it and keep the HTML simple. But if you like to, you might as well change .footer:before back to #HPFooterlinebreak.
.footer {
background-color: blue;
position: relative;
height: 200px;
}
.footer:before{
content: "";
position:absolute;
bottom:25pt;
right:30pt;
left:30pt;
background-color:#EFF1EF;
height:1px;
}
<div class="footer">
Yo
</div> | unknown | |
d14363 | val | ORA-00942: table or view does not exist
"You tried to execute a SQL statement that references a table or view that either does not exist, that you do not have access to, or that belongs to another schema and you didn't reference the table by the schema name."
I'd see if the database table is correct and double check the SQL query.
Ref: https://www.techonthenet.com/oracle/errors/ora00942.php
A: Error mean you don't have permision or your table incorrect. Please check entity. Make sure table : TitleOfMyDb exist in database. If you don't specific table with anotation @table hibernate automatic pick your name entity TitleOfMyDb | unknown | |
d14364 | val | You can move your DataTrigger under DataTemplate.Triggers.
Have it set the Visibility for a new TextBlock with the text you want.
<DataTemplate>
<Grid>
<Image/>
<TextBlock Visibility="Collapsed"/>
</Grid>
<DataTemplate.Triggers>
</DataTemplate.Triggers>
</DataTemplate> | unknown | |
d14365 | val | This behavior is a bug in ActiveX control.
As a work around, use a button from the Forms Controls, rather than an ActiveX button
Using the Forms button you will need to add a Module, declare a Sub with your code and assign the Sub as the action macro to your button (as apposed to putting your code in the click event of an ActiveX button)
I tried this on Excel 2007, seem to work OK - the button appears and works on both windows | unknown | |
d14366 | val | If I understand what you're looking for, this should do it:
static <E> TypeToken<List<E>> listToken(Class<E> elementClass) {
return new TypeToken<List<E>>() {}
.where(new TypeParameter<E>() {}, elementClass);
}
See ReflectionExplained for more info. | unknown | |
d14367 | val | So it turns out that the solution to this problem is adding the following line to initialize the memory pointed by dev_out.
cudaMemcpy( dev_out, image_out, size_out * sizeof(int), cudaMemcpyHostToDevice );
I forgot to initialize it since I was thinking that it is a output variable and I initialized it on the host.
Just like that talonmies said, it has nothing to do with atomicAdd at all. Both int version and double version of atomicAdd works perfectly. Just remember to initialize your variable on device. | unknown | |
d14368 | val | This work around has been less than ideal, but it seems to get the job done:
1 - I added an attribute to subject called count.
2 - I set (part of) my expression to
ANY correspondent.subjects.count == 1
Note that no SUBQUERY() was necessary for this workaround.
3 - Everytime I modify a subject's correspondents set, I run
subject.count = @(subject.correspondents.count);
I'm still hoping for a better solution and will be happy to mark any (working) better solution as correct.
A: I had a similar problem. I created an additional field countSubentity. And when add/remove subentity change this field. And predicate looks:
[NSPredicate predicateWithFormat:@"SUBQUERY(subcategories, $s,
$s.countSubentity > 0).@count > 0"]; | unknown | |
d14369 | val | HTML5 has something called data-attributes that might fit your needs. You could do something like this:
<body data-test="true"></body>
And then check the boolean value of the attribute like this (using jQuery):
!!$('body').attr('data-test')
Explanation of the "double bang" operator:
You can get the boolean value of any javascript object like this:
!!0 //false
!!1 //true
!!undefined //false
!!true //true
Edit
As noted by David, a non-empty string (like "false" for example) would yield true.
You've got 2 options here:
*
*dont set the attribute, which will be undefined and hence false
*compare to the string "true" instead of using the !! operator
Hope that helps! | unknown | |
d14370 | val | boost.thread is probably linked to libstdc++.
libstdc++ and libc++ have incompatible ABI. They shouldn't be used both in one program. | unknown | |
d14371 | val | SELECT author.author_id, author.name, count(song.song_id)
FROM song, author, song_author,
WHERE song.song_id = $id
AND song.song_id = song_author.song_id
AND song_author.author_id = author.author_id
AND song_author.display_order != 1
GROUP BY song_author.author_id, author.name
ORDER BY author.author_id asc;
A: try this..
select b.author_Id, b.name, COUNT(a.Song_Id) as 'total'
FROm song_author as a
INNER JOIN author as b
ON a.author_id = b.author_id
where a.song_id IN (select s.song_id
From songs as s
Where s.Song_Id = 598
AnD s.is_draft = 1)
GROUP bY b.author_Id, b.name
A: New to SQL too, but off the top of my head maybe this? This doesn't explicitly spell out joins, but I've found it works for my purposes. Maybe someone can let me know if this is bad practice?
Select author.author_id
, author.name
, count(author.author_id)
from song, author, song_author
where song.song_id = song_author.song_id
and author.author_id = song_author.author_id
group by author.authorid, author.name
order by author.author_id asc; | unknown | |
d14372 | val | You're gonna need to change up your CSS a little so the clearfix can be moved in the first place.
.clearfix{
position: absolute;
left: -20%;
top: 0px;
height: 100%;
width: 100%;
}
As for jQuery, it's pretty simple to use.
function toggleSidebar(){
$('.in').animate({left: '0%'}, function(){
$(this).addClass('out').removeClass('in');
});
$('.out').animate({left: '-20%'}, function(){
$(this).addClass('in').removeClass('out');
});
}
$('.moreB').on('click', toggleSidebar);
One more thing to do is to add a semantic class to clearfix named in
<div class="clearfix in">
A: You can do this primarily with CSS, and use jQuery to toggle a class on the wrapping element to expand/collapse the sidebar.
http://jsfiddle.net/G7K6J/
HTML
<div class="wrapper clearfix">
<div class ="sideBar">
</div>
<div class="mainCon">
<div class="moreB">
<div class="buttonText">
Learn More
</div>
</div>
</div>
</div>
CSS
.clearfix {
clear:both;
overflow:hidden;
}
.sideBar{
width: 0%;
height: 200px;
background-color: #FF0040;
float: left;
-webkit-transition: width 300ms;
-moz-transition: width 300ms;
-o-transition: width 300ms;
transition: width 300ms;
}
.mainCon{
height: 200px;
width: 100%;
float: left;
background-color: #F3F781;
-webkit-transition: width 300ms;
-moz-transition: width 300ms;
-o-transition: width 300ms;
transition: width 300ms;
}
.wrapper.expanded .sideBar {
width:20%;
}
.wrapper.expanded .mainCon {
width:80%;
}
.moreB{
color: #ffffff;
width: 100px;
height: 50px;
margin:0 auto;
border-radius: 60px 60px 60px 60px;
-moz-border-radius: 60px 60px 60px 60px;
-webkit-border-radius: 60px 60px 60px 60px;
border: 2px solid #ffffff;
}
jQuery
$(".moreB").click(function(){
$(".wrapper").toggleClass("expanded");
}); | unknown | |
d14373 | val | Try this
function selectUserField($email, $field, $connection){
$select_user = "SELECT `$field` FROM users WHERE `email`='$email' LIMIT 1"; //wrap it with ` around the field or don't wrap with anything at all
$result = mysqli_query($connection, $select_user);
$value = mysqli_fetch_assoc($result);
return $value[$field];
}
//And I try to echo the result of the function
$connection = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
echo selectUserField("[email protected]", "name", $connection);
A: No quotes around $field.
"SELECT $field FROM users WHERE email='$email' LIMIT 1"; | unknown | |
d14374 | val | in short this is how you create a broadcast
private static final String ACTION_ALARM = "your.company.here.ACTION_ALARM";
public static void createAlarm(){
Intent alarmIntent = new Intent();
alarmIntent.setAction(ACTION_ALARM);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, alarmIntent, 0);
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, timestamp for alarm, pi);
}
public void onReceive(...){
//whatever is supposed to happen on receive
}
and you need to declare that broadcastreceiver and the actionname its supposed to receive in manifest:
<receiver
android:name="your.company.here.AlarmReciever">
<intent-filter>
<action android:name="your.company.here.ACTION_ALARM" />
</intent-filter>
</receiver> | unknown | |
d14375 | val | You can access shapes by name, as in:
Dim oSlide As Slide
Set oSlide = ActivePresentation.Slides(1)
Dim oShape As Shape
Set oShape = oSlide.Shapes(strShapeName)
Dim oTextRange As TextRange
Set oTextRange = oShape.TextFrame.TextRange
oTextRange.Text = "this is some text"
oTextRange.Font.Bold = msoTrue
Note that whatever you're looking to do, just record a macro of you doing it via the UI, and copy that. You're right that the recorded macro will use the Selection object a lot, but that's easily fixed - just get a reference to the appropriate Shape object (or whatever) and then subsitute that in the generated code.
So, for example, if the recorded macro for changing the fill color of a shape is this:
With ActiveWindow.Selection.ShapeRange
.Fill.Visible = msoTrue
.Fill.Solid
.Fill.ForeColor.RGB = RGB(255, 0, 0)
.Fill.Transparency = 0#
End With
... and you want to apply the fill color to a shape which you already have a reference to as oShape, then change the code to this:
With oShape
.Fill.Visible = msoTrue
.Fill.Solid
.Fill.ForeColor.RGB = RGB(255, 0, 0)
.Fill.Transparency = 0#
End With
To get the current name of a shape, you can enter this in the "immediate" window in the VBA editor:
?ActiveWindow.Selection.ShapeRange(1).Name
You could turn that into a (single) macro very easily:
Sub ShowMeTheName()
MsgBox ActiveWindow.Selection.ShapeRange(1).Name
End Sub
Note that I would personally rename the shapes to something meaningful rather than using the default names. Simply turn do this in the immediate window:
ActiveWindow.Selection.ShapeRange(1).Name = "MyName"
...or create a macro to prompt for a name.
A: When I need to automate Word or Excel (nobody I know or work with has any use for PowerPoint), I open the app in question, turn on Macro recording and do the task I want to automate. Then I use the generated code as the basis for my Access code. It's often a pretty straightforward process, sometimes as simple as copying and pasting and then prefacing each line with the application object I'm using from Access.
If I had to do what you're doing, that's exactly how I'd start, by doing recording the task being performed interactively, and then experimenting with what part of the code is essential. | unknown | |
d14376 | val | What do you want to fix?
First you compiled your source file with javac Hello.java...
Then you tried to run it with java Hello...
However the command java requires a fully qualified class name. What you supplied (Hello) seems to me, like the name of he .class file, without extension.
When you tried with java myclass, it worked, because it is the fully qualified class name of your class...
See: java and javaw reference | unknown | |
d14377 | val | You could do something similar to - https://stackoverflow.com/a/3667379/33116 - you can then instead of redirecting you can do a request to a web api end point which can return the download count and update an element with the returned value. | unknown | |
d14378 | val | The networking tutorial explains, in full detail, how to create a TCP server socket and accept connections from it.
Here's the gist of it:
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(4444);
} catch (IOException e) {
System.err.println("Could not listen on port: 4444.");
System.exit(1);
}
Socket clientSocket = null;
try {
clientSocket = serverSocket.accept();
} catch (IOException e) {
System.err.println("Accept failed.");
System.exit(1);
}
// now get the input and output streams from the client socket
// and use them to read and write to the TCP connection
clientSocket.close();
serverSocket.close(); | unknown | |
d14379 | val | You don't have a column called empno that you are returning in the subquery. I think you want something like this which will return the max(sal) for each employee based on the job:
Select a.*, b.sal
From EMP a
inner join
(
Select job, MAX(sal) sal
From emp
Group By job
) c
on a.job = b.job
A: Try this instead:
Select a.*
From EMP a
INNER JOIN
(
Select job, MAX(sal) MaxSal
From EMP
Group By job
) b ON a.job = b.job AND a.sal = b.MaxSal | unknown | |
d14380 | val | client.guilds.cache.forEach(guild => {
console.log(`${guild.name} | ${guild.id}`);
})
A: let clientguilds = client.guilds.cache()
console.log(clientguilds.map(g => g.id) || "None")
This should do the trick! It's going to cache all the guilds your bot is in and then it will map the guilds as an array. We then get the id of each guild or, if it's not in any guilds "none". | unknown | |
d14381 | val | Check this out, Unitils. Here is a related discussion, with some example codes.
Here is the example, showing DBUnit, Spring and OpenJPA together. You might not using all, but this can take you somewhere if you want to go with DBUnit, I believe.
A: I'm in the middle of trying out OpenEJB (http://openejb.apache.org/) for my ongoing project. It's an embeddable container with support for EJB 3.0 (and partially 3.1). My first impression of it is fairly good.
A: recently I faced a problem of testing:
*
*business logic operating on JPA Entities
*complex JPQL queries mixed with business logic.
I used JPA-Unit and it solved all my problems. | unknown | |
d14382 | val | You have to pass the model in Header from the view and from controller and in partialview too
lisk below
Please get look deeply in bold text and the text in between ** **
**@model Hybridinator.Domain.Entities.Database**
<div class="modal fade" id="modalEditDBInfo" role="application" aria-labelledby="modalEditDBInfoLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modalEditDBInfoContent" style="background-color:white; border-radius:10px; box-shadow:10px;">
@Html.Partial("_EditDatabaseInfo", **Model** )
</div>
</div>
[HttpPost]
public ActionResult EditDatabaseInfo(Database database)
{
string s = database.database;
//do other stuff
// **you have to get the model value in here and pass it to index action**
return RedirectToAction(**"Index", modelValue**);
}
public ActionResult Index(**ModelClass classValue**)
{
//pass the model value into index view.
return View(**"Index", classValue**);
}
A: Change the Model in view, partial view and in action . Instead of passing entity model, create view model and pass it in view as well as partial view. consider the following
@model **DatabaseModel**
<div class="modal fade" id="modalEditDBInfo" role="application" aria-labelledby="modalEditDBInfoLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modalEditDBInfoContent" style="background-color: white; border-radius: 10px; box-shadow: 10px;">
@Html.Partial("_EditDatabaseInfo", **Model**)
</div>
</div>
</div>
@model DatabaseModel
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4 class="modal-title" id="editModelTitle">Edit Database Info</h4>
</div>
<div class="modal-body">
@using (Html.BeginForm( new { @class = "modal-body" }))
{
<div class="form-group">
<div id="databaselabel" >@Html.LabelFor(m => m.DatabaseName, "Database")</div>
<div id="databaseedit" >@Html.EditorFor(m => m.DatabaseName)</div>
</div>
<div class="form-group">
<div id="databaseserverlabel" >@Html.LabelFor(m => m.DatabaseServer, "Database Server")</div>
<div id="databaseserveredit" >@Html.EditorFor(m => m.DatabaseServer)</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button class="btn btn-inverse btn-primary" type="submit">Save</button>
</div>
}
</div>
public class DatabaseModel
{
public string DatabaseName { get; set; }
public string DatabaseServer { get; set; }
}
As of my knowledge Database is a key word, because of that it is getting null | unknown | |
d14383 | val | Try this:
Remove the transform property from cog class. Then it will only rotate.
CSS
.cog {
margin-top: 250px;
cursor: pointer;
transition: transform 0.5s ease-in-out;
position: relative;
left: 50%;
}
.cog:hover {
transform: rotate(-.4turn);
}
A: You need to include the translation on hover too:
.cog {
cursor: pointer;
transition: transform 0.5s ease-in-out;
position: relative;
left: 50%;
transform: translateX(-50%);
width:50px;
height:50px;
background:red;
}
.cog:hover {
transform: translateX(-50%) rotate(-.4turn);
}
<div class="cog"></div> | unknown | |
d14384 | val | It's not clear whether you're getting locking problems or errors.
"TX-row lock contention" is an event indicating that two sessions are trying to insert the same value into a primary or unique constraint column set -- an error is not raised until the first one commits, then the second one gets the error. So you definitely have multiple sessions inserting rows. If you just had one session then you'd receive the error immediately, with no "TX-row lock contention" event being raised.
Suggestions:
*
*Insert into a temporary table without the constraint, then load to the real table using logic that eliminates the duplicates
*Eliminate the duplicates as part of the read of the XML.
*Use Oracle's error logging syntax -- example here. http://docs.oracle.com/cd/B28359_01/server.111/b28286/statements_9014.htm#SQLRF55004 | unknown | |
d14385 | val | in your yml, what you have is formatted in a ".properties' file format, you need to format your property to yml format. So, your yml file should be in the format (something like this):
spring:
profiles:
active: dev
config:
activate:
onProfile: dev
application:
id : dev-app
etc... | unknown | |
d14386 | val | This is one way to use it. First, you have to use ITelephony in your project. I will give you an example to use it in below link. Second, you have to insert code to start service when you restart phone as follows:
in AndroidManifest File :
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
Change this to :
@Override
public void onReceive(Context context, Intent intent) {
Intent serviceIntent = new Intent(context,BackgroundService.class);
startService(serviceIntent);
}
The sample code at https://github.com/Levon-Petrosyan/Call_redirect_and_reject | unknown | |
d14387 | val | If you did not find a better solutions( I know it is very late, but I am doing something similar and I found my self in here.)
I think you can "cache" previous results, put them in ArrayList. And then in your adapter when performFiltering is called, start by checking the results you have in your Arraylist and if you receive a number of similar items, dont make a request to the API. I am not sure if it is clear but you can at least save a couple requests like that and for the user side, the autocomplete is always refreshing.
I hope it helps.
A: I think a better implementation to reduce the number of calls to the Places API would be to put in a delay of maybe 0.75 seconds after the last key-press. That would avoid confusion on the part of a user who after seeing autocomplete after 3 letters, sits and waits after typing his 5th. | unknown | |
d14388 | val | You are going to have to choose your own method of converting colours from the greyscale scheme to whatever colour you want.
In the example you've given, you could do something like this.
public Color newColorFor(int pixel) {
Color c = colors[pixel];
int r = c.getRed(); // Since this is grey, the G and B values should be the same
if (r < 86) {
return new Color(r * 3, 0, 0); // return a red
} else if (r < 172) {
return new Color(0, (r - 86) * 3, 0); // return a green
} else {
return new Color(0, 0, (r - 172) * 3); // return a blue
}
}
You may have to play around a bit to get the best algorithm. I suspect that the code above will actually make your image look quite dark and dingy. You'd be better off with lighter colours. For example, you might change every 0 in the code above to 255, which will give you shades of yellow, magenta and cyan. This is going to be a lot of trial and error.
A: I recommend you to take a look at Java2D. It has many classes that can make your life much easier. You may end up reinventing the wheel if you ignore it.
Here is a short showcase of what you can do:
int width = 100;
int height = 100;
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
image.getRGB(x, y);
Graphics2D g2d = (Graphics2D)image.getGraphics();
g2d.setColor(Color.GREEN);
g2d.fillRect(x, y, width, height); | unknown | |
d14389 | val | 239.254.1.2 is a multicast address that the UDP server is sending packets to. Anyone listening on that address will receive the packets. So:
*
*create a UDP socket
*bind your socket to port 7125
*join the multicast group 239.254.1.2
*your app will start receiving the udp packets
Probably should just mention that UDP is connectionless protocol, i.e. you cannot connect to a UDP server.
A: RichardBrock was right and sample code from UPDATE1 works perfectly. Problem was with my home Network, and when I tryed this code in the work Network everything works fine!!!
Thanks you | unknown | |
d14390 | val | You are reading the first column, but not the rest. What I do is create a dictionary, using the first number as the index, and stuffing the other two fields into a System.ValueTuple (you need to include the ValueTyple Nuget package to get this to work).
First I set some stuff up:
const int column1Start = 0;
const int column1Length = 3;
const int column2Start = 8;
const int column2Length = 15;
const int column3Start = 24;
int indexMin = int.MaxValue; //calculated during the first
int indexMax = int.MinValue; //pass through the file
Then I create my dictionary. That (string, decimal) syntax describes a 2-tuple that contains a string and a decimal number (kind of like the ordered-pairs you were taught about in high school).
Dictionary<int, (string, decimal)> data = new Dictionary<int, (string, decimal)>();
Then I make a pass through the file's lines, reading through the data, and stuffing the results in my dictionary (and calculating the max and min values for that first column):
var lines = File.ReadAllLines(fileName);
foreach (var line in lines) {
//no error checking
var indexString = line.Substring(column1Start, column1Length);
var cartoon = line.Substring(column2Start, column2Length).TrimEnd();
var numberString = line.Substring(column3Start);
if (int.TryParse(indexString, out var index)) {
//I have to parse the first number - otherwise there's nothing to index on
if (!decimal.TryParse(numberString, out var number)){
number = 0.0M;
}
data.Add(index, (cartoon, number));
if (index < indexMin) {
indexMin = index;
}
if (index > indexMax) {
indexMax = index;
}
}
}
Finally, with all my data in hand, I iterate from the min value to the max value, fetching the other two columns out of my dictionary:
for (int i = indexMin; i <= indexMax; ++i) {
if (!data.TryGetValue(i, out var val)){
val = ("0", 0.0M);
}
Console.WriteLine($"{i,5} {val.Item1,-column2Length - 2} {val.Item2, 10:N}");
}
My formatting isn't quite the same as yours (I cleaned it up a bit). You can do what you want. My results look like:
300 Family Guy 1,123.00
301 Dexters Lab 456.00
302 Rugrats 1,789.52
303 0 0.00
304 Scooby-Doo 321.00
305 0 0.00
306 Recess 2,654.00
307 Popeye 1,987.02 | unknown | |
d14391 | val | From the code you posted, this looks good in theory, but still has a few errors.
*
*You're using ObjArray in AppComponent without initializing it, so you can't access it with [1]
*The getData method in your service doesn't actually return anything
Here are my proposed changes for the service:
getData() {
this.objAr = utils.sheet_to_json(this.wbSheet, { header: 1 });
return this.objAr;
}
and for the component:
export class AppComponent implements OnInit {
ObjArray: any[] = [];
constructor(private _operationDataService: OperationDataService) { }
ngOnInit() {
let data = this._operationDataService.getData();
this.ObjArray.push(data);
}
}
A: this it's work :
Upload() {
let fileReader = new FileReader();
fileReader.onload = (e) => {
this.arrayBuffer = fileReader.result;
/* convert data to binary string */
var data = new Uint8Array(this.arrayBuffer);
var arr = new Array();
for(var i = 0; i != data.length; ++i) arr[i] = String.fromCharCode(data[i]);
var bstr = arr.join("");
var workbook = XLSX.read(bstr, {type:"binary"});
var first_sheet_name = workbook.SheetNames[0];
var worksheet = workbook.Sheets[first_sheet_name];
console.log('excel data:',XLSX.utils.sheet_to_json(worksheet,{raw:true}));
}
fileReader.readAsArrayBuffer(this.file);
} | unknown | |
d14392 | val | Use the DriveType property of the Drive object:
For Each d in CreateObject("Scripting.FileSystemObject").Drives
WScript.sleep 60
If d.DriveType = 4 Then
CreateObject("Shell.Application").Namespace(17).ParseName(d.DriveLetter & ":\").InvokeVerb("Eject")
End If
Next
A: Here is code that uses Media Player to eject; I'm not sure how easy it would be to invoke from your WinPE environment:
' http://www.msfn.org/board/topic/45418-vbscript-for-openingclosing-cd/
' http://waxy.org/2003/03/open_cdrom_driv/
Set oWMP = CreateObject("WMPlayer.OCX.7" )
Set colCDROMs = oWMP.cdromCollection
For d = 0 to colCDROMs.Count - 1
colCDROMs.Item(d).Eject
Next 'null
Plan B would be to download a copy of "eject.exe", and include it on your WinPE media:
*
*http://www.911cd.net/forums/index.php?showtopic=2931&hl=cd+eject | unknown | |
d14393 | val | The easiest way in my opinion is to override the get_queryset method of your ModelViewSet:
views.py
def BaseAPIView(...):
''' base view for other views to inherit '''
def get_queryset(self):
queryset = self.queryset
# get filter request from client:
filter_string = self.request.query_params.get('filter')
# apply filters if they are passed in:
if filters:
filter_dictionary = json.loads(filter_string)
queryset = queryset.filter(**filter_dictionary)
return queryset
The request url will now look like, for example: my_website.com/api/products?filter={"name":"book"}
Or more precisely: my_website.com/api/products?filter=%7B%22name%22:%22book%22%7D
Which can be built like:
script.js
// using ajax as an example:
var filter = JSON.stringify({
"name" : "book"
});
$.ajax({
"url" : "my_website.com/api/products?filter=" + filter,
"type" : "GET",
...
});
Some advantages:
*
*no need to specify which fields can be filtered on each view class
*write it once, use it everywhere
*front end filtering looks exactly like django filtering
*can do the same with exclude
Some disadvantages:
*
*potential security risks if you want some fields to be non-filterable
*less intuitive front-end code to query a table
Overall, this approach has been far more useful for me than any packages out there. | unknown | |
d14394 | val | Localization Override: You can try to add a localization file and then override the WelcomeDlgTitle string (the WiX GUI string list / list of string identifiers can be found here (for English):
*
*Note that this assumes the Mondo dialog set:
*
*Add to WiX markup: <UIRef Id="WixUI_Mondo" />
*Add reference to %ProgramFiles(x86)%\WiX Toolset v3.11\bin\WixUIExtension.dll
*WiX Hello World Sample in Visual Studio (WiX markup with comments towards bottom is usually enough for developers to get the gist of things)
*Right click your WiX project in Visual Studio => Add => New Item...
*Select WiX v3 in the left menu. Double click Localization file (very common to add a WiX v4 file instead, double check please)
*Add the string below to the localization file:
<?xml version="1.0" encoding="utf-8"?>
<WixLocalization Culture="en-us" xmlns="http://schemas.microsoft.com/wix/2006/localization">
<String Id="WelcomeDlgTitle">{\WixUI_Font_Bigger}Welcome to the [ProductName] [ProductVersion] Setup Wizard</String>
</WixLocalization>
*Compile and test
Sample Dialog:
WiX GUI: I am quite confused myself with WiX GUI, hence I wrote this little overview and "check list" to remember better (uses a similar approach to change the style of a dialog entry): Changing text color to Wix dialogs.
Links:
*
*WiX UI Sources: (languages strings and dialog sources)
*
*https://github.com/wixtoolset/wix3/tree/develop/src/ext/UIExtension/wixlib
*WiX UI English Strings:
*
*https://github.com/wixtoolset/wix3/blob/develop/src/ext/UIExtension/wixlib/WixUI_en-us.wxl
*WiX UI Norwegian Strings:
*
*https://github.com/wixtoolset/wix3/blob/develop/src/ext/UIExtension/wixlib/WixUI_nb-NO.wxl
*There are many such language files, use above link for full list
A: WiX UI extension doesn't allow this type of customization. Your two chances would be
1) define Name="Test Application $(var.ProductVersion)" (Side effect. version listed in programs and features twice
2) Stop using the WiXUI extension and instead clone all the code from https://github.com/wixtoolset/wix3/tree/develop/src/ext/UIExtension/wixlib into your project. | unknown | |
d14395 | val | You need to make the first capture group "lazy" or non-greedy.
var re = new RegExp("^(\\S+?)(?:-\\d+)?$");
var testStrings = [
"brand-new-car",
"brand-new-car-1",
"brand-new-car-100",
"307"
];
for (var i=0; i<testStrings.length; i++) {
var result = re.exec(testStrings[i]);
say("result: " + result);
}
The results:
result: brand-new-car,brand-new-car
result: brand-new-car-1,brand-new-car
result: brand-new-car-100,brand-new-car
result: 307,307
A: Try this (?xms)(^[\w-]+.*?)(?=[\w-]+|\Z)
Here, below is an image of regex buddy
where you can catch the "name" regardless of whether the string has -count the yellow and blue foreground highlights the different selections.
A: Just remove the pipe '|', then it works
(\S+)(?:-\d+)$
Checked here rubular | unknown | |
d14396 | val | Never mind, I found out why it did not work and I will post it here for anybody facing the same problem.
The problem was in this piece:
@font-face {
font-family: \'mgenplus\';
font-style: normal;
font-weight: 400;
src: url(dompdf/fonts/rounded-mgenplus-1c-regular.ttf) format(\'truetype\');
}
.ft0{font: 14px;line-height: 16px;}
*{ font-family: mgenplus !important;}
I had to remove the @font-face block, it is not needed since you load the font from DomPDF and not from the file. The line that caused all the trouble was .ft0{font: 14px;line-height: 16px;} it sets the font-family to the browser default apparently and the overwrite afterwards is not taken into account by DomPDF (no support for !important?).
Changing the line to .ft0{font-size: 14px;line-height: 16px;} fixed my problem. | unknown | |
d14397 | val | Just run the following in your composer
composer require "illuminate/html":"5.0.*"
Inside your config/app.php add the following codes inside it
In the 'providers' => [ ..]
'Illuminate\Html\HtmlServiceProvider',
And in the
'aliases' => [ ..]
'Form'=> 'Illuminate\Html\FormFacade',
'HTML'=> 'Illuminate\Html\HtmlFacade',
And then refresh the page you should find that it should be working. | unknown | |
d14398 | val | You can try some variation on the following
//get user input as a string and convert to integer array
int[] num = "12345".Select(a => Int32.Parse(a.ToString())).ToArray();
A: Try this way
string str1 = "123456";
int[] arr = new int[str1.Length];
for (int ctr = 0; ctr <= str1.Length - 1; ctr++)
{
arr[ctr] = Convert.ToInt16(str1[ctr].ToString());
}
Demo result:
Take a look at Page load event code only.... :p Cheers
A: String input="123456";
int [] intArray=new int[input.Length];
int count=0;
foreach(var ch in input)
{
intArray[count]=Convert.ToInt32(ch.ToString());
count++;
} | unknown | |
d14399 | val | I think it should be like this:
lmdb_env = lmdb.open(lmdb_file_name, readonly=True)
print lmdb_env.stat()
Then it prints the directory that Jaco pasted here.
A: env = lmdb.open('db file path', max_dbs = ' > 0')
with env.begin() as tx:
db = env.open_db(b'db name', txn=tx)
print(env.stat())
print(tx.stat(db)) # this gives stats about one specific db
env.stat() gives entries of the main database. tx.stat(db) gives entries of one named database.
A: You can use event.stat(). It will return the following dictionary with entries detailing the number of records in this database:
{'branch_pages': 1040L,
'depth': 4L,
'entries': 3761848L,
'leaf_pages': 73658L,
'overflow_pages': 0L,
'psize': 4096L}
A: I found a simple solution using for loop. Here it is:
count = 0
for key, value in lmdb_env.cursor():
count = count + 1
However, I think there should be a better way using pre-defined function. | unknown | |
d14400 | val | In general, we use WebView.NavigateToString(htmlstring); to load and display html string. For source of WebView, only apply for Uri parameters. But you can create an attached property like HtmlSource for WebView and when it changes to call NavigateToString to load.
public class MyWebViewExtention
{
public static readonly DependencyProperty HtmlSourceProperty =
DependencyProperty.RegisterAttached("HtmlSource", typeof(string), typeof(MyWebViewExtention), new PropertyMetadata("", OnHtmlSourceChanged));
public static string GetHtmlSource(DependencyObject obj) { return (string)obj.GetValue(HtmlSourceProperty); }
public static void SetHtmlSource(DependencyObject obj, string value) { obj.SetValue(HtmlSourceProperty, value); }
private static void OnHtmlSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
WebView webView = d as WebView;
if (webView != null)
{
webView.NavigateToString((string)e.NewValue);
}
}
}
.xaml:
<WebView x:Name="webView" local:MyWebViewExtention.HtmlSource="{x:Bind myHtml,Mode=OneWay}"></WebView>
For more details, you can refer to Binding HTML to a WebView with Attached Properties. | unknown |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.