id
stringlengths 5
11
| text
stringlengths 0
146k
| title
stringclasses 1
value |
|---|---|---|
doc_23525100
|
The test:
get user_path(@user1)
puts @response.body
assert_select "img[src*='profile.gif']", count: 2
puts @response.body confirms that the image is there twice as the body includes two times:
src="/assets/account/profile-3454be0beae***256dab6d.gif". Nevertheless the test fails.
Does anyone understand this? And how should I solve it?
A: Change seems to be related with rails 4 as stated in the Asset Pipeline documentation:
Rails 4 no longer sets default config values for Sprockets in test.rb,
so test.rb now requires Sprockets configuration. The old defaults in
the test environment are: config.assets.compile = true,
config.assets.compress = false, config.assets.debug = false and
config.assets.digest = false.
So if digests are not expected in the test environment it should be explicitly configured in the config/environments/test.rb file:
config.assets.digest = false
| |
doc_23525101
|
I have even ran SET GLOBAL max_allowed_packet within the server. After every method of changing this value, checking the variable('SHOW VARIABLES LIKE') after a MySQL restart always returns around 67000000, no matter what I set it to (which I would think is enough).
I've also tried changing the dependency versions.
Controller:
@Controller
public class PersonController{
@GetMapping(value = "/home")
public String getAllPeople(){
return "home";
}
}
Main (SQL command):
@SpringBootApplication
public class DemoApplication implements CommandLineRunner{
@Autowired
private JdbcTemplate jdbcTemplate;
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
String sql = "SELECT * FROM people";
int ans = jdbcTemplate.update(sql);
if(ans>0) System.out.println("new table created");
}
}
application.properties:
spring.datasource.url = jdbc:mysql://10.0.0.200:3333/test
spring.datasource.username = boss
spring.datasource.password = StrongPass123!
Pom.xml (relevant dependencies):
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.29</version>
</dependency>
Trace:
2022-06-29 19:44:04.268 ERROR 14664 --- [ main] com.zaxxer.hikari.pool.HikariPool : HikariPool-1 - Exception during pool initialization.
com.mysql.cj.jdbc.exceptions.PacketTooBigException: Packet for query is too large (4,739,923 > 65,535). You can change this value on the server by setting the 'max_allowed_packet' variable.
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:107) ~[mysql-connector-java-8.0.29.jar:8.0.29]
at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:828) ~[mysql-connector-java-8.0.29.jar:8.0.29]
at com.mysql.cj.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:448) ~[mysql-connector-java-8.0.29.jar:8.0.29]
...
| |
doc_23525102
|
What I'd like to see instead is to have some command that would take an output of diff -u -p (or have integration with VC modes so it could process svn diff etc) and to create all the skeleton entries at once.
For example, if svn status shows
D file1.c
M file2.c
A file3.c
the command would create
2009-09-05 My Name <my.email>
* file1.c: Removed.
* file2.c: WRITE YOUR CHANGES HERE
* file3.c: New.
Better yet, if it could parse the changed files in some languages to an extent so it could offer:
* file2.c (new_function): New function.
(deleted_function): Removed.
(changed_function): WRITE YOUR CHANGES HERE
I have found this feature in Emacs manual, but I don't see how I could apply it here.
Any suggestions? Thanks.
EDIT: One answer suggested vc-update-change-log. Unfortunately it only supports CVS and it creates ChangeLog entries by querying the already-commited VC logs. Thus even if it supported svn and others, it would be impossible to commit the changes and the ChangeLog in the same commit.
EDIT2: Apparently add-changelog-entry-other-window (C-x 4 a) works not only from visited file but from diff hunk involving that file too. (Source) This is almost what I am looking for. This together with elisp loop to iterate through all hunks should solve it.
A: There is a function vc-update-change-log that automatically generates change log entries from the version control log entries.
A: diff-add-change-log-entries-other-window is documented to do exactly what you mentioned in EDIT2:
diff-add-change-log-entries-other-window is an interactive compiled
Lisp function in `diff-mode.el'.
(diff-add-change-log-entries-other-window)
Iterate through the current diff and create ChangeLog entries.
I.e. like `add-change-log-entry-other-window' but applied to all hunks.
Unfortunately, it doesn't work very well for, say, new files: it doesn't even include the filenames of such files in the skeletal changelog entry.
You might have better luck with gcc's mklog script, which you can get from http://gcc.gnu.org/viewcvs/gcc/trunk/contrib/mklog.
A: I don't know of a function that does this, but it should be easy to implement. Basically, you want to
*
*get the changed files
*for each file, call add-change-log
"Find change log file, and add an entry for today and an item for this file.
Optional arg WHOAMI (interactive prefix) non-nil means prompt for user
name and email (stored in `add-log-full-name' and `add-log-mailing-address').
Second arg FILE-NAME is file name of the change log.
If nil, use the value of `change-log-default-name'.
Third arg OTHER-WINDOW non-nil means visit in other window.
Fourth arg NEW-ENTRY non-nil means always create a new entry at the front;
never append to an existing entry. Option `add-log-keep-changes-together'
otherwise affects whether a new entry is created.
Option `add-log-always-start-new-record' non-nil means always create a
new record, even when the last record was made on the same date and by
the same person.
The change log file can start with a copyright notice and a copying
permission notice. The first blank line indicates the end of these
notices.
Today's date is calculated according to `add-log-time-zone-rule' if
non-nil, otherwise in local time."
so the magic code is going to look something like
(apply 'make-magic-change-log-entry changed-files-list)
and make-magic-change-log-entry simply curries the add-change-log function so that the only argument is file-name — you set the other ones.
A: I've written a function to do something similar to what you were talking about. You can get the code at http://www.emacswiki.org/emacs/log-edit-fill
| |
doc_23525103
|
I got it to work fine in the API Explorer but the request it prints out is just the basic pieces without the context code to make it work, so I'm guessing I'm messing something up in the implementation of calling the ajax post command. Here's what I'm doing:
var myAccessToken = "blahblah"; //from oauth2, works fine for other calls
$.ajax({
type: "POST",
url: "https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&access_token=" + myAccessToken,
data: {
"snippet": {
"playlistId": "PLIjo1t8cDbpGhOJrgEgMGFMb-VtAus_x9",
"resourceId": {
"kind": "youtube#video",
"videoId": "KMGuyGY5gvY"
},
}
},
success: function(data, textStatus, request) {
console.log("in success of ajax call, data: ", data);
},
dataType: 'jsonp'
});
My current error is below. Not sure if I actually need a "filter selected" or if my syntax is just wrong somewhere.
Error 400:
domain: "youtube.parameter"
location: ""
locationType: "parameter"
message: "No filter selected."
reason: "missingRequiredParameter"
Any ideas to try?
A: I believe you're missing part: 'snippet', before your data resource.
A: I got it working, though I'm not positive exactly what part was the problem. I came across this example: https://code.google.com/p/youtube-api-samples/source/browse/yt-upload-javascript/index.js
which had an example that was doing almost the same thing as what I needed, and once I changed my syntax to be like that, it worked. Here's what I ended up with:
var accessToken = "blahblah";
var metadata = {
snippet: {
playlistId: "WL", //specifically works for WatchLater list,
//but a playlist ID can be used too
resourceId: {
kind: "youtube#video",
videoId: "eNAajAflpBQ"
},
}
};
$.ajax({
method: "POST",
url: "https://www.googleapis.com/youtube/v3/playlistItems?part=snippet",
data: JSON.stringify(metadata),
headers: {
Authorization: 'Bearer ' + accessToken
},
contentType: 'application/json',
}).done( function(data, textStatus, request) {
console.log("in success of ajax call, data: ", data);
});
Thanks to those who looked into it and gave suggestions!
A: Initially I requested SCOPES = 'https://www.googleapis.com/auth/youtube.readonly'
and according to this:
Authorization
This request requires authorization with at least one of
the following scopes (read more about authentication and
authorization).
Scope
https://www.googleapis.com/auth/youtubepartner
https://www.googleapis.com/auth/youtube
https://www.googleapis.com/auth/youtube.force-ssl
I was needed to request an additional SCOPE.
My insert looks like this:
let request = gapi.client.youtube.playlistItems.insert({
part: 'snippet',
resource: {
snippet: {
playlistId: 'PLAYLIST_ID',
resourceId: {
videoId: 'YOUTUBE_TRACK_ID,
kind: 'youtube#video'
}
}
}
})
request.execute(function (response) {
...
})
| |
doc_23525104
|
There is a One-To-One relationship between an Appartment and a Contract. They are not embedded.
A contract is not mandatory, so an Appartment may not have a contract.
A contract has a start and end-date, but they are not mandatory so one or both may be NULL.
*
*If there is no contract, it means the Appartment has a never ending contract.
*If the contract start is NULL, it means the contract has lasted from the dawn of days
*If the contract end is NULL, the contract is valid forever.
Basicly i'm sending an integer to my DAO. The integer indicates the year. The DAO should return all Appartments that was/is valid sometime during that year.
That means it should return:
*
*All Appartments without a contract
*All appartments with a startDate before or equal to this year, and NULL as endDate
*All Appartments with a endDate equal to or after this year, and NULL as startDate
*All Appartments with startDate equal or before this year and enddate equal or after this year.
So far i am unsure on how to handle the NULLs. And also how to compare the year to a date-field. Any help would be greatly appriciated.
I have gotten this far:
DetachedCriteria criteria = DetachedCriteria.forClass(Appartment.class)
.setFetchMode("contract", FetchMode.JOIN)
.createAlias("contract", "c")
.add(Restrictions.le("c.startDate", ????))
.add(Restrictions.ge("c.endDate", ????));
A: As for the null, you need to use the explicit NullExpression criterion, just like you would have used if you wrote direct SQL.
| |
doc_23525105
|
printf("%#d\n",15);
It seems to be ignored while printing. The output of the statement is:
15
A: I didn't come up with this answer myself. I just did a quick Google search and found this:
"Adding a # will cause a '0' to be prepended to an octal number (when using the o conversion specifier), or a 0x to be prepended to a hexadecimal number (when using a x conversion specifier). For most other conversion specifiers, adding a # will simply force the inclusion of a decimal point, even if the number has no fractional part."
You can read more here:
http://www.cprogramming.com/tutorial/printf-format-strings.html
A: You can look in the printf documentation. You can find the description for # under flags:
Used with o, x or X specifiers the value is preceded with 0, 0x or 0X
respectively for values different than zero. Used with e, E and f, it
forces the written output to contain a decimal point even if no digits
would follow. By default, if no digits follow, no decimal point is
written. Used with g or G the result is the same as with e or E but
trailing zeros are not removed.
| |
doc_23525106
|
I tried creating an UIPageViewController object, adding its view as subview of the current screen (self.view.addSubview(tutorialViewController.view)) and the screen is displayed, however when I swipe the UIPageViewController is not responding the event.
class TutorialViewController:UIPageViewController, UIPageViewControllerDataSource {
var tutorialsViewControllers = [UIViewController]()
override func viewDidLoad() {
super.viewDidLoad()
tutorialsViewControllers.append(Tutorial1ViewController())
tutorialsViewControllers.append(Tutorial2ViewController())
tutorialsViewControllers.append(Tutorial3ViewController())
tutorialsViewControllers.append(Tutorial4ViewController())
tutorialsViewControllers.append(Tutorial5ViewController())
self.setViewControllers([tutorialsViewControllers.first!], direction: .Forward, animated: false) { (complete) -> Void in
}
self.dataSource = self
}
func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? {
if let position = find(self.tutorialsViewControllers, viewController)
where position > 0
{
return self.tutorialsViewControllers[position - 1]
}
return nil
}
func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController?{
if let position = find(self.tutorialsViewControllers, viewController)
where position < self.tutorialsViewControllers.count - 1
{
return self.tutorialsViewControllers[position - 1]
}
return nil
}
}
That's the view controller code
let tutorialViewController = TutorialViewController()
self.view.addSubview(tutorialViewController.view)
A: Did you add the tutorialViewController as child view controller?
self.addChildViewController(tutorialViewController)
self.view.addSubview(tutorialViewController.view)
| |
doc_23525107
|
if ound some links for detecting on iphone/ipad mobile browsers using this link HTML5 video for iPhone / iPad. How to detect connection speed?
but is it possible for desktop windows bandwidth
| |
doc_23525108
|
ERR (3): exception 'Exception' with message 'Requested and configured
user@domain.com merchant emails do not match.' in
/home/user/public_html/app/code/core/Mage/Paypal/Model/Ipn.php:257
Based on my reading of the code:
*
*The "configured merchant email" comes from the Magento configuration
*The empty "Requested merchant email" comes from the receiver_email
field in the PayPal IPN message.
Why would the IPN message have an empty receiver_email field? I can make several guesses:
*
*Protocol error from PayPal's service.
*Configuration error in the PayPal.com account.
*Magento bug resulting in empty or corrupt data.
*Network problem resulting in empty or corrupt data.
Which is more likely, and how can I narrow it down?
It appears to be related to an adjustment transaction. A few odd things:
*
*The referenced order was paid by credit card, not Paypal Express.
*The referenced order was adjusted months ago.
*This latest transaction is missing from the order comment history.
I suspect this is a code or protocol error. The transaction POST data is below with identifiers obscured to protect the innocent.
Array
(
[txn_type] => adjustment
[payment_date] => 12:17:03 Jul 20, 2015 PDT
[payment_gross] => -64.45
[mc_currency] => USD
[verify_sign] => ...
[payer_status] => verified
[payer_email] => seller@address.com
[txn_id] => ...
[parent_txn_id] => ...
[payer_id] => ...
[invoice] => 123456789
[reason_code] => chargeback_settlement
[payment_status] => Completed
[payment_fee] => -20.00
[mc_gross] => -64.45
[charset] => windows-1252
[notify_version] => 3.8
[ipn_track_id] => ...
)
A: In my case the issue was the configured email was not the primary email set on my paypal account. So, paypal was sending the default email account (which was different) as the requested email. After setting the configured email as the primary email address in paypal the issue seems to have been fixed.
A: I think this is a Magento bug. For chargebacks the merchant is actually the "payer". That is why in this case the address can be found in the payer_email field. The _verifyOrder method will have to be adjusted accordingly.
A: In my case the error happened after changing the primary email in the PayPal admin panel.
When changing the primary email in PayPal you need to generate new API credentials since it looks like the credential are based on the primary email at the moment of its generation.
Once you remove the old API credentials and generate new ones, update the credentials in Magento (Stores > Configuration > Sales > Payment Methods > PayPal Express Checkout), flush the cache and the problem should be gone.
| |
doc_23525109
|
Here is an example script:
x = open("file.txt", "r+").read().split("\n")
for i in x:
print(something)
where something = I don't know. I want the output to be what the first line of the text file says, then what the second line says, and so on except print the second/third/fourth... line over the first line and each line is an unknown length, some shorter than others. Lets say the file.txt says:
Overflow
Stack
I would want it to print "Overflow" then "Stack", except each word gets printed on the first line and once you print "Stack", every part of "Overflow" can't be seen
Keep in mind that print("Hello World", end="\r") won't work because of the length.
A: You could work around the \r solution by padding each line with spaces according to the previous line:
prev_size = 0
with open("file.txt", "r+") as f:
for line in f:
print(f"{line.strip()}{' '*prev_size}", end='\r')
prev_size = len(line)
You would probably want to add a sleep between prints to be able to actually see the text changing...
A: When you use the print function in python, you're just pushing characters onto a pipe somewhere (the pipe might be connected to the standard out, but your program doesn't know that). Once its, pushed, there is nothing you can do to un-push it. Afterall, the pipe might not even be connected to a screen. It might be directly connected to the input of another program, or it might be using a physical printer for display. What would un-pushing even mean in those cases?
There are, however, special control characters (such as the "backspace" character) that you push to the pipe to signal that you want to erase characters. However, The terminal you are connected to is free to do what it wants with these characters. It can respect your wishes and erase characters, or it can print the literal '\b' characters to indicate a backspace, or it can completely ignore you and continue to print after the previous letters. That's completely out of your control.
Assuming the terminal that print the characters supports overwriting the characters, you can use the ANSI control sequences. The sequence for moving cursor to beginning of line is '\033[1G' and for erasing the everything from current cursor position to end of line is '\033[0K'. So,
import time
print('hello world', end='', flush=True) # prints "hello world" with no newline at the end
time.sleep(2) # wait 2 seconds
print('\033[1G\033[0K', end='') # moves cursor to beginning of line and erases the line
print('hi') # prints "hi" with newline at the end
flush=True is needed because the print function is buffered by default and doesn't actually print anything until it hits a newline. This tells the function you want to flush the buffer immediately.
Take a look at ANSI escape codes, section on "CSI sequences" to see what other codes are available.
| |
doc_23525110
|
raise NotImplementedError("The database backend only supports "
NotImplementedError: The database backend only supports count() queries.
The main page works, but I get that error whenever I click any of the login links. Any help would be greatly appreciated!
The full text of the error is below (I shortened some of the directories). Thank you so much in advance for any help.
Environment:
Request Method: GET
Request URL: http://localhost:8080/login/google-oauth2/
Django Version: 1.4.3
Python Version: 2.7.6
Installed Applications:
('django.contrib.admin',
'django.contrib.contenttypes',
'django.contrib.auth',
'django.contrib.sessions',
'djangotoolbox',
'autoload',
'dbindexer',
'httplib2',
'openid',
'oauth2',
'social_auth',
'djangoappengine')
Installed Middleware:
('autoload.middleware.AutoloadMiddleware',
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware')
Traceback:
File "C:\Program Files (x86)\Google\google_appengine\lib\django-1.4\django\core\handlers\base.py" in get_response
188. response = middleware_method(request, response)
File "C:\Program Files (x86)\Google\google_appengine\lib\django-1.4\django\contrib\sessions\middleware.py" in process_response
36. request.session.save()
File "C:\Program Files (x86)\Google\google_appengine\lib\django-1.4\django\contrib\sessions\backends\cached_db.py" in save
42. super(SessionStore, self).save(must_create)
File "C:\Program Files (x86)\Google\google_appengine\lib\django-1.4\django\contrib\sessions\backends\db.py" in save
51. session_key=self._get_or_create_session_key(),
File "C:\Program Files (x86)\Google\google_appengine\lib\django-1.4\django\contrib\sessions\backends\base.py" in _get_or_create_session_key
145. self._session_key = self._get_new_session_key()
File "C:\Program Files (x86)\Google\google_appengine\lib\django-1.4\django\contrib\sessions\backends\base.py" in _get_new_session_key
139. if not self.exists(session_key):
File "C:\Program Files (x86)\Google\google_appengine\lib\django-1.4\django\contrib\sessions\backends\cached_db.py" in exists
39. return super(SessionStore, self).exists(session_key)
File "C:\Program Files (x86)\Google\google_appengine\lib\django-1.4\django\contrib\sessions\backends\db.py" in exists
27. return Session.objects.filter(session_key=session_key).exists()
File "C:\Program Files (x86)\Google\google_appengine\lib\django-1.4\django\db\models\query.py" in exists
565. return self.query.has_results(using=self.db)
File "C:\Program Files (x86)\Google\google_appengine\lib\django-1.4\django\db\models\sql\query.py" in has_results
441. return bool(compiler.execute_sql(SINGLE))
File ".\app project directory\dbindexer\compiler.py" in execute_sql
24. return super(SQLCompiler, self).execute_sql(*args, **kwargs)
File ".\app project directory\djangotoolbox\db\basecompiler.py" in execute_sql
364. raise NotImplementedError("The database backend only supports "
Exception Type: NotImplementedError at /login/google-oauth2/
Exception Value: The database backend only supports count() queries.
| |
doc_23525111
|
private static bool OnlyNumbersAllowed(string text)
{
Regex regex = new Regex("[^0-9]+");
return !regex.IsMatch(text);
}
private void PreviewTextInputHandlerInt(object sender, TextCompositionEventArgs e)
{
e.Handled = !OnlyNumbersAllowed(e.Text);
}
While in the main window i want to access this code, like:
<TextBox Name="Par5" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="357,36,0,0" Width="120"
PreviewTextInput="{DynamicResource PreviewTextInputHandlerInt}"/>
Which won't work (the resource could not be resolved).
Also, I did some changes in dictionary root element, like:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="network_app.Resources.ResDictionary"
x:ClassModifier="public">
I have access to this event handler from many other windows in my project, that's why I don't want to copy the code of event handler all over these windows in code-behind. Is it possible somehow to access my event handler, declared in resource dictionary? Thanks.
A: Ok, I made this by adding this thing into resourcedictionary.xaml:
<ControlTemplate x:Key="TextBoxInt">
<TextBox PreviewTextInput="PreviewTextInputHandlerInt"/>
</ControlTemplate>
Then I accessed this in main window xaml like this:
<TextBox Template="{StaticResource TextBoxInt}" Name="Par5" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="357,36,0,0" Width="120" />
| |
doc_23525112
|
Is there a way to check if the video was played for a certain duration? Or is it possible to disable forwarding?
This is my code currently:
<ReactPlayer
onEnded={() => setVideoEnded(true)}
url={
"https://...server.net/NodeUploadServer/public/" +
course.video
}
width="100%"
height="100%"
controls={true}
/>
<Button disabled={!videoEnded} >
Go to test
</Button>
A: Here are two possible solutions to your question:
Use a custom player UI
The first solution is to remove the default player controls which is rendering the timeline component. However, with this solution, you will need to create your custom UI.
Keep track of the played time
The react-native player does have an event to publish the elapsed time, but this isn't what you are looking for.
If you are using the HTML5 Video player, you could leverage the played property and verify if the video has been played a certain range.
If not, you will have to keep track of the time played using an interval or using the timeupdate event.
| |
doc_23525113
|
A: Purpose
I think the purpose using cgitb is to get the whole information from web browser to help debugging.So we sholud correct the problem, not avoid the problem.
Do some research
Let us have a look at the information:
AH02429: Response header name '<!--' contains invalid characters, aborting request
It indicates the header name contains invalid characters, so i do some research on cgitb.py code as follow:
def reset():
"""Return a string that resets the CGI and browser to a known state."""
return '''<!--: spam
Content-Type: text/html
<body bgcolor="#f0f0f8"><font color="#f0f0f8" size="-5"> -->
<body bgcolor="#f0f0f8"><font color="#f0f0f8" size="-5"> --> -->
</font> </font> </font> </script> </object> </blockquote> </pre>
</table> </table> </table> </table> </table> </font> </font> </font>'''
This function returns the characters <!--. But apache httpd treat it as response header name which should not contain <!--.
There is also a open issue8704 in the Issue Tracker of python.
Maybe not a good solution
I do not know the should we delete the code in cgitb.py or adjust the configration of apache httpd. My solution is deleting some code as follows:
return '''
<body bgcolor="#f0f0f8"><font color="#f0f0f8" size="-5"> -->
<body bgcolor="#f0f0f8"><font color="#f0f0f8" size="-5"> --> -->
</font> </font> </font> </script> </object> </blockquote> </pre>
</table> </table> </table> </table> </table> </font> </font> </font>'''
Then it works very well, and it has good view.Anyone know what is the situation in ngix?
A: The answers from @eorochena and @dogacan are special cases. In general:
You get this error if an exception is raised in a Python CGI script.
A good way of figuring out what went wrong is to invoke Python's CGI module debug helper function at the beginning of your CGI script like this:
cgitb.enable(display=0, logdir=OUTDIR)
where OUTDIR is a directory name. If your CGI scripts raises some exception, then Apache puts an HTML file into that directory. The file has some garbage name such as tmpw4olz3xr.html, and at its end it contains the Python stack trace enclosed within HTML comments (<!-- ... -->). This is the information that will help you fix the problem.
Notes:
*
*The display=0 parameter means that the error details are not shown
in the browser to your users.
*You should probably comment out
cgitb.enable(...) when you are sure your script works OK.
A: In my case the problem was the way the aligment of the output from the print statement
Before:
try:
if <some-condition>
message = "%s" % filename
else:
message = "file not found"
print """\n
Content-Type: text/html\n
<html><body>
<p>%s</p>
</body></html>
""" % (message,)
except Exception as e:
print e
After:
try:
if <some-condition>:
message = "%s" % filename
else:
message = "file not found"
print """\
Content-Type: text/html\n
<html><body>
<p>%s</p>
</body></html>
""" % (message,)
except Exception as e:
print e
A: For the same error, in a similar printing case, it was due to database collation; changing it to a UTF-8 helped me.
| |
doc_23525114
|
A: I did some research and it seems that is not possible. See this answer from Get preferred screen brightness in Android.
I also tried this code:
int brightnessValue = Settings.System.getInt(
getContentResolver(),
Settings.System.SCREEN_BRIGHTNESS,
0
);
But it always returns the non-automatic brightness.
| |
doc_23525115
|
If I use socat as
socat -u open:test.ts udp:localhost:1234
sleep 0.001
It correctly sends the contents of the file on that socket and I can listen to that port in my client application to analyze transport stream packets. Now, I want my application to support multicast as well.For that, I use something like
socat -u open:test.ts udp:239.48.208.1:1234
sleep 0.001
and listen to that multicast address on my application. I receive nothing. Since I know that multicast address is valid within my firewall, I am assuming this is an issue of socat not sending any packets in the first place. So, I believe this is not the correct way to send file contents over network using socat.
It does not have to be an MPEG-2 stream though. I just want to know how to multicast contents of a binary file on a specific multicast address and port.
A: I have not tried this, but there are many detailed examples on dest-unreach.org by Gerhard Rieger, the author of socat. The first example is of a multicast client and several receiving servers on a common network 192.168.10.*. The client 192.168.10.1 sends to a multicast address, and the receiving
servers may send response packets. On any of the servers, e.g. 192.168.10.2, we have
socat UDP4-RECVFROM:6666,ip-add-membership=224.1.0.1:192.168.10.2,fork EXEC:hostname
which means receive multicasts to 224.1.0.1, and fork a process for each packet. The process (eg hostname) can send one or more reply packets back. 192.168.10.2 is the interface to receive on (so differs on each server); see the socat man page for ip-add-membership.
On the sending client we have
socat STDIO UDP4-DATAGRAM:224.1.0.1:6666,range=192.168.10.0/24
which sends data from stdin to be multicast. It will print any received replies.
| |
doc_23525116
|
Have simple test case
tl <- list()
tl[['a']][['aa']] <- list(1,2,3)
tl[['a']][['bb']] <- 'b'
tl[['a']][['cc']] <- list('a','b','c','d')
bl <- list()
bl[['bb']] <- 'b'
bl[['aa']] <- list(1,2,3)
bl[['cc']] <- list('a','b','c','d')
cl <- list()
cl[['a']][['bb']] <- 'b'
cl[['a']][['aa']] <- list(1,2,3)
cl[['a']][['cc']] <- list('a','b','c','d')
dl <- list()
dl[['bb']] <- 'b'
dl[['aa']] <- list(1,2,3)
dl[['cc']] <- list('a','b','c','d')
nl <- list()
nl[['a']] <- dl
The lists tl, bl, and nl are as I expect. However list cl gives the following error: Error in cl[["b"]][["aa"]] <- list(1, 2, 3) :
more elements supplied than there are to replace.
R is constructing different a different type of list when it is assigned an atomic sublist before attempting to assign a list() sublist.
A: The "problem" is the default behavior of [[<-. This is a generic operator that does different things depending on what type of object you use it on. It's not exclusively used for lists. Consider this example
x <- NULL
x[["b"]] <- 'c'
# str(x)
# Named chr "c"
# - attr(*, "names")= chr "b"
Here x is defined as NULL. In this case, x[["b"]] turns x into a named vector (not a list). That's because R had no idea you wanted x to be a list so it just chose the most simple data type it could.
Assigning to a named slot and expecting a container to be automatically instantiation is called autovivification and languages like Perl really love that, it's not really a core concept in R. If you need a list where never there was a list before, be sure to explicitly created it.
cl <- list()
cl[['a']] <- list()
cl[['a']][['bb']] <- 'b'
cl[['a']][['aa']] <- list(1,2,3)
cl[['a']][['cc']] <- list('a','b','c','d')
| |
doc_23525117
|
I'm getting data from backend. Purpose is to dynamically parse forms with validations
Issue:
My validation accessors are returned as string, I need them to be Classes.
Question: How to escape quotation marks dynamically? (Dynamically, because I'm getting an array of validation objects)
What I'm getting:
What I need:
| |
doc_23525118
|
I'm developing an app with the new Android 5.0 Material-styled sliding tabs with new AppCompat Tab bar.
What I want:
I want to put an image behind the bar and the tabs like Play Kiosko. Any solution for this would be grateful.
Kiosko App Design:
You can see the image behind that pager tab strip!
| |
doc_23525119
|
class ViewController: UIViewController {
deinit {
print("ViewController deinitialised")
}
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
self.tableView.dataSource = self
}
func didTapBlue() {
}
}
extension ViewController: UITableViewDataSource, CustomCellDelegate {
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 5
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("myCell") as! CustomCell
cell.delegate = self
cell.textLabel!.text = "\(indexPath.row)"
return cell
}
func buttonTapped() {
print("Button tapped")
}
}
CustomCell Code
class CustomCell: UITableViewCell {
deinit {
print("Cell deinitialised")
}
var delegate: CustomCellDelegate! //When protocol Type is A
// weak prefix when protocol Type is B
// weak var delegate: CustomCellDelegate!
@IBAction func buttonClickAction(sender: AnyObject) {
if let del = self.delegate {
del.buttonTapped()
}
}
}
Protocol Type A
protocol CustomCellDelegate{
func buttonTapped()
}
Protocol Type B
protocol CustomCellDelegate: class {
func buttonTapped()
}
I am confused about what is the appropriate way to implement delegate pattern for passing message between Cell And ViewController. I know that if two objects hold each other's reference strongly, there will be a retain cycle and they won't get deallocated in the application lifetime.
In the above code, ViewController doesn't seem to hold reference of Cell. Hence I think it doesn't matter if I use protocol of type A and keep the strong reference of ViewController in cell.
But will my code be any safer if I declare the delegate property as a weakly referenced property? What are the implications of it?
Update:
Turns out that even if the ViewController is not holding direct reference of cell & even if TableView's reference is weak, ViewController is somehow holding strong reference to the cells. When I follow Method A, that is without declaring the delegate to be of weak reference. The deinit methods in Cell and ViewController never gets called. I checked in instruments too. The persistent retain count keeps increasing if I don't declare delegate as weak.
Now the big question is how is ViewController holding strong reference to the cells?
A: There are a couple things going on there.
*
*Making every ViewController conform to UITableViewDelegate and UITableViewDatasource is needless since you already have UITableViewController and you'll probably need to override those methods anyway. You would be duplicating code at some point in your development lifecycle.
*delegates always need to be a weak reference to avoid retain cycles.
A: Deinitialization Process:
When the view controller is popped out.
Then deinit method is called.
Then only all the other references that view controller is holding is cleared.
Parents deinit triggers, child's deinit triggers then after all the deinit is traversed through then deallocation of parent is done finally at last.
If any of the child is strongly referencing the parent. The deinit of parent never gets called and all the deinitialization process halts. In our case, since cell is retaining view controller strongly. The deinit method of ViewController never gets called. Hence The retain cycle.
Here is great explanation for retain cycle.
| |
doc_23525120
|
CONFIGURATION:
HTML charset: windows-1250
DB charset / collation: cp1250 COLLATE cp1250_czech_cs (I cant use UTF-8 because I need proper CZECH collation, case sensivity, etc.)
PROBLEM:
Sometimes I need to store to my database special char like greek letter, or <tag>. How to set up the process of storing values from HTML forms to DB and vice versa + displaying values so that there will be no html entities in DB and in forms or when displaying there will be always the real character (not the entity).
Thanks 4 any advice.
A: Your question has no answer given the requirements because you need some way of escaping the unicode characters, and so you might just as well use html entiites and store them in the DB.
This would work well together with using the php filter functions and FILTER_SANITIZE_SPECIAL_CHARS on inputs.
If you don't like that, use Unicode in the DB.
| |
doc_23525121
|
Here is my situations:
(1)I have n ODE equations to solve, coupled together. The number of ODEs, or n, is not constant. It is dynamically changing.
(2) Here are ODEs:
dx_1/dt = a_1*x_1+b_1*y_1+b_2*y_2+......+b_n*y_n+c_1
dy_1/dt=b_{11}*(x_1-y_1)+b_{12}*(z_1-y_1)+b_{13}
dy_2/dt=b_{21}*(x_{1}-y_{2})+b_{22}*(z_{2}-y_{2})+b_{23}
dy_3/dt=b_{31}*(x_{1}-y_{3})+b_{32}*(z_{3}-y_{3})+b_{33}
......
dy_n/dt=b_{n1}*(x_{1}-y_{n})+b_{n2}*(z_{n}-y_{n})+b_{n3}
dz_1/dt=c_{11}*(x_1-z_1)+c_{12}*(z_1-y_1)+c_{13}
dz_2/dt=c_{21}*(x_1-z_2)+c_{22}*(z_2-y_2)+c_{23}
dz_3/dt=c_{31}*(x_1-z_3)+c_{32}*(z_3-y_3)+c_{33}
......
dz_n/dt=c_{n1}*(x_{1}-z_{n})+c_{n2}*(z_{n}-y_{n})+c_{n3}
def model(state, y, t, (a1, a2, ...) ):
// how do I program those equations here with changing number of ODES???
| |
doc_23525122
|
My problem is, that when gitlab has an absolute link to itself, it links always to https://gitlab/. This host also can be seen in the "New group" dialog:
Docker call:
docker run \
--name git \
--net mydockernet \
--ip 172.18.0.2 \
--hostname git.mydomain.com \
--restart=always \
-p 766:22 \
-v /docker/gitlab/config:/etc/gitlab \
-v /docker/gitlab/logs:/var/log/gitlab \
-v /docker/gitlab/data:/var/opt/gitlab \
-d \
gitlab/gitlab-ce:latest
gitlab.rb:
external_url 'https://git.mydomain.com'
ci_nginx['enable'] = false
nginx['listen_port'] = 80
nginx['listen_https'] = false
gitlab_rails['gitlab_shell_ssh_port'] = 766
Nginx config:
upstream gitlab {
server 172.18.0.2;
}
server {
listen 443 ssl http2;
listen [::]:443 ssl http2;
server_name git.mydomain.com;
ssl on;
ssl_certificate /etc/ssl/certs/mydomain.com.chained.pem;
ssl_certificate_key /etc/ssl/private/my.key;
location / {
proxy_pass http://gitlab/;
proxy_read_timeout 10;
}
}
I tried to replace the wrong url wit nginx. This worked for the appearance like in the screen shot, but not for the links:
sub_filter 'https://gitlab/' 'https://$host/';
sub_filter_once off;
A: You've set your url correctly in your mapped volume /etc/gitlab/gitlab.rb
external_url 'https://git.mydomain.com'
Run sudo gitlab-ctl reconfigure for the change to take effect.
A: Problem solved. It was in the nginx reverse proxy config. I named the upstream "gitlab" and somehow this name found it's way into the web pages:
upstream gitlab {
server 172.18.0.2;
}
...
proxy_pass http://gitlab/;
I didn't expect that. I even omitted the upstream part in my original question because I thought the upstream name is just an internal name and will be replaced by the defined ip.
So the fix for me is, to write the full domain into the upstream:
upstream git.mydomain.com{
server 172.18.0.2;
}
...
proxy_pass http://git.mydomain.com/;
| |
doc_23525123
|
I am getting invalid database error while trying to use the ORM Composer from github .
The error is like :
You have specified an invalid database connection group (test) in your config/database.php file.
But in config/database.php i have given it clearly. Please help me on that.
| |
doc_23525124
|
ALL_CONFIGS: {callDigitalIo=true, controllerId=1, numberPlatesHashSalt=..., numberPlatesShouldBeHashed=false, parkingStatusShouldBeChecked=true}
Where boolean params should be displayed like input element with type=checkbox.
Here is how I handle it on UI page (.ftl):
<div>
<label class="col-form-label">
Parking Status Should Be Checked:
<input type="checkbox" class="form-check-input ml-2"
id="parkingStatusShouldBeChecked" name="parkingStatusShouldBeChecked"
<#if parkingStatusShouldBeChecked??>checked="checked"</#if>
/>
</label>
</div>
However, checkboxes are all selected:
Number Plates Should be Hashed should not be selected.
How to select only true variables?
A: After huge research I found solution for this issue:
<div>
<label class="col-form-label">
Parking Status Should Be Checked:
<input type="checkbox" class="form-check-input ml-2"
id="parkingStatusShouldBeChecked"
<#if parkingStatusShouldBeChecked == "true">checked</#if>
/>
</label>
</div>
It works fine.
A: Assuming that parkingStatusShouldBeChecked is a boolean, this way works too:
<input type="checkbox" class="form-check-input ml-2"
id="parkingStatusShouldBeChecked" name="parkingStatusShouldBeChecked"
${parkingStatusShouldBeChecked?string('checked','')} />
The first parameter is the "true" expression, so FreeMarker prints checked. Otherwise it prints just an empty string.
See https://freemarker.apache.org/docs/ref_builtins_boolean.html#ref_builtin_string_for_boolean
| |
doc_23525125
|
<ul>
<li>one</li>
<li>two</li>
<li>three</li>
<li id="right">right?</li>
</ul>
li {
display: inline-block;
margin: 0;
padding: 2px;
}
ul {
width: 300px;
list-style: none;
margin: 0;
padding: 0;
}
li#right {
text-align: right;
}
It does not work so I guess I am misunderstanding something fundamentally. But what?
There is a fiddle here: http://jsfiddle.net/lborgman/b22g7/
A: You can absolutely position the last element to achieve what you want without having to apply any clearfix to correct issues caused by float.
ul {
width: 300px;
list-style: none;
margin: 0;
padding: 0;
position: relative;
}
li#right {
position: absolute;
right: 0px;
}
JSFiddle
A: text-align aligns the element's text to the right. Which it is doing. You just can't see it. If you had blah blah blah<br />blah in that <li> you'd see the alignment clear as day.
If you want the <li> itself to be on the right, try using float:right but keep in mind that you may need to move it to be the first one.
A: Here's one way to do it:
http://jsfiddle.net/b22g7/6/
HTML:
<div class="container">
<ul>
<li>one</li>
<li>two</li>
<li>three</li>
<li id="right">right?</li>
</ul>
</div>
CSS:
.container {
overflow: auto;
}
ul {
width: 300px;
list-style: none;
margin: 0;
padding: 0;
background: #ff3;
}
li {
float: left;
border: solid 1px blue;
margin: 0;
padding: 2px;
}
li#right {
float: right;
}
A: You meant float: right; instead of text-align.
text-align will just align the text 'within' the li
A: Just add li:last-child{float:right;} and remove the id, you don't need it
| |
doc_23525126
|
A: Not THE answer...but changing to use IE makes it work...
It might be because it is slower to load
However IE doesn't make the test folders visible like Chrome does so cannot debug in IE.
| |
doc_23525127
|
Driver code is :
self._chartFigure.update_layout(
updatemenus=[
super().reverse_colorScale(self),
super().reverse_axis(self,
x=self._chartTypeObject.__getitem__("y"),
y=self._chartTypeObject.__getitem__("x"))
])
i tried this code : but its not rendering anything after click , so not sure whether its possible or not
def reverse_axis(self, x, y):
return dict(
buttons=list([
dict(args=[{"x": y, "y": x, "xbin.size": 0.2, "xbin.start": 0,"ybins.size": 1, "ybins.start": 0}],
label="Switch X to Y",
method="restyle"
),
dict(args=[{"x": x, "y": y,"xbin.size": 1, "xbin.start": 0, "ybins.size": 0.2, "ybins.start": 0}],
label="Switch Y to X",
method="update"
)
]),
type="dropdown",
direction="right",
showactive=True,
x=0.13,
y=1.065,
xanchor="center",
yanchor="bottom"
)
Before Click :
Ater Click :
A: here is answer which works if any one else is looking for it
def reverse_axis(self, x, y):
return dict(
buttons=list([
dict(args=[{"x": [list(y)], "y": [list(x)], "xbin.size": 0.2, "xbin.start": 0,"ybins.size": 1, "ybins.start": 0}],
label="Switch X to Y",
method="restyle"
),
dict(args=[{"x": [list(x)], "y": [list(y)],"xbin.size": 1, "xbin.start": 0, "ybins.size": 0.2, "ybins.start": 0}],
label="Switch Y to X",
method="update"
)
]),
type="dropdown",
direction="right",
showactive=True,
x=0.13,
y=1.065,
xanchor="center",
yanchor="bottom"
)
| |
doc_23525128
|
when I add a new site, all seem to work correctly, I have a message that says that the site has been successfully created but when I click on the visit link I get a 404 error.
Moreover, nothing seems to be created in my files although it takes a pretty long time to create the new site.
I'm probably missing something but I have no idea of what I can do now, so thanks for your help!
A: Okay, i did this kind of things before. here are the tips to follow you debug:
before we start, We assume your multisite network is setup successfully.
setting up adding new site
1.Go to login main site wp-admin, which will lead you to network wp-admin then you can
create new site by the build in wizard.
2.by creating a new site, it also auto create a set of cloned tables in your multisite shared Database
such as using diff prefix other than the default "wp_" for example the "wp_2_" , "wp_3_" etc by default. If you are not sure, just go phpmyadmin and see the changes and decide which table prefix you want to use.
3.creating new site don't mean creating files in the sub site path, you need to copy paste your wordpress files into the path you created.
4.You also need to change the .htaccess & wp-config of the new sub site properly , in wp-config, don't forget to point correct wordpress table prefix (such as "wp_2_") of your new created site.
5.Go to the "option" table of your new created site (such as wp_2_option) to check whether the themes, the site_url, home_url etc are configured properly, otherwise you might see blank page when visiting your subsite path. (noted this setting also can be done in network wp-admin panel)
6.update database and login wp-admin to enable all deactivated plugins (as multisite will auto deactivate them initially so you may see a lot of error messages when plugin is not activated first.)
7.usually, after successfully creating the new sub site, you also need to do a proper table content migration to your new created site's tables, as because the new wordpress table created by multisite wp-admin panel only contains basic informations which can not display the whole features of the site you expected to display.
(do the sql migration just like you do in other single site wordpress migration, but using differnt table prefix. so you may find and replace urls/strings of the sql manually. )
A: If just adding a new site via admin, and your installation is ok, steps 1 and 2 (in first answer) should suffice, check the extra database tables have been created in step 2, if that's not happened, something is awry with your installation, and I would suggest that's the first issue to resolve. You shouldn't have to look at .htaccess, wp-config.php, etc if everything is setup ok to simply add new sites.
| |
doc_23525129
|
FROM fluentd:v1.14.0-debian-1.0
USER root
RUN ["gem", "install", "fluent-plugin-elasticsearch", "--no-document", "--version", "5.1.2"]
USER fluent
From which I create a container in my compose file:
version: '3'
services:
fluentd:
build: ./fluentd
volumes:
- ./fluentd/conf:/fluentd/etc
links:
- "elasticsearch"
restart: always
container_name: fluentd
ports:
- "24224:24224"
- "24224:24224/udp"
networks:
- network
elasticsearch:
image: docker pull amazon/opendistro-for-elasticsearch:latest
container_name: elasticsearch
environment:
- cluster.name=elasticsearch
- node.name=elasticsearch
- discovery.seed_hosts=elasticsearch
- cluster.initial_master_nodes=elasticsearch
- bootstrap.memory_lock=true # along with the memlock settings below, disables swapping
- "ES_JAVA_OPTS=-Xms512m -Xmx512m" # minimum and maximum Java heap size, recommend setting both to 50% of system RAM
ulimits:
memlock:
soft: -1
hard: -1
nofile:
soft: 65536 # maximum number of open files for the Elasticsearch user, set to at least 65536 on modern systems
hard: 65536
volumes:
- elasticsearch:/usr/share/elasticsearch/data
ports:
- 9200:9200
- 9600:9600 # required for Performance Analyzer
networks:
- network
kibana:
image: docker pull amazon/opendistro-for-elasticsearch-kibana:latest
container_name: odfe-kibana
ports:
- 5601:5601
expose:
- "5601"
environment:
ELASTICSEARCH_URL: https://elasticsearch:9200
ELASTICSEARCH_HOSTS: https://elasticsearch:9200
networks:
- network
volumes:
elasticsearch:
networks:
network:
driver: bridge
name: network
And this is my fluent.conf
<source>
@type forward
port 24224
bind 0.0.0.0
</source>
<match *.**>
@type copy
<store>
@type elasticsearch
host elasticsearch
port 9200
user admin
password admin
logstash_format true
logstash_prefix fluentd
logstash_dateformat %Y%m%d
include_tag_key true
type_name access_log
tag_key @log_name
scheme https
ssl_verify false
</store>
<store>
@type stdout
</store>
</match>
For some reason the elasticsearch and the kibana start without issues, yet fluentd cannot connect. This is the error I am getting
*
2021-11-04 16:47:35 +0000 [error]: #0 /usr/lib/ruby/gems/2.7.0/gems/fluent-plugin-elasticsearch-5.1.2/lib/fluent/plugin/elasticsearch_index_template.rb:52:in `retry_operate'
fluentd | 2021-11-04 16:47:35 +0000 [error]: #0 /usr/lib/ruby/gems/2.7.0/gems/fluent-plugin-elasticsearch-5.1.2/lib/fluent/plugin/out_elasticsearch.rb:487:in `handle_last_seen_es_major_version'
fluentd | 2021-11-04 16:47:35 +0000 [error]: #0 /usr/lib/ruby/gems/2.7.0/gems/fluent-plugin-elasticsearch-5.1.2/lib/fluent/plugin/out_elasticsearch.rb:339:in `configure'
fluentd | 2021-11-04 16:47:35 +0000 [error]: #0 /usr/lib/ruby/gems/2.7.0/gems/fluentd-1.14.0/lib/fluent/plugin.rb:187:in `configure'
fluentd | 2021-11-04 16:47:35 +0000 [error]: #0 /usr/lib/ruby/gems/2.7.0/gems/fluentd-1.14.0/lib/fluent/plugin/multi_output.rb:110:in `block in configure'
fluentd | 2021-11-04 16:47:35 +0000 [error]: #0 /usr/lib/ruby/gems/2.7.0/gems/fluentd-1.14.0/lib/fluent/plugin/multi_output.rb:99:in `each'
fluentd | 2021-11-04 16:47:35 +0000 [error]: #0 /usr/lib/ruby/gems/2.7.0/gems/fluentd-1.14.0/lib/fluent/plugin/multi_output.rb:99:in `configure'
fluentd | 2021-11-04 16:47:35 +0000 [error]: #0 /usr/lib/ruby/gems/2.7.0/gems/fluentd-1.14.0/lib/fluent/plugin/out_copy.rb:39:in `configure'
fluentd | 2021-11-04 16:47:35 +0000 [error]: #0 /usr/lib/ruby/gems/2.7.0/gems/fluentd-1.14.0/lib/fluent/plugin.rb:187:in `configure'
fluentd | 2021-11-04 16:47:35 +0000 [error]: #0 /usr/lib/ruby/gems/2.7.0/gems/fluentd-1.14.0/lib/fluent/agent.rb:132:in `add_match'
fluentd | 2021-11-04 16:47:35 +0000 [error]: #0 /usr/lib/ruby/gems/2.7.0/gems/fluentd-1.14.0/lib/fluent/agent.rb:74:in `block in configure'
fluentd | 2021-11-04 16:47:35 +0000 [error]: #0 /usr/lib/ruby/gems/2.7.0/gems/fluentd-1.14.0/lib/fluent/agent.rb:64:in `each'
fluentd | 2021-11-04 16:47:35 +0000 [error]: #0 /usr/lib/ruby/gems/2.7.0/gems/fluentd-1.14.0/lib/fluent/agent.rb:64:in `configure'
fluentd | 2021-11-04 16:47:35 +0000 [error]: #0 /usr/lib/ruby/gems/2.7.0/gems/fluentd-1.14.0/lib/fluent/root_agent.rb:149:in `configure'
fluentd | 2021-11-04 16:47:35 +0000 [error]: #0 /usr/lib/ruby/gems/2.7.0/gems/fluentd-1.14.0/lib/fluent/engine.rb:105:in `configure'
fluentd | 2021-11-04 16:47:35 +0000 [error]: #0 /usr/lib/ruby/gems/2.7.0/gems/fluentd-1.14.0/lib/fluent/engine.rb:80:in `run_configure'
fluentd | 2021-11-04 16:47:35 +0000 [error]: #0 /usr/lib/ruby/gems/2.7.0/gems/fluentd-1.14.0/lib/fluent/supervisor.rb:716:in `block in run_worker'
fluentd | 2021-11-04 16:47:35 +0000 [error]: #0 /usr/lib/ruby/gems/2.7.0/gems/fluentd-1.14.0/lib/fluent/supervisor.rb:968:in `main_process'
fluentd | 2021-11-04 16:47:35 +0000 [error]: #0 /usr/lib/ruby/gems/2.7.0/gems/fluentd-1.14.0/lib/fluent/supervisor.rb:708:in `run_worker'
fluentd | 2021-11-04 16:47:35 +0000 [error]: #0 /usr/lib/ruby/gems/2.7.0/gems/fluentd-1.14.0/lib/fluent/command/fluentd.rb:372:in `<top (required)>'
fluentd | 2021-11-04 16:47:35 +0000 [error]: #0 /usr/lib/ruby/2.7.0/rubygems/core_ext/kernel_require.rb:83:in `require'
fluentd | 2021-11-04 16:47:35 +0000 [error]: #0 /usr/lib/ruby/2.7.0/rubygems/core_ext/kernel_require.rb:83:in `require'
fluentd | 2021-11-04 16:47:35 +0000 [error]: #0 /usr/lib/ruby/gems/2.7.0/gems/fluentd-1.14.0/bin/fluentd:15:in `<top (required)>'
fluentd | 2021-11-04 16:47:35 +0000 [error]: #0 /usr/bin/fluentd:23:in `load'
fluentd | 2021-11-04 16:47:35 +0000 [error]: #0 /usr/bin/fluentd:23:in `<main>'
fluentd | 2021-11-04 16:47:35 +0000 [info]: Worker 0 finished unexpectedly with status 1
fluentd | 2021-11-04 16:47:43 +0000 [info]: adding match pattern="*.**" type="copy"
fluentd | 2021-11-04 16:47:45 +0000 [error]: #0 unexpected error error_class=Elasticsearch::UnsupportedProductError error="The client noticed that the server is not a supported distribution of Elastic
*
*
I am not sure if the plugin used for fluentd to connect to elasticsearch is eligible to also connect to OpenDistro for elasticsearch. If any other information is needed please ask.
Any help would be much appreciated.
A: the problem is that the plugin works with lower version of elasticsearch, after refactoring my docker file everything worked as a charm:
FROM fluentd:v1.14.0-debian-1.0
USER root
RUN gem install elasticsearch -v 7.13.3 \
&& gem install fluent-plugin-elasticsearch --no-document
USER fluent
A: Use stable latest versions of plugins elasticsearch and fluent-plugin-elasticsearch.
My worked Dockerfile for example:
FROM fluent/fluentd:v1.12.0-debian-1.0
USER root
RUN ["gem", "install", "elasticsearch", "--no-document", "--version", "7.13.3"]
RUN ["gem", "install", "fluent-plugin-elasticsearch", "--no-document", "--version", "5.0.5"]
USER fluent
A: I was testing the connection with an elasticsearch 7.10.2 server
I removed the fluentd plugins with recentd version to 8.x and install the plugins for the version I'm using (7)
This section help me to debug the issue
RUN fluent-gem uninstall --force fluent-plugin-elasticsearch
RUN fluent-gem uninstall --force elasticsearch
RUN fluent-gem uninstall --force elastic_ruby_console
RUN fluent-gem uninstall -a --force elasticsearch-api
RUN fluent-gem uninstall -a --force elastic-transport
RUN fluent-gem uninstall -a --force elasticsearch-xpack
RUN fluent-gem install elasticsearch -v 7.10
RUN fluent-gem install fluent-plugin-elasticsearch
A: it is work
version: '3.7'
services:
fluentd:
image: cr.fluentbit.io/fluent/fluent-bit
| |
doc_23525130
|
If anyone know how to create a button like this please let me know bellow.
I tried much times but nothing worked properly.
This is what I've done so far :
jsfiddle.net/dzk6uj7e/74/
Best regards,
A: A button consists of 8 lines which are html elements that are 1px tall or wide. It's not that difficult:
body {
background-color: #444444;
}
.fancybutton {
width: 200px;
height: 80px;
position: absolute;
cursor: pointer;
}
.line {
position: absolute;
width: 1px;
height: 1px;
background-color: white;
transition: .5s;
opacity: 0.6;
}
.v1 {
left: 0;
top: 40px;
height: 70px;
margin: -35px 0;
}
.v2 {
left: 5px;
top: 40px;
height: 80px;
margin: -40px 0;
}
.v3 {
right: 5px;
top: 40px;
height: 80px;
margin: -40px 0;
}
.v4 {
right: 0;
top: 40px;
height: 70px;
margin: -35px 0;
}
.h1 {
left: 100px;
top: 0;
width: 190px;
margin: 0 -95px;
}
.h2 {
left: 100px;
top: 5px;
width: 200px;
margin: 0 -100px;
}
.h3 {
left: 100px;
bottom: 5px;
width: 200px;
margin: 0 -100px;
}
.h4 {
left: 100px;
bottom: 0;
width: 190px;
margin: 0 -95px;
}
.buttontext {
position: absolute;
left: 10px;
right: 10px;
top: 10px;
bottom: 10px;
color: white;
line-height: 60px;
font-size: 13px;
font-family: Arial, sans-serif;
letter-spacing: 1.5px;
text-align: center;
transition: .5s;
}
.fancybutton:hover .buttontext {
background-color: white;
color: #222222;
box-shadow: 0 0 30px rgba(255, 255, 255, 0.5);
}
.fancybutton:hover .v1, .fancybutton:hover .v4 {
margin: 0;
height: 0;
opacity: 1;
}
.fancybutton:hover .v2, .fancybutton:hover .v3 {
height: 70px;
margin: -35px 0;
opacity: 1;
}
.fancybutton:hover .h1, .fancybutton:hover .h4 {
margin: 0;
width: 0;
opacity: 1;
}
.fancybutton:hover .h2, .fancybutton:hover .h3 {
width: 190px;
margin: 0 -95px;
opacity: 1;
}
<div class="fancybutton">
<div class="line vertical v1"></div>
<div class="line vertical v2"></div>
<div class="line vertical v3"></div>
<div class="line vertical v4"></div>
<div class="line horizontal h1"></div>
<div class="line horizontal h2"></div>
<div class="line horizontal h3"></div>
<div class="line horizontal h4"></div>
<div class="buttontext">FANCY BUTTON</div>
</div>
| |
doc_23525131
|
k <- c(1,2,3)
a <- rep(apply(expand.grid(k, k), 1, prod), each=3)
a
[1] 1 1 1 2 2 2 3 3 3 2 2 2 4 4 4 6 6 6 3 3 3 6 6 6 9 9 9
This vector should be aligned in a block matrix of the form:
rbind(
cbind(diag(a[1:3]), diag(a[4:6]), diag(a[7:9])),
cbind(diag(a[10:12]), diag(a[13:15]), diag(a[16:18]) ),
cbind(diag(a[19:21]), diag(a[22:24]), diag(a[25:27]) )
)
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9]
[1,] 1 0 0 2 0 0 3 0 0
[2,] 0 1 0 0 2 0 0 3 0
[3,] 0 0 1 0 0 2 0 0 3
[4,] 2 0 0 4 0 0 6 0 0
[5,] 0 2 0 0 4 0 0 6 0
[6,] 0 0 2 0 0 4 0 0 6
[7,] 3 0 0 6 0 0 9 0 0
[8,] 0 3 0 0 6 0 0 9 0
[9,] 0 0 3 0 0 6 0 0 9
Now this is of course a small and simple example and I would like to do this for much larger vectors/matrices. Thus my question: Is there a general way to align a vector in a block matrix of certain form (without looping)?
A: Instead of manually doing the split, we can use %/%
k <- 3
lst <- split(a, (seq_along(a)-1)%/%k + 1)
do.call(rbind, lapply(split(lst, (seq_along(lst)-1) %/% k + 1),
function(x) do.call(cbind, lapply(x, function(y) diag(y)))))
# [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9]
# [1,] 1 0 0 2 0 0 3 0 0
# [2,] 0 1 0 0 2 0 0 3 0
# [3,] 0 0 1 0 0 2 0 0 3
# [4,] 2 0 0 4 0 0 6 0 0
# [5,] 0 2 0 0 4 0 0 6 0
# [6,] 0 0 2 0 0 4 0 0 6
# [7,] 3 0 0 6 0 0 9 0 0
# [8,] 0 3 0 0 6 0 0 9 0
# [9,] 0 0 3 0 0 6 0 0 9
A: An alternative using the Kronecker product on a slightly different vector is as follows.
# create initial vector
aNew <- rep(1:3, 3) * rep(1:3, each=3)
aNew
[1] 1 2 3 2 4 6 3 6 9
Note that aNew is the unique values of the vector a in the same order, that is, it is equivalent to unique(a). Convert aNew into a 3X3 matrix and then perform the Kronecker product against it and the 3X3 identity matrix.
matrix(aNew, 3, 3) %x% diag(3)
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9]
[1,] 1 0 0 2 0 0 3 0 0
[2,] 0 1 0 0 2 0 0 3 0
[3,] 0 0 1 0 0 2 0 0 3
[4,] 2 0 0 4 0 0 6 0 0
[5,] 0 2 0 0 4 0 0 6 0
[6,] 0 0 2 0 0 4 0 0 6
[7,] 3 0 0 6 0 0 9 0 0
[8,] 0 3 0 0 6 0 0 9 0
[9,] 0 0 3 0 0 6 0 0 9
| |
doc_23525132
|
I originally got an array of structs working but when changing the array of structs into an array of struct pointers I get a segmentation fault when trying to assign or access values of the structs by dereferencing.
I like to know what I am doing wrong.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct s{
int a;
char *b;
int c;
int d;
}s;
s** readStruct(){
FILE *f = fopen("file.csv", "r");
if(!f){
printf("Can't open file\n");
exit(1);
}
//An array of struct pointers of size 50
s **x = (s **)malloc(50 * sizeof(s *));
char str[60];
int i = 0;
//Loop through each line of the file while !EOF
//copy each line to string for tokenizing
while(fgets(str, 60, f)){
char *tok = strtok(str, ",/n");
// segmentation fault happens here:
x[i]->a = atoi(tok);
// also happens here too:
printf("%d\n", x[i]->a);
tok = strtok(NULL, tok);
// segmentation fault would result here:
strcpy(x[i]->b, tok);
tok = strtok(NULL, ",\n");
// and here:
x[i]->c = atoi(tok);
tok = strtok(NULL, ",\n");
// and here:
x[i]->d = atoi(tok);
i++;
}
return x;
}
int void main(){
s **x = readStruct();
for(int i = 0; (x + i) < NULL; i++){
printf("%d\n", x[idx]->a);
printf("%s\n", x[idx]->b);
printf("%d\n", x[idx]->c);
printf("%d\n", x[idx]->d);
printf("\n");
}
return 0;
}
A: You allocated the space for the array, but not for each individual struct that the pointers in the array point to:
while(fgets(str, 60, f)){
char *tok = strtok(str, ",/n");
a[i] = malloc( sizeof( s ) );
//...
Other notes:
*
*In C, you should not cast the result of malloc().
*Since you are reusing the delimiter string, it would be good to store that in a variable (const char* delim = ",\n") instead of retyping the same sequence. It helps to prevent errors, like typing ",/n", when you mean ",\n" which you did.
| |
doc_23525133
|
I have two sub-domains; CRM and Accounting. The customer concept needs to be modeled differently in the two sub-domains. CRM needs to know the size (number of employees) of the company but not the tax number. Accounting needs to know the tax number but not the size. The company name is needed by both sub-domains.
I am thinking of modeling both CRM Customer and Accounting Customer as entities. But then whenever a new customer is created by a CRM user, an Accounting Customer instance also needs to be created. And if a report needs information from both sub-domains, then the queries become more complicated then when you have single entity containing all the information.
Is this the way to go? Is there a better way? Does it make sense to have multiple sub-domains without utilizing domain events?
A: Are you sure you need DDD? The use case seems quite simple, maybe you just left out all the other complexities, but from just the info you're asking, a simple CRUD app would do. Data Centric apps, like reporting, don't need DDD. You need DDD when you must modify the data in strict ways, to maintain consistency.
If you are sure you do need DDD, then you need to understand the point of the model is to protect against the invariants of the domain. You say a CRM Customer must always have an equivalent Accounting Customer. How is this handled by the business today? How does accounting know about CRM customers? How does accounting know they're talking about the same customer as CRM? However they are doing it currently, is what you should try to model.
As an example, if they do it in real life by just letting the other one know. You could have your CRM context publish a new Customer event, and your Accounting context could react to it by creating an Accounting Customer for it.
If on the other hand, they both learn about it from something else, then maybe they both react to that other something's event.
If you don't want to use events, it could be a direct call, from the CRM context to the Accounting context. Though know that this would grow more restricted as the app grows, but if again you've got a simple domain, its no problem.
Also, querying data is not the same as modifying it. Queries should not use the domain model entities and value objects. It could, but it should not be constrained by it. That's because query is a read only operation. You need to put your data inside your domain model only when you are going to change it.
| |
doc_23525134
|
I have not made any other change to the app code. To test, I have set very high ecpm for FAN on admob page so that the ads should be served first from FAN and not admob.
To test, I installed my modified app on the phone that already had facebook app installed. Now, I only see admob test ads and no facebook ads.
When I test only facebook ads, I have this message :
[FBAudienceNetworkLog/FBAdProvider:135 <error>] Ad request error: Error Domain=com.facebook.ads.sdk Code=1001 "No fill" UserInfo=0x174a7d480 {
NSLocalizedDescription=No fill,
FBAdErrorDetailKey = {
msg = "No fill. We are not able to serve ads to this person. Please refer to https://developers.facebook.com/docs/audience-network/faq#a12. If you are integrating Audience Network for the first time, you can use test ads https://developers.facebook.com/docs/audience-network/testing.";
}
}
My status on facebook profile for this placement is: Activated
I don't understand why I have this message.
Please advise.
A: Even if the ad is activated does not mean it will always display an ad.
*
*You need to have the Facebook app installed and you need to be logged in.
*You have to disable Limit Ad Tracking in the system settings
*Even then it might just not have an ad available.
A: It works perfectly on middle east app users , as Facebook is a mainly app there.
It has lower fill rate in USA.
| |
doc_23525135
|
df =
result
0 -43.859440
1 -20.000000
2 63.666667
3 116.500000
4 -22.333333
5 12.500000
6 -103.705882
7 322.800000
8 -513.888889
9 774.000000
10 -4508.000000
I want to produce another column called count consisting element 1 if a value in corresponding row result is >0 and -1 if less than zero.
My current code:
df['count'] = [1 if df['result']>0 else -1 if df['result']>-1]
My present output:
SyntaxError: invalid syntax
My expected output:
df =
result count
0 -43.859440 -1
1 -20.000000 -1
2 63.666667 1
3 116.500000 1
.
.
What could be wrong in my present code?
A: You can use np.where(). See below:
import numpy as np
df['count'] = np.where(df['result']>0,1,0)
| |
doc_23525136
|
Here is the relevant code so far:
<script>
$(document).ready(function() {
$("button").click(function() {
$("h1").text("Heading 2");
$("p").text("blah blah blah");
$("#picture").attr({ src: "../img/img2.jpg", title: "a new image", alt: "descriptive picture"});
$("button").text("Change back");
});
});
</script>
<body>
<h1>Heading 2</h1>
<img src="../img/img1.jpg" alt="basic picture" id="picture">
<p>Blah blah blah</p>
<button>Next</button>
</body>
A: You can store the initial values in data-attributes. Just did an example Fiddle with an additional div as wrapper to store the state and added the initial values as default data values, e.g. like this: <h1 data-default="Heading 1">Heading 1</h1>.
$("button").click(function () {
if ($(".container").data("state") == "default") {
$("h1").text("Heading 2");
$("p").text("blah blah blah");
$("#picture").attr({
src: "../img/img2.jpg",
title: "a new image",
alt: "descriptive picture"
});
$(".container").data("state", "changed");
$("button").text("Change back");
} else {
$("h1").text($("h1").data("default"));
$("p").text($("p").data("default"));
$("#picture").attr({
src: $("#picture").data("defaultImg"),
title: $("#picture").data("defaultTitle"),
alt: $("#picture").data("defaultAlt")
});
$(".container").data("state", "default");
$("button").text($("button").data("default"));
}
});
To avoid the double entries for the initial values, it's also possible to set the initial values of each element as data-attribute value when the button is clicked first. Adjusted Fiddle with the adjustment to set the initial value for the div-wrapper to "start" and the adjusted script:
$("button").click(function () {
if ($(".container").data("state") == "start") {
$("h1").data("default", $("h1").text());
$("img").data("defaultAlt", $("img").attr("alt"));
$("img").data("defaultTitle", $("img").attr("title"));
$("img").data("defaultImg", $("img").attr("src"));
$("p").data("default", $("p").text());
$("button").data("default", $("button").text());
}
if ($(".container").data("state") != "changed") {
.... // rest stays the same as in first script
For reference: http://api.jquery.com/jquery.data/
A: Try this Fiddle
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<h1>Heading 2</h1>
<img src="http://home.iitk.ac.in/~amitkum/images/4.jpg" alt="basic picture" id="picture" height="100">
<p>Blah blah blah</p>
<button>Next</button>
</body>
<script>
var img = 'http://home.iitk.ac.in/~amitkum/dp.jpg';
$(document).ready(function() {
$("button").click(function() {
tmp = $('#picture').attr('src');
$("h1").text("Heading 2");
$("p").text("blah blah blah");
$("#picture").attr({
src: img,
title: "a new image",
alt: "descriptive picture"
});
img = tmp;
$("button").text("Change back");
});
});
</script>
| |
doc_23525137
|
<FlatList
removeClippedSubviews
numColumns={1}
{...{ data }}
extraData={this.state}
renderItem={object => renderItem(object)}
/>
It, of course, works fine with the below function.
function renderItem(object) {
return <Text>Test</Text>;
}
However, when adding React Hooks, such that:
function renderItem(object) {
const [foo, setFoo] = useState("bar");
return <Text>{foo}</Text>;
}
RN returns:
Hooks can only be called inside the body of a function component.
Hooks work elsewhere in the codebase, so it's not a package mismatch issue.
Any help greatly appreciated.
A: You cannot call hooks inside functional component. You can instead convert functions to functional components
<FlatList
removeClippedSubviews
numColumns={1}
{...{ data }}
extraData={this.state}
renderItem={object => <TextComponent item={object} />}
/>
function TextComponent ({item}) {
const [foo, setFoo] = useState("bar");
return <Text>{foo}</Text>;
}
A: It is one of the rules when you work with hooks, You can't declare a hook, like this.
You must declare the hook in your top level. If you do this, React can't understand that this is a hook.
Here are the rules which you need to follow while working with hooks
https://reactjs.org/docs/hooks-rules.html
A: The reason your renderItem example didn’t work is because the function was neither capitalized nor starting with use. This is not special javascript, just a convention defined by the React team. If you change to function RenderItem you won’t get the hook error. renderItem is a component because it takes in data and returns JSX, it just needs to be appropriately capitalized to use hooks.
Then you can do renderItem={RenderItem}.
| |
doc_23525138
|
A: shouldComponentUpdate life cycle method do this what you want. Lets say this is our App component
import React from 'react';
import Counter from './Counter';
import './style.css';
class App extends React.Component {
constructor() {
super();
this.state = {
appValue: 0,
};
}
render() {
return (
<Counter
appValue={this.state.appValue}
updateHandler={() => {
this.setState({ appValue: this.state.appValue + 1 });
console.log('appValue update: ', this.state.appValue);
}}
/>
);
}
}
export default App;
We use Counter component where we pass appValue and updateHandler as props. And in the Counter component, we render two values - Counter's own state value and appValue which is received as prop. Here is the Counter component:
import React from 'react';
class Counter extends React.Component {
constructor() {
super();
this.state = {
counterValue: 0,
};
}
shouldComponentUpdate(prevProps, prevState) {
if (prevState.counterValue !== this.state.counterValue) {
return true;
} else {
return false;
}
}
render() {
console.log('Inside render of Counter Component');
return (
<>
<div>
<h1>Counter Value: {this.state.counterValue}</h1>
<button
onClick={() => {
this.setState({ counterValue: this.state.counterValue + 1 });
}}
>
Update Counter Value
</button>
</div>
<div>
<h1>App Value: {this.props.appValue}</h1>
<button onClick={this.props.updateHandler}>Update App Value</button>
</div>
</>
);
}
}
export default Counter;
As you notice, when we click the Update App Value button - appValue will increase but won't show the updated value, that means Counter component won't re-render because of prop changing.
And when we click the Update Counter Value button - counterValue will increase and Counter component will re-render as-usual. We will see the updated appValue also.
This will happen because of condition checking inside shouldComponentUpdate life cycle method. To understand more clearly, notice the console.
Here is a little bit about shouldComponentUpdate life cycle method:
The shouldComponentUpdate is a lifecycle method in React. This method makes the component to re-render only when there is a change in state or props of a component and that change will affect the output.
The shouldComponentUpdate() is invoked before rendering an already mounted component when new props or states are being received.
Syntax:
shouldComponentUpdate(nextProps, nextState)
| |
doc_23525139
|
A: Add the following to pom.xml:
<properties>
<maven.build.not.supported>
Do not use Maven to build this module. Please see README.html for
instructions on how to build it.
</maven.build.not.supported>
</properties>
<build>
<plugins>
<plugin>
<artifactId>maven-antrun-plugin</artifactId>
<executions>
<execution>
<id>fail-clean-lifecycle</id>
<phase>pre-clean</phase>
<configuration>
<tasks>
<fail message="${maven.build.not.supported}" />
</tasks>
</configuration>
<goals>
<goal>run</goal>
</goals>
</execution>
<execution>
<id>fail-default-lifecycle</id>
<phase>validate</phase>
<configuration>
<tasks>
<fail message="${maven.build.not.supported}" />
</tasks>
</configuration>
<goals>
<goal>run</goal>
</goals>
</execution>
<execution>
<id>fail-site-lifecycle</id>
<phase>pre-site</phase>
<configuration>
<tasks>
<fail message="${maven.build.not.supported}" />
</tasks>
</configuration>
<goals>
<goal>run</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
Since we cannot apparently bind a plugin execution to multiple phases, we need to repeat the execution block three times, one for each of the built-in lifecycles (clean, default and site). To avoid duplication of the failure message, we store it in a Maven property and reuse that property in each execution. In each execution we bind to the first phase of the lifecycle to fail it immediately.
| |
doc_23525140
|
http://www.example.com?param=1|2|3|4|test¶m1=5|6
Regex used -
.*param=.*\|(\w+)\|.*
The output I get is "4".
I have even tried this to no avail -
.*param=.*\|(.*?)\|.*
Any help is much appreciated.
Thanks
A: You need to make the first .* non-greedy:
param=.*?\|(\w+)\|
or make it not match a pipe:
param=[^|]*\|(\w+)\|
A: Using you regex, simply add a ? after .* to capture as less characters as possible :
.*param=.*?\|(\w+)\|.*
A: \|(\w+)\|
Try this .See demo.
http://regex101.com/r/rQ5jJ3/1
| |
doc_23525141
|
thanks
2021-07-15 08:47:59,466 [DE][Receiving message '<200,{"data":{"returnCode":"00"}},[Expires:"-1", Cache-Control:"no-cache,no-store,must-revalidate", Access-Control-Allow-Headers:"Accept-Encoding, Accept, Content-Type, tsec, consumerrequestid, authenticationchallenge, authenticationtype, authenticationdata, authenticationstate, contactid, consumeruuid, consumerapplicationid, perimetertsec, authorization, responsewarningcode, responsewarningdescription, cuf, prefer, phoneNumber, Location, X-RHO-PARENTSPANID, X-RHO-TRACEID, preferredauthenticationtype, X-HTTP-Method-Override, Access-Control-Allow-Methods, iv-remote-address, thirdparty-x-forwarded-for, thirdparty-user-agent, thirdparty-geolocation, thirdparty-calculated-scoring, thirdparty-deviceid, vnd.bbva.security-client-certificate, order-preferredaction, authenticationresponse, Access-Control-Max-Age, BCS-Device-Id, BCS-Device-OS-Name, BCS-Device-Model-Name, BCS-Device-Model-Manufacturer, BCS-Device-Screen-Size, BCS-Device-OS-Version, BCS-Device-DPI, BCS-Device-App-Name, BCS-Device-App-Version, Third-Party-Application-Id, ECS-Signature-Platform-Use-Case, BCS-Process-Code, BCS-Operation-Tracer, BCS-Process-Tracer, order-preferredaction, order-id, order-accepteddisclaimers", X-XSS-Protection:"1; mode=block", Pragma:"no-cache", Referrer-Policy:"same-origin", Content-Security-Policy:"script-src 'self'", Date:"Thu, 15 Jul 2021 06:47:59 GMT", Connection:"keep-alive", Strict-Transport-Security:"max-age=31536000; includeSubDomains", Transfer-Encoding:"chunked", Access-Control-Allow-Methods:"GET, POST, DELETE, PUT, OPTIONS, PATCH", old-catalog:"true", X-Frame-Options:"sameorigin", Access-Control-Expose-Headers:"Accept-Encoding, Accept, Content-Type, tsec, consumerrequestid, authenticationchallenge, authenticationtype, authenticationdata, authenticationstate, contactid, consumeruuid, consumerapplicationid, perimetertsec, authorization, responsewarningcode, responsewarningdescription, cuf, prefer, phoneNumber, Location, X-RHO-PARENTSPANID, X-RHO-TRACEID, preferredauthenticationtype, X-HTTP-Method-Override, Access-Control-Allow-Methods, iv-remote-address, thirdparty-x-forwarded-for, thirdparty-user-agent, thirdparty-geolocation, thirdparty-calculated-scoring, thirdparty-deviceid, vnd.bbva.security-client-certificate, order-preferredaction, authenticationresponse, Access-Control-Max-Age, BCS-Device-Id, BCS-Device-OS-Name, BCS-Device-Model-Name, BCS-Device-Model-Manufacturer, BCS-Device-Screen-Size, BCS-Device-OS-Version, BCS-Device-DPI, BCS-Device-App-Name, BCS-Device-App-Version, Third-Party-Application-Id, ECS-Signature-Platform-Use-Case, BCS-Process-Code, BCS-Operation-Tracer, BCS-Process-Tracer, order-preferredaction, order-id, order-accepteddisclaimers", tsec:"eJxtlNmKq1gARX/lUq+hSo0zVBXE2Tgbx7w0Rz0O0TjH6eu7Grov96FfN", Access-Control-Allow-Origin:"*", consumerrequestid:"c580c0cd-4589-4156", X-Content-Type-Options:"nosniff", Content-Type:"application/json; charset=UTF-8"]>'
| |
doc_23525142
|
The issue occurs when the application is running in the background. The modal window properly appears above whatever application is running in the foreground, but when the user clicks the "Save" button, the rest of the application's windows also are made active. This is undesirable, as the user then has to click back to whatever app they were using. (Destroying the convenience of the NSStatusItem.) I'm displaying the modal window using:
[myWindow setFrame:finalRect display:YES animate:NO];
[myWindow setLevel:NSPopUpMenuWindowLevel];
[NSApp runModalForWindow:myWindow];
Is there any way to prevent clicks/events in my popup window from causing the rest of the application to become active? Or a way to let NSApp know that this particular panel shouldn't automatically activate the rest of the app? Thanks!
A: NSApp's beginModalSessionForWindow, runModalSession, endModalSession are methods you need.
Have a look here for example how to use it:
Creating a fully customized NSAlert
A: Instead of creating an NSWindow, create an NSPanel with the style NSNonactivatingPanelMask. You can then do the usual makeKeyAndOrderFront: and orderOut: to show/hide panel as needed.
A: A solution by Ken Thomases on the cocoa-dev list a couple years ago looks applicable here too:
[[NSApplication sharedApplication] hide:self];
[[NSApplication sharedApplication] performSelector:@selector(unhideWithoutActivation)
withObject:nil
afterDelay:0.05];
Which in theory tells the application to hide itself and unhide at the bottom of the window stack.
You could also intercept the mouse click event and use [NSApp preventWindowOrdering]
A: You can try something like:
...
if ([NSApp isHidden])
[myWindow makeKeyAndOrderFront:self];
else
[NSApp runModalForWindow:myWindow];
...
and when finish:
...
if ([NSApp isHidden])
[myWindow orderOut:self];
else
[NSApp stopModal];
...
| |
doc_23525143
|
I've got a very simple question to ask.
Given the code below, i would like to use moq to test if the return result is as expected.
public class FrameworkServices : IFrameworkServices
{
public ILoggingService getLogger()
{
return LoggingFactory.getInstance().Create(LoggingEnum.Log4Net);
}
where ILogginService is an interface, LoogingFactory is a class.
Please share with me on how to moq this. All kind help are very much appreciated.
A: You don't need a moq to check if a method returns as expected, just call the method and assert what you need, is a plain standard unit test. In the example you shown you can mock for example IFrameworkService and having getLogger returning a stub logger.
| |
doc_23525144
|
But the problem is that from this new class which i created when i try inflating or referencing any resource element at all, i get errors.
so my question is :
1. Is it impossible to refer to resources from classes that i create ?
2. Is there an error in my IDE(eclipse) or its just a java thing.
here's the secondary layout XML file and the class i created.
the java lines with * is where i have the errors.
when inflating "R.layout.song","R.id.song_artist" and "R.id.song_title"
import android.R;
import android.R.*;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.ArrayList;
public class SongAdapter extends BaseAdapter {
private ArrayList<Song> songs;
private LayoutInflater songInf;
public SongAdapter(Context c, ArrayList<Song>theSongs){
songs = theSongs;
songInf = LayoutInflater.from(c);
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return songs.size();
}
@Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LinearLayout songLay = (LinearLayout) songInf.inflate(R.layout.song,parent,false);*
TextView songView = (TextView)songLay.findViewById(R.id.song_title);*
TextView artistView = (TextView)songLay.findViewById(R.id.song_artist);*
Song currSong = songs.get(position);
songView.setText(currSong.getTitle());
artistView.setText(currSong.getArtist());
songLay.setTag(position);
return songLay;
}
}
the XML file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="5dp"
android:onClick="songPicked" >
<TextView
android:id="@+id/song_title"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#FFFFFF99"
android:textSize="20sp"
android:textStyle="bold"/>
<TextView
android:id="@+id/song_artist"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#FFFFFF99"
android:textSize="18sp"
android:textStyle="italic"/>
</LinearLayout>
the error description reads
"Description Resource Path Location Type
song_artist cannot be resolved or is not a field
song cannot be resolved or is not a field
line 46 Java Problem
song_title cannot be resolved or is not a field
"
thanks in advance.
A: What is R pointing at in your code?
It should point at something like your.package.name.R. If it is pointing to Android.R, it won't work. Remove import Android.R and import Android.R.*, then it should be OK.
A: You can hit Ctrl+Shift+O to organize your imports and if you still have a problem change Android.R to packageName.R and this should solve the problem.
| |
doc_23525145
|
# Database settings
Aisse.LocalHost=localhost
Aisse.LocalDataBase=mydb
Aisse.LocalPort=5432
Aisse.LocalUser=myuser
Aisse.LocalPasswd=mypwd
# My other app settings
Aisse.NumDir=../../data/Num
Aisse.NumMobil=3000
# Log settings
#Aisse.Trace_AppliTpv=blabla1.tra
#Aisse.Trace_AppliCmp=blabla2.tra
#Aisse.Trace_AppliClt=blabla3.tra
#Aisse.Trace_LocalDataBase=blabla4.tra
In particular, I want to get the value mydb from line
Aisse.LocalDataBase=mydb
So far, I have developed this
mydbname=$(echo "$my_conf_file.conf" | grep "LocalDataBase=" | sed "s/LocalDataBase=//g" )
that returns
mydb #Aisse.Trace_blabla4.tra
that would be ok if it did not return also the comment string.
Then I have also tryed
mydbname=$(echo "$my_conf_file.conf" | grep "Aisse.LocalDataBase=" | sed "s/LocalDataBase=//g" )
that retruns void string.
How can I get only the value that is preceded by the string "Aisse.LocalDataBase=" ?
A: Using sed
$ mydbname=$(sed -n 's/Aisse\.LocalDataBase=//p' input_file)
$ echo $mydbname
mydb
A: You can use
mydbname=$(sed -n 's/^Aisse\.LocalDataBase=\(.*\)/\1/p' file)
If there can be leading whitespace you can add [[:blank:]]* after ^:
mydbname=$(sed -n 's/^[[:blank:]]*Aisse\.LocalDataBase=\(.*\)/\1/p' file)
See this online demo:
#!/bin/bash
s='# Database settings
Aisse.LocalHost=localhost
Aisse.LocalDataBase=mydb
Aisse.LocalPort=5432
Aisse.LocalUser=myuser
Aisse.LocalPasswd=mypwd
# My other app settings
Aisse.NumDir=../../data/Num
Aisse.NumMobil=3000
# Log settings
#Aisse.Trace_AppliTpv=blabla1.tra
#Aisse.Trace_AppliCmp=blabla2.tra
#Aisse.Trace_AppliClt=blabla3.tra
#Aisse.Trace_LocalDataBase=blabla4.tra'
sed -n 's/^Aisse\.LocalDataBase=\(.*\)/\1/p' <<< "$s"
Output:
mydb
Details:
*
*-n - suppresses default line output in sed
*^[[:blank:]]*Aisse\.LocalDataBase=\(.*\) - a regex that matches the start of a string (^), then zero or more whiespaces ([[:blank:]]*), then a Aisse.LocalDataBase= string, then captures the rest of the line into Group 1
*\1 - replaces the whole match with the value of Group 1
*p - prints the result of the successful substitution.
A: You may use this sed:
mydbname=$(sed -n 's/^[^#][^=]*LocalDataBase=//p' file)
echo "$mydbname"
mydb
RegEx Details:
*
*^: Start
*[^#]: Matches any character other than #
*[^=]*: Matches 0 or more of any character that is not =
*LocalDataBase=: Matches text LocalDataBase=
A: I'm afraid you're being incomplete:
You mention you want the line, containing "LocalDataBase", but you don't want the line in comment, let's start with that:
A line which contains "LocalDataBase":
grep "LocalDataBase" conf.conf.txt
A line which contains "LocalDataBase" but who does not start with a hash:
grep "LocalDataBase" conf.conf.txt | grep -v "^ *#"
??? grep -v "^ *#"
That means: don't show (-v) the lines, containing:
*
*^ : the start of the line
* * : a possible list of space characters
*# : a hash character
Once you have your line, you need to work with it:
You only need the part behind the equality sign, so let's use that sign as a delimiter and show the second column:
cut -d '=' -f 2
All together:
grep "LocalDataBase" conf.conf.txt | grep -v "^ *#" | cut -d '=' -f 2
Are we there yet?
No, because it's possible that somebody has put some comment behind your entry, something like:
LocalDataBase=mydb #some information
In order to prevent that, you need to cut that comment too, which you can do in a similar way as before: this time you use the hash character as a delimiter and you show the first column:
grep "LocalDataBase" conf.conf.txt | grep -v "^ *#" | cut -d '=' -f 2 | cut -d '#' -f 1
Have fun.
| |
doc_23525146
|
public class EmailDetails
{
public string EmailAddress { get; set; }
public string EmailDisplayName { get; set; }
}
public List<EmailDetails> EmailInformation { get; set; }
[WebMethod]
public static List<EmailDetails> GetEmails()
{
List<EmailDetails> emailAddresses = new List<EmailDetails>();
//queries AD to pull all users
var search = new DirectorySearcher();
search.Filter = "(&(objectClass=user)(mail=*)(displayName=*))";
search.PageSize = 1000;
using (var results = search.FindAll())
{
foreach (SearchResult result in results)
{
emailAddresses.Add(new EmailDetails
{
EmailAddress = result.Properties["mail"][0].ToString(),
EmailDisplayName = result.Properties["displayName"][0].ToString()
});
}
}
//sort email address list alphabetically and return sorted list
List<EmailDetails> sortedEmailAddresses = emailAddresses.OrderBy(o => o.EmailDisplayName).ToList();
return sortedEmailAddresses;
So my dilemma is, I am trying to find a way to speed up the process of the drop-down being loaded with the returned list. What would be the best way to achieve this? Memory cache? I am open to any options that you all deem reasonable...
A: https://msdn.microsoft.com/en-us/library/94xkskdf.aspx store it in the Application. It gets cleaned every time you recycle the application pool, stays up the rest of the time. Nothing fancy, does the job.
[WebMethod]
public static List<EmailDetails> GetEmails()
{
if(HttpContext.Current.Application["sortedEmailAddresses"]==null) {
List<EmailDetails> emailAddresses = new List<EmailDetails>();
//queries AD to pull all users
var search = new DirectorySearcher();
search.Filter = "(&(objectClass=user)(mail=*)(displayName=*))";
search.PageSize = 1000;
using (var results = search.FindAll())
{
foreach (SearchResult result in results)
{
emailAddresses.Add(new EmailDetails
{
EmailAddress = result.Properties["mail"][0].ToString(),
EmailDisplayName = result.Properties["displayName"][0].ToString()
});
}
}
//sort email address list alphabetically and return sorted list
List<EmailDetails> sortedEmailAddresses = emailAddresses.OrderBy(o => o.EmailDisplayName).ToList();
HttpContext.Current.Application["sortedEmailAddresses"] = sortedEmailAddresses;
}
return HttpContext.Current.Application["sortedEmailAddresses"] as List<EmailDetails>;
}
| |
doc_23525147
|
**function changeTitle()
{
*var titleClass = document.getElementsByClassName("changeTitle");*
var newTitle = nameElement.value;
document.getElementByClassName("KpiTitle").innerHTML += newTitle;
}
{
// Update KPI title
$(document).bind('keypress', function (changeTitle) {
if (changeTitle.keyCode == 13) {
$('#changeTitle').trigger('click');
}
});
};**
| |
doc_23525148
|
<?php
require "/root/vendor/autoload.php";
set_time_limit( 0 );
function print_time( $id ) {
while( true ) {
print( $id );
sleep( 1 );
}
}
class Threaded_upload extends Thread {
public function __construct( $args ) {
$this->args = $args;
}
public function run() {
print_time( $this->args );
}
}
$thread_1 = new Threaded_upload( "1" );
$thread_1->start();
$thread_2 = new Threaded_upload( "2" );
$thread_2->start();
$thread_3 = new Threaded_upload( "3" );
$thread_3->start();
thanks for any help in advance!
| |
doc_23525149
|
The URL schemes for http:// and mailto: are working in the notes section (Safari and Mail are started, respectively), but myapp:// does not work, and neither does skype:
myapp:// is working fine when I put it into the address field in Safari, so the custom URL scheme did install successfully.
Is the Calendar only implementing some standard URL schemes and not able to recognize any installed custom URL scheme? Or am I doing something wrong?
A: Ok, found it myself ...
Apparently it is not enough to just write
myapp://
but it has to be
myapp://<sometexthere>
in order for the calendar to recognize it as a custom URL scheme. Safari also accepts the version without text after the two slashes.
One never learns enough ...
A: I keep forgetting to open my Science News E-Zine and there's no other 'reminder'... so:
In CALENDAR I created a monthly-repeating event called: ScienceNewsOpen and it's ‘Alert’ is ‘Open File: SCIENCE NEWS OPENER.APP’
In AUTOMATOR I created that application which began as a Calendar Event but was saved as an app:
FIND CALENDAR EVENTS where ALL is true, "Date Starting" is "Today" and "Any Content" contains Science News.
GET SPECIFIED URLs, "Remove" the existing default Apple.com, "Add" ScienceNews.org
DISPLAY WEBPAGES:
The Science News Website opens in my default browser (FFox) in its own tab, i.e., not a new window once a month - but it can open any URL you put in the Application at any time you want to program into the Calendar.
| |
doc_23525150
|
<section class="test">
<div class="n4">
<div class="n2">
1 // first row id
</div>
<div class="n21">
2 // second row id
</div>
</div>
</section>
<section class="test">
<div class="n4">
<div class="n2">
3 // third row id
</div>
<div class="n21">
4 // fourth row id
</div>
</div>
</section>
..... <section> ....upto all ids in the row
What i am tried to do is
Suppose table test has 20 rows.
<?php
$query=$db->query("SELECT * FROM test");
$counter=1;
foreach($query as $row)
{
?>
<section class="test">
<div class="n4">
<?php if($counter %2 !=0) ?>
<div class="n2">
<?php echo $row['id']; ?>
</div>
<?php else ?>
<div class="n21">
<?php echo $row['id']; ?>
</div>
</div>
</section>
<?php
$counter++;
} ?>
This is not showing the exact result.
Any help please?
A: You have wrong with your code, lets try this
<?php
$query=$db->query("SELECT * FROM test");
$counter=1;
foreach($query as $row)
{
?>
<section class="test">
<div class="n4">
<?php if($counter %2 !=0): /* you've missing ":" symbol*/ ?>
<div class="n2">
<?php echo $row['id']; ?>
</div>
<?php else: /* you've missing ":" symbol*/ ?>
<div class="n21">
<?php echo $row['id']; ?>
</div>
<?php endif; /* you dont need close bracket, but you need "endif" */ ?>
<?php $counter++; ?>
</div>
</section>
<?php } ?>
A: This way will work as you want, i have try this as well
<?php
$query = [['id' => 1], ['id' => 2], ['id' => 3]] ; // example of result
for ($i=0; $i < count($query); $i+=2) {
try {
?>
<section class="test">
<div class="n4">
<div class="n2">
<?php echo @$query[$i]['id'] // ignore error ?>
</div>
<div class="n21">
<?php echo @$query[$i+1]['id'] // ignore error ?>
</div>
</div>
</section>
<?php
} catch (Exception $e) {
}
}
Above will produce result like this
<section class="test">
<div class="n4">
<div class="n2">
1
</div>
<div class="n21">
2
</div>
</div>
</section>
<section class="test">
<div class="n4">
<div class="n2">
3
</div>
<div class="n21">
</div>
</div>
</section>
| |
doc_23525151
|
I manage to get it running however every time after starting from scratch it stops working, I suspect this is associated with stopping the [virtualbox] VM / putting the laptop to sleep, but can't confirm if this is definitely the case.
My experience is limited and I'm having difficulties in not just resolving the issue, but also in understanding what is going wrong.
Apologies if this is an obvious problem, but I haven't been able to clearly determine how to stop this problem from happening, and the only solution I've had so far is to destroy the deployment using Vagrant and then starting from scratch - which takes a while and isn't the optimal fix I'm sure. :)
I've noticed that the 'bosh vms' show unresponsive agents and that they're not staring properly. The error in bosh cck indicates a locking issue, but I suspect that this may be a misnomer as running bosh locks indicates that there are no locks. Once again, I'm a newbie, so this may simply be a misunderstanding ...
Help - how do I fix this!! Is there a way to quickly 'reset' to a working state? (vagrant reload --provision doesn't help)
Where exactly is the issue?
Also, what is the (default) root password for the vagrant cloudfoundry/bosh-lite VM?
> bosh vms
+---------------------------------------------------------------------------+--------------------+-----+-----------+--------------+
| VM | State | AZ | VM Type | IPs |
+---------------------------------------------------------------------------+--------------------+-----+-----------+--------------+
| api_z1/0 (8dfeb143-59b1-46dd-9482-e90931a70a0d) | unresponsive agent | n/a | large_z1 | 10.244.0.138 |
| blobstore_z1/0 (7795ce02-d64e-4cc7-be1e-0e328384d568) | unresponsive agent | n/a | medium_z1 | 10.244.0.130 |
| consul_z1/0 (e92f6bfd-f623-4ba4-abf3-3d4baa0953fa) | unresponsive agent | n/a | small_z1 | 10.244.0.54 |
| doppler_z1/0 (049eaa18-3d4f-48d8-92ed-ea4b6a20cd29) | unresponsive agent | n/a | medium_z1 | 10.244.0.146 |
| etcd_z1/0 (e45a7648-e43d-4753-8a18-3ab21b86293d) | unresponsive agent | n/a | large_z1 | 10.244.0.42 |
| ha_proxy_z1/0 (ba6e8ce6-8f40-4868-8a71-c74119f173ea) | failing | n/a | router_z1 | 10.244.0.34 |
| hm9000_z1/0 (ff8ae6a3-1889-4fb0-aabf-072012cf9f48) | unresponsive agent | n/a | medium_z1 | 10.244.0.142 |
| loggregator_trafficcontroller_z1/0 (8f2e4ea1-dda7-4d15-9050-528338824e3b) | unresponsive agent | n/a | small_z1 | 10.244.0.150 |
| nats_z1/0 (9e4eab32-ac91-4f05-83be-b8189c2991e7) | unresponsive agent | n/a | medium_z1 | 10.244.0.6 |
| postgres_z1/0 (fb8d1eee-3ade-480e-aa01-3db26a64b447) | unresponsive agent | n/a | medium_z1 | 10.244.0.30 |
| router_z1/0 (f9ce017b-580f-4fce-b79d-01ceef190e19) | unresponsive agent | n/a | router_z1 | 10.244.0.22 |
| runner_z1/0 (c0b0871b-c672-46c8-ac4a-1aabd81864f6) | unresponsive agent | n/a | runner_z1 | 10.244.0.26 |
| uaa_z1/0 (63b4bfa7-499d-4dba-93f6-2017b04a7588) | unresponsive agent | n/a | medium_z1 | 10.244.0.134 |
+---------------------------------------------------------------------------+--------------------+-----+-----------+--------------+
> bosh cck
Acting as user 'admin' on deployment 'cf-warden' on 'Bosh Lite Director'
Performing cloud check...
Director task 96
Error 100: Unable to get deployment lock, maybe a deployment is in progress. Try again later.
Task 96 error
For a more detailed error report, run: bosh task 96 --debug
> bosh locks
Acting as user 'admin' on 'Bosh Lite Director'
No locks
It is possible to do a 'reset' and get it up and running again using the commands below, but this takes quite some time and is surely more of a 'hammer' than is required!
# bosh-lite dir
vagrant destroy && vagrant up
# cd cf-release dir
bosh upload release
bosh deploy
# cd bosh-lite dir
bin/add-route
cf api --skip-ssl-validation https://api.bosh-lite.com
cf create-org my_org
cf create-space development -o my_org
A: You can use sudo su after ssh'ing into the bosh-lite VM with vagrant ssh to become root without needing to enter a root password.
BOSH-lite has always been hard to resurrect after a VM reboot/sleep.
Someone recently (Dec 2016) wrote a utility to "gracefully put machines running BOSH Lite to sleep" and restore it on system wake, to address it:
https://github.com/henryaj/ambient
A: I usually do vagrant suspend and then vagrant up to avoid a situation with dead containers/VMs inside BOSH Lite.
You can do bosh cck but my experience shows that a simple deployment recreate is much faster and also more reliable.
A: It is recommended that we pause the Bosh-lite VM when its not in use so that it can simply be resumed after the system goes to sleep/get rebooted; otherwise VM will be halted by OS (Bosh-lite VM goes in aborted state). Running vagrant up on aborted bosh-lite, gets it running but in that case CF VMs go in unresponsive state which requires redeployment.
Running vagrant suspend for pausing and vagrant resume when restarting the work helps avoid the situation with unresponsive CF VMs.
| |
doc_23525152
|
Exception in thread "main" java.lang.NoClassDefFoundError: com/sun/mail/util/MailLogger
at javax.mail.Session.initLogger(Session.java:227)
at javax.mail.Session.<init>(Session.java:212)
at javax.mail.Session.getDefaultInstance(Session.java:315)
at gmailconsole.Email.createEmail(Email.java:45)
at gmailconsole.GmailApiQuickStart.main(GmailApiQuickStart.java:91)
Caused by: java.lang.ClassNotFoundException: com.sun.mail.util.MailLogger
at java.net.URLClassLoader$1.run(URLClassLoader.java:372)
at java.net.URLClassLoader$1.run(URLClassLoader.java:361)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:360)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 5 more
The code that associated with the exception
public static void sendMessage(Gmail service, String userId, MimeMessage email)
throws MessagingException, IOException {
Message message = createMessageWithEmail(email);
message = service.users().messages().send(userId, message).execute();
System.out.println("Message id: " + message.getId());
System.out.println(message.toPrettyString());
}
Method call in the main class
try {
MimeMessage mimeMessage = Email.createEmail("isurub1992@gmail.com", "me", "Test", "This is a test message");
Email.sendMessage(service, "me", mimeMessage);
} catch (MessagingException ex) {
ex.printStackTrace();
}
P.S : I have added all the libraries and JavaEE API Library in NetBeasns
A: ClassNotFoundException is definite: the class is not found in classpath.
Short search reveals that the missing class com.sun.mail.util.MailLogger is found in com.sun.mail_1.4.2.jar; so have a look, I would place a bet that this would solve your problem.
Not the same problem, but it could be a nice information for you, too:
java.lang.NoClassDefFoundError: javax/mail/Authenticator, whats wrong?
| |
doc_23525153
|
Therefore I have to link it with another static library (myanotherlibrary.lib).
I use this command line :
gprbuild -d "D:\My_grp_project\My_grp_project.gpr"
Here the content of the .gpr :
project My_grp_project is
Architecture := "x86";
for Languages use ("Ada");
for Source_Dirs use (".", "source", "source\common");
for Library_Dir use "dll\" & Architecture;
for Library_Ali_Dir use "ali\" & Architecture;
for Library_Name use "My_grp_project";
for Library_Kind use "dynamic";
for Object_Dir use "obj\" & Architecture;
package Linker is
for Default_Switches ("Ada") use ("-L.", "-lbar");
end Linker;
end My_grp_project;
I put "myanotherlibrary.lib" in the directory "D:\My_grp_project\", but it still doesn't link: "undefined reference to ..."
Could anyone help me please ?
Regards
Glen
A: Looking at the docs, I think you should be using the Library_Options attribute instead of package Linker:
for Library_Options use ("-L.", "-lbar”);
(I’m confused - do you mean myanotherlibrary.lib or bar.lib?)
I’d be a bit concerned about using a static library from a dynamic library: I’d expect the dynamic library to be built with -fPIC or equivalent switch to get position-independent code, so that the same loaded library binary can be seen at different addresses in each of the executables using it.
A: Here the solution I finally found.
*
*It is not possible to link static library compiled with MSVC. I had to compile my static library with GCC (same version as the one included in GNAT).
*I had to add "Library_Options" options, without "-L" and "-l" arguments (another problem I passed). Note that package Linker is not taken into account while building a dynamic library. Note also that paths shall have no spaces !
project My_grp_project is
for Languages use ("Ada");
for Source_Dirs use (".", "source", "source\common");
for Library_Dir use “dll";
for Library_Ali_Dir use "ali";
for Object_Dir use "obj";
for Library_Name use "My_grp_project";
for Library_Kind use "dynamic";
for Library_Options use ("path\myanotherlibrary.a", "path_to_GNAT\libstdc++.a");
end My_grp_project;
*
*I builded the project in the GPS (default option) : "Build All"
*In result I do have my dynamic library "libMy_grp_project.dll"
Voilà.
Thanks !
| |
doc_23525154
|
SELECT * FROM users WHERE ip LIKE '88.99.%';
The problem is that the inet datatype does not seems to support wildcards (at least not in the way I have utilized them in the preceding query).
What I'd like to know is whether it would be a smart move to convert the field into string before specifying the LIKE filter? (On the other hand, this would probably slow down the whole query, even if the approach itself was valid.)
A: Use subnet operators for such queries. '88.99.0.0/16' should do it :
SELECT * FROM users WHERE ip << inet '88.99.0.0/16';
A: Another option which worked for me if you want to do a string comparison is this:
SELECT * FROM users WHERE TEXT(ip) LIKE '88.99.%';
although it will be less efficient than "How to use LIKE on inet field in Postgres".
Reference: https://www.postgresql.org/docs/8.2/static/functions-net.html
| |
doc_23525155
|
Thats is some of attempts:
<resources>
<style name="LaunchTheme" parent="@android:style/Theme.Black.NoTitleBar">
<!-- Show a splash screen on the activity. Automatically removed when
Flutter draws its first frame -->
<item name="android:windowBackground">@drawable/launch_background</item>
</style>
<color name="goiaba">#e1635a</color>
</resources>
The file is android -> app -> res -> values -> styles.xml
<!-- Modify this file to customize your launch splash screen -->
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@android:color/black" />
<item android:drawable="@android:color/holo_blue_light">
</item>
</layer-list>
The file is android -> app -> res -> drawable -> launch_background.xml
When the item drawable is color holo_blue_light its works fine because its android color already, but when i try put the color "goiaba" doesn't works...
Thats is the message of error:
android/app/src/main/res/drawable/launch_background.xml:13: AAPT: error: resource android:color/goiaba not found.
A: I'm found how create new color in android with flutter project, i need create the colors.xml in PROJECT/android/app/src/main/res/values/ and i added using @color/COLOR_NAME
A: It's ok that not create the colors.xml file, the reason why you did not succeed for the first try is that you used @android:color/goiaba instead of @color/goiaba .
| |
doc_23525156
|
priv.c:122: error: undefined reference to 'hw_get_module'
clang++: error: linker command failed with exit code 1 (use -v to see invocation)
make: *** [private_libs/obj/local/armeabi-v7a/libanw.10.so] Error 1
Have latest vlc - android from git and android sdk 23, android ndk 13.
My first attempt was to add APP_STL := stlport_static to the Application.mk but this didnt fix the problem.
Please, can someone help?
Kind regards
A: Leaving some tips for people going through the same hell(I compile on ubuntu 16.04):
*
*Make sure you have dependencies and everything is up to date.
It's superbly annoying but missing dependencies surface as a totally irrelevant error.
sudo apt-get install automake ant autopoint cmake build-essential libtool patch pkg-config protobuf-compiler ragel subversion unzip git openjdk-8-jre openjdk-8-jdk
sudo apt-get upgrade ant autoconf automake autopoint cmake gawk gcc g++ libtool m4 patch pkg-config libprotobuf-dev libprotobuf-c0-dev protobuf-c-compiler ragel subversion unzip
protobuf and gettext are not in the above since you can't install the latest versions via apt, so you should download and compile them.
*Delete contrib folders if it fails to compile for some reason
Sadly compile.sh is far from perfect and assumes sub modules are built fine as long as folders are there.
*Failing to download gradle zip file once causes the script to
download the file in endless loop
The script does not overwrite the zip file it first downloaded, so once it fails and unless you manually remove it, the script looks only at that failed zip download and exits.
*compile.sh fails
Re-run the script until the same error appears.
| |
doc_23525157
|
$('.call-hunt-btn').on('click', callHunt);
function callHunt(e) {
e.preventDefault();
$.arcticmodal({
type: 'ajax',
url: 'wp-content/themes/beton/modals/modal-feedback.php',
overlay: {
css: {
backgroundColor: '#000',
opacity: .75
}
},
afterOpen: function(){
setMaskPhone();
setDataSBJS('.arcticmodal-container');
}
});
}
It uses a php template. I want to use ACF fields in this template.
If I just write: <?php the_field('class'); ?>, but nothing happens.
How do I fix it?
A: If you are adding your javascript via wp_enqueue_script() function, you could expose the ACF values via the wp_localize_script() function (https://codex.wordpress.org/Function_Reference/wp_localize_script).
The wp_localize_script() function creates a Javascript object based on the values set in the PHP array supplied to the wp_localize_script(). The ACF values can then be access from the Javascript object using dot notation.
| |
doc_23525158
|
if(isCollides(prize, splash))
in other function Working well but in runnable function not working.
private Runnable Scoring =new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
try {
if(isCollides(prize, splash))
{
score++;
p.setText(":"+score);
}
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
mHandler.postDelayed(mStartVamp, 3000);
}
};
public boolean isCollides(Sprite Sprite1 ,Sprite Sprite2) throws Exception
{
float diffX = Math.abs( (Sprite1.getX() + Sprite1.getWidth()/2 )-
(Sprite2.getX() + Sprite2.getWidth()/2 ));
float diffY = Math.abs( (Sprite1.getY() + Sprite1.getHeight()/2 )-
(Sprite2.getY() + Sprite2.getHeight()/2 ));
if(diffX < (Sprite1.getWidth()/2 + Sprite2.getWidth()/3)
&& diffY < (Sprite1.getHeight()/2 + Sprite2.getHeight()/3))
{
return true;
}
else{
return false;
}
}
A: Any change you make to AndEngine entities needs to happen on the AndEngine UpdateThread - so your call to p.setText() should be enveloped in a runOnUpdateThread() call - see this thread for how to - How can repair this error? "java.lang.IndexOutOfBoundsException"
| |
doc_23525159
|
<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
<Field ID="{854DCDF4-5091-4B1E-AA31-D9DC71A29637}"
Type="Text"
Required="TRUE"
DisplayName="Customer ID"
Name="Customer-ID"
Indexed="TRUE"
EnforceUniqueValues="FALSE" />
<Field ID="{7E898932-91C0-4285-A8A2-B6440BE2FDC9}"
Type="Text"
Required="FALSE"
DisplayName="Customer Name"
Name="Customer-Name" />
<Field ID="{5168AB24-21A8-438A-8112-E82E24E180CE}"
Type="Text"
Required="FALSE"
DisplayName="Country"
Name="Country" />
<!-- Parent ContentType: Item (0x01) -->
<ContentType ID="0x010081e20b9903d945a8beacde43ae09f766"
Name="Customer"
Group="Custom Content Types"
Description="Customer Content Type"
Inherits="TRUE"
Version="0">
<FieldRefs>
<FieldRef ID="{854DCDF4-5091-4B1E-AA31-D9DC71A29637}" />
<FieldRef ID="{7E898932-91C0-4285-A8A2-B6440BE2FDC9}" />
<FieldRef ID="{5168AB24-21A8-438A-8112-E82E24E180CE}" />
</FieldRefs>
<XmlDocuments>
<XmlDocument NamespaceURI="http://schemas.microsoft.com/sharepoint/v3/contenttype/forms/url">
<FormUrls xmlns="http://schemas.microsoft.com/sharepoint/v3/contenttype/forms/url">
<New>_layouts/customer/customer.aspx</New>
<Display>_layouts/customer/customerdisp.aspx</Display>
<Edit>_layouts/customer/customeredit.aspx</Edit>
</FormUrls>
</XmlDocument>
</XmlDocuments>
</ContentType>
</Elements>
A: Try Inherts="FALSE" as an attribute on the element
| |
doc_23525160
|
I have tried connecting to salesforce API to access the files but I looking for ideal solution to perform this.
| |
doc_23525161
|
In short, I need a way of getting app names (i.e. "Angry Birds v1.0.0") for user installed applications through adb shell.
Any light on the matter? Any help is appreciated on this.
A: adb shell pm list packages will give you a list of all installed package names.
You can then use dumpsys | grep -A18 "Package \[my.package\]" to grab the package information such as version identifiers etc
A: just enter the following command on command prompt after launching the app:
adb shell dumpsys window windows | find "mCurrentFocus"
if executing the command on linux terminal replace find by grep
A: A shell script to accomplish this:
#!/bin/bash
# Remove whitespace
function remWS {
if [ -z "${1}" ]; then
cat | tr -d '[:space:]'
else
echo "${1}" | tr -d '[:space:]'
fi
}
for pkg in $(adb shell pm list packages -3 | cut -d':' -f2); do
apk_loc="$(adb shell pm path $(remWS $pkg) | cut -d':' -f2 | remWS)"
apk_name="$(adb shell aapt dump badging $apk_loc | pcregrep -o1 $'application-label:\'(.+)\'' | remWS)"
apk_info="$(adb shell aapt dump badging $apk_loc | pcregrep -o1 '\b(package: .+)')"
echo "$apk_name v$(echo $apk_info | pcregrep -io1 -e $'\\bversionName=\'(.+?)\'')"
done
A: Inorder to find an app's name (application label), you need to do the following:
(as shown in other answers)
*
*Find the APK path of the app whose name you want to find.
*Using aapt command, find the app label.
But devices don't ship with the aapt binary out-of-the-box.
So you will need to install it first. You can download it from here:
https://github.com/Calsign/APDE/tree/master/APDE/src/main/assets/aapt-binaries
Check this guide for complete steps:
How to find an app name using package name through ADB Android?
(Disclaimer: I am the author of that blog post)
A: If you know the app id of the package (like org.mozilla.firefox), it is easy.
First to get the path of actual package file of the appId,
$ adb shell pm list packages -f com.google.android.apps.inbox
package:/data/app/com.google.android.apps.inbox-1/base.apk=com.google.android.apps.inbox
Now you can do some grep|sed magic to extract the path : /data/app/com.google.android.apps.inbox-1/base.apk
After that aapt tool comes in handy :
$ adb shell aapt dump badging /data/app/com.google.android.apps.inbox-1/base.apk
...
application-label:'Inbox'
application-label-hi:'Inbox'
application-label-ru:'Inbox'
...
Again some grep magic to get the Label.
A: This is what I just came up with. It gives a few errors but works well enough for my needs, matching package names to labels.
It pulls copies of all packages into subdirectories of $PWD, so keep that in mind if storage is a concern.
#!/bin/bash
TOOLS=~/Downloads/adt-bundle-linux-x86_64-20130717/sdk/build-tools/19.1.0
AAPT=$TOOLS/aapt
PMLIST=adb_shell_pm_list_packages_-f.txt
TEMP=$(echo $(adb shell mktemp -d -p /data/local/tmp) | sed 's/\r//')
mkdir -p packages
[ -f $PMLIST ] || eval $(echo $(basename $PMLIST) | tr '_' ' ') > $PMLIST
while read line; do
package=${line##*:}
apk=${package%%=*}
name=${package#*=}
copy=packages$apk
mkdir -p $(dirname $copy)
if [ ! -s $copy ]; then # copy it because `adb pull` doesn't see /mnt/expand/
adb shell cp -f $apk $TEMP/copy.apk
adb pull $TEMP/copy.apk $copy
fi
label=$($AAPT dump badging $copy || echo ERROR in $copy >&2 | \
sed -n 's/^application-label:\(.\)\(.*\)\1$/\2/p')
echo $name:$label
done < <(sed 's/\r//' $PMLIST)
adb shell rm -rf $TEMP
A: So I extremely grateful to jcomeau_ictx for providing the info on how to extract application-label info from apk and the idea to pull apk from phone directly!
However I had to make several alteration to script it self:
*
*while read line; do done are breaking as a result of commands within while loop interacting with stdin/stdout and as a result while loop runs only once and then stops, as it is discussed in While loop stops reading after the first line in Bash - the comment from cmo I used solution provided and switched while loop to use unused file descriptor number 9.
*All that the script really need is a package name and adb shell pm list packages -f is really excessive so I changed it to expect a file with packages list only and provided example on how one can get one from adb.
*jcomeau_ictx script variant do not take in to account that some packages may have multiple apk associated with them which breaks the script.
*And the least and last, I made every variable to start with underscore, it's just something that makes it easier to read script.
So here another variant of the same script:
#!/bin/bash
_TOOLS=/opt/android-sdk-update-manager/build-tools/29.0.3
_AAPT=${_TOOLS}/aapt
#adb shell pm list packages --user 0 | sed -e 's|^package:||' | sort >./packages_list.txt
_PMLIST=packages_list.txt
rm ./packages_list_with_names.txt
_TEMP=$(echo $(adb shell mktemp -d -p /data/local/tmp) | sed 's/\r//')
mkdir -p packages
[ -f ${_PMLIST} ] || eval $(echo $(basename ${_PMLIST}) | tr '_' ' ') > ${_PMLIST}
while read -u 9 _line; do
_package=${_line##*:}
_apkpath=$(adb shell pm path ${_package} | sed -e 's|^package:||' | head -n 1)
_apkfilename=$(basename "${_apkpath}")
adb shell cp -f ${_apkpath} ${_TEMP}/copy.apk
adb pull ${_TEMP}/copy.apk ./packages
_name=$(${_AAPT} dump badging ./packages/copy.apk | sed -n 's|^application-label:\(.\)\(.*\)\1$|\2|p' )
#'
echo "${_package} - ${_name}" >>./packages_list_with_names.txt
done 9< ${_PMLIST}
adb shell rm -rf $TEMP
| |
doc_23525162
|
mysql_select_db($database_Myconnec, $Myconnec);
$query_service = "SELECT service.Service_id,
IF(physical.Service_id IS NULL, ('Add'), ('Edit')) as physical
FROM service LEFT JOIN physical ON (service.Service_id = physical.Service_id )";
$service = mysql_query($query_service, $Myconnec) or die(mysql_error());
$row_service = mysql_fetch_assoc($service);
$totalRows_service = mysql_num_rows($service);
<table border="1" class="floatedTable">
<tr>
<td><div align="center">Service ID</td>
<td><div align="center">Physical Check</td>
</tr>
<?php do { ?>
<tr>
<td><div align="center"><?php echo $row_service['Service_id']; ?></td>
<td><div align="center"><?php echo $row_service['physical']; ?></td>
</tr>
<?php } while ($row_service = mysql_fetch_assoc($service)); ?>
</table>
What I want is the word 'Add' and 'Edit' to appear as a clickable php links when it is shown in the tables how do i do that?
A: You could, if I understood, do something akin to this perhaps
<table border="1" class="floatedTable">
<tr>
<td><div align="center">Service ID</td>
<td><div align="center">Physical Check</td>
</tr>
<?php
do {
$id=$row_service['Service_id'];
$phys=$row_service['physical'];
$action=$phys=='Add' ? 'add.php' : 'edit.php'; #assumed script names correspond to text
?>
<tr>
<td><div align="center"><?php echo $id; ?></td>
<td><div align="center"><?php echo "<a href='{$action}?id={$id}' title='$phys'>$phys</a>";?></td>
</tr>
<?php } while ($row_service = mysql_fetch_assoc($service)); ?>
</table>
# view.php
# --------
<table border="1" class="floatedTable">
<tr>
<td><div align="center">Service ID</td>
<td><div align="center">Physical Check</td>
</tr>
<?php
do {
$id=$row_service['Service_id'];
$phys=$row_service['physical'];
$action=$phys=='Add' ? 'add.php' : 'edit.php'; #assumed script names correspond to text
?>
<tr>
<td><div align="center"><?php echo $id; ?></td>
<td><div align="center"><?php echo "<a href='{$action}?id={$id}' title='$phys'>$phys</a>";?></td>
</tr>
<?php } while ($row_service = mysql_fetch_assoc($service)); ?>
</table>
# add.php
# -------
$id = isset( $_GET['id'] ) ? $_GET['id'] : false;
if( $id ){
/*
generate form to add record
use $id somewhere?
*/
}
# edit.php
# --------
$id = isset( $_GET['id'] ) ? $_GET['id'] : false;
if( $id ){
/*
do stuff - generate form to edit content etc
use $id to lookup data
*/
}
With reference to your last comments regarding removal of hyperlink for specific values - perhaps try like this?
do {
$id=$row_service['Service_id'];
$phys=$row_service['physical'];
$action=$phys=='Add' ? 'add.php' : 'edit.php'; #assumed script names correspond to text
if( strtolower( $phys )=='wait' )$content=$phys;
else $content="<a href='{$action}?id={$id}' title='$phys'>$phys</a>";
?>
<tr>
<td><div align="center"><?php echo $id; ?></td>
<td><div align="center"><?php echo $content; ?></td>
</tr>
<?php } while ($row_service = mysql_fetch_assoc($service)); ?>
</table>
| |
doc_23525163
|
A: Read The LLVM Target-Independent Code Generator first. In particular, this section about instruction selection should answer your question.
E.g.:
This phase takes a legal SelectionDAG as input, pattern matches the
instructions supported by the target to this DAG, and produces a new
DAG of target code.
It's a pretty long section with examples, so reproducing it fully here doesn't make much sense.
DAG matching is a topic that appears in many compiler texts and isn't LLVM specific.
For more LLVM specifics, and tablegen in particular, there's also this resource.
| |
doc_23525164
|
When I look at the JSFIDDLE they are aligned fine. Can anybody see what is wrong?
ul {
counter-reset: section;
list-style: none;
}
li {
margin: 0 0 10px 0;
line-height: 40px;
}
li:before {
content: counter(section);
counter-increment: section;
display: inline-block;
width: 40px;
height: 40px;
margin: 0 20px 0 0;
border: 1px solid #ccc;
border-radius: 100%;
text-align: center;
}
**Updated code to question**
<div id="feature">
<div class="container">
<div class="row">
<div class="col-md-10 col-md-offset-1 col-sm-12 text-center feature-title">
<!-- Seminariet bulletpoints -->
<h2>PÅ BAGGRUND AF SEMINARIET VIL DU</h2>
<ul>
<li>First item</li>
<li>Second item</li>
<li>Third item</li>
</ul>
</div>
</div>
</div>
</div>
**Updated picture**
[![enter image description here][3]][3]
A: i guess the problem is that you have text-align:center on the li or on the ul ( as far as i can see from your screenshot, in your code everything is fine )
so you want to center the lis . they stay like that because every li has a different text length so they align correctly on the center of their parent ul
there are a number of ways to make them aligned on center and also nicely one on top of the other. this would be one of the solutions
EDIT centering ul the way you want it to look ( without text-align:center ) it's problematic so you need to use something like the snippet below
i think it will be much more responsive. if not, you can always use @media query to make it ' look good ' on smaller devices
( also made some example @media Queries )
ul {
counter-reset: section;
list-style: none;
position:relative;
padding:0;
left:45%;
display:inline-block;
}
li {
margin: 0 0 10px 0;
line-height: 40px;
}
li:before {
content: counter(section);
counter-increment: section;
display: inline-block;
width: 40px;
height: 40px;
margin: 0 20px 0 0;
border: 1px solid #ccc;
border-radius: 100%;
text-align: center;
}
h2 {
text-align:center;
}
@media only screen and (max-width: 640px) {
ul {
left:40%;
}
}
@media only screen and (max-width: 425px) {
ul {
left:35%;
}
}
@media only screen and (max-width: 320px) {
ul {
left:25%;
}
}
<div id="feature">
<div class="container">
<div class="row">
<div class="col-md-10 col-md-offset-1 col-sm-12 text-center feature-title">
<!-- Seminariet bulletpoints -->
<h2>PÅ BAGGRUND AF SEMINARIET VIL DU</h2>
<div style="border: 1px solid black;">
<ul style="text-align:left">
<li>First item</li>
<li>Second item</li>
<li>Third item</li>
</ul>
</div>
</div>
</div>
</div>
</div>
| |
doc_23525165
|
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="match_parent" >
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/mHeaderHeader"
android:visibility="visible"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<include
android:id="@+id/myInclude"
layout="@layout/myInclude_layout" />
<include
android:id="@+id/myInclude2r"
layout="@layout/myInclude2" />
<FrameLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
</FrameLayout>
<include
android:id="@+id/myInclude3"
layout="@layout/myinclude3layout" />
<ImageView
android:id="@+id/myImageView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
<android.support.v4.view.ViewPager
android:id="@+id/myViewPager"
android:visibility="visible"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
<include layout="@layout/myinclude4" />
</LinearLayout>
A: You can try something like this:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="match_parent" >
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/mHeaderHeader"
android:visibility="visible"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentTop="true"
android:orientation="vertical">
<include
android:id="@+id/myInclude"
layout="@layout/myInclude_layout" />
<include
android:id="@+id/myInclude2r"
layout="@layout/myInclude2" />
<include
android:id="@+id/myInclude3"
layout="@layout/myinclude3layout" />
<ImageView
android:id="@+id/myImageView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
<include layout="@layout/myinclude4"
android:id="@+id/myinclude4" />
<android.support.v4.view.ViewPager
android:id="@+id/myViewPager"
android:visibility="visible"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignBelow="@id/mHeaderHeader"
android:layout_alignAbove="@id/myinclude4" />
</RelativeLayout>
I suppose that ViewPager takes all space, so I placed it below header and above footer using RelativeLayout
| |
doc_23525166
|
Below is the code I am using for obtaining weighted means:
group_by(time, gender) %>%
summarise(Mean=mean(x, na.rm=T, wt=weights))
Typically, I use the below code for weighted SD:
weighted.sd(df$x, df$weights, na.rm = T)
However, I cannot get that function to work within dplyr. Any ideas?
Additionally, is there any way to combine functions so that I can see two columns, one for weighted mean and one for weighted SD?
Thanks!
A: You don't provide a reproducible example. However, grouping and summarizing with the weighted.sd() function from radiant.data seems to work fine in a dplyr pipeline:
library(tidyverse)
mtcars |>
group_by(vs, cyl) |>
summarize(w_mean = weighted.mean(x = mpg, wt = hp),
w_sd = radiant.data::weighted.sd(x = mpg, wt = hp))
#> `summarise()` has grouped output by 'vs'. You can override using the `.groups`
#> argument.
#> # A tibble: 5 × 4
#> # Groups: vs [2]
#> vs cyl w_mean w_sd
#> <dbl> <dbl> <dbl> <dbl>
#> 1 0 4 26 0
#> 2 0 6 20.6 0.646
#> 3 0 8 15.1 2.39
#> 4 1 4 26.7 4.48
#> 5 1 6 19.1 1.39
Created on 2022-08-02 by the reprex package (v2.0.1)
Note that radiant.data masks a lot of functions from the Tidyverse packages, which might cause other problems, so I just used the weighted.sd function directly rather than loading the package.
| |
doc_23525167
|
A: For making a contract call from another contract you need to:
*
*Create an interface on the caller contract with the entry points of your interest of the to-be-called contract (ie MyRemoteContract):
contract MyRemoteContract =
entrypoint my_remote_entrypoint : (int) => bool
entrypoint another_remote_entrypoint : (address, int) => bool
*Manage the other contract inside your caller contract (ie: keeping it in your state)
contract MyCallerContract =
record state = {
some_field : address,
remote_contract_instance : MyRemoteContract }
*Finally when you are doing your init you can send by parameter your remote contract address to instantiate on your caller contract
stateful entrypoint init( remote_contract_instance_param : MyRemoteContract) : state = {
remote_contract_instance = remote_contract_instance_param }
*When calling to this contract (caller) you will need to tell him the address (ct_....) of the instance of the deployed contract
*From now own your contract will be able to call any remote entrypoint you got on the interface.
stateful entrypoint try_remote_call(value: int) =
state.token.my_remote_entrypoint(value)
Some side note, be careful when your remote contract does Call.caller uses because it won't be the actual address but the contract address as caller.
A: To call another contract, you can deploy the first contract and then pass the same parameter into the method for the call
| |
doc_23525168
|
A: You are almost never going to beat the query time in a DB IDE / Developer Tool. There's just more that has to happen when you are consuming the data into Spotfire. First, the exact same execution has to happen on the DB side. While in PL/SQL Developer this is the end of the steps. When loading into Spotfire there are more steps (conversion, loading into memory, etc).
What could also be slowing down your load time is transformations, calculated columns, low RAM / CPU availability on the Spotfire DB Server, network bandwidth between your Oracle DB and the Spotfire DB, and so on...
So theoretically your problem could be represented with something like:
Normal Query Time + Network Latency + Resource Limitations + Spotfire Transformations + Other files being loaded in the analysis + unknowns...
| |
doc_23525169
|
The solution revolves around a boolean preference (the one having startedBeforePreferenceKey as key in the following code). In the onCreate() of the launcher activity, I try to retrieve a preference with the key startedBeforePreferenceKey and store it in a variable startedBefore. If the preference does not exist, startedBefore is assigned false.
Then I check if startedBefore is false, and if so, I create the mentioned preference, give it a value of true and store it in the SharedPreferences, and start this activity which should launch the app for the first time. This way, when this check is executed next time the onCreate() is being executed, startedBefore will be assigned true and thus this launch-once activity won't start.
THE PROBLEM IS that when the app is launched for the first time, the normal launcher SHOWS MOMENTARILY before the activity which should launch the app only when the app is launched for the first time is started.
When the app is launched for the first time, the normal launcher should not show at all. Directly, the special activity which I want to show when app is launched for the first time, should show.
What should I do?
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
boolean startedBefore = sharedPreferences.getBoolean(getString(R.string.startedBeforePreferenceKey), false);
if (!startedBefore) {
SharedPreferences.Editor sharedPreferencesEditor = sharedPreferences.edit();
sharedPreferencesEditor.putBoolean(getString(R.string.startedBeforePreferenceKey), true);
sharedPreferencesEditor.commit();
startActivity(new Intent(this, MainActivity.class));
}
EDIT: @HammadTariqSahi
First, this excerpt from LogCat:
03-16 08:42:25.629: E/AndroidRuntime(1837): FATAL EXCEPTION: main
03-16 08:42:25.629: E/AndroidRuntime(1837): Process: tests.globalactivitytest, PID: 1837
03-16 08:42:25.629: E/AndroidRuntime(1837): java.lang.RuntimeException: Unable to instantiate application tests.globalactivitytest.activity.GlobalActivity: java.lang.ClassNotFoundException: Didn't find class "tests.globalactivitytest.activity.GlobalActivity" on path: DexPathList[[zip file "/data/app/tests.globalactivitytest-1/base.apk"],nativeLibraryDirectories=[/data/app/tests.globalactivitytest-1/lib/x86, /vendor/lib, /system/lib]]
03-16 08:42:25.629: E/AndroidRuntime(1837): at android.app.LoadedApk.makeApplication(LoadedApk.java:578)
03-16 08:42:25.629: E/AndroidRuntime(1837): at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4680)
03-16 08:42:25.629: E/AndroidRuntime(1837): at android.app.ActivityThread.-wrap1(ActivityThread.java)
03-16 08:42:25.629: E/AndroidRuntime(1837): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1405)
03-16 08:42:25.629: E/AndroidRuntime(1837): at android.os.Handler.dispatchMessage(Handler.java:102)
03-16 08:42:25.629: E/AndroidRuntime(1837): at android.os.Looper.loop(Looper.java:148)
03-16 08:42:25.629: E/AndroidRuntime(1837): at android.app.ActivityThread.main(ActivityThread.java:5417)
03-16 08:42:25.629: E/AndroidRuntime(1837): at java.lang.reflect.Method.invoke(Native Method)
03-16 08:42:25.629: E/AndroidRuntime(1837): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
03-16 08:42:25.629: E/AndroidRuntime(1837): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
03-16 08:42:25.629: E/AndroidRuntime(1837): Caused by: java.lang.ClassNotFoundException: Didn't find class "tests.globalactivitytest.activity.GlobalActivity" on path: DexPathList[[zip file "/data/app/tests.globalactivitytest-1/base.apk"],nativeLibraryDirectories=[/data/app/tests.globalactivitytest-1/lib/x86, /vendor/lib, /system/lib]]
03-16 08:42:25.629: E/AndroidRuntime(1837): at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
03-16 08:42:25.629: E/AndroidRuntime(1837): at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
03-16 08:42:25.629: E/AndroidRuntime(1837): at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
03-16 08:42:25.629: E/AndroidRuntime(1837): at android.app.Instrumentation.newApplication(Instrumentation.java:981)
03-16 08:42:25.629: E/AndroidRuntime(1837): at android.app.LoadedApk.makeApplication(LoadedApk.java:573)
03-16 08:42:25.629: E/AndroidRuntime(1837): ... 9 more
03-16 08:42:25.629: E/AndroidRuntime(1837): Suppressed: java.lang.ClassNotFoundException: tests.globalactivitytest.activity.GlobalActivity
03-16 08:42:25.629: E/AndroidRuntime(1837): at java.lang.Class.classForName(Native Method)
03-16 08:42:25.629: E/AndroidRuntime(1837): at java.lang.BootClassLoader.findClass(ClassLoader.java:781)
03-16 08:42:25.629: E/AndroidRuntime(1837): at java.lang.BootClassLoader.loadClass(ClassLoader.java:841)
03-16 08:42:25.629: E/AndroidRuntime(1837): at java.lang.ClassLoader.loadClass(ClassLoader.java:504)
03-16 08:42:25.629: E/AndroidRuntime(1837): ... 12 more
03-16 08:42:25.629: E/AndroidRuntime(1837): Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack trace available
GlobalActivity.java:
package tests.globalactivitytest;
import android.app.Application;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
public class GlobalActivity extends Application {
@Override
public void onCreate() {
super.onCreate();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
//SharedPreferences.Editor editor = sharedPreferences.edit();
boolean launchedBefore = sharedPreferences.getBoolean("launchedBefore", false);
if (launchedBefore) {
Intent intent = new Intent(this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
} else {
Intent intent = new Intent(this, LaunchOnceActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
}
MainActivity.java:
package tests.globalactivitytest;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
LaunchOnceActivity.java:
package tests.globalactivitytest;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class LaunchOnceActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_launch_once);
}
}
Manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="tests.globalactivitytest"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="23" />
<application
android:name=".activity.GlobalActivity"
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".LaunchOnceActivity"
android:label="@string/title_activity_launch_once" >
</activity>
</application>
</manifest>
A: Above answers are also fine but if you need to do it without splash activity then you can use below method
Step 1:Create a new class and extends from Application and add below code (do not forget to change your activity name accordingly). The most important part of it is setting appropriate Intent Flags before starting any of the activities.
This GlobalActivity will be called before your launcher Activity
public class GlobalActivity extends Application {
@Override
public void onCreate() {
super.onCreate();
SharedPreferences userInfo = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = userInfo.edit();
boolean logedIn = userInfo.getBoolean("loggedIn", false);
if (logedIn)
{
Intent intent = new Intent(this,MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
else {
Intent intent = new Intent(this,LaunchOnceActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
}
}
Step 2:
Your manifest file should be like below
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.app.appid" >
<application
android:name=".GlobalActivity"
android:allowBackup="true"
android:icon="@drawable/launch"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".LaunchOnceActivity"
android:label="Launch Once" >
</activity>
</application>
</manifest>
And then change loggedIn varibale in any of the activity accordingly for future use.
A: You could create a splash activity and from its onCreate method check which activity to run next, wait a few seconds, launch the activity and then immediately finish the splash.
If you don't want to create a splash, then create a fake splash activity with no GUI content and translucent theme, and do the routing in the onCreate, then finish immediately. This will be so fast the user won't notice.
A: You can wrap your activity and the normal launcher in fragments. Then, create another activity with a fragmentmanager in its onCreate and make that your launcher at all times. Check for the preference before putting the right fragment on the screen in that activity.
| |
doc_23525170
|
for(var g = 0; g < filtererdData.length; ++g) {
if(filtererdData[g].positive == undefined) {
filtererdData[g].positive == "0";
}
console.log(filtererdData[g].positive);
but in console I still get undefined for some values, what am I doing wrong or I can triple check if it is really undefined?
A: if(!filtererdData[g].positive) {
filtererdData[g].positive = 0; //there was also mistake as pointed out in comments
}
This will check if it's falsy
if doing in that way then you should check like this
if(typeof filtererdData[g].positive == "undefined")
because in JS, undefined if type
| |
doc_23525171
|
The only changes to my _vimrc are to set line numbers, lines, columns, and enable syntax.
Everytime I edit a file with vim, save it and close it (:wq), a new _viminfo file is created in that files directory.
Also, the backup *.*~ files and .swp files persist, and arn't cleared upon saving. Running Windows 7 enterprise.
This really clutters everything - and is a pain trying to open a file for which a .swp file exists..
Help?
A: disable viminfo file:
set viminfo="NONE"
disable swap file:
set noswf
disable backup :
set nobk
set nowb
more details:
:h 'swf'
:h 'bk'
:h 'wb'
:h 'viminfo'
A: That's strange; the viminfo file should be written in your home directory, nowhere else:
*
*The default name of the viminfo file is "$HOME/.viminfo" for Unix and OS/2,
"s:.viminfo" for Amiga, "$HOME_viminfo" for MS-DOS and Win32. For the last
two, when $HOME is not set, "$VIM_viminfo" is used. When $VIM is also not
set, "c:_viminfo" is used. For OS/2 "$VIM/.viminfo" is used when $HOME is
not set and $VIM is set.
It appears as if your %HOME% variable (or the %HOMEDRIVE%%HOMEPATH%) isn't properly set.
| |
doc_23525172
|
'''
{"CorrelationId": "awsnightlyendtoend_zone08_20190828T2319", "ValidationType": "validate_adwactivityfact", "Success": false, "OutputPath": ["s3://zone08-data-validation/awsnightlyendtoend_zone08_20190828T2319/validate_adwactivityfact/requires-replay.csv", "s3://zone08-data-validation/awsnightlyendtoend_zone08_20190828T2319/validate_adwactivityfact/require-investigation.csv"], "ValidationDetail": "Comparison Failed: matched=146455, missing=6, mismatched=0, percent success=99.9918066925666%"}
{"CorrelationId": "awsnightlyendtoend_zone50_20190828T2303", "ValidationType": "validate_adwactivityfact", "Success": false, "OutputPath": ["s3://zone50-data-validation/awsnightlyendtoend_zone50_20190828T2303/validate_adwactivityfact/requires-replay.csv", "s3://zone50-data-validation/awsnightlyendtoend_zone50_20190828T2303/validate_adwactivityfact/require-investigation.csv"], "ValidationDetail": "Comparison Failed: matched=145541, missing=24, mismatched=0, percent success=99.96702504036%"}
'''
A: If you're only going to do it once, you can use an online json to html converter (like this one: http://convertjson.com/json-to-html-table.htm
If not, you'll have to use some javascript to convert parse the json and display as html.
(Probably just jQuery may do the trick)
| |
doc_23525173
|
I have packaged my Java application into a single jar using the Maven plugin One-Jar.
Now I want to run the application as a Unix Daemon using JSVC, i.e. Apache Commons Daemon.
I am using JSVC as follows (which works for Jars made with the Maven assembly plugin, etc):
jsvc -user $USER -home $HOME -pidfile $PID_PATH -cp $PATH_TO_ONE_JAR my.package.MyClass
The error is this:
jsvc.exec error: Cannot find daemon loader org/apache/commons/daemon/support/DaemonLoader
jsvc.exec error: Service exit with a return value of 1
Does anyone know if it is even possible to use JSVC and One-Jar together, since One-Jar uses a custom class loader? The jar runs just fine when I run java -jar my-one-jar.jar.
What can be done?
Thank you for any insight!
A: I had to add all jars dependencies to the classpath option from jsvc. It seems jsvc doesn't use the jars inside another jar
A: If you use the (poorly-documented) Maven Shade Plugin instead of One-jar (they can achieve similar results as each other), it should solve your problems. It unpacks the dependent jars and stores the class files directly in the fat Jar (rather than having jars within the jar). I have used it to create an executable jar for running under JSVC with some success.
Of course, things are seldom as simple as they sound. With the Shade plugin, you may have to do some work to relocate classes when there are conflicts in your dependency tree, or use resource transformers to handle your non-Java resource files. But hopefully not.
(Of course Mkyong.com has a guide on this)
| |
doc_23525174
|
Traceback (most recent call last):
File "E:/ankosh/trial13.py", line 14, in <module>
if grades_mix[index_no]=="HM1":
IndexError: list index out of range)
I would really appreciate the help.
`file_pointer=open("C:/python27/Doc/student_grades.txt", "r")
read_grades=file_pointer.readline()
my_list=[]
while 0==0:
grades_mix=read_grades.split()
name_str=grades_mix[0]
contained_list=[name_str,0,0,0,0,0.0]
index_no=1
count_num=0
sum_float=0.0
avg_float=0.0
while 0==0:
if grades_mix[index_no]=="HM1":
index_no+=1
grade_num=int(grades_mix[index_no])
count_num+=1
sum_float+=grade_num
contained_list[1]=grade_num
elif grades_mix[index_no]=="HM2":
index_no+=1
grade_num=int(grades_mix[index_no])
count_num+=1
sum_float+=grade_num
contained_list[2]=grade_num
elif grades_mix[index_no]=="HM3":
index_no+=1
grade_num=int(grades_mix[index_no])
count_num+=1
sum_float+=grade_num
contained_list[3]=grade_num
elif grades_mix[index_no]=="HM4":
index_no+=1
grade_num=int(grades_mix[index_no])
count_num+=1
sum_float+=grade_num
contained_list[4]=grade_num
index_no+=1
if count_num>0:
avg_float=sum_float/count_num
contained_list[5]=avg_float
index_num=0
while index_num<len(my_list):
if my_list[0]>name_str:
break
index_no+=1
my_list.insert(index_num, contained_list)
read_grades=file_pointer.readline()
file_pointer.close()
print format ("Name","<10")+" | "+format("HM1"," >5")+" | "+format("HM2"," >5")+" | "+format("HM3"," >5")+" | "+format("HM4"," >5")+" | "+format("avg_float"," <10")+" | "
for index_no in range(0, len(my_list)):
print format(my_list[index_num][0], "<10") + " | " + \
format(my_list[index_num][1], " >5") + " | " + \
format(my_list[index_num][2], " >5") + " | " + \
format(my_list[index_num][3], " >5") + " | " + \
format(my_list[index_num][4], " >5") + " | " + \
format(my_list[index_num][5], " >10.2f") + " | "
A: You have, in abbreviated form:
while 0==0:
if grades_mix[index_no]=="HM1":
index_no+=1
with no break statement to ever get out of the loop (which, how about while True?). Sooner or later you're going to go out of range.
A: The error message
IndexError: list index out of range
indicates that you are using an index that does not exist in the array. Try to check the size of the array by printing out its length
print "length of array grades_mix =" ,len(grades_mix)
If the length of the array is less than or equal to 1, then you will get an error at the first step when calling
grades_mix[index_no]
with
index_no=1
It might be that your file contains empty lines or lines with a single word, you need to take care of that in your script.
| |
doc_23525175
|
http://cm.bell-labs.com/cm/ms/departments/sia/project/nlme/UGuide.pdf
and one to use to work with:
The .Rnw file
% File: example.Rnw
\documentclass{article}
\usepackage{fullpage}
\usepackage{graphics}
\usepackage{Sweave}
\usepackage[margin = 10pt, font=small, labelfont={bf}]{caption}
\begin{document}
Here is an example file to show what I want to do. I would like to figure out how to use the \LaTeX\ reference command to reference a figure being generated by R code. Note in the R code, in a comment there is a reference to the figure, but of course the output file shows a verbatim copy of the \LaTeX\ markup. Does anyone know how to get something for Figure \ref{fig2}?
<< example plot >>=
library(reshape)
library(ggplot2)
n <- 100
lambda <- 1 / 3
x <- seq(0, qexp(0.999, rate = lambda), length = n)
q1.a <- data.frame(x = x,
f = dexp(x, rate = lambda),
F = pexp(x, rate = lambda))
q1.a <- melt(q1.a, id.vars = 'x')
g <- ggplot(q1.a) + # Produces \ref{fig1}
aes(x = x, y = value) +
geom_line() +
facet_wrap( ~ variable, scale = "free_y")
ggsave(g, filename = "example1.jpeg")
@
\begin{figure}[h]
\centering
\includegraphics[width = 0.48\textwidth]{./example1}
\caption{Exponential Distribution based plots.}
\label{fig1}
\end{figure}
Here is more of what I would like to see:
<< example plot 2 >>=
ggsave(g + geom_point(), filename = "example2.jpeg") # Produces Figure 2
@
\begin{figure}
\centering
\includegraphics[width = 0.48\textwidth]{./example2}
\caption{Exponential Distribution based plots with points and lines.}
\label{fig2}
\end{figure}
\end{document}
and the pdf is build with the R commands
Sweave(file = 'example.Rnw',
engine = "R",
keep.source = 'TRUE',
echo = 'TRUE',
results = 'verbatim')
tools::texi2dvi(file = "example.tex",
pdf = TRUE,
clean = TRUE)
Any insight on how do this would be great.
A: Here is one way to solve this issue by redefining the Sinput environment in which source code is wrapped by Sweave. By default, it is a simple verbatim environment which is not processed by latex for tokens. The trick is to redefine it to use the alltt environment which allows some tokens to be parsed inside the alltt environment. Note that this might lead to unwanted side effects that I am not aware of, so use with caution!
Here is a reproducible example that works. If you compile it, you will generate a file where ref{fig1} is replaced by the figure number.
\documentclass{article}
\usepackage{Sweave}
\usepackage{alltt}
\renewenvironment{Sinput}{\begin{alltt}}{\end{alltt}}
\begin{document}
In this document, we will create a plot using `R`, and reference its position in
the source code.
<<produce-plot, results = hide>>=
pdf('example1.pdf')
plot(1:10, 1:10) # Produces Figure \ref{fig1}
dev.off()
@
\begin{figure}
\includegraphics{example1.pdf}
\caption{Figure 1}
\label{fig1}
\end{figure}
\end{document}
| |
doc_23525176
|
Here code for HTML Table(found in Net):
Function create_table(rng As Range) As String
Dim mbody As String
Dim mbody1 As String
Dim i As Long
Dim j As Long
mbody = "<TABLE width=""30%"" Border=""1"", Cellspacing=""0""><TR>" ' configure the table
'create Header row
For i = 1 To rng.Columns.Count
mbody = mbody & "<TD width=""100"", Bgcolor=""#000000"", Align=""Center""><Font Color=#FFFFFF><b><p style=""font-size:12px"">" & rng.Cells(1, i).Value & " </p></Font></TD>"
Next
' add data to the table
For i = 2 To rng.Rows.Count
mbody = mbody & "<TR>"
mbody1 = ""
For j = 1 To rng.Columns.Count
mbody1 = mbody1 & "<TD width=""80"", Align=""Center""><p style=""font-size:12px"">" & rng.Cells(i, j).Value & "</TD>"
Next
mbody = mbody & mbody1 & "</TR>"
Next
create_table = mbody
End Function
Code for email:
email = Worksheets("Sheet1").Range("B1").Value
subj = Worksheets("Sheet1").Range("B2").Value
body = "Hello" & "<br><br>" & _
create_table(ActiveSheet.Range("A1").CurrentRegion) & "</Table></Table>"
thund = "Thunderbird path" & _
" -compose " & """" & _
"to='" & email & "'," & _
"cc='" & cc & "'," & _
"bcc='" & bcc & "'," & _
"subject='" & subj & "'," & _
"body='" & body & "'" & """"
Call Shell(thund, vbNormalNoFocus)
Application.Wait (Now + TimeValue("0:00:03"))
Is there any limition? Is it possible to change it?
A: Thunderbird allows using a file for the body with the message parameter, use that instead of the body parameter
Dim FSO As New FileSystemObject
Set FSO = CreateObject("Scripting.FileSystemObject")
fname = FSO.GetTempName & ".html"
Set FileToCreate = FSO.CreateTextFile(fname)
FileToCreate.Write body
FileToCreate.Close
Email = Worksheets("Sheet1").Range("B1").Value
subj = Worksheets("Sheet1").Range("B2").Value
body = "Hello" & "<br><br>" & _
create_table(ActiveSheet.Range("A1").CurrentRegion) & "</Table></Table>"
thund = "Thunderbird path" & _
" -compose " & """" & _
"to='" & Email & "'," & _
"cc='" & cc & "'," & _
"bcc='" & bcc & "'," & _
"subject='" & subj & "'," & _
"message='" & fname & "'" & """"
Call Shell(thund, vbNormalNoFocus)
Kill fname
Application.Wait (Now + TimeValue("0:00:03"))
| |
doc_23525177
|
After publishing it to Azure Websites via Visual Studio, all I see is the default template "hostingstart.html".
On exploring more using Kudu console, I found out that there is only that file in the wwwroot folder. Why is my app files not there when I have published them via Visual Studio project?
| |
doc_23525178
|
Game.findAll({include: Gamemode});
So i have 2 databases :
*
*board schema with Game Model
*queue schema with Gamemode Model
So this is my code :
I've been able to create a @ForeignKey between theses 2 remotes tables :
So my games table from board schema has an id_gamemode based on id from gamemodes table of my queue schema.
The model for my table games look like this :
@Table({ tableName: 'games', timestamps: false })
export class Game extends Model<Game> {
@Column({
allowNull: false,
type: UUID,
defaultValue: UUIDV4,
primaryKey: false,
autoIncrement: false,
get() {
const rawValue = this.getDataValue('gamemode_id');
return rawValue ? rawValue.toString() : null;
},
references: {
model: {
tableName: "gamesmodes",
schema: "queue"
},
key: 'id'
}
})
@ForeignKey(() => Gamemode)
gamemode_id: string;
}
Now i'm trying to get a reference to my Gamemode Model to create an easy sequelize association
@BelongsTo(() => Gamemode, { foreignKey: 'my_ibfk_1', targetKey: 'id' } )
gamemode: Gamemode;
But on compilation, i have this error :
Error: Gamemode has not been defined
I think it's logic : my Gamemode is not defined in my board database ; it's defined on my secondary database queue.
But with NestJS & Sequelize, can i create this relation between theses 2 "remote" models ?
Someone has an idea please ?
Regards
| |
doc_23525179
|
model = Sequential()
model.add(Dense(32,input_shape=(3,)))
model.add(Dense(1))
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
model.fit(x, y, batch_size=5, epochs=10)
print(model)
Error
<tensorflow.python.keras.engine.sequential.Sequential object at 0x000001823B68BDD8>
A: one option is model.get_config() that gives you a JSON list
A: Elaborating the suggestions mentioned in the comment and providing the solution below.
From the question and comments, I understand that you have built a Model, trained it and you want to access Parameters/Metrics/Loss like loss, epochs, batch_size, metrics, etc..
For getting those values, as mentioned in the comments, assign the results of model.fit to a variable, say history, as shown below
history = model.fit(x = Train_Generator, shuffle=True, epochs = 3, steps_per_epoch = steps_per_epoch,
validation_data = Val_Generator, validation_steps = validation_steps
)
All the values which we need will be present in history.history:
print(history.history)
Output of the above command is :
{'loss': [0.7191072106361389, 0.6968516707420349, 0.7295272946357727],
'acc': [0.5074999928474426, 0.531499981880188, 0.5584999918937683],
'val_loss': [4.8877854347229, 5.5809173583984375, 58.02076721191406],
'val_acc': [0.5, 0.49900001287460327, 0.5090000033378601]}
As seen above, since the Training was done for 3 Epochs, there are 3 Values corresponding to Training Loss, Training Accuracy, Validation Loss and Validation Accuracy.
We shall now print the values which we want:
print('Number of Epochs are ', len(history.history['loss']))
print("Training Loss is ", history.history['loss'])
print("Validation Loss is ", history.history['val_loss'])
print("Training Accuracy is ", history.history['acc'])
print("Validation Accuracy is ", history.history['val_acc'])
Output of the above print statements are shown below:
Number of Epochs are 3
Training Loss is [0.7191072106361389, 0.6968516707420349, 0.7295272946357727]
Validation Loss is [4.8877854347229, 5.5809173583984375, 58.02076721191406]
Training Accuracy is [0.5074999928474426, 0.531499981880188, 0.5584999918937683]
Validation Accuracy is [0.5, 0.49900001287460327, 0.5090000033378601]
We can also plot the beautiful plots of the above Metrics/Values using the Code below:
training_acc = history.history['acc']
val_acc = history.history['val_acc']
training_loss = history.history['loss']
val_loss = history.history['val_loss']
Number_Of_Epochs = range(1, len(history.history['acc']) + 1)
plt.plot(Number_Of_Epochs, training_acc, color = 'green', marker = '*', label = 'Training Accuracy')
plt.plot(Number_Of_Epochs, val_acc, color = 'blue', marker = 'o', label = 'Validation Accuracy')
plt.title('Training Accuracy and Validation Accuracy Vs Epochs')
plt.legend()
plt.figure()
plt.plot(Number_Of_Epochs, training_loss, color = 'green', marker = '*', label = 'Training Loss')
plt.plot(Number_Of_Epochs, val_loss, color = 'blue', marker = 'o', label = 'Validation Loss')
plt.title('Training Loss and Validation Loss Vs Epochs')
plt.legend()
plt.figure()
Plots are shown in the screenshot below:
Hope this helps. Happy Learning!
| |
doc_23525180
|
Scenario :
I have a table having table_id as primary key, which is set to auto-increment.
table_id more_columns
1 some value
2 others
Now if i delete row 2, and insert one more row, the table_id becomes 3 (Expected is 2)
table_id more_columns
1 some value
3 recent
Why is it so? Here I am loosing some ids (I know they are not important). Please put some lights on this behavior
A: In auto-increment field If a row is deleted, the auto_increment column of that row will not be re-assigned.
Please see here for more information.
For reasons why auto-increment doesn't use deleted values you can refer here(mentioned in comments by @AaronBlenkush).
A: A MySQL auto_increment column maintains a number internally, and will always increment it, even after deletions. If you need to fill in an empty space, you have to handle it yourself in PHP, rather than use the auto_increment keyword in the table definition.
Rolling back to fill in empty row ids can cause all sorts of difficulty if you have foreign key relationships to maintain, and it really isn't advised.
The auto_increment can be reset using a SQL statement, but this is not advised because it will cause duplicate key errors.
-- Doing this will cause problems!
ALTER table AUTO_INCREMENT=12345;
EDIT
To enforce your foreign key relationships as described in the comments, you should add to your table definition:
FOREIGN KEY (friendid) REFERENCES registration_table (id) ON DELETE SET NULL;
Fill in the correct table and column names. Now, when a user is deleted from the registration, their friend association is nulled. If you need to reassociate with a different user, that has to be handled with PHP. mysql_insert_id() is no longer helpful.
If you need to find the highest numbered id still in the database after deletion to associate with friends, use the following.
SELECT MAX(id) FROM registration_table;
After delete write this query
ALTER TABLE tablename AUTO_INCREMENT = 1
A: The auto_increment value is a counter stored internally for each table. The counter is only increased, never decreased.
Every syntactically correct INSERT statement fired against the table increments this counter, even when it is rolled back and also when you define an insert value for the primary key.
| |
doc_23525181
|
@interface AppDelegate : NSObject <NSApplicationDelegate>
@property (weak) IBOutlet NSSlider *slider;
- (void)doSomething;
@end
…and this is the *m:
@implementation AppDelegate
- (void) doSomething {[self.slider setFloatValue:0];}
@end
I'm new to Xcode and Objective C, and I would like to use and understand the modern “tools” presented by Apple in its documentation, namely ARC, or here more specifically the ability to skip @synthesize.
If I understood correctly, @property (weak) IBOutlet NSSlider *slider; does a few things for me, including:
*
*creating an instance variable called _slider;
*creating a getter named slider;
*creating a setter named setSlider.
I've been doing C++ until now, so I see instance variables as the equivalent of what I am calling (rightly, I hope) members of my C++ classes, which I incidentally always call _member.
I understand that the whole point of encapsulation is that, if you're outside a given class, you have to use accessors to access those variables; they are private to you, so there's no way you can access them via _member even if you tried.
But, when I'm writing my *.m file of my class, _member means something. Back to my example, I think self.slider and _slider are equivalent. The latter comes naturally to mind first, as it saves a few character.
My question is: are the two absolutely equivalent?
I know this looks similar to this question, for example, but here’s a few reasons why I wanted to ask myself:
*
*I don’t use @synthesize, so I’m really not the one creating _slider, and I wonder if this makes a difference (I believe this is a fairly recent improvement of ObjC, and most answers still refer to @synthesize);
*it seems that on average, most conversations end up with “so, just use self.name”, but I don’t grasp if this is just a recommendation, a convention, of something more important (with an impact on, say, the performance);
*similarly, some say you should only use _name in methods like dealloc and its friends; but I don’t write those thanks to ARC, so does this mean I should never use _name? If so, why?
I hope this justifies this post, I apologies if I missed a preexisting answer. Thanks in advance for your help.
A: self.name = compiles to [self setName:] this is very different then setting the variable directly.
One of the main reasons that using the default setter differs deals with key value observing often referred to as KVO. Using the setter will notify observers of changes, setting the _name directly will not.
Thats not to say you can't fire the events your self with willChangeValueForKey: and didChangeValueForKey:, but the default implementation will handle that for you. So as you say outside the class accessing them you have to use the property get/set but inside your class setting the variable directly will lose out on some notifications. I'm sure there are other differences this is the first that comes to mind.
Using the variable directly does have it's use cases, such as a custom property setter. I think the main take away is the dot syntax is a hidden function call to get/set.
https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/KeyValueObserving/Articles/KVOCompliance.html
A: Under basic circumstances, where you use the pre-made accessors, you could probably get away with using _slider or self.slider within your class interchangeably. They're not equivalent in how they compile necessarily, but the functionality could be said to be equivalent.
The bigger issue comes into play when you start overriding those accessors. When those accessors do more than just "getting" or "setting" a variable, such as accessing some sort dependency variable, accessing the instance variable directly bypasses that functionality that the accessors provide. In these cases, I don't think it can be said that the two are equivalent at all.
| |
doc_23525182
|
I am using the official selenium-webdriver module (ver 2.37.0), and co (ver 2.1.0) to create my generators.
Here's a regular test with no generator/yield magic:
driver.isElementPresent(wd.By.css('.form-login')).then(function (isPresent) {
console.log(isPresent); // true
});
Here are 2 attempts trying to get the same result with yield/generator magic:
var isPresent = yield browser.isElementPresent(wd.By.css('.form-login'));
console.log(isPresent); // undefined
var isPresent = yield browser.isElementPresent(wd.By.css('.form-login')).then(function (isPresent) {
console.log(isPresent); // true
});
console.log(isPresent); // undefined
As you can see, isPresent is always undefined, except when inside the then() callback of the promise. I must admit, I am not too familiar with either generators or promises, so I might be missing something very obvious.
A: I came up with the following solution. It works, but I don't think it's ideal. I have a feeling that there is a better/simpler way.
describe("The login form", function() {
it("should have an email, password and remember me fields and a submit button", function *() {
var results = [];
yield browser.isElementPresent(wd.By.css('.form-login'))
.then(function (isPresent) {
results.push(isPresent);
});
yield browser.isElementPresent(wd.By.css('.form-login input[name="email"]'))
.then(function (isPresent) {
results.push(isPresent);
});
yield browser.isElementPresent(wd.By.css('.form-login input[name="password"]'))
.then(function (isPresent) {
results.push(isPresent);
});
yield browser.isElementPresent(wd.By.css('.form-login button[type="submit"]'))
.then(function (isPresent) {
results.push(isPresent);
});
results.forEach( function (result) {
result.must.be.true();
});
});
});
| |
doc_23525183
|
df<- fread("df.txt")
head(df)
Number Region Type Car ...
1 1 1
2 1 2
3 1 1
4 1 1
5 2 2
6 2 3
I would like to do a subset of df with the Type Car iqual to 1 and 3. When I write something like this
>class(df)
"data.table" "data.frame"
>subset(df, Type Car %in% c(1,3))
This does not work. Some solution?
A: You've got a data table from fread() (unless you used data.table = FALSE), so you can use data table row subsetting instead of subset(). Since you have a multi-word column name, you will need to apply back-ticks around it.
df[`Type Car` %in% c(1, 3)]
The same goes for subset() if you choose to use it. In fact, back-ticks will always be necessary when referencing multi-word names that contain spaces. It would be better to use qualified R names. You can reset the names with
setnames(df, make.names(names(df), unique = TRUE))
so you can avoid the back-ticks. Then you could do
df[Type.Car %in% c(1, 3)]
Note: In data.table version 1.9.6, you can now name the columns in fread() with the col.names argument. As Michael Chirico has mentioned, it's best to get this problem out of the way immediately.
| |
doc_23525184
|
<input type="color" id="Color" />
but when i submit button in action method Color in my model has been Null Value
public int Id { get; set; }
public Color Color { get; set; }
public string Name { get; set; }
A: When writing ViewModels ,Try to keep your Property types as simple as possible. I would change your property to simple string type and use the same name in your form for the Model binding to work.
public class SomeViewModel
{
public int ID { set;get;}
public string Color { set;get;}
public string Name { set;get;}
}
In the view
<input type="color" name="Color" id="Color" />
Remember that color input is not supported by all browsers.
| |
doc_23525185
|
function assignmentWithDriveFile(){
const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheetByName('ASSIGNMENT (Drive File)');
const courseId = sheet.getRange('B1').getValue();
const topicId = sheet.getRange('B2').getValue.toString();
var assignment = {
topicId: topicId,
title: sheet.getRange('B3').getValue().toString(),
description: sheet.getRange('B4').getValue().toString(),
materials :[{
driveFile: {
driveFile: {
id: sheet.getRange('B5').getValue.toString(),
title: sheet.getRange('B6').getValue.toString()
},
shareMode: "STUDENT_COPY"
}
}],
maxPoints : sheet.getRange('B7').getValue().toString(),
state: "PUBLISHED",
workType: "ASSIGNMENT"
};
const newCourseAssignment = Classroom.Courses.CourseWork.create(assignment, courseId);
const assId = newCourseAssignment.id;
sheet.getRange('D1').setValue(assId);
}
after running I get a notification in my spreadsheet that is "GoogleJsonResponseException: API call to classroom.courses.courseWork.create failed with error: @AttachmentNotVisible The item referenced by an attachment was not found or not visible to the user."
well what should i do?
I really wait for your answer and I appreciate it```
Do I have to change the drive ID?
A: Modification points:
*
*About the error of The item referenced by an attachment was not found or not visible to the user., in this case, when the file ID is the invalid file ID, such an error occurs. When I saw your showing script, I thought that at id: sheet.getRange('B5').getValue.toString(),, getValue should be getValue(). This can be also seen at title: sheet.getRange('B6').getValue.toString(). If your file ID is correct, I thought that the reason for your issue might be due to this.
*In your situation, I think that the values can be retrieved from cells B1:B7 by one call.
When these points are reflected in your script, how about the following modification?
Modified script:
function assignmentWithDriveFile() {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheetByName('ASSIGNMENT (Drive File)');
const [[courseId], [topicId], [title], [description], [driveFileId], [driveFileTitle], [maxPoints]] = sheet.getRange("B1:B7").getDisplayValues();
var assignment = {
topicId,
title,
description,
materials: [{
driveFile: {
driveFile: {
id: driveFileId, title: driveFileTitle
},
shareMode: "STUDENT_COPY"
}
}],
maxPoints: maxPoints,
state: "PUBLISHED",
workType: "ASSIGNMENT"
};
const newCourseAssignment = Classroom.Courses.CourseWork.create(assignment, courseId);
const assId = newCourseAssignment.id;
sheet.getRange('D1').setValue(assId);
}
*
*I think that when these values of [[courseId], [topicId], [title], [description], [driveFileId], [driveFileTitle], [maxPoints]] are correct values, this script works.
| |
doc_23525186
|
my code:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.toolbartest.MainActivity" >
<android.support.v7.widget.Toolbar
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/my_awesome_toolbar"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:minHeight="?attr/actionBarSize"
android:background="#ff9900">
<Button
android:layout_height="match_parent"
android:layout_width="match_parent"
android:text="GSSGSDGSDG"/>
</android.support.v7.widget.Toolbar>
</LinearLayout>![enter image description here][1]
Toolbar toolbar = (Toolbar) findViewById(R.id.my_awesome_toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
I got this:
A: I solved it, here xml code:
<android.support.v7.widget.Toolbar
xmlns:plugshare="http://schemas.android.com/apk/res-auto"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/my_awesome_toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#ff9900"
android:minHeight="?attr/actionBarSize"
app1:contentInsetStart="0dp" >
<Button
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:text="GGSSSDFSDFSFFSDF" />
</android.support.v7.widget.Toolbar>
| |
doc_23525187
|
<div style='clear:both;border-bottom:3px solid #999;border-top:#333 solid thin;background:#D7E7E8;position:relative;'>
<div style='width:1091px;margin:0 auto;margin-top:70px;'>
<div style='float:left;width:200px;border:thin solid black;margin-bottom:50px;position:relative;'>
float LEFT
</div>
<div style='float:right;border:thin solid black; width:800px;border:thin solid black;margin-bottom:50px;position:relative;'>
float RIGHT
</div>
</div>
</div>
thank you!
A: You must clear the floats so the parent can surround them.
<div style='clear:both;border-bottom:3px solid #999;border-top:#333 solid thin;background:#D7E7E8;position:relative;'>
<div style='width:1091px;margin:0 auto;margin-top:70px;'>
<div style='float:left;width:200px;border:thin solid black;margin-bottom:50px;position:relative;'>
float LEFT
</div>
<div style='float:right;border:thin solid black; width:800px;border:thin solid black;margin-bottom:50px;position:relative;'>
float RIGHT
</div>
<!--HERE IS THE CLEARING DIV: -->
<div style="clear: left;"></div>
</div>
</div>
You can also, make the parent itself float, and then you won't need the additional markup (clearing div). If you do this, then your parent will need a width specified.
EXPLANATION:
When an element is floating, the parent is not aware of its height (unless it is a floating element itself). You need a clear below the floats so that the parent div recognises the full height of all its children.
A: You don't need to force-clear the floats - you need only to define the overflow for any position:relative div. Overflow:hidden and overflow:auto close the div without any further intervention, on everything from IE6 up.
Change the first line to:
<div style='clear:both;border-bottom:3px solid #999;border-top:#333 solid thin;background:#D7E7E8;position:relative; overflow:hidden;'>
and it'll accomplish the same thing as forcing the div closed.
| |
doc_23525188
|
Is it possible to turn the service/applications on or off for all users or for users in specific organizational units through APIs
A: The API does not give you access to enable/disable specific services for Org Units. You need to setup the OUs for the desired levels of access to services and then move users between OUs via the API to control their access to services.
The only other option you have is to use the blockInheritance attribute. Enabling/disabling ineritance allows you to control which services are on for an OU at any given time.
| |
doc_23525189
|
[{
"websiteId": "4f8b36d00000000000000001",
"date": "2019-04-01T00:00:00.000Z",
"chats": 121,
"missedChats": 0
},
{
"websiteId": "4f8b36d00000000000000002",
"date": "2019-04-01T00:00:00.000Z",
"chats": 13,
"missedChats": 0
},
{
"websiteId": "4f8b36d00000000000000001",
"date": "2019-04-02T00:00:00.000Z",
"chats": 92,
"missedChats": 1
}]
Response should be:
a) If the date range is not provided, the sum should be calculated for the entire data set.
[{
"websiteId": "4f8b36d00000000000000001",
"chats": 121+92,
"missedChats": 0+1
},
{
"websiteId": "4f8b36d00000000000000002",
"chats": 13,
"missedChats": 0
},
]
b) if Date range newDate(2019,3,1) new Date(2019,2,1)
[{
"websiteId": "4f8b36d00000000000000001",
"chats": 121+92,
"missedChats": 0+1
},
{
"websiteId": "4f8b36d00000000000000002",
"chats": 13,
"missedChats": 0
},
]
A: Use reduce to sum the values, the below code may help you.
let data = [
{
websiteId: '4f8b36d00000000000000001',
date: '2019-04-01T00:00:00.000Z',
chats: 121,
missedChats: 0,
},
{
websiteId: '4f8b36d00000000000000002',
date: '2019-04-01T00:00:00.000Z',
chats: 13,
missedChats: 0,
},
{
websiteId: '4f8b36d00000000000000001',
date: '2019-04-02T00:00:00.000Z',
chats: 92,
missedChats: 1,
},
];
let result = data
.map(item => item.websiteId)
.filter((item, index, self) => self.indexOf(item) === index)
.map(websiteId =>
data
.filter(_item => _item.websiteId === websiteId)
.reduce(
(r, c) => {
r.chats += c.chats;
r.missedChats += c.missedChats;
r.websiteId = c.websiteId;
return r;
},
{chats: 0, missedChats: 0},
),
);
console.log(result);
| |
doc_23525190
|
#include<iostream>
using namespace std;
class student
{
int rollno;
public:
void getnumber()
{
cout << "Enter roll number: ";
cin >> rollno;
cout << endl;
}
int putnumber()
{
return rollno;
}
};
class test : virtual public student
{
float part1marks;
float part2marks;
public:
void getmarks()
{
cout << "Enter Marks(Parts 1 and 2): ";
cin >> part1marks >> part2marks;
cout << endl;
}
float putmarks()
{
float marks = part1marks + part2marks;
return marks;
}
};
class sports : virtual public student
{
float score;
public:
void getscore()
{
cout << "Enter score: ";
cin >> score;
cout << endl;
}
float putscore()
{
return score;
}
};
class result : public test, public sports
{
float total;
public:
void display()
{
test t;
sports s;
float sc = s.putscore();
float ms = t.putmarks();
total = sc + ms;
cout <<"Total marks= "<< total;
}
};
int main()
{
result obj;
obj.getnumber();
obj.getmarks();
obj.getscore();
obj.display();
system("pause");
return 0;
}
Expected Output
Enter roll number: 21
Enter Marks(Parts 1 and 2): 22.2
22.2
Enter score: 22.2
Total marks= 66.6 Press any key to continue . . .
Actual Output
Enter roll number: 21
Enter Marks(Parts 1 and 2): 22.2
22.2
Enter score: 22.2
Total marks= -3.22123e+08Press any key to continue . . .
A: You are creating new objects with uninitialized values in display().
void display()
{
test t; // <- This is a new object with uninitialized members variables
sports s; // <- This is a new object with uninitialized members variables
float sc = s.putscore(); // Replace with this->putscore() or simply putscore()
float ms = t.putmarks(); // Replace with this->putmarks() or simply putmarks()
total = sc + ms;
cout <<"Total marks= "<< total;
}
Multiple inheritance is almost never a good idea. Is your assignment really forcing you to do that?
| |
doc_23525191
|
In a canvas I display 9 images Every 8 rows I add a column. This is only for testing purposes. At the end the images should be hundreds.
I am trying to identify each image with a unique number. In order to do this I have an event which gives me the coordinates of the canvas. And here comes the noobs part. To get this unique number my code is
if x_on_grid==0 and y_on_grid==448:
index_bin=0
elif x_on_grid==0 and y_on_grid==384:
index_bin=1
elif x_on_grid==0 and y_on_grid==320:
index_bin=2
elif x_on_grid==0 and y_on_grid==256:
index_bin=3
elif x_on_grid==0 and y_on_grid==192:
index_bin=4
elif x_on_grid==0 and y_on_grid==128:
index_bin=5
elif x_on_grid==0 and y_on_grid==64:
index_bin=6
elif x_on_grid==0 and y_on_grid==0:
index_bin=7
elif x_on_grid==64 and y_on_grid==448: #new column
index_bin=8
elif x_on_grid==64 and y_on_grid==384:
index_bin=9
Of course it works perfectly, but it's not scientific at all.
I am trying to reduce all these lines with a loop but I can't get the number needed, only the last one.
Any ideas?
Best
A: Consider the following code
import tkinter as tk
def onclick(event):
print(vars(event))
nearest = event.widget.find_closest(event.x,event.y)
nearest_tag = event.widget.gettags(nearest)[0]
print(nearest_tag)
def drawCircles(c):
size = 20
for i in range(100):
row = i % 10
col = i // 10
x1 = (row * size) + 30
y1 = (col * size) + 30
c.create_oval((x1,y1,x1+size,y1+size),tags="image_%03d" % i)
root = tk.Tk()
c = tk.Canvas(root,width=400,height=400,bg="white")
c.grid()
c.bind("<Button-1>",onclick)
drawCircles(c)
root.mainloop()
I'm using circles(ovals) rather than images but the principle is still the same. I draw 100 circles and as I draw then I assign a tag to them in the format image_?. When I click on the canvas, the find_closest method is used to determine which of the circles is nearest to the click. It then looks up the tag (or tags) of that object and prints it out.
No need for long winded if-elif-else statements.
| |
doc_23525192
|
Here is what I have so far:
grades = ['62','68','93','75','89','85']
print grades [3]
def lettergrade (grades):
if grades >=90:
print('A')
elif grades >=80 and grades <90:
print('B')
elif grades >=70 and grades <80:
print('C')
elif grades >=60 and grades <70:
print('D')
else:
print('F')
print lettergrade (grades)
A: This should achieve what you are looking for:
grades = [62, 68, 93, 75, 89, 85]
def LetterGrade(grade):
if grade >= 90:
result = [grade, 'A']
elif grade >= 80 and grades < 90:
result = [grade, 'B']
elif grade >= 70 and grades < 80:
result = [grade, 'C']
elif grade >= 60 and grades < 70:
result = [grade, 'D']
else:
result = [grade, 'F']
return result
# call LetterGrade for each value in grades array
for grade in grades:
print(LetterGrade(grade))
You needed to loop for each value in the grades array. Also, try to get into the habit of following PEP 8 (Python style guide)
A: The problem that you are experiencing is grades contains only Strings. '1' is a String just like 'hello'. In python, Strings will not be equal to numbers, so comparing them will always be false. In addition, you are comparing the entirety of grades to a number, which will also evaluate to false. The comparison that you are looking for is if(grades[index]>= 90): where index is whatever index you are looking at.
The print() statement inside lettergrade() will only print out the grade, so change each print statement to `print('LETTER:' + value).
In addition, the method lettergrade() will only print out one thing, so there needs to be a loop to call it multiple times, with multiple values:
for value in grades:
lettergrade(value)
A: You need to be careful with indentation, python is a language indented.
Try this:
# define lettergrade function
def lettergrade(grades):
if grades >=90:
return('A')
elif grades >=80 and grades <90:
return('B')
elif grades >=70 and grades <80:
return('C')
elif grades >=60 and grades <70:
return('D')
else:
return('F')
grades = ['62','68','93','75','89','85']
for grade in grades: # iterate in grades
# call to lettergrade function -> lettergrade(grade)
print(grade, ' equivalent ', lettergrade(grade))
A: I am confused here, If you want the user input why do you want a list of values then? all you have to do is to wait for user input and check which grade that input belongs too. Please comment If you want some changes!!
x = raw_input("Enter Score: ")
score = float(x)
try:
if grades >=90:
print('A', score)
elif grades >=80 and grades <90:
print('B', score)
elif grades >=70 and grades <80:
print('C', score)
elif grades >=60 and grades <70:
print('D', score)
else:
print('F', score)
except:
print "Error"
| |
doc_23525193
|
We have a business case where we need to update all the documents in the index and remove one nested object everyday.
There is elasticsearch's Update by query API which will solve our purpose.
But in our java application we are using Java high level rest client. The update by query api is being supported by the rest client version 6.5.
Now if we upgrade the rest client to 6.5, we need to upgrade the elasticsearch version in our pom as well. Otherwise they aren't compatible.
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>${elasticsearch.version}</version>
</dependency>
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>${elasticsearch.version}</version>
</dependency>
So can we upgrade the client and elasticsearch version to 6.5 in our java service and still use the elasticsearch 6.3?
I tried it and it works, but just want to be thorough as we don't want our data to be corrupted.
Edit:
The Update by query is also available in 6.3 but this api uses the older Transportclient which is supposed to be deprecated soon.
A: According to Elasticsearch,
running a mixed version cluster is something we only recommend during the upgrade process, not as the status quo. Having older versions of nodes or clients in the cluster limits the support of newer features, as the older client simply doesn't know how to write or read requests in the newer binary format.
This should also apply the other way round (newer Client for old ES-Version)
In addidition, in this Recommendation, noted by @Samuel Kok, states:
The client should always be updated last, once all of the nodes in the cluster have been upgraded to the new major version.
A: Based on the Elastic Search Documentation
The High Level Client is guaranteed to be able to communicate with any
Elasticsearch node running on the same major version and greater or
equal minor version.
The 6.0 client is able to communicate with any 6.x Elasticsearch node,
while the 6.1 client is for sure able to communicate with 6.1, 6.2 and
any later 6.x version, but there may be incompatibility issues when
communicating with a previous Elasticsearch node version, for instance
between 6.1 and 6.0, in case the 6.1 client supports new request body
fields for some APIs that are not known by the 6.0 node(s).
In other words, the Java Rest Client should never be newer than the Elasticsearch node.
For your case, it strongly advised that you should either upgrade Elastic Search to 6.5 as well or downgrade your Java Rest Client back to 6.3.
Updated By Query is available in 6.3 as well so I don't see why you need to use version 6.5 of the Java Rest Client. Unless there is some new features within the Updated By Query API that is released in 6.5 which I'm unaware.
| |
doc_23525194
|
success: function(data)
{
//console.log('ticket added');
this.closeModal();
}
But it is not working, can anyone sort this out. Thanks in Advance
<script>
require(
[
'jquery',
'Magento_Ui/js/modal/modal'
],
function($, modal) {
var options = {
type: 'popup',
responsive: true,
innerScroll: true,
title: 'Test title',
buttons: [{
text: $.mage.__('Continue'),
class: '',
click: function () {
this.closeModal();
}
}]
};
var popup = modal(options, $('#events_popup'));
$("#click-me").on('click',function(){
$("#events_popup").modal("openModal");
});
});
</script>
<div id="events_popup" style="display: none;" class="events_popup">
<script type="text/javascript">
require(
[
'jquery'
],
function($,modal) {
$("#<?php echo $_product->getId()?>").submit(function(e) {
$.ajax({
type: "POST",
url: $(this).attr('action'),
data: $("#<?php echo $_product->getId()?>").serialize(),
showLoader: true,
success: function(data)
{
//console.log('ticket added');
document.close();
}
});
e.preventDefault();
});
}
);
</script>
</div>
A: I got the solution, we can destroy the modal with the following line of code.
$('#events_popup').modal('closeModal');
A: Have you tried
$('#yourmodalid').modal('hide');
| |
doc_23525195
|
But I just cannot figure out what I am doing wrong.
Many thanks in advance
protocol receivingStringDelegate:class {
func didReceiveString(message:String)
}
class GameScene: SKScene {
weak var gamescene_transmissiondelegate: receivingStringDelegate?
private func sendString(message:String){
gamescene_transmissiondelegate?. didReceiveString(message)
}
}
class SecondScene: SKScene, receivingStringDelegate {
// here I get stuck, what to do?
var gameScene : GameScene = GameScene()
override func didMove(to view: SKView) {
gameScene.gamescene_transmissiondelegate = self
}
func didReceiveString(message:String) {
print ("hi there", message)
}
}
A: I woudld do it with scene properties vs a global class
class ConnectionScene: SKScene {
private var player1pos: CGPoint = CGPoint.zero
private var player2pos: CGPoint = CGPoint.zero
///some code in this scene sets player positions
func startMultiplayerGame() {
//this assumes your scene is setup in the editor not programmatically
if let gameScene = GameScene(fileNamed: "GameScene") {
gameScene.scaleMode = .aspectFill
gameScene.player1pos = player1pos
gameScene.player2pos = player2pos
self.view?.presentScene(multiplayerScene, transition: SKTransition.reveal(with: .down, duration: 1.0))
}
}
}
class GameScene: SKScene {
var player1pos: CGPoint = CGPoint.zero
var player2pos: CGPoint = CGPoint.zero
override func sceneDidLoad() {
//sceneDidLoad happens first
super.sceneDidLoad()
//do setup that doesn't require passed in variables in here
//this isn't set from connectScene yet so won't have the values
print("player1pos \(player1pos)")
print("player2pos \(player2pos)")
}
override func didMove(to view: SKView) {
//didMove happens last and already has the variables assigned
//now do setup that requires these variables
//this now has value from connectScene
print("player1pos \(player1pos)")
print("player2pos \(player2pos)")
}
}
| |
doc_23525196
|
A: UPDATE: As tripleee pointed out, the Aho-Corasick algorithm seems very relevant to virus scanners. Here is some stuff to read:
http://www.dais.unive.it/~calpar/AA07-08/aho-corasick.pdf
http://www.researchgate.net/publication/4276168_Generalized_Aho-Corasick_Algorithm_for_Signature_Based_Anti-Virus_Applications/file/d912f50bd440de76b0.pdf
http://jason.spashett.com/av/index.htm
Aho-Corasick-like algorithm for use in anti-malware code
Below is my old answer. Its still relevant for easily detecting malware like worms which simply make copies of themselves:
I'll just write some of my thoughts on how AVs might work. I don't know for sure. If someone thinks the information is incorrect, please notify me.
There are many ways in which AVs detect possible threats. One way is signature-based
detection.
A signature is just a unique fingerprint of a file (which is just a sequence of bytes). In terms of computer science, it can be called a hash. A single hash could take about 4/8/16 bytes. Assuming a size of 4 bytes (for example, CRC32), about 67 million signatures could be stored in 256MB.
All these hashes can be stored in a signature database. This database could be implemented with a balanced tree structure, so that insertion, deletion and search operations can be done in O(logn) time, which is pretty fast even for large values of n (n is the number of entries). Or else if a lot of memory is available, a hashtable can be used, which gives O(1) insertion, deletion and search. This is can be faster as n grows bigger and a good hashing technique is used.
So what an antivirus does roughly is that it calculates the hash of the file or just its critical sections (where malicious injections are possible), and searches its signature database for it. As explained above, the search is very fast, which enables scanning huge amounts of files in a short amount of time. If it is found, the file is categorized as malicious.
Similarly, the database can be updated quickly since insertion and deletion is fast too.
You could read these pages to get some more insight.
Which is faster, Hash lookup or Binary search?
https://security.stackexchange.com/questions/379/what-are-rainbow-tables-and-how-are-they-used
A: Many signatures are anchored to a specific offset, or a specific section in the binary structure of the file. You can skip the parts of a binary which contain data sections with display strings, initialization data for internal structures, etc.
Many present-day worms are stand-alone files for which a whole-file signature (SHA1 hash or similar) is adequate.
The general question of how to scan for a large number of patterns in a file is best answered with a pointer to the Aho-Corasick algorithm.
A: I don't know how a practical AV works. but I think the question have some relative with finding words in a long text with a given dictionary.
For the above question, data structures like TRIE will make it very fast. processing a Length=N text dictionary of K words takes only O(N) time.
| |
doc_23525197
|
http://jsfiddle.net/ericclemmons/LEHLX/2/
Really, what it comes down to is the classic "assigning users to groups" issue. I have a list of users and a list of groups, but I'd like to be able to have nesting of the groups: user "Eric" would be in "Users", "Web", and "Administrators".
The problem is that I cannot drag a user to an empty <ul> in the list.
A: I had to reformat your HTML a little bit and change the group ID to classes, try the updated demo.
HTML
<h3>Groups</h3>
<ul>
<ul class="groups">
<span>Administrators</span>
<li></li>
</ul>
<ul class="groups">
<span>Web</span>
<li></li>
</ul>
</ul>
<hr />
<h3>Users</h3>
<ul id="users">
<li>Eric</li>
<li>Richard</li>
<li>Evan</li>
</ul>
Script
$('.groups').sortable({
revert: 'invalid',
placeholder: 'ui-state-highlight'
});
$('#users li').draggable({
connectToSortable: '.groups',
helper: 'clone'
});
I hope that is what you were trying to achieve.
Edit: Oh I forgot to add, I had to do this because it appears that sortable/draggable/droppable doesn't work on lists deeper than one level.
| |
doc_23525198
|
the problem is when the tasks are created automatically by the engine, it sets the parent task id with null.
Is there like an option when initiating the process to enable setting the parent id for the tasks automatically or how can i do this?
I need to have the previous task id with me at every step.
| |
doc_23525199
|
Assuming that the request is embedded into the HTML source as
<script type=\"text/javascript\" src=\"http://www.mydomain.com/generatejs.js\" charset=\"UTF-8\"></script>
And i have a PHP script that is called generatejs.js.php which outputs more JavaScript code
The Apache rewrite condition/rule are
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^([^\.]+)$ $1.php [NC,L]
But I am getting a 404 when trying to access http://www.mydomain.com/generatejs.js. Can someone please help me with the missing bit? :)
A: Do you mean this?
RewriteEngine on
RewriteRule ^generatejs.js$ generatejs.js.php
A: Your RewriteRule is not matching /generatejs.js because of the [^\.]+ (which is anything BUT a .) So, if you update it to the following, you should have better luck:
RewriteRule ^([^\.]+)\.js$ $1.js.php [NC,L]
Hope this helps.
A: RewriteEngine On
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^(.+)\.js$ $1.js.php [NC,L]
Now every smth.js file is redirected to smth.js.php
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.