text
stringlengths 15
59.8k
| meta
dict |
|---|---|
Q: Facebook public profile without graph api I am making a testimonial for a website and i want a user to login through facbook so that i can save his profile picture and name etc in my database
Is there any code of facebook that we can get picture and public information of the user without graph api and facebook app?
Cz now facebook need https to make a app.
A:
Is there any code of facebook that we can get picture and public information of the user without graph api and facebook app?
No.
The Graph API is the basis of any automated communication with Facebook’s systems, and an app id is the basis of using the API.
Cz now facebook need https to make a app.
Rightfully so. You should not compromise your users’ security and privacy by not using HTTPS any more these days, especially if any kind of “login” is involved.
Getting a certificate doesn’t have to cost you much any more - Let’s Encrypt is widely available.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/52056237",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: How to get JSON data from php webservice : "no value for data" error I am new to the Android Platform and I want to fetch value's from a PHP Web Service through JSON Parser. But I am not getting the data, rather the error: No value for data25 ,data26 and data27.
I appreciate any help sorting out this problem.
try{
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++)
{
HashMap<String, String> map = new HashMap<String, String>();
JSONObject json_data = jArray.getJSONObject(i);
map.put("data25", "date25:" + json_data.getString("data25"));
map.put("data26", "data26:" + json_data.getString("data26"));
map.put("data27", "data27:" + json_data.getString("data27"));
mylist.add(map);
}
The JSON result is as follows:
[
{
"data1": "5794",
"data2": "2922",
"data3": "6799",
"data4": "2729",
"data5": "9860",
"data6": "4486",
"data7": "9903",
"data8": "0113",
"data9": "9936",
"data10": "5470",
"data11": "7423",
"data12": "1237",
"data13": "6564",
"data14": "1261",
"data15": "4730",
"data16": "7714",
"data17": "2410",
"data18": "7486",
"data19": "7046",
"data20": "8263",
"data21": "4305",
"data22": "6244",
"data23": "2495",
"data24": " 19\/09\/2012(Wed)"
},
{
"data1": "555",
"data2": "039",
"data3": "353",
"data4": "1438",
"data5": "8720",
"data6": "7490",
"data7": "1294",
"data8": "4000",
"data9": "6017",
"data10": "2294",
"data11": "4042",
"data12": "0064",
"data13": "8441",
"data14": "1252",
"data15": "9609",
"data16": "0797",
"data17": "1680",
"data18": "0917",
"data19": "7492",
"data20": "9488",
"data21": "3253",
"data22": "7915",
"data23": "1071",
"data24": " 19\/09\/2012(Wed)",
//--heredata25,
data26,
data27----------"data25": "9555",
"data26": "3039",
"data27": "6353"
},
{
"data1": "0395",
"data2": "5928",
"data3": "8998",
"data4": "6447",
"data5": "1827",
"data6": "8131",
"data7": "7454",
"data8": "4647",
"data9": "1892",
"data10": "3656",
"data11": "1989",
"data12": "9095",
"data13": "6826",
"data14": "1860",
"data15": "9766",
"data16": "6069",
"data17": "6050",
"data18": "6526",
"data19": "8392",
"data20": "0520",
"data21": "7540",
"data22": "3608",
"data23": "7430",
"data24": " 19\/09\/2012(Wed)"
},
A: As per the response you have posted, it is a JSONArray of JSONObjects. Each JSONObject contains the values with the keys like data1, data2...etch. But every JSONObject doesn't contain the keys data25, data26, data27. If you don't want to throw exception even the response does n't contain the data25,data26, data27 keys in every JSONObject then you need to modify the code like below:
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++)
{
HashMap<String, String> map = new HashMap<String, String>();
// getJSONObject() will throw exception if the key is not found in the jsonObject. Instead of it use optJSONObject() to get the values from JSONObject. It returns the value if contains otherwise returns the empty jsonObject.
// JSONObject json_data = jArray.getJSONObject(i);
JSONObject json_data = jArray.optJSONObject(i);
//map.put("data25", "date25:" + json_data.getString("data25"));
map.put("data25", "date25:" + json_data.optString("data25")); // returns empty string on not finding the key in JSONObject.
//map.put("data26", "data26:" + json_data.getString("data26"));
//map.put("data27", "data27:" + json_data.getString("data27"));
mylist.add(map);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/12542387",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to decompress tar.gz file with low memory usage [php 7]? I have a 4 gb tar.gz file i'd like to decompress into a tar file. I've been using
$p = new PharData('/path/to/file/name');
$p->decompress();
to try and do so. However I get an error 'PHP Fatal error: Allowed memory size of 8589934592 bytes exhausted (tried to allocate 36864 bytes)'
Things I've tried:
(1) ini_set('memory_limit', '-1');
Result: Generic 'Killed' error message
(2) ini_set('memory_limit', '6000M');
Result: 'PHP Fatal error: Allowed memory size of 8589934592 bytes exhausted (tried to allocate 36864 bytes)' error message
I've also gone into the php.ini file to make the same changes. How can I decompress the tar.gz file into a tar file?
A: Apparently the phar:// stream wrapper will allow you to read the CSV file contents directly out of the gzipped TAR.
$fh = fopen('phar://example.tar.gz/target_file.csv', 'r');
while( $row = fgetcsv($fh) ) {
// code!
}
This should leverage PHP's stream goodness so that reading from the file doesn't require more than a few kilobytes actually reside in memory at a given time.
That said, if you start just appending rows to an array in that loop you're going to have the same memory problems. Do something with the row, and then discard it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/63289723",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Import different openapi.json file to spring boot app I have custom openapi.json file and empty spring boot app. When I start the app I want it to import that file and show it in swagger-ui URL.
I couldn't find how to do it. All answers were how to generate openapi.json file from code. But my task is opposite.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/71464170",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: EXTJS 4.1.1. iframes reloads when switching tabs in TabPanel on Firefox: I've got a problem with PDF's in the TabPanel (only on Firefox). They are reloading everytime I switch tabs. The PDF is in a iframe.
Because of it the user can not compare two PDF files. When you click a tab with a PDF it loads 10 seconds, then you switch to a second tab and it also loads 10 seconds and so on....
I know this problem with Firefox has been around for years (which relates IFRAME, OBJECT, elements, FF reinitializes the objects, if their size changes).
It cannot be that there is no solution for this problem.
However, I have not found any for Extjs4 yet.
It would be great if someone could help me with it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/25781045",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Javascript regex to strip selective html tags I am trying to strip all (except some) html tags from a string using regex. What I am trying currently trying is as follows:
var a = "<pre><code><p>This is a <span>test</span></p></code></pre>";
var b = a.replace(/(\<|\<\/)[^\>,p,li,br,b]*\>/ig,"");
but b's value is returned as "<pre><p>This is a <span>test</span></p></pre>"
It seems any tags that contain even a single instance of [>,p,li,br,b] are not being removed, as here all pre, span and p contains the character p. However, I only want to ignore the exact characters in [^\>,p,li,br,b].
The output I am expecting is "<p>This is a test</p>".
what am I doing wrong ?
A: var a = "<pre><code><p>This is a <span>test</span></p></code></pre>";
var b = a.replace(/\<(?!\/?(p|li|br|b)[ >])[^>]*\>/ig,"");
This regex matches the leading < or </ only if it is not followed by one of the tag names you want to keep p, li, br, b (followed by a space or closing >, so that it doesn't think <pre> is <p>).
Then it matches everything up to the closing >.
A: See this answer.
That said, square brackets [] match on single characters, not words - for more information on what yours is doing, see the bottom of this answer. Instead, you would need to use parentheses (?:p|li|br|b) to match words - the ?: is used to avoid capturing. Also, the parentheses would occur outside of the square brackets.
Since you're using a negative match you may wish to look into lookarounds; specifically, the section on Positive and Negative Lookbehind.
[^\>,p,li,br,b] translates to not > and not , and not p and not , and not l and not i and not , and not b and not r and not , and not b.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/20401897",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Difficulty deploying lumen app I'm trying to deploy a small application to my remote server, however, I seem to be having difficulty with some of the routes. Bare in mind that everything works on my local machine.
Here is what I've done:
*
*Uploaded the entire project to /home/user/app
*Moved contents of /home/user/app/public to /home/user/public_html/api
*Modified /home/user/public_html/api/index.php from:
$app->run();
to
$request = Illuminate\Http\Request::capture();
$app->run($request);
...this allowed my first route to work, but I cannot load any other routes such as:
http://www.mywebsite.com/api/v1/book
Please note that only http://www.mywebsite.com/api is the only route that loads correctly.
My routes.php looks like this:
$app->get('/', function() use ($app) {
return "Lumen RESTful API";
});
$app->group(['prefix' => 'api/v1','namespace' => 'App\Http\Controllers'], function($app)
{
$app->get('book','BookController@index');
$app->get('book/{id}','BookController@getbook');
$app->post('book','BookController@createBook');
$app->put('book/{id}','BookController@updateBook');
$app->delete('book/{id}','BookController@deleteBook');
});
My .htaccess is as follows:
<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
Options -MultiViews
</IfModule>
RewriteEngine On
# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [L,R=301]
# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
</IfModule>
The error I am receiving:
Let me know if you need any more information?
Any help would be greatly appreciated!
A: Change route group prefix to:
$app->group(['prefix' => 'v1'
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/39418056",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How does the onDraw(Canvas) function of the View class work? I need to implement an interactive graph in Android
For a start I am trying to see how this code works
There, in a class called LineChartView Which extends the user generated class ChartView which extends the View class, there is an @overrideed function called onDraw(Canvas canvas). How and when does this function get called? the output of that code is a bunch of graphs on full screen, but my interactive graph should only take up a part of the screen. Does the onDraw() function get called automatically? If so, when? And what is the size of the canvas? Is it always the full screen occupied by the current activity's window?
A: in this link View Android Developer there is a section on implementing a custom view
onDraw(Canvas canvas) is called whenever a view should render its content
if you define to use this view in your layout xml or even in code you can specify the attributes
android:layout_width=
android:layout_height=
and those attributes will be applied to the size that the view will use
in your layout.xml
<your.package.name.extendedviewclass
android:layout_width="100dp"
android:layout_height="100dp"/>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/18776692",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Javascript uncaugh error in promise even with a catch With Javascript, I am trying to make a call to an external API when a form is submited.
I am using promises in order to set follow up actions once the call is done and to catch eventual errors.
This is where my problem is, even if I think I am catching my errors correctly, the console throws an
Uncaught (in promise) error : [The error I throw]
I do not understand why.
Here is a minimal version of my code which would reproduce the error when the refreshToken is expired :
try {
functionGeneratingTheError();
} catch (error) {
doSomethingElse();
}
function functionGeneratingTheError() {
var getTokenCallPayload = {
"client_id" : clientId,
"client_secret" : clientSecret,
"refresh_token" : refreshToken,
"grant_type" : "refresh_token"
};
var getTokenCallOptions = {
"method" : "POST",
"body" : JSON.stringify(getTokenCallPayload),
"muteHttpExceptions" : false
};
fetch(tokenURL, getTokenCallOptions)
.then(response => {
if (response.ok) {
return response.json();
} else {
throw new Error("Error");
}
})
.then(data => {
doSomething();
})
.then(response=> {
doSomethingAgain();
})
.catch(error => {
throw error;
});
}
If I understand correctly, when the fetch is a bad request, it should throw the error "Error" which should then be caught in the first catch and run the doSomethingElse() function.
However, instead of doing that, I get this error in the browser console "Uncaught (in promise) Error: Error"
What am I doing wrong ?
I have tried including the fetch in a try{}catch(){} but it doesn't change anything.
I also tried not throwing the error and directly call my doSomethingElse() function, but then the following .then fails because data is undefined.
A: Change your functionGeneratingTheError function to return the chained promise like below:
function functionGeneratingTheError() {
var getTokenCallPayload = {
"client_id" : clientId,
"client_secret" : clientSecret,
"refresh_token" : refreshToken,
"grant_type" : "refresh_token"
};
var getTokenCallOptions = {
"method" : "POST",
"body" : JSON.stringify(getTokenCallPayload),
"muteHttpExceptions" : false
};
return
fetch(tokenURL, getTokenCallOptions)
.then(response => {
if (response.ok) {
return response.json();
} else {
throw new Error("Error");
}
})
.then(data => {
doSomething();
})
.then(response=> {
doSomethingAgain();
})
.catch(error => {
throw error;
});
}
And then await it in your calling code by wrapping the calling code inside an async self invoking function like so:
(async function() {
try {
await functionGeneratingTheError();
} catch (error) {
doSomethingElse();
}
})();
You can read more about async/await here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75297892",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: $.ajax not loading data data everytime from server I have written a simple jQuery.ajax function which loads a user control from the server on click of a button. The first time I click the button, it goes to the server and gets me the user control. But each subsequent click of the same button does not goes to the server to fetch me the user control.
Since my user control fetches data from db, I need to reload the user control everytime i hit the button. But if anyhow I get my user control to unload from the page, and re-click the button, it goes to the server and fetches me the user control. Here's the code:
$("#btnLoad").click(function() {
if ($(this).attr("value") == "Load Control") {
$.ajax({
url: "AJAXHandler.ashx",
data: { "lt": "loadcontrol" },
dataType: "html",
success: function(data) {
content.html(data);
}
});
$(this).attr("value", "Unload Control");
}
else {
$.ajax({
url: "AJAXHandler.ashx",
data: { "lt": "unloadcontrol" },
dataType: "html",
success: function(data) {
content.html(data);
}
});
$(this).attr("value", "Load Control");
}
});
Please let me know if there is any other way I can get my user control loaded from server everytime I click the button.
A: Add a cache property with the value false to the objects you pass to jQuery.ajax.
$.ajax({
url: "AJAXHandler.ashx",
cache: false,
data: { "lt": "loadcontrol" },
dataType: "html",
success: function(data) {
content.html(data);
}
});
You can set this globally by:
jQuery.ajaxSetup({
cache: false
});
jQuery will used cached responses for anything except SCRIPT/ JSONP by default.
A: If your btnLoad is inside the user control you're reloading, you need to do this instead:
$("#btnLoad").live('click', function() {
When loading ajax, you're replacing the elements, and any event handlers bound directly to them. If you use .live() instead, it won't be destroyed as part of the callback...it works differently and the event handler lives higher in the DOM, so it doesn't get blown aware with the button itself.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/2571365",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Mikrotik Router Management via Web App I need help in building a project. Let me first describe my project -
I want to build a Web application (using php / php framework(laravel) , html, css, javaScript, bootstrarp ) that will help ISP owner to manage their router (most of them use Mikrotik router).
Reason to build this App:
Most ISP provider here use Mikrotik router to manage their internet business. But managing the router using Winbox ( a desktop based windows software that is build to manage Mikrotik router) seems complex to them. Just for creating new ip to assign a new user, blocking a user if he/she do not pay bills and managing bandwidth they need to operate winbox every time which they find difficult. My approach is to build a web application that will ease their work.
The features I want to provide are-
*
*Creating new IP address and addressing them to user (internet user / end user)
*Manage bandwidth of an IP address
*Block / Lock any particular IP address automatically (in this case any particular user) who have not paid their monthly bill on certain date of a month
*Re-enabling blocked IP address on paying their dues automatically
*Showing daily graph of bandwidth received and used
*Recording client history (client IP address, Monthly rent, Name, Address etc.)
*Recording payment history of client
*Auto bill calculation / due calculation
*Auto sort out of due users of months
I am able to do 6 - 9 features as described but I have no idea how to implement 1 - 5 features !
Problem That I am facing :
a. I don't know how to connect to a MikrotiK router via web application
b. If some how i can access to the MikrotiK router using router IP address , I don't know how to create new IP address on that router database
c. how to manage bandwidth via web application
d. how to block / lock ip address !
Points I get myself :
I think using management vlan (router Ip address) i can access to that router form command promt using ssh/telnet. After that what would be the command to create, lock/block, manage bandwidth of an IP address ? IF all this things can be done using command prompt, how can I make it for my web application ?
Can anyone please help me with this, referring any link?? I googled but only thing I find is Mikrotik router management manual !
A: I did part of what you are asking for a customer weeks ago. Your question is to broad, very extensive, it will take months to accomplishes the job.
Start your project with the basic that you can find at http://wiki.mikrotik.com/wiki/API_PHP_class, then you can grow your application and post specific questions about your problems in places like stackoverflow or reddit.
Follow a sample to connect to the API, then execute commands and then disconnect.
$API = new RouterosAPI();
$API->debug = true; // turn debug on to learn more about your api
if ($API->connect($server , $username , $passwd, $port)) {
// wireless registration table
$API->write('/interface/wireless/registration-table/print',false);
$API->write('=stats=');
// print output here
} else {
// connection fails
}
$API->disconnect();
Ref.:
*
*https://www.reddit.com/r/mikrotik/
*http://wiki.mikrotik.com/wiki/API_PHP_class
A: You should either use APIs or a remote command protocols like ssh/telnet(PHP-SSH2).
This is a PHP API project you could use:
https://github.com/BenMenking/routeros-api
After connecting you can commit commands just like you do on mikrotik console.
Mikrotik commands wiki
A: In my opinion you better use Radius server with database on MySQL. Mikrotik works perfect with Radius. In application implement interface with the database and all interaction with Mikrotik leaves to Radius. Read about FreeRadius for example:
https://www.howtoforge.com/authentication-authorization-and-accounting-with-freeradius-and-mysql-backend-and-webbased-management-with-daloradius
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/34411457",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: system.diagnostics.contracts.contract exists in both v4.0 v3.5 I just upgraded to visual studio 2010 and installed the code contracts msi. When I try to use it I get a compiler error that the system.diagnostics.contracts.contract dll exists in both the v3.5 and v4 framework. Anyone know what I should do to resolve this? Thanks.
A: If you're upgrading a .NET 3.5 project that uses contracts to .NET 4.0, make sure you remove your reference to the Microsoft.Contracts assembly.
The Microsoft.Contracts assembly provides code contracts for use in .NET 2.0 or 3.5 projects, but is provided by default with .NET 4.0 in mscorlib, so you don't need it. They both share the System.Diagnostics.Contracts namespace, so by having references to both at the same time, the compiler isn't able to figure out which one you're trying to use.
A: I solved it by first installing it, thou that did not actually solve it.
Then removed the references and then I changed the project versions to 4.5 and after that, it worked.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/3498461",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: can't list files in a directory I'm using CF 7 and this code is not returning any files:
<cfset fileLocation = "\\server\uploader\pass-fail">
<cfdirectory
action = "list"
directory = fileLocation
name = "pass_fail_files"
>
<cfdump var="#pass_fail_files#" expand="yes" label="files in pass-fail" >
<cfoutput>#pass_fail_files.name#</cfoutput>
<cfoutput>#pass_fail_files.directory#</cfoutput>
<cfoutput>#pass_fail_files.size#</cfoutput>
<cfoutput>#pass_fail_files.type#</cfoutput>
<cfoutput>#pass_fail_files.dateLastModified#</cfoutput>
<cfoutput>#pass_fail_files.attributes#</cfoutput>
<cfoutput>#pass_fail_files.mode# </cfoutput>
I have checked to make sure that the directory indeed has several text files. But when I run the code, all I get is:
alt text http://img682.imageshack.us/img682/5603/nofiles.png
What am I doing wrong?
A: I've just tried this:
<cfset fileLocation = "\\192.168.8.20\websites">
<cfdirectory
action = "list"
directory = "#fileLocation#"
name = "pass_fail_files"
>
<cfdump var="#pass_fail_files#" expand="yes" label="files in pass-fail" >
On CF7, CF8 and Railo, and works everytime.
Notice I updated your code so it uses the directory attribute as directory = "#fileLocation#" as opposed to directory = fileLocation.
Trying your code, I never got results, but didn't get errors either. Changing it to use double-quotes and hashes did the trick, as it stopped using it as a variable.
Hope it helps you.
A: My first question would be, does the ColdFusion Service User have read access on folder?
Actually, I think your code should be
<cfdirectory
action = "list"
directory = "#fileLocation#"
name = "pass_fail_files"
>
I think right now, you're telling it to look in a directory named "fileLocation".
A: Assuming you've done all the latest CF7 updates/patches/hotfixes..
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/2455345",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Redirect POST-request in apache I'm trying to do a transparent redirect of a post-request in my apache server.
The request looks like this:
POST www.domain.com//maincontroller.php/api
I want to redirect this to:
POST www.domain.com/maincontroller.php/api
I don't want a 301 redirect but instead a silent redirect (edit the Post address and send it to httpd).
Everything I tried with mod_rewrite didn't rewrite the POST, but successfully rewrote a GET.
A: Coworker found it !
RewriteCond %{THE_REQUEST} POST
RewriteCond %{THE_REQUEST} ^[A-Z]+\s//+(.*)\sHTTP/[0-9.]+$ [OR]
RewriteCond %{THE_REQUEST} ^[A-Z]+\s(.*/)/+\sHTTP/[0-9.]+$
RewriteRule .* http://%{HTTP_HOST}/%1 [P]
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/30839937",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Django Session Form (save form temporarily) I have created a page for review form. All users can fill out the form, but only logged in users can submit the form. If users is not logged in, they will be redirected to the login page. After they login, they will be redirected to the profile page.
So the flow will be like this :
User fills out the form > click the submit > redirected to login page > user login and redirected to profile page (at the same time, the form they have filled in is automatically saved)
I want the form they have filled in automatically saved after they login. How to do that?
My idea is to create a session that saves the form temporarily, then save to database after they login. But I'm confused how to write the code
Can anyone explain a bit what a django session is like? and how to write code to handle this problem?
A: You can try something like,
1 User fills out the form and hits submit
2 in the POST view where you handle the form, use the "**is_authenticated**" function and,
a)if the user is authenticated you handle the form as usual...
b)else set the contents of the form into a session variable in the views and redirect to the login page like,
request.session['review_body'] = request.post.get(the_form_body_field)
3 as per what you've said, after login it goes to profile page and form is submitted...
a)so in views where you serve the profile page, check if the session variable containing form data's exist and has values
b)if yes, directly save the contents from your views and clear the session data
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/69893123",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Chef - Returning a variable from powershell script I would like to know if there is a way to return a variable value from a powershell script defined in powershell_script resource?
My powershell resource looks like following:
powershell_script "Test Script" do
code <<-EOH
Write-Host "Hello World!"
return "test"
EOH
end
I would like to use the returned value test from the script to use in other resources based on if conditions.
Thanks
A: Ohai!
I think you actually want to use the PowershellOut Mixin found here in the Powershell cookbook.
Chef resources rarely return values, but that's what heavy-weight resources are for!
If you have the powershell cookbook, you can do this:
include Chef::Mixin::PowershellOut
cmd = powershell_out!('command')
cmd.stdout #=> ...
cmd.stderr #=> ...
A: We actually came across this exact issue and solved it by writing our own Mixlib to get the exit code from a powershell script. Example:
# get the result object (and exit code) from the code execution:
result = Mixlibrary::Core::Shell.windows_script_out(:powershell, mycode)
exit_status = result.exitstatus
@carpNick is planning on open-sourcing this perhaps as soon as this week....at the moment it only handles powershell, but we plan on implementing support for other types as well (bash, win modules, etc.) -- which should be fairly easy to add on support for others.
We are currently using it in-house and it works great. I'm sure Chef will want to review Nick's excellent code once he gets it out there. We are just waiting on legal to tell us what open-source license to use.
Ask Nick for more details... @carpnick | https://github.com/carpnick
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/20805780",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: add record via has_many with default scope Records are added with default scope, but not with required.
class PostsTag
# published is false by default
end
class Post
has_many :posts_tags
{published: true, private: false}.each do |key, val|
has_many "#{key}_tags",
through: "posts_tags",
conditions: ["posts_tags.published = ?", val],
source: :tag
end
end
#--------------------
Post.first.published_tags << Tag.first
Post.first.published_tags.count # = 0
Post.first.private_tags.count # = 1
What do I wrongly? Thanks for advance.
A: Inserting a new Tag into published_tags does not set its published attribute to true by default.
What you need to do is to extend the published_tags association and override the << method of it to set the published attribute to true upon insertion. The code will look something like that:
has_many :published_tags do
def <<(tag)
tag.published = true
proxy_association.owner.posts_tags+= [tag]
end
end
I've written a full working example of exactly this case here, you should definitely have a look at it to get some more insights.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/12226988",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Find out max divisor of a positive integer I need to find the biggest divisor of a positive integer and output it. Divisor should not be 1 or be equal to the integer itself. If it's a prime number the output should be "0". I have this code so far. However it doesn't work. It only works when I use "break" instead of "return 0" statement, but according to the task I should not use break :( How can I fix it? Thnx
#include <stdio.h>
int main() {
int input, maxDiv;
int div = 2;
scanf("%d", &input);
for ( ; div <= input/2; div += 1 ) {
if ( input % div == 0 ) {
maxDiv = input / div;
return 0;
} else {
maxDiv = 0;
}
}
printf("%d\n", maxDiv);
return 0;
}
A: You can rewrite it this way
int main(){
int input, maxDiv = 0;
int div = 2;
scanf("%d", &input);
for(; !maxDiv; div++)
if(!(input%div))
maxDiv = input/div;
printf("%d\n", ( maxDiv == 1 || input < 0 ? 0 : maxDiv ) );
return 0;
}
It is an infinite loop that will exit as soon as maxDiv != 0. The complexity is O(sqrt (n)) as there is always a divisor of n less than or equal to sqrt(n), so the code is bound to exit (even if input is negative).
I forgot, you have to handle the case where input is zero.
A: Maybe you can declare a flag?
#include <stdio.h>
int main() {
int input, maxDiv;
int div = 2;
char found = 0;
scanf("%d", &input);
for ( ; div <= input/2 && !found ; div += 1 ) {
if ( input % div == 0 ) {
maxDiv = input / div;
found = 1;
} else {
maxDiv = 0;
}
}
printf("%d\n", maxDiv);
return 0;
}
A: You can stop the loop when you reach sqrt(input)... it's not that difficult to find a perfectly good integer sqrt function.
There's not a lot of point dividing by all the even numbers after 2. In fact there's not a lot of point dividing by anything except the primes. It's not hard to find the primes up to sqrt(INT_MAX) (46340, for 32-bit integer)... there are tables of primes freely available if you don't want to run a quick sieve to generate same.
And the loop...
maxdiv = 0 ;
i = 0 ;
sq = isqrt(input) ;
while ((maxdiv == 0) && (prime[i] < sq))
{
if ((input % prime[i]) == 0)
maxdiv = input / prime[i] ;
i += 1 ;
} ;
assuming a suitable integer sqrt function and a table of primes... as discussed.
A: Since you are looking for the largest divisor, is there a reason you're not looping backward to 2? If there isn't, then there should be no need for a break statement or any special logic to exit the loop as you should keep looping until div is greater than input / 2, testing every value until you find the largest divisor.
maxDiv = -1;
for (div = input / 2;
div >= 2 && maxDiv == -1;
--div)
{
if (input % div == 0)
maxDiv = div;
}
maxDiv += (maxDiv == -1);
printf ("%d\n", maxDiv);
I added the extra condition of maxDiv being -1, which is like adding a conditional break statement. If it is still -1 by the end of the loop, then it becomes 0 because maxDiv += 1 is like writing maxDiv = -1 + 1, which is 0.
Without any jump statement such as break, this sort of test is what you must do.
Also, regarding your code, if I input 40, the if statement will be triggered when div is 2, and the program will end. If the return 0 is changed to a break, maxDiv will be 2, not 20. Looping backward will find 20 since 40/2=20, and 40%20==0.
A: Let us denote D to the max divisor of a given composite number N > 1.
Then, obviously, the number d = N / D is the min non-trivial divisor of N.
If d would not a primer number, then d would have a non-trivial divisor p < d.
By transitivity, this implies that p is a divisor of N, but this fact would contradict the fact that d is the min divisor of N, since p < d.
*
*So, d must be a prime number.
In particular, it is enouth to search over those numbers which are less than sqrt(N), since, if p is a prime number greater than sqrt(N) which divies N, then N / p <= sqrt(N) (if not, *p * (N / p) > sqrt(N)sqrt(N) == N, wich is absurd).
This shows that it's enough to do the search the least divisor d of N just within the range of primer numbers from 2 to sqrt(N).
For efficiency, the value sqrt(N) must be computed just once before the loop.
Moreover, it is enough a rough approximation of sqrt(N), so we can write:
#include <math.h>
#include <stdio.h>
int main(void)
{
int N;
scanf("%d",&N);
// First, we discard the case in that N is trivial
// 1 is not prime, but indivisible.
// Change this return if your want.
if (N == 1)
return 0;
// Secondly, we discard the case in that N is even.
if (N % 2 == 0)
return N / 2;
// Now, the least prime divisor of N is odd.
// So, we increment the counter by 2 in the loop, by starting in 3.
float sqrtN = fsqrt(N); // square root of N in float precision.
for(d = 3; d <= sqrtN; d += 2)
if (N % d == 0)
return N/d;
// If the loop has reached its end normally,
// it means that N is prime.
return 0;
}
I think that the problem is not well stated, since I consider that a better flag to signalize that N is prime would be a returned value of 1.
There are more efficient algorithms to determine primality, but they are beyond the scope of the present question.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/25097162",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: extract individual words from string c++ I am trying to make a C++ program that receives user input, and extracts the individual words in the string, e.g. "Hello to Bob" would get "Hello", "to", "Bob". Eventually, I will be pushing these into a string vector. This is the format I tried to use when designing the code:
//string libraries and all other appropriate libraries have been included above here
string UserInput;
getline(cin,UserInput)
vector<string> words;
string temp=UserInput;
string pushBackVar;//this will eventually be used to pushback words into a vector
for (int i=0;i<UserInput.length();i++)
{
if(UserInput[i]==32)
{
pushBackVar=temp.erase(i,UserInput.length()-i);
//something like words.pushback(pushBackVar) will go here;
}
}
However, this only works for the first space encountered in the string.It does not work if there are any spaces before the word (e.g. if we have "Hello my World", pushBackVar will be "Hello" after the first loop, and then "Hello my" after the second loop, when I want "Hello" and "my".) How do I fix this? Is there any other better way to extract individual words from a string? I hope I haven't confused anyone.
A: See Split a string in C++?
#include <string>
#include <sstream>
#include <vector>
using namespace std;
void split(const string &s, char delim, vector<string> &elems) {
stringstream ss(s);
string item;
while (getline(ss, item, delim)) {
elems.push_back(item);
}
}
vector<string> split(const string &s, char delim) {
vector<string> elems;
split(s, delim, elems);
return elems;
}
So in your case just do:
words = split(temp,' ');
A: You can use the operator >> direct to a microbuffer (string) to extract the word. (getline is not needed). Take a look at the function below:
vector<string> Extract(const string& Text) {
vector<string> Words;
stringstream ss(Text);
string Buf;
while (ss >> Buf)
Words.push_back(Buf);
return Words;
}
A: #include <algorithm> // std::(copy)
#include <iostream> // std::(cin, cout)
#include <iterator> // std::(istream_iterator, back_inserter)
#include <sstream> // std::(istringstream)
#include <string> // std::(string)
#include <vector> // std::(vector)
using namespace std;
auto main()
-> int
{
string user_input;
getline( cin, user_input );
vector<string> words;
{
istringstream input_as_stream( user_input );
copy(
istream_iterator<string>( input_as_stream ),
istream_iterator<string>(),
back_inserter( words )
);
}
for( string const& word : words )
{
cout << word << '\n';
}
}
A: Here I have created a vector of words from the sentence.
#include<bits/stdc++.h>
using namespace std;
int main(){
string s = "the devil in the s";
string word;
vector<string> v;
for(int i=0; i<s.length(); i++){
if(s[i]!=' '){
word+=s[i];
}
else{
v.push_back(word);
if(i<s.length()+1)
word.clear();
}
}
v.push_back(word);
for(auto i:v){
cout<<i<<endl;
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/39050225",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Designing a database connection class in VS 2005 I am working on designing a SQL Server database connection class in VB.net 2005. The idea behind doing this will be so a developer can can call the class, pass it a stored procedure name along with the parameters, and get return values back (if any).
My question is, how would I design the class so the stored proc parameters are dynamic?
My second question is, how would I account for the data type being passed to the stored procedure?
A: This assumes SQL Server, but the SqlParameter type could be changed to match the connection type. As items are added to this list the data type would have to be identified.
Imports System.Data.SqlClient
Dim Params As List(Of SqlParameter)
Public Property ParameterList() As List(Of SqlParameter)
Get
Return Params
End Get
Set(ByVal value As List(Of SqlParameter))
Params = value
End Set
End Property
You'll have to loop through the list and add each parameter to a command object.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/4033131",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: clicking href on capybara I'm trying to tell Capybara/Cucumber to click on href but failed trying different options. Here's the code:
<div>
<h6 class="animation-visible tile-animation link-group color-white border-round bg-primary animated" data-animation-delay="1000" data-animation="cta-1">
<label>Option 1</label>
<a href="http://some.com/page1/">More</a>
</h6>
<h6 class="animation-visible tile-animation link-group color-white border-round bg-primary animated" data-animation-delay="1000" data-animation="cta-1">
<label>Option 2</label>
<a href="http://some.com/page2/">More</a>
</h6>
...
</div>
1st attempt was to have find_link('More').click the "link".
within(all(.animation-visible.tile-animation.link-group.color-white.border-round.bg-primary.animated>a).[0]) do
find_link('More').click
end
That didn't work. I've tried having it clicked straight away.
find(all('.animation-visible.tile-animation.link-group.color-white.border-round.bg-primary.animated>a')[0]).click
That didn't work either.
Just wondering if there's any other way to click Option 1? Or Option 2? These options need to be tested individually.
A: Assuming the elements are visible on the page (not sure what the animation classes on the h6 elements are actually doing) then your first attempt wont work because of the extra > a on the selector in the within - which means you're finding the a already and then saying inside that find another a. Your second attempt won't work because find takes a selector type and selector (selector type defaults to css) to match against elements, but all returns an array of elements (you call either find to return one element or all to return multiple elements) - the following should work instead
within(all('.animation-visible.tile-animation.link-group.color-white.border-round.bg-primary.animated')[0]) do
find_link('More').click
end
which is saying inside the first .animation-visible... matching element find a link with 'More' for its text and click it. This could also be written
within(first('.animation-visible.tile-animation.link-group.color-white.border-round.bg-primary.animated', minimum: 1)) do
click_link('More')
end
That is basically the same thing except the minimum: 1 option will make it wait until at least one matching element is on the page (good for if your previous call is #visit or the elements are loading via ajax
Note: you could use the minimum: 1 (or whatever number of elements you're expecting to appear on the page) on the first example too
The find_link calls suggested in the other answer won't work because find_link doesn't take a css selector, it takes a string to match against the text, id, or title of the link. So the following would work
find_link('More', href: 'http://some.com/page1/').click
or
click_link('More', href: 'http://some.com/page1/')
A: Wouldn't these work?
First link
find_link("a[href$='page1/']").click
Second link:
find_link("a[href$='page2/']").click
Translation of the css selector:
Find the link that ends with XXX
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/33728538",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: PHP while() wrapping items I have this html code:
<div class="row elem2">
<div class="item"></div>
<div class="item"></div>
</div>
<div class="row elem4">
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
</div>
<div class="row elem3">
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
</div>
and I am looking for a way to implement it in my php while (wordpress).
The while is as
while ( have_posts() ) : the_post();
echo '<div class="item"></div>';
endwhile;
I've tried a lot of stuff, but none have worked. I need to divide every 2 items and put them in a wrap <div class="row elem2"> after that the next 4 items in <div class="row elem4"> and after that the next 3 items in <div class="row elem3">
I did a lot of searching, but I am not even sure what to search for.
A: A little crude but here's one solution
$i = 0; // Number of items made so far in the row
$mode = 0; // Current row type enumerated by $elem
$elem = array(2,4,3); // Enumeration of the desired row sizes
while ( have_posts() ) : the_post();
// Make a new row when there's no items yet
if ($i == 0) echo '<div class="row elem'. $elem[$mode] .'">';
echo '<div class="item"></div>';
$i++;
// Once the items in the current row has reached the row's maximum size
if ($i % $elem[$mode] == 0):
echo '</div>';
$i = 0; // Reset items made for the row back to 0
$mode = ($mode + 1) % 3; // Increment mode and wrap if necessary
endif;
endwhile;
if ($i > 0) echo '</div>'; // Finish the last row if it wasn't finished
This is what the modulos was built for!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/20666903",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to display all projects in the Project View in PHPStorm? In eclipse / Zend Studio the project manager displays per default all projects of the workspace (or of one of its Working Sets, if selected):
Now I'm looking for the according configuration in PHPStorm, that shows only one project per window:
How can I see all my projects in the project view of the same window?
A: PhpStorm does not support multiple independent projects in one window / frame:
https://youtrack.jetbrains.com/issue/WI-15187 -- star/vote/comment to get notified on progress.
But ... you can list files from another project there (in Project View panel). If that is good enough, then just go to Settings | Directories and add desired folder as an Additional Content Root. P.S. This also means that the setting from current project will be applied to all content roots.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/26704215",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How can I prevent RMySQL errors and show to user in Shiny? I have a Shiny App that executes a query to a MySQL database like this example:
UI
textAreaInput("query")
SERVER
data <- reactive({
df<-dbGetQuery(conection, input$query)
return(df)
})
The problem is that when the user types a wrong syntax in the textAreaInput the Shiny App closes and the error is shown in the R Console.
What I want is to print that error in the app so the user can try again and write another query.
Can someone help me please?
A: We can use tryCatch. Here is a complete example based on @Fan Li's answer here
library(RSQLite)
con <- dbConnect(SQLite(), dbname="sample.sqlite")
dbWriteTable(con, "test", data.frame(value1 = letters[1:4], value2 = letters[5:8]))
dbDisconnect(con)
library(shiny)
library(RSQLite)
runApp(list(
ui = bootstrapPage(
#select * from te fail
#select * from test work
textAreaInput("query",'Query'),
actionButton("action", label = "Run Query"),
hr(),
tableOutput("table")
),
server = function(input, output){
#Reactive is eager by definition and it will signal unreal/annoying errors, hence I used eventReactive
data <- eventReactive(input$action,{
tryCatch({
con <- dbConnect(SQLite(), dbname="sample.sqlite")
data<-dbGetQuery(con, input$query)
dbDisconnect(con)
return(data)
},
error = function(e){
showModal(
modalDialog(
title = "Error Occurred",
tags$i("Please enter valid query and try again"),br(),br(),
tags$b("Error:"),br(),
tags$code(e$message)
)
)
})
})
output$table <- renderTable(data())
}))
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/54243937",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do I update my HTML Selects with ajax based on other Selects? I've got this search page with 7 different Selects and 2 textfields.
The data wich is stored in the selects is fetched from a MYSQL database.
Now when I make a choice, I want the other selects to update based on the choise I made.
This needs to be accomplished with Ajax. Can someone point me in the right direction?
A: collect the values of already filled selects, and send them to the server to obtain the filtered values list.
let's say you have an car manufacturer / model selector.
<select name="manufacturer">
<option value="1">Acura</option>
<option value="2">Audi</option>
...
</select>
<select name="model"></select>
the function to fill "model" select with values should look like this:
$.get('/get_models_by_manufacturer', {manuf: $('select[name=manufacturer']).val()}, function(data){
// data returned by the server is expected to be html code of options NOT surrounded with <select>
$('select[name=model]').html(data);
});
A: IF your're using jquery there is an discussion: http://forum.jquery.com/topic/how-to-reload-a-select-in-a-form-using-ajax-via-jquery
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/16415141",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: EF Code first - many to many relation mapping table with extra columns I am having a User Model and and a Group Model. User and Group share a many to many relationship. In when I translate this to table, I want to have a mapping table. I am using the following to achieve this.
modelBuilder.Entity<UserGroup>()
.HasMany(a => a.Users)
.WithMany(b => b.UserGroup)
.Map(mc =>
{
mc.ToTable("UserUserGroupMapping");
mc.MapLeftKey("UserId");
mc.MapRightKey("UserGroupId");
});
This creates a table with UserId and UserGroupId as columns. However I have few challenges,
I would like to be able to add an Identity column to this table and some audit columns (ex: Created by, created date) to the table. I am not sure how to do this.
Can any one help me here?
Thanks
A: I think it'll work if you do the following:
*
*Remove the configuration you showed in the code snippet above
*Add a mapping table and configure its table name to match the original table name.
// name this whatever you want
class UserUserGroupMapping
{
public UserUserGroupMappingId { get; set; }
public int UserId { get; set; }
public virtual User User { get; set; }
public int UserGroupId { get; set; }
public virtual UserGroup UserGroup { get; set; }
// other properties
}
modelBuilder.Entity<UserUserGroupMapping>()
.HasKey(um => um.UserUserGroupMappingId)
.ToTable("UserUserGroupMapping");
*Replace the many-to-many collection properties from User and UserGroup and replace it with one-to-many associations
class User
{
// other properties
// remove this:
// public virtual ICollection<UserGroup> UserGroup { get; set; }
public virtual ICollection<UserUserGroupMapping> UserGroupMappings { get; set; }
}
class UserGroup
{
// other properties
// remove this:
// public virtual ICollection<User> Users { get; set; }
public virtual ICollection<UserUserGroupMapping> UserMappings { get; set; }
}
modelBuilder.Entity<UserUserGroupMapping>()
.HasRequired(um => um.UserGroup).WithMany(g => g.UserMappings)
.HasForeignKey(um => um.UserGroupId);
modelBuilder.Entity<UserUserGroupMapping>()
.HasRequired(um => um.User).WithMany(g => g.UserGroupMappings)
.HasForeignKey(um => um.UserId);
*Use the package manager to Add-Migration and remove anything from the scaffolded migration that might attempt to drop the old table and create a new table. The migration will need to at least (I might be missing some here):
*
*DropPrimaryKey for the original key columns
*AddColumn for the new columns (with Int(identity:true, nullable: false) for the new primary key column)
*AddPrimaryKey for the new key column
Then you can use the methods outlined in this answer to retrieve entities.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/30899930",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Does delete[] need to be called on the original pointer position According to answers in this question : "How does delete[] "know" the size of the operand array?"
your allocator will keep track of how much memory you have allocated
and
How free knows how much memory to deallocate"
Yes, the memory block size is stored "somewhere" by malloc (normally in the block itself), so that's how free knows. However, new[]/delete[] is a different story. The latter basically work on top of malloc/free. new[] also stores the number of elements it created in the memory block (independently of malloc), so that later delete[] can retrieve and use that number to call the proper number of destructors
Does this mean that delete[] is independent on where the pointer points to? Is the following code valid or will it result in memory leaks?
void createArray(){
char* someArray = new char[20];
readData(someArray);
//Is this delete still valid after moving the pointer one position?
delete[] someArray;
}
char readData(char* &arr){
char value = *arr;
//Let it point to the next element
arr += 1;
return value;
}
A: Yes it does. If you change a new[]-ed pointer value and then call delete[] operator on it you are invoking undefined behavior:
char* someArray = new char[20];
someArray++;
delete[] someArray; // undefined behavior
Instead store the original value in a different pointer and call delete[] on it:
char* someArray = new char[20];
char* originalPointer = someArray;
someArray++; // changes the value but the originalPointer value remains the same
delete[] originalPointer; // OK
A: You might be interested to know what new and delete really do under the covers (some licence taken, ignores exceptions and alignment):
template<class Thing>
Thing* new_array_of_things(std::size_t N)
{
std::size_t size = (sizeof(Thing) * N) + sizeof(std::size_t);
void* p = std::malloc(size);
auto store_p = reinterpret_cast<std::size_t*>(p);
*store_p = N;
auto first = reinterpret_cast<Thing*>(store_p + 1);
auto last = first + N;
for (auto i = first ; i != last; ++i)
{
new (i) Thing ();
}
return first;
}
template<class T>
void delete_array_of_things(Thing* first)
{
if (first)
{
auto store_p = reinterpret_cast<std::size_t*>(first) - 1;
auto N = *store_p;
while (N--)
{
(first + N)->~Thing();
}
std::free(store_p);
}
}
Summary:
The pointer you are given is not a pointer to the beginning of the allocated memory. The size of the array is stored just before the memory that provides storage for the array of objects (glossing over some details).
delete[] understands this and expects you to offer the pointer that was returned by new[], or a copy of it.
A: General rule is that you can delete only pointers you got from new. In an non-array version you are allowed to pass a pointer to base class subobject created with new (granted the base class has virtual destructor). In case of array version, it must be the same pointer.
From cppreference
For the second (array) form, expression must be a null pointer value or a pointer value previously obtained by an array form of new-expression. If expression is anything else, including if it's a pointer obtained by the non-array form of new-expression, the behavior is undefined.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/48322684",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Android calendarview font size I am using Xamarin for building android application this is my first app. I have a CalendarView I need to change the font size and style of the day.
I tried the below code the font color changed but the size is too small. The minimum API level is 11 and target API level is 16. I am using galaxy note 2 for testing.
<style name="Widget.CalendarView.Custom" parent="@android:style/Widget.CalendarView">
<item name="android:focusedMonthDateColor">@color/gray</item>
<item name="android:weekDayTextAppearance">@android:style/TextAppearance.Medium</item>
<item name="android:dateTextAppearance">?android:attr/textAppearanceLarge</item>
<item name="android:selectedWeekBackgroundColor">@android:color/transparent</item>
</style>
A: All you need to do is reference a different style that includes a slightly bigger font for the size of the date. I'm not exactly sure why yours isn't working using the styles.xml as it seems correct. However I would just simply add it to the XML attributes for the calendar. This will be fine as presumably you're only using one Calendar and therefore it isn't really inefficient. Add this line to the calendar XML:
android:dateTextAppearance="@android:style/TextAppearance.Large"
Hope this helps you!
A: You should change "android:dateTextAppearance", you can check this reference too ;)
CalendarView
also you can try this
Style will save the world!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/16412549",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to know most used procedure in my database? I completed my project, there are many procedures used and now I got the job to find the mostly used procedure and there average execution time.
In this way I know what are the procedures I need to tune first?
It there any way to get procedure execution history for a particular database?
A: I believe you can use the sys.dm_exec_query_stats dynamic management view. There are two columns in this view called execution_count, and total_worker_time that will help you.
execution_count gives the total number of times the stored procedure in question was executed since the last time it was recompiled.
total_worker_time gives the total CPU time in milliseconds that was spent executing this stored procedure since the last time it was recompiled.
Here is an MSDN link:
http://msdn.microsoft.com/en-us/library/ms189741.aspx
A: You can use dm_exec_cached_plans to look for the stored procedures that have been compiled into query plans. The function dm_exec_query_plan can be used to retrieve the object id for a plan, which in turn can be translated into the procedure's name:
select object_name(qp.objectid)
, cp.usecounts
from sys.dm_exec_cached_plans cp
cross apply
sys.dm_exec_query_plan(cp.plan_handle) qp
where cp.objtype = 'Proc'
order by
cp.usecounts desc
A: I think you want to check SQL Server Profiler for this.
You can check the details in MSDN and other places as well.
But, before using it in production server, you need to keep in mind that:
Profiler adds too much overhead to production server. So, first check when your site has less no of hits, and go ahead.
A: This is what the SQL Server Profiler is for. With it you can keep track of query run count, execution time, etc.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/15733170",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Email sending from ASP.net fails on IIS server I have implemented email service in my ASP.net application, and am using SmtpClient class to send email. The mail sending works perfectly fine from my local code, however it throws exception when published on the server.
The code is pretty basic, as below:
var message = new MailMessage();
message.To.Add(new MailAddress(recipientEmail));
message.Subject = subject;
message.Body = emailBody;
using (var smtp = new SmtpClient())
{
smtp.Credentials = new NetworkCredential(EmailSettings.Username, EmailSettings.Password);
smtp.Host = EmailSettings.Host;
smtp.Port = EmailSettings.Port;
smtp.EnableSsl = true;
await smtp.SendMailAsync(message);
}
The exception which is being thrown is as follows:
"Syntax error, command unrecognized. The server response was: "
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/51247107",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Using struct in a switch statement I'm trying to create a struct that can be used in a switch statement. I'm using a bunch of wierd compilers like keil armcc and old-fashioned gcc 4.7.1.
That also means c++11 is not an option.
For some time this idea actually worked:
struct Test
{
const int a;
Test() : a(1) {}
template<typename T>
operator T() const;
operator int() const {return a;}
};
...
Test t;
switch(t)
{
case 1:
break;
}
That compiled just fine. Now I'm trying to move to more recent version of gcc without breaking compatibility with armcc.
But now gcc gives me this:
error: ambiguous default type conversion from 'Test'
switch(t)
^
error: candidate conversions include 'template<class T> Test::operator T() const'
And I can't really understand where is the ambiguity since template operator has no body.
Is there any way to fix this?
A: You could assign to a temporary int:
int n = t;
switch (n) {
...
}
In the context of switch (t), the compiler considers coercion to integer types including int, unsigned int, long. By assigning to a variable of type int, we collapse the wave function force it to pick the conversion we want, and there's no ambiguity when we get to the switch.
You should also seriously consider making your template conversion operator explicit if you can, as a catch-all conversion can lead to unpleasant surprises.
A: switch(t)
{
case 1:
break;
}
Here the compiler doesn't know what conversion operator to call; it's ambiguous. It could instantiate your templated conversion operator for a few different integral types or call your int conversion operator. The fact that the templated conversion operator function is undefined doesn't matter to overload resolution.
The simplest solution is to use switch (static_cast<int>(t)).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/34152354",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to fail a cucumber scenario In my scenario, i need to validate if there exists 10 objects in a page.
If any of the object doesn't exists, then the step should be failed and eventually the scenario should also be reported as failed, but the script execution should continue to validate the remaining object exists.
I know scenario.getStatus()give if the scenario is failed, but how can i set the status of the scenario to failed? Importantly the script execution should continue afterwards.
A: Depending on the testing framework you are using junit or testng you can use the concept of soft assertion. Basically it will collect all the errors and throw an assertion error if something is amiss.
To fail a scenario you just need an assertion to fail, no need to set the status of the scenario. Cucumber will take care of that if an assertion fails.
For testng you can use the SoftAssert class - http://testng.org/javadocs/org/testng/asserts/SoftAssert.html You will get plenty tutorials for this. Call to doAssert will trigger of the verification of all stored assertions.
For junit you can use the ErrorCollector Rule class -
http://junit.org/junit4/javadoc/4.12/org/junit/rules/ErrorCollector.htmlenter link description here As cucumber does not support @Rule annotation, you need to inherit from this class and override the verify property to change its modifier to public in place of protected. Create an instance of the new class and add the assertions. Call to verify method will start the verification.
A: QAF provides assertion and verification concepts, where on assertion failure scenario exited with failed status and in case of verification scenario continue for next step and final status of step/scenario is failed if one or more verification failure.
You also can set step status failure using step listener which result in test failure. With use of step listener, you also can continue even step failure by converting exception to verification failure.
A: It is not a good idea to continue executing steps after a step failure because a step failure can leave the World with an invariant violation. A better strategy is to increase the granularity of your scenarios. Instead of writing a single scenario with several "Then" statements, use a list of examples to separately test each postconditions. Sometimes a scenario outline and list of examples can consolidate similar stories. https://cucumber.io/docs/reference#scenario-outline
There is some discussion about adding a feature to tag certain steps to continue after failure. https://github.com/cucumber/cucumber/issues/79
There are some other approaches to continuing through scenario steps after a failure here: continue running cucumber steps after a failure
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/40676750",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: WordPress add_action style arguments works but changes admin panel I've made a code so you can easily add a style sheet to the site, this is for our framework.
It works but if I use this the CSS changes the dashboard layout either? Same with customizer, if I don't use this method, but just a normal wp enqueue it works but that's not what I want.
class theme_setup{
function main_css_setup($css) {
wp_enqueue_style( 'style', get_template_directory_uri().'/css/'.$css.'.css' );
}
function add_css_main($css){
add_action( 'wp_enqueue_scripts', array($this, 'main_css_setup'),10,1 );
do_action( 'wp_enqueue_scripts', $css );
}
}
$theme_setup = new theme_setup();
$theme_setup->add_css_main('main');
Dashboard change:
First example
Second example
I think it has something to do with the do_action, I searched on my best behave, but without any luck.
I'm using the 'do_action' to pass the argument that the user gives with the add_css_main, I know I can use global variables, but these are "static", and that will make the idea be gone of a flexible function.
Update:
function themename_custom_logo_setup($height,$width) {
$defaults = array(
'height' => $height,
'width' => $width,
'flex-height' => true,
'flex-width' => true,
'header-text' => array( 'site-title', 'site-description' ),
);
add_theme_support( 'custom-logo', $defaults );
}
function add_custom_logo($width,$height){
add_action( 'after_setup_theme', array($this, 'themename_custom_logo_setup' ),10,2);
do_action( 'after_setup_theme', $height,$width);
}
$theme_setup->add_custom_logo(88,250);
Does work, but the variables are not even passed at al.
A: This should avoid loading the CSS with this conditional (maybe apply it somewhere else in your code):
function add_css_main($css){
if( !is_admin() ) {
add_action( 'wp_enqueue_scripts', array($this, 'main_css_setup'),10,1 );
do_action( 'wp_enqueue_scripts', $css );
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/49740782",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: E/AndroidRuntime: FATAL EXCEPTION: main PID: 5112 Hy
I am new to Android / Java is I am facing a BMO problem
I code it but it does not work
an idea ??
thank you
<string name="onCreate_Go">onCreate Go</string>
<TextView
android:id="@+id/scrollTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="18sp" />
import android.widget.TextView;
private final TextView txt = (TextView) this.findViewById(R.id.scrollTxt);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txt.setText(R.string.onCreate_Go);
}
5112-5112/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.gmail.test1, PID: 5112
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.gmail.test1/com.gmail.test1.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2121)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at android.support.v7.app.AppCompatDelegateImplBase.(AppCompatDelegateImplBase.java:117)
at android.support.v7.app.AppCompatDelegateImplV9.(AppCompatDelegateImplV9.java:149)
at android.support.v7.app.AppCompatDelegateImplV11.(AppCompatDelegateImplV11.java:29)
at android.support.v7.app.AppCompatDelegateImplV14.(AppCompatDelegateImplV14.java:54)
at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:202)
at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:183)
at android.support.v7.app.AppCompatActivity.getDelegate(AppCompatActivity.java:519)
at android.support.v7.app.AppCompatActivity.findViewById(AppCompatActivity.java:190)
at com.gmail.test1.MainActivity.(MainActivity.java:13)
at java.lang.Class.newInstanceImpl(Native Method)
at java.lang.Class.newInstance(Class.java:1208)
at android.app.Instrumentation.newActivity(Instrumentation.java:1061)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2112)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
02-16 16:41:21.634 5112-5112/? I/Process: Sending signal. PID: 5112 SIG: 9
A: Please add your Activity in your AndroidManifest.xml. like below code:
<activity android:name=".activities.MainActivity"/>
Also put the findViewById() after setContentView() so it can actually return something other than null.
A: You can't initialize the textView before call "setContentView" method. I recommend you create a "init" method where initialize all layout's elements and call it after "setContentView"
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/48832092",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
}
|
Q: How can I upload a file to a GitHub Codespaces environment? I use GitHub Codespaces, but I don't know how to upload a single file to GitHub Codespaces without the assistance of, for example, github.
A: Simple Drag and Drop has worked for me.
To update the answer, there is now also an update option if you right click in the explorer view:
A: I was able to transfer a ton of training data from firebase to a codespace using firebase-admin.
in the codespace terminal:
pip install firebase-admin
pip install --ignore-installed <other firebase-admin dependencies>
run whatever script you use to download things from firebase
note that there are storage limits
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/62284623",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: How not to remove first number in the sentence and remove later occurances of numbers in Python? I have a sentence that consists of numbers and words. I am looking for a solution to remove numbers except at the beginning. I have tried the following code, but it's removing all the numbers.
x = '45 is fourth five 45 when 9 and 5 are multiplied'
re.sub('\d', '', x)
Its output was
'is Fourth five when and are multiplied'
But need the output in the following manner.
'45 is Fourth five when and are multiplied'
Note:
*
*The number may or may not present at the beginning.
*Inside the sentence, there can be alphanumeric (460KG), then it should be changed (KG). That means, except at the beginning, the number should be removed elsewhere.
example :
6-apples price is 56Rs
I need an output as
6-apples price is Rs
A: You can use this:
x = '45 is fourth five 45 when 9 and 5 are multiplied'
string = re.sub(r'(?<!^)\b\d+\s', '', x)
Result:
>>> print(string)
45 is fourth five when and are multiplied
A: Using Pypi regex library, you can do:
import regex
x = '45 is fourth five 45 when 9 and 5 are multiplied'
print regex.sub(r'(?<=\D*\d+\D+)\d+ ?', '', x)
Output:
45 is fourth five when and are multiplied
Explanation:
(?<= # positive lookbehind, make sure we have before:
\D* # 0 or more non digits
\d+ # 1 or more digits
\D+ # 1 or more non digits
) # end lookbehind
\d+ # 1 or more digits
? # optional space
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/61085443",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Eclipse Marketplace hangs (Luna, Java8) My newly installed Eclipse Luna hangs when I launch Marketplace. I tried to move my workspace out of the way, clean everything, re-install and start fresh.
It would still hang and has to be killed -9. I saved the stack trace (as well as versions of the OS, Java, and Eclipse) at https://gist.github.com/c51821cbd4e676cd7c9f
The funny part is, things go just fine if I switch back Java1.7.0_25. I'd like to use Java8 though.
Is that a known problem and are there ways around it?
A: I would try to un-install and install again the Java8 JDK. Have you tried that?
Have you got multiple JDK installed? If yes try with just Java8 (un-install the others).
Or try also to run eclipse with
eclipse -vm c:\java8path\jre\bin\javaw.exe
or
eclipse -vm c:\java8path\jre\bin\client\jvm.dll
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/26069849",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Resampling of MultiIndex I would like a daily breakdown of a dataset by type. There are not records for every day for every type, where they don't exist I would like NaN.
I'm able to get a 'resampled to daily' result, but the type is ommitted.
The code below should be a fully working example (well, working apart from the known error at the end!):
import pandas as pd
import datetime as dt
df = pd.DataFrame({
'Date': [dt.datetime(2021,1,1), dt.datetime(2021, 1, 3), dt.datetime(2020,1,2)],
'Type': ['A', 'A', 'B'],
'Value': [1,2,3]
})
df.set_index('Date', inplace=True)
# this loses the 'type'
print(df.resample('1D').mean())
df = df.reset_index().set_index(['Date', 'Type'])
# this raises an exception "TypeError: Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of 'MultiIndex'"
print(df.resample('1D').mean())
Output I'm looking for is a row for every day / type combo:
date
type
value
20210101
A
1
20210102
A
NaN
20210103
A
2
20210101
B
NaN
20210102
B
3
20210103
B
NaN
Any advice or pointers gratefully received.
A: If need resample per groups is possible use Grouper for resample per days and then for add missing values is used Series.unstack with DataFrame.stack:
df = (df.groupby(['Type', pd.Grouper(freq='1D', key='Date')])['Value']
.mean()
.unstack()
.stack(dropna=False)
.reset_index(name='Value')
)
print (df)
Type Date Value
0 A 2021-01-01 1.0
1 A 2021-01-02 NaN
2 A 2021-01-03 2.0
3 B 2021-01-01 NaN
4 B 2021-01-02 3.0
5 B 2021-01-03 NaN
If need only append missing datetimes per groups is used DataFrame.reindex:
mux = pd.MultiIndex.from_product([df['Type'].unique(),
pd.date_range(df['Date'].min(), df['Date'].max())],
names=['Date','Type'])
df = df.set_index(['Type','Date']).reindex(mux).reset_index()
print (df)
Date Type Value
0 A 2021-01-01 1.0
1 A 2021-01-02 NaN
2 A 2021-01-03 2.0
3 B 2021-01-01 NaN
4 B 2021-01-02 3.0
5 B 2021-01-03 NaN
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/65791213",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Bootstrap carousel image height change according to sm md sx lg The issue is quality of image at smaller screens i.e 320px 375px 425px gets blur as i mention height in the class.. I am mentioning the height as i want the image to fit screen initially without user needing to scroll down to look for further information
My question here is should i resize the image so that it has quality in it..
Am sharing my code
CSS
'
.carousel{
background-color: #2f4357;
}
.carousel .item img{
margin: 0 auto;
height:570px;/* Align slide image horizontally center */
}
.bs-example{
margin: 20px;
}
'
html
'
<div class="row">
<div class="col-md-12">
<div class="bs-example">
<div id="myCarousel" class="carousel slide" data-ride="carousel">
<!-- Carousel indicators -->
<ol class="carousel-indicators">
<li data-target="#myCarousel" data-slide-to="0" class="active"></li>
<li data-target="#myCarousel" data-slide-to="1"></li>
<li data-target="#myCarousel" data-slide-to="2"></li>
</ol>
<!-- Wrapper for carousel items -->
<div class="carousel-inner">
<div class="item active">
<img src="images/aa.jpg" alt="First Slide">
</div>
<div class="item">
<img src="images/aa.jpg" alt="Second Slide">
</div>
<div class="item">
<img src="images/aa.jpg" alt="Third Slide">
</div>
</div>
<!-- Carousel controls -->
<a class="carousel-control left" href="#myCarousel" data-slide="prev">
<span class="glyphicon glyphicon-chevron-left"></span>
</a>
<a class="carousel-control right" href="#myCarousel" data-slide="next">
<span class="glyphicon glyphicon-chevron-right"></span>
</a>
</div>
</div>
</div><!-- /.col-md-8 -->
</div> <!-- /.end carousel row -->
'
A: You do not need to set any height or width to images in Bootstrap carousel if you are using them as img source. You need to add height only if you are using them as a background image. For this, you need to add height to .item class and set the background properties for the same.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/41257134",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: handling page orientation change in Xamarin When using Xamarin, what is the best or most accepted method of handling changes in orientation?
I have a carousel page which rotates through 5 content pages (the same page, just different text/images), in the content pages I have a 6 row grid, each row containing either an image, text or a button.
When changing from portrait to landscape I reset the size and padding of these within OnSizeAllocated. This seems to work randomly for 3 out of 5 content pages, the text in the other 2 will be out of position, and it's not always the same 3 that work either.
I'm guessing there's a better way to do this than manually resize things?
protected override void OnSizeAllocated(double width, double height)
{
base.OnSizeAllocated(width, height); //must be called
if (this.width != width || this.height != height)
{
this.width = width;
this.height = height;
//reconfigure layout
if (width > height)
{
img.HeightRequest = 62.5;
img.WidthRequest = 62.5;
logo.HeightRequest = 52.5;
logo.WidthRequest = 142.27;
headerStack.Padding = new Thickness(0, -60, 0, 0);
txtStack.Padding = new Thickness(20, -60, 20, 0);
sIndicator.Padding = new Thickness(20, 0, 20, 100);
sButton.Padding = new Thickness(0, -40, 0, 0);
}
else
{
img.WidthRequest = 250;
img.HeightRequest = 250;
logo.HeightRequest = 70;
logo.WidthRequest = 189.7;
headerStack.Padding = new Thickness(20, 40, 20, 0);
txtStack.Padding = new Thickness(20, 0, 20, 0);
sIndicator.Padding = new Thickness(20, 25, 20, 0);
}
}
}
A: With a few tweaks to what I was setting I got this working just fine, would still be interested in other peoples' views on how they do it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/44777237",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Function to show result in multiple divs I need to make this script to print the result (true, or false) for the transparency of the image in the divs according to the area if its transparent or not.
Here is the example where I can see the result if its transparent but only on mouse move and for pixel by pixel according to the pointer.
https://jsfiddle.net/kdichev/0jhazjoa/
Here i have put a overlay over the image with 1/10 of the size square divs which I would like to change colors depending if they have transparent pixels in their area or not
https://jsfiddle.net/kdichev/ae9pjstm/1/
Ideally if there is one pixel below the box it should have a red background color or print in it false.
(function () {
var img = new Image(),
output = document.getElementById('transparent'),
bImg = document.getElementById('img');
img.src = bImg.src;
function isTransparent(e) {
var x = e.pageX - this.offsetLeft,
y = e.pageY - this.offsetTop;
var canvas = document.getElementById('imgcheck-canvas') || (function (_this) {
var e = document.createElement('canvas');
e.setAttribute('width', _this.width);
e.setAttribute('height', _this.height);
e.setAttribute('id', _this.id + '-canvas');
e.setAttribute('style', 'display:none;');
document.body.appendChild(e);
var cx = e.getContext('2d');
cx.drawImage(_this, 0, 0, _this.width, _this.height);
return e;
})(this);
if (canvas.getContext === undefined) {
return false;
}
var ctx = canvas.getContext('2d');
output.innerHTML = ((ctx.getImageData(x, y, 1, 1).data[3] === 0) ? true : false);
}
function init() {
console.log('init');
bImg.addEventListener('mousemove', isTransparent, false);
}
img.addEventListener('load', init, true);
})();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/29199237",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Object.entries and addEventListener I have this object and I want to display the key in the options that gets created and the value in the .info <p> tag. I then want to change the info text, when I change the city by using an addEventListener.
My question is, is it possible to use the info in for(const [city, info] of entries) in a addEventListener function? I tried to have the eventListener in the for loop but that didn't work out right. But can I somehow pass the info to another function? Or is it better too just loop the keys and then do another loop for the values in an addEventListener function?
let citiesWithInfo = {"New York": 'The biggest city in the world.',
"Los Angeles": 'Home of the Hollywood sign.',
"Maui": 'A city on the beautiful island of Hawaii.',
"Vancover": 'It\'s a city where it rains alot. And I mean alot.',
"Miami": 'The samba city of the world.'
};
const cityWithInfoPrompt = document.querySelector('#cities-with-info');
const entries = Object.entries(citiesWithInfo);
for(const [city, info] of entries) {
let optionCity = document.createElement("option");
optionCity.textContent = city;
optionCity.value = city;
cityWithInfoPrompt.appendChild(optionCity);
let currentCity = cityWithInfoPrompt.options[cityWithInfoPrompt.selectedIndex];
if(currentCity.textContent == city) {
document.querySelector(".info").textContent = info;
}
}
<body>
<select name="cities-with-info" id="cities-with-info"></select>
<p>Info: <span class="info"></span></p>
<script src="eventTarget.js"></script>
</body>
A: You can attach the event outside the loop where you can match the value between the selected value and the object property name:
let citiesWithInfo = {"New York": 'The biggest city in the world.',
"Los Angeles": 'Home of the Hollywood sign.',
"Maui": 'A city on the beautiful island of Hawaii.',
"Vancover": 'It\'s a city where it rains alot. And I mean alot.',
"Miami": 'The samba city of the world.'
};
const cityWithInfoPrompt = document.querySelector('#cities-with-info');
const entries = Object.entries(citiesWithInfo);
for(const [city, info] of entries) {
let optionCity = document.createElement("option");
optionCity.textContent = city;
optionCity.value = city;
cityWithInfoPrompt.appendChild(optionCity);
}
cityWithInfoPrompt.addEventListener('change', function(){
let currentCity = this.options[this.selectedIndex].value;
document.querySelector(".info").textContent = citiesWithInfo[currentCity];
});
// On page load
// Create event
var event = new Event('change');
// Dispatch the event
cityWithInfoPrompt.dispatchEvent(event);
<body>
<select name="cities-with-info" id="cities-with-info"></select>
<p>Info: <span class="info"></span></p>
<script src="eventTarget.js"></script>
</body>
Solution using Arrow Function (() => {}) and Event.target
let citiesWithInfo = {"New York": 'The biggest city in the world.',
"Los Angeles": 'Home of the Hollywood sign.',
"Maui": 'A city on the beautiful island of Hawaii.',
"Vancover": 'It\'s a city where it rains alot. And I mean alot.',
"Miami": 'The samba city of the world.'
};
const cityWithInfoPrompt = document.querySelector('#cities-with-info');
const entries = Object.entries(citiesWithInfo);
for(const [city, info] of entries) {
let optionCity = document.createElement("option");
optionCity.textContent = city;
optionCity.value = city;
cityWithInfoPrompt.appendChild(optionCity);
}
cityWithInfoPrompt.addEventListener('change', () => {
let currentCity = event.target.value;
document.querySelector(".info").textContent = citiesWithInfo[currentCity];
});
// On page load
// Create event
var event = new Event('change');
// Dispatch the event
cityWithInfoPrompt.dispatchEvent(event);
<body>
<select name="cities-with-info" id="cities-with-info"></select>
<p>Info: <span class="info"></span></p>
<script src="eventTarget.js"></script>
</body>
A: I used this code for the addEventListener to get the info from the object to the info HTML tag.
cityWithInfoPrompt.addEventListener("change", (e) => {
let selectedCity = e.target.value
for(const [city, info] of entries) {
if(selectedCity == city) {
document.querySelector(".info").textContent = info;
}
}
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/58375202",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to integrate git hooks with eclipse I am trying to setup pre-commit hook which we have customized to our requirement .
It is working fine in git bash but it is unable to pick up the hook from eclipse .
How can I integrate or configure so the pre-commit hook gets invoked.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/36308136",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Is there a way to include both WICTextureLoader and DDSTextureLoader without 'redefinition' errors? I'm trying to load a DDS texture. For that, I'm using DDSTextureLoader11 provided by DirectXTex. I already am using another texture loader from the same library - WICTextureLoader11.
The problem is, I don't get errors with WICTextureLoader11, however I do get errors either when including only DDSTextureLoader11, or when I use both of them.
This is some of the errors I get when I include both or only DDSTextureLoader11:
/WICTextureLoader11.cpp:51:17: error: redefinition of 'SetDebugObjectName'
/WICTextureLoader11.cpp:273:17: error: redefinition of 'MakeSRGB'
/WICTextureLoader11.cpp:747:17: error: no matching function for call to 'SetDebugObjectName'
/DDSTextureLoader.h:156:35: error: redefinition of default argument
I first thought that it was because both WICTextureLoader and DDSTextureLoader contain same functions, so when including both they "overlap" (i.e. compiler detects redefinition).
I'm using a batchfile to compile my project, where I link against both DirectXTex and DirectXTK. I also tried to include DDSTextureLoader, but without success: I've read the GitHub page of the DirectXTK's DDSTextureLoader, where I include <DDSTextureLoader.h> that gives me a link error, which I guess is related to the incorrect call of the function CreateDDSTextureFromFile, so right now I'm trying to find a way to make the right call to the function.
Edit: no, it seems like I'm making the right function call. The wrong thing is that I'm trying to include DDSTextureLoader.h, but it also wants DDSTextureLoader.cpp. However, the errors occur when I include DDSTextureLoader.cpp, such as:
'DDSTextureLoader.cpp': call to 'BitsPerPixel' is ambiguous -> 'DirectXTex.h' or 'DDSTextureLoader' error: redefinition of 'SetDebugTextureInfo', previous definition in 'WICTextureLoader'.
I think, what I need is to include the .cpp file, but somehow get rid of the errors.
Edit2: So far, I tried to get rid of DirectXTex (I don't remember why I even needed it), and I've included WICTextureLoader.cpp and DDSTextureLoader.cpp. I downloaded and built the DirectXTK library, then included #pragma comment(lib, "directxtk.lib"). Now, the weird thing is: when I compile with Clang++, it doesn't throw any errors (but the program crashes after a second-long gray screen), however when I compile with cl (through vcvars64), I get fatal error LNK1104: cannot open file 'directxtk.lib'.
Edit3: Wait, I don't even know why I even need the directxtk.lib. So I removed it, and it compiles, but nothing works. I thought I needed that static library to resolve external symbol errors when trying to include the header (XXXTextureLoader.h), instead of the source (XXXTextureLoader.cpp).
Edit4: Wait,wait,wait. I think, I'm going crazy. Now, if I include only WICTextureLoader.cpp (and remove DDSTextureLoader.cpp), it gives me this error: (directxtk.lib) mismatch detected for 'RuntimeLibrary': value 'MD_DynamicRelease' doesn't match value 'MT_StaticRelease'. I don't know why I did that, but I'm crazy now, I blindly brute-force my way through resolving this cursed issue. Why can't I just throw both headers in my directory and just simply include them? Is there a way to do so? What should I do? Why doesn't DirectXTK/Tex pages on GitHub give a step-by-step guide to how to use these things? The examples drive me crazy!
Please, help me resolve this what seems to be a simple issue.
Edit5: The last thing that I tried is to include DDSTextureLoader.h and WICTextureLoader.h, and use directxtk.lib, but it gives me these errors:
directxtk.lib(DDSTextureLoader.obj) : error LNK2038: mismatch detected for 'RuntimeLibrary': value 'MD_DynamicRelease' doesn't match value 'MT_StaticRelease' in main-3dacd8.o
directxtk.lib(pch.obj) : error LNK2038: mismatch detected for 'RuntimeLibrary': value 'MD_DynamicRelease' doesn't match value 'MT_StaticRelease' in main-3dacd8.o
LINK : warning LNK4098: defaultlib 'MSVCRT' conflicts with use of other libs; use /NODEFAULTLIB:library
I don't use VS, so I don't know how to use /NODEFAULTLIB.
A: You have three choices for loading DDS and other image files with WIC:
*
*Use DirectXTex (the library)
*Use DDSTextureLoader/WICTextureLoader (the standalone versions)
*or use DirectX Tool Kit (the library).
There's no reason to use more than one of them in the same program, and it's going to conflict if you try. See this post.
Unless you are writing a texture processing tool, or need support for the plethora of legacy DDS pixel formats, using DirectX Tool Kit is usually the simplest. The tutorials for DirectX Tool Kit covers this pretty well.
The error you are getting indicates something much more basic to using Visual C++. The DirectXTex, DirectXTK libraries build using the recommended "Multithreaded DLL" version of the C/C++ Runtime (i.e. /MDd and /MD).
The error indicates your program is building with "Statically linked" version of the C/C++ Runtime.
See Microsoft Docs
You didn't mention what compiler toolset you are using other than "not VS".
See directx-vs-templates for a bunch of 'basic device and present loop' samples. If you don't use VS, there are 'CMakeLists.txt' available on that site.
A: I was confused once again with DirectXTex and DirectXTK.
I resolved the issue by:
*
*Removing DirectXTex
*Downloading DirectXTK
*Running the DirectXTK_Desktop_2019_Win10 solution
*Changing the Build to Release and x64
*Opening the properties
*Finding the option Runtime Library
*Choosing Multi-threaded /MT
*Building the solution
In my source file, I include:
#include <WICTextureLoader.h> and #include <DDSTextureLoader.h>
I can now link to the generated static library directxtk.lib, without getting errors.
Plus. If there are people who want to use things like /NODEFAULTLIB:library, but you don't use cl or Visual Studio, you can use the #pragma directive in your source file like this:
#pragma comment(linker, "/NODEFAULTLIB:MSVCRT")
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/65409371",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: WSO2IS - Disable Embedded LDAP - deployment.toml How can I disable Embedded Ldap on Identity Server 5.10.0 version? I'm checking conf/identity/embedded-ldap.xml and enable property is true.
<EmbeddedLDAP>
<Property name="enable">true</Property>
<Property name="port">${Ports.EmbeddedLDAP.LDAPServerPort}</Property>
<Property name="instanceId">default</Property>
.....
I couldn't find how I can disable. If I overwrite this file when docker starts it came back to true.
A: *
*If you have <wso2is-5.10.0-home>/repository/resources/conf/templates/repository/conf/identity/embedded-ldap.xml.j2 file and it's enable property value under <EmbeddedLDAP> is templated as {{embedded_ldap.enable}} (shown below),
<EmbeddedLDAP>
<Property name="enable">{{embedded_ldap.enable}}</Property>
<Property name="port">${Ports.EmbeddedLDAP.LDAPServerPort}</Property>
<Property name="instanceId">default</Property>
.....
</EmbeddedLDAP>
you can use the following deployment.toml config
[embedded_ldap]
enable = false
*If the <wso2is-5.10.0-home>/repository/resources/conf/templates/repository/conf/identity/embedded-ldap.xml.j2 file contains the EmbeddedLDAP config's enable property value as hardcoded to "true", you can change it to false and restat the server to change the config in embedded-ldap.xml.
<EmbeddedLDAP>
<Property name="enable">true</Property>
<Property name="port">${Ports.EmbeddedLDAP.LDAPServerPort}</Property>
<Property name="instanceId">default</Property>
.....
</EmbeddedLDAP>
*If you don't have <wso2is-5.10.0-home>/repository/resources/conf/templates/repository/conf/identity/embedded-ldap.xml.j2 file, the property value changes in embedded-ldap.xml won't be replaced once the server is restarted.
A: In WSO2 Identity Server 5.10.0 the configurations are managed by a centralized toml file which is called as deployment.toml. We can add the following configuration to the deployment.toml file which is located in <IS_HOME>/repository/conf directory.
[embedded_ldap]
enable = false
A: In WSO2 Identity Server 5.10.0 version the file embedded-ldap.xml.j2 doesn't come inside
wso2is-5.10.0/repository/resources/conf/templates/repository/conf/identity so I needed to copy the file from this link: embedded-ldap.xml.j2 and put inside my configuration for docker container conf/is-as-km/repository/resources/conf/templates/repository/conf/identity
docker-compose.yml
...
volumes:
- ./conf/is-as-km:/home/wso2carbon/wso2-config-volume
ports:
- "9444:9443"
...
After that I put the property in deployment.toml:
[embedded_ldap]
enable = false
And everything worked as shown in docker log:
cup-is-as-km ... NFO {org.wso2.carbon.identity.oauth.uma...} - UMA Grant component activated successfully.
cup-is-as-km ... INFO {org.wso2.carbon.ldap.server.DirectoryActivator} - Embedded LDAP is disabled.
cup-is-as-km ... INFO {org.wso2.carbon.mex.internal.Of...} - Office365Support MexServiceComponent bundle activated successfully..
Based on the last answers and comments I reached the solution ;).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/66445389",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Why my picture resolution are very bad with UIImage in swift I use the following function to make picture photoOutput?.capturePhoto(with: AVCapturePhotoSettings(), delegate: self).
When I save the picture his weight is only about 200Ko however the size with the AVCaptureSession.presset is .hight so it's make 1920x1080.
there is m'y prepare function to change view where all "image" var are UIImage :
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showPhoto_Segue"{
let previewVC = segue.destination as! PreviewViewController
previewVC.image = self.image
}
}
in my photoOutput function I have :
func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto photo: AVCapturePhoto, error: Error?) {
if let imageData = photo.fileDataRepresentation(){
image = UIImage(data: imageData)
Arrayimages.append(image!)
Arraytimes.append(Float64(CMTimeGetSeconds(currentCamera!.exposureDuration)))
}
if pictureNumber < 11 {
pictureNumber += 1
DispatchQueue.main.asyncAfter(deadline: .now() + newDurationSeconds + 0.3, execute: {
self.photoOutput?.capturePhoto(with: AVCapturePhotoSettings(), delegate: self)
})
}
else{
image = OpenCVWrapper.hdrImaging(Arrayimages, Arraytimes)
performSegue(withIdentifier: "showPhoto_Segue", sender: nil)
}
}
In my OpenCVWrapper.mm I have :
+(UIImage *) hdrImaging:(NSArray *)images :(NSArray *)times{
std::vector<cv::Mat> imagesVector;
std::vector<float> timesVector;
for (int i = 0; i < images.count; i++) {
UIImage * imageToUse = images[i];
UIImageWriteToSavedPhotosAlbum(imageToUse, nil, nil, nil);
}
//some traitment
return response;
}
when I use UIImageWriteToSavedPhotosAlbum function my pictures are already compressed but I don't know why and the weight of the file is to small to get good quality !
what can I do to get full resolution of my piture in 1920x1080 ?
maybe with AVCapturePhotoSettings ??
thanks!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/54555285",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Am I correct in my understanding of selectors?
.top-menu {
margin: 50px auto;
padding: 0;
list-style: none;
width: 610px;
height: 35px;
box-shadow: 0 3px 4px #8b8b8b;
background-color: #dadada;
}
.top-menu li {
float: left;
border-right: 1px solid #929292;
}
.top-menu li a:link {
color: black;
text-decoration: none;
text-align: center;
display: block;
width: 100px;
height: 35px;
line-height: 35px;
}
.top-menu li a:visited {
color: black;
}
ul li a:hover {
background-color: #555;
color: #fff;
}
<head>
<meta charset="UTF-8">
<title>pseudo selecotor</title>
</head>
<body>
<nav>
<ul class="top-menu">
<li><a href="#">menu1</a></li>
<li><a href="#">menu2</a></li>
<li><a href="#">menu3</a></li>
<li><a href="#">menu4</a></li>
<li><a href="#">menu5</a></li>
<li><a href="#">menu6</a></li>
</ul>
</nav>
</body>
i run this page,
if hover on menu, text color is black.
but in css, hover's text color is white.
if i change hover's selector
from ul -> to .top-menu
text color is white.
Is this because I gave black as class selector and white as tag selector?
Is it because the class is applied after applying the tag?
A: It's because classes have higher specificity value than Elements and Pseudo Elements. In your case .top-menu have higher specificity than the element ul, therefore its style is followed/used. Refer to this table for specificity:
More on specificity here.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/70888604",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to rearrange data frame so that values in one column are row names? I have a data frame containing 450K methylation beta-values for approx. 450 probes for two samples. This data is displayed in three columns, and looks like this:
>head(ICGC)
submitted_sample_id probe_id methylation_value
1 X932-01-4D cg00000029 0.6
2 X932-01-6D cg00000029 0.4
3 X932-01-4D cg00000108 0.3
4 X932-01-6D cg00000108 0.7
5 X932-01-4D cg00000109 0.9
6 X932-01-6D cg00000109 0.1
I would like to rearrange this data.frame so that the probe IDs are the rownames and the sample IDs are the column names, so that it looks like this:
>head(ICGC_2)
X932-01-4D X932-01-6D
cg00000029 0.6 0.4
cg00000108 0.3 0.7
cg00000109 0.9 0.1
I have tried:
>library(tidyverse)
ICGC_2 <- ICGC %>% remove_rownames %>% column_to_rownames(var = "probe_id")
But this didn't work as each probe ID in ICGC appears twice in the column (as there are two samples). I also tried:
hello <- data.frame(ICGC[,-2], row.names = ICGC[,2])
But this had the same problem. The reason I want to rearrange this data in this way is because I would like to convert the beta values to M-values and use this data as the object in cpg.annotate (available through Bioconductor package DMRcate) - cpg.annotate requires the object to have unique Illumina probe IDs as rownames and unique sample IDs as column names.
Thank you!
A: You are very close. spread funciton from the tidyr package is what you need.
library(tidyverse)
ICGC_2 <- ICGC %>%
spread(submitted_sample_id, methylation_value) %>%
remove_rownames() %>%
column_to_rownames(var = "probe_id")
ICGC_2
X932-01-4D X932-01-6D
cg00000029 0.6 0.4
cg00000108 0.3 0.7
cg00000109 0.9 0.1
Data:
ICGC <- read.table(text = "submitted_sample_id probe_id methylation_value
1 'X932-01-4D' cg00000029 0.6
2 'X932-01-6D' cg00000029 0.4
3 'X932-01-4D' cg00000108 0.3
4 'X932-01-6D' cg00000108 0.7
5 'X932-01-4D' cg00000109 0.9
6 'X932-01-6D' cg00000109 0.1",
header = TRUE, stringsAsFactors = FALSE)
A: In base R you can do this:
wICGC <- reshape(ICGC, idvar = "probe_id",
timevar = "submitted_sample_id", direction = "wide")
wICGC <- data.frame(wICGC[,-1], row.names=wICGC[,1])
wICGC
# methylation_value.X932.01.4D methylation_value.X932.01.6D
# cg00000029 0.6 0.4
# cg00000108 0.3 0.7
# cg00000109 0.9 0.1
A: For a different perspective, you can also use melt in reshape.
library(reshape)
m <- melt(IGC, id=c("submitted_sample_id", "probe_id"))
cast(m, probe_id~submitted_sample_id)
> cast(m, probe_id~submitted_sample_id)
probe_id X932-01-4D X932-01-6D
1 cg00000029 0.6 0.4
2 cg00000108 0.3 0.7
3 cg00000109 0.9 0.1
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/45757978",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Is it possible to subclass the immutable date class and override the __str__ method? I am trying to subclass the immutable date class in Python, but I also need to override the __str__ method. So far, I have the following:
from datetime import date
class Year(date):
def __new__(cls, year):
return super(Year, cls).__new__(cls, year, 1, 1)
def __str__(self):
return self.strftime('%Y')
Constructor works fine, but the __str__ method is completely ignored when I try to print the object. I have seen a few samples subclassing other immutable classes such as int and float. All of them were using the same convention. Am I missing something? Is there anything special for the date object?
UPDATE:
It seems that there is nothing wrong with the code. I was trying to print a Year object inside a Django template and since Django formats date objects using a localizable format __str__ method was being ignored.
A: Add a return to the __str__ method.
UPDATE:
I ran your updated code on my machine, and it works fine:
aj@localhost:~/so/python# cat date2.py
from datetime import date
class Year(date):
def __new__(cls, year):
return super(Year, cls).__new__(cls, year, 1, 1)
def __str__(self):
return self.strftime('%Y')
y=Year(2011)
print str(y)
aj@localhost:~/so/python# python date2.py
2011
A: If this is your complete code you are missing the return statement:
def __str__(self):
return self.strftime('%Y')
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/6195232",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: OpenAPI definition not generating Scala properties I'm using the springdoc-openapi-ui plugin with spring-boot to generate an OpenAPI definition. It doens't seem to detect properties from Scala based objects. Java defined objects are working fine. Is there a way to fix this?
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-ui</artifactId>
<version>1.6.9</version>
</dependency>
Controller:
case class OpenApiTest(a: String, b: String)
@RestController
class TestController {
@GetMapping(path=Array("/open-api-test"))
def openApiTest = OpenApiTest("a", "b")
}
Result of /v3/api-docs. Source is a Java class, OpenApiTest Scala:
"components": {
"schemas": {
"Source": {
"type": "object",
"properties": {
"path": {
"type": "string"
}
}
},
"OpenApiTest": {
"type": "object"
}
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72703028",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Change AppBar back icon size in Flutter Here's the current AppBar code:
AppBar(
iconTheme: IconThemeData(
color: Colors.black,
size: 100 // This isn't performing any changes
),
centerTitle: false,
backgroundColor: Colors.white,
title: Text(
title,
style: TextStyle(color: Colors.black87,
),
elevation: 1.0,
);
Current size attribute from IconThemeData not making any change.
A: Try this you need to use leading
*
*A widget to display before the title.
SAMPLE CODE
AppBar(
title: new Text("Your Title"),
leading: new IconButton(
icon: new Icon(Icons.arrow_back,size: 50.0,),
onPressed: () => {
// Perform Your action here
},
),
);
OUTPUT
A: You can use Transform.scale widget and wrap IconButton with it. This widget has scale property which you can set based on your need. Working sample code below:
appBar: AppBar(
leading: Transform.scale(
scale: 2,
child: IconButton(
icon: Icon(Icons.arrow_back, color: Colors.black),
onPressed: () {}
)
),
centerTitle: false,
backgroundColor: Colors.white,
title: Text(
'test',
style: TextStyle(color: Colors.black87,
),
// elevation: 1.0,
)),
Hope this answers your question.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/59487873",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to fetch both IPv4 and IPv6 on dual stack OS I have dual stack machine .
My problem is i am getting only IPv4 using
InetAddress address = InetAddress.getLocalHost();
and If i use Network Interface API then i get all the IP address in which includes my MAC addrres as well in the form of IP address.
why-do-i-get-multiple-global-ipv6-addresses-listed-in-ifconfig
Now is there any way i can get both IPv4 and IPv6 of my machine.
A: In Linux,
InetAddress.getLocalHost() will look for the hostname and then return the first IP address assigned to that hostname by DNS. If you have that hostname in the file /etc/hosts, it will get the first IP address in that file for that hostname.
If you pay attention this method returns only one InetAddress.
If you haven't assigned a hostname, most probably it will be localhost.localdomain. You can set the hostname with command line:
hostname [name]
or by setting it in file /etc/sysconfig/network
If you want to get all ip addresses, including IPv6, assigned to a hostname you can use:
InetAddress.getAllByName(InetAddress.getLocalHost().getHostName());
If you want to get all ip addresses, including IPv6, assigned to a host's network interfaces, you must use class NetworkInterface.
Here I'm pasting some example code:
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.net.SocketException;
import java.net.NetworkInterface;
import java.util.*;
public class Test
{
public static void main(String[] args)
{
try
{
System.out.println("getLocalHost: " + InetAddress.getLocalHost().toString());
System.out.println("All addresses for local host:");
InetAddress[] addr = InetAddress.getAllByName(InetAddress.getLocalHost().getHostName());
for(InetAddress a : addr)
{
System.out.println(a.toString());
}
}
catch(UnknownHostException _e)
{
_e.printStackTrace();
}
try
{
Enumeration nicEnum = NetworkInterface.getNetworkInterfaces();
while(nicEnum.hasMoreElements())
{
NetworkInterface ni=(NetworkInterface) nicEnum.nextElement();
System.out.println("Name: " + ni.getDisplayName());
System.out.println("Name: " + ni.getName());
Enumeration addrEnum = ni.getInetAddresses();
while(addrEnum.hasMoreElements())
{
InetAddress ia= (InetAddress) addrEnum.nextElement();
System.out.println(ia.getHostAddress());
}
}
}
catch(SocketException _e)
{
_e.printStackTrace();
}
}
}
For this example, I got code from one of the responses in InetAddress.getLocalHost().getHostAddress() is returning 127.0.1.1
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/30798888",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Why swift compiler doesn't find Alamofire? I try to install Alamofire. I really haven't possibility to use cocoaPods, so I try to install it manually.
The steps I took:
*
*I download Alamofire from GitHub.
*In folder drag Alamofire.xcodeproj and drop into my projects
*In my projects in "generals" in "Embedded Binaries" add framework for iOs
*import Alamofire in code
When I want to make a request I enter "Alamofire" and swift offers me "AlamofireExtended", "AlamofireNotifications", "AlamofireExtension" and "AlamofireVersionNumber".
I try to enter request manually, but nothing happen
A: Did you follow their guidelines for manual installation?
You should run
$ git init
(if your project is not initialized as a git repository)
and then
$ git submodule add https://github.com/Alamofire/Alamofire.git
(so that you can add it as a submodule)
I would also suggest you to delete the derived data, clean the project and then build it again.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/55831700",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: On orientation change button touchlistener not working I have two layouts table.xml(port) and table.xml(land) which from there names one of the landscape and other for the protrait.
I have included this layout in another layout called fragment_test.xml like this:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<include layout="@layout/table"/>
</RelativeLayout>
And this is my fragment code of the above layout fragment_test:
public class Fragment_test extends Fragment implements View.OnTouchListener{
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mytable= (LinearLayout) getActivity().findViewById(R.id.mytableid);
typeface = Typeface.createFromAsset(getActivity().getAssets(), "fonts/font.ttf");
for (int i = 0; i < table1.getChildCount(); i++) {
LinearLayout mychild = (LinearLayout) mytable.getChildAt(i);
for (int j = 0; j < mychild.getChildCount(); j++) {
Button b = (Button) child.getChildAt(j);
b.setTypeface(typeface);
b.setOnTouchListener(this);
}
}
}
}
//this is called when a button is touched
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
return true;
}
}
So basically I have several buttons in the table layout I am looping through to setontouchlistener for each one of them.
So my problem is when I switch from protrait to landscape or the opposite the touchlistener of the button does not work anymore and even the typeface doesn't work anymore when changing the layout.
> Edit: this is the activity code
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Home");
FragmentManager manager = getFragmentManager();
manager.beginTransaction().add(R.id.container, new Fragment_test(), "mytag").commit();
}
A: Try calling setRetainInstance(true) after super.onActivityCreated(savedInstanceState);
here is the documentation of setRetainInstance(boolean)
Activity :
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
FragmentManager manager = getSupportFragmentManager();
Fragment myFragment = manager.findFragmentByTag("myFragment");
if (myFragment == null) {
myFragment = new ParentFragment();
}
manager.beginTransaction().add(R.id.fragmentHolder, myFragment, "myFragment").commit();
}
}
Fragment:
public class ParentFragment extends Fragment{
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setRetainInstance(true);
}
}
A: I am just give you the information.
you can check the Orientataion of device this way and set it layout.
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (newConfig.orientation==Configuration.ORIENTATION_LANDSCAPE){
setContentView(R.layout.table_horizontal);
button1 = (Button)findViewById(R.id.button1);
button1.setOnClickListener(this);
}else if (newConfig.orientation==Configuration.ORIENTATION_PORTRAIT){
setContentView(R.layout.table_vertical);
button1 = (Button)findViewById(R.id.button1);
button1.setOnClickListener(this);
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/38504941",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: HTML Code to display UIAlertView on iOS I've gone to different websites on my iPhone that will pop up a UIAlertView when it loads. How is this accomplished? I want to put some code on my page to pop up a UIAlertView when viewed on an iPhone.
A: You can make use of bridecall from the js to native code to trigger the UIAlertView..
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/21695051",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: SQL Server compare two tables rows with identical columns and return changed columns I want to compare two tables with the same columns:
*
*product - Id, Name, Description
*Temp_Product - Id, Name, Description
Now update done by user will be saved into Temp_Product. When admin will see the details of that product I need to show the changes done by user. I want to compare both tables with a query and return columns that have changed from Product to Temp_Product.
Please suggest me better way to do this?
A: Select p.id,p.name as orgn,t.name as altn,p.descripion as orgd,t.description as altd
from product p
join tmp_product t
on t.id=p.id and (t.name<>p.name or t.description <> p.description)
A:
I want to compare both tables with a query and return columns that
have changed from Product to Temp_Product
Since the two tables have the same structure, you can use the EXCEPT set oeprator for this:
SELECT * FROM Temp_Product
EXCEPT
SELECT * FROM Product;
SQL Fiddle Demo
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/13428993",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Applescript Copy All File from USB to Folder Could you help me to make this script working ?
property ignoredVolumes : {"DD APPLE", "MobileBackups"}
tell application "System Events"
set Destination_Folder to folder "/Users/Joseph/Downloads/Test" of startup disk
set rootVolume to disk item (POSIX file "/Volumes" as text)
set allVolumes to name of every disk item of rootVolume
repeat with aVolume in allVolumes
if aVolume is not in ignoredVolumes then
copy every item of folder (aVolume) to Destination_Folder
end if
end repeat
end tell
The problem is in the line copy every item of folder (aVolume) to Destination_Folder - the error message I get is Can’t get every file of "NO NAME". (No Name is my USB key.)
Thank you very much for your help.
A: System Events doesn't have a "copy" command. Where did you get that? You might try "move" instead. Plus "aVolume" is not a folder, it's a disk. You probably want to change "folder aVolume" to "disk aVolume". And you might even need to use "disk (contents of aVolume)"
EDIT: Try the following script. I didn't test it but it should work. Good luck.
property ignoredVolumes : {"DD APPLE", "MobileBackups", "home", "net"} -- leave home and net in this list
set Destination_Folder to ((path to downloads folder as text) & "Test:") as alias
set mountedVolumes to list disks
repeat with i from 1 to count of mountedVolumes
set thisVolume to item i of mountedVolumes
if thisVolume is not in ignoredVolumes then
tell application "Finder"
set theItems to items of disk thisVolume
move theItems to Destination_Folder
end tell
end if
end repeat
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/28172682",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Discordbot javascript react to mentions I'm completely new to Javascript and i would like to make a discord bot.
I have a bot already running with a few commands, now i would like to add something that posts a reaction whenever someone specific is tagged.
client.on('message', message => {
var user = "123456479879541";
if(message.mentions.users.id === user) {
message.channel.send('ok');
}
});
What do i have to do to make it work?
A: Message.mentions.users is a collection. You need to determine if your ID is in the collection. You are comparing equality, which since user is not a collection will always be false. Replace this with a .has You can then add a react to the message. For that, there is a guide here describing how to get a unicode reaction as shown below.
var user = "123456479879541";
if(message.mentions.users.has(user)) {
message.channel.reply('ok');
message.react('');
}
A: You should use Message#react()
So basically for example you could do:
client.on('message', message => {
var user = "123456479879541";
const reaction = message.guild.emojis.find(emoji => emoji.name === 'EMOJI NAME')
if(message.mentions.users.has(user)) {
message.channel.reply('ok');
message.react(reaction)
}});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/60774146",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to get index position in textBox using javascript How do i get the index position when user click in textBox using JavaScript?
for example in my textBox have this string :
`this is best| of the world`.
it should be return 13.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/13723624",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Link Resources in c# Project I have 2 files, 1 is form1.cs and the second is form1.resx. they should be linked but are not. how can I link the 2? if i just make sure the namespaces are the same will they automatically link to each other? do i need to clean the project?
A: Install VSCommand 2010.
Select two files then group two item from the context menu.
A: Right-click both files and click Exclude from project.
Then, click Show all Files on top of the Solution Explorer, then right-click the .cs file and click Include in project.
A: You mean one as a subtree of the other? If what SLaks says doesn't work you can edit the proj file.
I think it is like this, using the dependentupon xml
<Compile Include="FPtoICVService.cs">
<SubType>Component</SubType>
</Compile>
<Compile Include="FPtoICVService.Designer.cs">
<DependentUpon>FPtoICVService.cs</DependentUpon>
</Compile>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/3943889",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Personal Autoformat (Visual Studio C# / git) I have 2 different settings in visual studio, my personal and our company guidelines and a git repository where code should be commited with our company guidelines. Is it possible to automatically autoformat the code on opening the file with my personal settings? Then, when I finished working (either on save or preferably on git pre-commit) I would like to autoformat the files I worked on with our company guidelines.
Is there a way to achieve this?
EDIT: Language is C#.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73360698",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Cannot find element in Vue Js Applications I created vue js applications with visual studio 2017 . but the problem is when i run the applications , i got following errors in google chrome console windows .
[Vue warn]: Cannot find element: #intro
[Vue warn]: You are using the runtime-only build of Vue where the template compiler is not available. Either pre-compile the templates into render functions, or use the compiler-included build.
Here is the code for App.vue...
<template>
<div id="app">
<Home msg="Hello world!" />
</div>
</template>
<script>
import Home from './components/Home.vue';
import component1 from './components/component1.vue';
export default {
name: 'app',
components: {
Home,
component1
}
};
</script>
<style>
</style>
Here is the code for component1.vue..
<template>
<div class="intro" style="text-align:center;">
<h1>{{ message }}</h1>
</div>
</template>
<script type="text/javascript">
import Vue from 'vue';
new Vue({
el: '#intro',
data: {
message: 'My first VueJS Task'
}
});
</script>
<style scoped>
</style>
Here is the screen shot of the google console windows ..
A: You have set the class on the element instead of the id.
But that is irrelevant anyway because you do not need to any of this for a single file component; just do this instead (as you did for App.vue):
<template>
<div class="intro" style="text-align:center;">
<h1>{{ message }}</h1>
</div>
</template>
<script>
export default {
data() {
return {
message: 'My first VueJS Task'
}
}
}
</script>
Constructing a Vue component manually with new Vue() is only necessary for the root component instance.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/56910780",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: UWP: BackgroundTask open App Mainpage Is it possible to open my app by my own backgroundtask?
when i have a backgroudtask in windows universal platform, can i start or open my app.mainpage from there?
my backgroundtask checks periodicaly the clipboard and if it gets an hit, then it should open my app.
does this work with uwp or is uwp again a no-go software ?
any soltutions or ideas therefore?
A: You can do that by a toast. Here is an example.
var content =
$@"
<toast activationType='foreground' launch='args'>
<visual>
<binding template='ToastGeneric'>
<text>Open app</text>
<text>Your clipboard is ready.Open app</text>
</binding>
</visual>
<actions>
<action content='ok' activationType='foreground' arguments='check'/>
<action activationType='system' arguments='dismiss' content='cancel' />
</actions>
</toast>";
Windows.Data.Xml.Dom.XmlDocument toastDOM = new Windows.Data.Xml.Dom.XmlDocument();
toastDOM.LoadXml(content);
ToastNotification toast = new ToastNotification(toastDOM);
var notifier = ToastNotificationManager.CreateToastNotifier();
notifier.Show(toast);
And then if user press the ok button you must go in App.xaml.cs and handle that
protected override void OnActivated(IActivatedEventArgs args)
{
if (args.Kind == ActivationKind.ToastNotification)
{
var toastArgs = args as ToastNotificationActivatedEventArgs;
var arguments = toastArgs.Argument;
if (arguments == "check")
{
Frame rootFrame = Window.Current.Content as Frame;
if (rootFrame == null)
{
rootFrame = new Frame();
Window.Current.Content = rootFrame;
}
rootFrame.Navigate(typeof(YOURPAGEHERE));
Window.Current.Activate();
}
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/35794065",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: laravel 5 .. ubuntu .. command line I am working using laravel5 php framework on ubuntu and I have 2 problems
1- when I try to use the composer to require anything .. it doesnt work
2- when i tried to make some changes to illuminate/Html .. it doesn't work too
so after that when i tried to use the artisan to serve my project I got that error
PHP Fatal error: Class 'Illuminate\Html\HtmlServiceProvider' not found in /home/shaimaa/Sites/Laravel5/eoswdt/storage/framework/compiled.php on line 5617
exception 'Symfony\Component\Debug\Exception\FatalErrorException' with message 'Class 'Illuminate\Html\HtmlServiceProvider' not found' in /home/shaimaa/Sites/Laravel5/eoswdt/storage/framework/compiled.php:5617
Stack trace:
#0 /home/shaimaa/Sites/Laravel5/eoswdt/storage/framework/compiled.php(1500): Illuminate\Foundation\Bootstrap\HandleExceptions->fatalExceptionFromError(Array)
#1 [internal function]: Illuminate\Foundation\Bootstrap\HandleExceptions->handleShutdown()
#2 {main}
A: Just run the following in your composer
composer require "illuminate/html":"5.0.*"
Inside your config/app.php add the following codes inside it
In the 'providers' => [ ..]
'Illuminate\Html\HtmlServiceProvider',
And in the
'aliases' => [ ..]
'Form'=> 'Illuminate\Html\FormFacade',
'HTML'=> 'Illuminate\Html\HtmlFacade',
And then refresh the page you should find that it should be working.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/30425876",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: error when try to install flask in the virtual enviroment I just configure the environment to develop the flask based web app. All the things goes smoothly, but when I run my hello world app, the python interpret tell me no module named flask:
Traceback (most recent call last):
File "hello.py", line 1, in <module>
from flask import Flask
ImportError: No module named flask
but I seriously install flask.
When I get the error, i just run the command in the virtual environment, sudo pip install flask. Then, the console show the message:
(venv)ubuntu@localhost:/var/www/demoapp$ sudo pip install flask
Requirement already satisfied (use --upgrade to upgrade): flask in /usr/local/lib/python2.7/dist-packages
Requirement already satisfied (use --upgrade to upgrade): Werkzeug>=0.7 in /usr/local/lib/python2.7/dist-packages (from flask)
Requirement already satisfied (use --upgrade to upgrade): Jinja2>=2.4 in /usr/local/lib/python2.7/dist-packages (from flask)
Requirement already satisfied (use --upgrade to upgrade): itsdangerous>=0.21 in /usr/local/lib/python2.7/dist-packages (from flask)
Requirement already satisfied (use --upgrade to upgrade): markupsafe in /usr/local/lib/python2.7/dist-packages (from Jinja2>=2.4->flask)
Cleaning up...
Who can tell me how can I run my hello world flask app?
A: When you run
$ sudo pip install...
system pip will be used. So to install flask in current environment just run
$ pip install ...
or as:
$ /path/to/venv/bin/pip install ...
Or make your venv able to load global system packages by parameter --system-site-packages, while configure virtual environment.
A: If you are having the same trouble even if you have your virtualenv running, just make sure you didn't accidentally delete the files and attempt to execute pip in that folder you created for your venv... Like I did. :D
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/26679030",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to use the default value attribute of a select tag Now im working on a small task with a select tag like this
<select
name="selectmedgroup"
id="selectmedgroup"
value={selectedGroupValue}
onChange={filterOnSelectChange}
>
<option value="" defaultValue hidden>
-Select Group-
</option>
<option value="a">A</option>
<option value="b">B</option>
<option value="c">C</option>
<option value="d">D</option>
</select>
I want to get the value on change. Here is my on change function and state
const [selectedGroupValue, setSelectedGroupValue] = useState();
const filterOnSelectChange = (e) => {
setSelectedGroupValue(e.target.value);
console.log(selectedGroupValue);
};
Everything seems to work fine but when I log out the selected option first if I choose A for the first time I get undefined on the logs. If I choose B I get A logged out. If I choose C I get B logged out.
I don't think it's my ordering that's wrong. Remember I don't want to have an initial value on the state because this will be just a selection that I will use to filter what the user sees on the page. So for the first time on the component mount, nothing should be filtered.
I have a feeling that the problem is the first Option tag with the -Select Group- . Is there any way I can avoid using that first options tag because it is just like a placeholder whose value I don't need to be selected?
How can I get the correct values? Please help
A: Try to console your selectedGroupValue on useEffect hook , solve it like this
import React, { useState } from 'react';
const App = () => {
const [selectedGroupValue, setSelectedGroupValue] = useState();
const filterOnSelectChange = (e) => {
setSelectedGroupValue(e.target.value);
};
React.useEffect(() => {
console.log(selectedGroupValue);
}, [selectedGroupValue]);
return (
<>
<select
name="selectmedgroup"
id="selectmedgroup"
value={selectedGroupValue}
onChange={filterOnSelectChange}
>
<option value="" defaultValue hidden>
-Select Group-
</option>
<option value="a">A</option>
<option value="b">B</option>
<option value="c">C</option>
<option value="d">D</option>
</select>
</>
);
};
export default App;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72097974",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: two digit year as primary key in sql server I have a table with these columns:
ID int,
d date
Now what I need is to define the primary key in such a way that ID would be unique for each year; meaning that there can not be two same IDs in 2004, but it is possible to have two same IDs in two different years.
Like:
insert into myTable values(1, '1-1-2004'), (1, '1-1-2005')
but not like:
insert into myTable values(1, '3-1-2005'), (1, '1-1-2005')
I tried this:
primary key(ID, datepart(YY, d))
but I get syntax error.
A: One way of doing this, if you can alter the table structure, is to add a persisted computed column for the year part, and then add a primary key for (id, computer_col), like this:
CREATE TABLE myTable (
id INT NOT NULL,
d DATE NOT NULL,
y AS DATEPART(YEAR,d) PERSISTED NOT NULL,
PRIMARY KEY(id,y)
)
I'm not saying this is a good solution in any way, but it should work. Using a trigger on insert or a check constraint might be better.
Using your test data this will allow the first insert statement, but disallow the second as it violates the primary key constraint.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/25271922",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Tap UIImageView with no alpha response? I have an image which has a relatively large area of transparency, alpha space. So is there a way I can detect a tap on this UIImageView but not have any response if the user taps the alpha area?
A: This is theoretical and I don't have code to add, but you could create an identical button and add it for UIControlStateTouched so there's no change when the button/image is touched.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/10665511",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to get Primary MX IP from domain in Bash I am trying to write a bash script that will from a domain name find it MX records, from them figure out which is the primary (they are not always in order) and then find its IP.
(when there are more then one primary MX the first one found would be ok)
For example:
./findmxip.sh gmail.com
Would give me 173.194.71.26. For me to do this I need to host gmail.com
then find the primary MX in the results and host it, getting its IP.
A: To get exactly 0 or 1 answers:
dig +short gmail.com mx | sort -n | nawk '{print $2; exit}' | dig +short -f -
You'll need a non-ancient dig that supports +short.
As noted there may be more than one "primary" MX as the preferences need not be unique. If you want all the IP addresses of all of the lowest preference records then:
dig +short oracle.com mx | sort -n |
nawk -v pref=65536 '($1<=pref) {pref=$1; print $2}' |
dig +short -f - | uniq
This does not handle the case where there is no MX record and the A record accepts email, an uncommon but perfectly valid configuration.
Sadly all the dig versions I've tested return 0 whether the domain exists or not (NXDOMAIN), and whether any MX records exist or not. You can catch a DNS time-out (rc=9) though. The related host command does return a non-zero rc with NXDOMAIN, but its behaviour is a little inconsistent, it's messy to script and the output harder to parse.
A poor man's error-checking version (inspired by tripleee's comment) that might be slightly more robust depending on your host command is:
DOMAIN=gmail.com
if ! host -t any $DOMAIN >/dev/null 2>&1 ; then
echo "no such domain"
elif ! host -t mx $DOMAIN >/dev/null 2>&1; then
echo "no MX records"
else
dig +short $DOMAIN mx | sort -n | nawk '{print $2; exit}' | dig +short -f -
fi
(Perversely, you may require an older version of host (bind-8.x) for the -t mx test to work, newer versions just return 0 instead.)
This is just about the point people start backing away nervously asking why you're not using perl/python/$MFTL.
If you really need to write a robust version in bash, check out the djbdns CLI tools and debugging tools which are rather easier to parse (though sadly don't set user exit codes either).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/15208095",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Axios request with Contact forms 7 I'm using contact forms 7, and in my form submission I use this function:
const formData = {
'your-name':'John Doe',
'your-email': 'johndoe@mail.com',
}
axios({
method: 'POST',
url: 'https://0xsociety.com/wp-json/contact-form-7/v1/contact-forms/258/feedback',
headers: {
"content-type": "multipart/form-data",
},
data: formData,
})
But it doesnt work, i get errors saying fields are empty.
But I tried with postman and it works perfectly when i do it manually
How would I get my axios post request to mimic this:
https://gyazo.com/e1ffe5bcc3f943a074d9b9e2c32b162d
A: I figured this out by using postman in my app:
import request from 'postman-request'
const formData = {
'your-name': name,
'your-email': email,
'your-subject': inquiries.find(x=> x.value === inquiry).text,
'file-871': file
}
request.post('https://your-domain/wp-json/contact-form-7/v1/contact-forms/your-form-id/feedback',{ form: formData}, function(err,httpResponse,body){
if(err) {
console.log(err)
}
else {
console.log(body)
}
})
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/68186075",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Angular 9 - how to inject dynamic parameters into a service constructor I need to make requests to a backend url which comes in this form:
localhost:8000/myapp/item1/:id1/item2/:id2/item3
where id1 and id2 are dynamic numbers.
I've thought using a service that takes 2 arguments in the constructor, something like this
export class Item3Service {
private id1: number;
private id2: number;
constructor(
id1: number,
id2: number
) {
this.id1 = id1;
this.id2 = id2;
}
getList() {/**** implementation here ****/}
getDetail(id3: number) {/**** implementation here ****/}
create() {/**** implementation here ****/}
update(id3: number) {/**** implementation here ****/}
delete(id3: number) {/**** implementation here ****/}
}
I really don't know how to inject parameters into the constructor. I also need to use this service inside a resolver and again, how can I pass parameters to it in a resolver?
Creating injection token sounds useless in this case because the token value should change every time. I've run out of ideas
A: I don't know where you get the dynamic ids, but you could actually maybe put them in the providers array and use dependency injection like you would with injection tokens. If it is possible to create a factory method for the ids of course
Service
export class Item3Service {
constructor(
@inject(LOCALE_ID) private locale: string) {}
}
app.moudle.ts
@NgModule({
providers: [
{ provide: LOCALE_ID, useFactory: () => window.navigator.language}
]
})
Edit
Since the ids are part of your route, I would do it like this
Component
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { MyServiceService } from '../my-service.service';
@Component({
selector: 'app-routed',
templateUrl: './routed.component.html',
styleUrls: ['./routed.component.scss']
})
export class RoutedComponent implements OnInit {
constructor(private route: Router, private myService: MyServiceService) { }
ngOnInit(): void {
this.myService.setUrl(this.route.url)
}
}
Service
import { Injectable } from '@angular/core';
import { ReplaySubject, Observable } from 'rxjs';
import { share, switchMap } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class MyServiceService {
private _url$: ReplaySubject<string> = new ReplaySubject<string>(1);
private _mydata$: Observable<string>;
get myData$() { return this._mydata$.pipe(share()); }
constructor() {
this._mydata$ = this._url$.pipe(
switchMap(url => {
const parsedUrl = this.parseUrl(url);
return this.callBackend(parsedUrl)
})
)
}
setUrl(url: string) {
this._url$.next(url);
}
private callBackend(parsedUrl): Observable<string> {
// call backend
}
private parseUrl(url: string): number[] {
// parse ids
}
}
A: It's better for your Service to be stateless, it will bring down the complexity of your app and spare you some issues and debugging and it's just not necessary in your case because you can always get item1Id and item2Id from your activated route, so let the activated route hold the state of your application (in this case the state is what Item1Id and Item2Id are selected) and create a stateless service that you can call from anywhere and that holds the logic of your Item API.
Here is how I envision your service to be (Keep in mind that this is just an example to take into consideration since I don't know exactly your semantics and use cases)
ItemService
export class ItemService {
constructor(private http: HttpClient) {}
getList(item1Id: string, item2Id: string) {
/* Call to Get List endpoint with Item1Id and Item2Id */
}
getDetails(item1: string, item2: string, item3: string) {
/* Call to Get Details endpoint with Item1Id and Item2Id and Item3Id */
}
}
Then you can use this service everywhere, as long as you have access to the ActivatedRouteSnapshot or ActivatedRoute
Example Use in Resolver for Route item1/:item1Id/item2/:item2Id
export class ItemResolver implements Resolve<any> {
constructor(private itemService: ItemService) {}
resolve(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<any> {
return this.itemService.getList(route.params['item1Id'], route.params['item2Id']);
}
}
Example Use in Component for Route item1/:item1Id/item2/:item2Id to get Item 3 details
export class HelloComponent {
constructor(private route: ActivatedRoute, private itemService: ItemService) {}
getDetails(item3Id) {
this.route.params.pipe(
take(1),
map(({ item1Id, item2Id }) => {
console.log(this.itemService.getDetails(item1Id, item2Id, item3Id))
})
).subscribe();
}
}
Here is a working StackBlitz demonstrating this : https://stackblitz.com/edit/angular-ivy-h4nszy
You should rarely use stateful services (unless it's really necessary and even in that case I recommend using something like ngrx library to manage your state) with the information that you have given though, you really don't need to be passing parameters to the constructor of your service, you should keep it stateless and pass the parameters to your methods.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/63363102",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: puts implementation in assembly with nasm x86-64 I'm new to assembly and I'm trying to work on an implementation of the C function puts in assembly with nasm x86-64 on my Ubuntu.
Everything was fine until I write the tests for the function: there is a behavior that I can not reproduce:
When I send char *str = strdup(""); to my puts function (alias ft_puts), my function return an error instead of printing a newline like the original puts function.
Here is my puts implementation (ft_puts.s):
section .data
new_line db 10 ; new line
section .text
global ft_puts
extern strlen
ft_puts: ; Alias int puts(const char *s)
call strlen
push rax ; Number of printed chars have to be returned by ft_puts
cmp rax, 0
jg print_string ; if length > 0, print string
cmp rax, 0
jz print_newline ; else if length == 0 (jle or <= 0, give the same result to my problem), print new line char
jmp error ; else go to error
print_string:
mov rsi, rdi ; string arg for write
mov rdi, 1 ; file_descriptor arg for write
mov rdx, rax ; length arg returned by ft_strlen for write
mov rax, 1 ; write
syscall
test rax, rax
jle error ; if write failed, go to error
jmp print_newline ; else print new line char
print_newline:
mov rsi, new_line ; new line as string arg for write
mov rdx, 1 ; new line string length
mov rax, 1 ; write
syscall
test rax, rax
jle error ; if write failed, go to error
jmp success ; else go to success
success:
pop rax ; Get number of chars printed by print_string
inc rax ; Add new line printed by print_newline to this number
jmp end
error:
pop rax
mov rax, -1 ; Return EOF (alias -1) on error
jmp end
end:
ret
Sorry if my code looks terrible, I started assembly a week ago.
I'm new to Stack Overflow and the help center told me to give a code for testing my code. So, here is a main.c:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
int ft_puts(const char *s);
int main(void)
{
char *str;
int ret[2];
str = strdup(".");
write(1, "[", 1);
ret[0] = puts(str);
write(1, "]", 1);
write(1, "\n", 1);
write(1, "[", 1);
ret[1] = ft_puts(str);
write(1, "]\n", 2);
printf("puts return value : %d | ft_puts return value : %d\n\n", ret[0], ret[1]);
free(str);
str = strdup("");
write(1, "[", 1);
ret[0] = puts(str);
write(1, "]", 1);
write(1, "\n", 1);
write(1, "[", 1);
ret[1] = ft_puts(str);
write(1, "]\n", 2);
printf("puts return value : %d | ft_puts return value : %d\n", ret[0], ret[1]);
free(str);
return (0);
}
And to compile and run this code :)
nasm -f elf64 ft_puts.s -o ft_puts.o
gcc -c main.c
gcc main.o ft_puts.o -o test
./test
The problem seems to be in my print_newline label but I can't find it. If someone can help me ? (It's hard to get some help on assembly language around me irl)
(I don't know if should include C tag to my question too haha, so much questions)
A: Two problems. One, the call strlen is allowed to clobber some registers which include rdi and you need that later. So, surround the call strlen with push rdi and pop rdi to save and restore it.
Second, you do not initialize rdi in the print_newline block. You need to set it to 1 for stdout just like you did in the print_string block.
PS: You should learn to use a debugger.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/30744518",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Why does changing innerText value also changes innerHTML? I have a asp.net code that creates a button as follows:
<a href="#" id="button1" title="Maximize" onclick="function1('span1')" class="button"><span id="span1" class="iconMaximizeLightText">Maximize</span></a>
now in the javascript file I am doing the following inside the function1 function:
document.getElementById("button1").innerText = "Minimize";
document.getElementById("button1").value = "Minimize";
document.getElementById("button1").className = "iconMinimizeLightText";
What I noticed was before the line : "document.getElementById("button1").innerText = "Minimize";" is executed the value in "document.getElementById("button1").innerHTML" is
document.getElementById("button1").innerHTML = "<span id=span1 class=iconMaximizeLightText>Maximize</span>"
but after that line is executed the value in "document.getElementById("button1").innerHTML" is
document.getElementById("button1").innerHTML = "Minimize"
Why is innerHTML value changing as I only changed the innerText value ?
Thanks in advance.
P.S. Sorry this might be a stupid question but I have only started learning this language since a couple of weeks.
A: Both innerText and innerHTML set the HTML of the element. The difference is that innerText—by the way, you might want to use textContent instead—will escape the string so that you can't embed HTML content in it.
So for example, if you did this:
var div = document.createElement('DIV');
div.innerText = '<span>Hello</span>';
document.body.appendChild(div);
Then you'd actually see the string "<span>Hello</span>" on the screen, as opposed to "Hello" (inside a span).
There are some other subtleties to innerText as well, which are covered in the MDN article referenced above.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/21999375",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Why does this menu act screwy in IE? SOS I hope someone can help. This is driving me nuts.
You can see the page i'm having problems with at www.jomundayphotography.com/template.html.
The dropdown menu is working everywhere but Internet Explorer (all versions are having problems).
The Code:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<link href='http://fonts.googleapis.com/css?family=Droid+Sans:400,700' rel='stylesheet' type='text/css'>
<link href="css/navcss.css" rel="stylesheet" type="text/css"/>
<link href="css/csstest2.css" rel="stylesheet" type="text/css">
<script src="JavaScript/jq.js" type="text/javascript"></script>
<script src="JavaScript/easing.js" type="text/javascript"></script>
<script src="JavaScript/color.js" type="text/javascript"></script>
<script src="JavaScript/navjs.js" type="text/javascript"></script>
<script src="JavaScript/mainTest2.js" type="text/javascript"></script>
</head>
<body>
<div id="container">
<div id="header">
<img src="images/Logos/logo.png" id="logo" alt="Sinclairs Solicitors Logo"/>
<img src="images/Logos/conveyancingqualitylogo.gif" id="conveyancingQuality" alt="Conveyancing Quality"/>
<div id="motto">
<p>
<span id="motto1">Professional</span>
<span id="motto2">Experienced</span>
<span id="motto3">Approachable</span>
</p>
</div>
</div>
<div id="nav"><div id="navBar">
<ul>
<li id="aboutUsHeading"class="menuItem"><a href="#">about Us</a></li>
<li id="teamMenuHeading" class="menuItem">
<a href="#">the team</a>
<ul>
<li class="subMenuItem"><a href="#">Henry Drucker</a></li>
<li class="subMenuItem"><a href="#">Joanna Yianni</a></li>
</ul>
</li>
<li id="servicesMenuHeading" class="menuItem">
<a href="#">services</a>
<ul>
<li class="subMenuItem"><a href="#">Residential Property</a></li>
<li class="subMenuItem"><a href="#">Commercial Property</a></li>
<li class="subMenuItem"><a href="#">Company Commercial</a></li>
<li class="subMenuItem"><a href="#">Landlord and Tenant</a></li>
<li class="subMenuItem"><a href="#">Wills</a></li>
<li class="subMenuItem"><a href="#">Trust and Probate</a></li>
<li class="subMenuItem"><a href="#">Family Life</a></li>
<li class="subMenuItem"><a href="#">Employment</a></li>
<li class="subMenuItem"><a href="#">General Litigation</a></li>
<li class="subMenuItem"><a href="#">Personal Injury</a></li>
</ul>
</li>
<li id="contactMenuHeading" class="menuItem"><a href="#">contact us</a>
<ul>
<li class="subMenuItem"> <a href="#">find us</a></li>
</ul>
</li>
</ul>
</div></div> <!--end of navBar-->
<div id="content">
<div class="contentBox" id="sideBarLeft">
<div id="miniMenu">
<ul>
<li><a href="ResidentialProperty.html"><nobr>Residential Property</nobr></a></li>
<li><a href="CommercialProperty.html"><nobr>Commercial Property</nobr></a></li>
<li><a href="CompanyCommercial.html"><nobr>Company Commercial</nobr></a></li>
<li><a href="LandlordTenant.html"><nobr>Landlord and Tenant</nobr></a></li>
<li><a href="Wills.html"><nobr>Wills</nobr></a></li>
<li><a href="TrustandProbate.html"><nobr>Trust and Probate</nobr></a></li>
<li><a href="FamilyLaw.html"><nobr>Family Law</nobr></a></li>
<li><a href="Employment.html"><nobr>Employment</nobr></a></li>
<li><a href="GeneralLitigation.html"><nobr>General Litigation</nobr></a></li>
<li><a href="PersonalInjury.html"><nobr>Personal Injury</nobr></a></li>
</ul>
</div>
</div>
<div class="contentBox" id="galleryBox">
<div id="contentHolder">
<p id="p1">moving House?</p>
<p id="p3">At Sinclairs we have over<br/>25 years experience,<br/>helping our clients<br/>through the moving process,<br/>advising on how to stay<br/>in control of their rented<br/>properties,and in all areas<br/>of legal documentation.</p>
<p id="p4">renting?</p>
<p id="p7">need to make a Will?</p>
<p id="contact">0208 203 3344 <br/>info@sinclairssolicitors.com<button class="myButton" email><a href="#">email us</a></button><br/>20 Watford Way, Hendon, NW4 3AD</p>
<div>
</div>
<div class="contentBox" id="galleryBox2">
<!--<img id="image1" src="images/civillitigation2.jpg"class="top"/>-->
</div>
<div class="contentBox" id="galleryBox3"><p></p><img src="images/speechbubble.png"><span>read what our clients have to say about us</span><div id="testimonialTeaser"></div></div>
</div>
</div>
</div>
</div> <!--container end-->
<div id="footertop"></div>
<div id="footer"></div>
</body>
</html>
The CSS
@charset "utf-8";
/* CSS Document */
@charset "utf-8";
/* CSS Document */
@charset "utf-8";
/* CSS Document */
/* reset */
html, body, div, span, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code,del, dfn, em, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, b, u, i, center, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td {
margin: 0;
padding: 0;
border: 0;
font-size: 100%;
font: inherit;
vertical-align: baseline;
}
body {
line-height: 1;
}
ol, ul {
list-style: none;
}
blockquote, q {
quotes: none;
}
blockquote:before, blockquote:after, q:before, q:after {
content: '';
content: none;
}
table {
border-collapse: collapse;
border-spacing: 0;
}
/* @font-face @/ /* Generated by Font Squirrel (http://www.fontsquirrel.com) on May 2, 2011 04:30:37 PM America/New_York */
/* end reset*/
body {
position:relative;
background: url(../images/Backgrounds/bgtile1.gif);
z-index: -30;
overflow: scroll;
}
#container {
position:relative;
top: 0px;
width: 1002px;
height:850px;
margin: 20px auto 0px auto;
background-color: #fff;
/*border-right: 15px #18c662 solid;*/
}
#header {
position:relative;
display: block;
clear: both;
z-index:10;
margin: 0px;
height: 170px;
background-image: url(../images/Backgrounds/headerbg.gif);
background-repeat:repeat-x;
}
#logo {
clear:both;
padding-top: 20px;
padding-bottom:15px;
padding-left: 30px;
float:left;
height: 140px;
background: none;
}
#conveyancingQuality {
float:right;
height: 95px;
padding-top: 10px;
}
#motto {
clear:both;
position: absolute;
line-height:.9;
left: 470px;
top: 30px;
color: #000;
width: 200px;
font-size: 1.8em;
padding-top: 4px;
padding-right: 0px;
padding-bottom: 4px;
padding-left: 0px;
margin: 0px;
font-family: 'Ropa Sans', "Trebuchet MS", Helvetica, Arial, sans-serif;
font-style: italic;
line-height: 1.3;
}
#motto1 {
display: none;
}
#motto2 {
display: none;
margin-left: 40px;
}
#motto3 {
display: none;
margin-left: 70px;
}
#navBar {
clear:both;
width: 100%;
margin: 0 auto;
}
#navBar a {
display: block;
width: 238.5px;
height: 18px;
/*margin-right: 16.25px;
margin-left: 16.25px;*/
padding: 6px;
border-right:0px #fff solid;
text-decoration:none;
background: url(../images/Buttons/buttona.png);
height: 50px;
background-repeat:no-repeat;
color: #000;
font-family: 'Ropa Sans', "Trebuchet MS", Helvetica, Arial, sans-serif;
font-size:1.8em;
}
#aboutUsHeading a {
/*margin-left: 30.25px;*/
}
#contactMenuHeading a{
/*margin-right: 0px;*/
border-right:0px #fff solid;
}
#navBar a:hover {
color: #039;
color: rgba(21, 68, 86, .9);
background: url(../images/Buttons/buttonb.png);
background-repeat: repeat-x;
}
#navBar li.menuItem {
/*z-index:21;*/
margin-top:-6px;
text-align:center;
margin-right:0px;
float:left;
line-height: 1.6;
font-size:100%;
height: 30px;
border-right:0px #fff solid;
}
.subMenuItem {
position:relative;
top: 0px;
display: none;
font-size:80%;
text-indent: 15px;
text-align: left;
border-right:0px #fff solid;
height: 50px;
z-index:30;
}
#navBar ul ul li a {
height:30px;
background: url(../images/Buttons/submenubuttona.png);
background-repeat: no-repeat;
font-size: 95%;
}
#navBar ul ul li a:hover {
background: url(../images/Buttons/submenubuttonb.png)
}
#content {
clear: both;
z-index: 22;
position: absolute;
top: 235px;
}
.contentBox {
position: absolute;
float:left;
border: 1px #154456 solid;
margin: 0px;
height: 600px;
/*background-image: url(../images/Backgrounds/contentbg2.png);
background-repeat: repeat-x;
/*-webkit-border-radius: 7px;
-moz-border-radius: 7px;
border-radius: 7px;*/
}
#sideBarLeft {
position:relative;
width: 1000px;
}
#miniMenu {
padding: 5px 0px;
margin: 210px 0px 5px 13px;
font-family: 'Ropa Sans', "Trebuchet MS", Helvetica, Arial, sans-serif;
background: none;
width: 200px;
-webkit-box-shadow: 1px 1px 2px 1px rgba(0, 0, 0, .7);
-moz-box-shadow: 1px 1px 2px 1px rgba(0, 0, 0, .7);
box-shadow: 1px 1px 2px 1px rgba(0, 0, 0, .7);
}
#miniMenu a {
display:block;
text-decoration:none;
font-size:110%;
height: ;
padding: 3px 3px 3px 10px;
margin-top: 0px;
margin-bottom: 3px;
width:90%;
background-image: url(../images/Buttons/submenubuttona.png);
background-repeat:no-repeat;
color: #000;
font-family: 'Ropa Sans', "Trebuchet MS", Helvetica, Arial, sans-serif;
text-indent:0px;
}
#miniMenu a:hover {
text-decoration:none;
color: rgba(21, 68, 86, .9);
background-image: url(../images/Buttons/submenubuttonb.png);
font-style:italic;
-webkit-box-shadow: 0px 0px 0px 0px rgba(0, 0, 0, .7);
-moz-box-shadow: 0px 0px 0px 0px rgba(0, 0, 0, .7);
box-shadow: 0px 0px 0px 0px rgba(0, 0, 0, .7);
}
#articleBox {
left: 210px;
width: 580px;
}
#sideBarRight {
left: 799px;
width: 200px;
}
.contentBox, #container, #content {
-webkit-box-shadow: 2px 2px 6px 2px rgba(0, 0, 0, .7);
-moz-box-shadow: 2px 2px 6px 2px rgba(0, 0, 0, .7);
box-shadow: 2px 2px 6px 2px rgba(0, 0, 0, .7);
}
#galleryBox {
positioning: absolute;
top: 13px;
left: 10px;
height: 170px;
width: 980px;
background: url(../images/Backgrounds/dep_5272790-London-Skyline.png);
}
#contentHolder{
width: 550px;
height:100%;
background:#fff;
margin-left:250px;
z-index: 10
}
#contentHolder p {
padding: 0;
z-index: 11;
padding-top: 10px;
}
#p1 {
display: none;
font-family: 'Droid Sans', "Trebuchet MS", Helvetica, Arial, sans-serif;
font-size: 80%;
color: #154456;
margin-left: 470px;
}
#p3 {
position: absolute;
top: 0px;
display: none;
margin-left: 320px;
font-family: 'Droid Sans', "Trebuchet MS", Helvetica, Arial, sans-serif;
font-size: 100%;
text-align:center;
color: #154456;
}
#p4 {
display: none;
font-family: 'Droid Sans', "Trebuchet MS", Helvetica, Arial, sans-serif;
font-size: 80%;
color: #154456;
margin-left: 470px;
}
#p7 {
display: none;
font-family: 'Droid Sans', "Trebuchet MS", Helvetica, Arial, sans-serif;
font-size: 80%;
color: #154456;
margin-left: 470px;
}
#contact {
display: none;
font-family: 'Droid Sans', "Trebuchet MS", Helvetica, Arial, sans-serif;
font-size: 200%;
color: #154456;
margin-left: 0px;
}
#contact a{
color: #154456;
text-decoration:none;
}
#contact a:hover{
text-decoration: underline;
}
#contactBox {
display: block;
width: 200px;
height: 100px;
position:absolute;
top: 76px;
background: #3F3
}
.myButton {
background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, #ededed), color-stop(1, #154456) );
background:-moz-linear-gradient( center top, #ededed 5%, #154456 100% );
filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#ededed', endColorstr='#154456');
background-color:#ededed;
-moz-border-radius:6px;
-webkit-border-radius:6px;
border-radius:6px;
border:1px solid #154456;
display:inline-block;
color:#f5f5f5;
font-family:arial;
font-size:15px;
font-weight:bold;
padding:6px 24px;
text-decoration:none;
}.myButton:hover {
background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, #154456), color-stop(1, #ededed) );
background:-moz-linear-gradient( center top, #154456 5%, #ededed 100% );
filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#154456', endColorstr='#ededed');
background-color:#154456;
}.myButton:active {
position:relative;
top:1px;
}
#galleryBox2 img {;
position:absolute;
width: 100%;
height:100%;
margin: 0 auto;
}
#image2 {
display: block;
}
#image1 {
display: block;
}
#galleryBox2 img:hover {
}
#galleryBox2 {
positioning: absolute;
top: 190px;
left: 215px;
height: 375px;
width: 210px;
background-image: url(../images/Backgrounds/contentbg2.png);
}
#galleryBox3 {
positioning: absolute;
top: 190px;
left: 440px;
height: 375px;
width: 538px;
background-image: url(../images/Backgrounds/contentbg2.png);
}
#testimonialTeaser {
position: relative;
top: 12px;
background:none;
/*background: #18c662;*/
width: ;
height: 100px;
margin: 0 auto;
}
#footertop {
margin: 40px 0px 0px 0px;
background: url(../images/Backgrounds/footerbg.png);
background-repeat: repeat-x;
position:relative;
top:0px;
height:75px;
}
#footer {
background:#FFFFFF;
position:relative;
top:75px;
height:auto;
}
The JavaScript
// JavaScript Document
$(document).ready(function() {
var teamMenuHeading = $('#teamMenuHeading');
var teamSubMenu = $('#teamMenuHeading li');
var teamSubMenuLinks = $('#teamMenuHeading a');
var buttonb = ['images/buttonb.gif'];
//alert (teamSubMenu.length)
teamMenuHeading.hover(
function(){
teamSubMenu.stop(true,true).slideDown(700, 'easeOutSine' //, function() {
)
}, //end teamMenuHeading hover first function
function(){
teamSubMenu
.stop(true,true).slideUp(200, 'easeOutSine'//, function() {
)
}); //end teamMenuHeading hover
var servicesMenuHeading = $('#servicesMenuHeading')
var servicesSubMenu = $('#servicesMenuHeading li');
var servicesSubMenuLinks = $('#servicesMenuHeading a');
//alert (servicesSubMenu.length)
servicesMenuHeading.hover(
function(){
servicesSubMenu.stop(true,true).slideDown(700, 'easeOutSine' //, function() {
)
}, //end teamMenuHeading hover first function
function(){
servicesSubMenu
.stop(true,true).slideUp(200, 'easeOutSine'//, function() {
)
}); //end servicesMenuHeading hover
var contactMenuHeading = $('#contactMenuHeading')
var contactSubMenu = $('#contactMenuHeading li');
var contactSubMenuLinks = $('#contactMenuHeading a');
//alert (servicesSubMenu.length)
contactMenuHeading.hover(
function(){
contactSubMenu.stop(true,true).slideDown(700, 'easeOutSine' //, function() {
)
}, //end teamMenuHeading hover first function
function(){
contactSubMenu
.stop(true,true).slideUp(500, 'easeOutSine'//, function() {
)
}); //end contactMenuHeading hover
}); //end ready
A: Number 1 rule for styling lists:
Reset your lists: ul, li { margin:0;padding:0 }
Do not style LIs, other than display:, position: and float:.
Use display:block and put all styling on your A-tag.
This will clear up 99% of list layout problems.
See my tutorial: http://preview.moveable.com/JM/ilovelists/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/9317571",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Kivy ScreenManager can't reference class from .py file class any more. Attribute error: 'super' has I just started developing my first app in python using kivy. I generated the general layout of the app and also some logic in an python file in addition to my main py to seperate everything a bit. This worked perfectly fine and the app was running without any issues. I wanted to add some screens when hitting buttons that provide extra information. Managed to do so, but now the app crashes when hitting the buttons that worked before adding the extra screens. Those buttons use classes that aren't implemented in the main.py but in a side file. Like I explained, they worked before adding the ScreenManager. here's the short version of the error I get: AttributeError: 'super' object has no attribute '__getattr__'
Main.py:
peenomat.py
import kivy
# -*- coding: iso-8859-1 -*-
from kivy.app import App
from kivy.uix.button import Label
from kivy.uix.widget import Widget
from kivy.uix.textinput import TextInput
from kivy.lang import Builder
from kivy.uix.anchorlayout import AnchorLayout
from kivy.core.text import LabelBase
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import BooleanProperty
from kivy.properties import ObjectProperty
from kivy.config import Config
Builder.load_file('Header.kv')
Builder.load_file('Statusbar.kv')
Builder.load_file('Inputparameters.kv')
Builder.load_file('Outputparameters.kv')
Builder.load_file('Extra.kv')
#loading main kv
Builder.load_file('peenomat.kv')
class Peenomat(Screen):
pass
class Instruction(Screen):
pass
class Additional(Screen):
pass
# Create the screen manager
sm = ScreenManager()
sm.add_widget(Peenomat(name='peenomat'))
sm.add_widget(Instruction(name='instruction'))
sm.add_widget(Additional(name='additional'))
class PeenomatApp(App):
def build(self):
self.icon = 'icon.png'
#return pm
return sm
#return Peenomat()
if __name__=="__main__":
PeenomatApp().run()
the main kv.file:
peenomat.kv
<Peenomat>
AnchorLayout:
anchor_x: 'left'
anchor_y: 'bottom'
GridLayout:
cols: 1
InputParameters:
id:_input_parameters
StatusBar:
id:_status_bar
<Instruction>:
AnchorLayout:
anchor_x: 'left'
anchor_y: 'bottom'
GridLayout:
cols: 1
canvas.before:
Label:
text:
Button:
text:
on_release:
app.root.current = "peenomat"
app.root.transition.direction = "up"
<Additional>:
AnchorLayout:
anchor_x: 'left'
anchor_y: 'bottom'
GridLayout:
cols: 1
Button:
text:
on_release:
app.root.current = "peenomat"
app.root.transition.direction = "left"
the .kv file where I reference the function of the buttons:
statusbar.kv
#: import statusbar StatusBar
<StatusBar@BoxLayout>
orientation:'horizontal'
padding:
spacing:
Label:
size_hint: 0.05, 1
Button:
text: 'Leeren'
on_press: root.btn_clear()
Button:
text: "Mehr"
on_release:
app.root.current = "additional"
app.root.transition.direction ="right"
Button:
text: u"Los schl\u00e4gts"
on_press: root.btn_submit()
Button:
text: "?"
on_release:
app.root.current = "instruction"
app.root.transition.direction ="down"
and finally the python file that provides the classes where i generate the functions of the buttons that now crash:
StatusBAr.py
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.gridlayout import GridLayout
from kivy.properties import ObjectProperty
from kivy.properties import StringProperty
from kivy.app import App
from kivy.lang import Builder
#from Inputparameters import InputParameters
ver = ''
class InputParameters(GridLayout):
verfahren =ObjectProperty(None)
def on_state(self, togglebutton):
tb = togglebutton
global ver
if tb.state == 'down':
self.verfahren = tb.text
ver = tb.text
print(self.verfahren, ver)
return self.verfahren
class StatusBar(BoxLayout):
#InputGrößen
group_mode = False
prozess = ObjectProperty(None)
vorbehandlung = ObjectProperty(None)
material = ObjectProperty(None)
haerte = ObjectProperty(None)
rauheit = ObjectProperty(None)
verfahren = ObjectProperty(None)
#OutputGrößen
frequency = StringProperty(None)
speed = StringProperty(None)
hub = StringProperty(None)
def btn_submit(self):
global ver
ip = App.get_running_app().root.ids._input_parameters
op = App.get_running_app().root.ids._output_parameters
frequenz = 0
if ip.haerte.value < 50:
op.frequency = str(180) +" Hz"
op.speed = str(2.4) +" mm/s"
op.hub = str(3.4) + " mm"
elif ip.haerte.value < 60:
op.frequency = str(200) +" Hz"
op.speed = str(3.5) + " mm/s"
op.hub = str(5.23) + " mm"
else:
op.frequency = str(220) +" Hz"
op.speed = str(1.2) + " mm/s"
op.hub = str(7.2) + " mm"
#control to see if right value is taken
print(op.frequency)
def btn_clear(self):
ip = App.get_running_app().root.ids._input_parameters
op = App.get_running_app().root.ids._output_parameters
ip.pro1.state = "normal"
ip.pro2.state = "normal"
ip.pro3.state = "normal"
ip.material.text = "Auswahl treffen"
ip.vorbehandlung.text = "Auswahl treffen"
ip.haerte.value = 55
ip.rauheit.value = 5.5
op.frequency = "---"
op.speed = "---"
op.hub = "---"
so if the buttons submit or clear are used I get the following error:
[INFO ] [Base ] Leaving application in progress...
Traceback (most recent call last):
File "kivy\properties.pyx", line 860, in kivy.properties.ObservableDict.__getattr__
KeyError: '_input_parameters'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:/Users/schum/Dokumente/TUD/Masterthesis/Peenomat.py", line 79, in <module>
PeenomatApp().run()
File "C:\Users\schum\Dokumente\TUD\Masterthesis\venv\lib\site-packages\kivy\app.py", line 855, in run
runTouchApp()
File "C:\Users\schum\Dokumente\TUD\Masterthesis\venv\lib\site-packages\kivy\base.py", line 504, in runTouchApp
EventLoop.window.mainloop()
File "C:\Users\schum\Dokumente\TUD\Masterthesis\venv\lib\site-packages\kivy\core\window\window_sdl2.py", line 747, in mainloop
self._mainloop()
File "C:\Users\schum\Dokumente\TUD\Masterthesis\venv\lib\site-packages\kivy\core\window\window_sdl2.py", line 479, in _mainloop
EventLoop.idle()
File "C:\Users\schum\Dokumente\TUD\Masterthesis\venv\lib\site-packages\kivy\base.py", line 342, in idle
self.dispatch_input()
File "C:\Users\schum\Dokumente\TUD\Masterthesis\venv\lib\site-packages\kivy\base.py", line 327, in dispatch_input
post_dispatch_input(*pop(0))
File "C:\Users\schum\Dokumente\TUD\Masterthesis\venv\lib\site-packages\kivy\base.py", line 233, in post_dispatch_input
listener.dispatch('on_motion', etype, me)
File "kivy\_event.pyx", line 707, in kivy._event.EventDispatcher.dispatch
File "C:\Users\schum\Dokumente\TUD\Masterthesis\venv\lib\site-packages\kivy\core\window\__init__.py", line 1402, in on_motion
self.dispatch('on_touch_down', me)
File "kivy\_event.pyx", line 707, in kivy._event.EventDispatcher.dispatch
File "C:\Users\schum\Dokumente\TUD\Masterthesis\venv\lib\site-packages\kivy\core\window\__init__.py", line 1418, in on_touch_down
if w.dispatch('on_touch_down', touch):
File "kivy\_event.pyx", line 707, in kivy._event.EventDispatcher.dispatch
File "C:\Users\schum\Dokumente\TUD\Masterthesis\venv\lib\site-packages\kivy\uix\screenmanager.py", line 1191, in on_touch_down
return super(ScreenManager, self).on_touch_down(touch)
File "C:\Users\schum\Dokumente\TUD\Masterthesis\venv\lib\site-packages\kivy\uix\widget.py", line 549, in on_touch_down
if child.dispatch('on_touch_down', touch):
File "kivy\_event.pyx", line 707, in kivy._event.EventDispatcher.dispatch
File "C:\Users\schum\Dokumente\TUD\Masterthesis\venv\lib\site-packages\kivy\uix\relativelayout.py", line 288, in on_touch_down
ret = super(RelativeLayout, self).on_touch_down(touch)
File "C:\Users\schum\Dokumente\TUD\Masterthesis\venv\lib\site-packages\kivy\uix\widget.py", line 549, in on_touch_down
if child.dispatch('on_touch_down', touch):
File "kivy\_event.pyx", line 707, in kivy._event.EventDispatcher.dispatch
File "C:\Users\schum\Dokumente\TUD\Masterthesis\venv\lib\site-packages\kivy\uix\widget.py", line 549, in on_touch_down
if child.dispatch('on_touch_down', touch):
File "kivy\_event.pyx", line 707, in kivy._event.EventDispatcher.dispatch
File "C:\Users\schum\Dokumente\TUD\Masterthesis\venv\lib\site-packages\kivy\uix\widget.py", line 549, in on_touch_down
if child.dispatch('on_touch_down', touch):
File "kivy\_event.pyx", line 707, in kivy._event.EventDispatcher.dispatch
File "C:\Users\schum\Dokumente\TUD\Masterthesis\venv\lib\site-packages\kivy\uix\widget.py", line 549, in on_touch_down
if child.dispatch('on_touch_down', touch):
File "kivy\_event.pyx", line 707, in kivy._event.EventDispatcher.dispatch
File "C:\Users\schum\Dokumente\TUD\Masterthesis\venv\lib\site-packages\kivy\uix\behaviors\button.py", line 151, in on_touch_down
self.dispatch('on_press')
File "kivy\_event.pyx", line 703, in kivy._event.EventDispatcher.dispatch
File "kivy\_event.pyx", line 1214, in kivy._event.EventObservers.dispatch
File "kivy\_event.pyx", line 1098, in kivy._event.EventObservers._dispatch
File "C:\Users\schum\Dokumente\TUD\Masterthesis\venv\lib\site-packages\kivy\lang\builder.py", line 64, in custom_callback
exec(__kvlang__.co_value, idmap)
File "C:\Users\schum\Dokumente\TUD\Masterthesis\Statusbar.kv", line 38, in <module>
on_press: root.btn_submit()
File "C:\Users\schum\Dokumente\TUD\Masterthesis\StatusBar.py", line 41, in btn_submit
ip = App.get_running_app().root.ids._input_parameters
File "kivy\properties.pyx", line 863, in kivy.properties.ObservableDict.__getattr__
AttributeError: 'super' object has no attribute '__getattr__'
the function of the buttons is to get selected parameter out of this .kv.file
inputparameters.kv
#: import statusbar StatusBar
<InputParameters@GridLayout>
#Initialisierung .py zu .kv Ids
prozess: _prozess
pro1: _prozess1
pro2: _prozess2
pro3: _prozess3
vorbehandlung: _vorbehandlung
material: _material
haerte: _haerte
rauheit: _rauheit
cols: 2
padding: 25
spacing: 10
#Prozess
Label:
text:'Prozess: '
BoxLayout:
orientation: 'horizontal'
id: _prozess
ToggleButton:
id:_prozess1
text:'P-MOH'
group: "proc_group"
on_state: root.on_state(self)
ToggleButton:
id:_prozess2
text:'E-MOH'
group: "proc_group"
on_state: root.on_state(self)
ToggleButton:
id:_prozess3
text:'PE-MOH'
group: "proc_group"
on_state: root.on_state(self)
#Material
Label:
text: 'Material:'
Spinner:
id: _material
text: "Auswahl treffen"
values: ['1.2379', 'Gusseisen', 'Kautschuk', 'Carbon', 'Adamantium']
# Herstellschritte
Label:
text:'Fertigungsschritte:'
Spinner:
id: _vorbehandlung
text: "Auswahl treffen"
values: [u'Fr\u00e4sen', 'Erodieren', 'Schleifen', 'Polieren']
# Haerte
Label:
text: u"H\u00e4rte:"
BoxLayout:
orientation: 'vertical'
Label:
text: str(_haerte.value) + ' HRC'
Slider:
id: _haerte
min: 45
max: 65
step: 1
value_track: True
# Rauheit
Label:
text:'Rauheit:'
BoxLayout:
orientation: 'vertical'
Label:
text: str("%.1f" % _rauheit.value) + ' Rz' #eine Nachkommastelle
Slider:
id: _rauheit
min: 1
max: 10
value_track: True
whats weirrd is that the togglebuttons can still use the function generatet in the statusbar.py and do their job.
I hope you can help me out with this and don't even know where to start...
Thank's in advance!
A: The ids dictionary is created for each rule in the kv file, and those ids are placed in the dictionary for the root of that rule. So the _input_parameters id is only in the ids of the Peenomat instance.
So, I think you need to change:
ip = App.get_running_app().root.ids._input_parameters
to something like:
ip = App.get_running_app().root.get_screen('peenomat').ids._input_parameters
The root of your App is the ScreenManager, and get_screen('peenomat') gets the Peenomat Screen instance.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/63474256",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: StackOverflowError on recursive algorithm I'm trying to code a recursive algorithm in order to generate a valid board(unique solution) for a game called kakuro.
When executing the program I keep getting a StackOverflowError. I tried debugging my code and it is working as expected, but it suddenly crashes in a non recursive method. I have been reading about this issue on the internet and I have already checked that I don't make two recursive calls with the same parameters. This algorithm tries different values for certain squares and (when every square has its own value, it should thus try every possible combination of values for those squares) solves it in order to see whether it has an unique solution.
private boolean generarKakuroRecursivo(ArrayList<Negra> noColocados, Casella[][] tablero){
if (noColocados.size() == 0 ){
System.out.println(getStringTablero());
if (kakuroUnico(tablero)){
this.tauler = tablero;
return true;
}
else return false;
}
Negra casillaNegra = noColocados.get(0);
boolean fila = casillaNegra.getFila() == 0 && casillaNegra.getCoords().getElement1()+1 < dimensio && this.tauler[casillaNegra.getCoords().getElement0()][casillaNegra.getCoords().getElement1()+1].getTipus() == 'B';
boolean columna = casillaNegra.getColumna() == 0 && casillaNegra.getCoords().getElement0()+1 < dimensio && this.tauler[casillaNegra.getCoords().getElement0()+1][casillaNegra.getCoords().getElement1()].getTipus() == 'B';
ArrayList <Pair<Integer, ArrayList<ArrayList<Integer>> >> posibilidadesNegra = calcularPosibilidades(casillaNegra);
//CALCULAMOS LOS POSIBLES NUMEROS PARA LA CASILLA NEGRA QUE HEMOS COGIDO
int index1 = casillaNegra.getCoords().getElement0(), index2 = casillaNegra.getCoords().getElement1();
for (Pair<Integer, ArrayList<ArrayList<Integer>> > posibilidad : posibilidadesNegra){
int valor = posibilidad.getElement0();
if (fila && columna){
colocarNegra(((Negra)tablero[index1][index2]), valor, true);
noColocados.get(0).setNumFil(valor); //poner fila =false
} //actualizar restricciones
else if(fila){
colocarNegra(((Negra)tablero[index1][index2]), valor, true);
noColocados.remove(0);
}
else if (columna){
colocarNegra(((Negra)tablero[index1][index2]), valor, false);
noColocados.remove(0);
}
if (generarKakuroRecursivo(noColocados, tablero)) return true;
else{
if (!noColocados.contains(casillaNegra)) noColocados.add(casillaNegra);
if (fila){
retirarNegra((Negra)tablero[index1][index2],true);
if (!noColocados.contains(casillaNegra)) noColocados.add(casillaNegra);
}
else if (columna) {
retirarNegra((Negra)tablero[index1][index2], false);
if (!noColocados.contains(casillaNegra)) noColocados.add(casillaNegra);
}
}
} //Caso recursivo
//PROBAMOS RECURSIVAMENTE TODAS LAS OPCIONES
return false;
}
This is the recursive function in discuss, noColocados is an ArrayList which contains the squares (belonging to tablero) where we want to try all the possible combinations (if one of those combinations generates a unique solution(it should happen) the algorithm stops).
Boards generated by the algorithm before crashing
As you can see in the picture above, the algorithm works well until it crashes.
Debug information of the crash
In this picture you can see where the StackOverflowError is triggered, as you can see calculaNumCells is a non recursive method.
Edit: I also tried not parsing the parameter tablero as it was unnecessary (it is the same as the implicit parameter of the class) to the recursive algorithm nor other methods like CalculaNumCells.
Anyway the execution keeps crashing in the same exact point that it was crashing before.
A: A StackOverflowError merely indicates that there’s no space available in the stack for a new frame. In your case, the recursive calls still fill up most of the stack but, since the method calls other methods besides itself, those can also exhaust the stack.
If, for example, your recursive method called only itself, the stack would always be exhausted when calling that one method.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/65243424",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to handle One-to-Many Join without repeat rows In MS SQL Server I have two tables [Products] and [Product_img] with relationship (ONE TO MANY).
SELECT p_id, name FROM dbo.products
| 15 | | name1 |
| 17 | | name2 |
SELECT p_id, path FROM dbo.product_img
| 1.jpg | | 15 |
| 2.jpg | | 15 |
| 3.jpg| | 17 |
| 4.jpg | | 17 |
SELECT dbo.product_img.p_id, dbo.products.name, dbo.product_img.path FROM dbo.product_img INNER JOIN dbo.products ON dbo.product_img.p_id = dbo.products.p_id
| 15 | | name1 | | 1.jpg |
| 15 | | name1 | | 2.jpg |
| 17 | | name2 | | 3.jpg |
| 17 | | name2 | | 4.jpg |
What is the SQL statement that can show the tables like this (with out repeating)?
| 15 | | name1 | | 1.jpg | | 2.jpg |
| 17 | | name2 | | 3.jpg | | 4.jpg |
A: USE MAX AND MIN
SELECT
dbo.product_img.p_id
, dbo.products.name
, MAX(dbo.product_img.path)
, MIN(dbo.product_img.path)
FROM dbo.product_img
INNER JOIN dbo.products
ON dbo.product_img.p_id = dbo.products.p_id
GROUP BY dbo.product_img.p_id , dbo.products.name
A: If you can have more than two images per product you can do this to get one column with the img path's.
select
p.p_id,
p.name,
stuff((select ', '+i.path
from product_img as i
where p.p_id = i.p_id
for xml path(''), type).value('text()[1]', 'nvarchar(max)'), 1, 2, '') as path
from products as p
Result
p_id name path
----- ----- ------------
15 name1 1.jpg, 2.jpg
17 name2 3.jpg, 4.jpg
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/5749037",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: CSS clearfix hiding text in chrome / safari? I have an odd problem that I'm facing. I'm using a simple CSS clearfix hack as described on CSS-Tricks to clear floats. Code snippet:
*:after {
content: "";
display: table;
clear: both;
}
However, adding the above code causes the text to be invisible in Chrome and Safari. I've tested it on several devices now and had the same results each time, but I can't figure out why this would be breaking anything. However, Firefox
You can view the working version here and the broken version here. If you inspect page source, the only difference is the above snippet being commented out.
Screenshot of the issue http://cl.ly/image/3h1s0Q31473Q
I've spent some time looking around, but I can't find any mention of this problem anywhere else. Everything renders fine in Firefox.
Thanks in advance,
-Zach
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/13795823",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to check if there is a table on an excel sheet I have to make a VBA macro to check if there is a chart already present on an excel sheet. So, if there is any chart present, I have to delete it and if not, I have to put in a new chart.
I tried using:
Worksheets("Sheet.Name").ChartObjects.Delete directly, but if a chart was not present on a sheet, it gave an error.
i also tried using ThisWorkbook.Charts.Count but it is always showing that I have 0 charts in my workbook even though there are 2 charts on the first sheet itself.
Please help. Thanks :)
A: Try looping through all ChartObjects in your worksheet, and delete each one of them (if exists).
Code:
Option Explicit
Sub CheckCharts()
Dim ChtObj As ChartObject
For Each ChtObj In Worksheets("Sheet1").ChartObjects '<-- modify "Sheet1" with your sheet's name
ChtObj.Delete
Next ChtObj
End Sub
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/41803613",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Creating a dynamic Linq select clause from Expressions Let's say I have defined the following variables:
IQueryable<MyClass> myQueryable;
Dictionary<string, Expression<Func<MyClass, bool>>> extraFields;
// the dictionary is keyed by a field name
Now, I want to tack on some dynamic fields to the IQueryable, so that it returns an IQueryable<ExtendedMyClass>, where ExtendedMyClass is defined as:
class ExtendedMyClass
{
public MyClass MyObject {get; set;}
public IEnumerable<StringAndBool> ExtraFieldValues {get; set;}
}
class StringAndBool
{
public string FieldName {get; set;}
public bool IsTrue {get; set;}
}
In other words, for every value in extraFields, I want to have a value in ExtendedMyClass.ExtraFieldValues representing whether that expression evaluates to True or not for that row.
I have a feeling this should be doable in dynamic Linq and LinqKit, though I've never used that seriously before. I'm also open to other suggestions, especially if this can be done in good ol' strong-typed Linq.
I am using Linq to Entities, so the query needs to translate to SQL.
A: So, we'll have a lot of steps here, but each individual step should be fairly short, self-contained, reusable, and relatively understandable.
The first thing we'll do is create a method that can combine expressions. What it will do is take an expression that accepts some input and generates an intermediate value. Then it will take a second expression that accepts, as input, the same input as the first, the type of the intermediate result, and then computes a new result. It will return a new expression taking the input of the first, and returning the output of the second.
public static Expression<Func<TFirstParam, TResult>>
Combine<TFirstParam, TIntermediate, TResult>(
this Expression<Func<TFirstParam, TIntermediate>> first,
Expression<Func<TFirstParam, TIntermediate, TResult>> second)
{
var param = Expression.Parameter(typeof(TFirstParam), "param");
var newFirst = first.Body.Replace(first.Parameters[0], param);
var newSecond = second.Body.Replace(second.Parameters[0], param)
.Replace(second.Parameters[1], newFirst);
return Expression.Lambda<Func<TFirstParam, TResult>>(newSecond, param);
}
To do this we simply replace all instances of the second parameter in the second expression's body with the body of the first expression. We also need to ensure both implementations use the same parameter instance for the main parameter.
This implementation requires having a method to replace all instances of one expression with another:
internal class ReplaceVisitor : ExpressionVisitor
{
private readonly Expression from, to;
public ReplaceVisitor(Expression from, Expression to)
{
this.from = from;
this.to = to;
}
public override Expression Visit(Expression node)
{
return node == from ? to : base.Visit(node);
}
}
public static Expression Replace(this Expression expression,
Expression searchEx, Expression replaceEx)
{
return new ReplaceVisitor(searchEx, replaceEx).Visit(expression);
}
Next we'll write a method that accepts a sequences of expressions that accept the same input and compute the same type of output. It will transform this into a single expression that accepts the same input, but computes a sequence of the output as a result, in which each item in the sequence represents the result of each of the input expressions.
This implementation is fairly straightforward; we create a new array, use the body of each expression (replacing the parameters with a consistent one) as each item in the array.
public static Expression<Func<T, IEnumerable<TResult>>> AsSequence<T, TResult>(
this IEnumerable<Expression<Func<T, TResult>>> expressions)
{
var param = Expression.Parameter(typeof(T));
var body = Expression.NewArrayInit(typeof(TResult),
expressions.Select(selector =>
selector.Body.Replace(selector.Parameters[0], param)));
return Expression.Lambda<Func<T, IEnumerable<TResult>>>(body, param);
}
Now that we have all of these general purpose helper methods out of the way, we can start working on your specific situation.
The first step here is to turn your dictionary into a sequence of expressions, each accepting a MyClass and creating a StringAndBool that represents that pair. To do this we'll use Combine on the value of the dictionary, and then use a lambda as the second expression to use it's intermediate result to compute a StringAndBool object, in addition to closing over the pair's key.
IEnumerable<Expression<Func<MyClass, StringAndBool>>> stringAndBools =
extraFields.Select(pair => pair.Value.Combine((foo, isTrue) =>
new StringAndBool()
{
FieldName = pair.Key,
IsTrue = isTrue
}));
Now we can use our AsSequence method to transform this from a sequence of selectors into a single selector that selects out a sequence:
Expression<Func<MyClass, IEnumerable<StringAndBool>>> extrafieldsSelector =
stringAndBools.AsSequence();
Now we're almost done. We now just need to use Combine on this expression to write out our lambda for selecting a MyClass into an ExtendedMyClass while using the previous generated selector for selecting out the extra fields:
var finalQuery = myQueryable.Select(
extrafieldsSelector.Combine((foo, extraFieldValues) =>
new ExtendedMyClass
{
MyObject = foo,
ExtraFieldValues = extraFieldValues,
}));
We can take this same code, remove the intermediate variable and rely on type inference to pull it down to a single statement, assuming you don't find it too unweidly:
var finalQuery = myQueryable.Select(extraFields
.Select(pair => pair.Value.Combine((foo, isTrue) =>
new StringAndBool()
{
FieldName = pair.Key,
IsTrue = isTrue
}))
.AsSequence()
.Combine((foo, extraFieldValues) =>
new ExtendedMyClass
{
MyObject = foo,
ExtraFieldValues = extraFieldValues,
}));
It's worth noting that a key advantage of this general approach is that the use of the higher level Expression methods results in code that is at least reasonably understandable, but also that can be statically verified, at compile time, to be type safe. There are a handful of general purpose, reusable, testable, verifiable, extension methods here that, once written, allows us to solve the problem purely through composition of methods and lambdas, and that doesn't require any actual expression manipulation, which is both complex, error prone, and removes all type safety. Each of these extension methods is designed in such a way that the resulting expression will always be valid, so long as the input expressions are valid, and the input expressions here are all known to be valid as they are lambda expressions, which the compiler verifies for type safety.
A: I think it's helpful here to take an example extraFields, imagine how would the expression that you need look like and then figure out how to actually create it.
So, if you have:
var extraFields = new Dictionary<string, Expression<Func<MyClass, bool>>>
{
{ "Foo", x => x.Foo },
{ "Bar", x => x.Bar }
};
Then you want to generate something like:
myQueryable.Select(
x => new ExtendedMyClass
{
MyObject = x,
ExtraFieldValues =
new[]
{
new StringAndBool { FieldName = "Foo", IsTrue = x.Foo },
new StringAndBool { FieldName = "Bar", IsTrue = x.Bar }
}
});
Now you can use the expression trees API and LINQKit to create this expression:
public static IQueryable<ExtendedMyClass> Extend(
IQueryable<MyClass> myQueryable,
Dictionary<string, Expression<Func<MyClass, bool>>> extraFields)
{
Func<Expression<Func<MyClass, bool>>, MyClass, bool> invoke =
LinqKit.Extensions.Invoke;
var parameter = Expression.Parameter(typeof(MyClass));
var extraFieldsExpression =
Expression.Lambda<Func<MyClass, StringAndBool[]>>(
Expression.NewArrayInit(
typeof(StringAndBool),
extraFields.Select(
field => Expression.MemberInit(
Expression.New(typeof(StringAndBool)),
new MemberBinding[]
{
Expression.Bind(
typeof(StringAndBool).GetProperty("FieldName"),
Expression.Constant(field.Key)),
Expression.Bind(
typeof(StringAndBool).GetProperty("IsTrue"),
Expression.Call(
invoke.Method,
Expression.Constant(field.Value),
parameter))
}))),
parameter);
Expression<Func<MyClass, ExtendedMyClass>> selectExpression =
x => new ExtendedMyClass
{
MyObject = x,
ExtraFieldValues = extraFieldsExpression.Invoke(x)
};
return myQueryable.Select(selectExpression.Expand());
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/23389342",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: I have problems with opening file in C I assume I have a compilation problem, but I want to make sure that is not my fault.
I have compared my code with some other from a program that I made couple of days ago, and I literally couldn't find any difference.
FILE *f;
f = fopen("gps.txt","r");
if (f == NULL){
printf("Couldn't open the file.");
return 0;
}
int i= 0;
int n;
while(fscanf(f,"%c %d %d %d %c %d %d %d %d %d %d",&gps[i].sirina,&gps[i].stepen,&gps[i].min,&gps[i].sek,&gps[i].duzina,&gps[i].s1,&gps[i].m1,&gps[i].sek1,&gps[i].visina,&gps[i].brzina,&gps[i].sateliti)==11)
i++;
n = i;
printf("%d",gps[1].sek);
File informations:(25 55 22 N 123 213 123 S 25 23 2
123 123 123 N 234 25 53 S 123 5 1
12 41 3 N 12 5 13 S 1 2 4)
Result of this code is always 0 (this is just to check if I can continue doing my program). There are informations written in the file, I double checked that I saved it every time but still my program outputs 0. On the same code I wrote couple of days ago, outputs are okay, including the fact the file is same.
I would be happy to know is there is compiling problem or if there is a mistake in my code. Thanks!
A: according to your input the string in the fscanf is wrong.
you use the following string:
%c %d %d %d %c %d %d %d %d %d %d"
this is example of input line:
25 55 22 N 123 213 123 S 25 23 2
you need the following string:
%d %d %d %[^A-Z] %c %d %d %d %[^A-Z] %c %d %d %d
based on the given example, you read 25,55,22 using %d.
then and you skipping spaces etc using %[^A-Z], and then you read N or S using %c.
space is also a character, you need to pay attention to it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/58198656",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How can i make my own template/programming engine in php Ive been working some time on own template engines but i alwais get stuck in strucktured documents like
<block : block1>
<table>
<block : row>
<tr>
<td>
{value}
</td>
<td>
{value2}
</td>
</tr>
</block>
</table>
</block>
I can get "block 1" with a regex but it will break at the first (the one of "row")
But i want a smarter way (and not by using a function like DOM)
i was thinking about something like
while($i < strlen($code)){
if(substr($code,$i,1)){
//tag is opened
}
}
A: Basically, you're constructing a programming language here (albeit simple, it's still a programming language). To interpret a programming language you need a compiler, which usually contains a lexer (which splits input stream into meaningful tokens) and a parser (which reads tokens one by one and takes whatever actions are needed). In your simplified example, the lexer would be probably regexp-based, and the parser can be a simple stack-based one.
(terms in italic should actually be wikipedia links).
A: I am not entirely sure about what your question is, but there has been a lot of debating about templating languages in PHP but I think a
general consensus reached by now was that it usually doesn't make much sense to roll
your own templating language. You might get instant nice result by e.g. using string replacement
and regular expressions, but eventually you will need more functionality like loops
or other expressions and then it will become quite tricky (ultimately ending in creating your own compiler).
The best suggestion usually is to either use PHP as your templating language directly
(that is what PHP was designed for in the first place and with strictly following the MVC pattern quite a good solution, too) or try one
of the existing templating engines. Only if you can't make any of them
fit your needs (most of them are extensible through a plugin mechanism)
you should start making your own.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/2772715",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Using the python multiprocessing module for IO with pygame on Mac OS 10.7 I use pygame for running experiments in cognitive science, and often I have heavy I/O demands so I like to fork off these tasks to separate processes (when using a multi-core machine) to improve performance of my code. However, I encountered a scenario where some code works on my colleague's linux machine (Ubuntu LTS), but not on my mac. Below is code representing a minimal reproducible example. My mac is a 2011 Macbook Air running 10.7.2 and using the default python 2.7.1. I tried both pygame as installed via pre-built binary, and I also then tried after installing both SDL and pygame from source.
import pygame
import multiprocessing
pygame.init()
def f():
while True:
pygame.event.pump() #if this is replaced by pass, this code works
p = multiprocessing.Process(target=f)
p.start()
while True:
pass
As noted in the code, it seems that the culprit is putting pygame.event.pump() in a separate process. When I run this on my mac, I first get the following printed repeatedly in terminal:
The process has forked and you cannot use this CoreFoundation functionality safely. You MUST exec().
Break on __THE_PROCESS_HAS_FORKED_AND_YOU_CANNOT_USE_THIS_COREFOUNDATION_FUNCTIONALITY___YOU_MUST_EXEC__() to debug.
Then I get a crash report as copied to this gist.
Any suggestions for how to fix this?
A: Maybe you should initialize the pygame (which initialize SDL-> OpenGL) in each forked (child) process like in sample:
import multiprocessing
def f():
import pygame
pygame.init()
while True:
pygame.event.pump()
if __module__ == "__main__"
p = multiprocessing.Process(target=f)
p.start()
import pygame
pygame.init()
while True:
pygame.event.pump()
A: Try this link:
http://www.slideshare.net/dabeaz/an-introduction-to-python-concurrency#btnPrevious
It may help. The problem is that you are creating a process that never stops. This should be declared as a daemon:
p = multiprocessing.Process(target=f)
p.daemon = True
p.start()
Not sure if this will solve the problem, I'm just learning about the multiprocessing module as I'm posting this.
A: Have you tried using threads instead of processes? I've had issues before using the python multiprocessing module in OS X. http://docs.python.org/library/threading.html
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/8106002",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
}
|
Q: How do I put a SQL Server database under version control using Visual Studio Community 2015 RC? I would like to put my database schema and its data in my git repository and have it version controlled, just like my code.
I have SQL Server 2008 R2 and Visual Studio Community 2015 RC. I know that Visual Studio 2010 upwards, Database project templates have been introduced to do just this. Please see this article for example. But I don't find those templates in my Visual Studio Community Edition 2015 RC installation.
A: Sticking to RC isn't very viable in the long term. Especially now, when Visual Studio 2015 RTM has been released.
Unless you have some really strong incentive to stay on Release Candidate, I would recommend to:
*
*Get RTM Express Edition for free, whichever suits you best. SSDT 2015 is compatible with Web and Windows Desktop;
*Get SSDT 2015 (again, for free) and install on top of that.
AFAIR, that should give you SQL Server database projects and everything else you might need. The only catch is that, as usual, it will be a somewhat longer route if you have ever had any CTP / RC versions installed on the same Windows instance before. Then again, it's nothing new.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/31759748",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: JavaScript Collections API? I've searched quite a while for a Collections API (list, set) for JS and surprisingly I could only this: http://www.coffeeblack.org/work/jscollections/
This is exactly what I was looking for, but I'm wondering why doesn't jQuery provide that? What am I missing on? Or, perhaps, how ineffective are my searching techniques?
I know that arrays support pop() and push(), but I need contains() for example.
A: You can try js_cols, a collections library for JavaScript.
A: Can't you use the jquery collection plugin.
http://plugins.jquery.com/project/Collection
A: jQuery's primary focus is the DOM. It doesn't and shouldn't try and be all things to all people, so it doesn't have much in the way of collections support.
For maps and sets, I'd like to shamelessly point you in the direction of my own implementations of these: http://code.google.com/p/jshashtable/
Regarding lists, Array provides much of what you need. Like most methods you might want for arrays, you can knock together a contains() method in a few lines (most of which are to deal with IE <= 8's lack of support for the indexOf() method):
Array.prototype.contains = Array.prototype.indexOf ?
function(val) {
return this.indexOf(val) > -1;
} :
function(val) {
var i = this.length;
while (i--) {
if (this[i] === val) {
return true;
}
}
return false;
};
["a", "b", "c"].contains("a"); // true
A: You can also try buckets, it has the most used collections.
A: Since javascript have both arrays [] and associative arrays {}, most needs for datstructures are already solved. The array solves the ordered list, fast access by numeric index whilst the associative array can be considered a unordered hashmap and solves the fast access by string keys.
For me that covers 95% of my data structure needs.
A: If you get some free time you can checkout.
https://github.com/somnathpanja/jscollection
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/4295937",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: Font Awesome rendering wrong icons after updating lib to 6.1.1 We wanted to update all our used libs in our Node.js/Nuxt/Vue application.
And so we arrived at Font Awesome.
Before the update we used:
"@fortawesome/fontawesome-svg-core": "1.2.30",
"@fortawesome/free-brands-svg-icons": "5.14.0",
"@fortawesome/pro-regular-svg-icons": "5.14.0",
And we updated them to:
"@fortawesome/fontawesome-svg-core": "^6.1.1",
"@fortawesome/free-brands-svg-icons": "^6.1.1",
"@fortawesome/pro-regular-svg-icons": "^6.1.1",
I include here a screenshot of the before and after result of our left menu.
The encircled items should have unique icons like the left version.
However in some occasions it renders wrong icons, it looks likes it takes the icon from the item above.
In developer tools the HTML for one menu item with a wrong icon looks like the following:
You see the correct class in the icon element but the svg element somehow gets the class from the menu item above it. It should use the fa-cogs and not the fa-chart-line.
I want to point out that we did not change anything code wise.
Did anyone encounter something similar after updating the font awesome libs?
Or knows a solution to this problem?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72125195",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: plupload submits OPTIONS instead of POST to a WebAPI Have an MVC application and a separate WebAPI. Using plupload, when the url points to a method in the MVC controller, the files are POSTed.
Here's what Fiddler shows
POST /Home/HandleUpload/ HTTP/1.1
Host: localhost:50000
Connection: keep-alive
Content-Length: 38040
Origin: http://localhost:50000
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryT4glpqFi5sbmY2KL
Accept: */*
Referer: http://localhost:50000/Home/Index
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
When I change the url to point to the WebAPI, I get OPTIONS request instead of a POST, so the API method doesn't get hit.
OPTIONS /api/v1/Files/HandleUpload HTTP/1.1
Host: localhost:60000
Connection: keep-alive
Access-Control-Request-Method: POST
Origin: http://localhost:50000
Access-Control-Request-Headers: content-type
Accept: */*
Referer: http://localhost:50000/Home/Index
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
The only thing I change on the plupload configuration is the url.
Here's my method. It's the same in both projects.
[HttpPost]
public HttpResponseMessage HandleUpload(int? chunk, string name)
{
var fileUpload = HttpContext.Current.Request.Files[0];
var uploadPath = HttpContext.Current.Server.MapPath("~/App_Data");
chunk = chunk ?? 0;
//write chunk to disk.
string uploadedFilePath = Path.Combine(uploadPath, name);
using (var fs = new FileStream(uploadedFilePath, chunk == 0 ? FileMode.Create : FileMode.Append))
{
var buffer = new byte[fileUpload.InputStream.Length];
fileUpload.InputStream.Read(buffer, 0, buffer.Length);
fs.Write(buffer, 0, buffer.Length);
}
}
A: I was able to do this but not sure if this is the best practice. filename is set in UI in the preinit function
preinit: {
UploadFile: function (up, file) {
// You can override settings before the file is uploaded
// up.settings.url = 'upload.php?id=' + file.id;
//up.settings.multipart_params = { type: $("#Type").val(), title: $("#Title").val() };
up.settings.multipart_params = {
filename: file.name
};
}
},
Web api code
[HttpPost]
public async Task<IHttpActionResult> UploadPropertyImage()
{
if (!Request.Content.IsMimeMultipartContent())
throw new Exception(); // divided by zero
var provider = new MultipartMemoryStreamProvider();
await Request.Content.ReadAsMultipartAsync(provider);
var name = await provider.Contents.SingleOrDefault(p => p.Headers.ContentDisposition.Name == "\"name\"").ReadAsStringAsync();
var chunk = await provider.Contents.SingleOrDefault(p => p.Headers.ContentDisposition.Name == "\"chunk\"").ReadAsStringAsync();
var chunks = await provider.Contents.First(p => p.Headers.ContentDisposition.Name == "\"chunks\"").ReadAsStringAsync();
var filename = await provider.Contents.First(p => p.Headers.ContentDisposition.Name == "\"filename\"").ReadAsStringAsync();
var buffer = await provider.Contents.First(p => p.Headers.ContentDisposition.Name == "\"file\"").ReadAsByteArrayAsync();
//var Id = await provider.Contents.First(p => p.Headers.ContentDisposition.Name == "\"Id\"").ReadAsByteArrayAsync();
var Id = Guid.Empty;
var uploadPath = HostingEnvironment.MapPath(Path.Combine("~/app_data",Id.ToString()));
if (!Directory.Exists(uploadPath))
Directory.CreateDirectory(uploadPath);
using (var fs = new FileStream(Path.Combine(uploadPath,name), chunk == "0" ? FileMode.Create : FileMode.Append))
fs.Write(buffer, 0, buffer.Length);
return Ok();
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/19712176",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: PHP sql database, inserting UNIQUE values Im working with sql database (phpMyadmin) and with programming language PHP.
I've got a table with data e.g:
T1:
145
138.8
110.6
1759.4
1400.9
1891.4
1755.4
1760.4
T2:
141.9
110.6
1400.9
1891.4
1758.4
My question >
Is there existing sql syntax, that is able to average values which are lying in ONE THRESHOLD (like > 1755.4,1760.4,1759.4 OR 145,138.8) and INSERT THEM AS UNIQUE VALUES to another table ?
What I need is create T2(contain UNIQUE values) from T1, and INSERTING them only if they didn't exist in T2.
I was trying, to looping throw 2 arrays (1starray = T1 and 2ndarray = T2 ) too. And compare data in array1 and array2, and trying to insert values which can be unique.
for($z = 0; $z<$numberApp; $z++) {
while($j<$numberAbs-1){
$Abs=$arrayabs[$j];
$state_change = (abs($Abs - abs($previous_Abs)));
if ($state_change>100){
$instantChange = True;
echo "<br>"." better than tolerance: " . $instantChange;
}
else {
$instantChange = False;
echo "<br>"." lower than tolerance" . $instantChange;
}
//if($state_change = (abs($some_item - $previous_item)<= $tolerance)){
if($Abs != $previous_Abs){
echo "<br>" ." some_item : " .$Abs." previous_item : " .$previous_Abs;
}
//$lastAbs=$arrayabs[$j];
//echo " next_item : " .$lastAbs;
if ($instantChange == True and $onChange == False){
$Abs2 [] = $podiel;
$finalPower = $podiel;
}
if ($instantChange){
$D=0;
echo "ABSOLUT >>> " .$lastAbs;
$percentual1 = ($power_app[$z] * 0.9);
$percentual2 = ($power_app[$z] * 1.1);
if(($lastAbs<$percentual1 || $lastAbs>$percentual2)){
$user = 'root';
$pass = 'password';
$db = 'vypis';
//if($N>0){
$db = new mysqli('localhost', $user, $pass, $db) or die();
$sql = "INSERT INTO vypis.nilm_app2(power) VALUES ('$lastAbs')";
if(mysqli_query($db, $sql)){
echo "Records added successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($db);
}
}
//$power_app[$z++];
}
Thank you for everyone, who going to help, and sorry for my bad english.
A: The math here sounds complex enough that you're probably better off doing the complex stuff (averaging the values and determining whether a value is unique) in PHP, then finishing off with a couple simple MySQL statements.
This can probably be done in pure MySQL with a bit of trickery, but frequently it isn't worth the time and complexity it creates. (Imagine you'll have to debug that monster SQL query six months from now!)
By contrast, it's trivial to take a handful of values in PHP and average them; it's also trivial to run a quick MySQL query to determine whether a value is unique. So if you're unsure how to mash these together into one big SQL statement, start out by just handling them in the PHP code as separate steps! Then later on, if performance issues come up, you can think about how to combine them (but at least by that point you already have something that works).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/29969968",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Is there a way to reverse the bit order in UInt64? I am building a chess engine in Swift based off a tutorial written in Java. In the tutorial, Java's signed 64 bit integer long has a static method called reverse(long i) that "Returns the value obtained by reversing the order of the bits in the two's complement binary representation of the specified long value." It basically reverses the order of the binary bits so that, using 8-bit for simplicity's sake, 01000000 would become 00000010.
I am curious if there is a way to accomplish the same thing with Swift's UInt64. I understand that Java's long (signed, 2s complement) and Swift's UInt64 (unsigned) are different, but I imagine it wouldn't be hard to do this with UInt64.
I tried UInt64.byteSwapped, but this doesn't seem to be getting me the behavior I expect.
A: No, the Swift standard libraries do not provide a method to reverse the order of bits in an integer, see for example the discussion Bit reversal in the Swift forum.
One can use the C methods from Bit Twiddling Hacks, either by importing C code to Swift, or by translating it to Swift.
As an example, I have taken the loop-based variant
unsigned int s = sizeof(v) * CHAR_BIT; // bit size; must be power of 2
unsigned int mask = ~0;
while ((s >>= 1) > 0)
{
mask ^= (mask << s);
v = ((v >> s) & mask) | ((v << s) & ~mask);
}
because that is not restricted to a certain integer size. It can be translated to Swift as an extension to FixedWidthInteger so that it works with integers of all sizes:
extension FixedWidthInteger {
var bitSwapped: Self {
var v = self
var s = Self(v.bitWidth)
precondition(s.nonzeroBitCount == 1, "Bit width must be a power of two")
var mask = ~Self(0)
repeat {
s = s >> 1
mask ^= mask << s
v = ((v >> s) & mask) | ((v << s) & ~mask)
} while s > 1
return v
}
}
Examples:
print(String(UInt64(1).bitSwapped, radix: 16))
// 8000000000000000
print(String(UInt64(0x8070605004030201).bitSwapped, radix: 16))
// 8040c0200a060e01
print(String(UInt16(0x1234).bitSwapped, radix: 16))
// 2c48
Another option would be to use byteSwapped to reverse the order of bytes first, and then reverse the order of the bits in each byte with a (precomputed) lookup table:
fileprivate let bitReverseTable256: [UInt8] = [
0, 128, 64, 192, 32, 160, 96, 224, 16, 144, 80, 208, 48, 176, 112, 240,
8, 136, 72, 200, 40, 168, 104, 232, 24, 152, 88, 216, 56, 184, 120, 248,
4, 132, 68, 196, 36, 164, 100, 228, 20, 148, 84, 212, 52, 180, 116, 244,
12, 140, 76, 204, 44, 172, 108, 236, 28, 156, 92, 220, 60, 188, 124, 252,
2, 130, 66, 194, 34, 162, 98, 226, 18, 146, 82, 210, 50, 178, 114, 242,
10, 138, 74, 202, 42, 170, 106, 234, 26, 154, 90, 218, 58, 186, 122, 250,
6, 134, 70, 198, 38, 166, 102, 230, 22, 150, 86, 214, 54, 182, 118, 246,
14, 142, 78, 206, 46, 174, 110, 238, 30, 158, 94, 222, 62, 190, 126, 254,
1, 129, 65, 193, 33, 161, 97, 225, 17, 145, 81, 209, 49, 177, 113, 241,
9, 137, 73, 201, 41, 169, 105, 233, 25, 153, 89, 217, 57, 185, 121, 249,
5, 133, 69, 197, 37, 165, 101, 229, 21, 149, 85, 213, 53, 181, 117, 245,
13, 141, 77, 205, 45, 173, 109, 237, 29, 157, 93, 221, 61, 189, 125, 253,
3, 131, 67, 195, 35, 163, 99, 227, 19, 147, 83, 211, 51, 179, 115, 243,
11, 139, 75, 203, 43, 171, 107, 235, 27, 155, 91, 219, 59, 187, 123, 251,
7, 135, 71, 199, 39, 167, 103, 231, 23, 151, 87, 215, 55, 183, 119, 247,
15, 143, 79, 207, 47, 175, 111, 239, 31, 159, 95, 223, 63, 191, 127, 255]
extension FixedWidthInteger {
var bitSwapped: Self {
var value = self.byteSwapped
withUnsafeMutableBytes(of: &value) {
let bytes = $0.bindMemory(to: UInt8.self)
for i in 0..<bytes.count {
bytes[i] = bitReverseTable256[Int(bytes[i])]
}
}
return value
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/60594125",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: private data member in C++ OOP I am new to OOP in C++. I got a doubt. I know it may be a silly doubt.
In the code below in main function, commented line will give error as I can not access private data memebers directly. but in the member function complex add(complex &C) I created a object temp of class complex. How can I access the data member of object temp directly and modify them as those are private. Like in the main function, should it not throw error? Is there any rule that in the member function of class we can access private data of a object of same class directly.
using namespace std;
class complex{
private:
int real;
int img;
public:
complex(int r = 0, int i = 0);
complex add(complex &C);
};
complex :: complex(int r, int i){
real = r;
img = i;
}
complex complex :: add(complex &C){
complex temp;
temp.real = real + C.real;
temp.img = img + C.img;
return temp;
}
int main() {
complex c1(3,4);
complex c2(5,7);
complex c3;
// c3.real = 3;
// c3.img = 5;
c3 = c1.add(c2);
return 0;
}
A: I try and stick to rule, keep your member variables private, if you need to change them or access them once the object is created, use a public get / set function.
e.g:
int complex::GetReal() const { return m_real; }
void complex::SetReal(const int i) { m_real = i; }
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72971455",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Why docker run can't find file which was copied during build Dockerfile
FROM centos
RUN mkdir /test
#its ensured that sample.sh exists where the dockerFile exists & being run
COPY ./sample.sh /test
CMD ["sh", "/test/sample.sh"]
Docker run cmd:
docker run -d -p 8081:8080 --name Test -v /home/Docker/Container_File_System:/test test:v1
Log output :
sh: /test/sample.sh: No such file or directory
There are 2 problems here.
*
*The output says sh: /test/sample.sh: No such file or directory
*as I have mapped a host folder to container folder, I was expecting the test folder & the sample.sh to be available at /home/Docker/Container_File_System post run, which did not happen
Any help is appreciated.
A: When you map a folder from the host to the container, the host files become available in the container. This means that if your host has file a.txt and the container has b.txt, when you run the container the file a.txt becomes available in the container and the file b.txt is no longer visible or accessible.
Additionally file b.txt is not available in the host at anytime.
In your case, since your host does not have sample.sh, the moment you mount the directory, sample.sh is no longer available in the container (which causes the error).
What you want to do is copy the sample.sh file to the correct directory in the host and then start the container.
A: The problem is in volume mapping. If I create a volume and map it subsequently it works fine, but directly mapping host folder to container folder does not work.
Below worked fine
docker volume create my-vol
docker run -d -p 8081:8080 --name Test -v my-vol:/test test:v1
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/66533716",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Prevent second half of an if statement when first half is null I have a statement in VB.net that I thought I wrote correctly to prevent the second half from being evaluated. It looks like this:
If ((myDataSet2 IsNot Nothing) Or myDataSet2.Tables("CurData").Rows.Count > 0)
However it does not skip the second expresion "myDataSet2.Tables("CurData").Rows.Count > 0" like I want it to.
What should I change?
A: Use the OrElse operator.
If myDataSet2 IsNot Nothing OrElse myDataSet2.Tables("CurData").Rows.Count > 0
EDIT: See my comment on your original question. You are PROBABLY looking for:
If myDataSet2 IsNot Nothing AndAlso myDataSet2.Tables("CurData").Rows.Count > 0
That will check if myDataSet2 isn't null. Assuming that it's not, it will then check that there is at least one row. If it is null, then the second condition won't be checked.
A: You need to put the second statement into the first if-clause.
Like this:
If(statement1) then
If(statemtent2) then
Else
End if
Else
End If
As it is now both are evaluated and if one of them is true the content in your if-clause will be executed.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/17552081",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Jenkins Pipeline as Code Groovy Error on Class Annotation Hi I am trying to use Jenkins pipeline as code (formally workflow). I am getting errors whenever I try to use Annotations on a class defined in the pipeline script.
Error
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
General error during canonicalization: Unexpected variable type: null
java.lang.UnsupportedOperationException: Unexpected variable type: null
JenkinsFile
import groovy.transform.ToString;
import groovy.transform.EqualsAndHashCode;
@EqualsAndHashCode
@ToString
class BarDeploy {
String barFile
String app
String integrationServer
}
Any ideas why I cannot do this?
Full Stack Trace
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
General error during canonicalization: Unexpected variable type: null
java.lang.UnsupportedOperationException: Unexpected variable type: null
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:408)
at org.codehaus.groovy.reflection.CachedConstructor.invoke(CachedConstructor.java:77)
at org.codehaus.groovy.reflection.CachedConstructor.doConstructorInvoke(CachedConstructor.java:71)
at org.codehaus.groovy.runtime.callsite.ConstructorSite$ConstructorSiteNoUnwrap.callConstructor(ConstructorSite.java:81)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callConstructor(AbstractCallSite.java:190)
at com.cloudbees.groovy.cps.CpsTransformer.visitVariableExpression(CpsTransformer.groovy:723)
at org.codehaus.groovy.ast.expr.VariableExpression.visit(VariableExpression.java:70)
at org.codehaus.groovy.ast.expr.VariableExpression$visit.call(Unknown Source)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:42)
at org.codehaus.groovy.ast.expr.BinaryExpression$visit.call(Unknown Source)
at com.cloudbees.groovy.cps.CpsTransformer.visit(CpsTransformer.groovy:234)
at sun.reflect.GeneratedMethodAccessor546.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:90)
at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:233)
at org.codehaus.groovy.runtime.metaclass.ClosureMetaClass.invokeMethod(ClosureMetaClass.java:361)
at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:903)
at org.codehaus.groovy.runtime.callsite.PogoMetaClassSite.callCurrent(PogoMetaClassSite.java:66)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:141)
at com.cloudbees.groovy.cps.CpsTransformer$_visitBinaryExpression_closure25.doCall(CpsTransformer.groovy:553)
at sun.reflect.GeneratedMethodAccessor569.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:90)
at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:233)
at org.codehaus.groovy.runtime.metaclass.ClosureMetaClass.invokeMethod(ClosureMetaClass.java:272)
at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:903)
at org.codehaus.groovy.runtime.callsite.PogoMetaClassSite.callCurrent(PogoMetaClassSite.java:66)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:141)
at com.cloudbees.groovy.cps.CpsTransformer$_visitBinaryExpression_closure25.doCall(CpsTransformer.groovy)
at sun.reflect.GeneratedMethodAccessor568.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:90)
at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:233)
at org.codehaus.groovy.runtime.metaclass.ClosureMetaClass.invokeMethod(ClosureMetaClass.java:272)
at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:903)
at org.codehaus.groovy.runtime.callsite.PogoMetaClassSite.call(PogoMetaClassSite.java:39)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:42)
at org.codehaus.groovy.runtime.callsite.PogoMetaClassSite.call(PogoMetaClassSite.java:54)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:112)
at com.cloudbees.groovy.cps.CpsTransformer.makeChildren(CpsTransformer.groovy:278)
at sun.reflect.GeneratedMethodAccessor545.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite$PogoCachedMethodSiteNoUnwrapNoCoerce.invoke(PogoMetaMethodSite.java:272)
at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite.callCurrent(PogoMetaMethodSite.java:52)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallCurrent(CallSiteArray.java:46)
at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite.callCurrent(PogoMetaMethodSite.java:57)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:141)
at com.cloudbees.groovy.cps.CpsTransformer.makeNode(CpsTransformer.groovy:253)
at sun.reflect.GeneratedMethodAccessor544.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite$PogoCachedMethodSiteNoUnwrapNoCoerce.invoke(PogoMetaMethodSite.java:272)
at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite.callCurrent(PogoMetaMethodSite.java:52)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:145)
at com.cloudbees.groovy.cps.CpsTransformer.visitBinaryExpression(CpsTransformer.groovy:559)
at org.codehaus.groovy.ast.expr.BinaryExpression.visit(BinaryExpression.java:49)
at org.codehaus.groovy.ast.expr.BinaryExpression$visit.call(Unknown Source)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:42)
at org.codehaus.groovy.ast.stmt.ExpressionStatement$visit.call(Unknown Source)
at com.cloudbees.groovy.cps.CpsTransformer.visit(CpsTransformer.groovy:234)
at sun.reflect.GeneratedMethodAccessor546.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite$PogoCachedMethodSiteNoUnwrapNoCoerce.invoke(PogoMetaMethodSite.java:272)
at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite.callCurrent(PogoMetaMethodSite.java:52)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallCurrent(CallSiteArray.java:46)
at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite.callCurrent(PogoMetaMethodSite.java:57)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:141)
at com.cloudbees.groovy.cps.CpsTransformer.visitExpressionStatement(CpsTransformer.groovy:395)
at org.codehaus.groovy.ast.stmt.ExpressionStatement.visit(ExpressionStatement.java:40)
at org.codehaus.groovy.ast.stmt.ExpressionStatement$visit.call(Unknown Source)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:42)
at org.codehaus.groovy.ast.expr.StaticMethodCallExpression$visit.call(Unknown Source)
at com.cloudbees.groovy.cps.CpsTransformer.visit(CpsTransformer.groovy:234)
at sun.reflect.GeneratedMethodAccessor546.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite$PogoCachedMethodSiteNoUnwrapNoCoerce.invoke(PogoMetaMethodSite.java:272)
at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite.callCurrent(PogoMetaMethodSite.java:52)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:141)
at com.cloudbees.groovy.cps.CpsTransformer.visit(CpsTransformer.groovy:240)
at sun.reflect.GeneratedMethodAccessor552.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:90)
at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:233)
at org.codehaus.groovy.runtime.metaclass.ClosureMetaClass.invokeMethod(ClosureMetaClass.java:361)
at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:903)
at org.codehaus.groovy.runtime.callsite.PogoMetaClassSite.callCurrent(PogoMetaClassSite.java:66)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:141)
at com.cloudbees.groovy.cps.CpsTransformer$_visitBlockStatement_closure8.doCall(CpsTransformer.groovy:342)
at sun.reflect.GeneratedMethodAccessor580.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:90)
at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:233)
at org.codehaus.groovy.runtime.metaclass.ClosureMetaClass.invokeMethod(ClosureMetaClass.java:272)
at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:903)
at org.codehaus.groovy.runtime.callsite.PogoMetaClassSite.callCurrent(PogoMetaClassSite.java:66)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:141)
at com.cloudbees.groovy.cps.CpsTransformer$_visitBlockStatement_closure8.doCall(CpsTransformer.groovy)
at sun.reflect.GeneratedMethodAccessor579.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:90)
at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:233)
at org.codehaus.groovy.runtime.metaclass.ClosureMetaClass.invokeMethod(ClosureMetaClass.java:272)
at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:903)
at org.codehaus.groovy.runtime.callsite.PogoMetaClassSite.call(PogoMetaClassSite.java:39)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:112)
at com.cloudbees.groovy.cps.CpsTransformer.makeChildren(CpsTransformer.groovy:278)
at sun.reflect.GeneratedMethodAccessor545.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite$PogoCachedMethodSiteNoUnwrapNoCoerce.invoke(PogoMetaMethodSite.java:272)
at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite.callCurrent(PogoMetaMethodSite.java:52)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:141)
at com.cloudbees.groovy.cps.CpsTransformer.makeNode(CpsTransformer.groovy:253)
at sun.reflect.GeneratedMethodAccessor544.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite$PogoCachedMethodSiteNoUnwrapNoCoerce.invoke(PogoMetaMethodSite.java:272)
at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite.callCurrent(PogoMetaMethodSite.java:52)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:145)
at com.cloudbees.groovy.cps.CpsTransformer.visitBlockStatement(CpsTransformer.groovy:341)
at org.codehaus.groovy.ast.stmt.BlockStatement.visit(BlockStatement.java:69)
at org.codehaus.groovy.ast.stmt.BlockStatement$visit.call(Unknown Source)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:42)
at org.codehaus.groovy.ast.expr.VariableExpression$visit.call(Unknown Source)
at com.cloudbees.groovy.cps.CpsTransformer.visit(CpsTransformer.groovy:234)
at sun.reflect.GeneratedMethodAccessor546.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite$PogoCachedMethodSiteNoUnwrapNoCoerce.invoke(PogoMetaMethodSite.java:272)
at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite.callCurrent(PogoMetaMethodSite.java:52)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallCurrent(CallSiteArray.java:46)
at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite.callCurrent(PogoMetaMethodSite.java:57)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:141)
at com.cloudbees.groovy.cps.CpsTransformer.visit(CpsTransformer.groovy:240)
at sun.reflect.GeneratedMethodAccessor552.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:90)
at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:233)
at org.codehaus.groovy.runtime.metaclass.ClosureMetaClass.invokeMethod(ClosureMetaClass.java:361)
at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:903)
at org.codehaus.groovy.runtime.callsite.PogoMetaClassSite.callCurrent(PogoMetaClassSite.java:66)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:141)
at com.cloudbees.groovy.cps.CpsTransformer$_visitBlockStatement_closure8.doCall(CpsTransformer.groovy:342)
at sun.reflect.GeneratedMethodAccessor580.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:90)
at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:233)
at org.codehaus.groovy.runtime.metaclass.ClosureMetaClass.invokeMethod(ClosureMetaClass.java:272)
at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:903)
at org.codehaus.groovy.runtime.callsite.PogoMetaClassSite.callCurrent(PogoMetaClassSite.java:66)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:141)
at com.cloudbees.groovy.cps.CpsTransformer$_visitBlockStatement_closure8.doCall(CpsTransformer.groovy)
at sun.reflect.GeneratedMethodAccessor579.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:90)
at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:233)
at org.codehaus.groovy.runtime.metaclass.ClosureMetaClass.invokeMethod(ClosureMetaClass.java:272)
at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:903)
at org.codehaus.groovy.runtime.callsite.PogoMetaClassSite.call(PogoMetaClassSite.java:39)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:42)
at org.codehaus.groovy.runtime.callsite.PogoMetaClassSite.call(PogoMetaClassSite.java:54)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:112)
at com.cloudbees.groovy.cps.CpsTransformer.makeChildren(CpsTransformer.groovy:278)
at sun.reflect.GeneratedMethodAccessor545.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite$PogoCachedMethodSiteNoUnwrapNoCoerce.invoke(PogoMetaMethodSite.java:272)
at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite.callCurrent(PogoMetaMethodSite.java:52)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallCurrent(CallSiteArray.java:46)
at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite.callCurrent(PogoMetaMethodSite.java:57)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:141)
at com.cloudbees.groovy.cps.CpsTransformer.makeNode(CpsTransformer.groovy:253)
at sun.reflect.GeneratedMethodAccessor544.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite$PogoCachedMethodSiteNoUnwrapNoCoerce.invoke(PogoMetaMethodSite.java:272)
at org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite.callCurrent(PogoMetaMethodSite.java:52)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:145)
at com.cloudbees.groovy.cps.CpsTransformer.visitBlockStatement(CpsTransformer.groovy:341)
at org.codehaus.groovy.ast.stmt.BlockStatement.visit(BlockStatement.java:69)
at org.codehaus.groovy.ast.stmt.BlockStatement$visit.call(Unknown Source)
at com.cloudbees.groovy.cps.CpsTransformer.visitMethod(CpsTransformer.groovy:166)
at sun.reflect.GeneratedMethodAccessor606.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:90)
at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:233)
at org.codehaus.groovy.runtime.metaclass.ClosureMetaClass.invokeMethod(ClosureMetaClass.java:361)
at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:903)
at org.codehaus.groovy.runtime.callsite.PogoMetaClassSite.callCurrent(PogoMetaClassSite.java:66)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:141)
at com.cloudbees.groovy.cps.CpsTransformer$_call_closure1.doCall(CpsTransformer.groovy:95)
at sun.reflect.GeneratedMethodAccessor605.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:90)
at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:233)
at org.codehaus.groovy.runtime.metaclass.ClosureMetaClass.invokeMethod(ClosureMetaClass.java:272)
at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:903)
at groovy.lang.Closure.call(Closure.java:415)
at groovy.lang.Closure.call(Closure.java:428)
at org.codehaus.groovy.runtime.DefaultGroovyMethods.each(DefaultGroovyMethods.java:1379)
at org.codehaus.groovy.runtime.DefaultGroovyMethods.each(DefaultGroovyMethods.java:1351)
at org.codehaus.groovy.runtime.DefaultGroovyMethods$each.call(Unknown Source)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:42)
at org.codehaus.groovy.runtime.DefaultGroovyMethods$each.call(Unknown Source)
at com.cloudbees.groovy.cps.CpsDefaultGroovyMethods.each(CpsDefaultGroovyMethods.groovy:26)
at sun.reflect.GeneratedMethodAccessor582.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.codehaus.groovy.runtime.metaclass.ReflectionMetaMethod.invoke(ReflectionMetaMethod.java:51)
at org.codehaus.groovy.runtime.metaclass.NewInstanceMetaMethod.invoke(NewInstanceMetaMethod.java:54)
at org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite$PojoMetaMethodSiteNoUnwrapNoCoerce.invoke(PojoMetaMethodSite.java:271)
at org.codehaus.groovy.runtime.callsite.PojoMetaMethodSite.call(PojoMetaMethodSite.java:53)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:116)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.callSafe(AbstractCallSite.java:82)
at com.cloudbees.groovy.cps.CpsTransformer.call(CpsTransformer.groovy:95)
at org.codehaus.groovy.control.CompilationUnit.applyToPrimaryClassNodes(CompilationUnit.java:970)
at org.codehaus.groovy.control.CompilationUnit.doPhaseOperation(CompilationUnit.java:548)
at org.codehaus.groovy.control.CompilationUnit.processPhaseOperations(CompilationUnit.java:526)
at org.codehaus.groovy.control.CompilationUnit.compile(CompilationUnit.java:503)
at groovy.lang.GroovyClassLoader.doParseClass(GroovyClassLoader.java:302)
at groovy.lang.GroovyClassLoader.parseClass(GroovyClassLoader.java:281)
at groovy.lang.GroovyShell.parseClass(GroovyShell.java:731)
at groovy.lang.GroovyShell.parse(GroovyShell.java:743)
at org.jenkinsci.plugins.workflow.cps.CpsGroovyShell.reparse(CpsGroovyShell.java:106)
at org.jenkinsci.plugins.workflow.cps.CpsFlowExecution.parseScript(CpsFlowExecution.java:376)
at org.jenkinsci.plugins.workflow.cps.CpsFlowExecution.start(CpsFlowExecution.java:343)
at org.jenkinsci.plugins.workflow.job.WorkflowRun.run(WorkflowRun.java:212)
at hudson.model.ResourceController.execute(ResourceController.java:98)
at hudson.model.Executor.run(Executor.java:410)
1 error
at org.codehaus.groovy.control.ErrorCollector.failIfErrors(ErrorCollector.java:302)
at org.codehaus.groovy.control.CompilationUnit.applyToPrimaryClassNodes(CompilationUnit.java:997)
at org.codehaus.groovy.control.CompilationUnit.doPhaseOperation(CompilationUnit.java:548)
at org.codehaus.groovy.control.CompilationUnit.processPhaseOperations(CompilationUnit.java:526)
at org.codehaus.groovy.control.CompilationUnit.compile(CompilationUnit.java:503)
at groovy.lang.GroovyClassLoader.doParseClass(GroovyClassLoader.java:302)
at groovy.lang.GroovyClassLoader.parseClass(GroovyClassLoader.java:281)
at groovy.lang.GroovyShell.parseClass(GroovyShell.java:731)
at groovy.lang.GroovyShell.parse(GroovyShell.java:743)
at org.jenkinsci.plugins.workflow.cps.CpsGroovyShell.reparse(CpsGroovyShell.java:106)
at org.jenkinsci.plugins.workflow.cps.CpsFlowExecution.parseScript(CpsFlowExecution.java:376)
at org.jenkinsci.plugins.workflow.cps.CpsFlowExecution.start(CpsFlowExecution.java:343)
at org.jenkinsci.plugins.workflow.job.WorkflowRun.run(WorkflowRun.java:212)
at hudson.model.ResourceController.execute(ResourceController.java:98)
at hudson.model.Executor.run(Executor.java:410)
Finished: FAILURE
A: This issue is known about, and still open, in Jenkins. See https://issues.jenkins-ci.org/browse/JENKINS-40564
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/37531985",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: JQuery interfering with lxml parsing I am trying to scrape a website which was probably written poorly, so when you initially perform a GET request on their page, it responds with 5 entries in a mixture of html, javascript, jquery because it's the visual part of the page, and if you want to get more entries, you click a button, which internally performs a POST request on the same page along with the "pagination value" which is like the page you want, like if you want entries 6 to 10, you give a value of "2" to pagination value and if you want entries 11 to 15, you give a value of "3", and it does this asynchronously and appends the data to the end of the previous result set.
Sending/receiving is not a problem, in fact, when I try to scrape the page using lxml, I can easily get values for the first 5 entries, however, when I have to get the second set of data, I provide pagination value of "2" and I expect xml data back, because xml/html would be easy to parse, but here's my problem:
They return a weird combination of jquery AND html. It goes something like this:
$(".entry:last").after("
<div class="entry">
<p>some data</p>
</div>
<!-- 4 more entries omitted -->
");
When you inspect their website, this works flawlessly, the last 5 entries that just got downloaded asynchronously via AJAX, gets added sequentially to the first 5 entries, I looked into the "after" method of Jquery and I can confirm that it just appends the 5 entries after the 5th element.
When I initially scraped their data, the root element was a html tag, so I could parse it using lxml, but the response that they provide the moment I have to parse the result of this pagination is this weird mix of Jquery and html.
Also I can assure you that there is only one "after" method, and everything else is html, so basically 2 lines of Jquery, the first line and the last line, so I assumed I would just blindly remove the first and last line and then parse it again, but the response object that I get from the requests library, which I use to perform the POST operation, returns it as one long line of data, so I cannot do any readLine() on it, to seperate the first line from the second line from the last line, it's all just one line to me. So I would like pointers on how I would solve something like this.
Thanks :D
A: So if I understand correctly, the question is "How do I extract HTML embedded in javascript code".
The quick and dirty solution is to use a regular expression to extract the HTML. This is going to be a little finicky because of quoting but it's not too bad, you need a regular expression which can match a string with escaped quotes, this one will do the trick for doublequotes, it will match anything between doublequotes which is not a double quote, or is a quoted double quote:
"((?:[^"]+|\\")+)"
You can then use that to create a regular expression which will extract the contents of the html string from it's jquery wrapping:
import re
mixed_js_html = r'$(".entry:last").after("<div class=\"entry\"><p>some data</p></div>");')
m = re.search(r'after\("((?:[^"]+|\\")+)"\)', mixed_js_html):
html_code = m.group(1)
html_code = html_code.replace('\\"', '"') # unescape quotes
print(html_code)
# <div class="entry"><p>some data</p></div>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/26345446",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: accessing current redux state in monaco editor action run function I have a monaco editor instance, and I add an action for the Ctrl+S Keys.
const addActions = (editor: editor.IStandaloneCodeEditor) => {
editor.addAction({
id: "save-element-action",
label: "Save Element",
keybindings: [KeyMod.CtrlCmd | KeyCode.KEY_S],
precondition: undefined,
keybindingContext: undefined,
contextMenuGroupId: "navigation",
contextMenuOrder: 1.5,
// @param editor The editor instance is passed in as a convinience
run: function (ed) {
// TODO: saveElement is called but doesnt work yet because expressionEditorState is empty (Closure??)
saveElement();
},
});
};
in the saveElement function i want to access some state from my redux store
const saveElement = (editor?: editor.ICodeEditor) => {
if (expressionEditorState.elementContent === undefined || expressionEditorState.elementContent === "") {
dispatch(createErrorAction("No content for element"));
return;
}
dispatch(createSaveElementAction(user, expressionEditorState.elementContent, expressionEditorState.elementMetaData));
};
the expressionEditorState is the same as the initial state (so empty).
The setup of the state is down with a custom hook and the useSelector hook.
How can i access the current state of redux in the run function of a monaco action?
A: if anyone is following up...
the solution is to use thunks (see redux-thunks). so i rewrote saveElement as thunk and just dispatch it.
dispatch(saveElement())
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/65941526",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to specify different buld dirrectories for qmake? I use qmake. I have the following project structure:
/
|_SFMLWidgets
| |_...
| |_View.h
| |_View.cpp
| \_...
|
|_MapEditor
| |_...
| |_View.h
| |_View.cpp
| \_...
|
\_main.cpp
This views do different things. When I try to compile project I get compilation errors:
overriding recipe for target 'debug/View.o'
ignoring old recipe for target 'debug/View.o'
It happens because both views are builded in same directory. Is there any way to specify different build dirrectories?
I want something like:
/
|_debug
|_SFMLWidgets
| |_...
| |_View.o
| \_...
|
|_MapEditor
| |_...
| |_View.o
| \_...
|
|_main.o
\_main.exe
My .pro file
A: You can put each of SFMLwidgets and MapEditor in separate subdirs qmake project files. Shared configuration of the two subprojects can go into a pri file.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/42737742",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Scrollbar in mIRC window Is it possible to remove or hide (hide to allow mouse wheeling) a scroll bar within a custom mIRC window. The verticle scrollbar to be specific.
If you look to the very right of the picture you see the scrollbar.
Is there a way to remove it?
A: Yes, it can be removed.
I put together this AHK script that will hide the scrollbar in mIRC, and will keep it hidden even after resizing the window, as well as minimizing and restoring the window.
Load this up in autohotkey and it will start working once you click on a channel or anything in the switchbar.
~LButton::
MouseGetPos, , , , OutputVarControl
if (OutputVarControl = "mIRC_SwitchBar1" or OutputVarControl = "ScrollBar1")
{
WinWait, ahk_class mIRC
Control, Style, Hide, ScrollBar1
ControlGetPos, x,, Width,, mIRC_Channel1
ControlMove, mIRC_Channel1, ,, (Width + 18)
ControlGetPos, x,, Width,, mIRC_Query1
ControlMove, mIRC_Query1, ,, (Width + 18)
ControlGetPos, x,, Width,, mIRC_Status1
ControlMove, mIRC_Status1, ,, (Width + 18)
ControlGetPos, x,y, Width,Height, ListBox1
ControlMove, ListBox1, (x - 18),, ,
}
else if (OutputVarControl = "MSTaskListWClass1")
{
sleep, 500
if WinActive("ahk_class mIRC"){
WinWait, ahk_class mIRC
Control, Style, Hide, ScrollBar1
WinGetPos, X, Y, W, H, ahk_class mIRC
WinMove, ahk_class mIRC, , , , (W + 18),,
WinGetPos, X, Y, W, H, ahk_class mIRC
WinMove, ahk_class mIRC, , , , (W - 18),,
ControlGetPos, x,, Width,, mIRC_Channel1
ControlMove, mIRC_Channel1, ,, (Width + 18)
ControlGetPos, x,, Width,, mIRC_Query1
ControlMove, mIRC_Query1, ,, (Width + 18)
ControlGetPos, x,, Width,, mIRC_Status1
ControlMove, mIRC_Status1, ,, (Width + 18)
ControlGetPos, x,y, Width,Height, ListBox1
ControlMove, ListBox1, (x - 18),, ,
}
}
return
Assumes you use mIRC with one window maximized at a time inside the mIRC client like this. But you can have as many channels/query windows open, the script can handle switching between them.
A: No, The scroll-bar at the main custom window, can not be removed.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/18122180",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Flashlight app (How to set screen brightness to Max?) I am working on a flashlight android app, which has an option for screen light(Max Brightness). How can I set an activity brightness to max with a button press?
A: This site has some information about the topic: http://www.tutorialforandroid.com/2009/01/changing-screen-brightness.html
The part what you need:
IHardwareService hardware = IHardwareService.Stub.asInterface(ServiceManager.getService("hardware"));
if (hardware != null)
hardware.setScreenBacklight(brightness);
I didn't test it but it should work
UPDATE:
Alternate solution:
WindowManager.LayoutParams params = getWindow().getAttributes();
params.screenBrightness = 1.0f;
getWindow().setAttributes(params);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/11976800",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: StringBuilder, add Tab between Values I have a small problem:
I have a List of fields, with 3 Values. I want to build my String with these three Values,
delimited by a "TAB"..
Code:
StringBuilder stringBuilder = new StringBuilder();
foreach (string field in fields)
{
stringBuilder.Append(field).Append("\t");
}
stringBuilder.AppendLine();
return stringBuilder.ToString();
The Tab is only between the 3rd and 2nd Value (Between 1st and 2nd is a Space ?!)
So I tried this:
StringBuilder stringBuilder = new StringBuilder();
foreach (string field in fields)
{
stringBuilder.Append(field + "\t").Append("\t");
}
stringBuilder.AppendLine();
return stringBuilder.ToString();
Then I have 2 Tabs between 3rd and 2nd, one Tab between 1st and 2nd and also a Space
between 1st and 2nd..
(The Space is always there, how to avoid that?)
So what I have to do? Need only (without spaces..) a Tab between these Values..
A: I think you are confusing with tab char and sapces.
Are you expecting fixed no of white spaces to be added in the end of every word?
\t -> is just a tab char
The following is generated by the code given by you.
Java StackOverflow Banyan
Javasun StackOverflow Banyan
The above two lines have same tab char b/w the 1st & 2nd Word.
if you type one more char in the end of "Javasun" it will extend like the following
Javaasunk StackOverflow Banyan
A: try
StringBuilder stringBuilder = new StringBuilder();
foreach (string field in fields)
{
stringBuilder.Append(field.Trim()).Append("\t");
}
stringBuilder.AppendLine();
return stringBuilder.ToString();
Basically I would just use return string.Join ( "\t", fields ); .
A: I would have thought you would want
StringBuilder stringBuilder = new StringBuilder();
foreach (string field in fields)
{
stringBuilder.Append(field);
stringBuilder.Append("\t");
}
stringBuilder.AppendLine();
return stringBuilder.ToString();
A: Instead of looping, you can use string.Join:
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.AppendLine(string.Join("\t", fields));
Note that you can pass in the string directly to AppendLine as well.
A: Sub WarningWindow(ByVal content As String)
Dim sw As New StringWriter()
Dim hw As New HtmlTextWriter(sw)
Dim gridHTML As String = sw.ToString().Replace("""", "'").Replace(System.Environment.NewLine, "")
Dim sb As New StringBuilder()
Dim a As String = "Welcomeback"
'GridView1.RenderControl(hw)
sb.Append("<script type = 'text/javascript'>")
sb.Append("window.onload = new function(){")
sb.Append("var printWin = window.open('', '', 'left=0")
sb.Append(",top=0,width=1400,height=500,resize=yes,scrollbars =yes');")
sb.Append("printWin.document.write(""")
sb.Append("<INPUT Type=Button Name=Close Size=40 Value='Clsose(GSS)' onclick='self.close()'; / > ")
sb.Append("</br><INPUT Type=Button Name=fu Size=40 Value='Alert' onclick=javascript:window.alert('" & a & "'); / > ")
sb.Append("<INPUT Type=Text Name=gss Size=40 Value=300 ; / > ")
sb.Append(" <P>")
sb.Append(content)
sb.Append(""");")
sb.Append("printWin.focus();")
sb.Append("printWin.show;};")
sb.Append("</script>")
ClientScript.RegisterStartupScript(Me.GetType(), "suvesh", sb.ToString())
End Sub
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/9191756",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Working with array as table and employee hours and salaries I need help with an array that shows a list of employees, their hours, their wage and then totals the pay for each employee and then totals the hours for all employee's hours, wages and total employee pay. I have code so far as:
import java.util .*;
public class Employee
{
public static void main(String[] args)
{
String wages[][] =
{
{"Emp", " " , "Hours", " ", "Wages", " ", "Total Pay"},
{"Bobby", " ", "45", " ", "35"},
{"Rick", " ", "15", " ", "33"},
{"Mike", " ", "66", " ", "50"},
{"Jayme", " ", "15", " ", "45"},
{"Total", " ", " ", " ", " ", " "}
};
for (int i = 0; i < wages.length; i++)
{
for (int j = 0; j < wages[i].length; j++)
{
System.out.print(wages[i][j]);
}
System.out.println();
}
Integer H1 = Integer.valueOf(wages[1][2]);
Integer H2 = Integer.valueOf(wages[2][2]);
Integer H3 = Integer.valueOf(wages[3][2]);
Integer H4 = Integer.valueOf(wages[4][2]);
int sumH = 0;
sumH = H1 + H2 + H3 + H4;
System.out.println();
System.out.println("The Sum of All Employee Hours is: " + sumH);
Integer W1 = Integer.valueOf(wages[1][4]);
Integer W2 = Integer.valueOf(wages[2][4]);
Integer W3 = Integer.valueOf(wages[3][4]);
Integer W4 = Integer.valueOf(wages[4][4]);
double over = 0;
double totalPay1 = 0;
if (H1 <= 40)
{
totalPay1 = W1 * H1;
}
else
{
totalPay1 = (W1 * H1) + ((H1- 40 ) * (W1 * 1.5));
}
double totalPay2 = 0;
if (H2 <= 40)
{
totalPay2 = W2 * H2;
}
else
{
totalPay2 = (W2 * H2) + ((H2) * (W2 * 1.5));
}
double totalPay3 = 0;
if (H3 <= 40)
{
totalPay3 = W3 * H3;
}
else
{
totalPay3 = (W3 * H3) + ((H3) * (W3 * 1.5));
}
double totalPay4 = 0;
if (H4 <= 40)
{
totalPay4 = W4 * H4;
}
else
{
totalPay4 = (W4 * H4) + ((H4) * (W4 * 1.5));
}
double grandTotal = 0;
grandTotal = totalPay1 + totalPay2 + totalPay3 + totalPay4;
System.out.printf("The total number of Pay is $%.2f.%n", grandTotal);
//Bobby's totalPay1
double bobbyTotal = (double) 0;
bobbyTotal = totalPay1;
System.out.printf("Bobby's total pay is $%.2f.%n", bobbyTotal);
//Ricks Total
double rickTotal = (double) 0;
rickTotal = totalPay2;
System.out.printf("Rick's total pay is $%.2f.%n", rickTotal);
//Mikes Total
double mikeTotal = (double) 0;
mikeTotal = totalPay3;
System.out.printf("Mike's total pay is $%.2f.%n", mikeTotal);
//Jaymes Total
double jaymeTotal = (double) 0;
jaymeTotal = totalPay4;
System.out.printf("Jayme's total pay is $%.2f.%n", jaymeTotal);
}
}
I need to be able to print the totals for each employee as the last column in the array [x][6]
I was able to print them out but I want it to look more like a a table. Along with that my formulas might be off because I don't think it's factoring in overtime right. I think there might be something wrong with my IF ELSE statement.
The array should print out like
Emp Hours Wage Total
Bobby 45 35 $1662.50
Rick 15 33 $495.00
Mike 66 50 $3,950.00
Jayme 15 45 $675.00
Total 141 163 $6,782.50
What I've got is:
Emp Hours Wages Total Pay
Bobby 45 35
Rick 15 33
Mike 66 50
Jayme 15 45
Total
The Sum of All Employee Hours is: 141
The total number of Pay is $11257.50.
Bobby's total pay is $1837.50.
Rick's total pay is $495.00.
Mike's total pay is $8250.00.
Jayme's total pay is $675.00
A: Using a class rather than a String[]
We identified that each employee has name, hours, wage, total values, instead of representing this in a String[], we can use a class
class Employee{
private String name;
private int hours;
private int wage;
private int total;
public Employee(String name, int hours, int wage){
this.name = name;
this.hours = hours;
this.wage = wage;
this.total = hours * wage;
}
public String getName(){
return name;
}
public int getHours(){
return hours;
}
public int getWage(){
return wage;
}
public int getTotal(){
return total;
}
public String toString(){
return String.format("%s %d %d %d", name, hours, wage, total);
}
}
Now we have defined how an Employee looks like, so now we can use Employee
Putting the Employee into a List
public class EmployeeData{
public static void main(String[] args){
List<Employee> employees = new ArrayList<Employee>();
Employee bobby = new Employee("Bobby", 45, 35);
Employee rick = new Employee("Rick", 15, 33);
Employee mike = new Employee("Mike", 66, 50);
Employee jayme = new Employee("Jayme", 15, 45);
employees.add(bobby);
employees.add(rick);
employees.add(mike);
employees.add(jayme);
//Now we have added all the employees, so we can just run through them
System.out.println("Employee Hours Wage Total");
for(Employee employee: employees){
System.out.println(employee.toString());
}
}
}
Now you don't have to calculate everything many times, but just run through the list once, if you want to change the total, then you can calculate it inside here
public Employee(String name, int hours, int wage){
this.name = name;
this.hours = hours;
this.wage = wage;
this.total = hours * wage;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/48587206",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.