_id
stringlengths 2
6
| partition
stringclasses 3
values | text
stringlengths 4
46k
| language
stringclasses 1
value | title
stringclasses 1
value |
---|---|---|---|---|
d13001 | train | I think you should be able to do this in two different methods. First replace the text "images/" to your dynamic URL on the server side before you assign the email HTML to the container. It should be straight forward whatever language you are using.
If that is not possible then you can do that on client side with JQuery. The code below loops through all the img tags on the page and replaces to a path you specify. This does not actually change the source code but it renders the images with the new path.
$(document).ready(function(){
$("img").each(function(i) {
$(this).attr('src', $(this).attr('src').replace('old_path', 'new_Path'));
});
}); | unknown | |
d13002 | train | After adding the Faker gem to your gemfile, add this to your user.rb file.
def self.generate_new
name = Faker::Name.name
password = "foobar"
email = Faker::Internet.email
zip = Faker::Address.zip
User.create!(name: name,
passowrd: password,
email: email,
zip: zip)
end
After restarting your console, the command User.generate_new should run this command and generate a new user with random inputs.
A: Take a look at this gem: https://github.com/stympy/faker
It creates fake data for objects. | unknown | |
d13003 | train | Just add an default to your switch case
switch (speech)
{
case "1":
Bill.Speak("Command 1");
break;
case "2":
Bill.Speak("Command 2");
break;
default:
Bill.Speak("You have given an invalid command. Please try again.");
break;
}
A: I think what you want is a default for your switch. so
switch (case)...
{
//Commands
default: // not recognized
Bill.Speak("You have given an invalid command. Please try again.");
}
A: add
Default:
Bill.Speak("I donot understand command");
to your case statement | unknown | |
d13004 | train | Found the error in your code : the file is been opened in READ ONLY mode, so you can't write it :
proc OpenFile
;Open file
mov ah,3Dh
mov al,2 ;<================== 0:READ ONLY, 1:WRITE ONLY, 2:READ/WRITE.
lea dx,[filenameStr+2]
int 21h
jc openerror
mov [filehandle],ax
ret
openerror:
mov dx,offset ErrorOpenMsg
mov ah,9h
int 21h
ret
endp OpenFile | unknown | |
d13005 | train | By default, it seems like the debian package will start Sphinx with an additional keepalive process. I was able to stop it successfully with this;
sudo service sphinxsearch stop
A: the 'init: ... main process ended, respawning' suggests there is something in the init script that sets a watchdog to make sure sphinx doesnt die.
Perhaps you need to shutdown sphinx via the init script itself
/etc/init.d/sphinxsearch stop
A: To my knowledge, Upstart is responsible for respawning searchd after you attempt to stop/kill it.
Since we know that this process is being managed by upstart, we can terminate the daemon using "stop sphinxsearch" and then start it again with "start sphinxsearch".
If you want to kill it normally like any other process, then you can remove the "--nodetach" argument in the config file /etc/sphinxsearch/sphinx.conf. However, by doing this, you can no longer stop the process using "stop sphinxsearch".
A: No, there are no any sphinx option to restart Sphinx.
Probably some monitoring tool like monit installed for Sphinx. | unknown | |
d13006 | train | from your code:
<% @post.comments.each do |comment| %>
<%= render @post.comments %>
<% end %>
this should either be:
<%= render @post.comments %>
or:
<% @post.comments.each do |comment| %>
<%= render comment %>
<% end %>
A: I have a feeling what you want in your loop is this:
<ul class="comments">
<% @post.comments.each do |comment| %>
<%= render comment %>
<% end %>
</ul>
And not render, again, the whole collection @post.comments | unknown | |
d13007 | train | You cannot find a view by it's ID until AFTER the call to
setContentView(R.layout.main);
Put the above line as the 2nd line of your onCreate function and it will work.
A: As a suggestion, a handy java function is String.split(String pattern). Still assuming that each line in your text will always be: string, integer. We can re-write you reader loop:
while (( strLine = r.readLine()) != null) {
String[] pair = strLine.split(",");
Food newFood = new Food(pair[0], Integer.parseInt(pair[1]));
foodlist.add(newFood);
}
I'm not too sure what z nor numFoodItems are doing since they are set to zero on each loop so I left them out. If you want to know how many food items you have in foodlist you can always call foodlist.size();
You can condense this loop even more, but at some point you start to lose readability so it's up to you.
Addition
Aha, that is what you are trying to do with numFoodItems. Let's change the loop you use to build values:
for (Food foodItem : foodlist) {
values.add(foodItem.getName());
}
For-Each loops like these are faster, according to Oracle, and as a bonus they are shorter to type. Now you might get more than one row in your ListView. | unknown | |
d13008 | train | Simply sum the sample values at each time point, and divide by an appropriate scaling factor to keep your values in range. For example, to play A 440 and C 523.25 at the same time:
double[] a = tone(440,1.0);
double[] b = tone(523.25,1.0);
for( int i=0; i<a.length; ++ i )
a[i] = ( a[i] + b[i] ) / 2;
StdAudio.play(a);
A: In this example, Tone opens a single SourceDataLine for each Note, but you can open as many lines as there are notes in your chord. Then simply write() each Note of the chord to a separate line. You can create an arpeggio effect by using Note.REST.
A: you could use different threads for each frequence :)
here you can find a small example of threads in java
I hope this helps you :) | unknown | |
d13009 | train | For the first question, AChartEngine tries to fit your data the best way possible. However, you can tweak this behavior:
mRenderer.setXAxisMin(min);
mRenderer.setXAxisMax(max);
mRenderer.setYAxisMin(0);
mRenderer.setYAxisMax(40);
For the second question, I think you should first investigate how to add a custom font into a regular Android application and then it may work in AChartEngine too.
A: The answer for your second question is
first download the ttf file of your required font from net,
then create a folder named "assets", under it one more folder "fonts",
put the .ttf file inside fonts folder.
then in your activity write this code:
Typeface type=Typeface.createFromAssest(getAssets(),"fonts/yourttffile.ttf");
and set where you want, say textview
textview.setTypeface(type); | unknown | |
d13010 | train | Whenever you rebuild your project, classes folder gets completely refreshed, deleting and recreating all the class files. Put your log4j.properties file inside your project/src folder. It will be copied to your classes folder on rebuild. | unknown | |
d13011 | train | This is a known issue due to transition from old sandbox to the new site. You need to delete your cookies and re-login to access the sandbox site. Please note that IE has permanent cookies stored on file system that need to be deleted. Firefox or Chrome would work better than IE8. | unknown | |
d13012 | train | Use /access_token=(.*?)&/i:
Here's a working example: http://regex101.com/r/oN6fW0
This ensures that you capture (using parentheses ()) everything after access_token=, and between the next & using a non-greedy, 0 or more of anything expression .*?. | unknown | |
d13013 | train | its working fine on Mac OSX webkit browsers - Chrome 37+ and Safari 7+, as on Firefox 30+. Please specify the browser version.
A: It seems like there is a bug in Webkit and columns have been disabled for printing by its developer (Dave Hyatt) because page breaking couldn't be implemented properly. So the WebKit implementation have CSS3 columns turned off, but Firefox renders them correctly. I’ve tried making columns work for printing in Chrome, but still getting better results from Firefox. Also there are some posts by Dave Hyatt and one of them stating that “Columns are using the new pagination model, but printing isn't using it yet.”(https://bugs.webkit.org/show_bug.cgi?id=45993)
A: I know the question was asked over a year ago, but I found this worked for me.
-webkit-perspective: 1;
See http://jsfiddle.net/mtpj8god/6/
More about it (from http://caniuse.com/#search=column-count, in known issues):
Chrome is reported to incorrectly calculate the container height, and
often breaks on margins, padding, and can display 1px of the next
column at the bottom of the previous column. Part of these issues can
be solved by adding -webkit-perspective:1; to the column container.
This creates a new stacking context for the container, and apparently
causes chrome to (re)calculate column layout. | unknown | |
d13014 | train | ---
title: '[®γσ, ENG LIAN HU](https://beta.rstudioconnect.com/content/3091/ryo-eng.html)'
subtitle: 'Personal Profile'
author: '[®γσ, Lian Hu](https://englianhu.github.io/) <img src=''www/ENG.jpg''
width=''24'' align=''center'' valign=''middle''> <img src=''www/my-passport-size-photo.jpg''
width=''24'' align=''center'' valign=''middle''>®'
date: "10/22/1984"
output:
html_document:
number_sections: yes
toc: yes
toc_depth: 4
toc_float:
collapsed: yes
smooth_scroll: yes
code_folding: hide
---
Changed yaml to below :
---
title: '[®γσ, ENG LIAN HU](https://beta.rstudioconnect.com/content/3091/ryo-eng.html)'
subtitle: 'Personal Profile'
author: '[®γσ, Lian Hu](https://englianhu.github.io/) <img src=''www/ENG.jpg''
width=''24'' align=''center'' valign=''middle''> <img src=''www/my-passport-size-photo.jpg''
width=''24'' align=''center'' valign=''middle''>®'
date: "10/22/1984"
output:
html_document:
number_sections: yes
toc: yes
toc_depth: 4
code_folding: hide
---
figure 1 shows the collapsable menu as a line
figure 2 shows the tittle content at top | unknown | |
d13015 | train | You need to use input filter and set it on Edit Text with setFilters method
A: You need to look at the reference. EditTest inherits from TextView:
http://developer.android.com/reference/android/widget/TextView.html
There you can add an TextChangedListener:
addTextChangedListener(TextWatcher watcher)
Then you test for your special characters and remove them if they are found | unknown | |
d13016 | train | Wherein the asset and asset_alt values would be combined into one column (asset)
What is a relation between asset_alt and asset?
If asset_alt is empty then use asset:
select
COALESCE(ab.asset_alt, ab.asset) AS asset, -- join assets columns in one
-- use right price column
CASE
WHEN ab.asset_alt IS NOT NULL THEN ab.price_alt
ELSE ab.price
END AS price
FROM FROM assets ab
GROUP BY
COALESCE(ab.asset_alt, ab.asset),
CASE
WHEN ab.asset_alt IS NOT NULL THEN ab.price_alt
ELSE ab.price
END | unknown | |
d13017 | train | This creates a new empty dictionary:
dict={}
dict is not a good name for a variable as it shadows the built-in type dict and could be confusing.
This makes the name file point at the values in the dictionary:
file=dict.values()
file will be empty because dict was empty.
This iterates over pairs of values in file.
for key,values in file:
As file is empty nothing will happen. However if file weren't empty, the values in it would have to be pairs of values to unpack them into key, values.
This converts dict to a string and writes it to the outfile:
outfile.write(str(dict))
Calling write with a non-str object will call str on it anway, so you could just say:
outfile.write(dict)
You don't actually do anything with infile.
A: You can use re module (regular expression) to achieve what you need. Solution could be like that. Of course you can customize to fit your need. Hope this helps.
import re
def printing(file):
outfile=open('example.txt','a')
with open(file,'r') as f:
for line in f:
new_string = re.sub('[^a-zA-Z0-9\n\.]', ' ', line)
outfile.write(new_string)
printing('output.txt') | unknown | |
d13018 | train | Check whether your phone language and Firebase console are same. Otherwise this can happen. Firebase rechecks the locale of the phone that's causing the issue. | unknown | |
d13019 | train | Compare values by -1 and use cumulative sum by Series.cumsum and if first value of Series is 0 subtract 1:
s = pd.Series([-1, 1, -1, 1, 1, -1, 1, -1, 1, -1, 1, 1,
1, 1, 1, 1, -1, 1, 1, 1])
s1 = s.eq(-1).cumsum()
out = s1.sub(1) if s[0] == -1 else s1
If always first value is -1 subtract 1:
out = s.eq(-1).cumsum().sub(1) | unknown | |
d13020 | train | First thing, we should pivot_longer to pull the four posture columns into name-value pairs. Here I've put the names into the "Posture" column. Then we can map that to color and use the values for the y axis.
I've specified the range in scale_y_continuous, but it could also be done with coord_cartesian(ylim = c(0.5,4.5)) -- the difference will be that the out of range points are filtered out in this way, but are in some sense "still there" if you use the coord_cartesian option. That can make a difference if you are doing a summary step, like geom_boxplot or geom_smooth.
Finally, I use theme to specify the y-axis related elements that should be hidden.
library(tidyverse)
graph %>%
mutate(day = lubridate::day(Date)) %>%
pivot_longer(Standing:New_Sitting, names_to = "Posture") %>%
ggplot(aes(x = Time, y = value, color = Posture))+
geom_point()+
scale_y_continuous(limits = c(0.5,4.5), expand = expansion(0)) +
facet_wrap(~day, scales = "free_x") +
labs(title = "Posture vs. Time") +
theme(axis.title.y = element_blank(),
axis.text.y = element_blank(),
axis.ticks.y = element_blank(),
panel.grid.major.y = element_blank(),
panel.grid.minor.y = element_blank())
A: Here you go:
library(tidyverse)
graph_pre_long <- graph_pre %>% pivot_longer(c(Standing, New_Sitting , Stepping, Cycling), names_to = "Posture")
ggplot(graph_pre_long, aes(x = Time, y = value, color = Posture))+
geom_point()+
facet_wrap(~day, scales = "free_x") +
ylim(.5, 4.5) +
theme(axis.title.y = element_blank(), axis.text.y = element_blank(), axis.ticks.y = element_blank()) | unknown | |
d13021 | train | Your problem might be somewhere else. Your geometry seems to be valid:
WITH values(location, userid) AS
(VALUES ('0101000000000000C04141464000000000FE174440',5),
('0101000000000000200A45464000000000D7174440',16))
SELECT ST_Distance(location::GEOMETRY,ST_GeomFromText('POINT(44 45)')) FROM values;
st_distance
------------------
4.83948955585514
4.84387473202619
(2 Zeilen)
Here a few examples on different types of geometry literals:
ST_GeomFromText
db=# SELECT ST_GeomFromText('POINT(1 2)');
st_geomfromtext
--------------------------------------------
0101000000000000000000F03F0000000000000040
(1 Zeile)
ST_GeomFromGeoJSON:
db=# SELECT ST_GeomFromGeoJSON('{"type":"Point","coordinates":[1,2]}');
st_geomfromgeojson
--------------------------------------------
0101000000000000000000F03F0000000000000040
(1 Zeile)
ST_GeomFromEWKT:
db=# SELECT ST_GeomFromEWKT('SRID=4269;POINT(1 2)');
st_geomfromewkt
----------------------------------------------------
0101000020AD100000000000000000F03F0000000000000040
(1 Zeile)
ST_GeomFromGML:
db=# SELECT ST_GeomFromGML('<gml:Point><gml:coordinates>1,2</gml:coordinates></gml:Point>');
st_geomfromgml
--------------------------------------------
0101000000000000000000F03F0000000000000040
(1 Zeile)
ST_GeomFromKML:
db=# SELECT ST_GeomFromKML('<Point><coordinates>1,2</coordinates></Point>');
st_geomfromkml
----------------------------------------------------
0101000020E6100000000000000000F03F0000000000000040
(1 Zeile)
A: This could have been your intention:
WITH vvv(location, userid) as (
VALUES (st_geomfromewkt('0101000000000000C04141464000000000FE174440'),5)
)
SELECT st_distance(p.location, v.location::geometry) AS THE_DISTANCE
FROM vvv as v
JOIN live.partners as p
ON p."partnerId" = v.userid
WHERE EXISTS (
SELECT *
FROM backend.cars c
JOIN backend."carCompatibleTariffs" cCT
ON c."carId" = cCT."carId"
AND cCT."tariffId" = 1 AND cCT.active = true
WHERE c."userId" = p."partnerId"
AND c.active = true
)
AND NOT EXISTS(
SELECT * FROM backend."userBlacklist" bl
WHERE p."partnerId" = bl."blacklistedId"
AND 5 = bl."blacklisterId"
)
; | unknown | |
d13022 | train | Enumeration doesn't throw ConcurrentModificationException , why?
Because there is no path in the code being invoked which throws this exception. Edit: I am referring to the implementation provided by the Vector class, not about the Enumeration interface in general.
Why is this such behavior . Can we say that Enumerator is thread safe.
It is thread-safe in a sense that the code executed is properly synchronized. However, I don't think the result your loop yields is what you would except.
The reason for your output is that the Enumeration object maintains a counter, which is incremented after every invokation of nextElement(). This counter is not aware of your invokation of remove().
A: the fail-fast behaviour which throws the ConcurrentModificationException is only implemented for the Iterator as you can read in
http://docs.oracle.com/javase/6/docs/api/java/util/Vector.html
A: Concurrent modification here has nothing to do with threads.
Concurrency here simply means that you are modifying the collection while you are iterating over it. (In your example this happens in the same thread.)
Iterators and enumerations of collections can throw ConcurrentModificationException in this case, but don't have to. The ones that do exhibit fail-fast behaviour. Apparently, the enumeration of Vector isn't fail-fast.
Thread-safety obviously involves multiple threads somehow. Vector is thread-safe only in the sense that its operations (like add, get, etc.) are synchronized. This is to avoid non-deterministic behaviour when one thread is adding an element while at the same time another thread is trying to remove one for example.
Now, when one thread is structurally modifying your collection while another thread is iterating over it, you have to deal with both thread-safety and concurrent modification issues. In this case, and probably in general, it is safest not to rely on ConcurrentModificationException being thrown. It is best to choose the appropriate collection implementation (a thread-safe one for example) and avoid/disallow concurrent modification yourself.
Some iterators allow adding/setting/removing elements through the iterator itself. This can be a good alternative if you really need concurrent modification.
A: Note that ConcurrentModificationException has nothing to do with concurrency in the sense of multithreading or thread safety. Some collections allow concurrent modifications, some don't. Normally you can find the answer in the docs. But concurrent doesn't mean concurrently by different threads. It means you can modify the collection while you iterate.
ConcurrentHashMap is a special case, as it is explicitly defined to be thread-safe AND editable while iterated (which I think is true for all thread-safe collections).
Anyway, as long as you're using a single thread to iterate and modify the collection, ConcurrentHashMap is the wrong solution to your problem. You are using the API wrongly. You should use Iterator.remove() to remove items. Alternatively, you can make a copy of the collection before you iterate and modify the original.
EDIT:
I don't know of any Enumeration that throws a ConcurrentModificationException. However, the behavior in case of a concurrent modification might not be what you expect it to be. As you see in you example, the enumeration skips every second element in the list. This is due to it's internal index being incremented regardless of removes. So this is what happens:
*
*en.nextElement() - returns first element from Vector, increments index to 1
*v.remove(value) - removes first element from Vector, shifts all elements left
*en.nextElement() - returns second element from Vector, which now is "Pathak"
The fail-fast behavior of Iterator protects you from this kind of things, which is why it is generally preferable to Enumberation. Instead, you should do the following:
Iterator<String> it=v.iterator();
while(it.hasNext())
{
String value=(String) it.next();
System.out.println(value);
it.remove(); // not v.remove(value); !!
}
Alternatively:
for(String value : new Vector<String>(v)) // make a copy
{
String value=(String) it.next();
System.out.println(value);
v.remove(value);
}
The first one is certainly preferable, as you don't really need the copy as long as you use the API as it is intended.
A: Short answer: It's a bonus feature that was invented after enumeration was already there, so the fact that the enumerator does not throw it does not suggest anything particular.
Long answer:
From wikipedia:
Collection implementations in pre-JDK 1.2 [...] did not contain a
collections framework. The standard methods for grouping Java
objects were via the array, the Vector, and the Hashtable classes,
which unfortunately were not easy to extend, and did not implement a
standard member interface. To address the need for reusable
collection data structures [...] The
collections framework was designed and developed primarily by Joshua
Bloch, and was introduced in JDK 1.2.
When the Bloch team did that, they thought it was a good idea to put in a new mechanism that sends out an alarm (ConcurrentModificationException) when their collections were not synchronized properly in a multi-threaded program. There are two important things to note about this mechanism: 1) it's not guaranteed to catch concurrency bugs -- the exception is only thrown if you are lucky. 2) The exception is also thrown if you misuse the collection using a single thread (as in your example).
So, a collection not throwing an ConcurrentModificationException when accessed by multiple threads does not imply it's thread-safe either.
A: It depends on how you get the Enumeration. See the following example, it does throw ConcurrentModificationException:
import java.util.*;
public class ConcurrencyTest {
public static void main(String[] args) {
Vector<String> v=new Vector<String>();
v.add("Amit");
v.add("Raj");
v.add("Pathak");
v.add("Sumit");
v.add("Aron");
v.add("Trek");
Enumeration<String> en=Collections.enumeration(v);//v.elements();
while(en.hasMoreElements())
{
String value=(String) en.nextElement();
System.out.println(value);
v.remove(value);
}
System.out.println("************************************");
Iterator<String> iter = v.iterator();
while(iter.hasNext()){
System.out.println(iter.next());
iter.remove();
System.out.println(v.size());
}
}
}
Enumeration is just an interface, it's actual behavior is implementation-dependent. The Enumeration from the Collections.enumeration() call wraps the iterator in someway, so it's indeed fail-fast, but the Enumeration obtained from calling the Vector.elements() is not.
The not-fail-fast Enumeration could introduce arbitrary, non-deterministic behavior at an undetermined time in the future. For example: if you write the main method as this, it will throw java.util.NoSuchElementException after the first iteration.
public static void main(String[] args) {
Vector<String> v=new Vector<String>();
v.add("Amit");
v.add("Raj");
v.add("Pathak");
Enumeration<String> en = v.elements(); //Collections.enumeration(v);
while(en.hasMoreElements())
{
v.remove(0);
String value=(String) en.nextElement();
System.out.println(value);
}
}
A: remove the v.remove(value) and everything will work as expected
Edit: sorry, misread the question there
This has nothing to do with threadsafety though. You're not even multithreading so there is no reason Java would throw an exception for this.
If you want exceptions when you are changing the vector make it Unmodifiable | unknown | |
d13023 | train | Ancient question but,
Consider how WedDriverWait works, in an example independent from selenium:
def is_even(n):
return n % 2 == 0
x = 10
WebDriverWait(x, 5).until(is_even)
This will wait up to 5 seconds for is_even(x) to return True
now, WebDriverWait(7, 5).until(is_even) will take 5 seconds and them raise a TimeoutException
Turns out, you can return any non Falsy value and capture it:
def return_if_even(n):
if n % 2 == 0:
return n
else:
return False
x = 10
y = WebDriverWait(x, 5).until(return_if_even)
print(y) # >> 10
Now consider how the methods of EC works:
print(By.CSS_SELECTOR) # first note this is only a string
>> 'css selector'
cond = EC.presence_of_element_located( ('css selector', 'div.some_result') )
# this is only a function(*ish), and you can call it right away:
cond(driver)
# if element is in page, returns the element, raise an exception otherwise
You probably would want to try something like:
def presence_of_any_element_located(parent, *selectors):
ecs = []
for selector in selectors:
ecs.append(
EC.presence_of_element_located( ('css selector', selector) )
)
# Execute the 'EC' functions agains 'parent'
ecs = [ec(parent) for ec in ecs]
return any(ecs)
this WOULD work if EC.presence_of_element_located returned False when selector not found in parent, but it raises an exception, an easy-to-understand workaround would be:
def element_in_parent(parent, selector):
matches = parent.find_elements_by_css_selector(selector)
if len(matches) == 0:
return False
else:
return matches
def any_element_in_parent(parent, *selectors):
for selector in selectors:
matches = element_in_parent(parent, selector)
# if there is a match, return right away
if matches:
return matches
# If list was exhausted
return False
# let's try
any_element_in_parent(driver, 'div.some_result', 'div.no_result')
# if found in driver, will return matches, else, return False
# For convenience, let's make a version wich takes a tuple containing the arguments (either one works):
cond = lambda args: any_element_in_parent(*args)
cond( (driver, 'div.some_result', 'div.no_result') )
# exactly same result as above
# At last, wait up until 5 seconds for it
WebDriverWait((driver, 'div.some_result', 'div.no_result'), 5).until(cond)
My goal was to explain, artfulrobot already gave a snippet for general use of actual EC methods, just note that
class A(object):
def __init__(...): pass
def __call__(...): pass
Is just a more flexible way to define functions (actually, a 'function-like', but that's irrelevant in this context)
A: I did it like this:
class AnyEc:
""" Use with WebDriverWait to combine expected_conditions
in an OR.
"""
def __init__(self, *args):
self.ecs = args
def __call__(self, driver):
for fn in self.ecs:
try:
res = fn(driver)
if res:
return True
# Or return res if you need the element found
except:
pass
Then call it like...
from selenium.webdriver.support import expected_conditions as EC
# ...
WebDriverWait(driver, 10).until( AnyEc(
EC.presence_of_element_located(
(By.CSS_SELECTOR, "div.some_result")),
EC.presence_of_element_located(
(By.CSS_SELECTOR, "div.no_result")) ))
Obviously it would be trivial to also implement an AllEc class likewise.
Nb. the try: block is odd. I was confused because some ECs return true/false while others will throw NoSuchElementException for False. The Exceptions are caught by WebDriverWait so my AnyEc thing was producing odd results because the first one to throw an exception meant AnyEc didn't proceed to the next test.
A: Not exactly through EC, but does achieve the same result - with a bonus.
Still using WebDriverWait's until() method, but passing the pure find_elements_*() methods inside a lambda expression:
WebDriverWait(driver, 10).until(lambda driver: driver.find_elements_by_id("id1") or \
driver.find_elements_by_css_selector("#id2"))[0]
The find_elements_*() methods return a list of all matched elements, or an empty one if there aren't such - which is a a boolean false. Thus if the first call doesn't find anything, the second is evaluated; that repeats until either of them finds a match, or the time runs out.
The bonus - as they return values, the index [0] at the end will actually return you the matched element - if you have any use for it, in the follow-up calls.
A: I did this and it worked fine for me:
WebDriverWait(driver, 10).until( EC.presence_of_element_located(By.XPATH, "//div[some_result] | //div[no_result]")); | unknown | |
d13024 | train | Just ran into the same issue here is the code I used to solve.
$url = 'http://graph.facebook.com/' . $userInfo['id'] . '/picture?type=large';
$headers = get_headers($url, 1); // make link request and wait for redirection
if(isset($headers['Location'])) {
$url = $headers['Location']; // this gets the new url
} else {
$url = false;
}
$targetPath = $_SERVER['DOCUMENT_ROOT'] . "/yourImagePath/");
$destFile = "yourFileName.jpg"
if($url){
if (copy($url, $targetPath.$destFile)) {
// file is now copied to your server do what ever you want here
}
} | unknown | |
d13025 | train | Inside your controller, have
$data['nestedView']['otherData'] = 'testing';
before your view includes.
When you call
$this->load->view('view_destinations',$data);
the view_destinations file is going to have
$nestedView['otherData'];
Which you can at that point, pass into the nested view file.
A: From what you explain, I understand that you want to pass some data from a controller to another (since your URL's are different).
To do this, you can:
*
*Pass the data through query strings (GET) as explained above or
*Set a flash data variable in the first controller, and use it in the second. I would advise to use this solution, as that's why flash data exists.
A: You can use $this->uri->segment() of Codeigniter like below.
$this->uri->segment(1); // controller
$this->uri->segment(2); // action
$this->uri->segment(3); // 1stsegment
$this->uri->segment(4); // 2ndsegment
You can pass the variables values via url and get on the controller. and so on. | unknown | |
d13026 | train | Try eliminating the GROUP BY constraint. Then see where your duplicate rows are coming from, and fix your original query. This will fix your COUNTs as well.
A: Try either:
COUNT(DISTINCT comments.codeid) AS commentcount
or
(SELECT COUNT(*) FROM comments WHERE comments.codeid = code.id) AS commentcount
A: Try starting with a simple query, and building up from that. If I have understood your structure correctly, the following query will return the correct number of comments for each code submission:
SELECT code.*, COUNT(code.id) AS comment_count
FROM code
JOIN comments ON comments.codeid = code.id
GROUP BY(code.id);
There's a few odd looking column names and joins in your example, which may be contributing to the problem
or it might just be an odd naming scheme :-)
For example, you are joining ratingItems to code by comparing code.id with ratingItems.uniqueName. That might be correct, but it doesn't quite look right. Perhaps it should be more like:
LEFT JOIN ratingItems ON ratingItems.code_id = code.id
Start with a basic working query, then add the other joins. | unknown | |
d13027 | train | GeertG... now im emotionally involved :) try the link i found... it might do the trick as far as using a scrollview with more than a single child...I dont know if it solves your issue but...
If ScrollView only supports one direct child, how am I supposed to make a whole layout scrollable?
or
how to add multiple child in horizontal scroll view in android
Those solutions should work as creating a scrollview with more than 1 child... will it solve your problem? IDK...
also look in to
How to hide soft keyboard on android after clicking outside EditText?
but having the keyboard closed and re-opened seems kinda reasonable to me... dont linger on it for too long:)
A: The guidelines for what you are asking are can be found here. As you can see. there are a number of ways to achieve what you are asking.
Further to this, you could consider changing default action of the 'Enter' button on the keyboard to select the next EditText and finally to submit the form when you are done (read up about it here):
android:imeOptions="actionDone"
A: Use LinearLayout Height match_parent. And try if its working or not.
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:orientation="vertical"
android:scrollbars="vertical"
android:scrollbarAlwaysDrawVerticalTrack="true"> | unknown | |
d13028 | train | if [[ $line2 == `E*` ]];then
This definitely is not legal GNU AWK if statement, consult If Statement to find what is allowed, though it is not required in this case as you might as follows, let file.txt content be
E2dd,Rv0761,Rv1408
2s32,Rv0761,Rv1862,Rv3086
6r87,Rv0761
Rv2fd90c,Rv1408
Esf62,Rv0761
Evsf62,Rv3086
then
awk 'BEGIN{FS=","}($1~/^E/){map[$2]++} END { for (key in map) { print key, map[key] } }' file.txt
gives output
Rv3086 1
Rv0761 2
Explanation: actions (enclosed in {...}) could be preceeded by pattern, which does restrict their execution to lines which does match pattern (in other words: condition does hold) in above example pattern is $1~/^E/ which means 1st column does starts with E.
(tested in gawk 4.2.1)
A: You are so close. You are only missing the REGEX to identify records beginning with 'E' and then a ":" concatenated on output to produce your desired results (not in sort-order). For example you can do:
awk -F, '/^E/{map[$2]++} END { for (key in map) { print key ":", map[key] } }' file.txt
Example Output
With your data in file.txt you would get:
Rv3086: 1
Rv0761: 2
If you need the output sorted in some way, just pipe the output of the awk command to sort with whatever option you need. | unknown | |
d13029 | train | You can clone table to some popup and show it:
HTML
<table>
<tr id="sub-155642" style="display: none">
<td colspan="5">
<div id="sub-155642" style="display:none;">
<table width="100%">
<tr>
<td class="inner-table"></td>
<td class="inner-table">Document No</td>
<td class="inner-table">Document Type</td>
<td class="inner-table" id="amount-row">Total Amount</td>
</tr>
</table>
</div>
</td>
</tr>
</table>
<button onclick="popup()">Pop-up</button>
JavaScript
var popupEl;
function popup() {
var divEl,
tableEl,
xEl;
if(!popupEl) {
// Find table
tableEl = document.querySelector('#sub-155642 > table');
divEl = tableEl.parentNode;
// Create popup and clone table to it
popupEl = document.createElement('div');
popupEl.innerHTML = divEl.innerHTML;
popupEl.setAttribute('style', 'position:fixed;top:50%;left:50%;width:300px;height:100px;margin-left:-150px;margin-top:-50px;border:1px solid gray');
// Show popup
document.querySelector('body').appendChild(popupEl);
} else {
document.querySelector('body').removeChild(popupEl);
popupEl = null;
}
}
JSBin: http://jsbin.com/OyeXiNu/1/edit
otherwise you can make wrapping tables visible (but be sure IDs are unique):
JavaScript
var div = document.getElementById('sub-155642');
div.style.display = 'block';
div.parentNode.parentNode.style.display = 'table-row'; | unknown | |
d13030 | train | You have a break statement at the end of your for loop that probably shouldn't be there. Just delete that one.
else
printf("\nStudent not found. Please try again.\n");
break;
} ^
|
+------ this one
That printf is a bit inaccurate too; it will get printed out on every iteration of the loop where you didn't happen to find a matching ID.
A: Your scanf() statement has an incorrect format string. You don't need to add the trailing newline; scanf takes care of it. Change that line to scanf("%d", &id4); (no newline) and it should work.
I just wrote a small stub program that compares scanf with and without the newline, and it replicates your error.
A: This loop:
for (int c = k; c < *count; c++)
should probably instead be:
for (int c = k; c < *count - 1; c++)
As written, it reads one past the end of the valid array. The results are undefined. And in particular, the strcpy calls may go quite badly. When it gets to the last entry in that loop, list[c+1] refers to an entry that does not exist (based on *count).
A: Your scanf hangs as it never gets to read your number. No \n needed. Use %d only. | unknown | |
d13031 | train | Yes, you can put the whole email into a "text" or "string" column in the database.
Even better, many databases support text search functionality. So you could build a text index and be able to search through the email body efficiently.
The downside is that the rows are bigger, which can slow down using the table. If the emails are repeated, then you probably want a separate table for the emails, with an id representing the text. Another table would show which users received which email. | unknown | |
d13032 | train | Try this:
js <- c(
"function(xlsx) {",
" var table = $('#daypartTable').find('table').DataTable();",
" // Letters for Excel columns.",
" var LETTERS = [",
" 'A','B','C','D','E','F','G','H','I','J','K','L','M',",
" 'N','O','P','Q','R','S','T','U','V','W','X','Y','Z'",
" ];",
" // Get sheet.",
" var sheet = xlsx.xl.worksheets['sheet1.xml'];",
" // Get a clone of the sheet data. ",
" var sheetData = $('sheetData', sheet).clone();",
" // Clear the current sheet data for appending rows.",
" $('sheetData', sheet).empty();",
" // Row count in Excel sheet.",
" var rowCount = 1;",
" // Iterate each row in the sheet data.",
" $(sheetData).children().each(function (index) {",
" // Used for DT row() API to get child data.",
" var rowIndex = index - 2;", #
" // Don't process row if its the header row.",
sprintf(" if (index > 1 && index < %d) {", nrow(Dat)+2), #
" // Get row",
" var row = $(this.outerHTML);",
" // Set the Excel row attr to the current Excel row count.",
" row.attr('r', rowCount);",
" // Iterate each cell in the row to change the row number.",
" row.children().each(function (index) {",
" var cell = $(this);",
" // Set each cell's row value.",
" var rc = cell.attr('r');",
" rc = rc.replace(/\\d+$/, \"\") + rowCount;",
" cell.attr('r', rc);",
" });",
" // Get the row HTML and append to sheetData.",
" row = row[0].outerHTML;",
" $('sheetData', sheet).append(row);",
" rowCount++;",
" // Get the child data - could be any data attached to the row.",
sprintf(" var childData = table.row(':eq(' + rowIndex + ')').data()[%d];", ncol(Dat)-1), #
" if (childData.length > 0) {",
" var colNames = Object.keys(childData[0]);",
" // Prepare Excel formatted row",
" headerRow = '<row r=\"' + rowCount +",
" '\"><c t=\"inlineStr\" r=\"A' + rowCount +",
" '\"><is><t></t></is></c>';",
" for(var i = 0; i < colNames.length; i++){",
" headerRow = headerRow +",
" '<c t=\"inlineStr\" r=\"' + LETTERS[i+1] + rowCount +",
" '\" s=\"7\"><is><t>' + colNames[i] +",
" '</t></is></c>';",
" }",
" headerRow = headerRow + '</row>';",
" // Append header row to sheetData.",
" $('sheetData', sheet).append(headerRow);",
" rowCount++; // Inc excelt row counter.",
" }",
" // The child data is an array of rows",
" for (c = 0; c < childData.length; c++) {",
" // Get row data.",
" child = childData[c];",
" // Prepare Excel formatted row",
" var colNames = Object.keys(child);",
" childRow = '<row r=\"' + rowCount +",
" '\"><c t=\"inlineStr\" r=\"A' + rowCount +",
" '\"><is><t></t></is></c>';",
" for(var i = 0; i < colNames.length; i++){",
" childRow = childRow +",
" '<c t=\"inlineStr\" r=\"' + LETTERS[i+1] + rowCount +",
" '\" s=\"5\"><is><t>' + child[colNames[i]] +",
" '</t></is></c>';",
" }",
" childRow = childRow + '</row>';",
" // Append row to sheetData.",
" $('sheetData', sheet).append(childRow);",
" rowCount++; // Inc excel row counter.",
" }",
" // Just append the header row and increment the excel row counter.",
" } else {",
" $('sheetData', sheet).append(this.outerHTML);",
" rowCount++;",
" }",
" });",
"}"
)
datatable(
Dat, callback = callback, rownames = rowNames, escape = -colIdx-1,
extensions = "Buttons",
options = list(
dom = "Bfrtip",
columnDefs = list(
list(visible = FALSE, targets = ncol(Dat)-1+colIdx),
list(orderable = FALSE, className = 'details-control', targets = colIdx),
list(className = "dt-center", targets = "_all")
),
buttons = list(
list(
extend = "excel",
exportOptions = list(
orthogonal = "export",
columns = 0:(ncol(Dat)-2)
),
orientation = "landscape",
customize = JS(js)
)
)
)
)
Here is an example of the generated Excel file:
EDIT
Better:
excelTitle <- NULL # set to NULL if you don't want a title
js <- c(
"function(xlsx) {",
" var table = $('#daypartTable').find('table').DataTable();",
" // Number of columns.",
" var ncols = table.columns().count();",
" // Is there a title?",
sprintf(" var title = %s;", ifelse(is.null(excelTitle), "false", "true")),
" // Integer to Excel column: 0 -> A, 1 -> B, ..., 25 -> Z, 26 -> AA, ...",
" var XLcolumn = function(j){", # https://codegolf.stackexchange.com/a/163919
" return j < 0 ? '' : XLcolumn(j/26-1) + String.fromCharCode(j % 26 + 65);",
" };",
" // Get sheet.",
" var sheet = xlsx.xl.worksheets['sheet1.xml'];",
" // Get a clone of the sheet data. ",
" var sheetData = $('sheetData', sheet).clone();",
" // Clear the current sheet data for appending rows.",
" $('sheetData', sheet).empty();",
" // Row count in Excel sheet.",
" var rowCount = 1;",
" // Iterate each row in the sheet data.",
" $(sheetData).children().each(function (index) {",
" // Used for DT row() API to get child data.",
" var rowIndex = title ? index - 2 : index - 1;",
" // Don't process row if it's the title row or the header row.",
" var i0 = title ? 1 : 0;",
" if (index > i0) {",
" // Get row",
" var row = $(this.outerHTML);",
" // Set the Excel row attr to the current Excel row count.",
" row.attr('r', rowCount);",
" // Iterate each cell in the row to change the row number.",
" row.children().each(function (index) {",
" var cell = $(this);",
" // Set each cell's row value.",
" var rc = cell.attr('r');",
" rc = rc.replace(/\\d+$/, \"\") + rowCount;",
" cell.attr('r', rc);",
" });",
" // Get the row HTML and append to sheetData.",
" row = row[0].outerHTML;",
" $('sheetData', sheet).append(row);",
" rowCount++;",
" // Get the child data - could be any data attached to the row.",
" var childData = table.row(':eq(' + rowIndex + ')').data()[ncols-1];",
" if (childData.length > 0) {",
" var colNames = Object.keys(childData[0]);",
" // Prepare Excel formatted row",
" var headerRow = '<row r=\"' + rowCount +",
" '\"><c t=\"inlineStr\" r=\"A' + rowCount +",
" '\"><is><t></t></is></c>';",
" for(let i = 0; i < colNames.length; i++){",
" headerRow = headerRow +",
" '<c t=\"inlineStr\" r=\"' + XLcolumn(i+1) + rowCount +",
" '\" s=\"7\"><is><t>' + colNames[i] +",
" '</t></is></c>';",
" }",
" headerRow = headerRow + '</row>';",
" // Append header row to sheetData.",
" $('sheetData', sheet).append(headerRow);",
" rowCount++; // Inc excel row counter.",
" }",
" // The child data is an array of rows",
" for(let c = 0; c < childData.length; c++){",
" // Get row data.",
" var child = childData[c];",
" // Prepare Excel formatted row",
" var childRow = '<row r=\"' + rowCount +",
" '\"><c t=\"inlineStr\" r=\"A' + rowCount +",
" '\"><is><t></t></is></c>';",
" var i = 0;",
" for(let colname in child){",
" childRow = childRow +",
" '<c t=\"inlineStr\" r=\"' + XLcolumn(i+1) + rowCount +",
" '\" s=\"5\"><is><t>' + child[colname] +",
" '</t></is></c>';",
" i++;",
" }",
" childRow = childRow + '</row>';",
" // Append row to sheetData.",
" $('sheetData', sheet).append(childRow);",
" rowCount++; // Inc excel row counter.",
" }",
" // Just append the header row and increment the excel row counter.",
" } else {",
" $('sheetData', sheet).append(this.outerHTML);",
" rowCount++;",
" }",
" });",
"}"
)
datatable(
Dat, callback = callback, rownames = rowNames, escape = -colIdx-1,
extensions = "Buttons",
options = list(
dom = "Bfrtip",
columnDefs = list(
list(visible = FALSE, targets = ncol(Dat)-1+colIdx),
list(orderable = FALSE, className = 'details-control', targets = colIdx),
list(className = "dt-center", targets = "_all")
),
buttons = list(
list(
extend = "excel",
exportOptions = list(
orthogonal = "export",
columns = 0:(ncol(Dat)-2)
),
title = excelTitle,
orientation = "landscape",
customize = JS(js)
)
)
)
)
EDIT 2
In callback_js, replace
" var dataset = [];",
" var n = d.length - 1;",
" for(var i = 0; i < d[n].length; i++){",
" var datarow = $.map(d[n][i], function (value, index) {",
" return [value];",
" });",
" dataset.push(datarow);",
" }",
" var id = 'table#' + childId;",
" if (Object.keys(d[n][0]).indexOf('_details') === -1) {",
" var subtable = $(id).DataTable({",
" 'data': dataset,",
" 'autoWidth': true,",
" 'deferRender': true,",
" 'info': false,",
" 'lengthChange': false,",
" 'ordering': d[n].length > 1,",
" 'order': [],",
" 'paging': true,",
" 'scrollX': false,",
" 'scrollY': false,",
" 'searching': false,",
" 'sortClasses': false,",
" 'pageLength': 50,",
" 'rowCallback': rowCallback,",
" 'headerCallback': headerCallback,",
" 'footerCallback': footerCallback,",
" 'columnDefs': [",
" {targets: [0, 9, 10, 11], visible: false},",
" {targets: '_all', className: 'dt-center'}",
" ]",
" });",
" } else {",
" var subtable = $(id).DataTable({",
" 'data': dataset,",
" 'autoWidth': true,",
" 'deferRender': true,",
" 'info': false,",
" 'lengthChange': false,",
" 'ordering': d[n].length > 1,",
" 'order': [],",
" 'paging': true,",
" 'scrollX': false,",
" 'scrollY': false,",
" 'searching': false,",
" 'sortClasses': false,",
" 'pageLength': 50,",
" 'rowCallback': rowCallback,",
" 'headerCallback': headerCallback,",
" 'footerCallback': footerCallback,",
" 'columnDefs': [",
" {targets: [0, 9, 10, 11], visible: false},",
" {targets: -1, visible: false},",
" {targets: 0, orderable: false, className: 'details-control'},",
" {targets: '_all', className: 'dt-center'}",
" ]",
" }).column(0).nodes().to$().css({cursor: 'pointer'});",
" }",
with
" var n = d.length - 1;",
" var id = 'table#' + childId;",
" var columns = Object.keys(d[n][0]).map(function(x){",
" return {data: x, title: x};",
" });",
" if (Object.keys(d[n][0]).indexOf('_details') === -1) {",
" var subtable = $(id).DataTable({",
" 'data': d[n],",
" 'columns': columns,",
" 'autoWidth': true,",
" 'deferRender': true,",
" 'info': false,",
" 'lengthChange': false,",
" 'ordering': d[n].length > 1,",
" 'order': [],",
" 'paging': true,",
" 'scrollX': false,",
" 'scrollY': false,",
" 'searching': false,",
" 'sortClasses': false,",
" 'pageLength': 50,",
" 'rowCallback': rowCallback,",
" 'headerCallback': headerCallback,",
" 'footerCallback': footerCallback,",
" 'columnDefs': [",
" {targets: [0, 9, 10, 11], visible: false},",
" {targets: '_all', className: 'dt-center'}",
" ]",
" });",
" } else {",
" var subtable = $(id).DataTable({",
" 'data': d[n],",
" 'columns': columns,",
" 'autoWidth': true,",
" 'deferRender': true,",
" 'info': false,",
" 'lengthChange': false,",
" 'ordering': d[n].length > 1,",
" 'order': [],",
" 'paging': true,",
" 'scrollX': false,",
" 'scrollY': false,",
" 'searching': false,",
" 'sortClasses': false,",
" 'pageLength': 50,",
" 'rowCallback': rowCallback,",
" 'headerCallback': headerCallback,",
" 'footerCallback': footerCallback,",
" 'columnDefs': [",
" {targets: [0, 9, 10, 11], visible: false},",
" {targets: -1, visible: false},",
" {targets: 0, orderable: false, className: 'details-control'},",
" {targets: '_all', className: 'dt-center'}",
" ]",
" }).column(0).nodes().to$().css({cursor: 'pointer'});",
" }",
Moreover, you probably don't want the hidden columns in the Excel file. So replace this code:
" if (childData.length > 0) {",
" var colNames = Object.keys(childData[0]);",
" // Prepare Excel formatted row",
......
" // Append row to sheetData.",
" $('sheetData', sheet).append(childRow);",
" rowCount++; // Inc excel row counter.",
" }",
with
" if (childData.length > 0) {",
" var colNames = Object.keys(childData[0]).slice(1,9);",
" // Prepare Excel formatted row",
" var headerRow = '<row r=\"' + rowCount +",
" '\"><c t=\"inlineStr\" r=\"A' + rowCount +",
" '\"><is><t></t></is></c>';",
" for(let i = 0; i < colNames.length; i++){",
" headerRow = headerRow +",
" '<c t=\"inlineStr\" r=\"' + XLcolumn(i+1) + rowCount +",
" '\" s=\"7\"><is><t>' + colNames[i] +",
" '</t></is></c>';",
" }",
" headerRow = headerRow + '</row>';",
" // Append header row to sheetData.",
" $('sheetData', sheet).append(headerRow);",
" rowCount++; // Inc excel row counter.",
" }",
" // The child data is an array of rows",
" for(let c = 0; c < childData.length; c++){",
" // Get row data.",
" var child = childData[c];",
" // Prepare Excel formatted row",
" var childRow = '<row r=\"' + rowCount +",
" '\"><c t=\"inlineStr\" r=\"A' + rowCount +",
" '\"><is><t></t></is></c>';",
" for(let i = 0; i < colNames.length; i++){",
" childRow = childRow +",
" '<c t=\"inlineStr\" r=\"' + XLcolumn(i+1) + rowCount +",
" '\" s=\"5\"><is><t>' + child[colNames[i]] +",
" '</t></is></c>';",
" }",
" childRow = childRow + '</row>';",
" // Append row to sheetData.",
" $('sheetData', sheet).append(childRow);",
" rowCount++; // Inc excel row counter.",
" }",
EDIT 3
This doesn't work if there are some periods in the column names of a child table. Here is the fix:
" var columns = Object.keys(d[n][0]).map(function(x){",
" return {data: x.replace('.', '\\\\\\.'), title: x};",
" });", | unknown | |
d13033 | train | I tried to reproduce the same issue in my environment and got the below results
For installing the terraform in visual studio refer this link
We have to install the developer cli use this link to download and install
I have installed the visual studio code and install the terraform
Please find the versions which I have used
I have created terraform file
vi main.tf
terraform {
required_providers {
azurerm = {
source = "hashicorp/azurerm"
version = "3.28.0"
}
}
}
provider "azurerm" {
features {}
}
resource "azurerm_resource_group" "example23" {
name = "example-resourcegroup23"
location = "eastus"
}
I have followed some commands to run the file
Terraform init
terraform plan
terraform apply
When I open the portal I am able to see newly created resource group
Note:
1).In order to use the azure CLI, terraform should be able to do the azure cli authentication for that we have to add the token.
2).Both terraform and Azure cli should be on same path
az account get-access-token { "accessToken": token_id", "expiresOn": <Date_with_time>, "subscription": "subscription_id", "tenant": "", "tokenType": "token_type" }***
3). you can also refer this link here for know abt the issue | unknown | |
d13034 | train | You have itext7 samples here:
http://gitlab.itextsupport.com/itext7/samples/tree/develop
This is a sample about signature with appearance:
http://gitlab.itextsupport.com/itext7/samples/blob/develop/publications/signatures/src/test/java/com/itextpdf/samples/signatures/chapter03/C3_01_SignWithCAcert.java | unknown | |
d13035 | train | It looks like whenever if (last) condition is true and it's the same element as this, you're toggling show class twice on same element, so probably this is why it remains open (actually it closes and opens again at the same time).
So try to check if you're not toggling same element like this:
if (last && last != this) {
last.nextElementSibling.classList.toggle("show");
}
this.nextElementSibling.classList.toggle("show");
And I hope it helps. | unknown | |
d13036 | train | *
*Add @Component over Class of StratusAuthenticationEntryPoint that a bean created by spring ioc
*verify if the ComponentScan path contains Class of StratusAuthenticationEntryPoint | unknown | |
d13037 | train | Unity 2.0 and documentation is available as a separate download as of today.
http://msdn.microsoft.com/unity
http://blogs.msdn.com/agile/archive/2010/04/20/microsoft-enterprise-library-5-0-released.aspx
Unfortunately the limited support for the Unity configuration in the Configuration Tool that you may have seen in one of the EntLib 5.0 betas didn't make it into the final release due to time constraints.
However, we have made the Unity configuration XML significantly easier to author with things like assembly and namespace aliasing to save having to repeatedly specify fully qualified types.
A: We have released Unity 2.0 standalone, Unity 2.0 for Silverlight as well as Enterprise Library 5.0 full documentation set today.
A: Unity 2 is not yet finalized (still in Beta 2). I guess we have to wait.
Besides, Unity 2 config file is much easier to be typed manually, compared to the 1.x versions.
A: If interested in Unity config tool, which was part of the beta but didn't make it to the final EntLib5.0 release, you can find it here | unknown | |
d13038 | train | You cannot inline a window procedure. This is by design.
You can easily see the architectural limitation when registering a window class. This is done by calling RegisterClassExW, passing along a WNDCLASSEXW structure. That structure requires a valid lpfnWndProc. You cannot take the address of an inlined function.
There are other aspects that require the window procedure to be an actual function. For example, the stored window procedure address serves as a customization point and allows subclassing controls, e.g. to tweak the behavior of a standard control.
There's nothing you can do to avoid the function call. If you want to limit the scope of variables, you can assign the result of a lambda expression to the lpfnWndProc member. Visual Studio makes sure to synthesize the correct function signature. | unknown | |
d13039 | train | CAUSE
Your table is hidden initially which prevents jQuery DataTables from initializing the table correctly.
SOLUTION
Use the code below to recalculate column widths of all visible tables once modal becomes visible by using a combination of columns.adjust() and responsive.recalc() API methods.
$('#modal').on('shown.bs.modal', function(e){
$($.fn.dataTable.tables(true)).DataTable()
.columns.adjust()
.responsive.recalc();
});
You can also adjust single table by using table ID, for example:
$('#modal').on('shown.bs.modal', function(e){
$('#example').DataTable()
.columns.adjust()
.responsive.recalc();
});
LINKS
*
*jQuery DataTables: Column width issues with Bootstrap tabs - Responsive extension – Incorrect breakpoints.
*Datatable jquery - table header width not aligned with body width
A: Try to wrap the table inside a divand then give it the attribute overflow:auto; | unknown | |
d13040 | train | What you want to do is create a "service account". Then you want create a new calendar for your (not the service account) calendar. Next, you share your new calendar with the service account by adding it under the "Share with specific people" section. Take note of the "Calendar ID" for this new calendar.
Now when you use the api you should add events from your service account to the new calendar by passing the calendar id as the calendarId. | unknown | |
d13041 | train | Instead of hitting first curl use get_headers($url).
add Content-Type:application/json in header.
add $request_header[] = 'Content-Type:application/json'; this line after $request_header = array($request).
A: Thanks @Sufi, Working code for POST request (In case someone else needs this):
<?php
$username = 'username';
$password = 'password';
$url = "your url";
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch,CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch,CURLOPT_FOLLOWLOCATION, false);
curl_setopt($ch,CURLOPT_TIMEOUT, 30);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch,CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_HEADER, 1);
$first_response = curl_exec($ch);
$info = curl_getinfo($ch);
preg_match('/WWW-Authenticate: Digest (.*)/', $first_response, $matches);
if(!empty($matches))
{
$auth_header = $matches[1];
$auth_header_array = explode(',', $auth_header);
$parsed = array();
foreach ($auth_header_array as $pair)
{
$vals = explode('=', $pair);
$parsed[trim($vals[0])] = trim($vals[1], '" ');
}
$response_realm = (isset($parsed['realm'])) ? $parsed['realm'] : "";
$response_nonce = (isset($parsed['nonce'])) ? $parsed['nonce'] : "";
$response_opaque = (isset($parsed['opaque'])) ? $parsed['opaque'] : "";
$authenticate1 = md5($username.":".$response_realm.":".$password);
$authenticate2 = md5("POST:".$url);
$authenticate_response = md5($authenticate1.":".$response_nonce.":".$authenticate2);
$request = sprintf('Authorization: Digest username="%s", realm="%s", nonce="%s", opaque="%s", uri="%s", response="%s"',
$username, $response_realm, $response_nonce, $response_opaque, $url, $authenticate_response);
$request_header = array($request);
$request_header[] = 'Content-Type:application/json';
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch,CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch,CURLOPT_FOLLOWLOCATION, false);
curl_setopt($ch,CURLOPT_TIMEOUT, 30);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch,CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_HTTPHEADER, $request_header);
$result['response'] = curl_exec($ch);
$result['info'] = curl_getinfo ($ch);
$result['info']['errno'] = curl_errno($ch);
$result['info']['errmsg'] = curl_error($ch);
var_dump($result);
}
?> | unknown | |
d13042 | train | Your animations completion handler is NULL, which means nothing is happened after animation is completed.
And it's strange to use animations block if you actually animate nothing. Animations won't wait 4 seconds before calling competition handler if there is nothing to animate.
__block int i = 9;
void(^process)(void(^recursive)());
process = ^(void(^recursive)()) {
--i;
[UIView animateWithDuration:4.0
animations:^{
NSLog(@"%d", i);
}
completion:^(BOOL finished) {
recursive(recursive);
}];
};
process(process); | unknown | |
d13043 | train | I believe the green circle you're referring to is actually a green bug icon. That indicates that the procedure has been compiled for debug.
If you are editing a stored procedure in SQL Developer, there should be a gear icon at the top of the edit screen that you use to compile the procedure. If you click the arrow to expand that, you should get options to compile the procedure or to compile for debug. If you select "Compile for Debug", you'll get the green bug icon. If you select "Compile", the bug icon will go away. | unknown | |
d13044 | train | You also need to add '-nostdlib' or it will drag in files that have been compiled with Armv5. The 'arm-linux' kernel does not support ARMv4 CPUs as they do not have an MMU. You are viewing assembler from the gcc library which is compiled for Armv5.
The example label divsi3, shows that you are using division operation and this is coded in libgcc, which will link with the code. It is brought in by your % m code.
You can code and supply your own divsi3, or get a compiler library that supports Armv4. The libgcc.a must be generated (downgraded) to support that CPU. Gcc's backend is capable of generating code for all members of the ARM32/Thumb family, but not support libraries (without multi-lib support).
There is no bug in the compiler. If you look at the assembler for _start, it will not contain clz. If the % 7 could be % 8, you can downgrade to a &7 and the divsi3 would not be needed.
You can see why here.
It is a variation on this question. The issue is that the linker 'gnu ld' has no flag to say, reject Armv5 code.
*
*Provide divsi3 configured with Armv4.
*Provide your own divsi3 with a Division algorithm.
*Avoid the functionality (down grade to &). | unknown | |
d13045 | train | I just needed to add in the .h file
@property (nonatomic, retain) MKPolyline *routeLine1; //ORGINAL LINE
@property (nonatomic, retain) MKPolylineView *routeLineView1; //ORGINAL LINE
@property (nonatomic, retain) MKPolyline *routeLine2; //ADDED LINE
@property (nonatomic, retain) MKPolylineView *routeLineView2; //ADDED LINE
This in the .m
-(MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id <MKOverlay>)overlay
{
if(overlay == self.routeLine1)
{
if(nil == self.routeLineView1)
{
self.routeLineView1 = [[MKPolylineView alloc] initWithPolyline:self.routeLine1];
self.routeLineView1.fillColor = [UIColor greenColor];
self.routeLineView1.strokeColor = [UIColor greenColor];
self.routeLineView1.lineWidth = 5;
}
return self.routeLineView1;
}
if(overlay == self.routeLine2)
{
if(nil == self.routeLineView2)
{
self.routeLineView2 = [[MKPolylineView alloc] initWithPolyline:self.routeLine2];
self.routeLineView2.fillColor = [UIColor orangeColor];
self.routeLineView2.strokeColor = [UIColor orangeColor];
self.routeLineView2.lineWidth = 5;
}
return self.routeLineView2;
}
return nil;
} | unknown | |
d13046 | train | A Worksheet Change: Date Stamp To Multiple Columns
Sheet Module e.g. Sheet1
Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
AddDateStamp Target, "Route_1_Table", 7, 8, 3, 3, _
Array(11, "Pending Baseline"), Array(12, "Good")
End Sub
Standard Module e.g. Module1
Option Explicit
Sub AddDateStamp( _
ByVal Target As Range, _
ByVal TargetTableName As String, _
ByVal TargetColumn As Long, _
ByVal DateColumn As Long, _
ByVal TopRowsSkipped As Long, _
ByVal BottomRowsSkipped As Long, _
ParamArray DateColumnCriteriaPairs() As Variant)
On Error GoTo ClearError ' start error-handling routine
Dim tws As Worksheet: Set tws = Target.Worksheet
Dim trg As Range: Set trg = tws.ListObjects(TargetTableName).DataBodyRange
' Exclude top and bottom rows.
Set trg = trg.Resize(trg.Rows.Count - TopRowsSkipped - BottomRowsSkipped) _
.Offset(TopRowsSkipped)
' Reference the intersecting cells.
Dim irg As Range: Set irg = Intersect(trg.Columns(TargetColumn), Target)
If irg Is Nothing Then Exit Sub ' no intersection
Dim AnyDcPairs As Boolean
AnyDcPairs = Not IsMissing(DateColumnCriteriaPairs)
Dim dcIndex As Long, ccIndex As Long ' Date Column Index
If AnyDcPairs Then
dcIndex _
= LBound(DateColumnCriteriaPairs(LBound(DateColumnCriteriaPairs)))
ccIndex _
= UBound(DateColumnCriteriaPairs(LBound(DateColumnCriteriaPairs)))
End If
Dim urg As Range, iCell As Range, dcPair, iString As String
For Each iCell In irg.Cells
Set urg = RefCombinedRange( _
urg, iCell.Offset(, DateColumn - TargetColumn))
iString = CStr(iCell.Value)
If AnyDcPairs Then
For Each dcPair In DateColumnCriteriaPairs
If StrComp(iString, dcPair(ccIndex), vbTextCompare) = 0 Then
Set urg = RefCombinedRange( _
urg, iCell.Offset(, dcPair(dcIndex) - TargetColumn))
Exit For ' match found, stop looping
End If
Next dcPair
End If
Next iCell
Application.EnableEvents = False
urg.Value = Date
ProcExit: ' Exit Routine
On Error Resume Next ' prevent endless loop if error in the following lines
If Not Application.EnableEvents Then Application.EnableEvents = True
On Error GoTo 0
Exit Sub ' don't forget!
ClearError: ' continue error-handling routine
Debug.Print "Run-time error '" & Err.Number & "':" & vbLf & Err.Description
Resume ProcExit ' redirect to exit routine
End Sub
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Purpose: References a range combined from two ranges.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Function RefCombinedRange( _
ByVal urg As Range, _
ByVal arg As Range) _
As Range
If urg Is Nothing Then Set urg = arg Else Set urg = Union(urg, arg)
Set RefCombinedRange = urg
End Function | unknown | |
d13047 | train | Instead of
While WebsiteIW.Contains(" ")
WebsiteIW = WebsiteIW.Replace(" ", "")
End While
Use
WebsiteIW = WebsiteIW.trim
It's a lot faster, and will get rid of an stray newline characters. | unknown | |
d13048 | train | ForegroundService is better option you have, as of today, there are many Custom ROMs which kills application which is in the background.
I have used foregroundService for the same purpose and it is working perfectly. | unknown | |
d13049 | train | Well, after noting that an ideal way to do this would be to ignore that procedure, I did find how to ignore the procedure by name in the generally excellent jOOQ website documentation. Don't know how I missed in on first pass. If I needed to call this procedure in Java, I'm unclear which of the above options I would have used.
Luckily, there was no need for this procedure to be referenced in code, and I excluded it as shown below in in the jOOQ XML configuration.
<excludes>
databasechangelog.*
| maintain_edit_time
</excludes>
A: You've already found the perfect solution, which you documented in your own answer. I'll answer your various other questions here, for completeness' sake
Using ignoreProcedureReturnValues globally effects the project just because of this, which is fine for now, I don't have other procedures at all, much less others with a return value. But, I hate to limit future use. Also, I'm unclear one what the comment "This feature is deprecated as of jOOQ 3.6.0 and will be removed again in jOOQ 4.0." means on the jOOQ site under this flag. Is the flag going away, or is support for stored procedure return types going away? A brief dig through the jOOQ github issues didn't yield me an answer.
That flag has been introduced because of a backwards incompatible change in the code generator that affected only SQL Server: https://github.com/jOOQ/jOOQ/issues/4106
In SQL Server, procedures always return an INT value, just like functions. This change allowed for fetching this INT value using jOOQ generated code. In some cases, it was desireable to not have this feature enabled when upgrading from jOOQ 3.5 to 3.6. Going forward, we'll always generate this INT return type on SQL Server stored procedures.
This is why the flag has been deprecated from the beginning, as we don't encourage its use, except for backwards compatibility usage. It probably won't help you here.
Stored procedure support is definitely not going to be deprecated.
Tempted to simply turn off deprecation. This also seems like a global and not beneficial change, but it would serve the purpose.
Why not. A quick workaround. You don't have to use all the generated code. The deprecation is there to indicate that calling this generated procedure probably won't work out of the box, so its use is discouraged.
If I created a binding, I have no idea what it would do, or how to define it since TRIGGER really isn't a sensible thing to bind a Java object to. I assume I'd specify as TRIGGER in the forcedType element, but then the Java binding seems like a waste of time at best and misleading at worst.
Indeed, that wouldn't really add much value to your use cases as you will never directly call the trigger function in PostgreSQL.
Again, your own solution using <exclude> is the ideal solution here. In the future, we might offer a new code generation configuration flag that allows for turning on/off the generation of trigger functions, with the default being off: https://github.com/jOOQ/jOOQ/issues/9270 | unknown | |
d13050 | train | You can perform a depth limited search with limit of |V|/10 on your graph. It will help you find the path with the least cost.
limit = v_size / 10
best[v_size] initialize to MAX_INT
depth_limited(node, length, cost)
if length == limit
if cost < best[node]
best[node] = cost
return
for each u connected to node
depth_limited(u, length+1, cost + w[node][u])
depth_limited(start_node, 0, 0)
A: According to me Bellman Ford's algorithm SHOULD be applicable here with a slight modification.
After iteration k, the distances to each node u_j(k) would be the shortest distance from source s having exactly k edges.
Initialize u_j(0) = infinity for all u_j, and 0 for s. Then recurrence relation would be,
u_j(k) = min {u_p(k-1) + w_{pj} | There is an edge from u_p to u_j}
Note that in this case u_j(k) may be greater than u_j(k-1).
The complexity of the above algorithm shall be O(|E|.|V|/10) = O(|E|.|V|).
Also, the negative cycles won't matter in this case because we shall stop after |V|/10 iterations. Whether cost can be further decreased by adding more edges is irrelevant. | unknown | |
d13051 | train | By default, the .save method will save the file as .xls or .xlsx (dependant on your version of excel), you need to force this with .saveas
wkb.SaveAs Filename:=MyNewPathFilename, FileFormat:=xlOpenXMLWorkbookMacroEnabled
obviously change the variable 'MyNewPathFilename' to whatever you want to save the file as, probably want to take the Path and check it ends in .xlsm then pass it into this variable | unknown | |
d13052 | train | Can confirm something in conda or click broke recently: colorama is missing after installing click (which was installed for black in my case). I use conda environment files so instead of manually installing I added a more recent version with
- conda-forge::click
in the .yml file.
Then conda update installed click 8.03 and colorama, over click 8.0.1 which I had. Without an env file conda install -c conda-forge click should do the trick.
I do not know what exactly fixed it though, it is not in click's release notes: though there was arecent change to always install colorama, that was in version 8.0.0. | unknown | |
d13053 | train | Note: This post is just to have a bit more insight into a potentially confusing problem.
Using a channel of type error is the idiomatic way to send errors.
Another way around this would be to change the channel signature and explicitly say that is a channel pointer to error instead of a channel of interface errors:
package main
import (
"fmt"
"os/exec"
)
func main() {
errChan := make(chan *exec.Error)
go func() {
var e *exec.Error = nil
errChan <- e
}()
err := <-errChan
if err != nil {
fmt.Printf("err != nil, but err = %v\n", err)
} else {
fmt.Printf("err == nil\n")
}
}
http://play.golang.org/p/l6Fq8O0wJw
A: The problem lies in that the value passed into the channel as a error interface is not nil, but rather a exec.Error pointer which points to nil.
The program will behave correctly if you change:
go func() {
var e *exec.Error = nil
if e == nil {
errChan <- nil
}
}()
This is the appropriate way to solve the problem because the idiomatic way to report that no error occurred is by passing a nil error interface.
However, if you want to change the main instead (maybe because you use a third party package which makes the mistake of returning pointers set to nil), you will have to either do a type assertion to the specific type (*exec.Error) and then check if it is nil, or else use the reflect package.
Example using reflect to check for nil:
func IsNil(i interface{}) bool {
// Check if it is an actual nil-value
if i == nil {
return true
}
v := reflect.ValueOf(i)
switch v.Kind() {
// Only the following kinds can be nil
case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice:
return v.IsNil()
}
return false
}
Working example: http://play.golang.org/p/rpG1PVTwwM
You can find a discussion about it here: https://groups.google.com/forum/#!topic/golang-nuts/QzVDKv7p0Vs | unknown | |
d13054 | train | The approach you're using of dynamically changing the loaded stylesheet is not very reliable.
A much better approach is to put all the relevant styles in to the page, in separate stylesheets, then toggle() a class on a low level element, such as the body, and hang all your selectors off that.
In practice it would look something like this:
jQuery($ => {
$('.dark__mode').on('click', (e) => {
e.preventDefault();
$('body').toggleClass('dark');
})
});
/* Normal layout */
div { color: #0C0; }
a { color: #C00; }
/* Dark layout */
body.dark {
background-color: #333;
color: #FFF;
}
body.dark div { color: #CCC; }
body.dark a { color: #CC0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="#" class="dark__mode">Toggle</a>
<div>
<p>Lorem ipsum dolor sit</p>
<a href="#">Amet consectetur adipcing elit</a>
</div> | unknown | |
d13055 | train | 08:CC:D7:11:1F:1D:38
SHA1: F1:78:AD:C8:D0:3A:4C:0C:9A:4F:89:C0:2A:2F:E2:E6:D5:13:96:40
Signature algorithm name: SHA1withDSA
Version: 3
*******************************************
*******************************************
client.truststore
hostname[username:/this/is/a/path][713]% keytool -list -keystore client.truststore -v
Enter keystore password:
Keystore type: JKS
Keystore provider: SUN
Your keystore contains 1 entry
Alias name: mykey
Creation date: Feb 4, 2010
Entry type: trustedCertEntry
Owner: CN=hostname, OU=hostname, O=hostname, L=hostname, ST=hostname, C=hostname
Issuer: CN=hostname, OU=hostname, O=hostname, L=hostname, ST=hostname, C=hostname
Serial number: 4b6b0ea7
Valid from: Thu Feb 04 13:15:03 EST 2010 until: Wed May 05 14:15:03 EDT 2010
Certificate fingerprints:
MD5: 81:C0:3F:EC:AD:5B:7B:C4:DA:08:CC:D7:11:1F:1D:38
SHA1: F1:78:AD:C8:D0:3A:4C:0C:9A:4F:89:C0:2A:2F:E2:E6:D5:13:96:40
Signature algorithm name: SHA1withDSA
Version: 3
*******************************************
*******************************************
Update
I thought it could be useful to include the entire exception:
javax.xml.soap.SOAPException: java.io.IOException: Could not transmit message
at org.jboss.ws.core.soap.SOAPConnectionImpl.callInternal(SOAPConnectionImpl.java:115)
at org.jboss.ws.core.soap.SOAPConnectionImpl.call(SOAPConnectionImpl.java:66)
at com.alcatel.tpapps.common.utils.SOAPClient.execute(SOAPClient.java:193)
at com.alcatel.tpapps.common.utils.SOAPClient.main(SOAPClient.java:280)
Caused by: java.io.IOException: Could not transmit message
at org.jboss.ws.core.client.RemotingConnectionImpl.invoke(RemotingConnectionImpl.java:192)
at org.jboss.ws.core.client.SOAPRemotingConnection.invoke(SOAPRemotingConnection.java:77)
at org.jboss.ws.core.soap.SOAPConnectionImpl.callInternal(SOAPConnectionImpl.java:106)
... 3 more
Caused by: org.jboss.remoting.CannotConnectException: Can not connect http client invoker. sun.security.validator.ValidatorException: No trusted certificate found.
at org.jboss.remoting.transport.http.HTTPClientInvoker.useHttpURLConnection(HTTPClientInvoker.java:368)
at org.jboss.remoting.transport.http.HTTPClientInvoker.transport(HTTPClientInvoker.java:148)
at org.jboss.remoting.MicroRemoteClientInvoker.invoke(MicroRemoteClientInvoker.java:141)
at org.jboss.remoting.Client.invoke(Client.java:1858)
at org.jboss.remoting.Client.invoke(Client.java:718)
at org.jboss.ws.core.client.RemotingConnectionImpl.invoke(RemotingConnectionImpl.java:171)
... 5 more
Caused by: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: No trusted certificate found
at com.sun.net.ssl.internal.ssl.Alerts.getSSLException(Alerts.java:150)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1584)
at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Handshaker.java:174)
at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Handshaker.java:168)
at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:848)
at com.sun.net.ssl.internal.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:106)
at com.sun.net.ssl.internal.ssl.Handshaker.processLoop(Handshaker.java:495)
at com.sun.net.ssl.internal.ssl.Handshaker.process_record(Handshaker.java:433)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:877)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1089)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1116)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1100)
at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:402)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:170)
at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:857)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java:230)
at org.jboss.remoting.transport.http.HTTPClientInvoker.useHttpURLConnection(HTTPClientInvoker.java:288)
... 10 more
Caused by: sun.security.validator.ValidatorException: No trusted certificate found
at sun.security.validator.SimpleValidator.buildTrustedChain(SimpleValidator.java:304)
at sun.security.validator.SimpleValidator.engineValidate(SimpleValidator.java:107)
at sun.security.validator.Validator.validate(Validator.java:203)
at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:172)
at com.sun.net.ssl.internal.ssl.JsseX509TrustManager.checkServerTrusted(SSLContextImpl.java:320)
at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:841)
... 22 more
A: You mustn't do that. A keystore is strictly private. If you leak it to anybody you have fatally compromised security. There is no point in doing this kind of thing just to get it working, because it isn't working - it is just a security breach. You have to do it right: export from the server's keystore into the client's truststore, and from the client's keystore if any to the server's keystore.
A: You would need to "establish trust" between your server and client (I'm assuming you only need to do server-side authentication). This is because you use self-signed certs.
That involves importing your server's cert into the client trust store:
On the server side:
keytool -keystore <keystore file> -alias <alias> -export -file <certfilename>.cert
Copy the .cert file over to the client side and then:
keytool -keystore <truststore file> -alias <alias> -import -file <certfilename>.cert
A: You can't share the keystore between client and server, because the keystore contains the private key. When authenticating, the client skips the certificates with private keys. As said above you need to deploy a truststore on client side.
The certificates in a keystore don't behave the same way, depending on how you generated or imported them.
An imported certificate's entry type (seen when verbosely listing the whole keystore with -list -v) is "trustedCertEntry". A generated certificate's entry type is "PrivateKeyEntry". When you export a certificate, you only export its public key, and an optional reference to its issuer.
Seems like you need to export the self-signed certificate in your keystore as a trusted certificate in your truststore (names make sense here).
I wouldn't do that, because SSL/TLS implementations probably don't support it. From a real world perspective it's like deploying the ultimately secret private key from Verisign on some obscure Web server to sign casual pages, while the only purpose of this private key is to remain in a safe and sign other certificates. SSL/TLS implementors probably won't pollute their code with such a use case, and anyways, the "KeyUsage" certificate extension may restrict a certificate usage to signing, preventing encipherment.
That's why I suggest to rebuild a chain of certificates for your test.
The keytool documentation contains an interesting part about creating a chain (-gencert command) but it's a very skeletal example which doesn't cover the keystore-truststore relationship. I've enhanced it to simulate a third-party certification authority.
A temporary store their-keystore.jks represents a certificate-emitting authority. I feed it with a certificate chain of ca2 -> ca1 -> ca with ca being considered as a root certificate. The chain appears with each non-root certificate (namely ca1 and ca2) referencing their issuer as Certificate[2]. Please note that every certificate is "PrivateKeyEntry".
Then I feed the my-keystore.jks with those certificates in order: ca, ca1, ca2. I import ca with the -trustcacerts option which means it becomes a root certificate. In my-keystore.jks each imported certificate now is "trustedCertEntry" which means there is only the public key. The issuing relationship only appears in the "Issuer" field but it's OK because the trust relationship mattered most at the time of the import.
At this point my-keystore.jks simulates an environment containing some trusted certificates, like a fresh JRE. The their-keystore.jks simulates the owners of those certificates, who have the power to sign certificate requests.
So do I : I create a self-signed certificate e1 in my-keystore.jks, get it signed by ca2 (through their-keystore.jks) and import the signed result back into my-keystore.jks. e1 is still a "PrivateKeyEntry" (because its private key remains in my-keystore.jks) but now I've built the following chain : e1 -> ca2 -> ca1. It seems that ca1 -> ca is implicit with ca being a certification authority.
To build the truststore I just import certificates ca, ca1 and ca2 the same way I did for my-keystore.jks. Please note I don't import e1, as I expect the SSL/TLS client to validate it against ca2.
I think this gets rather close of how things work in real world. What's nice here is you have full control on the certificates, and no dependency on JRE's cacerts.
Here is the code putting what I say in practice. Seems to work with Jetty (client and server) as long as you disable certificate revocation list (a topic left for another day).
#!/bin/bash
rm their-keystore.jks 2> /dev/null
rm my-keystore.jks 2> /dev/null
rm my-truststore.jks 2> /dev/null
echo "===================================================="
echo "Creating fake third-party chain ca2 -> ca1 -> ca ..."
echo "===================================================="
keytool -genkeypair -alias ca -dname cn=ca \
-validity 10000 -keyalg RSA -keysize 2048 \
-ext BasicConstraints:critical=ca:true,pathlen:10000 \
-keystore their-keystore.jks -keypass Keypass -storepass Storepass
keytool -genkeypair -alias ca1 -dname cn=ca1 \
-validity 10000 -keyalg RSA -keysize 2048 \
-keystore their-keystore.jks -keypass Keypass -storepass Storepass
keytool -genkeypair -alias ca2 -dname cn=ca2 \
-validity 10000 -keyalg RSA -keysize 2048 \
-keystore their-keystore.jks -keypass Keypass -storepass Storepass
keytool -certreq -alias ca1 \
-keystore their-keystore.jks -keypass Keypass -storepass Storepass \
| keytool -gencert -alias ca \
-ext KeyUsage:critical=keyCertSign \
-ext SubjectAlternativeName=dns:ca1 \
-keystore their-keystore.jks -keypass Keypass -storepass Storepass \
| keytool -importcert -alias ca1 \
-keystore their-keystore.jks -keypass Keypass -storepass Storepass
#echo "Debug exit" ; exit 0
keytool -certreq -alias ca2 \
-keystore their-keystore.jks -keypass Keypass -storepass Storepass \
| keytool -gencert -alias ca1 \
-ext KeyUsage:critical=keyCertSign \
-ext SubjectAlternativeName=dns:ca2 \
-keystore their-keystore.jks -keypass Keypass -storepass Storepass \
| keytool -importcert -alias ca2 \
-keystore their-keystore.jks -keypass Keypass -storepass Storepass
keytool -list -v -storepass Storepass -keystore their-keystore.jks
echo "===================================================================="
echo "Fake third-party chain generated. Now generating my-keystore.jks ..."
echo "===================================================================="
read -p "Press a key to continue."
# Import authority's certificate chain
keytool -exportcert -alias ca \
-keystore their-keystore.jks -keypass Keypass -storepass Storepass \
| keytool -importcert -trustcacerts -noprompt -alias ca \
-keystore my-keystore.jks -keypass Keypass -storepass Storepass
keytool -exportcert -alias ca1 \
-keystore their-keystore.jks -keypass Keypass -storepass Storepass \
| keytool -importcert -noprompt -alias ca1 \
-keystore my-keystore.jks -keypass Keypass -storepass Storepass
keytool -exportcert -alias ca2 \
-keystore their-keystore.jks -keypass Keypass -storepass Storepass \
| keytool -importcert -noprompt -alias ca2 \
-keystore my-keystore.jks -keypass Keypass -storepass Storepass
# Create our own certificate, the authority signs it.
keytool -genkeypair -alias e1 -dname cn=e1 \
-validity 10000 -keyalg RSA -keysize 2048 \
-keystore my-keystore.jks -keypass Keypass -storepass Storepass
keytool -certreq -alias e1 \
-keystore my-keystore.jks -keypass Keypass -storepass Storepass \
| keytool -gencert -alias ca2 \
-ext SubjectAlternativeName=dns:localhost \
-ext KeyUsage:critical=keyEncipherment,digitalSignature \
-ext ExtendedKeyUsage=serverAuth,clientAuth \
-keystore their-keystore.jks -keypass Keypass -storepass Storepass \
| keytool -importcert -alias e1 \
-keystore my-keystore.jks -keypass Keypass -storepass Storepass
keytool -list -v -storepass Storepass -keystore my-keystore.jks
echo "================================================="
echo "Keystore generated. Now generating truststore ..."
echo "================================================="
read -p "Press a key to continue."
keytool -exportcert -alias ca \
-keystore my-keystore.jks -keypass Keypass -storepass Storepass \
| keytool -importcert -trustcacerts -noprompt -alias ca \
-keystore my-truststore.jks -keypass Keypass -storepass Storepass
keytool -exportcert -alias ca1 \
-keystore my-keystore.jks -keypass Keypass -storepass Storepass \
| keytool -importcert -noprompt -alias ca1 \
-keystore my-truststore.jks -keypass Keypass -storepass Storepass
keytool -exportcert -alias ca2 \
-keystore my-keystore.jks -keypass Keypass -storepass Storepass \
| keytool -importcert -noprompt -alias ca2 \
-keystore my-truststore.jks -keypass Keypass -storepass Storepass
keytool -list -v -storepass Storepass -keystore my-truststore.jks
rm their-keystore.jks 2> /dev/null
A: I don't get it. Are you using the server key store with the client? What is your use case exactly? Are you trying to setup mutual authentication?
If yes, you're on the wrong path here. You'll need a client key store (for the client's self-signed certificate and private key) and a client trust store (for the server's "stand-alone" self-signed certificate i.e. without its private key). Both are different from the server key store.
A: Springboot 2.1.5 , java 1.8, keytool(it is part of JDK 8)
these are the steps to follow to generate the self signed ssl certifcate in spring boot
1. Generate self signed ssl certificate
keytool -genkeypair -alias tomcat -keyalg RSA -keysize 2048 -storetype PKCS12 -keystore keystore.p12 -validity 3650
ex: D:\example> <here run the above command>
if it is not working then make sure that your java bin path is set at environment variables to the PATH variable as
C:\Program Files\Java\jdk1.8.0_191\bin
2. after key generation has done then copy that file in to the src/main/resources folder in your project
3. add key store properties in applicaiton.properties
server.port: 8443
server.ssl.key-store:classpath:keystore.p12
server.ssl.key-store-password: test123 # change the pwd
server.ssl.keyStoreType: PKCS12
server.ssl.keyAlias: tomcat
3. change your postman ssl verification settings to turn OFF
go to settings and select the ssl verification to turn off
now verify the url ( your applicaiton url)
https://localhost:8443/test/hello | unknown | |
d13056 | train | Without using math.h, or printf(“.n%f”), the other answer will work for you.
But regarding your phrase I want to store k = 2.8.... to n positions. It may be interesting to you that this has less to do with rounding than it has to do with type, and how much memory is required to store each type.
float, double and long double require differing amounts of memory to store the precision (numbers to the right of ".") required by the type, regardless of how you format them for display. That is:
A displayed representation of a float may look like 2.83
while in memory, a float will contain memory sufficient to 7 digits precision 2.8368361 (on 32 bit system)
And for a type double representation of the same number might stored as 2.836836100000001.
Again, the way a number has little to do with how it is stored.
Edit: (Rounding a float to n decimal places)
#include <ansi_c.h>//I did not realized that this header INCLUDEs math.h, oops
int main(void)
{
int p;
float a,c;
printf("Enter the floating point value:-");
scanf("%f",&a);
printf("Enter the precision value:-");
scanf("%d",&p);
if(a>0)
{
c=((int)(a*pow(10,p)+0.5)/(pow(10,p)));
printf("Value Rounding Off:-%f",c);
}
else
{
c=((int)(a*pow(10,p)+0.5)/(pow(10,p)));
printf("Value Rounding Off:-%f",c);
}
getchar();
getchar();
}
From HERE (thanks to H. Gupta)
A: If you want to have n digits, then you can first start with multiplying your number f with 10^n. After that you can turn it into an integer so that the rest of the decimals "disappear" - turn it again into an float and divide by 10^n
However, remember to check for if the number needs to be rounded up or down :)
*
*2 places = 10^2
*2.836836 * 10^2 = 283.6836
*rounding rules: add 0.5 to the number
*283.6836 + 0.5 = 284.1836
*(int) 284.1836 = 284
*284 * 1.0 / 10^2 = 2.84
=>
float f = 10^2 * f + 0.5
int newint = (int) f f = newint * 1.0 / 10^2
A: Scale x and then round. Make sure to deal with negative numbers correctly if rounding to nearest.
Thanks to @David Heffernan C : x to the power n using repeated squaring without recursive function
float pow10f(unsigned exponent) {
float base = 10.0;
float result = 1.0;
while (exponent > 0) {
while ((exponent & 1) == 0) {
exponent /= 2;
base *= base;
}
exponent--;
result *= base;
}
return result;
}
float RoundToNPlaces(float x, unsigned n) {
if (x < 0.0) {
return -RoundToNPlaces(-x, n);
}
float scale = pow10f(n); // fix per @Michael Burr
x *= scale;
uintmax_t u = (uintmax_t) (x + 0.5); // Add 0.5 if rounding to nearest.
x = (float) u;
x /= scale;
return x;
}
Does have a range limit though but likely wider than int.
[Edit] per @Michael Burr comment
(int) (RoundToNPlaces( 2.8386483, 2) * 100) --> 283 rather than the expected 284. What happened though, is correct. Rounded to 2 places the result of 2.8386483 is mathematically 2.84 but is not representable with typical float. The 2 closest float to 2.84 are
2.8399999141693115234375000
2.8400001525878906250000000
and RoundToNPlaces( 2.8386483, 2) resulted in the closer one: 2.8399999141693115234375.
Now performing (int) (2.8399999141693115234375f * 100) --> (int) 283.99999141693115234375f --> 283.
This exhibits the necessary compromise to the OP's original goal, finding 2.8386483f rounded to 2 decimal places does not typically lead to an exact answer. Hence subsequent operations like * 100 and then int conversion lead to unexpected results, not because the best answer was not found in the round to 2 decimal places step, but because the best answer still will not exhibit all the properties of the mathematical exact answer. | unknown | |
d13057 | train | In the record's Model, add a uniqueness validation as detailed in this Rails Guide. You can apply a scope on that validation, so that the uniqueness is determined using multiple record attributes.
Alternatively, if you really don't want to mark these records as unique, add an easy way for the user to update their submission to the post record creation page. i.e. they add a new record, the ability to edit that record immediately pops up in their view so that, rather than hitting back and creating a new record, they update the one they just made. | unknown | |
d13058 | train | You can checkout Angular UI @ http://angular-ui.github.io/ui-utils/
Provide details event handle related blur,focus,keydow,keyup,keypress
<input ui-event="{ blur : 'blurCallback()' }">
<textarea ui-keypress="{13:'keypressCallback($event)'}"></textarea>
<textarea ui-keydown="{'enter alt-space':'keypressCallback($event)'}"> </textarea>
<textarea ui-keydown="{27:'keydownCallback($event)'}"></textarea>
<textarea ui-keydown="{'enter alt-space':'keypressCallback($event)'}"> </textarea>
<textarea ui-keyup="{'enter':'keypressCallback($event)'}"> </textarea>
A: Here's what's happening:
*
*You press enter
*ng-keydown triggers (digest begins)
*You call target.blur()
*ng-blur triggers and attempts to start another digest cycle
*Angular complains
The blur is executed synchronously and immediately triggers the handler without finishing the first digest.
In my opinion, this is not a problem with your code, but rather an Angular bug. I've been trying to think of a better solution, but I can only find:
app.controller('BlurCtrl', function($scope, $timeout) {
$scope.blurModel = "I'm the value"
$scope.blurOnEnter = function( $event ) {
if ( $event.keyCode != 13 )
return
// this will finish the current digest before triggering the blur
$timeout(function () { $event.target.blur() }, 0, false);
}
$scope.onBlur = function() {
$scope.result = this.blurModel
}
})
A: Here is a small directive :
.directive('ngEnterBlur', function () {
return function (scope, element, attrs) {
element.bind("keydown keypress blur", function (event) {
if(event.which === 13 || event.type === "blur") {
scope.$apply(function (){
scope.$eval(attrs.ngEnterBlur);
});
event.preventDefault();
}
});
};
}) | unknown | |
d13059 | train | You can't add two pointers. You can add an integer to a pointer, and you can subtract two pointers to get an integer difference, but adding two pointers makes no sense. To solve your problem therefore you just need to remove the cast:
Flash_ptr = Flash_ptr + 0x200;
This increments Flash_ptr by 0x200 elements, but since Flash_ptr is of type unsigned char * then this just translates to an increment of 0x200 bytes.
In order to make this part of a loop and check for an upper bound you would do something like this:
while (Flash_ptr < (unsigned char *)0x50000) // loop until Flash_ptr >= 0x50000
{
// ... do something with Flash_ptr ...
Flash_ptr += 0x200;
}
A: You cannot add two pointers. What you can do is to increment the address held by the pointer. Remove the (unsigned char *)cast.
If you're interested, read more about pointer arithmatic here. | unknown | |
d13060 | train | I don't know which generic repository you are refering to, but here is my experience with A generic repository.
In general, a unit of work or repository is not needed with EntityFramework. EntityFramework does it all.
However, in my first EF project I found myself creating a factory class that handed out and saved all entities. The class was doing that without doing the complete work of a unit of work, nor providing a standardized interface like a repository does. The huge class was in need of some structure. So, my personal advice is against one big repository for all entities, this repository will grow and will be increasingly difficult to maintain. If you think of such a class you better use EF as it is.
In the second project I use a UnitOfWork and generic repository. This suits my purposes much better. One unit of work to do the save operation, saving all changes in one save operation and the same interface for all repositories. Two classes of which I only have to change the unit of work to accommodate a new entity. The unit of work also hides the use of the dbContext which to my opinion causes ugly code.
I do not use a fancy unitofwork or generic repository (I found mine at: http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application), just enough to have some guidance in implementation.
I agree with Gert in his immediate reply: it is all about personal preference. | unknown | |
d13061 | train | You should read up about using a ColorMatrix. This matrix can perform exactly the operation you are performing manually. In your case, since you are just adding a constant value to each component, your matrix would have a = g = m = s = 1, and e = j = o = value, and the rest of your matrix would be zeroes.
Then you can use setColorFilter() to apply a ColorMatrixColorFilter to your ImageView.
A: Maybe using a bitwise operation proves faster?
for(int x = 0; x < bgr.getWidth(); ++x)
{
for(int y = 0; y < bgr.getHeight(); ++y)
{
// get pixel color
pixel = bgr.getPixel(x, y);
int alpha = (pixel & 0xff000000) >> 24;
int R = (pixel & 0x00ff0000) >> 16;
int G = (pixel & 0x0000ff00) >> 8;
int B = (pixel & 0x000000ff);
// increase/decrease each channel
R += value;
if(R > 255) { R = 255; }
else if(R < 0) { R = 0; }
G += value;
if(G > 255) { G = 255; }
else if(G < 0) { G = 0; }
B += value;
if(B > 255) { B = 255; }
else if(B < 0) { B = 0; }
// apply new pixel color to output bitmap
bgr.setPixel(x, y, (alpha << 24) + (red << 16) + (green << 8) + blue);
}
If that proves too slow aswell,using a ColorMatrix would be the best way to do it,even if i presume it does the exact same filtering,it probably is more efficient. | unknown | |
d13062 | train | def __init__(self, variables = {}):
self.variables = {}
if ("leng") in variables:
self.variables["leng"] = variables["leng"]
else:
self.variables["leng"] = np.array([10,])
if ("width") in variables:
self.variables["width"]= variables["width"]
else:
self.variables["width"] = np.array([10,])
In the Console:
variables.items()
>>>"leng" : 10
>>>"width" : 10
A: Just use an object to call class items.
m=A() and then m.variables | unknown | |
d13063 | train | Try triggering a click event on the Avbryt button when a user clicks on the modal backdrop. Something like this:
$('.modal-backdrop').click(function(){
$('.avbryt').trigger('click');
});
That should bypass whatever the underlying problem is.
For reference: http://api.jquery.com/trigger/
A: According to the image in question, you are using angular-modal-service along with bootstrap.js in your project. So I searched its github repo and found this issue: https://github.com/dwmkerr/angular-modal-service/issues/107
According to the comments there, you should change your code as below:
ModalService.showModal({
templateUrl: 'newProject.html',
controller: "NewProjectModalController"
}).then(function(modal) {
modal.element.modal();
modal.close.then(function(result) {
$('#newProjectModal').modal('hide');
$('body').removeClass('modal-open');
$('.modal-backdrop').remove();
}
// added by me
modal.element.on('hidden.bs.modal', function () {// bootstrap event
modal.scope.close(false,500);
});
});
}); | unknown | |
d13064 | train | I strongly recommend that you go back and re-read The Rust Programming Language, specifically the chapter on generics.
LoadDsl::get_result is defined as:
fn get_result<U>(self, conn: &Conn) -> QueryResult<U>
where
Self: LoadQuery<Conn, U>,
In words, that means that the result of calling get_result will be a QueryResult parameterized by a type of the callers choice; the generic parameter U.
Your call of get_result in no way specifies the concrete type of U. In many cases, type inference is used to know what the type should be, but you are just printing the value. This means it could be any type that implements the trait and is printable, which isn't enough to conclusively decide.
You can use the turbofish operator:
foo.get_result::<SomeType>(conn)
// ^^^^^^^^^^^^
Or you can save the result to a variable with a specified type:
let bar: QueryResult<SomeType> = foo.get_result(conn);
If you review the Diesel tutorial, you will see a function like this (which I've edited to remove non-relevant detail):
pub fn create_post() -> Post {
diesel::insert(&new_post).into(posts::table)
.get_result(conn)
.expect("Error saving new post")
}
Here, type inference kicks in because expect removes the QueryResult wrapper and the return value of the function must be a Post. Working backwards, the compiler knows that U must equal Post.
If you check out the documentation for insert you can see that you can call execute if you don't care to get the inserted value back:
diesel::insert(&new_user)
.into(users)
.execute(&connection)
.unwrap(); | unknown | |
d13065 | train | Looks like a notification issue - you are changing node state without the model knowing of it. Assuming your model is a DefaultTreeModel, invoke a model.nodeChanged after changing the selection:
currentNode.setSelected(newState);
model.nodeChanged(currentNode);
A: Where is the code for your buttons used to select individual nodes? Are you trying to make a button that toggles but yours only checks the box right now? Maybe try this:
buttonPushed() {
//get your node for this button
node.setSelected(!node.isSelected());
} | unknown | |
d13066 | train | Try something like this:
try {
Charset myCharset = Charset.forName("iso-8859-1");
// and I really hope the name is correct - maybe "ISO-8859-1"
BufferedReader bufferedReader = new BufferedReader(new
InputStreamReader(inputStream, myCharset.newDecoder()));
// .. process your input here ...
}
catch(Exception ex)
{
Log.e("DECODER", ex.getMessage() );
}
A: I found the answer, thanks to @0X0nosugar, who helped me a lot. The problem was, the data that the server was retriving, was coming with 4 spaces, so when i was reiciving "null" in the app, which have 4 characters, the app was reading it with 8 characters. So, with simply trimming the data, it will convert the 8 char string, into a 4 char string:
if (result.trim().equals("null")){
Toast.makeText(mcontext, "You dont have a account with us.", Toast.LENGTH_LONG).show();
}else{
alertDialog.setMessage(result);
alertDialog.show();
mcontext.startActivity(startapp);
}
Don't know if the problem of inflate the data with spaces is actually a problem of the PHP or Android, but at least trim() helps to fix it. | unknown | |
d13067 | train | Since you have direct access to circle with id semi-circle, you can update it as the below snippet.
The snippet is running under a setTimeout to show the difference.
setTimeout(function() {
var circle = document.getElementById('semi-circle');
circle.setAttribute('r', 60)
}, 3000)
<svg id="floating-button-svg" height="100" width="100">
<circle id="semi-circle" class="cls-1" cx="50" cy="50" r="40" fill="red" />
</svg>
You can also do it in another way, check the snippet
setTimeout(function() {
var circle = document.getElementById('floating-button-svg');
circle.firstElementChild.setAttribute('r', 60)
}, 1500)
<svg id="floating-button-svg" height="400" width="400">
<circle id="semi-circle" class="cls-1" cx="80" cy="80" r="40" fill="red" />
</svg> | unknown | |
d13068 | train | QGridLayout doesn't draw anything, it just calculates the layout. So the QGridLayout itself cannot draw gridlines for you.
The easiest way is to put a QFrame to each of your QGridLayout's cell and move your content to these QFrames. In WinXP, setting QFrame's frameShape to Box and frameShadow to Plain, you get simple boxes.
You could also create a new widget that draws the gridlines according to the layout that the QGridLayout calculates. By using QGridLayout::itemAtPosition you can get a QLayoutItem for each cell. | unknown | |
d13069 | train | Your extension method is written for IList not IList<T> and because IList<T> does not inherit IList, you need to specify type argument in the extension method:
public static class Extensions
{
public static void Bind<T>(this IList<T> list)
{
//some stuff
}
} | unknown | |
d13070 | train | On click of button you can add a deeplink of message in channel
Use below deep link format to navigate to a particular conversation within channel thread:
https://teams.microsoft.com/l/message//?tenantId=&groupId=&parentMessageId=&teamName=&channelName=&createdTime=
Example: https://teams.microsoft.com/l/message//1648741500652?tenantId=&groupId=&parentMessageId=1648741500652&teamName=&channelName=&createdTime=1648741500652
Ref Doc: https://learn.microsoft.com/en-us/microsoftteams/platform/concepts/build-and-test/deep-links?tabs=teamsjs-v2#generate-deep-links-to-channel-conversation | unknown | |
d13071 | train | You can specify the version with e.g: "%tensorflow_version 2.x", as described here:
https://colab.research.google.com/notebooks/tensorflow_version.ipynb | unknown | |
d13072 | train | Your query is off. See here for what the proper format should be.
r1 <- c("PID1","PID2","PID3")
wrong
paste("select * from table2 where [Serial no] = '(",r1,")' ",sep ="")
output:
[1] "select * from table2 where [Serial no] = '(PID1)' " "select * from table2 where [Serial no] = '(PID2)' " "select * from table2 where [Serial no] = '(PID3)' "
correct
paste("select * from table2 where [Serial no] IN (",paste(r1,collapse=", "),") ",sep ="")
Output:
[1] "select * from table2 where [Serial no] IN (PID1, PID2, PID3) "
So the query becomes:
t2 <- sqlquery(db2,paste0("select * from table2 where [Serial no] IN (",paste(r1,collapse=", "),") ",sep =""))
Hope this helps. | unknown | |
d13073 | train | check this link I think its perfect.
http://pchart.sourceforge.net/
(also you should configure php to enable image creating).
In Windows, you'll include the GD2 DLL php_gd2.dll as an extension in php.ini. The GD1 DLL php_gd.dll was removed in PHP 4.3.2. Also note that the preferred truecolor image functions, such as imagecreatetruecolor(), require GD2.
check these links.
http://www.php.net/manual/en/image.requirements.php
http://www.php.net/manual/en/image.installation.php
http://www.php.net/manual/en/image.configuration.php
examples: | unknown | |
d13074 | train | CKAN has no built-in way to recover that data. There is the "activity stream" and its deprecated predecessor "revisions" (see this answer on SO), but AFAIK they cannot be used to restore your dataset.
If you don't have a backup of your data then it is lost.
For the future: an easy way to backup your CKAN data is using the ckanapi command line tool. | unknown | |
d13075 | train | If you would like to keep using blob storage, you can store metadata with the blobs - just add custom metadata to your blobs, add corresponding fields to the search index, and the blob indexer will pick up the metadata. | unknown | |
d13076 | train | Is it possible to define it in such a way that actions can be any number of functions with varying argument lists?
With a dynamic list, you need runtime checking. I don't think you can do runtime checking on these functions without branding them (I tried doing it on length since those two functions have different lengths, but it didn't work and it really wouldn't have been useful even if it had — (arg1: string) => void and (arg1: number) => void are different functions with the same length).
With branding and a runtime check, it's possible:
*
*Define branded types for the functions
*Create the functions
*Define the action list as an array of a union of the function types
*Have handleActions branch on the brand
Like this:
type Action1 = (
(arg1: string) => void
) & {
__action__: "action1";
};
type Action2 = (
(arg1: string, arg2: {a: string, b: number}) => void
) & {
__action__: "action2";
};
const action1: Action1 = Object.assign(
(arg1: string) => {},
{__action__: "action1"} as const
);
const action2: Action2 = Object.assign(
(arg1: string, arg2: {a: string, b: number}) => {},
{__action__: "action2"} as const
);
const actions = [action1, action2];
type ActionsList = (Action1 | Action2)[];
const handleActions = (actions: ActionsList) => {
const [action1, action2] = actions;
if (action1.__action__ === "action1") {
action1("x"); // <==== infers `(arg: string) => void` here
}
};
handleActions(actions);
Playground link
Before you added the text quoted at the top of the answer, it was possible with a readonly tuple type. I'm keeping this in the answer in case it's useful to others, even though it doesn't apply to your situation.
Here's what that looks like:
type ActionsList = readonly [
(arg1: string) => void,
(arg1: string, arg2: { a: string; b: number; }) => void
];
To make it readonly, you'll need as const on actions:
const actions = [action1, action2] as const;
// ^^^^^^^^^
A tuple is a kind of "...Array type that knows exactly how many elements it contains, and exactly which types it contains at specific positions." (from the link above)
Playground link | unknown | |
d13077 | train | If you are expecting the following statment to call the setter for VisibleQuestions, then you are mistaken:
VisibleQuestions.Add(sqc.SurveyQuestion.ID);
This statement calls the Add method on the List<int> instance returned by the VisibleQuestions getter.
Utilizing the setter would happen if you assigned a value to VisibleQuestions, like so:
VisibleQuestions = new List<int>();
A: You are not calling the setter on that line. You are calling the getter that returns a list to which you add an element. However next time you access the same getter you create a new list (without the added element) which you return anew
A: From MSDN - Using Properties (C# Programming Guide) - The set Accessor:
When you assign a value to the property, the set accessor is invoked
by using an argument that provides the new value.
The setter is only called if you actually set your property's value. In your case, you are calling your getter, which returns a new list, based on the value of the underlying field. If you want to then update that underlying field after you update the list, you will need to then set the value of the property to your updated list, like so:
// Calls the getter and returns a new list
List<string> questions = VisibleQuestions;
// Updates the list, but does not trigger the setter
questions.Add(sqc.SurveyQuestion.ID);
// Calls the setter
VisibleQuestions = questions; | unknown | |
d13078 | train | It's not possible with HTML. But it is definitely possible with Javascript, which you can add to any HTML code.
For code example please refer to this stackoverflow thread!
Your code will probably look like this:
<html>
<body>
<script>
var text = httpGet("https://steamgaug.es/api/v2");
obj = JSON.parse(text);
alert(obj.ISteamClient.online);
function httpGet(theUrl)
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", theUrl, false ); // false for synchronous request
xmlHttp.send( null );
return xmlHttp.responseText;
}
</script>
</body>
</html> | unknown | |
d13079 | train | The built-in #index is not a binary search, it's just a simple iterative search. However, it is implemented in C rather than Ruby, so naturally it can be several orders of magnitude faster. | unknown | |
d13080 | train | As Rayon Dabre says, const means that the value of the variable cannot be changed. The value of the variable foo in your example is unchanged: it is still the same object. That object's property changed.
In order to make an object itself unchangeable, you can use Object.freeze:
var foo = {'test': 'content'};
Object.freeze(foo);
foo.test = 'change';
foo.test
// => "content"
A: See Object.freeze:
const foo = Object.freeze( {'test': 'content'} ); | unknown | |
d13081 | train | dump($this->theme_path); and dump($this->theme); and check what is the path in these objects if the root path is ok than check your directory that you have this file or not
your_project_folder\assets\grocery_crud\themes\datatables\views\list_template.php
your_project_folder\assets\grocery_crud\themes\flexigrid\views\list_template.php | unknown | |
d13082 | train | In your situation, how about the following modification?
From:
const values = [headers, ...data.data.map(o => headers.map(h => o[h]))];
To:
var values = data.data.map(o => headers.map(h => o[h]));
if (sheet.getLastRow() == 0) values.unshift(headers);
*
*In this modification, by checking whether the 1st row is existing, the header row is added. | unknown | |
d13083 | train | A BufferStrategy has a number of initial requirements which must be meet before it can be rendered to. Also, because of the nature of how it works, you might need to repeat a paint phases a number of times before it's actually accepted by the hardware layer.
I recommend going through the JavaDocs and tutorial, they provide invaluable examples into how you're suppose to use a BufferStrategy
The following example uses a Canvas as the base component and sets up a rendering loop within a custom Thread. It's very basic, but shows the basic concepts you'd need to implement...
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
TestCanvas canvas = new TestCanvas();
JFrame frame = new JFrame();
frame.add(canvas);
frame.setTitle("Test");
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
canvas.start();
}
});
}
public class TestCanvas extends Canvas {
private Thread thread;
private AtomicBoolean keepRendering = new AtomicBoolean(true);
@Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
public void stop() {
if (thread != null) {
keepRendering.set(false);
try {
thread.join();
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}
public void start() {
if (thread != null) {
stop();
}
keepRendering.set(true);
thread = new Thread(new Runnable() {
@Override
public void run() {
createBufferStrategy(3);
do {
BufferStrategy bs = getBufferStrategy();
while (bs == null) {
System.out.println("get buffer");
bs = getBufferStrategy();
}
do {
// The following loop ensures that the contents of the drawing buffer
// are consistent in case the underlying surface was recreated
do {
// Get a new graphics context every time through the loop
// to make sure the strategy is validated
System.out.println("draw");
Graphics graphics = bs.getDrawGraphics();
// Render to graphics
// ...
graphics.setColor(Color.RED);
graphics.fillRect(0, 0, 100, 100);
// Dispose the graphics
graphics.dispose();
// Repeat the rendering if the drawing buffer contents
// were restored
} while (bs.contentsRestored());
System.out.println("show");
// Display the buffer
bs.show();
// Repeat the rendering if the drawing buffer was lost
} while (bs.contentsLost());
System.out.println("done");
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
} while (keepRendering.get());
}
});
thread.start();
}
}
}
Remember, the point of BufferStrategy is to give you full control over the painting process, so it works outside the normal painting process generally implemented by AWT and Swing
"At a later date the canvas will be updating many times a second so I am using a buffer strategy for this" - Before going down the "direct to hardware" solution, I'd consider using a Swing Timer and the normal painting process to see how well it works | unknown | |
d13084 | train | you can't use jquery to work with dom elements inside the editor, you need to use editor api like this:
<!DOCTYPE html>
<html lang="en">
<head>
<title>ACE in Action</title>
<style type="text/css" media="screen">
#e1 {
position: absolute;
top: 0;
right: 0;
bottom: 50%;
left: 0;
}
.misspelled {
border-bottom: 1px dashed red;
position: absolute;
}
</style>
</head>
<body>
tfa
<div id="e1"><xml>
function foo(items) {
var x = "All this is syntax highlighted";
return x;
}
</xml></div>
<pre id="e2">
second editor
</pre>
<script src="http://ajaxorg.github.io/ace-builds/src/ace.js"></script>
<script>
var Range = ace.require("ace/range").Range
var editor = ace.edit("e1");
editor.session.setMode("ace/mode/javascript");
editor.session.addMarker(new Range(1,0,1,20),"misspelled","fullLine",true);
editor.on("click", function(e) {
if (e.getDocumentPosition().row == 1)
alert('clicked');
});
</script>
</body>
</html> | unknown | |
d13085 | train | Ok so I fixed the initial issue by removing aws/aws-sdk-php : "^2.8.* that I had in my composer.json and ran a fresh 'composer require league/flysystem-aws-s3-v3 ~1.0'. This fixed the initial error in finding the S3 flysystem.
The second error fstat() expects parameter 1 to be resource, object given related to my attempt to pass an image object to the put method:
Storage::disk('s3')->put($slug, $img);
when it expects a string. This was fixed by stringifying the $img object
Storage::disk('s3')->put($slug, $img->__toString());
Hope this helps somebody else who might encounter this issue. | unknown | |
d13086 | train | df[df["overweight"] > 25] is not a valid condition.
Try this:
def overweight_normalizer():
df = pd.DataFrame({'overweight': [2, 39, 15, 45, 9]})
df["overweight"] = [1 if i > 25 else 0 for i in df["overweight"]]
return df
overweight_normalizer()
Output:
overweight
0 0
1 1
2 0
3 1
4 0 | unknown | |
d13087 | train | works in firefox for me but you defenitely need to clear your float. The easiest way to do that is using overflow: hidden on the list item so it takes the space of the floating icon and wraps its padding around that instead of just the text next to it
A: Try this my be slow your problem
CSS
give flot:left in below class
li p:nth-of-type(1) {float:left;}
And give flot:left in below class
li{float:left;} | unknown | |
d13088 | train | Try this:
MediaPlayer mp = new MediaPlayer();
mp.setDataSource("/data/test.ogg"); // replace with correct location
mp.prepare();
mp.start(); | unknown | |
d13089 | train | Try this add in. I have not used it, but it is described just as you need it. Addin
A: Try this addon which converts Selenium HTML scripts to Java .
Selenium4J
A: Look at the selenese4J-maven-plugin. Similar to selenium4j (https://github.com/RaphC/selenese4j-maven-plugin).
Provides many features :
Selenium 1/2 (WebDriver) conversion
Test Suite generation
Internationalisation of your html file
Possibility to use snippet into your html file for specific test (e.g : computing working day, write custom generation of values, handle dynamic values ...)
Use of tokenized properties
A: I took the selenium4j project and turned it into a maven plugin for those who want to take the html test cases and automatically have them run with your maven test phase. You can also separate the tests out using a profile override with surefire.
Readme is here: https://github.com/willwarren/selenium-maven-plugin
The short version of the readme:
Converts this folder structure:
./src/test/selenium
|-signin
|-TestLoginGoodPasswordSmoke.html
|-TestLoginBadPasswordSmoke.html
|-selenium4j.properties
Into
./src/test/java
|-signin
|-firefox
|-TestLoginGoodPasswordSmoke.java
|-TestLoginBadPasswordSmoke.java
This is only tested on windows with Firefox and Chrome.
I couldn't get the IE version to pass a test, but I'm new to selenium so hopefully, if you're a selenium guru, you can get past this. | unknown | |
d13090 | train | I fix it, but I'm not sure what was the exact error.
Three things I did:
1 - Two of the six projects were configured to "Any CPU" and the others to "x86", I change the ones with "Any CPU" to "x86" (can't remember which ones were, I believe it was MyService project and MyDAO project, but not sure).
2 - In the .csproj file of MyDAO project, the oracle reference was like this:
<Reference Include="Oracle.DataAccess, Version=2.112.3.0, Culture=neutral, PublicKeyToken=89b483f429c47342, processorArchitecture=x86" />
<SpecificVersion>False</SpecificVersion>
<HintPath>..\MyMainForm\bin\Release\Oracle.DataAccess.dll</HintPath>
</Reference>
But the .dll file version I'm using is 4.112.3.0, so I change it to:
<Reference Include="Oracle.DataAccess />
<SpecificVersion>False</SpecificVersion>
<Private>False</Private>
<HintPath>..\MyMainForm\bin\Release\Oracle.DataAccess.dll</HintPath>
</Reference>
3 - I change my Product.wxs to include the oracle dlls, like this:
<!-- Oracle libraries -->
<Component Guid="*">
<File Source="$(var.MyMainForm.TargetDir)\Oracle.DataAccess.dll" KeyPath="yes" />
</Component>
<Component Guid="*">
<File Source="$(var.MyMainForm.TargetDir)\oci.dll" KeyPath="yes" />
</Component>
<Component Guid="*">
<File Source="$(var.MyMainForm.TargetDir)\oramts.dll" KeyPath="yes" />
</Component>
<Component Guid="*">
<File Source="$(var.MyMainForm.TargetDir)\oramts11.dll" KeyPath="yes" />
</Component>
<Component Guid="*">
<File Source="$(var.MyMainForm.TargetDir)\orannzsbb11.dll" KeyPath="yes" />
</Component>
<Component Guid="*">
<File Source="$(var.MyMainForm.TargetDir)\oraocci11.dll" KeyPath="yes" />
</Component>
<Component Guid="*">
<File Source="$(var.MyMainForm.TargetDir)\oraociei11.dll" KeyPath="yes" />
</Component>
<Component Guid="*">
<File Source="$(var.MyMainForm.TargetDir)\OraOps11w.dll" KeyPath="yes" />
</Component>
This way I don't have to install Oracle Client on each machine. | unknown | |
d13091 | train | I never managed to get it working in WAMP server. I took my shot with XAMPP. Enormous gigantous (almost 1 GB), but heck yeah, it works!
So, try that, everything should work smoothly.
https://www.apachefriends.org/index.html
A: The solution can be found in internet connection, it is being interrupted that other components cannot be donwloaded. | unknown | |
d13092 | train | You can do this in bash itself:
var='1st line
2nd line
3rd line'
echo "${var//$'\n'/_}"
1st line_2nd line_3rd line
A: Could you please try following.
echo "$var" | paste -sd_
Where variable value is:
echo "$var"
1st line
2nd line
3rd line
A: This might work for you (GNU sed and bash):
<<<"$var" sed '1h;1!H;$!d;x;y/\n/_/'
or:
<<<"$var" sed -z 'y/\n/_/'
A: Here is another one which works:
awk -v ORS="_" '1' <<<"$var" | unknown | |
d13093 | train | You can redirect a user on clicking a like button using the Javascript SDK and FB.Event.Subscribe
FB.Event.subscribe('edge.create', function(response) {
window.parent.location = 'http://www.google.com';
});
edge.create is called when ever a user likes something on the page
response is the url that has just been liked.
If there are multiple like buttons on the page you could use an if statement with the response to make sure the page only redirects for a particular like button
Here's the full javascript code and a like button
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : 'YOUR_APP_ID', // App ID
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
oauth : true, // enable OAuth 2.0
xfbml : true // parse XFBML
});
FB.Event.subscribe('edge.create', function(response) {
window.parent.location = 'http://www.google.com';
});
};
// Load the SDK Asynchronously
(function(d){
var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/<?php if(isset($fb_user['locale'])){echo $fb_user['locale'];}else{echo'en_US';}?>/all.js";
d.getElementsByTagName('head')[0].appendChild(js);
}(document));
</script>
<fb:like href="http://www.google.com" send="false" width="450" show_faces="true"></fb:like> | unknown | |
d13094 | train | If eval throws stackoverflow, you can use this
http://code.google.com/p/json-sans-eval/
A JSON parser that doesn't use eval() at all.
A: I have written json parsers that are not recursive in several languages, but until now not in javascript. Instead of being recursive, this uses a local array named stack. In actionscript this was substantially faster and more memory efficient than recursion, and I assume javascript would be similar.
This implementation uses eval only for quoted strings with backslash escapes, as both an optimization and simplification. That could easily be replaced with the string handling from any other parser. The escape handling code is long and not related to recursion.
This implementation is not strict in (at least) the following ways. It treats 8 bit characters as whitespace. It allows leading "+" and "0" in numbers. It allows trailing "," in arrays and objects. It ignores input after the first result. So "[+09,]2" returns [9] and ignores "2".
function parseJSON( inJSON ) {
var result;
var parent;
var string;
var depth = 0;
var stack = new Array();
var state = 0;
var began , place = 0 , limit = inJSON.length;
var letter;
while ( place < limit ) {
letter = inJSON.charCodeAt( place++ );
if ( letter <= 0x20 || letter >= 0x7F ) { // whitespace or control
} else if ( letter === 0x22 ) { // " string
var slash = 0;
var plain = true;
began = place - 1;
while ( place < limit ) {
letter = inJSON.charCodeAt( place++ );
if ( slash !== 0 ) {
slash = 0;
} else if ( letter === 0x5C ) { // \ escape
slash = 1;
plain = false;
} else if ( letter === 0x22 ) { // " string
if ( plain ) {
result = inJSON.substring( began + 1 , place - 1 );
} else {
string = inJSON.substring( began , place );
result = eval( string ); // eval to unescape
}
break;
}
}
} else if ( letter === 0x7B ) { // { object
stack[depth++] = state;
stack[depth++] = parent;
parent = new Object();
result = undefined;
state = letter;
} else if ( letter === 0x7D ) { // } object
if ( state === 0x3A ) {
parent[stack[--depth]] = result;
state = stack[--depth];
}
if ( state === 0x7B ) {
result = parent;
parent = stack[--depth];
state = stack[--depth];
} else {
// error got } expected state {
result = undefined;
break;
}
} else if ( letter === 0x5B ) { // [ array
stack[depth++] = state;
stack[depth++] = parent;
parent = new Array();
result = undefined;
state = letter;
} else if ( letter === 0x5D ) { // ] array
if ( state === 0x5B ) {
if ( undefined !== result ) parent.push( result );
result = parent;
parent = stack[--depth];
state = stack[--depth];
} else {
// error got ] expected state [
result = undefined;
break;
}
} else if ( letter === 0x2C ) { // , delimiter
if ( undefined === result ) {
// error got , expected previous value
break;
} else if ( state === 0x3A ) {
parent[stack[--depth]] = result;
state = stack[--depth];
result = undefined;
} else if ( state === 0x5B ) {
parent.push( result );
result = undefined;
} else {
// error got , expected state [ or :
result = undefined;
break;
}
} else if ( letter === 0x3A ) { // : assignment
if ( state === 0x7B ) {
// could verify result is string
stack[depth++] = state;
stack[depth++] = result;
state = letter;
result = undefined;
} else {
// error got : expected state {
result = undefined;
break;
}
} else {
if ( ( letter >= 0x30 && letter <= 0x39 ) || letter === 0x2B || letter === 0x2D || letter === 0x2E ) {
var exponent = -2;
var real = ( letter === 0x2E );
var digits = ( letter >= 0x30 && letter <= 0x39 ) ? 1 : 0;
began = place - 1;
while ( place < limit ) {
letter = inJSON.charCodeAt( place++ );
if ( letter >= 0x30 && letter <= 0x39 ) { // digit
digits += 1;
} else if ( letter === 0x2E ) { // .
if ( real ) break;
else real = true;
} else if ( letter === 0x45 || letter === 0x65 ) { // e E
if ( exponent > began || 0 === digits ) break;
else exponent = place - 1;
real = true;
} else if ( letter === 0x2B || letter === 0x2D ) { // + -
if ( place != exponent + 2 ) break;
} else {
break;
}
}
place -= 1;
string = inJSON.substring( began , place );
if ( 0 === digits ) break; // error expected digits
if ( real ) result = parseFloat( string );
else result = parseInt( string , 10 );
} else if ( letter === 0x6E && 'ull' === inJSON.substr( place , 3 ) ) {
result = null;
place += 3;
} else if ( letter === 0x74 && 'rue' === inJSON.substr( place , 3 ) ) {
result = true;
place += 3;
} else if ( letter === 0x66 && 'alse' === inJSON.substr( place , 4 ) ) {
result = false;
place += 4;
} else {
// error unrecognized literal
result = undefined;
break;
}
}
if ( 0 === depth ) break;
}
return result;
}
A: I recommend you to divide JSON string in chunks, and bring them on demand. May be using AJAX too, you can have a recipe that just fit your needs.
Using a "divide and conquer" mechanism, I think you can still use common JSON parsing methods.
Hope that helps,
A: JSON parsing in browser is usually done with just eval, but preceding the eval with a regular expression "lint", that is supposed to make it safe to evaluate the JSON.
There is an example on this on wikipedia:
*
*http://en.wikipedia.org/wiki/JSON#Security_issues | unknown | |
d13095 | train | If x is a data.frame object, it should work:
df <- data.frame(a = c(1,2,3), b = c(4,NA,6), c = c(NA, 8, NA))
df[is.na(df)] <- 0
> df
a b c
1 1 4 0
2 2 0 8
3 3 6 0 | unknown | |
d13096 | train | Treating texture units as levels in a tree and do a sorted depth-first traversal is a good starting point.
Ideally what you want to do is minimize the number of texture unit state changes which may mean that the same texture gets selected and deselected multiple times in the optimal case. You suggestion of sorting the tuples of texture IDs is a good idea as well. | unknown | |
d13097 | train | Ok, I've not given you exactly what you asked for but it can be modified as you see fit.
In this FIDDLE I use divs instead of ul/li, and I think they can be styled in any way you want.
There is a holder div, into which are added holders for each of your individual divs.
By changing maxheight, you can control how many lines go into each of your "slides".
var maxheight = 100;
var divlistnum = 0;
$('.holder').append("<div class='" + "slidelist" + divlistnum + "'></div>");
$('#clickme').click(function(){
$(".slidelist" + divlistnum ).append("<div class='littlelist'>Stuff to Add</div>");
if( $(".slidelist" + divlistnum).height() > maxheight )
{
divlistnum = divlistnum + 1;
$('.holder').append("<div class='" + "slidelist" + divlistnum + "'></div>");
}
}); | unknown | |
d13098 | train | What about:
onValueChange={(selected) => {
this.setState({selected});
this.state.eventOnChange();
}}
A: Component.setState() is asynchronous and may be locked on the second call while it is still doing the first.
Do the second call in a callback like this:
onValueChange=
{ (selected) => {
this.setState(
{category:selected},() => {this.filter();} // Add Functions That's you want to call.
)
}
}
A: Resolved with the following code:
<TextInput
style={{height: 40, width: 200, borderColor: 'gray', borderWidth: 1, }}
onChangeText={(text) => this.setState({
text
}, () => {
this._onChangeText();
})
}
autoCorrect={false}
underlineColorAndroid='rgba(0,0,0,0)'
value={this.state.text}
/>
Thanks to @pinewood.
A: onValueChange={(itemValue, itemIndex) => this.setState({id: itemValue}),this.getOtherFunction } | unknown | |
d13099 | train | You are not allowed to block the main thread if you want to run other things async.
Just have your setTimeout run like it does now, when it fires, calculate ABalance/ABuy. If Abalance/Abuy < 10, do nothing and wait for next setTimeout to fire. If not, do the rest. | unknown | |
d13100 | train | In this case you should use session cookie for exactly checking when Browser session is
opened - it is the idea behind the function.
What you are looking for is something called Persistent Login Cookie that is something similar to
"Remember me" functionality mostly used in login forms. Basically you
set encrypted login cookie on user's browser and then can use it for automatic authentication of user.
This answer on Stack Overflow may be helpful: Improved Persistent Login Cookie Best Practice | unknown |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.