text
stringlengths 15
59.8k
| meta
dict |
---|---|
Q: How to return List> using Hibernate I want to return a List of maps from my createNativeQuery().getResultList(), where each map is a pair key - value representing column name - value. I already tried to use direct in the method like this:
public List<Map<String, Object>> execQuery(String nativeQuery) {
return entityManager().query(nativeQuery).getResultList();
}
but it always return List. Someone knows if what I want is even possible?
The JPA implementation that I'm using is Hibernate. I'm currently using Java 8 (don't know if this information is relevant for my case).
Any help is welcome.
Thanks in advance.
A: You can to use the ResultTransformer to transform your results in a map form.
Following the oficial documentation
Like this:
List<Map<String,Object>> mapaEntity = session
.createQuery( "select e from Entity" )
.setResultTransformer(new AliasToEntityMapResultTransformer())
.list();
A: Please try with
Query q1 = entityManager().query(nativeQuery);
org.hibernate.Query hibernateQuery =((org.hibernate.jpa.HibernateQuery)q1) .getHibernateQuery();
hibernateQuery.setResultTransformer(AliasToEntityMapResultTransformer.INSTANCE);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/38533488",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Laravel 5 public folder asset management I have a file stored in public/files/sample.pdf. When I want to download the file using <a href="/public/files/sample.pdf">Download</a>. It says not found. What will be the correct path. Thank you.
A: /files/sample.pdf
You can always use
href="{{asset('files/sample.pdf')}}"
It will be easier
A: You should apply url function instead of paste the directory directly.
<a href="{{url('/files/sample.pdf'}}">Download</a>
A: If you're really looking for a download response when clicking the link, you should have the URL link to a controller method.
<a href="{{ url('route/to/method') }}">
Now in the controller method
return response()->download(public_path('files/sample.pdf'));
Laravel responses
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30473006",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: W3C Font-Family Parse error 'Open Sans', Helvetica, Arial, sans-serif; Why do I get an Parse error ( line 24 ) on this line of CSS?
font-family: 'Open Sans', Helvetica, Arial, sans-serif;
the full Code where I get this error is:
.btn {
display: inline-block;
*display: inline;
/* IE7 inline-block hack */
*zoom: 1;
border:none;
box-shadow: none;
text-shadow: none;
background: #212121;
overflow: hidden;
z-index: 1;
font: inherit;
display: inline-block;
box-sizing: border-box;
vertical-align: middle;
line-height: 40px;
min-height: 40px;
font-size: 13px;
text-decoration: none;
text-align: center;
padding: 0 33px;
overflow: hidden;
z-index: 1;
font-family: 'Open Sans', Helvetica, Arial, sans-serif;
font-weight: 300;
text-transform: uppercase;
letter-spacing: 0;
-webkit-transition: all 0.15s ease-in-out;
transition: all 0.15s ease-in-out;
-webkit-backface-visibility: hidden;
}
A: property: value pairs must go inside a ruleset.
font-family: 'Open Sans', Helvetica, Arial, sans-serif;
… is not a valid stylesheet.
foo {
font-family: 'Open Sans', Helvetica, Arial, sans-serif;
}
… is.
Re edit:
The errors you are seeing are a side effect of the IE7 hacks at the beginning of the ruleset.
Remove the IE7 hacks. The browser is a decade out of date and doesn't even get security updates now.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46867358",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: MySQL WHERE IN no result with error I'm writing this little import/export class, and whenever I run it, the query fails, stating:
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near ')' at line 1
This is the query I wrote:
SELECT
b.voorletters,
b.voornaam,
b.achternaam,
b.tussenvoegsel,
b.email
FROM
`fietsvoordeelshop_twc`.`fvs_bestellingen` as b
INNER JOIN
`fietsvoordeelshop_twc`.`fvs_bestellingen_producten` as bp ON bp.bestelling_id = b.id
INNER JOIN
`fietsvoordeelshop_twc`.`fvs_producten` as p ON bp.product_id = p.id
WHERE
p.merk_id IN (3,6)
AND
p.cat_id IN (1)
GROUP BY b.email
The WHERE IN clause is being generated using PHP.
This works fine whenever there are results to be found, but if no results are found, the error occurs instead of returning, well, nothing. The query works fine using Workbench and HeidiSQL.
I'm using the old default MySQL library that comes with PHP.
Any help on this would be great. I tried and tried!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/12834897",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Parse Hello World warning - A long-running operation is being executed on the main thread I get the following error:
Warning: A long-running operation is being executed on the main
thread. Break on warnBlockingOperationOnMainThread() to debug.
Code as follows:
- (IBAction)createButtonClicked:(id)sender {
PFObject *demoObject = [PFObject objectWithClassName:
@"Demo"]; // 1
[demoObject setObject:@"data value" forKey:@"dataColumn"]; // 2
[demoObject save]; // 3
}
A: Please try this way,
PFObject * demoObject = [PFObject objectWithClassName:@"Demo"];
demoObject[@"dataColumn"] = @"data value";
[demoObject saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error)
{
// take any action after saving.
}];
| {
"language": "en",
"url": "https://stackoverflow.com/questions/29763462",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to send a GET request in html Is this possible? If not what are some alternatives..
Simply I want to send a GET request to
//steamgaug.es/api/v2
"ISteamClient": {
"online": 1
},
and have it respond to this i.e
if ISteamClient online:1
then make it do something
A: It's not possible with HTML. But it is definitely possible with Javascript, which you can add to any HTML code.
For code example please refer to this stackoverflow thread!
Your code will probably look like this:
<html>
<body>
<script>
var text = httpGet("https://steamgaug.es/api/v2");
obj = JSON.parse(text);
alert(obj.ISteamClient.online);
function httpGet(theUrl)
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", theUrl, false ); // false for synchronous request
xmlHttp.send( null );
return xmlHttp.responseText;
}
</script>
</body>
</html>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/33453435",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: .append() in Python is very slow. Is there a way to improve it? Consider:
i = 2
feature_vector_set = []
while i < 2405 - 2:
j = 2
while j < 1200 - 2:
block = diff_image[i-2:i+3, j-2:j+3]
feature = block.flatten()
feature_vector_set.append(feature)
j = j+1
i = i+1
diff_image is of type int16 with shape(2405, 1200).
The whole loop takes 40 minutes to run and is mainly caused by the following line:
feature_vector_set.append(feature)
Is there an alternative way to achieve the same result?
A: Try using a deque. It's part of the Python collections, and it uses a doubly-linked list internally.
from collections import deque
i = 2
feature_vector_set = deque()
while i < 2405 - 2:
j = 2
while j < 1200 - 2:
block = diff_image[i-2:i+3, j-2:j+3]
feature = block.flatten()
feature_vector_set.append(feature)
j = j+1
i = I+1
feature_vector_list = list(feature_vector_set)
You can find the time complexities of common operations on Python data types here.
Deque documentation
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58741519",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to rotate NSButton in clockwise direction from its center point in Cocoa? I want to set animation for NSButton in my mac application.
I followed the below link for the same, but below code is working for iOS, not for Mac.
How to rotate a flat object around its center in perspective view?
What I want to achieve:
Basically, I want to rotate an image clockwise from the center point of the image just like the above code works for iOS.
Issue currently having:
In Mac app, the image is rotating from its corner point, not from the center.
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
animation.fromValue = [NSNumber numberWithFloat:0];
animation.toValue = [NSNumber numberWithFloat:2 * M_PI];
animation.duration = 1.0;
animation.repeatCount = INFINITY;
animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
[btnScan setWantsLayer:YES];
[btnScan.layer addAnimation:animation forKey:@"transform.rotation.z"];
A: The point around which rotation occurs is affected by the layer's position and anchorPoint properties, see Anchor Points Affect Geometric Manipulations. The default values for these properties do not appear to match the documentation, at least under macOS 10.11 and whichever version you used.
Try setting them by adding four lines as follows:
[btnScan setWantsLayer:YES];
CALayer *btnLayer = btnScan.layer;
NSRect frame = btnLayer.frame;
btnLayer.position = NSMakePoint(NSMidX(frame), NSMidY(frame)); // position to centre of frame
btnLayer.anchorPoint = NSMakePoint(0.5, 0.5); // anchor point to centre - specified in unit coordinates
[btnScan.layer addAnimation:animation forKey:@"transform.rotation.z"];
It doesn't actually matter in which order you set these properties the result should be an image rotation around the centre point of the button.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/51113571",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Swift - Parse Query whereKey contains I have a parse object that i have saved to the LDS and i want to search for it via 1 key and an entry under another key.
Key: This is fine.
checkQuery.whereKeyExists("File-rZVgZNpNuB")
Key that contains: This does not work.
checkQuery.whereKey("seachKey", contains: "myItem0000000000")
The console is printing:
-[__NSArrayM length]: unrecognized selector sent to instance 0x7c09bbb0
I'm guessing because the mySearchString is an object within the "searchKey" field which returns an NSMutable Array. its easy enough to get the data out of the array once i have the object but i need to search for this string in the "searchKey" field to find the object. For various reasons i can not just save the object with a key of "myItem0000000000". perhaps i could add it as a third key when i save the object but that seems a bit messy.
It is there, if i look at the object through SQL Lite i can see it.
{"className":"downloadedAudio","__complete":true,"__operations":[{"ACL":{"*":{"read":true},"rZVgZNpNuB":{"write":true,"read":true}},"File-rZVgZNpNuB":{"__op":"Add","objects":[{"url":"https:\/\/parse-server-nextbreath-s3-bucket.s3.amazonaws.com\/b5d2110dce0b50dc3a1c620731fad66e_The%20Name%20of%20the%20Wind%2024-92.mp3","name":"b5d2110dce0b50dc3a1c620731fad66e_The Name of the Wind 24-92.mp3","__type":"File"}]},"__uuid":"77AE38AF-1ADB-4795-9BB0-5A5AB7205E28","__updatedAt":{"iso":"2017-03-03T21:28:19.637Z","__type":"Date"},"searchKey":{"__op":"Add","objects":["myItem0000000000"]}}],"isDeletingEventually":0}
---- EDIT ----
searching:
let searchKey = "File-\(PFUser.current()!.objectId!)"
let checkQuery = PFQuery(className: "downloadedAudio")
checkQuery.whereKeyExists(searchKey)
//checkQuery.whereKeyExists(item.name)
//checkQuery.whereKey("seachKey", contains: item.name)
checkQuery.fromLocalDatastore()
checkQuery.getFirstObjectInBackground(block: { (object, error) in
if object != nil {
// object?.unpinInBackground()
object?.unpinInBackground(block: { (success, error) in
if success {
saving:
let query = PFQuery(className: "Part")
query.whereKey("objectId", equalTo: selectedObjectId)
query.getFirstObjectInBackground { (object, error) in
if error != nil || object == nil {
// ----
} else {
let searchKey = "File-\(PFUser.current()!.objectId!)"
downloadedAudio.add(object?.object(forKey: "partAudio") as! PFFile, forKey: file)
downloadedAudio.add(object?.object(forKey: "partName") as! String, forKey: searchKey)
let downloadedFile = object?.object(forKey: "partAudio") as! PFFile
downloadedFile.getDataInBackground({ (data, error) in
A: I do believe you are getting that error because "File-rZVgZNpNuB" is an invalid key. Remember that keys can only start with a lowercase letter.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42589092",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Mailgun Attachments with PHP cURL - No SDK Catch Up Quickly: Due to the nature of what I've most recently found. I have recreated this question in a different category because this does not seem to be a Mailgun issue. That question can be found here:
PHP 7.2 CURLFile Gives "Invalid Filename" Warning
I'm aware of the SDK and that Mailgun does not offer support outside of it, and that's why I'm trying to get some support here for a light-weight implementation I'm working on; it was actually already complete and working until I decided to extend it with attachments, and it's still working, just no attachments are being added to the email. I have reviewed a few previous questions, and I can't seem to get attachments to work based on the solutions offered.
Info
*
*PHP 5.5 or Greater in Use (php 7.2 in my specific instance)
*Attached files have been confirmed that they exist and are readable by PHP/Apache
*php-curl and related php libraries are up-to-date
*Sensitive variables in the code and output below have been modified (including the various email addresses/domains)
*Emails deliver exactly as intended aside from the lack of attachments
*This is a snippet from within an object, thus the references to $this. All variables are loading correctly.
*Currently testing with a simple text email (not HTML).
*The functionality is configured to send multiple attachments using attachment[] key approach, which is documented as working on other SO threads, BUT I have also tried using just one attachment approach and setting just the attachment key -- the result is the same.
Code Block
$curl = curl_init();
$log->AddStep('Mailgun', 'API send request starting...');
$postUrl = 'https://' . $this->host . self::API_URL_BASE . '/' . $this->domain . '/messages';
$curlOpts = array(
CURLOPT_POST => 1,
CURLOPT_URL => $postUrl,
CURLOPT_TIMEOUT => 20,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
CURLOPT_USERPWD => 'api:' . $this->apiKey
);
$postFields = array(
'from' => $email->from,
'to' => $email->to,
'subject' => $email->subject
);
if (strlen($email->cc) > 0) {
$postFields['cc'] = $email->cc;
}
if (strlen($email->bcc) > 0) {
$postFields['bcc'] = $email->bcc;
}
if (strlen($email->html) > 0) {
$postFields['html'] = $email->html;
} else {
$postFields['text'] = $email->text;
}
if (count($email->attachments) > 0) {
// Curl attachments for < PHP5.5 not supported
if (function_exists('curl_file_create')) {
$curlOpts[CURLOPT_SAFE_UPLOAD] = 1; // for < PHP 7
//$curlOpts[CURLOPT_HTTPHEADER] = array('Content-Type: multipart/form-data');
for ($i = 1; $i <= count($email->attachments); $i++) {
$postFields['attachment[' . $i . ']'] = curl_file_create($email->attachments[$i - 1], "text/csv", basename($email->attachments[$i - 1]));
}
} else {
\D3DevelForms\Models\Error::CreateAndSaveSystemError(
$plugin,
\D3DevelForms\Common::ERROR_WARNING,
'PHP 5.5 or newer required for Mailgun Attachments',
\D3DevelForms\Models\Error::ERROR_CODE_API_MAILGUN_LOCAL_ERROR,
'You are using an outdated version of PHP. Email attachments via Mailgun will be ignored.');
}
}
$curlOpts[CURLOPT_POSTFIELDS] = $postFields;
$log->UpdateDebugLog('Mailgun API Options', $curlOpts);
curl_setopt_array($curl, $curlOpts);
$curl_response = curl_exec($curl);
$info = curl_getinfo($curl);
Curl Options ($curlOpts)
Array
(
[47] => 1
[10002] => https://api.mailgun.net/v3/devtester.devtest.com/messages
[13] => 20
[19913] => 1
[107] => 1
[10005] => api:APIKEY
[-1] => 1
[10015] => Array
(
[from] => Dev Tester <[email protected]>
[to] => [email protected]
[subject] => Form Summary
[text] => My Text Content
[attachment[1]] => CURLFile Object
(
[name] => /var/www/path_to/my_file.csv
[mime] => text/csv
[postname] => my_file.csv
)
)
)
Curl Info Returned ($info)
Array
(
[url] => https://api.mailgun.net/v3/devtester.devtest.com/messages
[content_type] => application/json
[http_code] => 200
[header_size] => 388
[request_size] => 312
[filetime] => -1
[ssl_verify_result] => 0
[redirect_count] => 0
[total_time] => 0.503718
[namelookup_time] => 0.004273
[connect_time] => 0.0932
[pretransfer_time] => 0.279756
[size_upload] => 1021
[size_download] => 105
[speed_download] => 208
[speed_upload] => 2026
[download_content_length] => 105
[upload_content_length] => 1021
[starttransfer_time] => 0.368725
[redirect_time] => 0
[redirect_url] =>
[primary_ip] => Y.Y.Y.Y
[certinfo] => Array
(
)
[primary_port] => 443
[local_ip] => X.X.X.X
[local_port] => 38636
)
Mailgun API Response
{
"id": "<[email protected]>",
"message": "Queued. Thank you."
}
Mailgun Log
{
"tags": [],
"envelope": {
"sender": "[email protected]",
"transport": "smtp",
"targets": "[email protected]"
},
"storage": {
"url": "https://sw.api.mailgun.net/v3/domains/devtester.devtest.com/messages/KK",
"key": "KK"
},
"log-level": "info",
"id": "II",
"campaigns": [],
"method": "http",
"user-variables": {},
"flags": {
"is-routed": false,
"is-authenticated": true,
"is-system-test": false,
"is-test-mode": false
},
"recipient-domain": "gmail.com",
"timestamp": 1550085991.344005,
"message": {
"headers": {
"to": "[email protected]",
"message-id": "[email protected]",
"from": "Dev Tester <[email protected]>",
"subject": "Form Summary"
},
"attachments": [],
"size": 945
},
"recipient": "[email protected]",
"event": "accepted"
}
I've been struggling with this for a couple days now with the goal of avoiding this question simply because of the anticipated resistance to not using the SDK, which I consider a last resort since this is all but working without needing to load an entire library.
Is there anything you guys can see that would prevent this code from sending the attachment via PHP + cURL?
Related Questions Reviewed:
*
*Mailgun send mail with attachment
*Using PHP Curl and Mailgun API to send mail with attachment using remote file
*Mailgun Sent mail With attachment
Update: When testing with cURL from command line, it does work as intended including when I run it as an the apache process.
sudo -u apache curl -s --user 'api:APIKEY' \
https://api.mailgun.net/v3/devtester.devtest.com/messages \
-F from='Dev Tester <[email protected]>' \
-F to='[email protected]' \
-F subject='Hello' \
-F text='Testing some Mailgun awesomness!' \
-F attachment=@/var/www/path_to/my_file.csv
{
"id": "<[email protected]>",
"message": "Queued. Thank you."
}
Update (Closing in on the Problem):
I am getting a PHP warning in the Apache logs, that appears as follows:
"PHP Warning: curl_setopt_array(): Invalid filename for key attachment[1]"
This is tricky because I have confirmed the following:
*
*The file exists
*The file is readable by Apache
*The file path does not include any characters outside of letters, numbers, slashes and hyphens
*Because the file is generated within the same thread, I have tried referencing a static file, but the result is the same.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/54678804",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Yii - echo the last query I have used Codeigniter before and it has a feature that will echo the last database query - really useful for debugging.
eg...
$this->getSomeData->findAll();
Yii command to output this single query e.g SELECT * FROM TABLE...
Does Yii have a similar feature to simply show the very last query executed?
A: Try this in your config file. You can see the query and other details at the bottom of the page.
'db'=>array(
'enableProfiling'=>true,
'enableParamLogging' => true,
),
'log'=>array(
'class'=>'CLogRouter',
'routes'=>array(
…
array(
'class'=>'CProfileLogRoute',
'levels'=>'profile',
'enabled'=>true,
),
),
),
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21231729",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: What is the risk of updating Registry settings programatically? I am trying to change the proxy settings to Enabled/Disabled for Internet Explorer programatically using C#. This to toggele between web sites that would require proxy or not.
My Code:
string key = "Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings";
RegistryKey RegKey = Registry.CurrentUser.OpenSubKey(key, true);
RegKey.SetValue("ProxyEnable", 1);
Most articles I referred to for updating the registry indicate there is a risk of doing so.
I want to know
*
*What are the risks involved in executing the above code
*Is there any mitigation I can do to cover the risks. For example, taking a registry backup for the particular key.
A: The risk of changing the registry is simply that you can damage the system. If you really want to run it on a customers machine:
*
*Read all the documentation you can find about the registry entries you change
*Take into account that different windows versions and different product versions may have different registry entries
*Ask someone who ever changed these values
*Make sure your application will have the permission to do this (say: run as administrator, which should not be done for regular usage. Only for instance in an installer).
*Make sure you can uninstall the changes
A: The registry is an environment that is controlled by the OS and may be subject of unexpectable updates from it. I think that the main risk is to be unable to know what really happens with your data (for example : if Windows thinks it is a good idea to reset or overwrite your values, you lose it all).
Also, like someone said in a comment to another answer, invalid entries may lead to data loss, especially if your data exceeds the maximum length allowed by the registry.
If you need to modify the registry, you may test if the key do exist and keep trace of original values before overwriting. Of course, you need to be sure that altering the key won't have unexpected effects.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/13833669",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: SCM Poll in jenkins multibranch pipeline Wanted to accommodate scheduled build starting 12AM every 3 hrs till 3PM on every weekday(mon-fri). It should be triggered build only if anything is committed into github repository.
Please provide the exact code as few code is working for multi-branch but not for above schedule.
A: Sorry what do you mean by the scheduled "build"?
*
*Do you want the Multi-Branch to check for more branches on your given interval?
If so you can only do it by "Scan Multibranch Pipeline with defaults Triggers"
*Do you want to issue a build on the branch when there is change on it?
Noted that the option in
the mult-branch folder > "Scan Multibranch Pipeline with defaults Now" and get all current branches > status > the jobs > View Configuration
is read only.
So, to alter the option, from https://issues.jenkins-ci.org/browse/JENKINS-33900?focusedCommentId=326181&page=com.atlassian.jira.plugin.system.issuetabpanels%3Acomment-tabpanel#comment-326181
, I think you should use the Jenkinsfile to do theSCM for every job.
So, for all jobs you need to configure for SCM poll,
include a Jenkinsfile on Git for each of them (Don't forget to install the pipeline-model-definition plugin and all its dependent plugins):
pipeline {
triggers {
pollSCM('H 0-15/3 * * H(1-5)')
}
agent any
stages{
stage('Build') {
steps {
echo 'Building.. or whatever'
}
}
}
}
That should do the job, at least it works for me``
Hope it helps
| {
"language": "en",
"url": "https://stackoverflow.com/questions/53388927",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: Error on ConfigureAwait(false) I am trying to retrieve some data from an API, the following is my piece of code that makes the request after authenticating and assigning the completed URL.
public async Task<T> GetAPIData<T>(string url)
{
using (var client = HttpClientSetup())
{
var response = await client.GetAsync(url).ConfigureAwait(false);
var JsonResponse = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
return JsonConvert.DeserializeObject<T>(JsonResponse);
}
}
private HttpClient HttpClientSetup()
{
var client = new HttpClient { BaseAddress = new Uri(apiBaseUrl) };
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = authenticationHeader;
return client;
}
I am getting an error on the line with ConfigureAwait(false);
as
"HTTPResponseMessage does not contain a definition for ConfigureAwait"
. Could anyone help me as to what might be going wrong?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36083050",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to get google recaptcha Public key from drupal API? I need to render the recaptcha manually and therefore I need a way to get the google recaptcha "Public key" from dupal 7 API.
It is currently in this path in the admin panel:
admin/config/spam_protection/google_recaptcha
A: For anyone come across this problem, I was able to get both secret key and public key the way it was retrieved in the google_recaptcha module as shown below.
variable_get('google_recaptcha')['public_key'];
variable_get('google_recaptcha')['secret_key'];
| {
"language": "en",
"url": "https://stackoverflow.com/questions/35407027",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to get all table names in android sqlite database? I have tried this code
Cursor c=db.rawQuery("SELECT name FROM sqlite_master WHERE type = 'table'",null);
c.moveToFirst();
while(!c.isAfterLast()){
Toast.makeText(activityName.this, "Table Name=> "+c.getString(0),
Toast.LENGTH_LONG).show();
}
But it throws the error:
"android.database.sqlite.SQLiteException: no such table: sqlite_master(code 1):, while
compiling: SELECT name FROM sqlite_master WHERE type='table'"
How to fetch all the table names?
A: To get table name with list of all column of that table
public void getDatabaseStructure(SQLiteDatabase db) {
Cursor c = db.rawQuery(
"SELECT name FROM sqlite_master WHERE type='table'", null);
ArrayList<String[]> result = new ArrayList<String[]>();
int i = 0;
result.add(c.getColumnNames());
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
String[] temp = new String[c.getColumnCount()];
for (i = 0; i < temp.length; i++) {
temp[i] = c.getString(i);
System.out.println("TABLE - "+temp[i]);
Cursor c1 = db.rawQuery(
"SELECT * FROM "+temp[i], null);
c1.moveToFirst();
String[] COLUMNS = c1.getColumnNames();
for(int j=0;j<COLUMNS.length;j++){
c1.move(j);
System.out.println(" COLUMN - "+COLUMNS[j]);
}
}
result.add(temp);
}
}
A: Checked, tested and functioning. Try this code:
Cursor c = db.rawQuery("SELECT name FROM sqlite_master WHERE type='table'", null);
if (c.moveToFirst()) {
while ( !c.isAfterLast() ) {
Toast.makeText(activityName.this, "Table Name=> "+c.getString(0), Toast.LENGTH_LONG).show();
c.moveToNext();
}
}
I am assuming, at some point down the line, you will to grab a list of the table names to display in perhaps a ListView or something. Not just show a Toast.
Untested code. Just what came at the top of my mind. Do test before using it in a production app. ;-)
In that event, consider the following changes to the code posted above:
ArrayList<String> arrTblNames = new ArrayList<String>();
Cursor c = db.rawQuery("SELECT name FROM sqlite_master WHERE type='table'", null);
if (c.moveToFirst()) {
while ( !c.isAfterLast() ) {
arrTblNames.add( c.getString( c.getColumnIndex("name")) );
c.moveToNext();
}
}
A: Try adding the schema before the table
schema.sqlite_master
From SQL FAQ
If you are running the sqlite3 command-line access program you can type ".tables" to get a list of all tables. Or you can type ".schema" to see the complete database schema including all tables and indices. Either of these commands can be followed by a LIKE pattern that will restrict the tables that are displayed.
From within a C/C++ program (or a script using Tcl/Ruby/Perl/Python bindings) you can get access to table and index names by doing a SELECT on a special table named "SQLITE_MASTER". Every SQLite database has an SQLITE_MASTER table that defines the schema for the database. The SQLITE_MASTER table looks like this:
CREATE TABLE sqlite_master (
type TEXT,
name TEXT,
tbl_name TEXT,
rootpage INTEGER,
sql TEXT
);
A: Try this:
SELECT name FROM sqlite_master WHERE type = "table";
A: Change your sql string to this one:
"SELECT name FROM sqlite_master WHERE type='table' AND name!='android_metadata' order by name"
A: I tested Siddharth Lele answer with Kotlin and Room, and it works as well.
The same code but using Kotlin and Room is something like that:
val cursor = roomDatabaseInstance.query(SimpleSQLiteQuery("SELECT name FROM sqlite_master WHERE type='table' AND name NOT IN ('android_metadata', 'sqlite_sequence', 'room_master_table')"))
val tableNames = arrayListOf<String>()
if(cursor.moveToFirst()) {
while (!cursor.isAfterLast) {
tableNames.add(cursor.getString(0))
cursor.moveToNext()
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/15383847",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "44"
} |
Q: Passing data to a controller with $.ajax (MVC 4) I have the following editor template:
DropDownListEditorTemplate
@model DropDownListViewModel
<script type="text/javascript">
$(function() {
$("select").on("change", function () {
$.ajax({
type: "POST",
url: '@Url.Action("ListItemChanged", "Controller")',
data: { "Value": "@Model.Items.FirstOrDefault(x => x.Selected).Value" }
});
});
})
</script>
@Html.DropDownListFor(m => m.Value, Model.Items, "(Select)")
Controller
public ActionResult ListItemChanged(string selectedItem)
{
// Stuff.
}
The problem is that when the editor template loads, I get an error saying that @Model.Items is null ("Object reference not set to an instance of an object"). That makes sense, except why would that line be evaluating without any select items changing? Even when I change the $.ajax call to only execute when 1 == 2, it still gives me that error. So clearly that line is being evaluated even when the jQuery function isn't executing.
Given that, how do I prevent that error from occurring? @Model.Items.First(x => x.Selected).Value is only going to have a value once a drop down list item has been selected.
A: Try this:
@model DropDownListViewModel
<script type="text/javascript">
$(function() {
$("select").on("change", function () {
$.ajax({
type: "POST",
url: '@Url.Action("ListItemChanged", "Controller")',
data: { "Value": $(this).val() }
});
});
})
</script>
@Html.DropDownListFor(m => m.Value, Model.Items, "(Select)")
A: What you have to understand is, the @expressions are parsed inside the server. You also have to understand that MVC model binder distinguishes the fields based on their name. Inside the data object of the jquery ajax function, where you are passing the object literal, you have to specify the name of the variable as your action method is expecting it to be (in your case, selectedItem). So the correct approach should be:
$("select").on('change', function () {
$.ajax({
type: 'POST',
url: '@Url.Action("ListItemChanged", "Controller")',
data: { "selectedItem": $(this).val() }
});
});
//Server
[HttpPost]
public ActionResult ListItemChanged(string selectedItem)
{
// Stuff.
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/29475585",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Error: Module administration/tfasettings not found I'm busy working on developing some plugins and apps, and when i am running c8y server locally and i try to enter Administration, i keep getting the following error:
Error: Module administration/tfasettings not found
Any ideas?
A: We have already fixed the issue for versions >= 9.1.0. Please try to install version 9.1.0 (or higher) with c8y install command. If administration/tfasettings
is still missing use npm cache clean --force and then once again try to install version 9.1.0 (or higher) with c8y install command.
Best regards
Dawid
| {
"language": "en",
"url": "https://stackoverflow.com/questions/49155214",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: iTextSharp table layout problems I'm having problems creating a particular layout in iTextSharp using tables.
I begin the document by creating a table that splits the page in two, and in each of these columns I then insert an additional table with x rows and 1 column each.
The reason I want to do it like this is because I want a layout resembling this HTML.
But what is happening is the following:
The tables which as per the code are independent seem linked together.
OLD CODE
private void AddBody()
{
Image smallerLogo = Image.GetInstance(_logo);
smallerLogo.ScaleAbsolute(100f, 100f);
Image normalLogo = Image.GetInstance(_logo);
ExtendedTable table = new ExtendedTable(2, 1, true, false, true);
table.SetWidths(new[] { 50, 50 });
ExtendedTable col1 = new ExtendedTable(1, 6, true, false, false);
col1.AddCell(new ExtendedCell(new Chunk("Impressions", _headingFont), false));
col1.AddCell(new ExtendedCell(smallerLogo, false));
col1.AddCell(new ExtendedCell(new Chunk("Visitor funnel", _headingFont), false));
col1.AddCell(new ExtendedCell(smallerLogo, false));
col1.AddCell(new ExtendedCell(new Chunk("Shortlists", _headingFont), false));
col1.AddCell(new ExtendedCell(smallerLogo, false));
ExtendedTable col2 = new ExtendedTable(1, 6, true, false, false);
col2.AddCell(new ExtendedCell(new Chunk("Leads", _headingFont), false));
col2.AddCell(new ExtendedCell(normalLogo, false));
col2.AddCell(new ExtendedCell(new Chunk("Demographics", _headingFont), false));
col2.AddCell(new ExtendedCell(normalLogo, false));
table.AddCell(new ExtendedCell(col1, false));
table.AddCell(new ExtendedCell(col2, false));
_document.Add(table);
}
NEW CODE
private void AddBody()
{
Image smallerLogo = Image.GetInstance(_logo);
smallerLogo.ScaleAbsolute(60.0f, 60.0f);
Image normalLogo = Image.GetInstance(_logo);
PdfPTable table = new PdfPTable(2);
table.SetWidths(new[] { 50, 50 });
PdfPTable col1 = new PdfPTable(1);
col1.AddCell("Impressions");
col1.AddCell(new PdfPCell(smallerLogo));
col1.AddCell("Visitor funnel");
col1.AddCell(new PdfPCell(smallerLogo));
col1.AddCell("Shortlists");
col1.AddCell(new PdfPCell(smallerLogo));
PdfPTable col2 = new PdfPTable(1);
col2.AddCell("Leads");
col2.AddCell(normalLogo);
col2.AddCell("Demographics");
col2.AddCell(normalLogo);
table.AddCell(col1);
table.AddCell(col2);
_document.Add(table);
}
Where ExtendedCell and ExtendedTable are small classes that remove the table borders.
Any ideas?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/19251316",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Datagridview Data Population from the database where one cell is a combobox c# I have a datagrid view that I need to populate with content from the database.
My database content is in a datatable that typically looks like this :
Prod id ProdName Version
1 abc 1.1
1 abc 2.1
1 abc 3.1
2 def 3.1
2 def 3.2
3 ghi 1.1
4 jkl 1.1
4 jkl 1.2
Now my problem is that when i display the content in a datagrid view, I want it to be displayed as such, where version should be a dropdown comboboxcell so each product has a list of versions :
Prod id ProdName Version
1 abc 1.1
2.1
3.1
2 def 3.1
3.2
3 ghi 1.1
4 jkl 1.1
1.2
Please help me in achieving this. I cannot directly say :
dataGridView1.DataSource = getdatatable()
So please do not suggest that as it gives me a flat view with no combobox. Eagerly looking forward to a positive reply. Is it possible to draw each row in the datagrid view and populate the combobox in that row with all the versions available for a product ? Please help. TIA
A: Essentially, you need to sort through your queried data, saving each unique product with a list of all its versions. Then you would manually create the columns for your DataGridView as I'll describe below.
To mock out this scenario I created the following object class:
// The type of binding object for your dgview source.
public class Product
{
public Product()
{
this.Version = new List<double>();
}
public int ID { get; set; }
public string Name { get; set; }
public List<double> Version { get; set; }
}
In your query returning all the objects, I would do something like this:
public BindingList<Product> YourQueryCall()
{
BindingList<Product> products = new BindingList<Product>();
/*
* Your code to query the db.
*/
while reader.Read()
{
Product existingProduct = new Product();
int id = // value from the reader
string name = // value from the reader
double version = // value from the reader
try
{
existingProduct = products.Single(p => p.ID == id && p.Name == name);
existingProduct.Version.Add(version);
}
catch // No product yet exists for this id and name.
{
existingProduct.ID = id;
existingProduct.Name = name;
existingProduct.Version.Add(version);
products.Add(existingProduct);
}
}
return products;
}
That will store only unique products and their lists of versions. And in the form, to show each row's unique list of versions in a ComboBoxColumn:
public Form1()
{
InitializeComponent();
this.Products = YourQueryCall();
this.FillDGView();
}
public BindingList<Product> Products { get; set; }
public void FillDGView()
{
DataGridViewTextBoxColumn col1 = new DataGridViewTextBoxColumn();
col1.Name = "Product ID";
col1.ValueType = typeof(int);
dataGridView1.Columns.Add(col1);
DataGridViewTextBoxColumn col2 = new DataGridViewTextBoxColumn();
col2.Name = "Product Name";
col2.ValueType = typeof(string);
dataGridView1.Columns.Add(col2);
DataGridViewComboBoxColumn col3 = new DataGridViewComboBoxColumn();
col3.Name = "Version";
col3.ValueType = typeof(double);
dataGridView1.Columns.Add(col3);
for (int i = 0; i < this.Products.Count; i++)
{
DataGridViewRow row = (DataGridViewRow)(dataGridView1.Rows[0].Clone());
DataGridViewTextBoxCell textCell = (DataGridViewTextBoxCell)(row.Cells[0]);
textCell.ValueType = typeof(int);
textCell.Value = this.Products[i].ID;
textCell = (DataGridViewTextBoxCell)(row.Cells[1]);
textCell.ValueType = typeof(string);
textCell.Value = this.Products[i].Name;
DataGridViewComboBoxCell comboCell = (DataGridViewComboBoxCell)(row.Cells[2]);
comboCell.ValueType = typeof(double);
comboCell.DataSource = this.Products[i].Version;
comboCell.Value = this.Products[i].Version[0];
dataGridView1.Rows.Add(row);
}
}
Hope this helps!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/27281660",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Simultaneous multiple key press release delay I am developing 2D game and faced problem with simultaneous multiple key press / release detection needed, for instance, for character diagonal movement.
Problem is when I "simultaneous" (it has nothing to do with my reaction I press / release very quickly) press / release multiple (two) keys delay between messages often is much more than single frame (16ms with VSync), for instance, it can reach 50-100 millisecond, so character starts moving single direction and only after slight delay diagonal (as intended).
Is it normal for WinAPI messages or is it hardware limit? Is it possible to detect input faster or how games deal with it?
Only solution that kinda helps is process inputs in game logics with periodic delay (for instance every 100 ms), but this sacrifices control responsiveness very much.
I am dispatching WinAPI WM_KEYDOWN / WM_KEYUP messages in while loop.
while (PeekMessage(&message, 0, 0, 0, PM_REMOVE))
DispatchMessage(&message);
I also tried to dispatch input in seperate from render thread with GetMessage.
Delay measurement test project : pastebin
Actual OpenGL diagonal movement test project : pastebin
A: I can't answer your question about why your processing is getting delayed, but regarding your question about getting faster input, try using Raw Input instead. That will allow the keyboard to send its own keystroke events directly to you so you do not have to wait for the OS to receive, interpret, and dispatch the keystrokes to you, which takes more time.
A: The straight answer is yes, delays of the order of 50 ms or so are common in processing key presses through the normal Windows message queue. I believe there are multiple sources of these delays.
First, the keyboard itself has a serial interface. Historically this was very slow, and probably tied to the underlying 55ms clock. A USB keyboard is likely to be much faster but the point is that each individual key press or release will be sent and processed individually, even if they appear to absolutely simultaneous.
The Windows code paths leading to the processing of Windows messages are long and the flow of intervening messages can be high. If there are many messages to process your simultaneous key releases may become separated by many other messages. You can reduce this by peeking messages instead of waiting for them, to a point.
So you really will have to use Raw Input, you're going to need to handle events quickly and you still need to anticipate delays. My guess is you're going to need to 'debounce' your input to the tune of at least 20ms to get smooth behaviour. There is lots of reading out there to help you on your way.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/22392683",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Is there a way to Install Tensorflow2-GPU in Google Colab for good? Is there a way I can Install Tensorflow 2- GPU in Google Colab without Installing it every time new after the Runtime ran out?
Right now I have:
!pip install -U tensorflow-gpu==2.0.0-alpha0
in my Setup, so it always Installs Tf 2. But it's kind of annoying to Install it every day, so is there a way I can install it for good?
A: You can specify the version with e.g: "%tensorflow_version 2.x", as described here:
https://colab.research.google.com/notebooks/tensorflow_version.ipynb
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57400352",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Attempt to present UINavigationController whose view AppDelegate
initialViewController = storyboard.instantiateViewControllerWithIdentifier("LoginViewController")as! UIViewController
}
self.window?.rootViewController = initialViewController
self.window?.makeKeyAndVisible()
Takes me to LoginViewController
let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("CardsNavController") as? UIViewController
self.presentViewController(vc!, animated: true, completion: nil)
I click on the login button takes me to CardsViewController
func goToProfile(button: UIBarButtonItem) {
pageController.goToPreviousVC()
}
Clicking on back button which is part of the UINavigationController runs goToProfile (above) and takes me to ViewController.swift because that's where the pageController is declared.
let pageController = ViewController(transitionStyle: UIPageViewControllerTransitionStyle.Scroll, navigationOrientation: UIPageViewControllerNavigationOrientation.Horizontal, options: nil)
The error shows up here
func goToPreviousVC() {
//let currentControllers = self.navigationController?.viewControllers
if viewControllers.isEmpty {
setViewControllers([profileVC], direction: UIPageViewControllerNavigationDirection.Reverse, animated: true, completion: nil)
pageController.presentViewController(profileVC, animated: true, completion: nil)
else {
let previousVC = pageViewController(self, viewControllerBeforeViewController: viewControllers[0] as! UIViewController)!
setViewControllers([previousVC], direction: UIPageViewControllerNavigationDirection.Reverse, animated: true, completion: nil)
}
Error:
Warning: Attempt to present <UINavigationController: 0x15ce314e0> on <MyApp.ViewController: 0x15cd2c6f0> whose view is not in the window hierarchy!
Basically the flow is like this AppDelegate -> LoginViewController -> ViewController and I need to get to ProfileViewController.
ProfileView has ProfileNavController while CardsView has CardsNavController
ViewController has a storyboardID of pageController.
Both ProfileView and and CardsView are embedded within UINavigationControllers (hence the NavController extension).
The second time I run the app after a fresh install it works perfectly (all the controllers get loaded okay). Should I push viewControllers in AppDelegate?
A: I've checked your code using Xcode 7, which may not be ideal for resolving this issue because I had to covert your code to Swift 2.0, but here was what I found out.
ISSUE
*
*First time opening the app, this block:
if currentUser() != nil {
initialViewController = pageController
}
else {
initialViewController = storyboard.instantiateViewControllerWithIdentifier("LoginViewController") as UIViewController
}
self.window?.rootViewController = initialViewController
Will initialize LoginViewController and make it the current window's rootViewController.
At this point there is no pageController initialized
*When user taps on the button to go to the Profile screen, this method will be called
func goToProfile(button: UIBarButtonItem) {
pageController.goToPreviousVC()
}
At this point, pageController is initialized, and off course, there is NOTHING in the viewControllers array. Let's see what happen in the goToPreviousVC method:
Original method looks like this:
let nextVC = pageViewController(self, viewControllerAfterViewController: viewControllers[0] as UIViewController)!
setViewControllers([nextVC], direction: UIPageViewControllerNavigationDirection.Forward, animated: true, completion: nil)
One thing you can see obviously is: calling viewControllers[0] could give you a crash because viewControllers is an empty array.
If you use Swift 2.0, it doesn't even let you compile your code :)
SOLUTION
Let's go directly to the solution: Ensure that the pageController is available before trying to call it's viewControllers.
I blindly tried fixing you code in Swift 2.0 and found out that this method would work for you:
BEFORE: In LoginViewController.swift line 63
let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("CardsNavController") as? UIViewController
self.presentViewController(vc!, animated: true, completion: nil)
AFTER: Let's fix it like this
let navc = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("CardsNavController") as! UINavigationController
if let viewControllers = pageController.viewControllers where viewControllers.count == 0 {
pageController.setViewControllers([navc.viewControllers[0]], direction: .Forward, animated: false, completion: nil)
}
self.presentViewController(pageController, animated: true, completion: nil)
It's working well here and probably I don't need to show you how the screen transition should look like :)
In case you would like to have the fixed source code as well, please find it HERE. Basically I converted your code to Swift 2.0 and ignored unnecessary parts like Facebook authentication for faster investigation.
Good luck & Happy coding!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/32594473",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to perform multiple related calls to AsyncTasks without overlapping? I have an application which needs to make repeated calls to a web API. Effectively, it iterates over records in a SQL table and makes a unique call out to the web server with the appropriate data. It's a kind of data synchronization.
As I understand it, when performing this kind of HTTP request to an API it should occur within an AsyncTask to avoid hanging up the UI, so I have made my AsyncTask class which makes a request and parses back the response, but I need to pass this data back to the calling class.
On top of that, I don't want the calling class to run these requests in parallel. I want it to make one request, and not iterate to the next record in the table and make a second request until that first request finishes. So in a way, I want this to be blocking, but still in a separate thread so the UI doesn't freeze up. At least, I think this is what I want.
Pseudo code is something along the lines of this:
// caller function
public void synchronize(){
load all records from sql table
for each record:
if record type is X:
new asyncX().execute(record)
// once this completes successfully,
// I want to do something with the return value here,
// before going on to the next iteration
//
// and eventually when there is some UI here,
// show some nice spinny logo and maybe some text for
// what's going on right now
if record type is Y:
new asyncY().execute(record)
// same as above
}
// Async class
public class asyncX extends AsyncTask<RecordType,Void,RecordType> {
protected RecordType doInBackground(RecordType... record) {
convert record to json
make http request
receive http response
parse response
return record
}
}
The way I'm thinking of doing this is changing the synchronize function to only run one record at a time, call the async task, and end, and then the async task calls back to a synchronize_followup() function which does what it needs to do with the return value, and then starts synchronize back up again, but I'm not sure I like that.
Thoughts on how to proceed?
A: The way you want to handle this is already invented with threading sychronization, so you don't have to implement it your way.
There's a class similar to Semaphore called CountDownLatch. When you declare an object, and activate the lock mechanism via .wait(), it will freeze execution of further code until you issue a .countDown() statement. Indeed, if you declare a CountDownLatch(1) will probably make the effect you're looking for.
On the CountDownLatch's reference page there's a nice example on how to implement this by blocking one Thread's execution depending on the execution of other.
A: To meet my needs, I instead made the synchronize functionality into an AsyncTask, spun that off from my UI thread, and left the outgoing HTTP request as regular functions (and as such, they block).
This means that the synchronization process happens in the background, does not affect the UI thread, and each outgoing API call happens sequentially.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/23255992",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Access $scope outside foreach function Angular js Firebase Here is the code: I'm looping through the data to get the value that I need, and I got it.
The questions is how can I access the value outside of this loop in other functions within the controller. The correct value have been assigned to $scope.theModel.
var refModels = firebase.database().ref("/users/" + $scope.UserID);
refModels.once('value').then(function (snapshot) {
snapshot.forEach(function (snapshot) {
var usersValue = snapshot.val();
console.log("users values", usersValue.carModel);
$scope.theModel = usersValue.carModel;
console.log("The model" + $scope.theModel); //output "e90"
});
$scope.processData();
});
So I need to use that value $scope.theModel outside of the function. What I'm trying to achieve, I will use the value of $scope.theModel -"e90" and compare it with another DB ref, and if it matches it will return the data. See the code of another DB ref:
$scope.processData = function (){
console.log("Process Model" + $scope.theModel); // returns undefined
$scope.carDetails = [];
firebase.database().ref("models").once('value').then(function(snapshot) {
snapshot.forEach(function(userSnapshot) {
var models = userSnapshot.val();
console.log(models);
if (models.brand == $scope.theModel){
$scope.carDetails.push(models);
}
});
});
};
A: It is because, refModels.once('value').then is async meaning that JS starts its execution and continues to next line which is console.log and by the time console.log is executed $scope.theModel hasn't been populated with data yet.
I suggest you read this
Asynchronous vs synchronous execution, what does it really mean?
You can still access your $scope.theModel in other functions, but you have to make sure it is loaded first.
Edit
refModels.once('value').then(function (snapshot) {
snapshot.forEach(function (snapshot) {
var usersValue = snapshot.val();
console.log("users values", usersValue.carModel);
$scope.theModel = usersValue.carModel;
console.log("The model" + $scope.theModel); //output "e90"
});
$scope.processData();
});
$scope.processData = function() {
// here $scope.theModel exists
// do some code execution here with $scope.theModel
// call your other firebase.database.ref("models") here
};
A: Ok so finally got it working, with Bunyamin Coskuner solution, the only thing I had to fix is to return $scope.processData;
var UserID = firebase.auth().currentUser.uid;
var refModels = firebase.database().ref("/users/" + UserID);
refModels.once('value').then(function(snapshot) {
console.log(snapshot)
snapshot.forEach(function(childSnapshot) {
console.log(childSnapshot)
var usersValue = childSnapshot.val();
// var theModel = usersValue.carModel;
console.log("The model", usersValue.carModel); //output "e90"
$scope.theModel = usersValue.carModel;
***return $scope.processData;*** // we have to return it here
});
$scope.processData();
});
$scope.processData = function (){
console.log("Process Model" + $scope.theModel); // now returns the value e90
$scope.carDetails = [];
firebase.database().ref("models").once('value').then(function(snapshot) {
snapshot.forEach(function(userSnapshot) {
var models = userSnapshot.val();
console.log(models);
if (models.brand == $scope.theModel){
$scope.carDetails.push(models);
}
});
});
}
It seems to be a very common mistake made by new javascript developers, the Async behaviour, so its good to read about it.
In this solution we called a function from inside of then function. That way, we'll have for sure the data, that can be used in other function
A: Your $scope.theModel gets set inside the "then" block as expected, but being async, this happens after the second console.log (outside the function) is invoked.
If you use angular components, you can init theModel inside $onInit method:
angular.module('app', []).component('myComponent', {
bindings: {
title: '@'
},
controller: function() {
this.$onInit = function() {
// Init the variable here
$scope.theModel = null;
});
//Following code should not be in the controller, but in a service (here just as sample)
var refModels = firebase.database().ref("/users/" + $scope.UserID);
refModels.once('value').then(function (snapshot) {
snapshot.forEach(function (snapshot) {
var usersValue = snapshot.val();
console.log("users values", usersValue.carModel);
// From this moment your variable is set and available outside
$scope.theModel = usersValue.carModel;
});
},
templateUrl: 'template.html'
});
A: You can watch the value changing. Async behaviour is explained in another answer.
$scope.$watch('theModel', function(newVal){
console.log(newVal);
});
Also I would use $evalAsync() on $scope.theModel = usersValue.carModel;
$scope.$evalAsync(function(){
$scope.theModel = usersValue.carModel;
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/44776410",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: edgeNGram_analyzer not found for field I have created a synonym analyser on an index it works on elasticsearch 1 but not for 2.4:
here is my mapping:
{
"product": {
"_all": {
"enabled": true,
"auto_boost": true,
"index_analyzer": "edgeNGram_analyzer",
"search_analyzer": "standard"
},
"properties": {
"brand": {
"type": "string",
"include_in_all": true
},
"brand_ar": {
"type": "string",
"analyzer": "arabic",
"include_in_all": true
},
"categories": {
"properties": {
"1": {
"type": "string"
},
"146": {
"type": "string"
},
"147": {
"type": "string"
},
"150": {
"type": "string"
},
"151": {
"type": "string"
},
"152": {
"type": "string"
},
"155": {
"type": "string"
},
"156": {
"type": "string"
},
"157": {
"type": "string"
},
"161": {
"type": "string"
},
"162": {
"type": "string"
},
"334": {
"type": "string"
},
"5": {
"type": "string"
}
}
},
"category": {
"type": "string",
"boost": 5.0,
"include_in_all": true
},
"category_ar": {
"type": "string",
"boost": 5.0,
"analyzer": "arabic",
"include_in_all": true
},
"category_id": {
"type": "integer",
"include_in_all": false
},
"colors": {
"type": "string",
"index": "not_analyzed"
},
"colors_name": {
"type": "string",
"include_in_all": true
},
"types": {
"type": "string",
"include_in_all": true
},
"types_array": {
"type": "string",
"index": "not_analyzed"
},
"colors_name_ar": {
"type": "string",
"analyzer": "arabic",
"include_in_all": true
},
"created_at": {
"type": "date",
"format": "dateOptionalTime"
},
"delivery": {
"type": "string"
},
"delivery_ar": {
"type": "string"
},
"description": {
"type": "string",
"include_in_all": true
},
"description_ar": {
"type": "string",
"analyzer": "arabic",
"include_in_all": true
},
"id": {
"type": "string",
"index": "no",
"include_in_all": false
},
"image_link": {
"type": "string",
"index": "not_analyzed"
},
"images": {
"properties": {
"id": {
"type": "string"
},
"name": {
"type": "string"
},
"path": {
"type": "string"
}
}
},
"is_best_seller": {
"type": "integer",
"include_in_all": false
},
"is_deal": {
"type": "integer",
"include_in_all": false
},
"keywords": {
"type": "string",
"include_in_all": true
},
"made_id": {
"type": "string"
},
"made_in": {
"type": "string",
"include_in_all": true
},
"made_in_ar": {
"type": "string",
"analyzer": "arabic",
"include_in_all": true
},
"name": {
"type": "string",
"boost": 10.0,
"index_analyzer": "edgeNGram_analyzer",
"include_in_all": true
},
"name_ar": {
"type": "string",
"boost": 10.0,
"analyzer": "arabic",
"include_in_all": true
},
"price": {
"type": "double",
"include_in_all": false
},
"price_before_discount": {
"type": "double",
"include_in_all": false
},
"quality": {
"type": "string",
"index": "not_analyzed"
},
"quality_ar": {
"type": "string",
"analyzer": "arabic"
},
"rating": {
"type": "integer",
"include_in_all": false
},
"status": {
"type": "string"
},
"updated_at": {
"type": "date",
"format": "dateOptionalTime"
},
"uuid": {
"type": "string",
"index": "no",
"include_in_all": false
},
"vendor_id": {
"type": "string"
},
"vendor_location": {
"type": "geo_point"
},
"vendor_name": {
"type": "string",
"include_in_all": false
},
"views": {
"type": "integer",
"include_in_all": false
},
"warranty": {
"type": "string"
},
"warranty_ar": {
"type": "string"
}
}
}
}
But when I try to use it with the mapping got this issue:
{
"error": "MapperParsingException[Analyzer [edgeNGram_analyzer] not found for field [name]]",
"status": 400
}
Any ideas, I may be missing something but I can't think what. I'm using elasticsearch 2.4
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41641694",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: It is possible to assign an Int value to an Array inside a Function in C++? It's possible to do the following code with C++:
myFunction(myArray, positionInsideMyArray) = myValue.
cout << myFunction[positionInsideMyArray] << endl; // Display muValue
How can I do that with C++?
To make my question more clear, With one value the following code work correctly,
I want to do the same thing but using an Array parameter.
int& myFunction(int &x){
return x;
}
this is the main function:
int x;
myFunction(x) = myValue;
cout << x << endl; // This will display myValue
A: #include <iostream>
int &myFunction(int *arr, size_t pos) { return arr[pos]; }
int main() {
using std::cout;
int myArray[30];
size_t positionInsideMyArray = 5;
myFunction(myArray, positionInsideMyArray) = 17.;
cout << myArray[positionInsideMyArray] << "\n"; // Display muValue
}
or with error checking:
#include <stdexcept>
template<size_t N>
inline int &myFunction(int (&arr)[N], size_t pos)
{
if (pos >= N)
throw std::runtime_error("Index out of bounds");
return arr[pos];
}
A: myFunction(myArray, positionInsideMyArray) = myValue.
cout << myFunction[positionInsideMyArray] << endl;
With functions alone, the second line is not possible; you'll need a class.
However, that the second call remembers myArray from the
first makes the whole semantics a bit strange...
A rough idea (no complete class, only for int-arrays):
class TheFunc
{
int *arr;
int &operator() (int *arr, size_t pos)
{
this->arr = arr;
return arr[pos];
}
int &operator[] (size_t pos)
{
return arr[pos];
}
};
...
TheFunc myFunction;
myFunction(myArray, positionInsideMyArray) = myValue.
cout << myFunction[positionInsideMyArray] << endl;
A different, more robust version, where the array it set separately:
class TheFunc
{
int *arr;
TheFunc(int *arr)
{
this->arr = arr;
}
int &operator() (size_t pos)
{
return arr[pos];
}
int &operator[] (size_t pos)
{
return arr[pos];
}
};
...
TheFunc myFunction(myArray);
myFunction(positionInsideMyArray) = myValue.
cout << myFunction[positionInsideMyArray] << endl;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/33723708",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
} |
Q: hide scrollbar shape in android textview i have a text view in my activity that populate from database . but when it's big Scrollbar shape show override the text . this is screenshot from it :
This is the textView xml :
<TextView
android:id="@+id/txtMatn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/dark_line"
android:lineSpacingExtra="12dp"
android:layout_margin="24dp"
android:scrollbars="vertical"/>
now I want hide the ScrollBar shape
A: maybe you enable scrollability of textview by
1. in java code : TextView.setMovementMethod(new ScrollingMovementMethod());
2. in xml : android:scrollbars="vertical"
... but only first job enable scrollability text without second job
so answer is below
1. in java code : TextView.setMovementMethod(new ScrollingMovementMethod());
2. in xml : android:scrollbars="none"
delta is value of android:scrollbars vertical->none
A: In XML
android:background="@android:color/transparent"
Or in Kotlin Class
editText?.isVerticalScrollBarEnabled = false
In Java Class
A: you can use this code
enter code here
<ScrollView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scrollbars="none">
<TextView
here your text
/>
</ScrollView>
A: implemented the OnTouchListener inside the adapter and set it on the text view he logic for touch event is: I check if the touch event is a tap or a swipe
@Override
public boolean onTouch(View v, MotionEvent motionEvent) {
switch (motionEvent.getAction()) {
case MotionEvent.ACTION_DOWN:
mIsScrolling = false;
mDownX = motionEvent.getX();
break;
case MotionEvent.ACTION_MOVE:
float deltaX = mDownX - motionEvent.getX();
if ((Math.abs(deltaX) > mSlop)) { // swipe detected
mIsScrolling = true;
}
break;
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
if (!mIsScrolling) {
openNewScreen(v); // this method is used for click listener of the ListView
}
break;
}
return false;
}
A: android:scrollbarThumbVertical="@android:color/transparent"
Keep the scroll Set transparent
| {
"language": "en",
"url": "https://stackoverflow.com/questions/35293274",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Custom Jasmine HTML output I am testing a project in rails with Jasmine which is all going great.
The only issue I now have is that I'm not a huge fan of the way the tests are being displayed. Currently I view my test suite at http://localhost:8000/jasmine and Jasmine is pulling in my styles along with it's own and rendering the tests as follows:
I would like to either render the tests like this (as I've seen elsewhere):
Or have some way of customising the HTML output/layout. Is this possible?
A: The output you want is produced if you use the jasmine.TrivialReporter. The one the gem displays is the recommended one, i.e. the jasmine.HtmlReporter. You can use the trivial one as described here: https://github.com/pivotal/jasmine/blob/v1.3.1/lib/jasmine-core/example/SpecRunner.html, but that implies running jasmine stand-alone not through the gem.
(version 1._._ only.)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/13364653",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: SQL Query how to summarize students record by date? I have a following table Students
Id StudentId Subject Date Grade
1 001 Math 02/20/2013 A
2 001 Literature 03/02/2013 B
3 002 Biology 01/01/2013 A
4 003 Biology 04/08/2013 A
5 001 Biology 05/01/2013 B
6 002 Math 03/10/2013 C
I need result into another table called StudentReport as shown below. This table is the cumulative report of all students records in chronological order by date.
Id StudentId Report
1 001 #Biology;B;05/01/2013#Literature;B;03/02/2013#Math;A;02/20/2013
2 002 #Math;C;03/10/2013#Biology;A;01/01/2013
3 003 #Biology;A;04/08/2013
A: Typically you would not store this data in a table, you have all the data needed to generate the report.
SQL Server does not have an easy way to generate a comma-separated list so you will have to use FOR XML PATH to create the list:
;with cte as
(
select id,
studentid,
date,
'#'+subject+';'+grade+';'+convert(varchar(10), date, 101) report
from student
)
-- insert into studentreport
select distinct
studentid,
STUFF(
(SELECT cast(t2.report as varchar(50))
FROM cte t2
where c.StudentId = t2.StudentId
order by t2.date desc
FOR XML PATH (''))
, 1, 0, '') AS report
from cte c;
See SQL Fiddle with Demo (includes an insert into the new table). Give a result:
| ID | STUDENTID | REPORT |
------------------------------------------------------------------------------------
| 10 | 1 | #Biology;B;05/01/2013#Literature;B;03/02/2013#Math;A;02/20/2013 |
| 11 | 2 | #Math;C;03/10/2013#Biology;A;01/01/2013 |
| 12 | 3 | #Biology;A;04/08/2013 |
A: If you are looking to insert the data from 'Students' into 'Student Report', try:
INSERT INTO StudentReport (ID, StudentID, Report)
SELECT ID, StudentID, '#' + subject + ';' + grade + ';' + date AS report
FROM Students
A: Without using CTE.Improve performance.
FOR XML
(select
min(ID) as ID,
StudentId,
STUFF((select ', '+'#'+s2.Subject+';'+s2.Grade+';'+convert(varchar(25),s2.Date)
from student s2
where s2.StudentId=s1.StudentId
FOR XML PATH (''))
,1,2,'') as report
into t
from student s1
group by StudentId)
;
select * from t
Where t would be new Table Name which doesn't exists in DataBase.
SQL Fiddle
| {
"language": "en",
"url": "https://stackoverflow.com/questions/16343294",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Updating data in MySQL table with PHP I was following an online tutorial lesson about login system with PHP. Everything works fine as far as lesson is concerned.
Now I added a new data column named "time" of type INT. And I want to update it with the time as soon as user has logged in. In the below code, I tried to update it. But it shows no error, but doesn't work(update the "time" variable), either. I don't know PHP very well, so I think I'm not doing it right. So help me with my code.
<?php
session_start();
// Change this to your connection info.
$DATABASE_HOST = 'localhost';
$DATABASE_USER = 'root';
$DATABASE_PASS = '';
$DATABASE_NAME = 'accounts';
// Try and connect using the info above.
$con = mysqli_connect($DATABASE_HOST, $DATABASE_USER, $DATABASE_PASS, $DATABASE_NAME);
if ( mysqli_connect_errno() ) {
// If there is an error with the connection, stop the script and display the error.
die ('Failed to connect to MySQL: ' . mysqli_connect_error());
}
// Now we check if the data from the login form was submitted, isset() will check if the data exists.
if ( !isset($_POST['username'], $_POST['password']) ) {
// Could not get the data that should have been sent.
die ('Please fill both the username and password field!');
}
// Prepare our SQL, preparing the SQL statement will prevent SQL injection.
if ($stmt = $con->prepare('SELECT id, password FROM accounts WHERE username = ?')) {
// Bind parameters (s = string, i = int, b = blob, etc), in our case the username is a string so we use "s"
$stmt->bind_param('s', $_POST['username']);
$stmt->execute();
// Store the result so we can check if the account exists in the database.
$stmt->store_result();
}
if ($stmt->num_rows > 0) {
$stmt->bind_result($id, $password);
$stmt->fetch();
// Account exists, now we verify the password.
// Note: remember to use password_hash in your registration file to store the hashed passwords.
if (password_verify($_POST['password'], $password)) {
// Verification success! User has loggedin!
// Create sessions so we know the user is logged in, they basically act like cookies but remember the data on the server.
session_regenerate_id();
$_SESSION['loggedin'] = TRUE;
$_SESSION['name'] = $_POST['username'];
$_SESSION['id'] = $id;
// I want to update "time" in my table
$now = time();
$stmt = $con->prepare('UPDATE accounts SET time = ? WHERE id = ?');
$stmt->bind_param('i', $now, $id);
$stmt->execute();
//echo 'Welcome ' . $_SESSION['name'] . '!';
header('Location: home.php');
} else {
echo 'Incorrect password!';
}
} else {
echo 'Incorrect username!';
}
$stmt->close();
?>
A: In your update code. $stmt->bind_param('i', $now, $id); you forgot to add another i.
It should be
$stmt->bind_param('ii', $now, $id);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58743431",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Doctrine2 incorrectly cascading oneToMany relationship I have 2 doctrine entities:
Commessa
/**
* @ORM\Id
* @ORM\Column(type = "bigint")
* @ORM\GeneratedValue(strategy = "AUTO")
*/
private $id;
/* ... */
/*
* @ORM\OneToMany(targetEntity = "AppBundle\Entity\Pipeline\pipeline", mappedBy = "commessa", cascade = {"persist", "remove"})
*/
private $pipelines;
and Pipeline
/**
* @ORM\Id
* @ORM\Column(type = "bigint")
* @ORM\GeneratedValue(strategy = "AUTO")
*/
private $id;
/* ... */
/**
* @ORM\ManyToOne(targetEntity = "AppBundle\Entity\Commessa\commessa", inversedBy = "pipelines")
* @ORM\JoinColumn(name = "id_commessa", name = "id")
*/
private $commessa;
As you can see, both entities have an AUTO-INCREMENT, single field primary key called id, and a bidirectional association to the other; pipeline gets automatically persisted whenever i do so with commessa.
Furthermore, both entities only have a getter method for the id, and not a setter one.
Now, whenever i try to flush an object instance of the class Commessa including more than a single pipeline, the following error pops up:
An exception occurred while executing 'INSERT INTO pipeline (descrizione, nome_logico, id) VALUES (?, ?, ?)' with params ["", "frontend", "9"]:
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '9' for key 'PRIMARY'
At no point in my code i set the pipeline's id, and dumping the Commessa object right before the flush (and after the persist) shows that it's populated correctly, and the pipelines have "null" as id, which i guess is correct.
Through the Symfony profiler, the following queries are reported:
"START_TRANSACTION"
INSERT INTO commessa (codice_commessa, data_creazione, data_scadenza, descrizione, id_anagrafica, id_cliente, id_stato, id_tipo_commesa) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
Parameters: [ 1 => lyme, 2 => 2017-01-13 10:47:53, 3 => 2017-01-17 00:00:00, 4 => Fai Lyme, 5 => 1, 6 => 1, 7 => 1, 8 => 1 ]
INSERT INTO pipeline (descrizione, nome_logico, id) VALUES (?, ?, ?)
Parameters: [1 => , 2 => frontend, 3 => 10]
INSERT INTO pipeline (descrizione, nome_logico, id) VALUES (?, ?, ?)
Parameters: [1 => , 2 => backend, 3 => 10]
"ROLLBACK"
I then stumbled upon the doctrine limitations and known issues page, stating at point 28.1.3
There are two bugs now that concern the use of cascade merge in combination with bi-directional associations.
but the related ticket link is dead.
Could this be my problem?
If it is, how can i solve this problem?
A: @ORM\JoinColumn(name = "id_commessa", name = "id") is wrong. there is 2 times name field
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41631835",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to Copy and Resize Image in Windows 10 UWP I have used the code from http://www.codeproject.com/Tips/552141/Csharp-Image-resize-convert-and-save to resize images programmatically. However, that project uses the System.Drawing libraries, which are not available to Windows 10 applications.
I have tried using the BitmapImage class from Windows.UI.Xaml.Media.Imaging instead, but it does not seem to offer the functionality that was found in System.Drawing..
Has anyone had any luck being able to resize (scale down) images in Windows 10? My application will be processing images from multiple sources, in different formats/sizes, and I am trying to resize the actual images to save space, rather than just letting the application size it to fit the Image in which it is being displayed.
EDIT
I have modified the code from the above mentioned link, and have a hack which works for my specific need. Here it is:
public static BitmapImage ResizedImage(BitmapImage sourceImage, int maxWidth, int maxHeight)
{
var origHeight = sourceImage.PixelHeight;
var origWidth = sourceImage.PixelWidth;
var ratioX = maxWidth/(float) origWidth;
var ratioY = maxHeight/(float) origHeight;
var ratio = Math.Min(ratioX, ratioY);
var newHeight = (int) (origHeight * ratio);
var newWidth = (int) (origWidth * ratio);
sourceImage.DecodePixelWidth = newWidth;
sourceImage.DecodePixelHeight = newHeight;
return sourceImage;
}
This way seems to work, but ideally rather than modifying the original BitmapImage, I would like to create a new/copy of it to modify and return instead.
Here is a shot of it in action:
A:
I may want to return a copy of the original BitmapImage rather than modifying the original.
There is no good method to directly copy a BitmapImage, but we can reuse StorageFile for several times.
If you just want to select a picture, show it and in the meanwhile show the re-sized picture of original one, you can pass the StorageFile as parameter like this:
public static async Task<BitmapImage> ResizedImage(StorageFile ImageFile, int maxWidth, int maxHeight)
{
IRandomAccessStream inputstream = await ImageFile.OpenReadAsync();
BitmapImage sourceImage = new BitmapImage();
sourceImage.SetSource(inputstream);
var origHeight = sourceImage.PixelHeight;
var origWidth = sourceImage.PixelWidth;
var ratioX = maxWidth / (float)origWidth;
var ratioY = maxHeight / (float)origHeight;
var ratio = Math.Min(ratioX, ratioY);
var newHeight = (int)(origHeight * ratio);
var newWidth = (int)(origWidth * ratio);
sourceImage.DecodePixelWidth = newWidth;
sourceImage.DecodePixelHeight = newHeight;
return sourceImage;
}
In this scenario you just need to call this task and show the re-sized image like this:
smallImage.Source = await ResizedImage(file, 250, 250);
If you want to keep the BitmapImage parameter due to some reasons (like the sourceImage might be a modified bitmap but not directly loaded from file), and you want to re-size this new picture to another one, you will need to save the re-sized picture as a file at first, then open this file and re-size it again.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36019595",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Getting tighter segmentation results of Deeplab for small/underbalanced classes I have trained the official Tensorflow deeplab model (https://github.com/tensorflow/models/tree/master/research/deeplab) on the CelebAMask-HQ dataset (https://github.com/switchablenorms/CelebAMask-HQ), to have a model that can semantically segment all facial segments (e.g. Eyes, nose, etc.). I have spent little time in hyperparameter settings and use the default settings:
CUDA_VISIBLE_DEVICES=0 python "${WORK_DIR}"/deeplab/train.py \
--logtostderr \
--train_split="train" \
--model_variant="xception_65" \
--atrous_rates=6 \
--atrous_rates=12 \
--atrous_rates=18 \
--output_stride=16 \
--decoder_output_stride=4 \
--train_crop_size="1025,1025" \
--train_batch_size=2 \
--training_number_of_steps=45000 \
--fine_tune_batch_norm=false \
--tf_initial_checkpoint="${WORK_DIR}/deeplab/pretrained_models/deeplabv3_pascal_trainval/model.ckpt" \
--train_logdir="${WORK_DIR}/deeplab/logs" \
--dataset="celeba" \
--dataset_dir="${WORK_DIR}/deeplab/datasets/celeba/tfrecords_padded/"
The only thing that I have adapted are the class weights, in which I have calculated class weights based on the ratio of all pixels belonging to each class in the total dataset. These calculated ratios are:
class_ratio = {0: 0.287781127731224, #BG
1: 0.31428004829848194, #hair
2: 0.25334614328648697, #face
3: 0.008209905199792278, #brows
4: 0.0044636011242926155, #eyes
5: 0.020564768086557928, #nose
6: 0.004150659950132944, #u_lip
7: 0.00680743101856918, #l_lip
8: 0.0030163743167156494, #mouth
9: 0.040800302545885576, #neck
10: 0.008106960279456135, #ears
11: 0.03355246488702522, #clothes
12: 0.009293231642880359, #hat
13: 0, #ear_ring -> 0
14: 0, #glasses -> 0
15: 0 #necklace -> 0
}
As the class weights, I take 1/<class_ratio> , so the class weight for the background is 3.57 and for the brows is 121.95.
Finally, I do some data augmentation such as rotation, flipping and changing the brightness.
My results are fairly good, but there is something noticable when I input some of the images of my training set into the model. Below the original segmentation:
And here the segmented result:
As you can see, the segmented result is quite good, but especially the smaller classes such as the eyes, brows and nose are not as 'tightly segmented' as I would like them to be. Basically for all images that are segmented by the model, the eyes, nose and brows are greater than the original segmentation. Therefore, I would like to change a few hyperparameters to obtain tighter segmentation results for the smaller classes.
Any suggestions on a possible approach to obtain more thight results for the smaller classes? My current approach for calculating the class weight based on the absolute percentage of pixels belonging to each class in the total dataset works reasonably well, but maybe an alternative approach for calculation of the class weights works better? Or different underlying model structure that is able to do fine segmentation?
Any help is appreciated. Thanks!
A: You could try xception-71 with DPC, which should give tighter segmentations.
Or maybe you can try this https://github.com/tensorflow/models/issues/3739#issuecomment-527811265.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/65682975",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Receiving contiinuous output from python spawn child process not working I am attempting to stream output from a weighing scale that is written in python. This program (scale.py) runs continuously and prints the raw value every half second.
import RPi.GPIO as GPIO
import time
import sys
from hx711 import HX711
def cleanAndExit():
print "Cleaning..."
GPIO.cleanup()
print "Bye!"
sys.exit()
hx = HX711(5, 6)
hx.set_reading_format("LSB", "MSB")
hx.reset()
hx.tare()
while True:
try:
val = hx.get_weight(5)
print val
hx.power_down()
hx.power_up()
time.sleep(0.5)
except (KeyboardInterrupt, SystemExit):
cleanAndExit()
I am trying to get each raw data point in a separate NodeJs program (index.js located in the same folder) that is printed by print val. Here is my node program.
var spawn = require('child_process').spawn;
var py = spawn('python', ['scale.py']);
py.stdout.on('data', function(data){
console.log("Data: " + data);
});
py.stderr.on('data', function(data){
console.log("Error: " + data);
});
When I run sudo node index.js there is no output and the program waits into perpetuity.
My thought process is that print val should put output into stdout stream and this should fire the data event in the node program. But nothing is happening.
Thanks for your help!
A: By default, all C programs (CPython included as it is written in C) that use libc will automatically buffer console output when it is connected to a pipe.
One solution is to flush the output buffer every time you need:
print val
sys.stdout.flush()
Another solution is to invoke python with the -u flag which forces it to be unbuffered:
var py = spawn('python', ['-u', 'scale.py']);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/49947402",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Link to files in VSCode .ipynb notebooks I'm trying to put a link to a file in a markdown cell in a notebook, for example:
See [feature scaling notes](feature_scaling_notes.md)
The file feature_scaling_notes.md is in the same folder as the .ipynb file.
A link is created, yet when I click on it, instead of opening the file, a browser window is opened with the address:
https://file+.vscode-resource.vscode-webview.net/...(file path)
How can I make the file open in the correct way?
Thanks.
A: Coming in v1.63 are file links in notebooks, see release note: file links in notebooks.
Markdown inside notebooks can now link to other files in the current
workspace
Links the start with / are resolved relative to the workspace root.
Links that start with ./ or just start with a filename are resolved
relative to the current notebook.
[link text](./cat.gif)
Bare http(s) links notebooks
In addition, markdown text that looks like an http and https is
now automatically turned into a link:
| {
"language": "en",
"url": "https://stackoverflow.com/questions/68879467",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Default android application for a Tablet In my application i have done all the process and they are working very well. Now my device needs only one application or other application must not come front to the user's view..
Can I make my Application as Default application or the only application viewable by the user?
To avoid the unnecessary usage of other applications or to keep time consumption I plan to try this.
Would I need to change anything in the Manifest.xml file of this solution solve this?
A: You cannot do this on a stock device. Your best bet is to create a launcher that only allows launching your app. The user needs to agree to run it however, and it can always be changed and/or disabled in Settings.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/13926016",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Can you create anonymous inner classes in Swift? I'm tired of declaring entire classes as having the ability to handle UIAlertView clicks by making them extend UIAlertViewDelegate. It starts to feel messy and wrong when I have multiple possible UIAlertViews, and have to distinguish which was clicked in the handler.
What I really want is to create a single object that implements the UIAlertViewDelegate protocol, and give this one-off object to my UIAlertView when showing it.
I want something like this:
let confirmDelegate = UIAlertViewDelegate() {
func alertView(alertView: UIAlertView!, clickedButtonAtIndex buttonIndex: Int) {
// Handle the click for my alertView
}
}
And then use it when showing the alert:
let alertView = UIAlertView(title: "Confirm", message: "Are you sure?", delegate: confirmDelegate, cancelButtonTitle: "No", otherButtonTitles: "Yes")
alertView.show()
Is this possible without declaring a new class?
I understand I could do something like this:
class ConfirmDelegate: UIAlertViewDelegate {
func alertView(alertView: UIAlertView!, clickedButtonAtIndex buttonIndex: Int) {
// ...
}
}
And then instantiate a ConfirmDelegate(), but I'm just wondering if this is possible as one-liner class declaration and instantiation.
A: As @ChrisWagner states in his comment, you shouldn't need to do any of this in iOS8, at least for UIAlertView since there is a new UIAlertViewController that uses closures without any delegates. But from an academic point of view, this pattern is still interesting.
I wouldn't use anonymous class at all. I would just create a class that can be assigned as the delegate and accept closures to execute when something happens.
You could even upgrade this to accept a closure for each kind of action: onDismiss, onCancel, etc. Or you could even make this class spawn the alert view, setting itself as the delegate.
import UIKit
class AlertViewHandler: NSObject, UIAlertViewDelegate {
typealias ButtonCallback = (buttonIndex: Int)->()
var onClick: ButtonCallback?
init(onClick: ButtonCallback?) {
super.init()
self.onClick = onClick
}
func alertView(alertView: UIAlertView!, clickedButtonAtIndex buttonIndex: Int) {
onClick?(buttonIndex: buttonIndex)
}
}
class ViewController: UIViewController {
// apparently, UIAlertView does NOT retain it's delegate.
// So we have to keep it around with this instance var
// It'll be nice when all of UIKit is properly Swift-ified :(
var alertHandler: AlertViewHandler?
func doSoemthing() {
alertHandler = AlertViewHandler({ (clickedIndex: Int) in
println("clicked button \(clickedIndex)")
})
let alertView = UIAlertView(
title: "Test",
message: "OK",
delegate: alertHandler!,
cancelButtonTitle: "Cancel"
)
}
}
Passing around closures should alleviate the need for anonymous classes. At least for the most common cases.
A: Unfortunately as far as I understand it, no you cannot effectively create anonymous inner classes. The syntax you suggest would be really nice IMO though.
Here is my attempt at getting something close to what you want, it's no where near as clean though.
import UIKit
class AlertViewDelegate: NSObject, UIAlertViewDelegate {
func alertView(alertView: UIAlertView!, clickedButtonAtIndex buttonIndex: Int) {
}
func alertView(alertView: UIAlertView!, didDismissWithButtonIndex buttonIndex: Int) {
}
func alertView(alertView: UIAlertView!, willDismissWithButtonIndex buttonIndex: Int) {
}
func alertViewCancel(alertView: UIAlertView!) {
}
func alertViewShouldEnableFirstOtherButton(alertView: UIAlertView!) -> Bool {
return true
}
}
class ViewController: UIViewController {
var confirmDelegate: AlertViewDelegate?
func doSoemthing() {
confirmDelegate = {
class ConfirmDelegate: AlertViewDelegate {
override func alertView(alertView: UIAlertView!, clickedButtonAtIndex buttonIndex: Int) {
println("clicked button \(buttonIndex)")
}
}
return ConfirmDelegate()
}()
let alertView = UIAlertView(title: "Test", message: "OK", delegate: confirmDelegate, cancelButtonTitle: "Cancel")
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/25247209",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: My api post request is working in postman tool but it is showing error in the console of a browser? This is postman tool and here post method is working fine hereI have attached here the screenshot of postman
[In the console, it's showing error. Please help me to resolve this issue.][2This is browser console screenshot
A: In postman you are doing a post and in browser by default it's a GET
So the error says there is no endpoint that accepts a GET method.
If you change method to get in postman you should get same 404
| {
"language": "en",
"url": "https://stackoverflow.com/questions/65059439",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to implement constraints for 2 labels between 2 images for xib file Edit: PLEASE LEAVE A COMMENT IF YOU'RE GOING TO DISLIKE SO I CAN IMPROVE MY QUESTION
I'm trying to recreate a custom table view cell in my xib file as shown below. The company's square image is on the left. The company's name and company's booth (2 UI Labels) are to the right of the company's image. The star button is to the right of the text and is a square image. I guesstimated that the company's image and favorites button should be about 8px from the top and edge.
I tried to create 4 constraints for the top, bottom, left, and right of every element (image, 2 UI labels, and button). I also added 1:1 aspect ratio constraint to the image and button to make sure the image would be square. Then I aligned the left edge of the 2 UI labels. I vertically centered the image and the button. However, it came out with no star button and the location and title switched. How do I create this design using constraints?
A: Their is no difficulty with that.
First if we talk about your left UIImageView, Set following constraints,
*
*Leading constraint
*Fixed Height
*Fixed Width
*Centre Vertically
After that the UIImageView on left, set following constraints,
*
*Trailing space from superview
*Fixed Height
*Fixed Width
*Centre Vertically
Now for both Labels, put them in a UIView and give that UIView following constraints,
*
*Leading space from left image view.
*trailing space from right image view.
*top space from superview
*bottom space from superview
Now for upper UILabel, Set following constraints,
*
*Leading space
*Trailing space
*top space
Now for lower UILabel, Set following constraints,
*
*Leading space
*Trailing space
*top space from upper UILabel
*bottom space
After all this, i think that this will work for you.
A: You can use the constraints in the image below. It will work for all screen size and for any height of row.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41541322",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: How to get Unique Device ID for Amazon Kindle Fire To get the Unique Device ID on Android phones/tablets, we use the following:
((TelephonyManager) ctx.getSystemService(Context.TELEPHONY_SERVICE)).getDeviceId()
But for Kindle Fire, we can't get one.
A: You should try using the following line:
deviceId = Secure.getString(context.getContentResolver(), Secure.ANDROID_ID);
This will get the device ID from tablets, the code you're using only works on phones (it will return null on tablets)
A: put
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
then
try this:
public String deviceId;
then:
// ------------- get UNIQUE device ID
deviceId = String.valueOf(System.currentTimeMillis()); // --------
// backup for
// tablets etc
try {
final TelephonyManager tm = (TelephonyManager) getBaseContext()
.getSystemService(Main.TELEPHONY_SERVICE);
final String tmDevice, tmSerial, tmPhone, androidId;
tmDevice = "" + tm.getDeviceId();
tmSerial = "" + tm.getSimSerialNumber();
androidId = ""
+ android.provider.Settings.Secure.getString(
getContentResolver(),
android.provider.Settings.Secure.ANDROID_ID);
UUID deviceUuid = new UUID(androidId.hashCode(),
((long) tmDevice.hashCode() << 32) | tmSerial.hashCode());
deviceId = deviceUuid.toString();
} catch (Exception e) {
Log.v("Attention", "Nu am putut sa iau deviceid-ul !?");
}
// ------------- END get UNIQUE device ID
from here -> Is there a unique Android device ID?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/8323326",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Using Shared Preferences to persist DataMap android wear I had a question related to the FORM Watch Face. I see that SharedPreferences have been used to persist DataMap. Why was it necessary to persist the data when we can fetch the DataMap from the Wearable.DataApi anytime? The developer.android wearable documentation does not mention using Shared Preferences anywhere and even the Android wear samples do not use SharedPreferences. Is it for performance or am I missing something here?
A: Roman Nurik posted an answer here:
https://plus.google.com/111335419682524529959/posts/QJcExn49ZrR
For performance. When the settings activity loads of the watch first shows up, I didn't want to wait for an IPC call to complete before showing anything
For a detailed description checkout my medium post.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31403307",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Unable to resolve dependencies react native google fit After adding the package I can't build the project. Error:
A problem occurred configuring project ':app'.
> Could not resolve all dependencies for configuration ':app:_debugApk'.
> A problem occurred configuring project ':react-native-google-fit'.
> Could not resolve all dependencies for configuration ':react-native-google-fit:_debugPublishCopy'.
> Could not find com.google.android.gms:play-services-auth:11.6.0.
Searched in the following locations:
file:/Users/wojciech/Library/Android/sdk/extras/google/m2repository/com/google/android/gms/play-services-auth/11.6.0/play-services-auth-11.6.0.pom
file:/Users/wojciech/Library/Android/sdk/extras/google/m2repository/com/google/android/gms/play-services-auth/11.6.0/play-services-auth-11.6.0.jar
file:/Users/wojciech/Documents/dev/uni/swifty-app/Swifty/android/sdk-manager/com/google/android/gms/play-services-auth/11.6.0/play-services-auth-11.6.0.jar
file:/Users/wojciech/Library/Android/sdk/extras/android/m2repository/com/google/android/gms/play-services-auth/11.6.0/play-services-auth-11.6.0.pom
file:/Users/wojciech/Library/Android/sdk/extras/android/m2repository/com/google/android/gms/play-services-auth/11.6.0/play-services-auth-11.6.0.jar
file:/Users/wojciech/Documents/dev/uni/swifty-app/Swifty/android/sdk-manager/com/google/android/gms/play-services-auth/11.6.0/play-services-auth-11.6.0.jar
Required by:
Swifty:react-native-google-fit:unspecified
> Could not find com.google.android.gms:play-services-fitness:11.6.0.
Searched in the following locations:
file:/Users/wojciech/Library/Android/sdk/extras/google/m2repository/com/google/android/gms/play-services-fitness/11.6.0/play-services-fitness-11.6.0.pom
file:/Users/wojciech/Library/Android/sdk/extras/google/m2repository/com/google/android/gms/play-services-fitness/11.6.0/play-services-fitness-11.6.0.jar
file:/Users/wojciech/Documents/dev/uni/swifty-app/Swifty/android/sdk-manager/com/google/android/gms/play-services-fitness/11.6.0/play-services-fitness-11.6.0.jar
file:/Users/wojciech/Library/Android/sdk/extras/android/m2repository/com/google/android/gms/play-services-fitness/11.6.0/play-services-fitness-11.6.0.pom
file:/Users/wojciech/Library/Android/sdk/extras/android/m2repository/com/google/android/gms/play-services-fitness/11.6.0/play-services-fitness-11.6.0.jar
file:/Users/wojciech/Documents/dev/uni/swifty-app/Swifty/android/sdk-manager/com/google/android/gms/play-services-fitness/11.6.0/play-services-fitness-11.6.0.jar
Required by:
Swifty:react-native-google-fit:unspecified
Thanks in advance.
A: There are two common ways to solve it.
1. add to your android/build.gradle file, under allprojects/repositoris sections
maven {
url 'https://maven.google.com'
}
so that it should looks like:
allprojects {
repositories {
mavenLocal()
maven {
url 'https://maven.google.com'
}
maven {
// All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
url "$rootDir/../node_modules/react-native/android"
}
maven { url "https://jitpack.io" }
jcenter()
}
}
*Another way (works for me) - for react-native-google-fit lib, and in android/build.gradle of library change dependency to
compile 'com.google.android.gms:play-services-auth+'
compile 'com.google.android.gms:play-services-fitness+'
And use your fork in your project
| {
"language": "en",
"url": "https://stackoverflow.com/questions/49785233",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Send email with log file as attachment I am using Hadoop (CDH 5.4.8) to process the unstructured data and after successful processing I want to send a mail notification to the concerned team with log file as attachment.
CDH 5.4.8 Oozie does not support attachment feature in email action. So I want to do this using shell script. Please let me know the best way to do this.
A: You can easily send an email from within a shell by piping a complete mail message (header and body) into sendmail. This assumes that the host you're doing this is properly configured with a mail transfer agent (e.g. sendmail or postfix) to send email messages.
The easiest way to send email with an attachment is to create a simple template message in your mail user agent (e.g. Thunderbird), and copy its contents as a template with the view source command. Modify that template to suit your needs and place it in the shell script.
Here is an example:
#!/bin/sh
cat <<\EOF |
To: Ramesh <[email protected]>
From: Diomidis Spinellis <[email protected]>
Subject: Here are your Hadoop results
Message-ID: <[email protected]>
Date: Sun, 3 Apr 2016 09:58:48 +0300
MIME-Version: 1.0
Content-Type: multipart/mixed;
boundary="------------030303090406090809090501"
This is a multi-part message in MIME format.
--------------030303090406090809090501
Content-Type: text/plain; charset=utf-8; format=flowed
Content-Transfer-Encoding: 7bit
The attachment contains your Hadoop results.
--------------030303090406090809090501
Content-Type: application/octet-stream;
name="data"
Content-Transfer-Encoding: base64
Content-Disposition: attachment;
filename="data"
HviDNR105+2Tr0+0fsx3OyzNueQqPuAXl9IUrafOi7Y=
--------------030303090406090809090501--
EOF
sendmail [email protected]
To configure a fixed message with actual data, replace the parts you want to modify with commands that generate them. (Note the missing backslash from the here document EOF marker.)
#!/bin/sh
cat <<EOF |
To: Ramesh <[email protected]>
From: Diomidis Spinellis <[email protected]>
Subject: Here are your Hadoop results
Message-ID: <[email protected]>
Date: $(date -R)
MIME-Version: 1.0
Content-Type: multipart/mixed;
boundary="------------030303090406090809090501"
This is a multi-part message in MIME format.
--------------030303090406090809090501
Content-Type: text/plain; charset=utf-8; format=flowed
Content-Transfer-Encoding: 7bit
The attachment contains your Hadoop results.
--------------030303090406090809090501
Content-Type: application/octet-stream;
name="data"
Content-Transfer-Encoding: base64
Content-Disposition: attachment;
filename="data"
$(base64 binary-data-file.dat)
--------------030303090406090809090501--
EOF
sendmail [email protected]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36370975",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Why is WKWebView not opening links with target=“_blank”? What is wrong with my code? Why is WKWebView not opening links with target=“_blank”? I want to open links that are opening in the new tab with the default browser. How Can this be achieved?
import UIKit
import WebKit
class ViewController: UIViewController, WKUIDelegate {
@IBOutlet weak var webView: WKWebView!
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let url = "https://example.com"
let request = URLRequest(url: URL(string: url)!)
self.webView.load(request)
self.webView.addObserver(self, forKeyPath: #keyPath(WKWebView.isLoading), options: .new, context: nil)
// Page Scrolling - false or true
webView.scrollView.isScrollEnabled = false
// Open new tab links
webView.uiDelegate = self
func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? {
if let frame = navigationAction.targetFrame,
frame.isMainFrame {
return nil
}
// for _blank target or non-mainFrame target
webView.load(navigationAction.request)
return nil
}
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == "loading" {
if webView.isLoading {
activityIndicator.startAnimating()
activityIndicator.isHidden = false
} else {
activityIndicator.stopAnimating()
activityIndicator.isHidden = true
}
}
}
}
A: This is the correct code for the question
import UIKit
import WebKit
class ViewController: UIViewController, WKUIDelegate {
@IBOutlet weak var webView: WKWebView!
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
override func viewDidLoad() {
super.viewDidLoad()
webView.uiDelegate = self
// Do any additional setup after loading the view, typically from a nib.
let url = "https://example.com"
let request = URLRequest(url: URL(string: url)!)
self.webView.load(request)
self.webView.addObserver(self, forKeyPath: #keyPath(WKWebView.isLoading), options: .new, context: nil)
// Page Scrolling - false or true
webView.scrollView.isScrollEnabled = false
}
// Open new tab links
func webView(_ webView: WKWebView,
createWebViewWith configuration: WKWebViewConfiguration,
for navigationAction: WKNavigationAction,
windowFeatures: WKWindowFeatures) -> WKWebView? {
if navigationAction.targetFrame == nil, let url = navigationAction.request.url, let scheme = url.scheme {
if ["http", "https", "mailto"].contains(where: { $0.caseInsensitiveCompare(scheme) == .orderedSame }) {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
}
}
return nil
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == "loading" {
if webView.isLoading {
activityIndicator.startAnimating()
activityIndicator.isHidden = false
} else {
activityIndicator.stopAnimating()
activityIndicator.isHidden = true
}
}
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58810014",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Combinations of Characters in an n by n Character Array: First a note: Sorry that my images aren't separated. I'm a new member, so I don't have enough reputation points to post more than a single hyperlink.
Let M be an n by n array (mathematically square matrix) of characters.
In M, I need to be able to find all permutation of characters with a restriction. The permutations do not have to be linear, but they they must contain characters such that each character is adjacent to at least one other character in the permutation. An example of an acceptable permutation follows below:
An unacceptable permutation is shown below.
I have derived this much:
*
*A permutation can have at most n squared characters in it (as no characters can be repeated).
*I do not know the exact number of permutation given the restrictions, but I believe there can be no more than the value generated by evaluating the expression pictured in the hyperlink.
I can very easily find the permutations which only contain characters in straight lines: vertical lines, horizontal lines, and diagonals. I am not sure of a way to exhaustively find all remaining permutations.
I have done research and have not been able to find a solution to a similar problem.
Any advice in the development of such an exhaustive algorithm would be greatly appreciated.
http://i.stack.imgur.com/uDNfv.png
A: One algorithm comes to mind immediately, though optimizations can be made, if time-complexity is a concern.
At each element in the 2x2 array (or we can call it a matrix if you like), there are 8 directions that we can travel (North, NE, East, SE, South, SW, West, NW).
The pseudo code for the meat of the algorithm goes a bit like this (I assume pass by value, so that "current_string" is a new string at each function call):
find(position, direction, current_string){
new_letter = m[0, position + direction];
if(!current_string.Contains(new_letter)){
// We have not yet encountered this letter during the search.
// If letters occur more than once in the array, then you must
// assign an index to each position in the array instead and
// store which positions have been encountered along each
// search path instead.
current_string += new_letter;
find(position, (0, 1), current_string);
find(position, (1, 1), current_string);
find(position, (1, 0), current_string);
find(position, (1, -1), current_string);
find(position, (0, -1), current_string);
find(position, (-1, -1), current_string);
find(position, (-1, 0), current_string);
find(position, (-1, 1), current_string);
} else {
// This letter has been encountered during this path search,
// terminate this path search. See comment above if letters
// occur more than once in the matrix.
print current_string; // Print one of the found strings!
}
}
Now you need to add some checks for things like "is position + direction outside the bounds of the array, if so, print current_string and terminate".
The high level idea of the algorithm above is to search along all possible paths recursively, terminating paths when they run into themselves (in the same way that snakes die in the game Snake).
If you use hashing to test containment of a new letter against the current string (as per the line if(!current_string.Contains(new_letter)){), which is amortized O(1) searching, then the worst case runtime complexity of this algorithm is linear in the number of possible strings there are in the matrix. I.e. if there are n possible string combonations in the matrix, then this algorithm takes about cn steps to complete for large n, where c is some constant.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/4858420",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How I can use mouse events with Jquery I'm tryng to configure the list of users in a chat adding the function slide
something like this
http://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_slide_down
Similar facebook, when mouse is over focus, the chat container is slowly hidden
I'm using jquery-1.8.1.min.js in the proyect and have the principal container with a id and i can configure those events like
$("mainContainer").someEvent(function () {
code...
}
I can use click, but i haven't mouse event when I put cursor inside for example.
I need .mousedown(), .mouseleave(), .mousemove(), hover(), etc.
Need I use another library JS?
I wish something like this, think the green box is the container with list of users in chat
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("div").mouseenter(function(){
$("div").animate({
width: '+=100px'
});
});
$("div").mouseout(function(){
$("div").animate({
width: '-=100px'
});
});
});
</script>
</head>
<body>
<div style="background:#98bf21;height:100px;width:50px;position:fixed;right:0px;">
User1<br/>
User2<br/>
User3<br/>
User4<br/>
</div>
</body>
</html>
A: Check http://api.jquery.com/on/
You could do something like this:
$("body").on({
click: function() {
//...
}
mouseleave: function() {
//...
},
//other event, etc
}, "#yourthing");
A: You can try this and can use any other mouse events according to your need:
$("#mainContainer").on('hover', function(){
$(selector).slideDown("slow");
}), function(){
$(selector).slideUp("slow");
});
A: Maybe something like this? You might not need any JavaScript for the mouseover effect.
#mainConatiner {
width: 300px;
height: 30px;
border: 1px solid #000;
}
ul {
opacity: 0;
transition: opacity 250ms ease;
}
#mainContainer:hover ul {
opacity: 1;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="mainContainer">
Hover me!
<ul>
<li>User 1</li>
<li>User 2</li>
</ul>
</div>
Let me know if it helps! Good luck.
A: JQuery has mouse based events. See here.
See this fiddle where I have adapted the w3schools example to work on mouseenter and mouseleave
A: You could use it like this, by calling the same function for multiple events:
$("mainContainer").on('click mouseenter',function (event) {
//This gives you what event happened, might be 'click' or 'mouseenter'
var type = event.type;
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30601659",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: changing the background colour of a recaptcha form that is placed in a DIV So i have a recaptcha form in a DIV. Currently the DIV has the background colour of white and the rest of my webpage is grey.
Where the recaptcha form is the white background is not displaying, but showing the grey colour instead.
The code i have for the recaptcha is in the DIV:
<div id="register">
<form action='register.php' method='post'>
<h1>Register Here:</h1>
<h1><?php echo $message; ?></h1>
Username:<input type='text' name='username'
value='<?php echo $username; ?>'><br />
Password:<input type='password' name='password'><br />
Repeat Password:<input type='password' name = 'repeatpassword' >
<?php echo $recaptcha_form; ?>
<input type='submit' name='submit' value='Register'>
<input name ='reset' type='reset' value='Reset'>
</form>
<h1>Once you have registered, log in <a href='login.php'>here!</a></h1>
</div>
And the CSS i have used is:
#login, #register, #home {
background-color: #FFFFFF;
width: 600px;
height: 500px;
margin: 0 auto;
border: solid;
border-color: #00ae00;
-moz-border-radius: 15px;
border-radius: 15px;
Padding-top: 10px;
text-align:center;
}
Below is more of the recaptcha code:
require_once('recaptcha/recaptchalib.php');
$publickey = "6Lem4-gSAAAAAMHLAVbieIknMtUZo71ZKzzCkoFN";
$privatekey = "6Lem4-gSAAAAADsaa9KXlzSAhLs8Ztp83Lt-x1kn";
$resp = recaptcha_check_answer($privatekey, $_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]);
$recaptcha_form = recaptcha_get_html($publickey);
//grab the form data
$submit = trim($_POST['submit']);
$username = trim($_POST['username']);
$password = trim($_POST['password']);
$repeatpassword = trim($_POST['repeatpassword']);
$message ='';
$s_usename ='';
//start to use PHP session
//determine whether user is logged in - test for vlaue in $_SESSION
if (isset($_SESSION['logged'])){
$s_username =$_SESSION['username'];
$message = "You are already logged in as $s_username.<br />
Please <a href='logout.php'>logout</a> before trying to register.";
}else{
//next block of code
if ($submit=='Register'){
//process submission
if (!$resp->is_valid) {
//what happens when the capture was entered incorrectly
$errMessage =$resp->error;
$message = "<strong>The recaptcha wasn't entered
correctly. Please try again.</strong> <br />" .
"(recaptcha said: $errMessage)<br />";
}else{
//process valid submission data here
if ($username&&$password&&$repeatpassword){
if ($password==$repeatpassword){
//process username details here
if (strlen($username)>25 ) {
$message= "Username is too long";
}else{
if (strlen($password)>25||strlen($password)<6) {
$message = "Password must be between 6-25 characters long";
}else{
//process details here
require_once("db_connect.php"); //include file to do db connect
if($db_server){
//clean the input not that we have a db connection
$username = clean_string($db_server, $username);
$password = clean_string($db_server, $password);
$repeatpassword = clean_string($db_server, $repeatpassword);
mysqli_select_db($db_server, $db_database);
//cheach whther username exsists
$query="SELECT username FROM register WHERE username='$username'";
$result=mysqli_query($db_server, $query);
if($row = mysqli_fetch_array($result)){
$message = "Username already exists. Please try again.";
}else{
//process further here
//Encrypt password
$password = salt($password);
$query = "INSERT INTO register (username, password) VALUES
('$username', '$password')";
mysqli_query($db_server, $query) or
die("Insert failed. ".mysqli_error($db_server));
$message = "<strong>Registration Successful!</strong>";
}
mysqli_free_result($result);
}else{
$message ="error: could not connect to the database.";
}
require_once("db_close.php"); //include file to do db close
}
}
}else{
$message = "Both passwords fields must match";
}
}else{
$message = "Please fill in all fields";
}
}
}
}
?>
Any idea what i can do which will colour the background area of the recapture form white?
please bare in mind im quire new to coding!
many thanks
A: Without having the recaptcha code, you can style it with this CSS:
#recaptcha_response_field { background: #fff !important; }
OR
you can use:
input[type=text] { background-color: #fff !important; }
A: https://developers.google.com/recaptcha/docs/display#render_param
there is a light dark setting
| {
"language": "en",
"url": "https://stackoverflow.com/questions/20995150",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Error with displaying an .bmp image using mfc dialog I am trying to display a bitmap image using MFC application.
I am using a browse button to select file which is working properly. But when I try to load an image by double clicking on the file, the application is launched, but the image is not displayed.
Here is my code for browse button and function to open a double clicked image.
void COpenImageDlg::OnBnClickedButton1()
{
// TODO: Add your control notification handler code here
CString path;
CFileDialog dlg(TRUE);
int result=dlg.DoModal();
if(result==IDOK)
{
path=dlg.GetPathName();
UpdateData(FALSE);
}
HBITMAP hBmp = (HBITMAP)::LoadImage(NULL, path, IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE|LR_CREATEDIBSECTION);
CBitmap bmp;
bmp.Attach(hBmp);
CClientDC dc(this);
CDC bmDC;
bmDC.CreateCompatibleDC(&dc);
CBitmap *pOldbmp = bmDC.SelectObject(&bmp);
BITMAP bi;
bmp.GetBitmap(&bi);
dc.BitBlt(0,0,bi.bmWidth,bi.bmHeight,&bmDC,0,0,SRCCOPY);
bmDC.SelectObject(pOldbmp);
}
void COpenImageDlg::OpenImage1(CString path)
{
//CString path;
CFileDialog dlg(TRUE);
int result=dlg.DoModal();
if(result==IDOK)
{
path=dlg.GetPathName();
UpdateData(FALSE);
}
HBITMAP hBmp = (HBITMAP)::LoadImage(NULL, path, IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE|LR_CREATEDIBSECTION);
CBitmap bmp;
bmp.Attach(hBmp);
CClientDC dc(this);
CDC bmDC;
bmDC.CreateCompatibleDC(&dc);
CBitmap *pOldbmp = bmDC.SelectObject(&bmp);
BITMAP bi;
bmp.GetBitmap(&bi);
dc.BitBlt(0,0,bi.bmWidth,bi.bmHeight,&bmDC,0,0,SRCCOPY);
}
Init class :
`BOOL COpenImageApp::InitInstance()
{
// InitCommonControlsEx() is required on Windows XP if an application
// manifest specifies use of ComCtl32.dll version 6 or later to enable
// visual styles. Otherwise, any window creation will fail.
INITCOMMONCONTROLSEX InitCtrls;
InitCtrls.dwSize = sizeof(InitCtrls);
// Set this to include all the common control classes you want to use
// in your application.
InitCtrls.dwICC = ICC_WIN95_CLASSES;
InitCommonControlsEx(&InitCtrls);
CWinApp::InitInstance();
AfxEnableControlContainer();
// Create the shell manager, in case the dialog contains
// any shell tree view or shell list view controls.
CShellManager *pShellManager = new CShellManager;
// Standard initialization
// If you are not using these features and wish to reduce the size
// of your final executable, you should remove from the following
// the specific initialization routines you do not need
// Change the registry key under which our settings are stored
// TODO: You should modify this string to be something appropriate
// such as the name of your company or organization
SetRegistryKey(_T("Local AppWizard-Generated Applications"));
COpenImageDlg dlg;
m_pMainWnd = &dlg;
INT_PTR nResponse = dlg.DoModal();
char* buff;
char* command_line = GetCommandLine();
buff = strchr(command_line, ' ');
buff++;
buff = strchr(buff, ' ');
buff++;
buff = strchr(buff, ' ');
buff++;
if (buff != NULL)
{
HBITMAP hBmp = (HBITMAP)::LoadImage(NULL, "C:\Users\Raguvaran\Desktop\tiger.bmp", IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE|LR_CREATEDIBSECTION);
CBitmap bmp;
bmp.Attach(hBmp);
dlg.RedrawWindow();
CClientDC dc(m_pMainWnd);
CDC bmDC;
bmDC.CreateCompatibleDC(&dc);
CBitmap *pOldbmp = bmDC.SelectObject(&bmp);
BITMAP bi;
bmp.GetBitmap(&bi);
dc.BitBlt(0,0,bi.bmWidth,bi.bmHeight,&bmDC,0,0,SRCCOPY);
}
//RedrawWindow(dlg, NULL, NULL, RDW_INVALIDATE);
//UpdateWindow(dlg);
if (nResponse == IDOK)
{
// TODO: Place code here to handle when the dialog is
// dismissed with OK
}
else if (nResponse == IDCANCEL)
{
// TODO: Place code here to handle when the dialog is
// dismissed with Cancel
}
// Delete the shell manager created above.
if (pShellManager != NULL)
{
delete pShellManager;
}
// Since the dialog has been closed, return FALSE so that we exit the
// application, rather than start the application's message pump.
return FALSE;
}`
I used the same code for browse button and it displays the image. But when I double click the file, the image is not displayed. Please tell me what I am doing wrong.
A: If you have associated your application with a particular file extension, it will be launched automatically when you double-click such a file (as you have said).
When this happens, your application is launched with the file name (actually the full path) supplied as a command line argument to your application.
In SDI MFC applications, this is handled automatically by the framework as long as you haven't overridden the default File/Open handling mechanism, but if you have a dialog-based application you will need to add code for this yourself.
A: Your dialog COpenImageDlg is created and displayed inside the call to DoModal before the command line has a chance to be processed. When the DoModal returns, the dialog is already destroyed, so there is no dialog for the code to draw upon.
A: I understand that when you double click the file to choose a image on file dialog, the image doesn't show. I just tried your code of function OnBnClickedButton1 and OpenImage1. And it turns out that the image is displayed when double click to choose a image. I use VS2010 on win7. I hope this will help you though i donot find the error of your code.
A: I found the answer to my question.
It was actually a very stupid mistake.
When I read the file address using Commandline, the address has single slash, whereas I need to pass the address using double slash.
Such a silly bug. Sorry to waste your time.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/20701561",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: C#: Attribute on collection element In C# can attribute be applied to element, which will be packed in collection?
I have Dictionary<string,Func<int,int,int>> and add elements in that way
Dictionary<string,Func<int,int,int>> dict = new Dictionary<string,Func<int,int,int>>();
dict.Add("SUM", (a,b) => {return a+b;});
So I want add additional information to element with key "SUM" such as "Returns summary of two numbers". Can this be done with attributes or I must include additional data in collection?
A: If you look at what you can apply an attribute to, you'll notice you can only apply it to Assembly, Class, Constructor, Delegate, Enum, Event, Field, GenericParameter, Interface, Method, Module, Parameter, Property, ReturnValue, or Struct (source). You can't apply attributes to individual values so you will have to store additional data, you could make a small class, something like:
public class Operation
{
public string Description {get;set;}
public Func<int, int, int> Func {get;set;}
}
And then use it in your dictionary like:
dict.Add("SUM", new Operation() {
Description = "Adds numbers",
Func = (a,b) => {return a+b;}
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/33308104",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Cannot locate pygubu-designer.exe after instalation I'm trying to install pygubu-designer, but the 'pygubu-designer.exe' never shows up in any of the folders after the installation process.
https://github.com/alejandroautalan/pygubu
https://github.com/alejandroautalan/pygubu-designer
I did:
pip install pygubu
cmd
pip install pygubu-designer
cmd
I have couple of folders with pygubu but pygubu-designer.exe is missing
explorer
I have python 3.10.4 and pip 20.0.4 and python is added as system variable:
cmd
I tried to upgrade pip version but it did not work
A: Could not locate pygubudesigner within my python310\Scripts folder and any other but the cmd command mentioned in this issue: https://github.com/alejandroautalan/pygubu/issues/222 worked for me
python -m pygubudesigner
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74533716",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Call AIR Application method from Javascript I have an Adoboe AIR (ActionScript) application that embeds an HTML page using the AIR HTML component. I would like to add communication between the two: E.g. I would like to call a method within the AIR Application from the Javascript within the HTML page in the HTML component etc... Is this possible ?
Thanks in advance,
Jon.
A: I willing to recommend. refer a this article:
Communicating between ActionScript and JavaScript in a web browser
| {
"language": "en",
"url": "https://stackoverflow.com/questions/11954439",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to get "who" invited using Facebook App Invite SDK for iOS? I've been trying to get the "who" invited someone on my app without success... Looked around FB docs and nothing.
What I mean is: "User??" invites "Friend", "Friend" taps install on the FB dialog which takes him to App Store, where s/he installs my app.
Once the app is installed, the "App Link" seems to not be passed on to my app and I can't find out who is "User??" (the inviter)
IF the app is already installed in the iPhone and the "Friend" clicks "open", then the "App Link" info is passed correctly.
How can I get the identity of "User??" (the inviter) when it's a new install? Is there another way I can do this "server side" etc?
EDIT:
I've found how to get apprequests from the new user's FB etc BUT now I have another problem: If two people invite the same "new user" how to know which invite s/he accepted? How can I get status about apprequests? I think I will create another question...
A: So, I've found out how. Once the "new user" installs my app and signs up with his facebook account I can execute this
GraphRequest request = GraphRequest.newGraphPathRequest(
accessToken,
"/me/apprequests",
new GraphRequest.Callback() {
@Override
public void onCompleted(GraphResponse response) {
// process the info received
}
});
request.executeAsync();
The above code will get all/any apprequests from my app only and I only have to check who sent it etc.
A: If the App is already installed on the device, are you getting the identity of the "User" who invited the "Friend"? If yes, how are you doing this?
Secondly, Applink will only pass the information if it is opened through the notification on Facebook, and not directly through the home screen.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/33195655",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Trying to send a friend request I am trying to send a friend request with my code. I followed an easy tutorial on youtube. The code does not have any errors but its not working. Here the important part:
fAuth = FirebaseAuth.getInstance();
fStore = FirebaseFirestore.getInstance();
userId = getIntent().getStringExtra("user_id");
reference = FirebaseDatabase.getInstance().getReference().child("users").child(userId);
FriendRequest = FirebaseDatabase.getInstance().getReference().child("Friend_req");
currentuser = FirebaseAuth.getInstance().getCurrentUser();
add.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (currentstate.equals("not_friends")){
FriendRequest.child(currentuser.getUid()).child(userId).child("request_type").setValue("sent")
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()){
FriendRequest.child(userId).child(currentuser.getUid()).child("request_type").setValue("received").addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
Toast.makeText(otherProfile.this, "SEND", Toast.LENGTH_SHORT).show();
}
});
} else {
Toast.makeText(otherProfile.this, "FAiLED", Toast.LENGTH_SHORT).show();
}
}
});
}
}
});
Maybe the problem is that I am not using a RealTimeDatabase ?
A: Your screenshot is showing Firestore, but your code is working with Realtime Database. These are completely different database products. Your code needs to match the product you're using. Be sure the check the product documentation for examples of correct usage.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/59938134",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Pass variable with subvariable from JQuery to Flask app I have a Flask that uses WTForms and Jquery to take from the user "input" fields in a form and shows "select" fields to the user. Jquery is used to filter the select fields shown to the user based on what they enter in the input fields. In order to filter the select fields, I need to take what the user enters in the input fields and send it to the Flask app.
These are the form fields -
class TableName(FlaskForm):
schema = StringField('Schema', validators=[DataRequired()], id = 'schema_name')
table = StringField('Table', validators=[DataRequired()], id = 'table_name')
class QaForm(FlaskForm):
test_table_in = FormField(TableName, id = 'test_table')
prod_table_in = FormField(TableName, id = 'prod_table')
This is the JQuery -
$(function() {
var tables = {
test_table: $('test_table_in-schema_name').val() + "." + $('test_table_in-table_name').val(),
prod_table: $('prod_table_in-schema_name').val() + "." + $('prod_table_in-table_name').val()
};
var fields = {
test: [$('#select_test_join_key'), $('#select_test_dimensions')],
prod: [$('#select_prod_join_key'), $('#select_prod_dimensions')]
};
fields.test.forEach(item => updateFields(tables.test_table, item));
fields.prod.forEach(item => updateFields(tables.prod_table, item));
function updateFields(table, field) {
var send = {
table: tables.table
};
$.getJSON("{{url_for('_get_fields') }}", send, function(data) {
//do something
});
}
});
When the user enters a "test_table", the test table should get passed to _get_fields() and when the user enters a prod_table, that value should get sent to _get_fields(). Test_table and prod_table are two form fields, each consisting of two subfields, "schema" and "table" that are combined to create one field in the format "schema.table".
Function _get_fields() in Flask view to receive the table name -
@app.route('/_get_fields/')
def _get_fields():
table = request.args.get('table', type=str)
fields_query = f"""select column_name AS Fields from information_schema.columns WHERE
table_name = '{table}' group by 1 limit 10;"""
conn.execute(fields_query)
result = conn.fetchall()
return jsonify(result)
Potential errors:
It's the request_args.get() function in the Flask view that I believe is not referring correctly to the JQuery variables. I've tried 'test_table', 'prod_table', and others but none of these have worked so far. I'm using the "name" of the input form elements to create the table variables - I'm wondering if that may be a part of the issue as well. Any thoughts or suggestions?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/67481988",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to count the advertisement hits and stores it in database We put our website advertisement in 2 other websites. We need to count the hits we are getting form those advertisement and like to store it in my database. Please give me an idea to do that.
A: The links to your website should have a parameter with some key that will allow you to identify the partner site.
Another approach would use the Referer http header but is less reliable.
A: Sorry, I din't understood at first place the question.
You can grab the referer using PHP or link the banners to a landing page instead of to the home directly (ex: http://yoursite.com/banner.php?id=N, you can identify the referer with PHP and with the banner ID and then redirect the user to your home.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/2857468",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Yup Validation isn't working with React JS I want a YUP validation to check if the user id already exists in the database or not.
I have written it like this :-
userName: Yup.string()
.required("You must enter the User ID")
.test(
"Unique User ID",
(value, {createError}) => {
axios
.get({url})
.then((res) => {
if(res.data.userName){
setUser(res.data);
}
else
setUser(null);
})
.catch((error) => {
});
return user !== null
? createError({
message: 'Please choose a different user id. User id is already in use on another account.',
path: 'userName',
})
: true;
}
)
.min(1, 'You must enter the User ID')
.test('length', 'User ID can only be of 8 characters', val => val != null ? val.length <= 8 : false),
The user id from backend returns a json response. If the response is positive then the object with data like userName,firstName etc is received and if the response is negative then the json response comprises of an error code and message.
Can someone help me on this?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/73134349",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Submit buttons and Enter key issues I'm trying to prevent form submit if users has focus on any submit button or input type text (as in a filtering datagrid).
I'm considering 2 options
*
*replace submit button with some kind of <p onclick='submitform¶meters'>Add</p>
*block the enter key on buttons and some preferred input fields
Is there a better way to do this?
A: If you add an onKeyPress event to the element in question, you can prevent the default action (form submission) by returning false from the function:
<input id="txt" type="text" onKeyPress="var key = event.keyCode || event.which; if (key == 13) return false;"></input>
Note that the which property of the keyboard event is deprecated, but you'll still want to check for it to support older user agents and/or Internet Exploder (reference).
If you don't want to use inline javascript (which is not recommended), you can instead attach an event. Also, it may be better to use the preventDefault (docs) method of the event object, as well as the stopPropagation method (docs) - the necessity for these methods this is highly dependent on what other events you have attached to the form or the elements:
var preventFormSubmit = function (event) {
var key = event.keyCode || event.which;
if (key != 13)
return;
if (event.stopPropagation) event.stopPropagation();
else event.cancelBubble = true; // deprecated, for older IE
if (event.preventDefault) event.preventDefault();
else event.returnValue = false; // deprecated, for older IE
return false;
};
var target = document.getElementById('txt');
if (typeof target.addEventListener == 'function')
target.addEventListener('keypress', preventFormSubmit, false);
else if (typeof target.attachEvent == 'function')
target.attachEvent('onkeypress', preventFormSubmit);
There are other approaches to use, such as attaching a more complex onSumit handler to the form itself - this may be more appropriate if you're going to be doing further manipulation of the form or data before submitting (or using AJAX to submit the form data).
A: Solution
input id="txt" type="text" onKeyPress="if (event.which == 13) return false;"></input>
Link
http://stackoverflow.com/questions/1567644/submit-form-problem-enter-key
Question closed
| {
"language": "en",
"url": "https://stackoverflow.com/questions/8141675",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Why does FaceAlpha affect ZData of different object? working with matlab 2015a in linux.
trying this code (with the slice grid ,x and y in the mat file attached)
FaveAlpha.mat
load('FaceAlpha.mat'); % Loading SliceGrid and X,Y parametrs
hold on; xlabel('X'), ylabel('Y'), zlabel('Z'); axis equal;
axis image;
plot(SliceGrid.x(X),SliceGrid.y(Y),'blue.');hold on;
h=[-8 -0.5 0.5 1]
v=[7 4 4 7];
fill_2=fill(h,v,'blue'); % Creating blue object
x=[0 -0.5 0.5 1]
y=[9 4 4 9];
fill_1=fill(x,y,'red');% Creating red object
t=[-2 -0.5 0.5 2];
z=[9 2 2 0];
fill_3=fill(t,z,'yellow'); % Creating yellow object
set(fill_1,'FaceAlpha',0.5); % After this line everthing is ok.
set(fill_2, 'ZData', repmat(10, size(get(fill_2, 'XData')))); % After this line the outside blue plot is damaged - as you can see in the above figure
%%%%%%%%%%%% if we omit the line -> set(fill_1,'FaceAlpha',0.5);
%%%%%%%%%%%% and leave the code with the ZData property, the outside blue plot doesn't damaged.
%%%%%%%%%%%% if we omit the line -> set(fill_2, 'ZData', repmat(10, size(get(fill_2, 'XData'))));
%%%%%%%%%%%% and leave the code with the FaceAlpha property, the outside blue plot doesn't damaged.
why and how does face alpha affect other object with ZData? and why are they doesn't work together? what is wrong? Thank you!!
before:
after:
A: Ok, so it seems that if we will check the code of after this line of code:
set(fill_1,'FaceAlpha',0.5);
a=get(gca,'SortMethod')
We will get a=childorder, that means that the appearance of every object is by the child order of gca of the figure (And this is by the way is the default)
After the line of code of ZData, that order is changed by Matlab, its changing to depth, so if you will re-use the function :
a=get(gca,'SortMethod')
a=depth now.
So if you want to fix the problem just use this code:
set(gca,'SortMethod','childorder')
And - We have a winner! :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31802621",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Need help searching for a value in firestore I'm new to firestore and I'm making a register page with vue.
Before a new user is made, it has to check if the given username already exists or not and if not, make a new user.
I can add a new user to the database, but I don't know how to check if the username already exists or not. I tried a lot of things and this is the closest I've gotten:
db.collection("Users")
.get()
.then(querySnapshot => {
querySnapshot.forEach(doc => {
if (this.username === doc.data().username) {
usernameExist = true;
}
});
});
Anyone got any ideas?
A: Link to documentation: https://firebase.google.com/docs/firestore/query-data/queries#simple_queries
You can where this query, which is beneficial to you in multiple ways:
1: Fewer docs pulled back = fewer reads = lower cost to you.
2: Less work on the client side = better performance.
So how do we where it? Easy.
db.collection("Users")
.where("username", "==", this.username)
.get()
.then(querySnapshot => {
//Change suggested by Frank van Puffelen (https://stackoverflow.com/users/209103/frank-van-puffelen)
//querySnapshot.forEach(doc => {
// if (this.username === doc.data().username) {
// usernameExist = true;
// }
//});
usernameExists = !querySnapshot.empty
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60341540",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Repast Simphony Model Library Is there any model library for Repast Simphony? I'm looking for something similar to the Computational Model Library of OpenABM. Unfortunatelly, there are only models for NetLogo but not for Repast in this library. (In particular, I'm searching for a scientific paper using agent based simulation for studying innovation diffusion processes and a corresponding model in Repast I can download. The idea in behind is to show the power of Repast in a lecture.)
Thank you very much!
A: The Computational Model Library contains models from a variety of ABM modeling toolkits, including Repast Simphony. These come up if you search using "Repast" as a keyword.
Repast Simphony also comes with demonstration models (included in the macOS and Windows distributions or available here as a standalone download), but those are more geared towards showing examples of how Repast Simphony features can be incorporated into user models. Have you looked at those?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/49840373",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to create reports page in Directus I want to create report page in Directus, I am programming in JS and PHP but I can not figure out how to embed some code into Directus in order to create reports page from which I could do a query to multiple tables in database and then show results.
A: You will need to create a page (an extension) within the Directus App using VueJS.
Basic understanding of JavaScript and VueJS would be required, but once you create the page, you can then query as many collections as you wish to create reports.
For more information see:
https://docs.directus.io/extensions/pages.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58324875",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: PHP Script stops running due to heavy load I have two while loops which is diplaying data from database,but due to heavy load its stops working.
please let me know how to destroy/clear previous load on each while loop.
**Code Example: this is not an exact code, but take it as example**
for ($aw = 1; $aw <= 150000; $aw++) {
$sql="INSERT INTO say (cname,cno,clocation,email) VALUES ('Fin','0743208899','London','[email protected]')";
$result=mysql_query($sql);
}
A: Instead of running 50,000 queries, build one query:
$rows = Array();
for( $aw=1; $aw<=50000; $aw++) $rows[] = "('Fin','0743208899','London','[email protected]')";
mysql_query("INSERT INTO say (cname,cno,clocation.email) VALUES ".implode(",",$rows));
| {
"language": "en",
"url": "https://stackoverflow.com/questions/11497402",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: TCL 0 not equal to FALSE I tried
expr 0==false
but it returns 0 instead of 1.
According to http://wiki.tcl.tk/16295, False values are the case-insensitive words no, off, false, their unique abbrevations, and 0.
It is weird, or my understanding are wrong?
A: While specifying operands for expr command, to validate against a boolean value, we should use only string is command.
% expr {0==false}
0
% expr {[string is false 0]}
1
Simply validating against boolean equal == will treat them as if like literal string/list.
Reference : expr
| {
"language": "en",
"url": "https://stackoverflow.com/questions/35261293",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: fitting a tanh curve and estimating parameters I have two sets of data (say x and y). I want to fit a tanh curve (hyperbolic tangent) for y=x-a-btanh[(x-a)/b)] and return a and b parameters. I tried the follwing code, but get an error, TypeError: 'numpy.ufunc' object is not subscriptable. Also, I want to know if the following function is a right way to fit a tanh curve. Thanks!
from scipy.optimize import curve_fit
import numpy as np
import matplotlib as plt
x=[799.0,872.0,882.0,986.0,722.0,479.0,747.0,510.0,1012.0,1114.0,801.0,662.0,853.0,878.0,779.0,987.0,707.0,756.0,730.0,523.0,802.0,1068.0,780.0,927.0,923.0,790.0,852.0,580.0,730.0,924.0,762.0,662.0,927.0,828.0,866.0,951.0,949.0,740.0,677.0,704.0,798.0,791.0,761.0]
y=[27.64,110.75,139.34,66.02,26.66,5.29,11.75,3.81,64.07,286.23,57.23,43.61,18.68,55.4,65.97,206.51,16.32,19.25,10.98,3.12,15.41,122.89,62.43,112.18,34.86,46.59,48.96,3.69,11.3,49.92,18.96,6.57,32.74,35.76,46.35,115.04,131.46,46.63,26.25,4.55,9.21,36.32,11.47]
def myfunc(x,a,b):
return x-a-b*np.tanh[(x-a)/b]
popt, pcov = curve_fit(myfunc, x, y)
plt.plot(x, myfunc(x, *popt))
A: The problem is here: np.tanh[(x-a)/b]
That might be the mathematical notation, but it's not valid python syntax.
Function are called with parentheses (). So it should be: np.tanh((x-a)/b)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74269928",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is it possible to decode a .c2z? Is it possible to decode a .c2z file and retrieve the code inside? if so How would I go about doing that?
I can't find any programs that will open it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74327001",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to use vert.x shell to monitor message traffic I have a simple verticle, which receives a string as input and replies with another string. I was planning to use vert.x shell (telnet) to send and publish messages using bus-send and bus-publish. However these methods does not seem to interact with the local bus. Any ideas what might go wrong?
I want to have a behavior similar to dbus-sendand dbus-monitorutilities in linux.
A: If the shell is started as it is stated in the docs:
vertx run -conf '{"telnetOptions":{"port":5000}}' maven:io.vertx:vertx-shell:3.2.1
it wont be able to commuicate with other verticles, as it is not in any cluster. The solution is to add --cluster and --cluster-host flags:
vertx run -conf '{"telnetOptions":{"port":5000}}' maven:io.vertx:vertx-shell:3.2.1 --cluster --cluster-host localhost
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37858188",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Airflow DAG for backfill I am a newbie to Apache Airflow and trying to explore things on that tool. I am not sure how can I use the dates in SQL Queries while bringing the data with Airflow where it is quite simple in Oozie like below:
"SELECT * FROM Table_Name WHERE datetm BETWEEN '${DATE_START}' AND '${DATE_STOP}'"
But not sure what parameters available in Airflow and how can we implement the logic to backfill or dynamic dates runtime.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/50671008",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Drag and Drop files uploading error php i watched many links on internet and also reffered to each and every question related to this topic but none helped! so plz any1 check this code and tell me where i'm doing wrong?
html code:
<div class="drop_zone">
<p>Drop Here</p>
</div>
<form enctype="multipart/form-data" id="yourregularuploadformId">
<input type="file" name="files[]" multiple="multiple">
</form>
jQuery and javascript code:
function handleFiles(droppedFiles) {
var uploadFormData = new FormData($("#yourregularuploadformId")[0]);
if(droppedFiles.length > 0) { // checks if any files were dropped
for(var f = 0; f < droppedFiles.length; f++) { // for-loop for each file dropped
alert(droppedFiles[f]['name']);
uploadFormData.append("files[]",droppedFiles[f]); // adding every file to the form so you could upload multiple files
}
}
// the final ajax call
alert(uploadFormData);
$.ajax({
url : "try.php", // use your target
type : "POST",
data : uploadFormData,
cache : false,
contentType : false,
processData : false,
success : function(ret) {
alert(ret);
}
});
return false;
}
$(document).ready(function() {
//alert("im in");
$('.drop_zone').bind("dragenter", function(e) {
// $('#StatusDrag').html('Drop The files Here...');
});
$('.drop_zone').bind("dragleave", function(e) {
// $('#StatusDrag').html('Drag and Drop Files Here to Share');
});
$('.drop_zone').bind("dragover", function(e) {
e.preventDefault();
return false;
});
$('.drop_zone').bind("drop", function(e) {
e.preventDefault();
e.stopPropagation();
e.originalEvent.preventDefault();
e.originalEvent.stopPropagation();
// $('#dragBox, #topDiv').hide();
var dt = e.originalEvent.dataTransfer;
var files = dt.files;
handleFiles(files);
});
});
php code:
<?php
if(isset($_FILES["files"]))
{
foreach ($_FILES["files"] as $file)
echo $file['name'];
}
?>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/19337390",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Layout does not exist in the current context I'm trying to include the layout in one of my views and it's saying it doesn't exist in current context along with viewbag.
@{
ViewBag.Title = "About Me";
Layout = "~/Views/Shared/_Layout.cshtml";}
I've looked at other solutions saying I need this or that in the web.config, though nothing has worked.
I'm on Mac OS and using Visual Studio for Mac Community
views/web.config:
<configuration>
<configSections>
<sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
<section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
<section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
</sectionGroup>
</configSections>
<system.web.webPages.razor>
<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.2.7.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<pages pageBaseType="System.Web.Mvc.WebViewPage">
<namespaces>
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Routing" />
<add namespace="GroundRoots" />
</namespaces>
</pages>
</system.web.webPages.razor>
<appSettings>
<add key="webpages:Enabled" value="false" />
</appSettings>
<system.webServer>
<handlers>
<remove name="BlockViewHandler" />
<add name="BlockViewHandler" path="*" verb="*" preCondition="integratedMode" type="System.Web.HttpNotFoundHandler" />
</handlers>
</system.webServer>
</configuration>
root web.config:
<!--
Web.config file for GroundRoots.
The settings that can be used in this file are documented at
http://www.mono-project.com/Config_system.web and
http://msdn2.microsoft.com/en-us/library/b5ysx397.aspx
-->
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.5">
<assemblies />
</compilation>
<httpRuntime targetFramework="4.5" />
</system.web>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-5.2.7.0" newVersion="5.2.7.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<system.webServer>
<handlers>
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="OPTIONSVerbHandler" />
<remove name="TRACEVerbHandler" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer></configuration>
Not really sure where to go from here...
A: Does the layout work on another views? Try to create a new view and check "Use a layout page" and then select your layout view file. Hope this works, it has always worked for me
| {
"language": "en",
"url": "https://stackoverflow.com/questions/61248639",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Add Facebook App 2 Times to fanpage i have created an app, which u can see online:
http://www.facebook.com/pages/Hotel-Des-Balances/302383665689?sk=app_102064213296864
But there i have created tabs inside the iframe, i want to create them directly in facebook, so that i have Tab1 for the Game1, Tab2 for game2 without creating multiple facebook apps!
How can i create multiple add to page ?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/14367520",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: WP Upload Image Through Ajax Response Issue I am facing an issue when I am trying to upload the image through WP ajax from front side. I can see the Ajax triggering fine. I can successfully upload the image to the server as well. But when I try to read the response, it does not do anything.
Here is my Ajax request.
jQuery.ajax({
type: "POST",
processData: false,
contentType: false,
cache: false,
url: testing.ajax_url,
data: form_data,
success: function (res) {
if ("success" == res.response) {
alert("Yeah!");
} else {
alert("Hmm");
}
}
});
I can see the response in the network area as well like {"response":"success"} this, but not able to access it.
Thanks!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60831543",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: optional parameter based off boolean template parameter I'm trying to declare a template function that...
*
*has 3 parameters if template boolean is true
*has only 2 parameters if template boolean is false
Is this possible?
The code below compiles, however both versions require 3 parameters. I need it to only need 2 parameters when the template boolean is false and the resulting usage of the function - the user only needs to supply 2 parameters.
Ideally this is a single function, so code duplication can be avoided as the function definition is very simple.
Static:
Iterate thru area, apply hash to nodes.
Dynamic:
Iterate thru area, transform node by 2D rotation, apply hash to node.
Ideally the selection of the logic to use can be evaluated at compile time aswell
if constexpr(Dynamic) ...
template<bool const Dynamic>
void setHashAt(rect2D_t area, uint32_t const hash, std::conditional_t<Dynamic, v2_rotation_t const&, void> vR)
Thanks!
A: Sure, you can do that through SFINAE;
#include <type_traits>
template <const bool EnableThird, std::enable_if_t<EnableThird, int> = 0>
void dynamic_parameter_count(int one, int two, int three) {
std::cout << "EnableThird was true\n";
}
template <const bool EnableThird, std::enable_if_t<!EnableThird, int> = 0>
void dynamic_parameter_count(int one, int two) {
std::cout << "EnableThird was false\n";
}
And you can then simply invoke using;
dynamic_parameter_count<true>(1, 2, 3);
dynamic_parameter_count<false>(1, 2);
This works by enabling or disabling one of the template instantiations based on the template parameters. You do, in fact, need two templates for this as far as I know. I'm not sure if you can do this in one template.
You can also simply specify two versions for the same function, however;
void parameter_count(int one, int two, int three) {
std::cout << "3 Parameters\n";
}
void parameter_count(int one, int two) {
std::cout << "2 Parameters\n";
}
To me, without knowing the context you are working in, this seems more logical.
Or even:
#include <optional>
void parameter_count(int one, int two, std::optional<int> three = {}) {
if (three.has_value()) {
std::cout << "3 Parameters\n";
} else {
std::cout << "2 Parameters\n";
}
}
A: Simple overload seems simpler, but to directly answer your question, you might (ab)use of variadic template and SFINAE:
template<bool Dynamic,
typename ... Ts,
std::enable_if_t<(Dynamic == false && sizeof...(Ts) == 0)
|| (Dynamic == true && sizeof...(Ts) == 1
&& std::is_convertible_v<std::tuple_element_t<0, std::tuple<Ts...>>,
v2_rotation_t>)
, bool> = false>
void setHashAt(rect2D_t area, uint32_t const hash, const Ts&... vR);
With the caveat that 3rd argument should be deducible (so no {..}).
A: This is a small variation to your solution
#include <type_traits>
struct None{};
template<bool select>
void foo(int, std::conditional_t<select, int, None> = None{}) {
}
int main() {
foo<false>(1);
foo<true>(1,2);
// foo<false>(1,2); // fails
// foo<true>(1); // fails
}
I don't think this is a clean solution, but instead overloading and refactoring the code to avoid duplication should be the right approach (as suggested in comments).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66366410",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Different types of login in Laravel I have 2 login types on my application:
protected function attemptLogin(Request $request)
{
if (!$uuid = $request->input('uuid')) {
$user = User::query()->firstWhere($this->username(), $request->input($this->username()));
return $this->guard()->attempt(
$this->credentials($request), $request->filled('remember')
);
}
$link = OneTimeLoginLink::findUnused($uuid);
$user = $link->user;
$this->guard()->login($user);
$request->session()->put('otl', $link);
return true;
}
The login is working fine on both. But I have a problem with the login by user: $this->guard()->login($user). After sometime when I open the page I'm not automated login based on cookie session, I need to remove this cookie from storage and make a refresh (after that I'm successfully login, don't understand why).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/71593911",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Out of Memory Exception in C# i am new to C#.
Thus, i am not so sure what the problem is with my program.
The program works with small image but it shows "Out of memory exeception" when it works with a large image which is about A4 size.
However, the program would be useless if it cannot work with large image.
How can I solve the problem?
With thanks.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
namespace ConsoleApplication6
{
class Program
{
static void Main(string[] args)
{
//Bitmap objects
//input image
Bitmap bmOrg = (Bitmap)Bitmap.FromFile(@"C:\B.png");
Bitmap bmTransparentLayover = new Bitmap(bmOrg.Width, bmOrg.Height);
//Create Graphic Objects.
Graphics gOriginal = Graphics.FromImage(bmOrg);
Graphics gTransparentLayover = Graphics.FromImage(bmTransparentLayover);
//Set Transparent Graphics back ground to an "odd" color
// that hopefully won't be used to
//Be changed to transparent later.
gTransparentLayover.FillRectangle
( Brushes.Pink,
new Rectangle
(0,
0,
bmTransparentLayover.Width,
bmTransparentLayover.Height
)
);
//Draw "transparent" graphics that will look through
// the overlay onto the original.
//Using LimeGreen in hopes that it's not used.
Point[] points = new Point[5];
points[0] = new Point(130, 140);
points[1] = new Point(130, 370);
points[2] = new Point(420, 370);
points[3] = new Point(420, 140);
points[4] = new Point(130, 140);
System.Drawing.Drawing2D.GraphicsPath gp = new
System.Drawing.Drawing2D.GraphicsPath();
gp.AddPolygon(points);
gTransparentLayover.FillPath(Brushes.LimeGreen, gp);
//Now make the LimeGreen Transparent to see through overlay.
bmTransparentLayover.MakeTransparent(Color.LimeGreen);
//draw the overlay on top of the original.
gOriginal.DrawImage(bmTransparentLayover,
new Rectangle(0, 0, bmTransparentLayover.Width, bmTransparentLayover.Height));
//Create new image to make the overlays background tranparent
Bitmap bm3 = new Bitmap(bmOrg);
bm3.MakeTransparent(Color.Pink);
//Save file.
//to save the output image
bm3.Save(@"save.png",System.Drawing.Imaging.ImageFormat.Png);
Image img = new Bitmap(480, 480);
//the background image
img = Image.FromFile(@"a.png");
Graphics g = Graphics.FromImage(img);
//to save the combined image
g.DrawImage(Image.FromFile(@"save.png"), new Point(-50, -70));
img.Save(@"final.png", ImageFormat.Png);
}
}
}
A:
it is a 9992x8750 image
Yes, you're in the danger zone for a 32-bit process. That image requires a big chunk of contiguous address space, 334 megabytes. You'll easily get that when you load the image early, right after your program starts. You can get about 650 megabytes at that point, give or take.
But that goes down-hill from there as your program allocates and releases memory and loads a couple of assemblies. The address space gets fragmented, the holes between the allocations are getting smaller. Just loading a DLL with an awkward base address can suddenly cut the largest hole by more than a factor of two. The problem is not the total amount of virtual memory available, it can be a gigabyte or more, it is the size of the largest available chunk. After a while, having a 90 megabyte allocation fail is not entirely unusual. Just that one allocation can fail, you could still allocate a bunch of, say, 50 megabyte chunks.
There is no cure for address space fragmentation and you can't fix the way that the Bitmap class stores the pixel data. But one, specify a 64-bit version of Windows as a requirement for your program. It provides gobs of virtual memory, fragmentation is a non-issue. If you want to chase it down then you can get insight in the VM layout with the SysInternals' VMMap utility. Beware of the information overload you may experience.
A: I suspect that your main problem is that you've got a number of bitmap and graphics instances in use at the same time.
It's probably worth trying to reorganise your code so that as few of these are present at any one time as possible, using .Dispose() to remove items you're finished with.
A: Try to work on Windows 64-bit, That's the solution of most of memory problems.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/11556683",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: How can I change Button color via a trigger in the button? Whats wrong with this trigger? I found it here: http://www.wpf-tutorial.com/styles/trigger-datatrigger-event-trigger/ and ive seen similar setups on SO
<Button x:Name="ColorPickerButton" Background="{Binding SelectedColor}">
<Button.Style>
<Style TargetType="{x:Type Button}">
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" Value="Red"/>
</Trigger>
</Style.Triggers>
</Style>
</Button.Style>
</Button>
Im trying to break down my spaghetti XAML and make it more readable. This is my old implementation which does work. I dont like it because it overwrites the button content and overlays a border which seems unnecessary. Also its massive
<Button x:Name="ColorPickerButton" Background="{Binding SelectedColor}">
<Button.Resources>
<Style TargetType="{x:Type Button}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Border x:Name="Bd"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"
Background="{TemplateBinding Background}"
Padding="{TemplateBinding Padding}"
SnapsToDevicePixels="true">
<GridViewRowPresenter/>
</Border>
<ControlTemplate.Triggers>
<MultiTrigger>
<MultiTrigger.Conditions>
<Condition Property="IsMouseOver" Value="True"/>
</MultiTrigger.Conditions>
<Setter Property="BorderBrush" Value="{StaticResource ColorPickerButton.MouseOver.Border}"/>
</MultiTrigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Button.Resources>
</Button>
A: Your Trigger does not work because the default Template of the button has its own trigger that changes the background brush of the root border when the IsMouseOver Property is set. This means: As long as the mouse is on top of the button, the Background-property of the button control will be ignored by its template.
The easiest way to check out the default style of your button is to: right-click at the button in the visual studio wpf designer. Click 'Edit template' -> 'Edit a copy' and select a location.
A copy of the default style is created at the specified location. You will see a trigger like this:
<Trigger Property="IsMouseOver" Value="true">
<Setter Property="Background" TargetName="border" Value="{StaticResource Button.MouseOver.Background}"/>
<Setter Property="BorderBrush" TargetName="border" Value="{StaticResource Button.MouseOver.Border}"/>
</Trigger>
On top of designer created style definition it also created the brushes that are used within the style:
<SolidColorBrush x:Key="Button.MouseOver.Background" Color="#FFBEE6FD"/>
<SolidColorBrush x:Key="Button.MouseOver.Border" Color="#FF3C7FB1"/>
You can either change these brushes or the Value property of the setters above to change the background when the mouse is over.
Or you create your own Template like you did in your old implementation.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/49560331",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to Add Zeros to Second Dimension of Array in Python? I have a latitude array with the shape (1111,) and am attempting to use matplotlib pcolormesh, but I'm getting an error since my array is not 2D so I am getting the error not enough values to unpack (expected 2, got 1). Is there a way I can add 1111 zeros to the second dimension of my latitude array? Below is the code I have that is causing the error.
import matplotlib.cm as cm
cmap = cm.get_cmap('BrBG')
cs = plt.pcolormesh(longitude.values, latitude.values, dens, cmap = cmap)
plt.title('Satellite Trajectory')
plt.xlabel('Longitude')
plt.ylabel('Latitude')
plt.savefig('Satellite Trajectory', dpi=200, bbox_inches='tight', pad_inches=0.025)
cb = plt.colorbar(cs, orientation = 'vertical')
cb.set_label(r'Density')
These are the first few lines of my Pandas latitude array:
0 50.224832
1 50.536422
2 50.847827
3 51.159044
4 51.470068
5 51.780895
6 52.091521
7 52.401941
8 52.712151
9 53.022145
10 53.331919
I have the same issue with the longitude array too. Here are some longitude values for reference.
0 108.873007
1 108.989510
2 109.107829
3 109.228010
4 109.350097
5 109.474136
6 109.600176
7 109.728265
8 109.858455
9 109.990798
10 110.125348
The other array shown is dens which is a density array and has the shape (5, 91, 181). Here are a few values for reference:
[6.042968853864891e-12, 6.042894605467602e-12, 6.042777396826408e-12, 6.042616263531836e-12, 6.042410211830538e-12, 6.042158216350682e-12, 6.0361190688090634e-12, 6.038107492458882e-12, 6.039984972063208e-12, 6.041748879958635e-12, 6.030375732644546e-12, 6.027898597657696e-12, 6.0251851962303345e-12, 6.0390021800772395e-12, 6.035096323493865e-12, 6.030879347062723e-12, 6.026343416350273e-12, 6.021480432118012e-12, 6.01628202402901e-12, 6.042274874237314e-12, 6.040409269411221e-1
I'm just stuck how to execute the pcolormesh without getting the following error:
ValueError Traceback (most recent call last)
<ipython-input-54-685815191229> in <module>
7
8
----> 9 cs = plt.pcolormesh(longitude.values, latitude.values, dens, cmap = cmap)
10
11 plt.title('Satellite Trajectory')
~\Anaconda3\lib\site-packages\matplotlib\pyplot.py in pcolormesh(alpha, norm, cmap, vmin, vmax, shading, antialiased, data, *args, **kwargs)
2771 *args, alpha=alpha, norm=norm, cmap=cmap, vmin=vmin,
2772 vmax=vmax, shading=shading, antialiased=antialiased,
-> 2773 **({"data": data} if data is not None else {}), **kwargs)
2774 sci(__ret)
2775 return __ret
~\Anaconda3\lib\site-packages\matplotlib\__init__.py in inner(ax, data, *args, **kwargs)
1808 "the Matplotlib list!)" % (label_namer, func.__name__),
1809 RuntimeWarning, stacklevel=2)
-> 1810 return func(ax, *args, **kwargs)
1811
1812 inner.__doc__ = _add_data_doc(inner.__doc__,
~\Anaconda3\lib\site-packages\matplotlib\axes\_axes.py in pcolormesh(self, alpha, norm, cmap, vmin, vmax, shading, antialiased, *args, **kwargs)
5980 allmatch = (shading == 'gouraud')
5981
-> 5982 X, Y, C = self._pcolorargs('pcolormesh', *args, allmatch=allmatch)
5983 Ny, Nx = X.shape
5984 X = X.ravel()
~\Anaconda3\lib\site-packages\matplotlib\axes\_axes.py in _pcolorargs(funcname, allmatch, *args)
5547 if isinstance(Y, np.ma.core.MaskedArray):
5548 Y = Y.data
-> 5549 numRows, numCols = C.shape
5550 else:
5551 raise TypeError(
ValueError: not enough values to unpack (expected 2, got 1)
I'm assuming it is because of the longitde and latitude array shape, so I'm asking for help filling the second dimension so I have an array (1111,1111) rather than (1111,).
If you have another recommendation I would love help. I am new to Python.
A: Use a for loop or a list comprehension in that case.
latitude = [50.224832, 50.536422, 50.847827, 51.159044, 51.470068]
longitude = [108.873007, 108.989510, 109.107829, 109.228010, 109.350097]
density = [.15,.25,.35,.45,.55]
output = [(latitude[i], longitude[i], density[i]) for i in range(len(latitude))]
print(output)
[(50.224832, 108.873007, 0.15), (50.536422, 108.98951, 0.25), (50.847827, 109.107829, 0.35), (51.159044, 109.22801, 0.45), (51.470068, 109.350097, 0.55)]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/63636553",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Best Practices for Organizing Android Code I have been coding an Android app that has a lot of code dedicated to it. As you can imagine, there's lots of case-driven code in there. Because most of Android callback functionality is based on integers and ItemIDs and requestCodes, there is a lot of functionality built into switch statements or if-then-else constructs.
What are the best practices for organizing/refactoring this code in a better way? What have you found that works to reduce the amount of code and clarifies it at the same time? Is a huge amount of small classes going to hurt Android performance?
Thanks in advance.
A: A large number of classes is not going to affect the performance of the application. Some good practices in Android, however, include placing values like integers, item IDs, and request codes into a Resources xml file.
You will also see a lot of Callback classes as inner interfaces of the Object they relate to:
public class MyObject
{
private Callback callback;
private Object returnObject;
public void setCallback(Callback callback)
{
this.callback = callback;
}
public void doSomething()
{
//do something - could be an anync task or other that assigns returnObject
callback.invoke(returnObject);
}
public interface Callback
{
public void invoke(Object obj);
}
}
Then you can use this as follows:
MyObject obj = new MyObject();
obj.setCallback(new MyObject.Callback() {
@Override
public void invoke(Object obj) {
Log.i("Callback", obj.toString());
}
});
obj.doSomething();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/16302739",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to use the user_passes_test decorator in class based views? I am trying to check certain conditions before the user is allowed to see a particular user settings page. I am trying to achieve this using the user_passes_test decorator. The function sits in a class based view as follows. I am using method decorator to decorate the get_initial function in the view.
class UserSettingsView(LoginRequiredMixin, FormView):
success_url = '.'
template_name = 'accts/usersettings.html'
def get_form_class(self):
if self.request.user.profile.is_student:
return form1
if self.request.user.profile.is_teacher:
return form2
if self.request.user.profile.is_parent:
return form3
@method_decorator(user_passes_test(test_settings, login_url='/accounts/usertype/'))
def get_initial(self):
if self.request.user.is_authenticated():
user_obj = get_user_model().objects.get(email=self.request.user.email)
if user_obj.profile.is_student:
return { ..........
...... ....
Below is the test_settings function:
def test_settings(user):
print "I am in test settings"
if not (user.profile.is_student or user.profile.is_parent or user.profile.is_teacher):
return False
else:
return True
I am getting the below error with the decorator.
File "../django/core/handlers/base.py", line 111, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "../django/views/generic/base.py", line 69, in view
return self.dispatch(request, *args, **kwargs)
File "../braces/views.py", line 107, in dispatch
request, *args, **kwargs)
File "../django/views/generic/base.py", line 87, in dispatch
return handler(request, *args, **kwargs)
File "../django/views/generic/edit.py", line 162, in get
form = self.get_form(form_class)
File "../django/views/generic/edit.py", line 45, in get_form
return form_class(**self.get_form_kwargs())
File "../django/views/generic/edit.py", line 52, in get_form_kwargs
'initial': self.get_initial(),
File "../django/utils/decorators.py", line 29, in _wrapper
return bound_func(*args, **kwargs)
TypeError: _wrapped_view() takes at least 1 argument (0 given)
I am not sure how to resolve this error. Am I applying the decorator on the wrong function? Any leads will be helpful.
A: Django 1.9 has authentication mixins for class based views. You can use the UserPassesTest mixin as follows.
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
class UserSettingsView(LoginRequiredMixin, UserPassesTestMixin, View):
def test_func(self):
return test_settings(self.request.user)
def get_login_url(self):
if not self.request.user.is_authenticated():
return super(UserSettingsView, self).get_login_url()
else:
return '/accounts/usertype/'
Note that in this case you have to override get_login_url, because you want to redirect to a different url depending on whether the user is not logged in, or is logged in but fails the test.
For Django 1.8 and earlier, you should decorate the dispatch method, not get_initial.
@method_decorator(user_passes_test(test_settings, login_url='/accounts/usertype/'))
def dispatch(self, *args, **kwargs):
return super(UserSettingsView, self).dispatch(*args, **kwargs)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/29682704",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
} |
Q: Appstore navigation bar functionality I wanted to implement a feature that is present in the Appstore app in iOS 11. As is visible from the gif, when the detail screen loads, the navigation bar is fully transparent and becomes visible when the view scrolls to the top.
I was under the impression that the navigation bar cannot be completely transparent.
Any insights so as to how Apple has implemented this feature would be helpful/
A: Check out Customizing the Navigation Bar section of this page.
Change the navigation background image and hide navigation bar on push
Also set prefersLargeTitles of bar as true only in iOS 11
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46817285",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Create Temporary Table Populated with Dates and LEFT JOIN to `created_at` Column - MySQL Original Query:
// Doesn't return dates with zero value
SELECT UNIX_TIMESTAMP( created_at ) AS DATE, COUNT( tweet_id ) AS count
FROM `tweets`
WHERE DATE( created_at ) > '2012-11-01'
AND DATE( created_at ) <= DATE( NOW( ) )
GROUP BY DATE
Modified Query:
// Attempting to return all dates with a value of zero if doesn't exist in `created_at` column
CREATE TEMPORARY TABLE DateSummary1 ( date timestamp ) SELECT DISTINCT(DATE(created_at)) as date FROM tweets;
CREATE TEMPORARY TABLE DateSummary2 ( date timestamp, number int ) SELECT DATE(created_at) as date, count(*) AS number FROM tweets WHERE DATE(created_at) > '2012-11-01' AND DATE(created_at) <= DATE(NOW()) GROUP BY DATE(created_at) ORDER BY created_at ASC;
SELECT ds1.date,ds2.number FROM DateSummary1 ds1 LEFT JOIN DateSummary2 ds2 on ds1.date=ds2.date;
Unfortunately, the latter result isn't providing me the dates with zero values like I had expected. What am I overlooking? I'm sure this is a logic error, but I'm not sure where my logic has faulted. I've gotten this far from reading copious threads on SO, Google, etc. but am not sure how to get over this final hurdle.
An example of the returned timestamps using jcho360's suggestion:
1387286811
1387286812
1387286813
1387286815
1387286820
A: Try this
SELECT UNIX_TIMESTAMP( created_at ) AS DATE, COUNT( tweet_id ) AS count
FROM `tweets`
WHERE (DATE( created_at ) > '2012-11-01'
AND DATE( created_at ) <= DATE( NOW( ) ) )
or DATE( created_at ) = date ('000-00-00') //I added this Line
GROUP BY DATE
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21293742",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to access other project forms in solution explorer for VS2008 C#? Image http://img43.imageshack.us/img43/1720/28264117.png
Here is the image for my solution Explorer. What i want is to use HR Management forms to b loaded through button click on a form of Classic Steel HR. So can anyone tell me how
A: I can't see your image here, unfortunately - but if I get what you're trying to ask; you can access forms from another assembly if they're public.
Then just check this setting is true:
Tools > Options > Windows Forms Designer > General : AutoToolboxPopulate
Alternatively:
Alternatively, you need to make sure that the HR project is referenced by the Classic_steel_hr project then in your forms code (assuming it's namespace is HR)
using HR;
private void ShowForm()
{
HR.Form1 hrForm = new HR.Form1();
hrForm.Show();
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/2871849",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Google Maps: Shade city I searched a lot, but I could not find how to shade city area on google maps. This can be done using Google Charts but it is not interactive. I want it to be exactly like google maps but with borders.
E.g Search Dallas on Google Maps and see it draws boundries. I want exactly like this to show on my website. I want to show multiple city borders in same map.
A: Google maps API doesn't provide this feature. So, if you want to highlight regions you have to create custom overlays based on the lat/long of the borders of the state.
Once you have the lat/long of the borders you have to draw polygons yourself.
For example:
// Define the LatLng coordinates for the polygon's path.
var washingtonShapeCoords = [new google.maps.LatLng(38.8921, -76.9112),
new google.maps.LatLng(38.7991, -77.0320),
new google.maps.LatLng(38.9402, -77.1144),
new google.maps.LatLng(38.9968, -77.0430),
new google.maps.LatLng(38.8996, -76.9167),
new google.maps.LatLng(33.7243, -74.8843),
new google.maps.LatLng(33.7243, -72.6870),
new google.maps.LatLng(32.3243, -72.6870),
new google.maps.LatLng(32.3985, -76.7300),
new google.maps.LatLng(33.7152, -76.6957),
new google.maps.LatLng(33.7243, -74.9489),
new google.maps.LatLng(38.8921, -76.9112)];
// Construct the polygon.
washingtonPolygon = new google.maps.Polygon({
paths: washingtonShapeCoords,
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35
});
washingtonPolygon.setMap(map);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31804345",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Run an SQL script only if a selection over a table before it gives a result. If it doesn't give a result the SQL script should not run I would like an SQL script to run only if a SQL command selection over a table give a result.
If it doesn't give a result the SQL script should not run.
Will this be possible to do?
A: I might help:
IF ( select count(1) from ( _your selection_ ) a ) > 0 THEN
_RUN your script_;
END IF
A: this is one way:
DECLARE
type t1
IS
TABLE OF hr.employees.first_name%type;
t11 t1;
BEGIN
SELECT e.first_name bulk collect
INTO t11
FROM hr.employees e
WHERE E.EMPLOYEE_ID=999;
IF(t11.count! =0) THEN
FOR i IN 1..t11.count/*here you can write your own query */
LOOP
dbms_output.put_line(t11(i));
END LOOP;
ELSE
dbms_output.put_line('oh..ho..no rows selected' );
END IF;
END;
/
any clarification plz let me know..
| {
"language": "en",
"url": "https://stackoverflow.com/questions/15219173",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: I was given an OOP project using SDL. I haven't used inheritance. What reason can i give to my evaluators I took a course OOP. We were supposed to create a game in a group of 3. I worked on the menu part. Unfortunately, i didnt use inheritance and other OOP concepts. I DID use classes. What is the possible reason that i can give to me evaluators without having my marks deducted? My viva is tomorrow. (after 13 hours)
Thanks.
A: It is a bit difficult to guess what you can say without knowing anything about your design (i.e. how the classes cooperate between each other), and there are a lot of "OOP concepts out there".
The only thing I can suggest you, assuming that you didn't declare every function of the other classes static, is to say that you did not use inheritance because composition is often (but not always) better. You have a composition if one member of you class is a class itself:
class Player
{
private:
Weapon gun;
public:
Player(Weapon& pistol);
void shoot(){gun.bang();}
};
Gun is a composition: Player uses a Gun to shoot() and it is a perfectly legit use of a composition here. This is a case when you DON'T want to use a composition:
class MedievalFolk
{
private:
Knight arthur;
public:
Player(Knight& pistol);
void duel(){arthur.duel();}
};
If you did something like this be prepared to be turned down, because there is no difference between a Knight and a MedievalFolk and you will need a better reason than "composition is better" here since this argument won't hold. Also, if you declared everything static then the only thing I can advise you is to rework your code not to do so. You would have just a glorification of old-fashioned procedural code (regardless of using classes) where everything is a function which calls other functions and, if I would be teaching a course on OOP, I would fail this coursework
I don't know what you are studying OOP for, but if you plan to get into software development I would strongly advise you to defer the examination and do your coursework properly, you won't be able to fix it all in a few hours not even professional can ressurect bad code in few days of work. Also there isn't a single employer that wish to hire a developer which is not proficient in OOP those days, unless you plan to work on ancient stuff of the 70s (and probably it still won't be sufficient). There is nothing wrong with taking a bit longer time if this makes you better
| {
"language": "en",
"url": "https://stackoverflow.com/questions/47699067",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
} |
Q: Pygame in python My game was working before I added lines 7 and 8.
what happened in the game was the red sprites that fall down the screen would hit the main character sprite which is green and the game would stop just as I need it to.
import pygame
import random
from os import path
img_dir = path.join(path.dirname(__file__),'PNG')
background = pygame.image.load(path.join(img_dir,'Space-Background.png')).convert()
background_rect = background.get_rect()
WIDTH = 480
HEIGHT = 600
FPS = 60
WHITE = (255,255,255)
BLACK = (0,0,0)
RED = (255,0,0)
GREEN = (0,255,0)
BLUE = (0,0,255)
pygame.init()
pygame.mixer.init()
screen = pygame.display.set_mode((WIDTH,HEIGHT))
pygame.display.set_caption("My Game")
clock = pygame.time.Clock()
class Player(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((50,40))
self.image.fill(GREEN)
self.rect = self.image.get_rect()
self.rect.centerx = WIDTH/2
self.rect.bottom = HEIGHT-10
self.speedx = 0
def update(self):
self.speedx = 0
keystate = pygame.key.get_pressed()
if keystate[pygame.K_LEFT]:
self.speedx = -5
if keystate[pygame.K_RIGHT]:
self.speedx = 5
self.rect.x += self.speedx
if self.rect.right > WIDTH:
self.rect.right = WIDTH
if self.rect.left < 0:
self.rect.left = 0
def shoot(self):
bullet = Bullet(self.rect.centrex,self.rect.top)
all_sprites.add(bullet)
bullets.add(bullet)
class Mob(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((30,40))
self.image.fill(RED)
self.rect = self.image.get_rect()
self.rect.x = random.randrange(0, WIDTH - self.rect.width)
self.rect.y = random.randrange(-100,-40)
self.speedy = random.randrange(1,8)
def update(self):
self.rect.y += self.speedy
if self.rect.top > HEIGHT +10:
self.rect.x = random.randrange(0, WIDTH - self.rect.width)
self.rect.y = random.randrange(-100,-40)
self.speedy = random.randrange(1,8)
class Bullet(pygame.sprite.Sprite):
def __init__(self,x,y):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((10,20))
self.image.fill(YELLOW)
self.rect = self.image.get_rect()
self.rect.bottom = y
self.rect.centrex = x
self.speedy = -10
def update(self):
self.rect.y += self.speedy
if self.rect.bottom < 0:
self.kill()
# player_img = pygame.image.load(path.join(img_dir,"spaceShips_003.png")).convert()
# bullet_img = pygame.image.load(path.join(img_dir,"spaceMissile_006.png")).convert()
# mob_img = pygame.image.load(path.join(img_dir,"SpaceMeteor_004.png")).convert()
all_sprites = pygame.sprite.Group()
mobs = pygame.sprite.Group()
bullets = pygame.sprite.Group()
player = Player()
for i in range(8):
m = Mob()
all_sprites.add(m)
mobs.add(m)
all_sprites.add(player)
running = True
while running:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
player.shoot()
all_sprites.update()
hits = pygame.sprite.groupcollide(mobs,bullets,True,True)
for hit in hits:
m = Mob()
all_sprites.add(m)
hits = pygame.sprite.spritecollide(player,mobs,False)
if hits:
running = False
screen.fill(BLACK)
# screen.split(background.background_rect)
all_sprites.draw(screen)
pygame.display.flip()
pygame.quit()
After I added the two lines for the images there was an error message. I am not sure what happened and I need some help fixing it.
>>> %Run trial.py
pygame 2.1.2 (SDL 2.0.18, Python 3.7.9)
Hello from the pygame community. https://www.pygame.org/contribute.html
Traceback (most recent call last):
File "C:\Users\Mish Mash\Documents\School File\trial.py", line 7, in <module>
background = pygame.image.load(path.join(img_dir,'Space-Background.png')).convert()
pygame.error: cannot convert without pygame.display initialized
A: The meaning of the following error: pygame.error: cannot convert without pygame.display initialized is that you are trying to use a method of pygame.display (the convert method) without initializing pygame first. To fix this, simply move pygame.init() to below the import statements.
Code
import pygame
import random
from os import path
pygame.init()
pygame.mixer.init()
img_dir = path.join(path.dirname(__file__), 'PNG')
background = pygame.image.load(path.join(img_dir, 'Space-Background.png')).convert()
background_rect = background.get_rect()
WIDTH = 480
HEIGHT = 600
FPS = 60
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("My Game")
clock = pygame.time.Clock()
class Player(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((50, 40))
self.image.fill(GREEN)
self.rect = self.image.get_rect()
self.rect.centerx = WIDTH / 2
self.rect.bottom = HEIGHT - 10
self.speedx = 0
def update(self):
self.speedx = 0
keystate = pygame.key.get_pressed()
if keystate[pygame.K_LEFT]:
self.speedx = -5
if keystate[pygame.K_RIGHT]:
self.speedx = 5
self.rect.x += self.speedx
if self.rect.right > WIDTH:
self.rect.right = WIDTH
if self.rect.left < 0:
self.rect.left = 0
def shoot(self):
bullet = Bullet(self.rect.centrex, self.rect.top)
all_sprites.add(bullet)
bullets.add(bullet)
class Mob(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((30, 40))
self.image.fill(RED)
self.rect = self.image.get_rect()
self.rect.x = random.randrange(0, WIDTH - self.rect.width)
self.rect.y = random.randrange(-100, -40)
self.speedy = random.randrange(1, 8)
def update(self):
self.rect.y += self.speedy
if self.rect.top > HEIGHT + 10:
self.rect.x = random.randrange(0, WIDTH - self.rect.width)
self.rect.y = random.randrange(-100, -40)
self.speedy = random.randrange(1, 8)
class Bullet(pygame.sprite.Sprite):
def __init__(self, x, y):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((10, 20))
self.image.fill(YELLOW)
self.rect = self.image.get_rect()
self.rect.bottom = y
self.rect.centrex = x
self.speedy = -10
def update(self):
self.rect.y += self.speedy
if self.rect.bottom < 0:
self.kill()
# player_img = pygame.image.load(path.join(img_dir,"spaceShips_003.png")).convert()
# bullet_img = pygame.image.load(path.join(img_dir,"spaceMissile_006.png")).convert()
# mob_img = pygame.image.load(path.join(img_dir,"SpaceMeteor_004.png")).convert()
all_sprites = pygame.sprite.Group()
mobs = pygame.sprite.Group()
bullets = pygame.sprite.Group()
player = Player()
for i in range(8):
m = Mob()
all_sprites.add(m)
mobs.add(m)
all_sprites.add(player)
running = True
while running:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
player.shoot()
all_sprites.update()
hits = pygame.sprite.groupcollide(mobs, bullets, True, True)
for hit in hits:
m = Mob()
all_sprites.add(m)
hits = pygame.sprite.spritecollide(player, mobs, False)
if hits:
running = False
screen.fill(BLACK)
# screen.split(background.background_rect)
all_sprites.draw(screen)
pygame.display.flip()
pygame.quit()
| {
"language": "en",
"url": "https://stackoverflow.com/questions/70832093",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
} |
Q: Symfony2 + Doctrine2 SQL Integrity Violation: Nullable field can't be null? So this project is moving some straight PDO SQL queries (with MySQL) to Doctrine. The tables already existed and had data in them. I set up the entities, and everything seemed golden. All the queries were rewritten with the Entity Manager in Doctrine, and everything seemed to work.
Except I forgot that three fields in one of the entities needed to be nullable. They were set to NOT NULL in the database and there was no nullable=true declaration in the Doctrine annotations.
I manually altered to table in MySQL to make the fields nullable, then added a nullable=true to the entities, cleared the cache and executed a
php app/console doctrine:schema:update --force
Just to be sure (which executed correctly).
However, despite the fact that the Doctrine entity allows null fields, and the database has the columns nullable as well, I still get this error:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'type_id' cannot be null
Is there any way for me to fix this without dropping the tables (which would involve also saving all the data)? What exactly is wrong here? According to all the code and databases involved, there should be no integrity violations at all (the field isn't a foreign key either).
Here is the entity in question:
class Audio
{
/**
* @ORM\Id
* @ORM\Column(type="integer", name="id")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @ORM\Column(type="string", name="type", columnDefinition="ENUM('song','demo')")
*/
protected $type;
/**
* @ORM\Column(type="integer", name="type_id", nullable=true)
*/
protected $typeId = null;
/**
* @ORM\Column(type="string", name="s3_url", nullable=true)
*/
protected $s3url = null;
/**
* @ORM\Column(type="string", name="s3_key", nullable=true)
*/
protected $s3key = null;
/**
* @ORM\Column(type="datetime", name="date_created")
*/
protected $dateCreated;
/**
* @ORM\Column(type="datetime", name="date_modified")
*/
protected $dateModified;
This is absolutely mystifying me. There's really no more ways for me to tell the program that it can be null.
A: Hi i don't know if you still have the problem.
You can do php app/console doctrine:schema:update --dump-sql
In order to know the difference bewteen your model and the database.
And apply the line he will tell you.
I think it will fix the problem
| {
"language": "en",
"url": "https://stackoverflow.com/questions/18966968",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: bitmap size exceed VM budget in second level I'm developing a game in which I am trying to move from 1st stage to 2nd stage.
When I start the 2nd stage directly it runs perfectly, but when I play the 1st stage and unlock the 2nd stage, and then start the second stage then it shows an error:
02-25 14:07:09.923: ERROR/AndroidRuntime(409): FATAL EXCEPTION: GLThread 12
02-25 14:07:09.923: ERROR/AndroidRuntime(409): java.lang.OutOfMemoryError: bitmap size exceeds VM budget
02-25 14:07:09.923: ERROR/AndroidRuntime(409): at android.graphics.Bitmap.nativeCreate(Native Method)
02-25 14:07:09.923: ERROR/AndroidRuntime(409): at android.graphics.Bitmap.createBitmap(Bitmap.java:477)
02-25 14:07:09.923: ERROR/AndroidRuntime(409): at android.graphics.Bitmap.createBitmap(Bitmap.java:444)
02-25 14:07:09.923: ERROR/AndroidRuntime(409): at com.threed.jpct.util.BitmapHelper.rescale(BitmapHelper.java:72)
02-25 14:07:09.923: ERROR/AndroidRuntime(409): at bones.samples.android.LevelTwo$MyRenderer.onSurfaceChanged(LevelTwo.java:555)
02-25 14:07:09.923: ERROR/AndroidRuntime(409): at android.opengl.GLSurfaceView$GLThread.guardedRun(GLSurfaceView.java:1356)
02-25 14:07:09.923: ERROR/AndroidRuntime(409): at android.opengl.GLSurfaceView$GLThread.run(GLSurfaceView.java:1118)
I can't understand this situation because when I only run a single stage then they run correctly but when run 2nd after first it can't.
Texture texture = new Texture(BitmapHelper.rescale(BitmapHelper.convert(getResources().getDrawable(R.drawable.bgtwo)), 512, 1024));
TextureManager.getInstance().addTexture("texture", texture);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/22008832",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What informations leaks during send mail programatically from google account Imagine if you are sending an email by the gmail.com using web online interface so entering the website of google, then compose mail and send it. In this case your ip address is not revealed to the receiver of mail. In details of mail header there are google server's informations.
If it is good or not it is a topic for a big discussion, have some advantages and disadvantages... However only one way to get someone's ip address so location is court way and lawyer sending a document to google with a question to reveal ip address of sender of the particular mail. Am I right ?
What is my wondering right now is if I have same privacy (assuming I claim true above) in case of using a program and perform a function like this:
public static void SendAnEmail(MailAccount mailAccount, Mail mail)
{
SmtpClient client = new SmtpClient();
client.Port = 587;
client.Host = mailAccount.host;
client.EnableSsl = true;
client.Timeout = 10000;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Credentials = new System.Net.NetworkCredential(mailAccount.username, mailAccount.password);
MailMessage mailMessage = new MailMessage(mailAccount.username, mail.mailTo, mail.subject, mail.body);
mailMessage.BodyEncoding = UTF8Encoding.UTF8;
mailMessage.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
client.Send(mailMessage);
}
where Mail contain subject, body and mailTo strings and MailAccount have username, password and host, so all required informations to send an email. The whole code is written in C# by the way.
Imagine that I have a program which is doing some office work and at the end of some activities is going to send an email using code above of course using a google host (an account created at google website). Then - what is happening ? What is in mail details header ? My computer ip address or google server ones ? Do this mail contain some more information like mac address of network card or my motherboard.
I hope you understand my question, if it is not clear, please ask questions about my situation. Any suggestion how to obtain such a privacy using "mailing by code" would be appreciated. However explanation of the situation it is what I am looking for.
Thank you in advance and have a nice day.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34750408",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to Display User Input of a HTML Form I've written the code below (part of my code) and I can't figure out why it won't show the user input in the form of table on the web page.
<form>
<label for="img_tag"> What is the above picture? </label><br>
<input type="text" name="What is the above picture?" id="input">
<input type="button" id="submit-button" value="Submit" onclick="insert_result()">
</form>
</div>
</div>
<div id="result_table">
<table>
<tr>
<th> Image </th>
<th> Tag </th>
</tr>
<tr id="results">
</tr>
</table>
</div>
<script type="text/javascript">
var input = document.getElementByID("input").value;
var result_row = document.getElementByID("results");
var new_row = document.createElement("td");
function insert_result() {
result_row.appendChild(new_row);
new_row.append(input);
}
</script>
A: *
*Spelling getElementById
*Move getting the input value inside the function that needs it
*you need a new cell each time, otherwise you just move the cell
you might want a new row too for each input
const inputField = document.getElementById("input");
const result_row = document.getElementById("results");
function insert_result() {
let input = inputField.value;
let new_row = document.createElement("td");
new_row.append(input);
result_row.appendChild(new_row);
}
<form>
<label for="img_tag"> What is the above picture? </label><br>
<input type="text" name="What is the above picture?" id="input">
<input type="button" id="submit-button" value="Submit" onclick="insert_result()">
</form>
<div id="result_table">
<table>
<tr>
<th> Image </th>
<th> Tag </th>
</tr>
<tr id="results">
</tr>
</table>
</div>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/73926531",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: using mysql to get a list of inserted records Inserting multiple records to a table in MYSQL returns me last inserted ID.
Is there a way I can get the list of all inserted records ?
One way would be to insert each record and then fetch that record using last inserted ID. But obviously that will raise performance issues.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/63390305",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is learning rate automatically decreased between passes when vw LDA is run with `--save_resume` vowpal wabbit (vw) supports out-of-core learning with --save_resume. This is what the --help options tells the end user about the --save_resume option:
--save_resume save extra state so learning can be
resumed later with new data
I have a large living data set, currently hundreds of millions documents sorted into 1024 batches, and my goal is train a LDA-model on all batches, and for that purpose I run a script that invokes vw like this (Nota bene I do not set --passes, so each data point is only seen once).
Initial invokation:
vw -d clean.txt --lda 100 --lda_D 307000000 -f weights --readable_model lda.model.vw
Subsequent invocations (the content of clean.txt is changed between invocations):
vw -d clean.txt --lda 100 --lda_D 307000000 --save_resume -i weights -f weights --readable_model lda.model.vw
I have successfully run all batches through vw this way, but from the output given by vw in each invocation, it seems the learning rate never drops, it always looks like this:
learning rate = 0.5
initial_t = 0
power_t = 0.5
I would have guessed that the learning rate is saved when --save_resume is requested, and that vw automatically decreases the learning rate as it sees more data, but this does not seem to be the case, right?
Do you have to manage the learning rate manually with vowpal wabbit?
A: It appears that LDA has a learn rate thats computed based on (but stored separately from) the global learning rate. LDA's learning/decay rates don't appear to be printed anywhere, so you wouldn't see them in the logs.
https://github.com/VowpalWabbit/vowpal_wabbit/blob/master/vowpalwabbit/lda_core.cc#L892
| {
"language": "en",
"url": "https://stackoverflow.com/questions/65542064",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Issue rendering dark mode - ReactJS I'm new and trying a project to make a switch that toggles between two themes;
Here is what I have so far and I'm struggling to understand why it's not toggling between my themes.
theme.js
import { createContext } from "react";
export const themes = {
dark: "dark-mode",
light: "white-mode",
};
export const ThemeContext = createContext({
theme: themes.dark,
changeTheme: () => {},
});
themeWrapper.js
import React, { useState, useEffect } from 'react';
import { ThemeContext, themes } from './theme.js';
import "./App.css"
export default function ThemeContextWrapper(props) {
const [theme, setTheme] = useState(themes.dark);
function changeTheme(theme) {
setTheme(theme);
}
useEffect(() => {
switch (theme) {
case themes.light:
document.body.classList.add('white-mode');
break;
case themes.dark:
default:
document.body.classList.remove('white-mode');
break;
}
}, [theme]);
return (
<ThemeContext.Provider value={{ theme: theme, changeTheme: changeTheme }}>
{props.children}
</ThemeContext.Provider>
);
}
So I've got a wrapper to re-render the app when dark mode is toggled, and two themes that are being exported.
App.css
.white-mode {
font: #333;
background: #eee;
link: cornflowerblue;
}
.dark-mode {
font: #eee;
background: rgb(41, 41, 41);
link: lightblue;
}
Index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import ThemeContextWrapper from '.themeWrapper';
ReactDOM.render(
<ThemeContextWrapper>
<React.StrictMode>
<App />
</React.StrictMode>{' '}
</ThemeContextWrapper>,
document.getElementById('root'),
);
So now in App.js I have the button
import './App.css';
import { Button, Container, InputGroup } from 'reactstrap';
import { ThemeContext, themes } from '.theme';
import React from 'react';
function App() {
const [darkMode, setDarkMode] = React.useState(true);
return (
<div className="App">
<header className="App-header">
<h1 className="text-warning">Dark/Light mode</h1>
<InputGroup>
<ThemeContext.Consumer>
{({ changeTheme }) => (
<Button
color="link"
onClick={() => {
setDarkMode(!darkMode);
changeTheme(darkMode ? themes.light : themes.dark);
}}
>
<span className="d-lg-none d-md-block">Toggle</span>
</Button>
)}
</ThemeContext.Consumer>
</InputGroup> */}
</header>
</div>
);
}
export default App;
But this button doesn't appear to do anything, where have I gone wrong?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/71563042",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: TX-row lock contention : Inserting Duplicate values for Unique Key We are getting a TX-row lock contention error while trying to insert data
It happens while running a job which processes an xml with almost 10000 records, inserting the data into a table
We are having a unique key constraint on one of the columns in the table, and in the request we are getting duplicate values. This is causing the locks and thereby the job is taking more time.
We are using hibernate and spring. The DAO method we use is hibernate template's 'save' annotated with Spring Transaction Manager's @Transactional
Any suggestions please?
A: It's not clear whether you're getting locking problems or errors.
"TX-row lock contention" is an event indicating that two sessions are trying to insert the same value into a primary or unique constraint column set -- an error is not raised until the first one commits, then the second one gets the error. So you definitely have multiple sessions inserting rows. If you just had one session then you'd receive the error immediately, with no "TX-row lock contention" event being raised.
Suggestions:
*
*Insert into a temporary table without the constraint, then load to the real table using logic that eliminates the duplicates
*Eliminate the duplicates as part of the read of the XML.
*Use Oracle's error logging syntax -- example here. http://docs.oracle.com/cd/B28359_01/server.111/b28286/statements_9014.htm#SQLRF55004
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21290438",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: eclipse shortcut publish everywhere I would like to change the publish shortcut behaviour to apply to every window i work.
This would remove the need to be in the server view to use this shortcut (CTRL+ALT+P)
So far I followed this post: eclipse key bindings everywhere
Setting "when" to "in windows" did not work. I guess because the shortcut is still part of the category "server"
How can I change the category? Is there another way to fix this?
A: This is not going to work. The command handler for the Publish action (org.eclipse.wst.server.ui.internal.view.servers.ServerActionHandler) expects the current selection to be a server and doesn't do anything if it is not. So you have to be in the server view for it to work.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/23359920",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Rails model design: propose and counter-propose a time I have a model that allows user A to propose a time for an appointment to user B. If B accepts, then event is set. But if B proposes another time, then A must accept or propose another time, and so on. Until one user accept the other's counter-proposal, the appointment won't be set.
How should I model this kind of back and forth proposals and to keep track of current stage in Rails?
Thank you.
A: What you're describing is a state machine.
Older SO question discussing the various gems and plugins of the time, plus some basics.
Newer blog post discussing the hows and whys.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7830382",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to serialize canonical/normalized JSON in PHP The order of keys in JSON is not relevant, so PHP's json_encode uses the internal order of keys when serializing JSON format. I'd like to make sure that equivalent JSON is always serialized the same form. For instance $a and $b in the following example
$a = ["foo" => 1, "bar" => 2, "doz" => 3];
$b = ["doz" => 3, "bar" => 2, "foo" => 1];
print json_encode($a)."\n";
print json_encode($b)."\n";
result in different serializations
{"foo":1,"bar":2,"doz":3}
{"doz":3,"bar":2,"foo":1}
but they are equivalent.
A: You need to sort the array in some way, I recommend sorting by key (foo, bar, doz).
http://php.net/manual/en/function.ksort.php
The order will always be the same when using the same keys.
I haven't tested this, but it should work for your code.
$a = ["foo" => 1, "bar" => 2, "doz" => 3];
$b = ["doz" => 3, "bar" => 2, "foo" => 1];
ksort($a);
ksort($b);
print json_encode($a)."\n";
print json_encode($b)."\n";
This will print:
{"bar":2,"doz":3,"foo":1}
{"bar":2,"doz":3,"foo":1}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/35435937",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What directives and other features are available for inputs with a ControlValueAccessor? I have a custom component. It has a ControlValueAccessor injected into it as a provider. This is the generic standard way to make custom components represent form inputs.
For a more precise example the component actually implements ControlValueAccessor and injects itself into itself. This detail should not be important.
I know that this makes the following things available for this component out of the box:
*
*ngModel directive for two-way data binding
*several css-classes managed by Angular: ng-dirty/ng-pristine, ng-valid and ng-touched
Is there any other directives available out of the box besides ngModel? I would expect at least something like blur and change events to work.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46491237",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: I don't know why this is happened and i don't know how to ask this question I'm using termux app, then i try to install npm packages in the different directory in my phone.
The first one "/storage/shared/coding"
.../0/Coding $ npm i node-session
npm WARN deprecated [email protected]: Package no longer supported. Contact [email protected] for more info.
npm WARN deprecated @mapbox/[email protected]: Please make plans to check GeoJSON in some other way
npm ERR! code EPERM
npm ERR! syscall symlink
npm ERR! path ../@mapbox/geojsonhint/bin/geojsonhint
npm ERR! dest /storage/emulated/0/Coding/node_modules/.bin/geojsonhint
npm ERR! errno -1
npm ERR! Error: EPERM: operation not permitted, symlink '../@mapbox/geojsonhint/bin/geojsonhint' -> '/storage/emulated/0/Coding/node_modules/.bin/geojsonhint'
npm ERR! [Error: EPERM: operation not permitted, symlink '../@mapbox/geojsonhint/bin/geojsonhint' -> '/storage/emulated/0/Coding/node_modules/.bin/geojsonhint'] {
npm ERR! errno: -1,
npm ERR! code: 'EPERM',
npm ERR! syscall: 'symlink',
npm ERR! path: '../@mapbox/geojsonhint/bin/geojsonhint',
npm ERR! dest: '/storage/emulated/0/Coding/node_modules/.bin/geojsonhint'
npm ERR! }
npm ERR!
npm ERR! The operation was rejected by your operating system.
npm ERR! It is likely you do not have the permissions to access this file as the current user
npm ERR!
npm ERR! If you believe this might be a permissions issue, please double-check the
npm ERR! permissions of the file and its containing directories, or try running
npm ERR! the command again as root/Administrator.
npm ERR! A complete log of this run can be found in:
npm ERR! /data/data/com.termux/files/home/.npm/_logs/2022-04-25T19_14_38_772Z-debug-0.log
.../0/Coding $ pwd
/storage/emulated/0/Coding
And the second one "/noda"
~/noda $ npm i node-session
npm WARN deprecated [email protected]: Package no longer supported. Contact [email protected] for more info.
npm WARN deprecated @mapbox/[email protected]: Please make plans to check GeoJSON in some other way
added 151 packages, and audited 152 packages in 7s
43 packages are looking for funding
run `npm fund` for details
17 vulnerabilities (1 moderate, 12 high, 4 critical)
To address issues that do not require attention, run:
npm audit fix
Some issues need review, and may require choosing
a different dependency.
Run `npm audit` for details.
~/noda $ pwd
/data/data/com.termux/files/home/noda
Why does node-session can be installed in /noda directory but not in /storage/shared/coding and how can i install it in /storage/shared/coding
A: NodeJs you installed on Termux doesn't have permission to install dependencies on /storage/emulated/0/Coding/node_modules/.bin/geojsonhint.
You can solve it by:
*
*Changing the directory of the project to somewhere with public permissession.
*Running the command with the administration privilege but on Termux, I think.
*Using nvm to install node js instead of default ways.
This problem comes when you try to install node js with Termux. try not to.
NVM repository link: nvm-sh/nvm.
pay attention:
*
*You need to check your dependency tree is compatible with the node version you want to install.
*If the project is big be careful because you can break your project easily.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/72004841",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Numbers from textboxes are add next to each other instead of adding them together I have 3 textboxes in which I write numbers and last one in which is the result. If I write numbers in TextBoxA and TextBoxB instead of adding them together after I press equal button then it put them next to each other.
[]
I tried this code:
private void EqualsButton_Click(object sender, EventArgs e)
{
OutputTextBox.Text = ($"{InputTextBoxA.Text + InputTextBoxB.Text}");
}
A:
First you must convert text on textbox to int or any number type
Simple way :
private void EqualsButton2_Click(object sender, EventArgs e)
{
int numberA = int.Parse(textBox1.Text.Trim());
int numberB = int.Parse(textBox2.Text.Trim());
var result = numberA + numberB;
textBox3.Text = result.ToString();
}
Safe way :
private void EqualsButton_Click(object sender, EventArgs e)
{
if (!int.TryParse(textBox1.Text.Trim(), out int numberA))
numberA = 0;
if (!int.TryParse(textBox2.Text.Trim(), out int numberB))
numberB = 0;
var result = numberA + numberB;
textBox3.Text = result.ToString();
}
A: private void EqualsButton_Click(object sender, EventArgs e)
{
var resultA=0;
var resultB=0;
if(!string.IsNullOrEmpty(InputTextBoxA.Text))
resultA=Convert.ToInt32(InputTextBoxA.Text);
if(!string.IsNullOrEmpty(InputTextBoxB.Text))
resultB=Convert.ToInt32(InputTextBoxB.Text);
OutputTextBox.Text = resultA+ resultB ;
}
A: Don't listen to anyone. Do this
txtResult.Text = string.Empty;
if (!decimal.TryParse(txt1.Text.Trim(), out decimal v1))
{
MessageBox.Show("Bad value in txt1");
return;
}
if (!decimal.TryParse(txt2.Text.Trim(), out decimal v2))
{
MessageBox.Show("Bad value in txt2");
return;
}
txtResult.Text = (v1 + v2).ToString();
A: You can change into this
private void EqualsButton_Click(object sender, EventArgs e)
{
try
{
OutputTextBox.Text = ($"{ Convert.ToInt32(InputTextBoxA.Text.Trim() == "" ? "0" : InputTextBoxA.Text) + Convert.ToInt32(InputTextBoxB.Text.Trim() == "" ? "0" : InputTextBoxB.Text)}");
}
catch(exception ex)
{
MessageBox.Show("Enter Valid number")'
}
}
A: You need to convert text fields to int and after for the answer back to the text.
If you did not enter a value, then there "" is considered as 0 when adding.
private void EqualsButton_Click(object sender, EventArgs e)
{
OutputTextBox.Text = Convert.ToString(
Convert.ToInt32(InputTextBoxA.Text == "" ? "0" : InputTextBoxA.Text)
+ Convert.ToInt32(InputTextBoxB.Text == "" ? "0" : InputTextBoxB.Text));
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74411052",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Subsets and Splits