text
stringlengths 15
59.8k
| meta
dict |
|---|---|
Q: Zooming in without scaling graphics I'm learning Opengl for 2D, (in particular using the java slick2D library, but that might not be a factor for this question). I discovered I can change push a new transformation matrix, for instance to transform world coordinates into screen (view) coordinates.
I want to use this to zoom my view, increasing the distances between objects, but once this is done I want to paint images and shapes in screen coordinates, like a HUD. Basically, I want the coordinates to change, but the graphics to stay the same, so I can render custom images on each scale.
Can this be done with some clever transformation or some OpenGL option instead of manually calculating all coordinates?
A: *
*Clear color and depth buffers
*Set projection/modelview matrices for zoomed 2D/3D rendering
*Enable depth test
*Render zoomed 2D/3D scene
*Reset projection/modelview for 2D overlay
*Disable depth test
*Draw 2D overlay
*Repeat
A: Ok, figured it out, you have to use two separate projection:
1.- Scale the world coordinates, so that the objects are drawn on the correct scene locations:
g.pushTransform();
// Always zoom in the center of the screen.
g.translate(resolution.getX(), resolution.getY());
g.scale(scale, scale);
// Move the view
g.translate(-view.getX(), -view.getY());
2.- Push a new matrix to draw the object, inverting the scale transformation so the object's graphics don't change with scale:
g.pushTransform();
// Center on the current object.
g.translate(pos.x, pos.y);
// Undo scaling of graphics!
g.scale(1.0f/scale, 1.0f/scale);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/16108952",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: SQL subquery returns more then 1 row I am trying to run this query :
select r.rolekey
from roles r
where r.rolekey in (select r.rolekey
from roles r
where r.role_name like
(concat('%',
replace ((
select s.rolename
from savroles s
join user_savroles us
on s.rolekey = us.rolekey
where us.userkey = 24),'ROLE_REPONSABLE_RESSOURCE_',''),'%'))) ;
Problem : I have table SAV roles where SAV role name is like : ROLE_REPONSABLE_RESSOURCE_SAP_SIAG or ROLE_REPONSABLE_RESSOURCE_SAP_CIIAM. I can assign 1 or many SAV roles to a user.
THen I have a table "roles' where roles name are like : APP_SAP_CIIAM_Z_XX_BASIC,APP_SAP_SIAG_BW_ZU_CT_SIAGBI,ROLE_REPONSABLE_RESSOURCE_SAP_CIIAM. Basically the Roles name contains SAP_SIAG or SAP_CIIAM that is also a string in SAV role.
This query works if user has only 1 SAV role but when I assign more then I get Error code 1242 subquery returns more then 1 row.
I could point to a specific subquery in this query that seems to be a probelm :
select replace ((select s.rolename from savroles s join user_savroles us on s.rolekey = us.rolekey where us.userkey = 24 ),'ROLE_REPONSABLE_RESSOURCE_',''); I think replace does not like more then 1 result.
How I can overcome this issue - I want to build a list of SAV roles on which I run a replace so the list will contain only pure substrings like SAP_SIAG and then I want to concat the string with % so it can be compared to Roles.
A: replace expect single value, not unbounded. limit the result of your subquery. you use a subquery to join the filter again to your main table
select r.rolekey
from roles r
inner join
(select r.rolekey from roles r
inner join savroles s on r.role_name like concat('%', replace(s.rolename, 'ROLE_REPONSABLE_RESSOURCE_',''), '%')
inner join user_savroles us on s.rolekey = us.rolekey
where us.userkey = 24)
t1 on t1.rolekey = r.rolekey;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/58944645",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: viewDidLoad UIView with CGPoint() I want to create my own custom segue animation in which I want to make presenting VC appear from the button.origin at size(1,1) and shift to CGPoint(0,0) and stretch to full screen size.
VC1 segues to VC2 and passes VC1's button.frame via
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let PVC = segue.destinationViewController as VC2
PVC.CGstart = button.frame.origin}
in VC2 I have
@IBOutlet var VC4: UIView!
var CGstart = CGPoint()
override func viewDidLoad() {
super.viewDidLoad()
VC4.frame.origin = CGstart
}
@IBAction func DragTest(sender: UIButton) {
VC4.frame.origin = CGstart
println(CGstart)
}
the viewDidLoad does not adjust VC4's frame.origin....while my @IBAction func DragTest does
Why is this? I've tried so many different variations.
A: Try moving the origin setting to viewWillAppear.
override func viewWillAppear() {
super.viewWillAppear()
VC4.frame.origin = CGstart
}
A: This solved the issue.
override func viewDidLoad() {
super.viewDidLoad()
self.view.layoutIfNeeded()
VC4.frame.origin = CGstart
}
no need for viewDidAppear or layoutSubviews.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/29402649",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Why my localhost doesn't load a website? PHP - Fedora I'm working on Fedora 32 and I have a problem with php project. So, when I enter localhost/ProjectDir in my web browser, it lists all files that are in ProjectDir.
And that's fine... but when I try to test run my project (website of that project), so I enter *localhost/ProjectDir/public*, which has index.php inside - the error shown below occurs.
I have no idea what's wrong with that - I have set permission to 775, changed group that this directory belongs to (from kinda user-group to apache). Does anybody have an idea how to solve that problem? What else can I do?
A: as written in the exception, you need to add write permission for the web-server. First possible solution would be to set the owner or the group of the folder to www-data. Another solution would be to allow "others" to write in this folder. I would not recommend the second solution, because it could be less secure.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/66101432",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: neo4jclient merge query cause unhandled exception I want to use merge in my neo4jclient c# application, so I read this link and create a query like the below one :
resultList.ForEach(
tweets => client.Cypher
.Merge("(tweet:Tweet {newtweet})")
.OnCreate()
.Set("tweet = {newtweet}")
.WithParams(new Tweets(tweets))
.ExecuteWithoutResults());
But it crash and I don't know what I am missing.
Which part of my code is wrong?
A: First define your tweet class:
public class Tweet {
public long StatusId { get; set; }
public string Author { get; set; }
public string Content { get; set; }
}
Then try this statement like this:
var newTweet = new Tweet { StatusId = 2344
, Author = "@AuthorName"
, Content = "this is a tweet" };
graphClient.Cypher
.Merge("(tweet:Tweet { StatusId: {id} })")
.OnCreate()
.Set("tweet = {newTweet}")
.WithParams(new {
id = newTweet.StatusId,
newTweet
})
.ExecuteWithoutResults();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/32658527",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Can I split an array of this format to this? How can I do the below change in PHP?
Input:
[hiddenAllPrefered] => Array
(
[0] => 14477,14478,14479,14485,14486,14487
)
Output should be like this:
[hiddenAllPrefered] => Array
(
[0] => 14477,14478,14479
[1] => 14485,14486,14487
)
A: try this as a boilerplate
function chunker($arr, $l) {
return array_chunk($arr, $l);
}
print_r(chunker($hap, 3));
/*
Array
(
[0] => Array
(
[0] => 14477
[1] => 14478
[2] => 14479
)
[1] => Array
(
[0] => 14485
[1] => 14486
[2] => 14487
)
)
*/
UPDATE
php > $h = [ "14477,14478,14479,14485,14486,14487" ];
php > $hap = explode(",", $h[0]);
php > print_r($hap);
Array
(
[0] => 14477
[1] => 14478
[2] => 14479
[3] => 14485
[4] => 14486
[5] => 14487
)
php > print_r(chunker($hap, 3));
Array
(
[0] => Array
(
[0] => 14477
[1] => 14478
[2] => 14479
)
[1] => Array
(
[0] => 14485
[1] => 14486
[2] => 14487
)
)
php >
A: A possible solution:
$input = array('14477,14478,14479,14485,14486,14487');
$output = array_map(
function (array $a){
return implode(',', $a);
},
array_chunk(
explode(',', $input[0]),
3
)
);
Read it from inside out:
*
*explode() splits the string $input[0] using comma (,) as delimiter and returns an array;
*array_chunk() splits the array into chunks of size 3; it returns an array of arrays, each inner array contains 3 elements (apart from the last one that can contain less);
*array_map() applies the function it receives as its first argument to each value of the array it gets as its second argument (the array of arrays returned by array_chunk()); it returns an array whose values are the values returned by the function;
*the anonymous function passed to array_map() gets an array (of size 3 or less) and uses implode() to join its elements into a string, using comma (,) to separate the values and returns the string;
*array_map() puts together all the values returned by the anonymous function (one for each chunk of 3 elements of the array) into a new array it returns.
The output (print_r($output)) looks like this:
Array
(
[0] => 14477,14478,14479
[1] => 14485,14486,14487
)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/43715931",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: FMOD error in borland turbo c++ 4.5 when I'm trying to compile it gives me 26 errors however everything is at its right place
but won't able to understand the errors mostly constant is too long.
Plz help I want to play a mp3 file through C programming.
*errors are shown in the jpg image
#include "inc/fmod.h"
FMUSIC_MODULE* handle;
int main ()
{
// init FMOD sound system
FSOUND_Init (44100, 32, 0);
// load song
handle=FMUSIC_LoadSong ("don.mp3");
// play song only once
// when you want to play a midi file you have to disable looping
// BEFORE playing the song else this command has no effect!
FMUSIC_SetLooping (handle, false);
// play song
FMUSIC_PlaySong (handle);
// wait until the users hits a key to end the app
while (!_kbhit())
{
}
//clean up
FMUSIC_FreeSong (handle);
FSOUND_Close();
}
http://i.stack.imgur.com/JH4Ts.jpg
A: Borland Turbo C++ pre-dates most C++ standards and modern C. I would not expect FMOD or any modern library to work with this compiler.
Visual C++ is free to use in the Express form, and is a vastly better compiler.
A: The code you have listed is FMOD 3 code, yet you are using FMOD 4 headers (and probably libs too). This will not work, I can see from your error pic you have other troubles too, perhaps include paths not being set correctly.
We provide a Borland lib that you will need to link with: 'fmodex_bc.lib' but again this is FMOD 4 code, I would highly recommend looking at the 'playstream' example that ships with the SDK, it demonstrates MP3 playback.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/8509794",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Deserializing a multidimensional JSON string I'm new here, so please excuse any lapses in proper question procedure!
Basically, I'm trying to deserialize a json array from the Pearson Dictionary Web API. Here's the JSON (I removed some excess results indices to conserve space):
{
"status": 200,
"offset": 0,
"limit": 10,
"count": 10,
"total": 47,
"url": "/v2/dictionaries/ldoce5/entries?headword=test",
"results": [
{
"datasets": [
"ldoce5",
"dictionary"
],
"headword": "test",
"homnum": 1,
"id": "cqAFzDfHTM",
"part_of_speech": "noun",
"pronunciations": [
{
"audio": [
{
"lang": "British English",
"type": "pronunciation",
"url": "/v2/dictionaries/assets/ldoce/gb_pron/brelasdetest.mp3"
},
{
"lang": "American English",
"type": "pronunciation",
"url": "/v2/dictionaries/assets/ldoce/us_pron/test1.mp3"
}
],
"ipa": "test"
}
],
"senses": [
{
"definition": [
"a set of questions, exercises, or practical activities to measure someone's skill, ability, or knowledge"
],
"examples": [
{
"audio": [
{
"type": "example",
"url": "/v2/dictionaries/assets/ldoce/exa_pron/p008-001626298.mp3"
}
],
"text": "Did you get a good mark in the test ?"
}
],
"gramatical_examples": [
{
"examples": [
{
"audio": [
{
"type": "example",
"url": "/v2/dictionaries/assets/ldoce/exa_pron/p008-000592041.mp3"
}
],
"text": "We have a test on irregular verbs tomorrow."
}
],
"pattern": "test on"
}
],
"signpost": "exam"
}
],
"url": "/v2/dictionaries/entries/cqAFzDfHTM"
}
]
}
And here is the C# code I'm using to deserialize the above:
class Program
{
static void Main(string[] args)
{
string word = "test";
string sURL = "https://api.pearson.com:443/v2/dictionaries/ldoce5/entries?headword=" + word;
WebClient client = new WebClient();
string full = client.DownloadString(sURL);
var final = JsonConvert.DeserializeObject<Dictionary>(full);
Console.WriteLine(final.results[0].senses.definition);
}
}
public class Dictionary
{
public Result[] results { get; set; }
}
public class Result
{
public string part_of_speech { get; set; }
public Senses senses { get; set; }
}
public class Senses
{
public string definition { get; set; }
}
For some reason, I'm getting this strange error when I try to run it:
Cannot deserialize the current JSON array (e.g. [1,2,3]) into type
'TestingJson.Senses' because the type requires a JSON object (e.g.
{"name":"value"}) to deserialize correctly. To fix this error either
change the JSON to a JSON object (e.g. {"name":"value"}) or change the
deserialized type to an array or a type that implements a collection
interface (e.g. ICollection, IList) like List that can be
deserialized from a JSON array. JsonArrayAttribute can also be added
to the type to force it to deserialize from a JSON array. Path
'results[0].senses', line 1, position 512.
Help would be greatly appreciated!
A: If you're interacting with something well defined (i.e. the vast majority of APIs out there), then you're much better off creating a strongly typed object(s) instead of dynamic or dictionary.
In Visual Studio if you go Edit>Paste Special>Paste JSON as Classes then it will generate all the objects you need.
public class Rootobject
{
public int status { get; set; }
public int offset { get; set; }
public int limit { get; set; }
public int count { get; set; }
public int total { get; set; }
public string url { get; set; }
public Result[] results { get; set; }
}
public class Result
{
public string[] datasets { get; set; }
public string headword { get; set; }
public int homnum { get; set; }
public string id { get; set; }
public string part_of_speech { get; set; }
public Pronunciation[] pronunciations { get; set; }
public Sens[] senses { get; set; }
public string url { get; set; }
}
public class Pronunciation
{
public Audio[] audio { get; set; }
public string ipa { get; set; }
}
public class Audio
{
public string lang { get; set; }
public string type { get; set; }
public string url { get; set; }
}
public class Sens
{
public string[] definition { get; set; }
public Example[] examples { get; set; }
public Gramatical_Examples[] gramatical_examples { get; set; }
public string signpost { get; set; }
}
public class Example
{
public Audio1[] audio { get; set; }
public string text { get; set; }
}
public class Audio1
{
public string type { get; set; }
public string url { get; set; }
}
public class Gramatical_Examples
{
public Example1[] examples { get; set; }
public string pattern { get; set; }
}
public class Example1
{
public Audio2[] audio { get; set; }
public string text { get; set; }
}
public class Audio2
{
public string type { get; set; }
public string url { get; set; }
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/32293130",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: translate text of ion select's ok and cancel buttons I want to translate ok and cancel buttons of ionic ion-select to local languages. These two OK and CANCEL buttons should be translated.
Can anyone guide me how to do that?
A: If using ngx-translate you can do the following:
<ion-select formControlName="myControl" [okText]="'okText' | translate" [cancelText]="'cancelText' | translate"></ion-select>
In translation file e.g. en.json
{
"okText": "OK",
"cancelText": "Cancel"
}
A: <ion-select multiple="true" okText="Okay" cancelText="Dismiss">
I am not sure but you can try this too
<ion-select multiple="true" okText="ٹھیک ہے" cancelText="خطرہ">
A: This work for me using ngx-translate doing the following:
HTML FILE
<ion-select cancelText="{{'SELECT.Cancel' | translate:params}}"
okText="{{'SELECT.ok' | translate:params}}">
</ion-select>
i18n en.josn FILE
{
"SELECT": {
"ok":"OK",
"Cancel":"Cancel"
},
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/45181236",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Execution in FixedThreadPool gets slower as time goes by I have around 100000 tasks need to be done, I know that they are CPU intensive, but will only take a short execution time (When CPU is fast enough).
I use ExecutorService executor = Executors.newFixedThreadPool(8);
I choose 8 because my CPU has 8 cores.
Then to process my tasks, I loop through all of them:
for(Task task : tasks) {
executor.submit(new Runnable() {
// 1. Text analyzing
// 2. Add result to a LinkedBlockingQueue
}
}
What I observed is that for the first few thousands of task, it is really fast. But then, says after 10k tasks has been processed, the speed becomes slower, and slower...
I tried to understand but fail to figure out why it gradually becomes slower. Since when a task is done, the resource will also be freed. So I expected that the processing speed should be stable.
Then I figured out that the problem may belong to the LinkedBlockingQueue that I use to store the result from the task. But it seems that LinkedBlockingQueue provides good performance for inserting.
Can someone give me some hints or suggestions what I may do wrong in this case?
Thank you.
A: The problem belongs to the performance decrement of the LinkedBlockingQueue. In my case the producers were more productive in adding data to the queue while the consumers were too slow to handle.
Java performance problem with LinkedBlockingQueue
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/36843866",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Show the default timezone from a date time string in PHP I'm trying to pull out the timezone from a string I'm receiving from an API to display it separately.
After reading a ton of answers none of them seem to cover this simple task I'm trying to do.
The string comes as 2019-01-17T10:00:00-05:00
1- If I do echo date('P', $variablecontainingthestring); it will return +00:00 for some reason.
2- If I do $datevar = date($variablecontainingstring); this will return 2019-01-17UTC10:00:00-05:00, doing the same echo as #1 but with the $datevar will also return +00:00 when it is clearly -05:00
Thanks for any help.
A: date in PHP accepts 2 parameters. The first is the format you want the date to be displayed in, and the second is a unix timestamp. What you would be better of using is the DateTime class. Then you can get the timezone like this:
echo (new \DateTime('2019-01-17T10:00:00-05:00'))->format('P');
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/54046082",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: how to manage rounding in angular filter? I am developing an angular filter that rounds of to 6 decimals. What I cant figure out how to round to 2 decimals when the decimals contain only zeros. So 1.00000 would convert to 1.00.
This is what my filter looks like:
app.filter('customCurrency',function ($filter) {
return function (amount, currencySymbol,fractionSize) {
var currency = $filter('currency');
if (amount < 0) {
return currency(amount, currencySymbol).replace('(', '-').replace(')', '');
}
debugger;
if (fractionSize !== undefined) {
amount = currency(amount, currencySymbol, fractionSize);
} else {
amount = currency(amount, currencySymbol)
}
debugger;
var amounts = amount.split(".");
var amountHtml ;
if (amounts[1].length==2 && amounts[1][0]==0 && amounts[1][1]==0)
{
amountHtml = amounts[0] + '<span class="decimals">.00</span>';
}
else
{
amountHtml= amounts[0] + '<span class="decimals">.' + amounts[1] + '</span>';
}
return amountHtml;
};
});
plunkr:http://plnkr.co/edit/cGmYcsqwn3huanOeX4g4?p=preview
A: try this one
it('if I have 3 zeros or more in decimals only display max of 2 zeros in decimals', function() {
// using $filter
expect($filter('customCurrency')(1.000, '$', 2)).toEqual('$1<span class="decimals">.00</span>');
});
A: Not sure this will work out for you in the long run as I'm sure there is a better way to go about this, but if you want a quick and dirty fix try this:
DEMO
app.filter('customCurrency',function ($filter) {
return function (amount, currencySymbol, fractionSize) {
var currency = $filter('currency');
if (amount < 0) {
return currency(amount, currencySymbol).replace('(', '-').replace(')', '');
}
debugger;
if (fractionSize !== undefined) {
amount = currency(amount, currencySymbol, fractionSize);
} else {
amount = currency(amount, currencySymbol)
}
debugger;
var amounts = amount.split("."),
fractionalPart = amounts[1],
decimals = fractionalPart.length,
zerosFromRight = countZerosFromRight(fractionalPart);
if(zerosFromRight > 2){
return amounts[0] + '<span class="decimals">.00</span>';
}
return amounts[0] + '<span class="decimals">.' + amounts[1] + '</span>';
///////////////////////////////////
function countZerosFromRight(str){
var len = str.length,
count = 0;
while(len--){
if(str[len] === '0'){
count++;
continue;
}
break;
}
return count
}
};
});
EDIT
Had a rethink and think this way is better:
I've added this test and maybe you don't need this functionality but I think this is a bit more robust.
DEMO2
it('should only remove the zeros up to the last non-zero number', function() {
expect($filter('customCurrency')(1.004000, '$', 6)).toEqual('$1<span class="decimals">.004</span>');
expect($filter('customCurrency')(1.4066000, '$', 6)).toEqual('$1<span class="decimals">.4066</span>');
});
app.js
var app = angular.module('plunker', ['ngRoute']);
'use strict';
var app = angular.module('plunker');
app.filter('customCurrency',function ($filter) {
return function (amount, currencySymbol, fractionSize) {
var currency = $filter('currency');
if (amount < 0) {
return currency(amount, currencySymbol).replace('(', '-').replace(')', '');
}
debugger;
var rounded = round(amount, fractionSize),
currencyString = currency(rounded, currencySymbol, fractionSize),
amounts = currencyString.split("."),
integerPart = amounts[0],
fractionalPart = amounts[1] || false,
indexLastNonZero = indexLastNonZero(fractionalPart);
// if only zeros after decimal then remove all but 2
if(indexLastNonZero === -1){
return integerPart + '<span class="decimals">.00</span>';
}
// if zeros and other numbers after decimal remove all trailing zeros
if(indexLastNonZero > 1){
return integerPart + '<span class="decimals">.' + fractionalPart.slice(0, indexLastNonZero + 1) + '</span>';
}
return integerPart;
/////////////////////////////////////////////
function round(str, decimals){
var num = +str;
return num.toFixed(decimals);
}
function indexLastNonZero(str){
var len = str.length;
while(len--){
if(str[len] !== '0'){
return len;
}
}
return -1;
}
};
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/31398678",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Extern stuct in C source files I am trying to have a dictionary_object structure named dict_obj available in two separate .c files. This is while trying to write a pthread TCP server for a class. I have not worked much with C before and am having a difficult time getting this figured out. I'm not sure if I'm declaring this as an external structure correctly as netbeans is throwing off errors on clean and build saying invalid use of undefined type.
In db_functions.c I have:
//------------------------------------------------------------------------------
// Server Function & Variable Initialization
//------------------------------------------------------------------------------
struct dictionary_object dict_obj;
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// Server Function Codes:
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// Database Initialization
//------------------------------------------------------------------------------
int db_initialization()
{
dict_obj.word_count = 0;
return 1;
In db_operations.c I have:
struct dictionary_object
{
char dictionary[DICTIONARY_SIZE][WORD_LENGTH];
int word_count;
pthread_mutex_t dict_mutex;
};
extern struct dictionary_object dict_obj;
Hopefully this gives you guys enough idea of what I'm trying to accomplish without having to overwhelm you with too much code. Thanks in advance! Let me know if you need to see more of the code.
A: I'll go out on a limb and guess that your problem is that the C compiler complains that it doesn't know how to allocate memory for a struct dictionary_object when it compiles db_functions.c. Its confusion is understandable because the file you're asking it to compile doesn't tell it what struct dictionary_object is at all.
You should move the definition of the struct to a header file that both of your .c files include.
A: You need to define the structure contents and layout once in an include file. Also define the "extern" definitions for all functions and statics for the code there. In any file wanting to use those structs or definitions, include the header file (something like db_struct.h).
db_struct.h:
struct dictionary_obhect {
char dictionary ...
}
extern struct dictionary_object dict_obj;
extern int db_initialization();
db_struct.c:
#include "db_struct.h"
struct dictionary_object dict_obj;
int db_initiatilization() {
dict_obc.word_count = 0;
}
Note this is all pretty old-style C code. Modern C++ etc. have other means of doing similar things.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/13300060",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: mcrypt_encrypt adds unwanted bytes I'm trying to encrypt some data using the MCRYPT_RIJNDAEL_128 algoritm. But somehow when I encrypt and afterwards decrypt, the decrypted data has randomly added bytes.
The input: string(13) "test@test.com"
The output: string(16) "test@test.com"
As you can see the output has 16 characters while the input has 13.
The following is the code used for encryption.
class Cipher
{
/**
* The key/salt(bin2hex format) used to encrypt data with in AES(RIJNDAEL) format.
* @var string
*/
private static $encryptionKey = 'baafbd1f8d752d920caae00ae550be8185c1183207a142c97c36fca3edc507da';
/**
* Gets and transforms the encryption key to binary format.
* @return string (in binary format)
*/
public static function getEncryptionKey()
{
return hex2bin(self::$encryptionKey);
}
/**
* Generates a new random main encryption key used to encrypt data.
* Store the generated key in the private property of this class.
* @param bool $strong Whether the encryption will be strong.
* @return string The generated key in hexadecimal format.
*/
public static function generateEncryptionKey($strong = true)
{
$keySize = mcrypt_get_key_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
return bin2hex(openssl_random_pseudo_bytes($keySize, $strong));
}
/**
* Creates an encryption key IV used to store near the database record for the encrypted data.
* Use bin2hex function for a representational string.
* @return string (in binary format)
*/
public static function createIv()
{
$ivSize = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
return mcrypt_create_iv($ivSize, MCRYPT_DEV_URANDOM);
}
/**
* Encrypts a given string by the generated encryption key and generated IV.
* @param string $string The string which will be encrypted.
* @param string $iv The dynamic key used to encrypt.
* @return string (in binary format)
*/
public static function encrypt($string, $iv)
{
return mcrypt_encrypt(MCRYPT_RIJNDAEL_128, self::getEncryptionKey(), $string, MCRYPT_MODE_CBC, $iv);
}
/**
* Decrypts a given string by the generated encryption key and generated IV.
* @param string $string The binary string which will be decrypted.
* @param string $iv The dynamic key which belongs to the encrypted string.
* @return string The decrypted string.
*/
public static function decrypt($string, $iv)
{
return mcrypt_decrypt(MCRYPT_RIJNDAEL_128, self::getEncryptionKey(), $string, MCRYPT_MODE_CBC, $iv);
}
}
The encryption key showed here isn't used in production or testing environments and is only used for display purposes.
The following is used to display the decryption
$iv = Cipher::createIv();
$emailAddress = Cipher::encrypt('test@test.com', $iv);
var_dump(Cipher::decrypt($emailAddress, $iv));exit;
I'm using the following environments:
Ubuntu: 14.10
PHP: PHP 5.5.9-1ubuntu4.3 (cli) (built: Jul 7 2014 16:36:58)
A: Those are just padding 0x00 characters added at the end, because the string's length for that cryptographic algorithms has to be a multiple of 16 (with 128 bit).
Indeed, if you add at the end of your code:
var_dump(bin2hex(Cipher::decrypt($emailAddress, $iv)));
You can see that the last 6 characters are all 0's (which means there are 3 0x00 bytes at the end).
To remove them, just run:
$decrypted = rtrim($decrypted, "\0");
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/25489509",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Custom tag that evaluates its body based on the variables of the tag Ok, now this is something for the hard core JSTL wizards I guess ;-)
I would like to have a tag whose body does not substitute the variables of the surrounding page. It should only take the variables into account that have been specified in the body of the tag or in the tag itself like this:
<c:set var="outsideVar" value="outside value"/>
<a:component>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<div data-component-id="9">
<c:set var="componentId" value="9"/>
<c:set var="path" value='${abc:getCurrentPath()}_${componentId}'/>
<c:set var="resource" value='${abc:getResourceFromPath(path)}'/>
<c:set var="val" value="${resource.getValue('paragraphValue')"/>
<p>${fn:escapeXml(val)}</p>
${outsideVar}
</div>
</a:component>
The outsideVar variable should not be set and the body of the tag should behave like the content of a <jsp:include/>
This is a more specific question of this one:
Is it possible to create a local page scope in a JSP?
The link also explains the background of this question.
A: Your custom tag can grab and remove all page attributes before evaluating the body, and then clear and restore afterwards.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/32404445",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to remove an incremental element in HTML using JavaScript So I want to create a function that will let me add/remove an element in the HTML, I'm already done with the "add" part that increments the id value onchange (example: id=tag1, id=tag2, etc). My problem is on the "remove" part, I don't know how to put an incremental value inside onclick=remove_tag(). Here's my code
function update() {
var selObj = document.getElementById("skill_tags");
var selVal = selObj.options[selObj.selectedIndex].text;
let counter = 0;
document.getElementById("textarea").innerHTML += "<div class='tags_inline' id='tag'><li class='list-inline-item'><span class='badge badge-dark'>" + selVal + "<button class='fa fa-times-circle text-white' id='delete' onclick=remove_tag('tag"+ counter +"');></button></span></li></div>";
$("#textarea div").each(function(i){this.id = "tag" + (i + 1)})
}
function remove_tag(id) {
document.getElementById(id).innerHTML = "";
}
What I want to do is to make my onclick on the button to be (onclick="remove_tag1", onclick="remove_tag2", onclick="remove_tag3", etc). Sorry for the question, still a newbie in JavaScript. Thanks for the help. Here's an image https://pasteboard.co/k7hb7cVHSQHj.png
<div class="resume-skill-item">
<h5>
<ul class="list-inline">
<div align="right">
<select id="skill_tags" onchange="update()">
<option selected="true" disabled="disabled">*Select All That Applies</option>
<option value="mechanic">Mechanic</option>
<option value="appliance_repairer">Appliance Repairer</option>
<option value="carpenter">Carpenter</option>
<option value="plumber">Plumber</option>
<option value="technician">Technician</option>
</select>
</div>
</ul>
<div id="textarea" class="large-single-textarea">
</div>
</h5>
</div>
```
A: You can use data attribute on delete button to keep reference on added items when you want to delete them.
function update(e) {
var selObj = document.getElementById("skill_tags");
var selVal = selObj.options[selObj.selectedIndex].text;
let counter = 0;
document.getElementById("textarea").innerHTML +=
`<div class="tags_inline" id="${e.value}"><li class="list-inline-item"><span class="badge badge-dark">"${selVal}"<button data-select-id="${e.value}" class="fa fa-times-circle text-white" id="delete" onclick=remove_tag(this) >remove</button></span></li></div>`;
}
function remove_tag(e) {
document.getElementById(e.dataset["selectId"]).remove();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="resume-skill-item">
<h5>
<ul class="list-inline">
<div align="right">
<select id="skill_tags" onchange="update(this)">
<option selected="true" disabled="disabled">*Select All That Applies</option>
<option value="mechanic">Mechanic</option>
<option value="appliance_repairer">Appliance Repairer</option>
<option value="carpenter">Carpenter</option>
<option value="plumber">Plumber</option>
<option value="technician">Technician</option>
</select>
</div>
</ul>
<div id="textarea" class="large-single-textarea">
</div>
</h5>
</div>
A: You can do it by sending the element itself thru args to the remove_tag function:
function update() {
var selObj = document.getElementById("skill_tags");
var selVal = selObj.options[selObj.selectedIndex].text;
//add tag with a remove_tag(this) onclick action
document.getElementById("textarea").innerHTML +=
"<div class='tags_inline' id='tag'><li class='list-inline-item'><span class='badge badge-dark'>" + selVal +
"<button class='fa fa-times-circle text-white' id='delete' onclick=remove_tag(this);></button></span></li></div>";
}
Then by DOM tree we can access and remove the element.
The DOM tree for this looks like div > li > span > button
The click event is triggered on the button so the function will look like this:
function remove_tag(element) {
//Here we grab the node that tag is on at the DOM tree
let tag = element.parentNode.parentNode;
//Same with the father div
let div = tag.parentNode;
//Then from that div we remove the selected element
div.removeChild(tag);
}
I recommend you to read more about the DOM
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/70255598",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Genymotion virtual device loads too slow I use Genymotion 2.7.2 with VirtualBox 5.0.4. I run my virtual machine (Google Nexus 5 - 6.0.0 - API 23) but my machine loads too slow (10 - 15 min) with this long black screen (view image).I check in a running window on VirtualBox and I get some command line in this picture (view image)
I try to fix but everything still work slowly. However, after the long loading, my virtual device works well, but it really wastes me a lot of time to wait it available. Can anyone help me? Thank you.
P/s: I have this issue on windows 10, but in other windows and even linux, everything works well.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/38483108",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How can i limit function-(slot play) just for 5 turn - with do/while loop I wanna create a slot machine with 3 number by javascript - but I want to finish my function when three numbers are equal.
I think that if I write it with do/while it will be work, but I can't do it
this is my js code:
function myF() {
var slotOne = Math.floor(Math.random() * 3) + 1;
var slotTwo = Math.floor(Math.random() * 3) + 1;
var slotThree = Math.floor(Math.random() * 3) + 1;
document.getElementById("slotOne").innerHTML = slotOne;
document.getElementById("slotTwo").innerHTML = slotTwo;
document.getElementById("slotThree").innerHTML = slotThree;
if(slotOne == slotTwo && slotTwo == slotThree) {
document.getElementById("slotOne").style.backgroundColor = "#48bd48";
document.getElementById("slotTwo").style.backgroundColor = "#48bd48";
document.getElementById("slotThree").style.backgroundColor = "#48bd48";
document.getElementById("winner").classList.add("show");
}
}
this function is set onclick attr of a button tag
A: Adding to comment, if you want to run function for no of times then just use a counter variable to check no of attempts:
Added a reset button to reset the game.
var counter = 0;
function myF() {
if (counter != 5) {
counter++;
document.getElementById("slotLeft").innerHTML = "Try count: " + counter;
var slotOne = Math.floor(Math.random() * 3) + 1;
var slotTwo = Math.floor(Math.random() * 3) + 1;
var slotThree = Math.floor(Math.random() * 3) + 1;
document.getElementById("slotOne").innerHTML = slotOne;
document.getElementById("slotTwo").innerHTML = slotTwo;
document.getElementById("slotThree").innerHTML = slotThree;
if (slotOne == slotTwo && slotTwo == slotThree) {
document.getElementById("slotOne").style.backgroundColor = "#48bd48";
document.getElementById("slotTwo").style.backgroundColor = "#48bd48";
document.getElementById("slotThree").style.backgroundColor = "#48bd48";
document.getElementById("winner").classList.add("show");
counter = 5; // Edited this line
}
} else {
console.log('Game over');
}
}
function myF1(){
counter = 0;
document.getElementById("slotOne").innerHTML = "";
document.getElementById("slotTwo").innerHTML = "";
document.getElementById("slotThree").innerHTML = "";
}
<button onclick="myF()">Check</button>
<button onclick="myF1()">Restart Game</button>
<div id="slotLeft">
</div>
<div id="slotOne">
</div>
<div id="slotTwo">
</div>
<div id="slotThree">
</div>
<div id="winner">
</div>
A:
function myF() {
var slotOneElem = document.getElementById("slotOne");
var slotTwoElem = document.getElementById("slotTwo");
var slotThreeElem = document.getElementById("slotThree");
var generateRand = function() {
return Math.floor(Math.random() * 3) + 1;
}
return (function () {
var slotOne = generateRand();
var slotTwo = generateRand();
var slotThree = generateRand();
slotOneElem.innerHTML = slotOne;
slotTwoElem.innerHTML = slotTwo;
slotThreeElem.innerHTML = slotThree;
if (slotOne === slotTwo && slotTwo === slotThree) {
slotOneElem.style.backgroundColor = "#48bd48";
slotTwoElem.style.backgroundColor = "#48bd48";
slotThreeElem.style.backgroundColor = "#48bd48";
document.getElementById("winner").classList.add("show");
// Here is the win
return true;
}
return false;
})();
}
var finished = myF();
while (!finished) {
finished = myF();
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/53968946",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: By what logic, should instance constructors have access to static fields I was wondering why do instance constructor have access to static fields? If I initialize static fields via static constructors, and by mistake again initialize them through instance constructors, then the second initialization overwrites the first one. What is the idea behind making them accessible through instance constructors? (Please have a look at the simple program below to understand my point)
using System;
class Program
{
static void Main()
{
Circle C1 = new Circle(5);
Console.WriteLine("The area of the first circle is {0}", C1.CalculateArea());
}
}
class Circle
{
public static float _Pi; // Since the value of pi will not change according to circles, we have to make it static
int _Radius; // This is an instance field, whose value is different for different instances of the class
static Circle() // A static constructor initializes the static fields
{
Console.WriteLine("Static constructor executed");
Circle._Pi = 3.14F;
}
public Circle(int Radius) // An instance constructor initializes the instance fields
{
Console.WriteLine("Instance constructor executed");
this._Radius = Radius;
Circle._Pi = 2.12F; // This again initializes the value of the pi to a different value as given by the static constructor
}
public float CalculateArea()
{
return this._Radius*this._Radius*Circle._Pi;
}
}
A: As an example of a use case where a constructor could want access to static members is when a static field contains a counter of instances for a class. You may want a class member to get, retain (in a non-static field), and increment this counter which would be static. Any time in the future that instance will have its own unique identifier.
Example:
public class Employee {
static int NextEmployeeId; // a counter across all employees
public int EmployeeId; // this instance's employee id
public string Name; // this instance's name.
static Employee() {
Employee.NextEmployeeId = 1; // first employee gets 1.
}
public Employee(string Name) {
this.Name = Name;
this.EmployeeId = Employee.NextEmployeeId++; // take an id and increment for the next employee
}
}
A: Static fields are accessible from everywhere, even from constructor, or even from Main/other class. The purpose is that you will have only one static property/ field singleton for the whole app.
public class AClass()
{
public static float staticField;
public float field;
public AClass()
{
staticField = 5;
field = 6;
}
static AClass()
{
staticField = 7;
}
}
public int Main()
{
float initially = AClass.staticField; // initially this staticField is 7.
AClass aclass = new AClass(); // instantiating AClass
float localfield = aclass.field; // this field does not affect anyone. It is 6
float newStaticField = AClass.staticField; // Due to previous instantiation, the value is now 5.
}
And I agree with you that in your example it is bad. Why? Because why would you change the value of Pi, since it is already determined and fixed, there is no reason to change the value of Pi in the constructor.
You probably need to know how to design class and get to know why you want to have the static field in the first place. Here is an example of a class which does it correctly having a static field (sort of... for example, because the Key should be hidden supposedly. This is just to show you how static field is useful and ok.):
public class NewEncryptionClass()
{
public static string Key;
public NewEncryptionClass()
{
}
public NewEncryptionClass(string newKey)
{
Key = newKey; // store the key and keep it forever
}
static NewEncryptionClass()
{
Key = "key1"; // initially key is "key1"
}
public string Encrypt(string str)
{
string result = string.Empty;
result = "adlasdjalskd" + Key + "ajlajfalkjfa" + str; // do the Encryption, I just made up
return result
}
}
Here, the purpose is that if you instantiate a NewEncryptionClass, you would want to save the key, so that the next time you do the encryption, you would always use the latest key without having to specify it everytime. For ex:
public int Main()
{
string initialkey = NewEncryptionClass.Key;
string result1 = new EncryptionClass().Encrypt("encryptThis"); // using key1
// let's change the key
string result2 = new EncryptionClass("key2").Encrypt("encryptThat"); // using key2
string result3 = new EncryptionClass().Encrypt("encryptOther"); // still using key2
}
This is of course if I want to keep the latest key forever, if not, then this class design is wrong and you need to rewrite it for your purpose.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/43508579",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
}
|
Q: How do I make UILabel's text flush with the top of its bounds? If I create a UILabel, set its text and call sizeToFit, there is still a small vertical gap between the top of the text and the top of the UILabel's bounds. How do I either eliminate the vertical gap, or calculate it so that I can extend -[UILabel drawTextInRect:] and eliminate it myself?
I've made a small test app to demonstrate the vertical space issue.
A: iOS creates a synthetic leading for all fonts, even those which don't have leading specified in the font files.
The only way to achieve this is to draw the label text yourself.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/12793020",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Many to many relation for same rank tables For example I have online store with keyboards and mouses tables. And on the product(keyboard or mouse) page I want to show Recommended to buy with... section where other product (keyboard or mouse) will appear. So on Keyboard#1 page may be recommended Keyboard#2 and Mouse#1, that means on Keyboard#2 and Mouse#1 pages will be recommended Keyboard#1.
The main question is, can I get by with one table?
I thought something about many to many (Polymorphic) relation but I am not sure if this will work.
Below is a rough scheme of what I think about right now:
Tables:
keyboards
*
*id
*number_of_keys
mouses
*
*id
*is_wireless
associations
*
*product_1_associatable_id
*product_1_associatable_type
*product_2_associatable_id
*product_2_associatable_type
Models:
Keyboard
public function associations()
{
return $this->morph...?('associatable');
}
Mouse
public function associations()
{
return $this->morph...?('associatable');
}
Upd: It's ok if there will be several relations but still only 1 table e.g. associated_keyboards and associated_mouses relations
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/67090763",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to get the external ip in Objective-C I looked for some code that will help me to get the ip that the iPhone connect with.
I find this one:
- (NSString *)getIPAddress
{
NSString *address = @"error";
struct ifaddrs *interfaces = NULL;
struct ifaddrs *temp_addr = NULL;
int success = 0;
// retrieve the current interfaces - returns 0 on success
success = getifaddrs(&interfaces);
if (success == 0)
{
// Loop through linked list of interfaces
temp_addr = interfaces;
while(temp_addr != NULL)
{
if(temp_addr->ifa_addr->sa_family == AF_INET)
{
// Check if interface is en0 which is the wifi connection on the iPhone
if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"])
{
// Get NSString from C String
address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
}
}
temp_addr = temp_addr->ifa_next;
}
}
// Free memory
freeifaddrs(interfaces);
return address;
}
but the problem is that he get me this ip
10.0.0.1
How to get the external ip?
A: The easiest way to get your internet ip address from code is to use NSURLConnection.
For the URL you can use:
http://www.whatismyip.com/m/mobile.asp
or
http://checkip.dyndns.com/
Just parse the return data and you have your external ip address.
A: Check Apple's PortMapper, does exactly what you want.
As of iOS7 this is irrelevant.
A: Have a look at the example in my second Answer here.
In a nutshell it uses *http://www.dyndns.org/cgi-bin/check_ip.cg*i to get the extenal I.P
A: Late to the party, but https://api4.ipify.org or http://api4.ipify.org returns nothing else but the external IPv4 address of your connection. Code:
NSURL *ipifyUrl = [NSURL URLWithString:@"https://api4.ipify.org/"];
NSString *externalAddr = [NSString stringWithContentsOfURL:ipifyUrl encoding:NSUTF8StringEncoding error:nil];
https://api6.ipify.org returns the external IPv6 address and https://api64.ipify.org either the IPv4 or the IPv6 address. Simple documentation can be found at https://www.ipify.org
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/5450621",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: How to do batch processing in Pro*c enter code hereI want to do batch processing using host array in pro c. But when the records are not equal to array length*n (n is 1 ,2 ,3 ...) then my program is failed to fetched row.
I dont know how to fetch remaining records.
int empid[20];
my table contains 24 records.
so after 1st fetch its showing error.
void print_rows(n)
int n;
{
int i;
printf("\nNumber Employee Salary");
printf("\n------ -------- -------\n");
for (i = 0; i < n; i++)
printf("%d %s %8.2f\n", emp_rec.emp_number[i],
emp_rec.emp_name[i], emp_rec.salary[i]);
}
void main()
{
int num_ret; /* number of rows returned */
EXEC SQL WHENEVER SQLERROR DO sql_error("Oracle error:");
/* Declare a cursor for the FETCH. */
EXEC SQL DECLARE c1 CURSOR FOR
SELECT empno, ename, sal FROM emp;
EXEC SQL OPEN c1;
/* Initialize the number of rows. */
num_ret = 0;
/* Array fetch loop - ends when NOT FOUND becomes true. */
EXEC SQL WHENEVER NOT FOUND DO break;
for (;;)
{
EXEC SQL FETCH c1 INTO :emp_rec;
/* Print however many rows were returned. */
print_rows(sqlca.sqlerrd[2] - num_ret);
num_ret = sqlca.sqlerrd[2]; /* Reset the number. */
}
/* Print remaining rows from last fetch, if any. */
if ((sqlca.sqlerrd[2] - num_ret) > 0)
print_rows(sqlca.sqlerrd[2] - num_ret);
EXEC SQL CLOSE c1;
/* Disconnect from the database. */
EXEC SQL COMMIT WORK RELEASE;
exit(EXIT_SUCCESS);
}`
`
Please help me how to fetch remaining records using pro c
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/47182227",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How To Include Xml File In Other Xml File Iwant to include or call dependencies xml file in testng xml file any helps????
I want Include
dependencies.xml:
<groups>
<group name="publierlivraison" depends-on="creerlivraison"></group>
</groups>
File in
TestNG.xml :
<test name="Managetestss" preserve-order="true">
<parameter name="browser" value="chrome"></parameter>
dependencies.xml????? how to include here this file
<classes>
<class name="com.az.tests.commun.TNR_Client_001_Ajouter_Client" />
<class name="com.az.tests.client.TNR_Client_002_Rechercher_Client"
</classes>
</test>
A: Maybe something like this:
<?xml version='1.0' encoding="UTF-8"?>
<document xmlns:xi="http://www.w3.org/2001/XInclude">
<p>Text of my document</p>
<xi:include href="copyright.xml"/>
</document>
https://en.wikipedia.org/wiki/XInclude
A: Below example should work to include external file:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "testng-1.0.dtd"
[<!ENTITY parent SYSTEM "./src/test/resources/dependencies.xml">]>
<suite name="suite1">
<test name="Managetestss" preserve-order="true">
&parent;
<parameter name="browser" value="chrome"></parameter>
<classes>
<class name="com.az.tests.commun.TNR_Client_001_Ajouter_Client" />
<class name="com.az.tests.client.TNR_Client_002_Rechercher_Client"
</classes>
</test>
</suite>
However the dependencies.xml you provided will not work because testng DTD doesn't support group tag under groups. Refer groups-of-groups and dependencies-in-xml
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/55160846",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Redirecting old anchor links to new anchor links I'm overhauling a website that someone else built for my organization. It was originally set up with "not so great" anchor links which included spaces. I have replaced those anchors with new ones that will work better.
Example:
One of the old anchors looked like this /course/#To Have which browsers would luckily convert to /course/#To%20Have. I changed that anchor to this: /course/#to-have.
I'm now wanting to make sure that any anchors that may have been shared on social media or that could be linked to from other websites still work; I was planning on doing this via redirect in the .htaccess file, such as this one:
Redirect 301 /course/#To%20Have /course/#to-have
After some research I've found that this is not possible due to the # in the URLs. And I also have not seen examples where an anchor was redirected to another anchor.
Is this possible?
A: As mentioned in my comment, this is not possible with .htaccess.
Reason being: the hash part (known as the fragment) is not actually sent to the server, and so Apache would not be able to pick it up. Servers may only pick up everything before that, which is described in the Syntax section of this article.
As an alternative, I would recommend that you use JavaScript to convert the fragment before scrolling to its location. You can do that by pulling in the value of [window.]location.hash (the part in square parenthises is optional as location is also available in the global scope) if it exists, as shown below:
if (window.location.hash) {
// Function to 'slugify' the fragment
// @see https://gist.github.com/mathewbyrne/1280286#gistcomment-1606270
var slugify = function(input) {
return input.toString().toLowerCase().trim()
.replace(/\s+/g, '-') // Replace spaces with -
.replace(/&/g, '-and-') // Replace & with 'and'
.replace(/[^\w\-]+/g, '') // Remove all non-word chars
.replace(/\-\-+/g, '-'); // Replace multiple - with single -
}
// Now get the hash and 'slugify' it
var hash = slugify(window.location.hash.split('#')[1]);
// Go to the new hash by setting it
window.location.hash = '#' + hash;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/35401679",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: delete more than 1 records using single prepared statement I am executing two prepared statement for deleting two records of different id. i want to delete both records in a single prepared statement execution
my code is like this
String sqlDelete,sqlSelect2;
sqlDelete = "delete from vul_detail where scanno=? and id=?";//
PreparedStatement ps2=conn.prepareStatement(sqlDelete);
// System.out.println("PS Created Successfully");
ps2.setString(1, "scan_2");
ps2.setInt(2, 2);
// ps2.setInt(3, 5);
ps2.executeUpdate();
System.out.println("first record deleted");
ps2.setString(1, "scan_2");
ps2.setInt(2, 5);
ps2.executeUpdate();
System.out.println("second record deleted");
sqlSelect2="select * from vul_detail;";
stmt=conn.createStatement();
System.out.println("select query created");
ResultSet rs2 = stmt.executeQuery(sqlSelect2);
I tried query as
sqlDelete = "delete from vul_detail where scanno=? and id=?,?";
PreparedStatement ps2=conn.prepareStatement(sqlDelete);
System.out.println("PS Created Successfully");
ps2.setString(1, "scan_2");
ps2.setInt(2, 2);
ps2.setInt(3, 5);
ps2.executeUpdate();
I am getting exception in this please help
A: The syntax for the "IN" condition is:
expression in (value1, value2, .... value_n);
In your example:
sqlDelete = "delete from vul_detail where scanno = ? and id in (?, ?)";
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/18998540",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: View with gradient is staying white after setting LayoutParams So I want a stylish gradient look for my app. Therefore I tried to also color the navigation bar with a gradient. I'm getting the height of the bar first and then change the layout params. The color is after resizing white. Has anyone of you an idea why it stays white?
Here you can see how it looks like now
Code
ImageView navBarBackground =
findViewById(R.id.navigationbar_background);
Resources resources = this.getResources();
int resourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android");
if (resourceId > 0) {
navBarBackground.setLayoutParams(new LinearLayout.LayoutParams(navBarBackground.getWidth(),
resources.getDimensionPixelSize(resourceId)));
navBarBackground.setImageResource(R.drawable.gradient_orange);
navBarBackground.setVisibility(View.VISIBLE);
}
I also tried to do it by changing the background. It didnt work out.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/linear_layout_sammlung"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".Activities.SammlungActivity">
<androidx.appcompat.widget.Toolbar
android:paddingTop="10dp"
android:layout_width="match_parent"
android:layout_height="60dp"
android:id="@+id/sammlung_toolbar"
android:background="@drawable/gradient_orange"
app:theme="@style/ToolbarTheme"/>
<GridView
android:id="@+id/grid_view_gegenstaende"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:columnWidth="90dp"
android:gravity="center"
android:horizontalSpacing="10dp"
android:numColumns="auto_fit"
android:stretchMode="columnWidth"
android:verticalSpacing="10dp"
android:visibility="gone" />
<de.lucadmin.sammelapp.dslv.DragSortListView
android:id="@+id/list_view_gegenstaende"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_weight="1"
android:divider="@null"
android:dividerHeight="0dp"
app:drag_start_mode="onLongPress"
android:visibility="visible">
</de.lucadmin.sammelapp.dslv.DragSortListView>
<LinearLayout
android:id="@+id/linear_layout_buttons"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0"
android:baselineAligned="false"
android:orientation="horizontal">
<TextView
android:id="@+id/gegenstand_button_hinzufuegen"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:drawableStart="@drawable/ic_add_box_black_24dp"
android:gravity="center"
android:text="Hinzufügen"
android:textSize="20sp" />
<TextView
android:id="@+id/gegenstand_button_einstellungen"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:drawableStart="@drawable/ic_art_track_black_24dp"
android:gravity="center"
android:text="Layout ändern"
android:textSize="20sp" />
</LinearLayout>
<ImageView
android:id="@+id/navigationbar_background"
android:layout_width="match_parent"
android:layout_height="20dp"
android:scaleType="centerCrop"
android:visibility="gone" />
</LinearLayout>
How it's supposed to look:
A: TL;DR you have to use MATCH_PARENT for the ImageView width:
navBarBackground.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
resources.getDimensionPixelSize(resourceId)));
By using navBarBackground.getWidth() you set the width of the ImageButton to zero, so all you see is the window background.
This happens because the ImageView is not yet completely laid out when you evaluate the width in onCreate(). (see also for example this blog post on The Life Cycle of a View in Android)
Useful tool for debugging layouts: Layout Inspector
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/59793221",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Rails and Capistrano missing gems I have a problem with missed gems when i tried to deploy rails app to vps. Can you help me?
capistrano.log
bundle check --path /home/root/apps/appname/shared/bundle
DEBUG [09094abf] [31mThe following gems are missing[0m
[31m * net-scp (1.2.1)[0m
[31m * sshkit (1.11.4)[0m
[31m * airbrussh (1.1.1)[0m
[31m * debug_inspector (0.0.2)[0m
[31m * binding_of_caller (0.7.2)[0m
[31m * byebug (9.0.6)[0m
[31m * capistrano-harrow (0.5.3)[0m
[31m * capistrano (3.6.1)[0m
[31m * capistrano-bundler (1.2.0)[0m
[31m * capistrano-rails (1.2.0)[0m
[31m * capistrano-rvm (0.1.2)[0m
[31m * capistrano3-puma (1.2.1)[0m
[31m * spring (2.0.0)[0m
[31m * web-console (2.3.0)[0m
[33mInstall missing gems with `bundle install`
A: You must use the capistrano/bundler gem to get the bundler tasks (like bundle install) in your deploy.
Basically, you must add the capistrano/bundler in your Gemfile and require it in your Capfile using the command below:
require 'capistrano/bundler'
Thereby the Capistrano will run the bundle install task during the deploy and this problem will be solved.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/40526599",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Python argparse get all parameters after specific flag as list I'm trying to make argparser like in gdb
program.py --valid-arg1 value1 --valid-arg2 value2 --args binary --bin-arg1 bin_arg1_value --bin-arg2 bin_arg2_value...
The problem is I need treat all arguments after --args just as values, and get them as a list inside my program. How can I do that?
Thanks
P.S. Use all unrecognized arguments it's bad solution because python and binary args may have same signature.
A: Have you tried using sys.argv instead of argparse? You can do something like that then:
import sys
dict = {}
tmp = []
key = ''
for arg in sys.argv:
if arg[0] == '-':
if tmp != []:
dict[key] = tmp
tmp = []
key = arg
if key == '--args':
dict[key] = sys.argv[sys.argv.find(key)+1:]
break
continue
tmp.append(arg)
This basically constructs an argument dictionary with flags as keys and list of arguments to flags as values. You might want to check what sys.argv is. If you invoke your python script with
python script.py -h yes -f yes no yes
sys.argv might be ['python', 'script.py', '-h', ...] but I am leaving that to you to find out. Then instead of for arg in sys.argv you want to do for arg in sys.argv[2:] or something you want.
So if we call
program.py --valid-arg1 value1 --valid-arg2 value2 --args binary --bin-arg1 bin_arg1_value --bin-arg2 bin_arg2_value
the dict will look like this:
dict = {
'--valid-arg1': ['value1'],
'--valid-arg2': ['value2'],
'args': ['binary', '--bin-arg1', 'bin_arg1_value', '--bin-arg2', 'bin_arg2_value']
}
Now if you want to use what is the value for --valid-arg1, you can do something like
try:
if dict['--valid-arg1'] == some_value1:
...
elif dict['--valid-arg1'] == some_value2:
...
except KeyError:
# no flag --valid-arg1
pass
With args you can do something like
try:
if something in dict['args']:
...
except KeyError:
# no additional args were given
pass
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/46073120",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: Routing mach with regex I have this in RouteConfig.cs:
routes.MapRoute(null,
"Login/{token}/{nameII}",
new { controller = "InicioPareja", action = "Login"
//, token = UrlParameter.Optional, nameII = UrlParameter.Optional
}
,new {token = @"/[0-9a-f]+/i{12}",nameII = @"^\w{1,20}$/" }
);
If I comment the constrain/regex (...token = @"/[0-9a-f ...) line, everything is OK.
It's match with the URL: .../Login/017E8BCADE06/Ana
Controller has the parameters: 017E8BCADE06 and Ana
But with the regex say: Not found. And commenting/uncommenting line: ...UrlParameter.Optional..., the same.
Obviously, even it doesn't executes the controller.
Even with the RouteDebugger doesn't match anything and it helps me nothing.
Any idea?
Thanks very much indeed.
A: Try this out:
routes.MapRoute(null,
"Login/{token}/{nameII}",
new { controller = "InicioPareja", action = "Login"
//, token = UrlParameter.Optional, nameII = UrlParameter.Optional
}
,new {token = @"[0-9a-f]{12}",nameII = @"^\w{1,20}$" }
);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/20785325",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to display multiple images from a site in recyclerview kotlin I want to display images like this :
This site has well over 200 apps and i am trying to show their apps in my recycler view. I don't want to save them one by one but i couldn't find any documentation on how to pull image data from URL in Kotlin.
data class PostModel(
val role : String = "listitem",
val clazz : String = "Zc7IjY"
)
I tried getting their id numbers but failed.
I want to access the url below inside my main url. But not just for one image, i want to access it for all of the images.
@font-face {
font-display: block;
font-family: 'Montserrat';
font-style: italic;
font-weight: 400;
src: local('Montserrat Italic'), local('Montserrat-Italic'),
url("//static.parastorage.com/tag-bundler/api/v1/fonts-cache/googlefont/woff2/s/montserrat/v14/JTUQjIg1_i6t8kCHKm459WxRzS7m0dR9pBOi.woff2") format('woff2');
unicode-range: U+0400-045F, U+0490-0491, U+04B0-04B1, U+2116;
}
A: The easiest way to do it is using a library like Picasso or Glide.
If you want to do it on your own you will have to decode the image yourself then transform it into a object that is accepted by an ImageView, you can refer to this other question https://stackoverflow.com/a/25463200/4632435
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75457490",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to create class instance and run it method in one string? Python How to create class instance and run it method in one string? Or not create any instance and call this method straight?
For example, i have class Car and method run_car(). How to call run_car() in one string?
car = Car()
car.run_car()
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/66931808",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Material images android Is there any generator of these images? I have seen a lot of images like that in android apps, so i think there must be a generator. I have searched for it, but found nothing. Maybe anyone know how to create such assets?
A: There is a tool called Material Design Background Generator that can do that for you. It's an online tool, check out this link: http://www.stringsistemas.com/materialgenerator.html
After a few random generations you can get some awesome patterns but you can't choose the palette colors unfortunately but it seems like the developer is open for suggestions.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/40615501",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to show value calculated from input form to the screen I'm new to react, and am trying to get a form to accept input from 2 lists, and output a calculated value to the screen. I used create-react-app to create the app and used the form sample from the react-bootstrap docs. I now can get the user's input, and getting the correct value in my console log. However, how do I output that randNum value to the screen?
import React, { useRef, useState } from 'react';
import { Form, Button, FormGroup, FormControl, ControlLabel } from "react-bootstrap";
import Fade from 'react-bootstrap/Fade'
import {CSSTransition} from 'react-transition-group'
import logo from './logo.svg';
import './App.css';
function App() {
const [diceType, setDiceType] = useState('');
const [diceNumber, setDiceNumber] = useState('');
const rollResult = () => {
const min = 1;
const max = parseInt(diceType, 10);
var randNum = 0;
for (let x = 0; x < parseInt(diceNumber, 10); x++){
randNum += min + (Math.round(Math.random() * (max - min)));
}
console.log(randNum);
};
const handleDiceTypeInput = e => {
setDiceType(e.target.value);
};
const handleDiceNumberInput = e => {
setDiceNumber(e.target.value);
};
const [open, setOpen] = useState(false);
return (
<div className="App">
<header className="App-header">
<Form>
<Form.Group controlId="diceType">
<Form.Label>Dice Type</Form.Label>
<Form.Control as="select" onChange={handleDiceTypeInput}>
<option value=""></option>
<option value="4">D4</option>
<option value="6">D6</option>
<option value="8">D8</option>
<option value="10">D10</option>
<option value="12">D12</option>
<option value="20">D20</option>
<option value="100">D100</option>
</Form.Control>
<Form.Text className="text-muted">
Number of sides on dice.
</Form.Text>
</Form.Group>
<Form.Group controlId="diceNumber" onChange={handleDiceNumberInput}>
<Form.Label>Dice Number</Form.Label>
<Form.Control as="select">
<option value=""></option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</Form.Control>
<Form.Text className="text-muted">
Number of dice to roll.
</Form.Text>
</Form.Group>
<Button onClick={rollResult} aria-controls="diceRoll" aria-expanded={open}>
Roll
</Button>
</Form>
<div id="diceRoll">
The result is:
</div>
</header>
</div>
);
}
export default App;
"dependencies": {
"bootstrap": "^4.4.1",
"react": "^16.12.0",
"react-bootstrap": "^1.0.0-beta.16",
"react-dom": "^16.12.0",
"react-scripts": "3.3.0",
"react-transition-group": "^4.3.0"
},
A: You can use useState for that as well.
Initialize randNum to '' and then, the place where you are console logging, set the value there. Inside the return function you can access the value by curly braces as {randNum}
Including only relevant part of your code:
function App() {
const [randNum, setRandNumber] = useState(''); // Initialization here
const rollResult = () => {
const min = 1;
const max = parseInt(diceType, 10);
var randNum = 0;
for (let x = 0; x < parseInt(diceNumber, 10); x++){
randNum += min + (Math.round(Math.random() * (max - min)));
}
setRandNumber(randNum) // Set Here
console.log(randNum);
};
return (
<div className="App">
<header className="App-header">
...
<div id="diceRoll">
The result is: {randNum} // Show Here
</div>
...
</header>
</div>
);
}
Hope it helps. Revert for any confusions.
A: Just add another useState variable and populate it within the button onClick handler:
const{ useRef, useState } = React;
function App() {
const [diceType, setDiceType] = useState('');
const [diceNumber, setDiceNumber] = useState('');
const [rollResult, setRollResult] = useState(0);
const handleDiceTypeInput = e => {
setDiceType(e.target.value);
};
const handleDiceNumberInput = e => {
setDiceNumber(e.target.value);
};
const handleButton = () => {
const min = 1;
const max = parseInt(diceType, 10);
var randNum = 0;
for (let x = 0; x < parseInt(diceNumber, 10); x++){
randNum += min + (Math.round(Math.random() * (max - min)));
}
console.log(randNum);
setRollResult(randNum);
}
return (
<div>
<select onChange={handleDiceTypeInput}>
<option value=""></option>
<option value="4">D4</option>
<option value="6">D6</option>
<option value="8">D8</option>
<option value="10">D10</option>
<option value="12">D12</option>
<option value="20">D20</option>
<option value="100">D100</option>
</select>
<select as="select" onChange={handleDiceNumberInput}>
<option value=""></option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
<button onClick={handleButton}>
Roll
</button>
<div id="diceRoll">
The result is: {rollResult}
</div>
</div>
);
}
const app = React.createElement(App);
ReactDOM.render(app, document.getElementById("app"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="app"></div>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/59397502",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: libGDX 1.4.1 can't slow down animations This is what I have:
...
private Array<Sprite> fireballFadeOutAnim;
private Array<Sprite> bucketFadeOutAnim;
private TextureAtlas fballAnimSheet;
private TextureAtlas bucketAnimSheet;
private Animation catch_animation;
private Animation visual_feedback;
private float elapsedTime = 0f;
...
@Override
public void create () {
...
fballAnimSheet = new TextureAtlas("animations/fireball_fadeout.txt");
bucketAnimSheet = new TextureAtlas("animations/bucket_fadeout.txt");
fireballFadeOutAnim = fballAnimSheet.createSprites("fireball_fadeout");
bucketFadeOutAnim = bucketAnimSheet.createSprites("bucket_fadeout");
catch_animation = new Animation(1/15f, fballAnimSheet.getRegions(), Animation.PlayMode.NORMAL);
visual_feedback = new Animation(1/15f, bucketAnimSheet.getRegions(), Animation.PlayMode.LOOP);
...
}
@Override
public void render () {
...
// Set the anim_elipsed_time
elapsedTime += Gdx.graphics.getDeltaTime();
...
// I try to draw them later on (under the render method) like this:
// Start and draw animation of fireball catch
batch.begin();
batch.draw(catch_animation.getKeyFrame(elapsedTime, true), fireBallRect.getX(), fireBallRect.getY());
batch.end();
}
I can see both animations happening extremely fast (they look like a white-flash), they do not loop even if the animation mode is set to "LOOP".
What am I doing wrong ? I can't seem to be able to slow them down or to have them LOOP. Thanks much.
Edited:
As requested, I upload all the code
public class MainActivity extends ApplicationAdapter {
public enum State {
PAUSE,
RUN,
RESUME,
STOPPED
}
public static State state = State.RUN;
private SpriteBatch batch;
private OrthographicCamera camera;
private Stage stage;
private Texture backgroundImage;
private Texture bucketImage;
private Texture fireballImage;
private Texture heart;
private TextureRegion criticalTexture;
private Sprite backgroundSprit;
private Sprite bucketSprite;
private Sprite fireballSprite;
private Sprite heartSprite;
private Rectangle bucketRect;
private Rectangle fireBallRect;
private Rectangle bucketSpriteRect;
private ShapeRenderer bucketRenderer;
private ShapeRenderer fireballRenderer;
private Button pauseButton;
private Array<Rectangle> fireballArray;
private Skin progressBarSkin;
private long lastFireballTime;
public static Sound bucket_tap;
public static Sound bucket_drag;
private Sound fireball_missed_sound;
private Sound catchFireball;
private Sound pauseBtnSound;
private Music bgMusic;
private float volume = 0.30f; // music and sfx volume control
public static int w;
public static int h;
private int barLength = 325;
private int numberOfFails = 10; // change numberOfFails to increase or decrese
// the total num. of missed fireballs the player
private int deductedBarSegment = barLength / numberOfFails;
private int numOfBallsLeft = numberOfFails; // use this var to check how many fballs left
private long fireballFrequency = 1000000000L; // change fireballFrequency to increase or decrease
// the number of fireballs on the screen
private int fireballSpeed = 400; // change the fireballSpeed to increase or decrease
// the speed at which the fireballs fall
private InputProcessor gameInputProcessor; // this sets the game input controller for the bucket
private InputMultiplexer multiplexer; // this sets the input processors from the game and UI
/************************************ Animation Properties ************************************/
private TextureAtlas fballAtlas;
private TextureAtlas bucketAtlas;
private Animation catch_animation;
private Animation visual_feedback;
private float elapsedTime = 0f;
private Actor feedbackPanel;
/**********************************************************************************************/
@Override
public void create () {
// Parse Test
//ParseObject testObject = new ParseObject("TestObject");
//testObject.put("foo", "bar");
//testObject.saveInBackground();
// Catch the dynamic size of the screen based on the device that's ran on
w = Gdx.graphics.getWidth();
h = Gdx.graphics.getHeight();
// Set up the camera
camera = new OrthographicCamera();
camera.setToOrtho(false, (float)w, (float)h);
// Instantiate the batch
batch = new SpriteBatch();
/***************************** These renders are for debugging only *****************************/
bucketRenderer = new ShapeRenderer();
fireballRenderer = new ShapeRenderer();
/**************************************************************************************************/
/******************************************** Stage and HUD ***************************************/
stage = new Stage();
pauseButton = new Button(new TextureRegionDrawable(
new TextureRegion(new Texture(Gdx.files.internal("images/pase_button_red.png")))),
new TextureRegionDrawable(new TextureRegion(new Texture(Gdx.files.internal("images/pase_button_white.png")))));
pauseButton.setX(flipCoordinates(w, 150));
pauseButton.setY(flipCoordinates(h, 170));
pauseButton.act(Gdx.graphics.getDeltaTime());
stage.addActor(pauseButton);
pauseButton.addListener(new ChangeListener() {
@Override
public void changed (ChangeEvent event, Actor actor) {
// Do something when the pauseButton is pressed
// Control multiple touches on the pauseButton
if(state == State.RUN) {
state = State.PAUSE;
pauseBtnSound.play();
// Set the pauseButton icon to the white version
//pauseButton.setColor(Color.WHITE);
}
else {
state = State.RUN;
pauseBtnSound.play();
}
}
});
// Add the critical_life indicator to the stage as an actor
criticalTexture = new TextureRegion(new Texture(Gdx.files.internal("images/critical_life.png")));
feedbackPanel = new Actor() {
public void draw(Batch batch, float alpha) {
batch.draw(criticalTexture, getX(), getY(), getOriginX(), getOriginY(), getWidth(), getHeight(),
getScaleX(), getScaleY(), getRotation());
}
};
feedbackPanel.setBounds(w / 2, h / 2,
criticalTexture.getRegionWidth(), criticalTexture.getRegionHeight());
// Set up an Action for the critical life actor
feedbackPanel.addAction(forever(sequence(scaleTo(2, 2, 0.5f), scaleTo(1, 1, 0.5f), delay(0.5f))));
feedbackPanel.act(Gdx.graphics.getDeltaTime());
stage.addActor(feedbackPanel);
/**************************************************************************************************/
/*********************************** Set up the Input Controllers *********************************/
// The multiplexer helps target several input processes (in this case, the stage and the
// InputProcessor.class)
multiplexer = new InputMultiplexer();
multiplexer.addProcessor(stage);
multiplexer.addProcessor(new GameInputProcessor());
// InputAdaptor
Gdx.input.setInputProcessor(multiplexer);
/**************************************************************************************************/
backgroundImage = new Texture("images/bg.jpg");
bucketImage = new Texture("images/bucket_small.png");
fireballImage = new Texture("images/fireball_small.png");
heart = new Texture("images/heart.png");
/*************************************** Animations Setup *****************************************/
fballAtlas = new TextureAtlas("animations/fireball_fadeout.txt");
bucketAtlas = new TextureAtlas("animations/bucket_fadeout.txt");
catch_animation = new Animation(0.50f, fballAtlas.getRegions());
visual_feedback = new Animation(0.15f, bucketAtlas.getRegions());
/**************************************************************************************************/
// Instantiate all sounds
bucket_tap = Gdx.audio.newSound(Gdx.files.internal("sounds/bucket_tap.ogg"));
bucket_drag = Gdx.audio.newSound(Gdx.files.internal("sounds/bucket_drag.ogg"));
fireball_missed_sound = Gdx.audio.newSound(Gdx.files.internal("sounds/fireball_missed.ogg"));
catchFireball = Gdx.audio.newSound(Gdx.files.internal("sounds/fastSteam.ogg"));
pauseBtnSound = Gdx.audio.newSound(Gdx.files.internal("sounds/pauseBtn_sound.ogg"));
bgMusic = Gdx.audio.newMusic(Gdx.files.internal("sounds/music_bg.mp3"));
bgMusic.setLooping(true);
bgMusic.play(); // <----------- turn bg music on/off
// Instantiate the progressBarSkin
progressBarSkin = new Skin();
progressBarSkin.add("progressBarBg", new Texture("images/progress-bar_bg.png"));
progressBarSkin.add("progressBar", new Texture("images/progress-bar_dynamic_red.png"));
// Create bg sprite
backgroundSprit = new Sprite(backgroundImage);
//backgroundSprit.setPosition((float)w / 2, (float)h / 2);
//backgroundSprit.setSize((float)w, (float)h);
// Bucket sprite
bucketSprite = new Sprite(bucketImage);
// Fireball sprite
fireballSprite = new Sprite(fireballImage);
// Heart sprite
heartSprite = new Sprite(heart);
// Set the bucketRect into the rect from the bucketSprite (THE GREEN ONE)
bucketSpriteRect = bucketSprite.getBoundingRectangle();
bucketSpriteRect.x = w / 2 - 100 / 2;
bucketSpriteRect.y = 20;
bucketSpriteRect.setSize(200, 200);
// Set the collision rectangle (THE RED ONE)
bucketRect = new Rectangle();
bucketRect.x = bucketSpriteRect.getX() + 70; // <---- adjust position left/right
bucketRect.y = bucketSpriteRect.getY() + 150; // <---- adjust position up/down
bucketRect.setSize(100, 10);
// Set a rectangle for each fireball sprite (THE WHITE ONE)
fireBallRect = new Rectangle();
fireBallRect.x = fireballSprite.getX();
fireBallRect.y = fireballSprite.getY();
fireBallRect.width = 55;
fireBallRect.height = 55;
fireballArray = new Array<Rectangle>();
}
@Override
public void render () {
// Devide the Render method into a few switch cases based on the game's state
switch (state) {
case RUN:
// Do all the batch drawing here
Gdx.gl.glClearColor(1, 1, 1, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
elipsedTime += Gdx.graphics.getDeltaTime();
batch.setProjectionMatrix(camera.combined);
batch.begin();
batch.draw(backgroundSprit, 0, 0, w, h);
batch.draw(bucketSprite, bucketSpriteRect.x, bucketSpriteRect.y,
bucketSprite.getWidth() - 160, bucketSprite.getHeight() - 140);
for(Rectangle fireball: fireballArray) {
batch.draw(fireballSprite, fireball.x, fireball.y,
fireballSprite.getWidth() - 20, fireballSprite.getHeight() - 20);
}
batch.draw(progressBarSkin.getSprite("progressBarBg"), 200, flipCoordinates(h, 170));
batch.draw(progressBarSkin.getSprite("progressBar"),
210, flipCoordinates(h, 162), barLength, 6); // <---- modify x, x, <x>, x to adjust the length of the life-bar
batch.draw(heartSprite, 95, flipCoordinates(h, 200), 90, 76);
stage.act(Gdx.graphics.getDeltaTime());
stage.draw();
batch.end();
/***************************************Debugging Rectangles************************************/
// Draw rects around sprites
// bucketRenderer.begin(ShapeRenderer.ShapeType.Line);
// bucketRenderer.setColor(Color.GREEN);
// bucketRenderer.rect(bucketSpriteRect.getX(), bucketSpriteRect.getY(),
// bucketSprite.getWidth() - 160, bucketSprite.getHeight() -140);
// bucketRenderer.end();
//
// bucketRenderer.begin(ShapeRenderer.ShapeType.Line);
// bucketRenderer.setColor(Color.RED);
// bucketRenderer.rect(bucketRect.getX(), bucketRect.getY(), 100, 10);
// //bucketRenderer.point(bucketRect.getX(), bucketRect.getY(), 0f);
// bucketRenderer.end();
//
// fireballRenderer.begin(ShapeRenderer.ShapeType.Line);
// fireballRenderer.setColor(Color.WHITE);
// fireballRenderer.rect(fireBallRect.x, fireBallRect.y,
// fireballSprite.getWidth() - 20, fireballSprite.getHeight() - 20);
// fireballRenderer.end();
// To avoid sprite flickering, surround batch.draw with a game state check
if (state != State.PAUSE) {
Iterator<Rectangle> iter = fireballArray.iterator();
while(iter.hasNext()) {
fireBallRect = iter.next();
fireBallRect.y -= fireballSpeed * Gdx.graphics.getDeltaTime();
// Remove the fireBallRect from the array as soon as it leaves the screen
if(fireBallRect.y + 106 < 0) {
iter.remove();
// The player missed the fireball, play a the fireball_missed_sound
fireball_missed_sound.play();
// Subtract a ball from the total number allowed to be missed
numOfBallsLeft --;
// Call life deduction
deductLifePoints();
// Check to see if this is the last fball left to fail
if (numOfBallsLeft == 1) {
}
// Check to see if life points are 0 or < 0
if (numOfBallsLeft <= 0) {
// Game over logic
barLength = 0;
// Set the game state to PAUSED
//state = State.PAUSE;
//bucketSprite.setColor(Color.RED);
batch.begin();
batch.draw(bucketSprite, bucketSpriteRect.x, bucketSpriteRect.y,
bucketSprite.getWidth() - 160, bucketSprite.getHeight() - 140);
batch.end();
}
}
// Collision detector
if(bucketRect.overlaps(fireBallRect)) {
catchFireball.play(volume);
// Start and draw animagion of fireball catch
batch.begin();
batch.draw(catch_animation.getKeyFrame(elapsedTime, true), fireBallRect.getX(), fireBallRect.getY());
batch.end();
// Remove the fireball that collides with the bucket
iter.remove();
}
}
}
// Touch input controller
if(Gdx.input.isTouched()) {
Vector3 touchPos = new Vector3();
touchPos.set(Gdx.input.getX(), Gdx.input.getY(), 0);
camera.unproject(touchPos);
if(touchPos.y <= 250) {
bucketSpriteRect.setX(touchPos.x - 115);
bucketRect.setX(touchPos.x - 50); // <---- adjust position left/right on touch
}
}
if(TimeUtils.nanoTime() - lastFireballTime > fireballFrequency) {
fireBallRect = new Rectangle();
fireBallRect.x = MathUtils.random(50, w - 270);
fireBallRect.y = h;
fireBallRect.width = 75;
fireBallRect.height = 75;
fireballArray.add(fireBallRect);
lastFireballTime = TimeUtils.nanoTime();
}
/**************************************************************************************************/
break;
case PAUSE:
// Pause the game here
/******************************** Redraw the sprites to avoid flickering **************************/
batch.begin();
batch.draw(backgroundSprit, 0, 0, w, h);
batch.draw(bucketSprite, bucketSpriteRect.x, bucketSpriteRect.y,
bucketSprite.getWidth() - 160, bucketSprite.getHeight() - 140);
for(Rectangle fireball: fireballArray) {
batch.draw(fireballSprite, fireball.x, fireball.y,
fireballSprite.getWidth() - 20, fireballSprite.getHeight() - 20);
}
batch.draw(progressBarSkin.getSprite("progressBarBg"), 200, flipCoordinates(h, 170));
batch.draw(progressBarSkin.getSprite("progressBar"),
210, flipCoordinates(h, 162), barLength, 6); // <---- modify x, x, <x>, x to adjust the length of the life-bar
batch.draw(heartSprite, 95, flipCoordinates(h, 200), 90, 76);
//pauseButton.draw(batch, 1);
stage.act(Gdx.graphics.getDeltaTime());
stage.draw();
batch.end();
/**************************************************************************************************/
break;
case RESUME:
break;
default:
break;
}
}
/************************************* Implement Dispose **************************************/
@Override
public void dispose() {
batch.dispose();
bucketRenderer.dispose();
fireballRenderer.dispose();
backgroundImage.dispose();
bucketImage.dispose();
fireballImage.dispose();
bucket_tap.dispose();
bucket_drag.dispose();
catchFireball.dispose();
bgMusic.dispose();
fireball_missed_sound.dispose();
progressBarSkin.dispose();
fballAtlas.dispose();
stage.dispose();
}
/************************************* Flip Coordinates Method ********************************/
public static float flipCoordinates(float height, float xORy) {
float newPosition = height - xORy;
return newPosition;
}
/************************************** Deduces Life Points ***********************************/
private void deductLifePoints() {
barLength -= deductedBarSegment;
}
/************************************** Set the Game's state **********************************/
public void setGameState(State s) {
this.state = s;
}
/******************************** Android's Lyfe-Cycle Overrides ******************************/
@Override
public void pause() {
super.pause();
this.state = State.PAUSE;
}
@Override
public void resume() {
super.resume();
this.state = State.PAUSE;
}
}
A: The first parameter of the Animation constructor is the frameDuration in seconds. You are passing it 1/15f, which is really fast. Try something greater, like 0.15f.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/26874690",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Countdown timer to specific date I'm trying to make a countdown timer that displays total number of days, hours, minutes and seconds remaining to specific date.
That's what I've up to now created.
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
SetContentView (Resource.Layout.Main);
txtDays = FindViewById<TextView> (Resource.Id.txtDays);
txtHours = FindViewById<TextView> (Resource.Id.txtHours);
txtMins = FindViewById<TextView> (Resource.Id.txtMins);
txtSec = FindViewById<TextView> (Resource.Id.txtSec);
DateTime enteredDate = new DateTime(2013, 7, 25, 12 ,30 ,00);
DateTime todaysDateTime = DateTime.Now;
DateTime formattedDate = todaysDateTime.AddHours (2);
TimeSpan span = enteredDate.Subtract(formattedDate);
double totalDays = span.TotalDays;
double totalHours = span.TotalHours;
double totalMins = span.TotalMinutes;
double totalSec = span.TotalSeconds;
new Thread(new ThreadStart(() =>
{
RunOnUiThread(() =>
{
Console.WriteLine ("Days: " + String.Format("{0:0}", Math.Truncate(totalDays)));
Console.WriteLine ("Hours: " + String.Format("{0:0}", Math.Truncate(totalHours)));
Console.WriteLine ("Minutes: " + String.Format("{0:0}", Math.Truncate(totalMins)));
Console.WriteLine ("Seconds: " + String.Format("{0:0}", Math.Truncate(totalSec)));
txtDays.Text = String.Format ("{0:0}", Math.Truncate (totalDays));
txtHours.Text = String.Format ("{0:0}", Math.Truncate (totalHours));
txtMins.Text = String.Format ("{0:0}", Math.Truncate (totalMins));
txtSec.Text = String.Format ("{0:0}", Math.Truncate (totalSec));
});
})).Start();
}
How to update TextViews every second automatically with Android C#?
EDIT 2:
I have used Timer, it's counting with Console.WriteLine, but the TextViews displays nothing and they don't updating... Somebody an idea how to update TextViews every second?
timer = 0;
new Thread(new ThreadStart(() =>
{
Thread.Sleep (1000);
RunOnUiThread(() =>
{
tmr.Elapsed += new System.Timers.ElapsedEventHandler(tmr_Elapsed);
tmr.Start();
while (timer < totalSec) ;
tmr.Stop();
});
})).Start();
void tmr_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
txtDays = FindViewById<TextView> (Resource.Id.txtDays);
txtHours = FindViewById<TextView> (Resource.Id.txtHours);
txtMins = FindViewById<TextView> (Resource.Id.txtMins);
txtSec = FindViewById<TextView> (Resource.Id.txtSec);
DateTime enteredDate = new DateTime(2013, 7, 25, 12 ,30 ,00);
DateTime todaysDateTime = DateTime.Now;
DateTime formattedDate = todaysDateTime.AddHours (2);
TimeSpan span = enteredDate.Subtract(formattedDate);
totalDays = span.TotalDays;
totalHours = span.TotalHours;
totalMins = span.TotalMinutes;
totalSec = span.TotalSeconds;
Console.WriteLine ("Days: " + String.Format("{0:0}", Math.Truncate(totalDays)));
Console.WriteLine ("Hours: " + String.Format("{0:0}", Math.Truncate(totalHours)));
Console.WriteLine ("Minutes: " + String.Format("{0:0}", Math.Truncate(totalMins)));
Console.WriteLine ("Seconds: " + String.Format("{0:0}", Math.Truncate(totalSec)));
txtDays.Text = String.Format ("{0:0}", Math.Truncate (totalDays));
txtHours.Text = String.Format ("{0:0}", Math.Truncate (totalHours));
txtMins.Text = String.Format ("{0:0}", Math.Truncate (totalMins));
txtSec.Text = String.Format ("{0:0}", Math.Truncate (totalSec));
}
A: In C# use Timer class and set that to 1 second.
A: Problem solved just added RunOnUiThread within tmr_Elapsed
void tmr_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
RunOnUiThread(() =>
{
txtDays = FindViewById<TextView> (Resource.Id.txtDays);
txtHours = FindViewById<TextView> (Resource.Id.txtHours);
txtMins = FindViewById<TextView> (Resource.Id.txtMins);
txtSec = FindViewById<TextView> (Resource.Id.txtSec);
DateTime enteredDate = new DateTime(2013, 7, 25, 12 ,30 ,00);
DateTime todaysDateTime = DateTime.Now;
DateTime formattedDate = todaysDateTime.AddHours (2);
TimeSpan span = enteredDate.Subtract(formattedDate);
totalDays = span.TotalDays;
totalHours = span.TotalHours;
totalMins = span.TotalMinutes;
totalSec = span.TotalSeconds;
Console.WriteLine ("Days: " + String.Format("{0:0}", Math.Truncate(totalDays)));
Console.WriteLine ("Hours: " + String.Format("{0:0}", Math.Truncate(totalHours)));
Console.WriteLine ("Minutes: " + String.Format("{0:0}", Math.Truncate(totalMins)));
Console.WriteLine ("Seconds: " + String.Format("{0:0}", Math.Truncate(totalSec)));
txtHours.Text = String.Format ("{0:0}", Math.Truncate (totalHours));
txtHours.Text = String.Format ("{0:0}", Math.Truncate (totalHours));
txtMins.Text = String.Format ("{0:0}", Math.Truncate (totalMins));
txtSec.Text = String.Format ("{0:0}", Math.Truncate (totalSec));
});
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/17185298",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Python: how do I create a list of combinations from a series of ranges of numbers For a list of numerical values of n length, e. g. [1, 3, 1, 2, ...], I would like to create a list of the lists of all possible combinations of values from range[x+1] where x is a value from the list. The output might look something like this:
for list[1, 3, 2] return all possible lists of range[x+1] values:
# the sequence of the list is unimportant
[
[0,0,0],[1,0,0],[0,1,0],[0,2,0],[0,3,0],[0,0,1],[0,0,2],[1,1,0],
[1,2,0],[1,3,0],[1,0,1],[1,0,2],[0,1,1],[0,2,1],[0,3,1],[0,1,2],
[0,2,2],[0,3,2],[1,1,1],[1,2,1],[1,3,1],[1,1,2],[1,2,2],[1,3,2]
]
So in this example I am looking for all variations of [e1, e2, e3] from e1 in [0,1], e2 in [0,1,2,3] and e3 in [0,1,2]
A: Python's itertools module has a tool that does what you need:
import itertools
p = itertools.permutations([0, 1, 2, 3])
p_as_list = list(p)
Edit: As your needs are fairly specific you could benefit from having your own function that does something alike this one: (note I haven't got the implementation down just yet, maybe someone might refine this):
def magic_permutations (*args):
lists = []
larg = len(args)
for i in range(larg):
lists.append([])
i = 0
for nums in args:
for num in nums:
if i >= larg:
i = 0
lists[i].append(num)
i += 1
return lists
Edit: I misunderstood your question the first time, so I'll apologize for that. I'll however leave this be.
A: Use itertools.product with a dynamically-specified list of iterators:
vals = [1,3,2]
for item in itertools.product(*[range(x+1) for x in vals]):
print item
Output:
(0, 0, 0)
(0, 0, 1)
(0, 0, 2)
(0, 1, 0)
(0, 1, 1)
(0, 1, 2)
(0, 2, 0)
(0, 2, 1)
(0, 2, 2)
(0, 3, 0)
(0, 3, 1)
(0, 3, 2)
(1, 0, 0)
(1, 0, 1)
(1, 0, 2)
(1, 1, 0)
(1, 1, 1)
(1, 1, 2)
(1, 2, 0)
(1, 2, 1)
(1, 2, 2)
(1, 3, 0)
(1, 3, 1)
(1, 3, 2)
A: To obtain the exact sequence shown in the question (albeit in a different order, but that's not a problem) use this function:
import itertools as it
def combs(lst):
return [list(e) for e in it.product(*(range(x+1) for x in lst))]
The result is as expected:
combs([1, 3, 2])
=> [[0, 0, 0], [0, 0, 1], [0, 0, 2], [0, 1, 0], [0, 1, 1], [0, 1, 2],
[0, 2, 0], [0, 2, 1], [0, 2, 2], [0, 3, 0], [0, 3, 1], [0, 3, 2],
[1, 0, 0], [1, 0, 1], [1, 0, 2], [1, 1, 0], [1, 1, 1], [1, 1, 2],
[1, 2, 0], [1, 2, 1], [1, 2, 2], [1, 3, 0], [1, 3, 1], [1, 3, 2]]
A: for ii in itertools.product(range(2),range(4),range(3):
print ii
(0, 0, 0)
(0, 0, 1)
(0, 0, 2)
(0, 1, 0)
(0, 1, 1)
(0, 1, 2)
(0, 2, 0)
(0, 2, 1)
(0, 2, 2)
(0, 3, 0)
(0, 3, 1)
(0, 3, 2)
(1, 0, 0)
(1, 0, 1)
(1, 0, 2)
(1, 1, 0)
(1, 1, 1)
(1, 1, 2)
(1, 2, 0)
(1, 2, 1)
(1, 2, 2)
(1, 3, 0)
(1, 3, 1)
(1, 3, 2)
A: It's not in the same order, but I think this is what you wanted:
def xrangeCombinations(input):
if len(input) > 1:
for i in xrange(input[-1] + 1):
for j in xrangeCombinations(input[:-1]):
yield j + [i]
else:
for i in xrange(input[-1] + 1):
yield [i]
for i in xrangeCombinations([1, 3, 2]):
print i
Produces the output:
[0, 0, 0]
[1, 0, 0]
[0, 1, 0]
[1, 1, 0]
[0, 2, 0]
[1, 2, 0]
[0, 3, 0]
[1, 3, 0]
[0, 0, 1]
[1, 0, 1]
[0, 1, 1]
[1, 1, 1]
[0, 2, 1]
[1, 2, 1]
[0, 3, 1]
[1, 3, 1]
[0, 0, 2]
[1, 0, 2]
[0, 1, 2]
[1, 1, 2]
[0, 2, 2]
[1, 2, 2]
[0, 3, 2]
[1, 3, 2]
This solution might be slower than alternatives so if speed is an issue you should probably improve it.
A: Using numpy if you don't mind getting tuples in the end:
>>> import numpy as np
>>> e1=np.array([0,1])
>>> e2=np.array([0,1,2])
>>> e3=np.array([0,1,2,3])
>>> g=np.meshgrid(e1,e2,e3) #you need numpy ver>1.7.0, change the order of final result by changing the order of e1, e2, e3
>>> zip(*[item.flatten() for item in g])
[(0, 0, 0), (0, 0, 1), (0, 0, 2), (0, 0, 3), (1, 0, 0), (1, 0, 1), (1, 0, 2), (1, 0, 3), (0, 1, 0), (0, 1, 1), (0, 1, 2), (0, 1, 3), (1, 1, 0), (1, 1, 1), (1, 1, 2), (1, 1, 3), (0, 2, 0), (0, 2, 1), (0, 2, 2), (0, 2, 3), (1, 2, 0), (1, 2, 1), (1, 2, 2), (1, 2, 3)]
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/18423100",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Ways to dynamically render a real world 3d environment in Unity3D Using Unity3D and C# I am attempting to display a 3d version of a real world location. Inside my Unity3D app, the user will specify the GPS coordinates of a location, then my app will have to generate a 3d plane(anything doesn't have to be a plane) of that location. The plane will show a 500 metre by 500 metre 3d snapshot of that location.
How would you suggest I achieve this in Unity3D? What methodology would you use to achieve this?
NOTE: I understand that this is a very difficult endevour(to render real world locations dynamically in Unity3d) so I expect to perform many actions to achieve this. I just don't know of all the technologies out there and which would be best for my needs
For example:
Suggested methodology 1:
*
*Prompt user to specify GPS coords
*Use Google earth API and HTTP to programmatically obtain a .khm file
describing that location(Not sure if
google earth provides that capability
*
*does it?)
*Unzip the .khm so I have the .dae file
*Convert that file to a .3ds file using ??? third party converter(is
there a converter that exists?)
*Import .3ds into Unity3D at runtime as a plane(is this possible)?
Suggested methodology 2:
*
*Prompt user to specify GPS coords
*Use Google earth API and HTTP to programmatically obtain a .khm file
describing that location(Not sure if
google earth provides that capability
*
*does it?)
*Unzip the .khm so I have the .dae file
*Parse .dae file using my own C# parser I will write(do you think its
possible to write a .dae parser that
can parse the .dae into an array of
Vector3 that describe the height map
of that location?)
*Dynamically create a plane in Unity3D and populate it with my
array/list of Vector3 points(is it
possible to create a plane this way?)
Maybe I am meant to create a mesh
instead of a plane?
Can you think of any other ways I could render a real world 3d environment in Unity3D?
A: No service available has a detailed 3d map of an area given gps coordinates. Google has a super simple height map that they draw and then map their aerial pictures onto, but even if you could get programmatic access to that it would look terrible if you were at street level. If you're okay with a horrid level of detail (like you're going to be viewing this from high up or something) maybe it would be feasible, but not as any kind of first person street level experience.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/11094203",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Fill Datagridview in each new identical TabPages I have TabControl with 1 TabPages and contains DataGridView.
I create TabPages2 from TabPages1 with code :
Dim Frm As New TabFormPage
Dim MoreTabs As TabPage = Frm.TabPage1
Dim i As Integer
For i = 1 To TabControl1.TabPages.Count
MoreTabs.Text = "TabPage" & i + 1
Next i
TabControl1.Controls.Add(MoreTabs)
Frm.Dispose()
TabPages2 Controls identical to TabPages1
If I fill DataGridView with BackgroundWorker in TabPages1 , it was working . But if I fill DataGridView in every New TabPages ( eg TabPages2 ) from different sources , it was not working (DataGridView in TabPages2/each New TabPages is empty/nothing) . It always fills Tabpages1 DataGridView
How to fill every DataGridView in every New TabPages with identical controls ?
Here's my code to fill DataGridview :
Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
MyConnection = New System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + FPathTab + ";Extended Properties=Excel 12.0;")
MyCommand = New System.Data.OleDb.OleDbDataAdapter("select * from [" & CSheetTab1 & "]'", MyConnection)
DtSet = New System.Data.DataSet
DtSet.Clear()
MyCommand.Fill(DtSet)
End Sub
Private Sub BackgroundWorker1_RunWorkerCompleted(sender As Object, e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
DataGridView1.DataSource = DtSet.Tables(0)
dv = DtSet.Tables(0).DefaultView
MaxRecords = DtSet.Tables(0).Rows.Count
MyConnection.Close()
DataGridView1.Columns("F20").Visible = False
DataGridView1.Columns("F21").Visible = False
DataGridView1.Columns("F22").Visible = False
End Sub
Thanks for your help
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/30152597",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: has anyone figured out a way to use the back-facing camera on android in any browser with getusermedia? I can’t seem to find the settings anywhere. I also tried searching the phone to set front-facing as default but had no luck. I’m using an xiaomi 1s if that helps.sorry ,my english is poor
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/16860701",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Subdomain overwiting CodeIgniter session I have 2 CodeIgniter installations, 1 on mydomain.com another on sub.mydomain.com.
I am trying to get sub.mydomain.com to be able to access the CI session created by mydomain.com. I have edited the cookie section of both config files to:
$config['cookie_prefix'] = "";
$config['cookie_domain'] = ".mydomain.com";
$config['cookie_path'] = "/";
$config['cookie_secure'] = FALSE;
Now if I go to mydomain.com setting the session and then go to sub.mydomain.com it seems to overwrite the session with a new one rather than being able to read from the existing session.
Am I missing something here?
A: This was driving me crazy for hours but the solution (as usual) was simple. I had forgotten to make sure
$config[‘encryption_key’]
was the same for both applications!
Working great now
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/9881092",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Guidance with a translation in Linq to Xml Can someone help with an explanation of what does this mean:
... .Select(Func<XElement, XElement>selector)
Please an example of what should go in as parameter will be appreciated.
Also found it a little bit difficult naming this question. Suggestion will also be appreciated.
A: It's a function taking XElement as argument and returning an XElement, so for instance:
public XElement someFunction(XElement argument)
{
XElement someNewElement = new XElement();
... // do something with someNewElement, taking into account argument
return someNewElement;
}
Func<XElement, XElement> variableForFunction = someFunction;
.... .Select(variableForFunction);
I'm not interely sure if you have to assign it to a variable first, you could probably just do this:
... .Select(variableForFunction);
give it a try (and let me know if it works :) )
oh and for more information, here's the msdn article, it also explains how to use delegates:
Func<XElement, XElement> variableForFunction = delegate(XElement argument)
{
....//create a new XElement
return newXElement;
}
and how to use lambdas, for instance:
Func<XElement, XElement> variableForFunction = s => {
....;//create an XElement to return
return newXElement;
}
or, in this instance, use the lambda directly:
.... .Select( s => {
....;//create an XElement to return
return newXElement;
})
edited it following Pavel's comment
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/1827892",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: If the address of a function can not be resolved during deduction, is it SFINAE or a compiler error? In C++0x SFINAE rules have been simplified such that any invalid expression or type that occurs in the "immediate context" of deduction does not result in a compiler error but rather in deduction failure (SFINAE).
My question is this:
If I take the address of an overloaded function and it can not be resolved, is that failure in the immediate-context of deduction?
(i.e is it a hard error or SFINAE if it can not be resolved)?
Here is some sample code:
struct X
{
// template<class T> T* foo(T,T); // lets not over-complicate things for now
void foo(char);
void foo(int);
};
template<class U> struct S
{
template<int> struct size_map
{ typedef int type; };
// here is where we take the address of a possibly overloaded function
template<class T> void f(T,
typename size_map<sizeof(&U::foo)>::type* = 0);
void f(...);
};
int main()
{
S<X> s;
// should this cause a compiler error because 'auto T = &X::foo' is invalid?
s.f(3);
}
Gcc 4.5 states that this is a compiler error, and clang spits out an assertion violation.
Here are some more related questions of interest:
Does the FCD-C++0x clearly specify what should happen here?
Are the compilers wrong in rejecting this code?
Does the "immediate-context" of deduction need to be defined a little better?
Thanks!
A: template<class T> void f(T,
typename size_map<sizeof(&U::foo)>::type* = 0);
This doesn't work, because U does not participate in deduction. While U is a dependent type, during deduction for f it's treated like a fixed type spelled with a nondependent name. You need to add it to the parameter list of f
/* fortunately, default arguments are allowed for
* function templates by C++0x */
template<class T, class U1 = U> void f(T,
typename size_map<sizeof(&U1::foo)>::type* = 0);
So in your case because U::foo does not depend on parameters of f itself, you receive an error while implicitly instantiating S<X> (try to comment out the call, and it should still fail). The FCD says at 14.7.1/1
The implicit instantiation of a class template specialization causes the implicit instantiation of the declarations, but not of the definitions or default arguments, of the class member functions, member classes, static data members and member templates;
That is, if you implicitly instantiate S<X> the following function template declaration will be instantiated
template<class T> void S<X>::f(T,
typename size_map<sizeof(&X::foo)>::type* = 0);
Analysis on that template declaration will then find that it can't resolve the reference to X::foo and error out. If you add U1, the template declaration will not yet try to resolve the reference to U1::foo (since U1 is a parameter of f), and will thus remain valid and SFINAE when f is tried to be called.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/2892087",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "24"
}
|
Q: C# Progress Bar is not showing progress I have a progress bar on my program and I am trying to add value to it after each "DataTable" has been processed, however it only updates after everything is done.
here is the code:
int c = 0;
OdbcConnection cn = openOdbcDB();
foreach(DataSet ds in allDataSets)
{
foreach(DataTable dt in ds.Tables)
{
foreach (DataRow dr in dt.Rows)
{
insertIntoDatabaseCurrentRecord(dr);
}
}
pbMain.Value = pbMain.Value + (33 / totalFiles);
c++;
}
cn.Close();
cn.Dispose();
Is there a way to force the bar to show progress after each table is finished like it is finished? At the moment, I only see the progress once loops finish, I see the line go from empty to full. There are about 18000 records per DataTable, so I should be able to see it because it takes about a minute for it to process all the records.
A: Assuming all this is happening in the UI thread, then it's not going to update because you are keeping the thread busy with processing your loop. You need to spawn off a background thread to do the processing so that it doesn't hang your UI thread. Then you will need to have the part where you actually set the progress bar pushed back to your UI thread using Contol.Invoke.
See here: http://msdn.microsoft.com/en-us/library/zyzhdc6b.aspx for both an example of threading (although there are many ways you can do this) and Control.Invoke.
A: Use BackgroundWorker:
BackgroundWorker _worker;
// executes on another thread
void worker_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = (BackgroundWorker)sender;
int c = 0;
OdbcConnection cn = openOdbcDB();
foreach (DataSet ds in allDataSets)
{
foreach (DataTable dt in ds.Tables)
{
foreach (DataRow dr in dt.Rows)
{
insertIntoDatabaseCurrentRecord(dr);
}
}
// do not update UI elements here, but in ProgressChanged event
//pbMain.Value = pbMain.Value + (33 / totalFiles);
c++;
worker.ReportProgress(c); // call ProgressChanged event of the worker and pass a value you can calculate the percentage from (I choose c, since it is the only calculated value here)
}
cn.Close();
cn.Dispose();
}
// gets called on your main thread
void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
// update the progressbar here.
// e.ProgressPercentage holds the value passed in DoWork.
}
A: Since your loops are blocking the active thread, you will have to use another Thread (clean way) or simply use Application.DoEvents() on WinForms:
int c = 0;
OdbcConnection cn = openOdbcDB();
foreach(DataSet ds in allDataSets)
{
foreach(DataTable dt in ds.Tables)
{
foreach (DataRow dr in dt.Rows)
{
insertIntoDatabaseCurrentRecord(dr);
Application.DoEvents(); //Quick and dirty
}
}
pbMain.Value = pbMain.Value + (33 / totalFiles);
c++;
}
cn.Close();
cn.Dispose();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/18210162",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Snap to Ticks and move Ticks position in Custom Range slider I am very new to this and i am trying to figure out how to solve my issue.
I am trying to design an Range slider for controling the speed of an machine application.
I have been searching here for many hours now but i can not find the right result for my issue.
The code i am adding here is something i have found other pages so it might not be best solution.
I would like to do 3 different things with it to start with.
*
*First issue is that i would like the handle to snap to the ticks i have made, is it possible to do that with code so if i change my Ticks the handle will stil snap to the new ticks?
*Is it possible to have more ticks between 0 and 10% so i have like 2% steps there up to 10% and when the handle is there it will then snap to the 2% steps and when its above 10% it will snap to the other 10% step interval.
*Is it possible to move the Ticks inside the slider instead and have the labels in the middle?
I would like to have the ticks both in the bottom and in the top and then the labels in the middle. I have attached a picture of what i am aiming for.
Many thanks
Range slider idea!
Link to my Code
https://www.w3schools.com/code/tryit.asp?filename=GT1V8EFG2RUA
A:
function toggleStep(element) {
if (element.value >= 10) { element.step = 10; }
else { element.step = 2; }
}
/**
* Sniffs for Older Edge or IE,
* more info here:
* https://stackoverflow.com/q/31721250/3528132
*/
function isOlderEdgeOrIE() {
return (
window.navigator.userAgent.indexOf("MSIE ") > -1 ||
!!navigator.userAgent.match(/Trident.*rv\:11\./) ||
window.navigator.userAgent.indexOf("Edge") > -1
);
}
function valueTotalRatio(value, min, max) {
return ((value - min) / (max - min)).toFixed(2);
}
function getLinearGradientCSS(ratio, leftColor, rightColor) {
return [
'-webkit-gradient(',
'linear, ',
'left top, ',
'right top, ',
'color-stop(' + ratio + ', ' + leftColor + '), ',
'color-stop(' + ratio + ', ' + rightColor + ')',
')'
].join('');
}
function updateRangeEl(rangeEl) {
var ratio = valueTotalRatio(rangeEl.value, rangeEl.min, rangeEl.max);
rangeEl.style.backgroundImage = getLinearGradientCSS(ratio, '#00FF00', '#c5c5c5');
}
function initRangeEl() {
var rangeEl = document.querySelector('input[type=range]');
var textEl = document.querySelector('input[type=text]');
/**
* IE/Older Edge FIX
* On IE/Older Edge the height of the <input type="range" />
* is the whole element as oposed to Chrome/Moz
* where the height is applied to the track.
*
*/
if (isOlderEdgeOrIE()) {
rangeEl.style.height = "20px";
// IE 11/10 fires change instead of input
// https://stackoverflow.com/a/50887531/3528132
rangeEl.addEventListener("change", function(e) {
textEl.value = e.target.value;
});
rangeEl.addEventListener("input", function(e) {
textEl.value = e.target.value;
});
} else {
updateRangeEl(rangeEl);
rangeEl.addEventListener("input", function(e) {
updateRangeEl(e.target);
textEl.value = e.target.value;
});
}
}
initRangeEl();
.slidecontainer {
width: 500px;
margin-left:15px;
}
input[type="range"] {
-webkit-appearance: none;
-moz-appearance: none;
width:100%;
height: 50px;
padding: 0;
border: solid 2px #000000;
border-radius: 8px;
outline: none;
cursor: pointer;
}
datalist {
display: flex;
margin-left: 2px;
margin-top: -50px;
}
datalist option {
flex-basis: 10%;
border-left: 1px solid #000;
}
datalist option:nth-child(-n+5) {
flex-basis: 2%;
}
datalist option:last-child {
display: none;
}
/*Chrome thumb*/
input[type="range"]::-webkit-slider-thumb {
-webkit-appearance: none;
-moz-appearance: none;
-webkit-border-radius: 5px;
/*16x16px adjusted to be same as 14x14px on moz*/
height: 45px;
width: 45px;
border-radius: 5px;
background: #e7e7e7;
border: 2px solid #000000;
opacity: 0.4;
cursor: pointer;
border-radius: 8px;
}
/*Mozilla thumb*/
input[type="range"]::-moz-range-thumb {
-webkit-appearance: none;
-moz-appearance: none;
-moz-border-radius: 5px;
height: 14px;
width: 14px;
border-radius: 5px;
background: #e7e7e7;
border: 1px solid #c5c5c5;
}
/*IE & Edge input*/
input[type=range]::-ms-track {
width: 300px;
height: 6px;
/*remove bg colour from the track, we'll use ms-fill-lower and ms-fill-upper instead */
background: transparent;
/*leave room for the larger thumb to overflow with a transparent border */
border-color: transparent;
border-width: 2px 0;
/*remove default tick marks*/
color: transparent;
margin-left:15px;
}
/*IE & Edge thumb*/
input[type=range]::-ms-thumb {
height: 14px;
width: 14px;
border-radius: 5px;
background: #e7e7e7;
border: 1px solid #c5c5c5;
}
/*IE & Edge left side*/
input[type=range]::-ms-fill-lower {
background: #000000;
border-radius: 2px;
margin-left:15px;
}
/*IE & Edge right side*/
input[type=range]::-ms-fill-upper {
background: #000000;
border-radius: 2px;
}
/*IE disable tooltip*/
input[type=range]::-ms-tooltip {
display: none;
}
input[type="text"] {
border: none;
}
.sliderticks {
display: flex;
justify-content: space-between;
padding: 0 50px;
}
.sliderticks p {
position: relative;
display: flex;
justify-content: center;
text-align: center;
width: 1px;
background: #D3D3D3;
height: 10px;
line-height: 40px;
margin: 0 0 20px 0;
}
<h1>Custom Range Slider</h1>
<p>Drag the slider to display the current value.</p>
<div class="slidecontainer">
<input type="range" value="10" min="0" max="100" oninput="toggleStep(this)" list="sliderticks" />
<div class="datalist">
<datalist id="sliderticks">
<option>0</option>
<option>2</option>
<option>4</option>
<option>6</option>
<option>8</option>
<option>10</option>
<option>20</option>
<option>30</option>
<option>40</option>
<option>50</option>
<option>60</option>
<option>70</option>
<option>80</option>
<option>90</option>
<option>100</option>
</datalist>
</div>
</div>
A: Hope the code below solves your needs:
document.querySelectorAll('.range input[type="range"]').forEach((range) => {
range.tickmarks = [...range.list.options].map((el) => parseFloat(el.value));
range.list.insertAdjacentHTML('afterend', `<div class="range-value"></div>`);
range.max = parseFloat(range.tickmarks[range.tickmarks.length - 1]);
let q = (range.clientWidth - 40) / range.max;
range.addEventListener('input', function(ev) {
if (this.hasAttribute('ticks-only')) {
this.value = range.tickmarks.map((x) => x).sort((x, y) => Math.abs(x - this.value) - Math.abs(y - this.value))[0];
}
this.parentElement.style.backgroundSize = `${(this.value * range.clientWidth) / range.max}px 100%, 100% 100%`;
this.list.nextElementSibling.textContent = this.value;
this.list.nextElementSibling.style.left = `${20 + this.value * q}px`;
});
range.tickmarks.forEach((el, i) => {
range.list.options[i].label = el % 10 ? ' ' : el;
range.list.options[i].style.left = 20 + el * q + 'px';
});
range.dispatchEvent(new Event('input', {bubbles: true}));
});
.range {
position: relative;
height: 52px; width: 500px;
border-radius: 0.125em;
overflow: hidden;
font: 16px/1em sans-serif;
background-image: linear-gradient(to right, #7bad23, #39594c), linear-gradient(to bottom, #84929d, #46576d);
background-size: 0 100%, 100% 100%;
background-repeat: no-repeat;
box-shadow: 0 0 0 0.125em #7f8c97, 0.0625em 0.125em 0.3125em 0em #93a2bd, -0.125em -0.1875em 0.3125em 0em #0e1116, inset 0 0 1.25em -0.3125em #0e1116;
}
datalist {
position: relative;
display: block;
height: 100%; width: 100%;
pointer-events: none;
}
.range datalist option {
position: absolute !important;
display: grid;
place-items: center;
height: 100%;
padding: 0;
transform: translatex(-50%);
font: bold 12px/1em monospace !important;
text-shadow: 1px 0 0.16666667em #fff5;
}
.range datalist option::before,
.range datalist option::after {
content: "";
position: absolute;
left: 50%;
height: 100%; width: 0;
box-shadow: 0 0 0 0.08333333em #0008;
}
.range datalist option::before { bottom: calc(50% + 1em); }
.range datalist option::after { top: calc(50% + 1em); }
input[type="range"] {
appearance: none;
position: absolute;
top: 0; left: 0; z-index: 1;
margin: 0;
height: 100%; width: 100%;
box-sizing: border-box;
font: inherit;
background-color: transparent;
cursor: pointer;
}
input[type="range"]::-webkit-slider-thumb {
appearance: none;
display: block;
width: 2.5em; height: 2.5em;
border: none;
border-radius: 0.75em;
background-color: #99c7;
box-shadow: 0 0 0.125em 0 #282850dd, inset 0 0 0.125em 0.125em #282850dd;
transition: background-color 0.5s ease-out 0.5s;
}
input[type="range"]:active::-webkit-slider-thumb {
background-color: #fff8;
transition: background-color 0.5s ease-out;
}
.range-value {
position: absolute;
top: 0; left: 0; z-index: 2;
display: grid;
place-items: center;
height: 100%;
transform: translatex(-50%);
font: bold 12px/1em monospace !important;
text-shadow: 0 0 0.16666667em #fff;
opacity: 0;
pointer-events: none;
transition: opacity 1s ease-in;
}
input[type="range"]:focus-visible~.range-value,
input[type="range"]:active~.range-value,
input[type="range"]:hover~.range-value {
opacity: 1;
transition: opacity 0.5s ease-out;
}
body { margin: 0; height: 100vh; background-color: #42516c; display: flex; flex-flow: column nowrap; justify-content: center; align-items: center; }
<div class="range">
<input type="range" list="high">
<datalist id="high">
<option value="0">
<option value="2">
<option value="4">
<option value="6">
<option value="8">
<option value="10">
<option value="20">
<option value="30">
<option value="40">
<option value="50">
<option value="60">
<option value="70">
<option value="100">
</datalist>
</div>
<h3>With "ticks-only" attribute</h3>
<div class="range">
<input type="range" list="bass" ticks-only>
<datalist id="bass">
<option value="0">
<option value="10">
<option value="15">
<option value="20">
<option value="30">
<option value="40">
<option value="50">
<option value="60">
<option value="70">
<option value="72">
<option value="74">
<option value="76">
<option value="78">
<option value="80">
<option value="100">
<option value="175">
<option value="200">
</datalist>
</div>
Note! This code only works for "webkit" (tested in Chrome). Firefox does not work correctly with the "position" property when parent and child elements are set to "absolute".
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/68606114",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Why AVL sort is not in place? I was recently told that AVL sort is not in place. Can anyone please explain it? From the below code, I am not sure where I assign extra space when sorting. In this code, when a data structure is built or an element are inserted, elements are ordered by their key.
Reference for the claim: They are using this claim to motivate "binary heap"
[1].https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-006-introduction-to-algorithms-spring-2020/lecture-notes/MIT6_006S20_r08.pdf
Reference for code:
[2]. https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-006-introduction-to-algorithms-spring-2020/lecture-notes/MIT6_006S20_r06.pdf
[3]. https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-006-introduction-to-algorithms-spring-2020/lecture-notes/MIT6_006S20_r07.pdf
def height(A):
if A: return A.height
else: return -1
class Binary_Node:
def __init__(self, x):
self.item = x
self.parent = None
self.left = None
self.right = None
self.subtree_update()
def subtree_update(self):
self.height = 1 + max(height(self.left), height(self.right))
def subtree_iter(self):
if self.left: yield from self.left.subtree_iter()
yield self
if self.right: yield from self.right.subtree_iter()
def subtree_first(self):
if self.left: return self.left.subtree_first()
else: return self
def subtree_last(self):
if self.right: return self.right.subtree_last()
else: return self
def sucessor(self):
if self.right: return self.right.subtree_first()
while self.parent and (self is self.parent.right): #A is parent's left child and A's parent exists
self = self.parent
return self.parent
def predecessor(self):
if self.left: return self.left.subtree_last()
while self.parent and (self is self.parent.left):
self = self.parent
return self.parent
def subtree_insert_before(self, A):
if self.left:
self = self.left.subtree_last()
self.right, A.parent = A, self
else:
self.left, A.parent = A, self
self.maintain()
def subtree_insert_after(self, A):
if self.right:
self = self.right.subtree_first()
self.left, A.parent = A, self
else:
self.right, A.parent = A, self
self.maintain()
def delete(self):
if not self.left and not self.right: # when self is leaf
if self.parent:
A = self.parent
if A.left is self: A.left = None
else: A.right = None
self.parent = None
if self.left:
self.item, self.left.subtree_last().item = self.left.subtree_last().item, self.item
self.left.subtree_last().delete()
else:
self.item, self.right.subtree_first().item = self.right.subtree_first().item, self.item
self.right.subtree_last().delete()
def subtree_delete(self):
if self.left or self.right:
if self.left: B = self.predecessor()
else: B = self.sucessor()
self.item, B.item = B.item, self.item
return B.subtree_delete()
if self.parent:
if self.parent.left is self: self.parent.left = None
else: self.parent.right = None
self.parent.maintain()
return self
def subtree_rotate_right(self):
assert self.left
B, E = self.left, self.right
A, C = B.left, B.right
B, self = self, B
self.item, B.item = B.item, self.item
B.left, B.right = A, self
self.left, self.right = C, E
if A: A.parent = B
if E: E.parent = self
B.subtree_update()
self.subtree_update()
def subtree_rotate_left(self):
assert self.right
A, D = self.left, self.right
C, E = D.left, D.right
self, D = D, self
self.item, D.item = D.item, self.item
self.left, self.right = A, C
D.left, D.right = self, E
if A: A.parent = self
if E: E.parent = D
self.subtree_update()
D.subtree_update()
def skew(self):
return height(self.right) - height(self.left)
def rebalance(self):
if self.skew() == 2:
if self.right.skew() < 0:
self.right.subtree_rotate_right()
self.subtree_rotate_left()
elif self.skew() == -2:
if self.left.skew() > 0:
self.left.subtree_rotate_left()
self.subtree_rotate_right()
def maintain(self):
self.rebalance()
self.subtree_update()
if self.parent: self.parent.maintain()
class Binary_Tree:
def __init__(self, Node_Type = Binary_Node):
self.root = None
self.size = 0
self.Node_Type = Node_Type
def __len__(self): return self.size
def __iter__(self):
if self.root:
for A in self.root.subtree_iter():
yield A.item
def build(self, X):
A = [x for x in X]
def build_subtree(A, i, j):
c = (i + j) // 2
root = self.Node_Type(A[c])
if i < c:
root.left = build_subtree(A, i, c - 1)
root.left.parent = root
if j > c:
root.right = build_subtree(A, c + 1, j)
root.right.parent = root
return root
self.root = build_subtree(A, 0, len(A) - 1)
class BST_Node(Binary_Node):
def subtree_find(self, k):
if self.item.key > k:
if self.left: self.left.subtree_find(k)
elif self.item.key < k:
if self.right: self.right.subtree_find(k)
else: return self
return None
def subtree_find_next(self, k):
if self.item.key <= k:
if self.right: return self.right.subtree_find_next(k)
else: return None
elif self.item.key > k:
if self.left: return self.left.subtree_find_next(k)
else: return self
return self
def subtree_find_prev(self, k):
if self.item.key >= k:
if self.left: return self.left.subtree_find_prev(k)
else: return None
elif self.item.key < k:
if self.right: return self.right.subtree_find_prev(k)
else: return self
return self
def subtree_insert(self, B):
if B.item.key < self.item.key:
if self.left: self.left.subtree_insert(B)
else: self.subtree_insert_before(B)
elif B.item.key > self.item.key:
if self.right: self.right.subtree_insert(B)
else: self.subtree_insert_after(B)
else:
self.item = B.item
class Set_Binary_Tree(Binary_Tree):
def __init__(self): super().__init__(BST_Node)
def iter_order(self): yield from self
def build(self, X):
for x in X: self.insert(x)
def find_min(self):
if self.root: return self.root.subtree_first()
def find_max(self):
if self.root: return self.root.subtree_last()
def find(self, k):
if self.root:
node = self.root.subtree_find(k)
if node:
return node.item
def find_next(self, k):
if self.root:
node = self.root.subtree_find_next(k)
if node:
return node.item
def find_prev(self, k):
if self.root:
node = self.root.subtree_find_prev(k)
if node:
return node.item
def insert(self, x):
new = self.Node_Type(x)
if self.root:
self.root.subtree_insert(new)
if new.parent is None: return False
else:
self.root = new
self.size += 1
return True
def delete(self, k):
assert self.root
node = self.root.subtree_find(k)
assert node
ext = node.subtree_delete()
if ext.parent is None: self.root = None
self.size -= 1
return ext.item
A: Wikipedia defines an in-place algorithm as follows:
In computer science, an in-place algorithm is an algorithm which transforms input using no auxiliary data structure. However, a small amount of extra storage space is allowed for auxiliary variables. The input is usually overwritten by the output as the algorithm executes. An in-place algorithm updates its input sequence only through replacement or swapping of elements.
So one of the properties of an algorithm that is called "in-place" is that it does not copy all input values into an newly allocated data structure. If an algorithm creates a binary search tree (like AVL), for which node objects are created that are populated with the input values, then it cannot be called in-place by the above definition, even if at the end of the process the values are copied back into the input array.
As a comparison, heap sort does not have to create a new data structure, as the input array can be used to reorganise its values into a heap. It merely has to swap values in that array in order to sort it. It is therefore an in-place algorithm.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/70285592",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Unhandled exception is not being caught by the handlers We have registered for the unhandled exceptions in the following way. The application is a remoting server. If an unhandled exception is thrown from the remoting server it is not handled by the unhandled exception handlers. What could be the problem?
[STAThread]
[Obfuscation(Exclude = true)]
static void Main(string[] args)
{
Application.ThreadException += new ThreadExceptionEventHandler(OnThreadException);
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(OnUnhandledException);
.
.
.
Application.EnableVisualStyles();
Application.Run(form);
}
A: Hope this method helps you 'Application.SetUnhandledExceptionMode'. It instructs the application how to respond to unhandled exceptions.
static void Main(string[] args)
{
Application.ThreadException += new ThreadExceptionEventHandler(OnThreadException);
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(OnUnhandledException);
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
Application.EnableVisualStyles();
Application.Run(form);
}
A: If it's a remoting server and the exception is happening as part of client interaction, then the exception will be sent to the client without causing the server to crash.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7329785",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: OPENSSL error: could not find native static library `C`, perhaps an -L flag is missing? I get the following error when I try to run the below code for a DTLS client server program using rust through visual studio code and its terminal. I have already installed openssl libraries using vcpkg and set the environment variables. I have also installed the c/c++ extensions for vscode.
Error: error: could not find native static library C, perhaps an -L flag is missing?
How do I resolve this error? My DTLS code is given below along with build.rs and cargo.toml
MAIN.rs
use openssl::ssl::SslMethod;
use std::{
io::{Read, Write},
net::UdpSocket,
thread,
time::Duration,
};
use udp_dtls::{Certificate, DtlsAcceptor, DtlsConnector, Identity, SrtpProfile};
use udp_dtls::{DtlsAcceptorBuilder, UdpChannel};
fn main() {
let buffer = include_bytes!("../test/identity.p12");
let identity = Identity::from_pkcs12(buffer, "mypass").unwrap();
let root_ca = include_bytes!("../test/root-ca.der");
let root_ca = Certificate::from_der(root_ca).unwrap();
let acceptor = DtlsAcceptor::builder(identity).build().unwrap();
let connector = DtlsConnector::builder()
.add_srtp_profile(SrtpProfile::Aes128CmSha180)
.add_srtp_profile(SrtpProfile::AeadAes256Gcm)
.add_root_certificate(root_ca)
.build()
.unwrap();
let server = UdpSocket::bind("127.0.0.1:0").unwrap();
let client = UdpSocket::bind("127.0.0.1:0").unwrap();
let server_addr = server.local_addr().unwrap();
let client_addr = client.local_addr().unwrap();
let server_channel = UdpChannel {
socket: server,
remote_addr: client_addr,
};
let client_channel = UdpChannel {
socket: client,
remote_addr: server_addr,
};
let guard = thread::spawn(move || {
let mut dtls_server = acceptor.accept(server_channel).unwrap();
let mut count = 0;
while true {
let mut received = [0; 5];
dtls_server.read_exact(&mut received);
println!(
"{:?} {:?}",
count,
String::from_utf8_lossy(received.as_ref())
);
count = count + 1;
thread::sleep(Duration::from_millis(2));
}
});
let mut dtls_client = connector.connect("foobar.com", client_channel).unwrap();
while true {
let mut buf = [0; 5];
let buf = b"hello";
dtls_client.write_all(buf);
thread::sleep(Duration::from_millis(30));
}
}
CARGO.toml
[package]
name = "udp-dtls"
version = "0.1.0"
authors = ["Timon Post <https://github.com/TimonPost>"]
edition = "2018"
description = "DTLS abstraction ontop of UDP"
repository = "https://github.com/TimonPost/udp-dtls"
documentation = "https://docs.rs/udp-dtls/"
license = "MIT"
keywords = ["DTLS", "UDP", "connection", "openssl", "ssl"]
exclude = ["target", "Cargo.lock"]
readme = "README.md"
[dependencies]
openssl = "0.10.19"
openssl-probe = "0.1.2"
log = "0.4.6"
bytes = "0.4.11"
[features]
vendored = ["openssl/vendored"]
BUILD.rs
use std::fs::File;
use std::io::Write;
use std::process::Command;
use std::env;
fn main() -> std::io::Result<()> {
if let Ok(v) = env::var("DEP_OPENSSL_VERSION_NUMBER") {
let version = u64::from_str_radix(&v, 16).unwrap();
if version >= 0x1_01_01_00_0 {
println!("cargo:rustc-cfg=openssl111");
}
}
let certs_dir = "src/certs";
let keys_dir = "src/keys";
let scratch_dir = "openssl-temp";
let server_ext = &format!("{}/server_ext", scratch_dir);
let client_ext = &format!("{}/client_ext", scratch_dir);
for dir in &[certs_dir, keys_dir, scratch_dir] {
// create if dir does not exist
match std::fs::create_dir(dir) {
_ => {}
}
}
let mut file = File::create(server_ext).unwrap();
file.write(b"basicConstraints=CA:false\nkeyUsage=critical,keyEncipherment")?;
let mut file = File::create(client_ext).unwrap();
file.write(b"basicConstraints=CA:false\nkeyUsage=critical,digitalSignature")?;
// Generate self-signed CA
Command::new("openssl")
.args(&[
"req",
"-x509",
"-newkey",
"rsa:2048",
"-subj",
"/CN=ca",
"-nodes",
"-keyout",
&format!("{}/ca-key.pem", keys_dir),
"-out",
&format!("{}/ca-cert.pem", certs_dir),
"-addext",
"keyUsage=critical,keyCertSign",
])
.output()?;
// Generate server key and CSR
Command::new("openssl")
.args(&[
"req",
"-newkey",
"rsa:2048",
"-subj",
"/CN=server",
"-nodes",
"-keyout",
&format!("{}/server-key.pem", keys_dir),
"-out",
&format!("{}/server-csr.pem", scratch_dir),
])
.output()?;
// Sign server CSR
Command::new("openssl")
.args(&[
"x509",
"-req",
"-CAcreateserial",
"-CA",
&format!("{}/ca-cert.pem", certs_dir),
"-CAkey",
&format!("{}/ca-key.pem", keys_dir),
"-in",
&format!("{}/server-csr.pem", scratch_dir),
"-out",
&format!("{}/server-cert.pem", certs_dir),
"-extfile",
server_ext,
])
.output()?;
// Generate client key and CSR
Command::new("openssl")
.args(&[
"req",
"-newkey",
"rsa:2048",
"-subj",
"/CN=client",
"-nodes",
"-keyout",
&format!("{}/client-key.pem", keys_dir),
"-out",
&format!("{}/client-csr.pem", scratch_dir),
])
.output()?;
// Sign client CSR
Command::new("openssl")
.args(&[
"x509",
"-req",
"-CAcreateserial",
"-CA",
&format!("{}/ca-cert.pem", certs_dir),
"-CAkey",
&format!("{}/ca-key.pem", keys_dir),
"-in",
&format!("{}/client-csr.pem", scratch_dir),
"-out",
&format!("{}/client-cert.pem", certs_dir),
"-extfile",
client_ext,
])
.output()?;
std::fs::remove_dir_all(scratch_dir)?;
Ok(())
}
For further reference please check this link for full code: https://github.com/TimonPost/udp-dtls
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72185223",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Wordpress if logged out, Laravel if logged in Well, the title explains it well... I do use Laravel for a control panel and Wordpress as the frontend facing the "outside world".
I need to use the same URL for both, I've accomplished it partially processing Wordpress as a Laravel view, but I have troubles with the Laravel namespaces/autoload and the Wordpress functionality.
It's easy to do what I need with .htaccess considering default routes... But the main trouble is with the index. The idea is to have the / route with Wordpress by default and with Laravel when logged in. Any ideas?
A: Well, sadly nobody answered. But I did it. Simply I did use a cookie to know where am I.
On laravel's www/index.php
if($_COOKIE['laravel']||$_SERVER['REQUEST_URI']=='/login'){
require __DIR__ . '/../private/bootstrap/autoload.php';
$app = require_once __DIR__ . '/../private/bootstrap/start.php';
$app->run();
}else{
define('WP_USE_THEMES', true);
require( dirname( __FILE__ ) . '/wordpress/wp-blog-header.php' );
}
On controllers/UserController.php function login()
if(Input::has('remember'))
setcookie ('laravel','yes!');
else
setcookie ('laravel','right!',time()+60*60*24*30);
On controllers/UserController.php function logout()
setcookie('laravel', null, -1);
Hope it helps somebody :)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/25491904",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: maven download plugin to add downloaded resource to jar I am using download-maven-plugin to download some of resources to be used in my project. The download is successful and I can use the downloaded file.
However, what I want is to include the downloaded file in the JAR.
Note : The resource file will be included in the JAR when it was pre-downloaded before running the build, but if it is not present (e.g. deleted or I want to update it perhaps) the resource file is not included in the JAR.
Basically what I want is to include the recently downloaded file (from mvn clean install) in the output JAR.
<plugin>
<groupId>com.googlecode.maven-download-plugin</groupId>
<artifactId>download-maven-plugin</artifactId>
<version>1.4.0</version>
<executions>
<execution>
<phase>prepare-package</phase>
<goals>
<goal>wget</goal>
</goals>
<configuration>
<url>https://downloadurl</url>
<outputFileName>error.json</outputFileName>
<outputDirectory>${project.resources.dir}/commons</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
Same thing happens when I use maven-ant-run plugin.
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-antrun-plugin</artifactId>
<executions>
<execution>
<id>download-files</id>
<phase>prepare-package</phase>
<goals>
<goal>run</goal>
</goals>
<configuration>
<tasks>
<get src="https://downloadurl"
dest="${project.resources.dir}/commons/data.json"
verbose="true"
usetimestamp="true"/>
</tasks>
</configuration>
</execution>
</executions>
</plugin>
A: Just download it to ${basedir}/target/classes before packaging phase. You don't need it to be in sources in order to include it to JAR.
A: Solved!
I changed the phase to process-resources..
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-antrun-plugin</artifactId>
<executions>
<execution>
<id>download-files</id>
<phase>process-sources</phase>
<goals>
<goal>run</goal>
</goals>
<configuration>
<tasks>
<get src="https://downloadUrl"
dest="${project.resources.dir}/commons/error.json"
verbose="true"
usetimestamp="true"/>
</tasks>
</configuration>
</execution>
</executions>
</plugin>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/47689426",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Can not import copy_reg I am hosting my Web2py app on PythonAnyware and have an issue importing copy_reg which web2py apparently needs. In previous versions this was no issue.
The trace back is as follows:
Traceback (most recent call last):
File "/home/richdijk/web2py/gluon/restricted.py", line 220, in restricted
exec ccode in environment
File "/home/richdijk/web2py/applications/im/models/db.py", line 78, in <module>
auth.define_tables(username=False, signature=False)
File "/home/richdijk/web2py/gluon/tools.py", line 1784, in define_tables
format='%(first_name)s %(last_name)s (%(id)s)'))
File "/home/richdijk/web2py/gluon/dal.py", line 8223, in define_table
table = self.lazy_define_table(tablename,*fields,**args)
File "/home/richdijk/web2py/gluon/dal.py", line 8260, in lazy_define_table
polymodel=polymodel)
File "/home/richdijk/web2py/gluon/dal.py", line 1122, in create_table
sql_fields_old = pickle.load(tfile)
File "/home/richdijk/web2py/gluon/custom_import.py", line 92, in custom_importer
return base_importer(pname, globals, locals, fromlist, level)
ImportError: No module named copy_reg
Does anybody know the resolution for this?
Thank you
A: For future reference:
Most often you should clear the cache and sessions. Use the appadmin interface to have a gui for this. This solved the issue for me more than once.
Sessions are pickled files which might lead to these problems. For example if you synchronize between different platforms, python versions and maybe sometimes even between upgrades on web2py (though i'm not certain on the latter).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/25023485",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Run an activity in background I'm using an activity to get MMS attachment once a MMS is received. I have completed the MMS listener for this and it will call the activity, which will use getContentResolver() to grab the attachment. I want the activity to run in the background, without showing the empty UI to the user. Is there anyway to do it?
A: You will want to use a service to make this happen. It is basically an activity without a view. Check out the link below for more info.
http://developer.android.com/guide/topics/fundamentals/services.html
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/6935259",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: git reset --mixed delete newly added file? I'm working with git on Github with a C++ project.
I have done the following in this order:
*
*Codding existing and new .cpp and .h files. Also added a big .stl file.
*Add the new files to git
*Create commit "A" with this changes
*Tried to push commit "A" to Github. It didn't let me push the commit because a file of 121MB had been added, which is more than the Github limit.
*Used the git reset --mixed command so that I could undo the commit "A" containing the large file, add that file to .gitignore, and recreate a commit without that file.
Now the changes contained in files that were already tracked have remained and I can re-commit them, but the newly added files in commit "A" are all gone.
Isn't the git reset --mixed command just undoing the commits without changing the files?
Is there any way to recover these files that I had just added to git and that have been deleted?
A: Apparently, the action that hides behind your IDE's "reset commit" isn't git reset --mixed, and it resulted in files being deleted from your disk.
As said in the comments : you can use the reflog to find past commits.
*
*run git reflog to spot the sha for commit A (the faulty commit with the 121MB file)
*use whatever action you see fit to get files back from that commit :
*
*git reset A
*git checkout A -- file1 file2
*git restore -s A -W -- . or git restore -s A -W -- file1 file2
*...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/70591327",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: how can i add an attribute onClick oto my links generated automatically? I would like to add an attribute onClick to my links generated automatically with jquery.
I select the parent div and then search if it has a link child, then add the attribute onClick.
It works on localhost but not on server
there is my code :
$('div.holder_notify_drop_data,li.holder_notify_drop_data').each(function () {
if ($(this).children('a').hasClass('holder_notify_drop_link')) {
$(this).on('click', function (e) {
var url = $(this).children('a').attr('href');
$(this).children('a').attr('onClick', "openFrame('" + url + "','yes')");
e.preventDefault();
});
};)
};
How can i do this ?
A: Make sure you include jQuery:
<script src="http://code.jquery.com/jquery-latest.js"></script>
IMPORTANT: Also put your code inside a document-ready function and I would suggest you to use jQuery click() function instead of the way you have done, but that's okay:
$(document).ready(function () {
$('div.holder_notify_drop_data,li.holder_notify_drop_data').each(function(){
if ($(this).children('a').hasClass('holder_notify_drop_link')){
$(this).on('click',function(e) {
var url = $(this).children('a').attr('href');
$(this).children('a').attr('onClick',"openFrame('"+url+"','yes')");
e.preventDefault();
});
};
)};
});
A: Here's a working example http://jsfiddle.net/g248G/.
HTML:
<div class="holder_notify_drop_data">
<a class="holder_notify_drop_link"
href="http://stackoverflow.com">Stackoverflow.com</a>
</div>
<ul>
<li class="holder_notify_drop_data">
<a class="holder_notify_drop_link"
href="http://google.com">Google.com</a>
</li>
</ul>
Javascript:
function openFrame(URL, option) {
window.open(URL);
}
$(document).ready(function() {
$('div.holder_notify_drop_data,li.holder_notify_drop_data').each(function() {
$(this).children('a').each(function() {
var $link = $(this);
if ($link.hasClass('holder_notify_drop_link')) {
var URL = $link.attr('href');
$link.on('click', function(event) {
event.preventDefault();
openFrame(URL, 'yes');
});
}
});
});
});
A: Why not use jQuery.on() for that?
This will bind click function to all current and future elements of a in holder_notify_drop_data container.
$('.holder_notify_drop_data').on('click', 'a', function (ev) {
ev.preventDefault();
openFrame($(this).prop('href'), 'yes');
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/22480088",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Difference between 2 DTD tag I want to know what is difference between this 2 ELEMENT tag :
<!ELEMENT bank (account*, customer*, depositor*)>
and
<!ELEMENT bank (account | customer | depositor )*>
thanks.
A: In a nutshell, the first ELEMENT declaration is saying the child elements have to be in a specific order. The second ELEMENT declaration is saying the child elements can be in any order.
The following means: a bank element containing zero or more account elements, followed by zero or more customer elements, followed by zero or more depositor elements. (In that specific order.)
<!ELEMENT bank (account*, customer*, depositor*)>
The following means: a bank element containing zero or more account or customer or depositor elements (in any order).
<!ELEMENT bank (account | customer | depositor )*>
The ',' means "followed by" and the '|' means "or". The '*' means zero or more. Also, a '+' means one or more (at least one).
A: It denotes a regular expression. Though I'm not very good at that, I think the second tag accepts sub-element of either account or customer or depositor.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/8832426",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Parsley Form Validation Error Okay,
I'm still a javascript student so I need some help. I'm using parsley.js for form validation and then jquery ajax to submit the form. I keep getting this luke warm message in the console to bind parsley to an existing element. I've followed all the instructions but continue to get a warning.
How can I get rid of the warning?
Code can be seen here: http://madmen6raphics.com/clients/marble/
thanks in advance.
Here is the code:
HTML:
<form action='mail_form.php' data-parsley-validate id='newsletter_signup' method='post' name='newsletter_signup' novalidate>
<fieldset>
<legend>Joing our mailing list!</legend>
<label for='name'>name:</label>
<input data-parsley-minlength='5' id='name' name='name' placeholder='John Doe' required type='text'>
<label for='email'>email:</label>
<input id='email' name='email' placeholder='johndoe@me.com' required type='email'>
<input name='Submit' type='submit'>
</fieldset>
</form>
javascript:
$('#newsletter_signup').parsley();
A: You are getting two errors of
You must bind Parsley on an existing element.
but those errors are not related to the code you posted.
In your ...js/site.js you have the following code:
$(document).ready(function() {
$('.slider').flexslider({controlNav: false,slideshowSpeed: 3000,directionNav: true});
$('input').iCheck({checkboxClass: 'icheckbox_square-yellow',radioClass: 'iradio_square-yellow',increaseArea: '20%'});
$('#newsletter_signup').parsley();
$('#request_a_quote').parsley();
$('#contact').parsley();
var form = $('#newsletter_signup');
(...)
You are binding parsley to three elements with the following ids: newsletter_signup, request_a_quote and contact.
The thing is, in the current page you only have the element newsletter_signup. If you do a console.log($('#request_a_quote')) you will see an empty object.
So, to fix your issue, you need to remove the code that binds parsley to non-existent elements. Or you could change your code in order to bind parsley only if the element exist. Something like this:
$(document).ready(function() {
$('.slider').flexslider({controlNav: false,slideshowSpeed: 3000,directionNav: true});
$('input').iCheck({checkboxClass: 'icheckbox_square-yellow',radioClass: 'iradio_square-yellow',increaseArea: '20%'});
if ($('#newsletter_signup').length > 0 )
$('#newsletter_signup').parsley();
if ($('#request_a_quote').length > 0 )
$('#request_a_quote').parsley();
if ($('#contact').length > 0 )
$('#contact').parsley();
var form = $('#newsletter_signup');
(...)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/25836868",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: WPF DataGrid selected row stays highlighted even when user clicks another control Is it possible to turn off the selected row highlighting when a user clicks another control in the window?
Thanks in advance.
A: You could set the SelectedIndex to -1 in the LostFocus event, thus losing the selected item and removing the highlight.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/4378492",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Quickstart.py - failed to connect to all addresses I installed the Python libraries on my local PC, I also added my GA-4 Property ID. When I attempt to run the script I get the following error, note that the error actually makes sense because the IP Address failing doesn't have a valid SSL certificate:
Traceback (most recent call last):
File "\\usalbodd01\bod_Share\BODS_Tools\google\api_core\grpc_helpers.py", line 72, in error_remapped_callable
return callable_(*args, **kwargs)
File "\\usalbodd01\bod_Share\BODS_Tools\grpc\_channel.py", line 946, in __call__
return _end_unary_response_blocking(state, call, False, None)
File "\\usalbodd01\bod_Share\BODS_Tools\grpc\_channel.py", line 849, in _end_unary_response_blocking
raise _InactiveRpcError(state)
grpc._channel._InactiveRpcError: <_InactiveRpcError of RPC that terminated with:
status = StatusCode.UNAVAILABLE
details = "failed to connect to all addresses; last error: UNKNOWN: ipv4:142.250.190.10:443: Ssl handshake failed: SSL_ERROR_SSL: error:1000007d:SSL routines:OPENSSL_internal:CERTIFICATE_VERIFY_FAILED"
debug_error_string = "UNKNOWN:failed to connect to all addresses; last error: UNKNOWN: ipv4:142.250.190.10:443: Ssl handshake failed: SSL_ERROR_SSL: error:1000007d:SSL routines:OPENSSL_internal:CERTIFICATE_VERIFY_FAILED {grpc_status:14, created_time:"2022-11-28T18:41:22.060505311+00:00"}"
>
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "\\usalbodd01\bod_Share\BODS_Tools\GoogleQuickstart.py", line 51, in <module>
sample_run_report("")
File "\\usalbodd01\bod_Share\BODS_Tools\GoogleQuickstart.py", line 43, in sample_run_report
response = client.run_report(request)
File "\\usalbodd01\bod_Share\BODS_Tools\google\analytics\data_v1beta\services\beta_analytics_data\client.py", line 511, in run_report
response = rpc(
File "\\usalbodd01\bod_Share\BODS_Tools\google\api_core\gapic_v1\method.py", line 154, in __call__
return wrapped_func(*args, **kwargs)
File "\\usalbodd01\bod_Share\BODS_Tools\google\api_core\grpc_helpers.py", line 74, in error_remapped_callable
raise exceptions.from_grpc_error(exc) from exc
google.api_core.exceptions.ServiceUnavailable: 503 failed to connect to all addresses; last error: UNKNOWN: ipv4:142.250.190.10:443: Ssl handshake failed: SSL_ERROR_SSL: error:1000007d:SSL routines:OPENSSL_internal:CERTIFICATE_VERIFY_FAILED
Have any of you run into this when attempting to run the quickstart.py script locally?
Regards,
Greg
I attempted to run the script after following the "TODOS". I installed the Google certificates locally. I then tested the IP Address the script is failing on, the address is not secured.
Your connection isn't private
Attackers might be trying to steal your information from 142.250.190.10 (for example, passwords, messages, or credit cards).
NET::ERR_CERT_AUTHORITY_INVALID
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/74605351",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: mootools Fx.slide not working IE6 I have some javascript that is built on top of mootools that is basically giving a div some show/hide functionality.
window.addEvent('domready', function(){
/*var mySlide = new Fx.Slide('customise_text').hide()
var mySlide2 = new Fx.Slide('customise_link').hide()
$('customise').addEvent('click', function(e){
$('customise').addClass('active');
mySlide.toggle(); //show-hide login panel
mySlide2.toggle(); //show-hide login panel
e.preventDefault();
});*/
/*$('moodal_close').addEvent('click', function(){
alert("1");
});*/
//alert("hello")
var vertical_slide = $('vertical_slide');
var checkoutVerticalSlide = $('vertical_slide_checkout');
var v_toggle_checkout = $('v_toggle_checkout');
if(!vertical_slide || !checkoutVerticalSlide || !v_toggle_checkout) {
return;
} else {
var status = {
'true': 'open',
'false': 'close'
};
//-vertical
var myVerticalSlide = new Fx.Slide('vertical_slide').hide();
$('v_toggle').addEvent('click', function(e){
e.preventDefault();
myVerticalSlide.toggle();
});
// When Vertical Slide ends its transition, we check for its status
// note that complete will not affect 'hide' and 'show' methods
myVerticalSlide.addEvent('complete', function() {
if(status[myVerticalSlide.open] == 'open')
{
$('v_toggle').addClass('open');
} else {
$('v_toggle').removeClass('open');
}
});
var checkout_status = {
'true': 'open',
'false': 'close'
};
var checkoutVerticalSlide = new Fx.Slide('vertical_slide_checkout').hide();
$('v_toggle_checkout').addEvent('click', function(e) {
e.preventDefault();
checkoutVerticalSlide.toggle();
});
checkoutVerticalSlide.addEvent('complete', function() {
if(status[checkoutVerticalSlide.open] == 'open')
{
$('v_toggle_checkout').addClass('open');
} else {
$('v_toggle_checkout').removeClass('open');
}
});
}
In IE6 I get page loaded with errors and get an error of Object does not support this method or property
A: This could be due to the fact that IE6 does not support the preventDefault method.
Where you make use of this method (e.preventDefault()), replace the call with the following
if (e.preventDefault) { e.preventDefault(); } else { e.returnValue = false; }
See if that works for you :)
While it feels warm and fuzzy to be able to support all browsers, IE6 is not a warm and fuzzy kind of browser. You will keep running into problems if you want to fully support IE6, I'm afraid.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/3085588",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Pandas merge columns, but not the 'key' column This may seem like a stupid question, but this has been bugging me for some time.
df1:
imp_type value
1 abc
2 def
3 ghi
df2:
id value2
1 123
2 345
3 567
Merginge the 2 df's:
df1.merge(df2, left_on='imp_type',right_on='id')
yields:
imp_type value id value2
1 abc 1 123
2 def 2 345
3 ghi 3 567
Then I need to drop the id column since it's essentially a duplicate of the imp_type column. Why does merge pull in the join key between the 2 dataframes by default? I would think there should at least be a param to set to False if you don't want to pull in the join key. Is there something like this already or something I'm doing wrong?
A: I agree it would be nice if one of the columns were dropped. Of course, then there is the question of what to name the remaining column.
Anyway, here is a workaround. Simply rename one of the columns so that the joined column(s) have the same name:
In [23]: df1 = pd.DataFrame({'imp_type':[1,2,3], 'value':['abc','def','ghi']})
In [27]: df2 = pd.DataFrame({'id':[1,2,3], 'value2':[123,345,567]})
In [28]: df2.columns = ['imp_type','value2']
In [29]: df1.merge(df2, on='imp_type')
Out[29]:
imp_type value value2
0 1 abc 123
1 2 def 345
2 3 ghi 567
Renaming the columns is a bit of a pain, especially (as DSM points out) compared to .drop('id', 1). However, if you can arrange for the joined columns to have the same name from the very beginning, then df1.merge(df2, on='imp_type') would be easiest.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/22208218",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "25"
}
|
Q: Inno Setup for Windows service? I have a .Net Windows service. I want to create an installer to install that windows service.
Basically, it has to do the following:
*
*Pack installutil.exe (Is it required?)
*Run installutil.exe MyService.exe
*Start MyService
Also, I want to provide an uninstaller which runs the following command:
installutil.exe /u MyService.exe
How to do these using Inno Setup?
A: Here's how i did it:
Exec(ExpandConstant('{dotnet40}\InstallUtil.exe'), ServiceLocation, '', SW_HIDE, ewWaitUntilTerminated, ResultCode);
Apparently, Inno setup has the following constants for referencing the .NET folder on your system:
*
*{dotnet11}
*{dotnet20}
*{dotnet2032}
*{dotnet2064}
*{dotnet40}
*{dotnet4032}
*{dotnet4064}
More information available here.
A: You can use
Exec(
ExpandConstant('{sys}\sc.exe'),
ExpandConstant('create "MyService" binPath= {app}\MyService.exe start= auto DisplayName= "My Service" obj= LocalSystem'),
'',
SW_HIDE,
ewWaitUntilTerminated,
ResultCode
)
to create a service. See "sc.exe" on how to start, stop, check service status, delete service, etc.
A: You don't need installutil.exe and probably you don't even have rights to redistribute it.
Here is the way I'm doing it in my application:
using System;
using System.Collections.Generic;
using System.Configuration.Install;
using System.IO;
using System.Linq;
using System.Reflection;
using System.ServiceProcess;
using System.Text;
static void Main(string[] args)
{
if (System.Environment.UserInteractive)
{
string parameter = string.Concat(args);
switch (parameter)
{
case "--install":
ManagedInstallerClass.InstallHelper(new string[] { Assembly.GetExecutingAssembly().Location });
break;
case "--uninstall":
ManagedInstallerClass.InstallHelper(new string[] { "/u", Assembly.GetExecutingAssembly().Location });
break;
}
}
else
{
ServiceBase.Run(new WindowsService());
}
}
Basically you can have your service to install/uninstall on its own by using ManagedInstallerClass as shown in my example.
Then it's just matter of adding into your InnoSetup script something like this:
[Run]
Filename: "{app}\MYSERVICE.EXE"; Parameters: "--install"
[UninstallRun]
Filename: "{app}\MYSERVICE.EXE"; Parameters: "--uninstall"
A: If you want to avoid reboots when the user upgrades then you need to stop the service before copying the exe and start again after.
There are some script functions to do this at Service - Functions to Start, Stop, Install, Remove a Service
A: have a look at topshelf
http://topshelf-project.com/
*
*it lets you develop your service as a console application
*adds a start/stop service as an API to your service...
*... that you can call from InnoSetup
[Run] Filename: "{app}\myservice.exe"; Parameters: "stop" ; Flags : waituntilterminated Filename: "{app}\myservice.exe"; Parameters: "uninstall" ; Flags : waituntilterminated Filename: "{app}\myservice.exe"; Parameters: "install -description ""myservice""" ; Flags : waituntilterminated
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/1449994",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "108"
}
|
Q: libpcap or PF_PACKET? I understand this question has been discussed many times: Should I use libpcap or PF_PACKET (the data link socket) to capture packets?
Based on my research, libpcap is suggested over PF_PACKET almost everywhere, mainly due to its portability.
However, for my current project (which is used in a production system), portability is not a concern at all, all I care about is performance (speed, packet loss ratio). My program is running on CentOS 5.10 (kernel 2.6.18)
As far as I know, libpcap put a timestamp on each packet. Does this cause big performance loss?
Are there other factors that make libpcap unsuitable in a high-speed network?
A:
As far as I know, libpcap put a timestamp on each packet.
No, libpcap gets a timestamp for the packet from the OS packet capture mechanism that it uses - which, on Linux is...
...PF_PACKET sockets.
The Linux kernel time stamps incoming packets. PF_PACKET sockets have multiple ways of reading from them:
*
*regular socket receives, for which you can either get a time stamp with an explicit ioctl (so you can avoid fetching it to userland, but you can't avoid the kernel time stamping the packet in the first place; libpcap, when using regular socket receives, always asks for the time stamp);
*memory-mapped access, which always supplies the time stamp.
Libpcap uses memory-mapped access whenever it's available; if you care about capture performance, you probably want to do so as well. It's not easy to use, however.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/26364888",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: How to use python to export the bake image form blender I want to make some operationi automatic.But I met some trouble in export the image after I bake it.At first I try to use "bpy.ops.object.bake_image()" to bake the image.But the result image can not be active in uv editor.
The bake was success,but the result image didn't appear in the uv editor.It need selected so that I could export the file.
So I search the document , and found the other command "bpy.ops.object.bake()".It have a parameter "save_mode",but I still met some obstacle in using this command.It always point me out that " RuntimeError: error: No active image found in material "material" (0) for object "1.001" ".
Here is the official document about this two command:
https://docs.blender.org/api/blender_python_api_2_78a_release/bpy.ops.object.html?highlight=bake#bpy.ops.object.bake
Can anyone try to give me some solution or some advice that how can I make this thing right.
A: Many of blenders operators require a certain context to be right before they will work, for bpy.ops.image.save() that includes the UV/Image editor having an active image. While there are ways to override the current context to make them work, it can often be easier to use other methods.
The Image object can save() itself. If it is a new image you will first need to set it's filepath, you may also want to set it's file_format.
img = bpy.data.images['imagename']
img.filepath = '/path/to/save/imagename.png'
img.file_format = 'PNG'
img.save()
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/42469844",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Compare Positions of Values in Php Array $commands = array();
for($p = 0; $p < $commandCount ; $p++){
$commands[$p] = $_POST['select'.$p];
}
So I have this Array $commands. In this Array, a List of Commands is stored. I have to check on which Position the Command "mark" is stored and if a certain command follows after it.
Some Example Data which can be in $commands:
"mark", "ignore", "pick", "random"
How would You do it?
A: You can use $index = array_search("mark", $commands) which will return the index of the first occurrence of the command "mark" and then you can use $commands[$index + 1] to get the next command in the array.
You will also need to check if $index != null as otherwise it may return the first item in your $commands array because null is interpreted as 0
A: Here is a demonstration with a battery of test cases to fully express how it works and identify fringe cases: (Demo Link)
*note, array_search() returns false when the needle is not found.
$commands = array("mark", "ignore", "pick", "random");
$attempts = array("mark", "ignore", "pick", "random", "bonk");
foreach($attempts as $attempt){
echo "$attempt => ";
$index=array_search($attempt,$commands);
// vv---increment the value
if($index===false || !isset($commands[++$index])){ // not found or found last element
$index=0; // use first element
}
echo $commands[$index],"\n";
}
The "or" (||) condition will "short circuit", so if $index is false it will exit the condition without calling the second expression (isset()).
Output:
mark => ignore
ignore => pick
pick => random
random => mark
bonk => mark
A: Just did some double checking you're going to want to assert first that your array contains the value of mark first. array_search will return a false otherwise, and that easily can be translated into 0.
Supporting Documentation :
PHP in_array
PHP array_search
$commands = array("mark", "ignore", "pick", "random");
//checks if $command contains mark,
//gets first index as per documentation
//Or sets index to -1, ie No such value exists.
$index = in_array("mark",$commands) ? array_search("mark",$commands):-1;
//gets the next command if it exists
$nextCommand = $index!=-1? $commands[++$index]:"Unable to Find Command: mark";
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/48846566",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Javascript image change causes embeded UserControls to flicker I have a n html page being displayed in IE. It has some buttons made up of images with mouseover/mouseout events on them in JavaScript, and a bunch of embedded .Net UserControls.
When the mouseover/mouseout events fire, I change the images src to something else (simple rollover effect). The problem is that the UserControls often (but not always) flicker when this happens.
To be clear, the images don't flicker, and the rest of the page doesn't flicker, just the embedded controls. This page is local, not coming from a server or anything.
So, any ideas?
More information : I've noticed that highlighting text does it too...
A: If you didn't preload the images, you could see this kind of problem.
To preload the images, just add a special div with the wanted urls.
<div id="preload">
<img src="/path/to/my/image.png" alt="">
<img src="/img2.gif" alt="">
</div>
In your css:
#preload { display:none; }
That's it !
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/866955",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Is there any good spec or library for uri-templating(routing) in java or scala I'm trying to create a mvc framework for myself in scala. Routers are necessary. I have a route file, contains:
/ "App.index"
/users "Users.index"
/users/{id} "Users.show"
/articles/{year}/{month}/{day} "Article.list"
I need a library to parse the urls and find the best matching.
I know there is one uri-templates, but I hope I can find more.
A: You can look at Routineer - Scala DSL for declaring HTTP routes:
https://github.com/mvv/routineer
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/5126932",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: jquery condition remove disable I have a class that has the value of total
<span class="price-value">0</span>
and a class of a radio button
class="radio-livraison element-radio-input" disabled="disabled"
is is possible to disable the radio button and enable it only if total is more than 28;
example you can't check the radio button if span price-value is less than 28
<script>
if ($('.ezfc-price-value') > 24){
$('.ly-radio-livraison').removeAttr("disabled");
}
</script>
but I get error:
Uncaught TypeError: $ is not a function
I have jQuery and Bootstrap on my template before the code.
A: Try this:
<script>
if (parseInt$('.ezfc-price-value').text()) > 24){
$('.ly-radio-livraison').prop("disabled", false);
}
</script>
You need to compare the text inside that element, not the element itself.
Hope this helps.
A: demo: http://jsbin.com/toguruzure/1/edit?html,js,output
$(function(){
$(".price-value").change(function(){
$('.radio-livraison').prop("disabled", !(parseInt($('.price-value').text()) > 28));
});
$("#total").on('input', function(){
$(".price-value").text($(this).val()).change();
});
})
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/49189513",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: DB2/400 SQL : How to insert PDF file in Blob Column? I would like to know if my SQL insert code is OK.
Here is my table :
-- Create table
Create table FNS_CHAMP_DEV
(
IDAUTO Integer not null generated always as identity ( start with
0, increment by 1, no cache) primary key,
BB_COL BLOB,
CB_COL CLOB
);
Is my syntax SQL below correct to insert a PDF file in BLOB Column ?
-- SQL insert request :
SELECT IDAUTO AS Last_ID from final table (Insert into FNS_CHAMP_DEV (
BB_COL ) Values(blob('C:\DOC_TECHNIQUE_WD\TEC_VISUAL_STUDIO\WPF_VISUAL_STUDIO.pdf')));
Thanks
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/54711276",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Why do I need Sum and Bank class to calculate Money? I am reading Test Driven Development: By Example. I am on chapter 13. Chapter 12 and 13 introduced Plus operation to Money object. A Money object can plus by other Money object.
The author added two classes (Bank and Sum) and one interface (IExpression) to the solution. This is the class diagram of the final solution.
Money store amount and currency for example 10 USD, 5 BAHT, 20 CHF. The Plus method returns Sum object.
public class Money : IExpression
{
private const string USD = "USD";
private const string CHF = "CHF";
public int Amount { get; protected set; }
public string Currency { get; private set; }
public Money(int value, string currency)
{
this.Amount = value;
this.Currency = currency;
}
public static Money Dollar(int amount)
{
return new Money(amount, USD);
}
public static Money Franc(int amount)
{
return new Money(amount, CHF);
}
public Money Times(int times)
{
return new Money(this.Amount * times, this.Currency);
}
public IExpression Plus(Money money)
{
return new Sum(this, money);
}
public Money Reduce(string to)
{
return this;
}
public override bool Equals(object obj)
{
var money = obj as Money;
if (money == null)
{
throw new ArgumentNullException("obj");
}
return this.Amount == money.Amount &&
this.Currency == money.Currency;
}
public override string ToString()
{
return string.Format("Amount: {0} {1}", this.Amount, this.Currency);
}
}
Sum store two Money objects which come from constructor arguments. It has one method Reduce that return new Money object (create new object by add amount of two object)
public class Sum : IExpression
{
public Money Augend { get; set; }
public Money Addend { get; set; }
public Sum(Money augend, Money addend)
{
this.Augend = augend;
this.Addend = addend;
}
public Money Reduce(string to)
{
var amount = this.Augend.Amount + this.Addend.Amount;
return new Money(amount, to);
}
}
Bank has one method - Reduce. It just call Reduce method of incoming IExpression argument.
public class Bank
{
public Money Reduce(IExpression source, string to)
{
return source.Reduce(to);
}
}
IExpression is an interface that implemented by Money and Sum.
public interface IExpression
{
Money Reduce(string to);
}
These are my questions.
*
*Bank does nothing good for the solution at this stage. Why do I need it?
*Why do I need Sum since I can create and return Money object inside Plus of the class Money (Like what the author did with Times)?
*What is the purpose of Bank and Sum? (Right now, it doesn't make any sense for me)
*I think Reduce sound strange for me as the method name. Do you think it is a good name? (please suggest)
A: Keep reading. Kent Beck is a very smart guy. He either has a very good reason why he created the example that way, and it will be clear later on, or it's a poor solution.
"Reduce" is a very good name if map-reduce is the ultimate goal.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/10395916",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: getline going over specified amount I have this code....
file_parser::file_parser(string file){
txtfile.open(file.c_str(), ios::in);
if (!txtfile.good()){
string error=err(0," "+file+" not found. Exit code ",1);
throw file_parse_exception(error);
}
while (!txtfile.eof()){
char str[200];
txtfile.getline(str, 200);
string str2=str;
vfile.push_back(str2);
}
txtfile.close();
}
and the problem is that if I have a line in the input file greater than 200 characters it hangs then crashes. I checked out the value of str at crash and it is preceded by a null char then it tries to push back a null(non-initialized) string onto the vector which causes the hang/crash. does anyone know a way to get around this? I thought by using getline it would truncate the char array at 199(+null) characters but apparently this isn't happening. I'm stumped. The thing is that I want each pushback to have a max of 200 characters. I really don't want the WHOLE line which is what 'string str' would do. and if a line is over 200 characters it should read the first 200 and then move on to the next line.
A: Replace your input loop with this:
std::string str;
while (std::getline(txtfile, str)){
vfile.push_back(str);
}
Using ios::eof() as a loop condition almost always creates a buggy program, as it did here. In this case, using eof() has two problems. First, eof() is only set after the read fails, not before, but you are checking it before the read. Second, eof() doesn't check the range of other errors. When an input line has more than 200 characters, istream::getline sets failbit, but not eofbit.
EDIT: With the added requirement of limiting the input lines to 200 characters, this should work:
// untested
std::string str;
while(std::getline(txtfile, str)) {
if(str.size() > 200)
str.erase(200, std::string::npos);
vfile.push_back(str);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/9425019",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do I add line breaks e.g. \\n in a Apache POI HWPF Document I have to modify Word Document in the old .doc format. Using Apache POI with the HWPF representation of the document. I struggled to insert line breaks into any table cell. In the modified document line breaks look like empty boxes.
table cell with added line break
The Code I used for this after I selected the specific cell:
cell.insertBefore("Test "+System.lineSeparator()+" Test");
The Following also doesnt work:
cell.insertBefore("Test "+System.getProperty("line.seperator")+" Test");
cell.insertBefore("Test \n Test");
cell.insertBefore("Test \r\n Test");
everything I tried was transformed into boxes.
I also tried writing the document to a temp file and then just replacing a placeholder with HWPF -> empty boxes.Does anybody know a solution to this?
Thanks in advance.
A: Forget about apache poi HWPF. It is in scratchpad and without any progress since decades. And there are no useable methods to insert or create new paragraphs. All Range.insertBefore and Range.insertAfter methods which take more than only text are private and deprecated and doesn't work properly also since decades. The reason of that may be that the binary file format of Microsoft Word HWPF of course is the most horrible file format of all the other horrible file formats like HSSF, HSLF. So who wants bothering with this?
But to answer your question:
In word processing text is structured in paragraphs containing text runs. Each paragraph takes a new line by default. But "Text\nText" or "Text\rText" or "Text\r\nText" stored in a text run would only mark a line break within that text run but not a new paragraph. Would ..., because of course Microsoft Word has it's own rules. There \u000B marks that line break within the text run.
So what you could do is the following:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.poi.hwpf.*;
import org.apache.poi.hwpf.usermodel.*;
public class ReadAndWriteDOCTable {
public static void main(String[] args) throws Exception {
HWPFDocument document = new HWPFDocument(new FileInputStream("TemplateDOC.doc"));
Range bodyRange = document.getRange();
System.out.println(bodyRange);
TableIterator tableIterator = new TableIterator(bodyRange);
while (tableIterator.hasNext()) {
Table table = tableIterator.next();
System.out.println(table);
TableCell cell = table.getRow(0).getCell(0); // first cell in table
System.out.println(cell);
Paragraph paragraph = cell.getParagraph(0); // first paragraph in cell
System.out.println(paragraph);
CharacterRun run = paragraph.insertBefore("Test\u000BTest");
System.out.println(run);
}
FileOutputStream out = new FileOutputStream("ResultDOC.doc");
document.write(out);
out.close();
document.close();
}
}
That places the text run "Test\u000BTest" before first paragraph in first cell of each table in the document. And the \u000B marks a line feed within that text run.
Maybe that is what you wanted to achieve? But, as said, forget about apache poi HWPF. The next unsolvable problem is only a step far away.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/68757906",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How does module resolution in TypeScript work for global values (i.e. describe)? While using jest on its own the corresponding typescript definitions got detected right after installing @types/jest.
I then started to implement integration tests with cypress. Since cypress is using mocha, I now incorrectly see references of mocha type definitions inside my jest tests. In fact, a number of overlapping type definitions are detected. For instance, describe seems to be defined in a number of files. I even tried to implement my own typing for describe pointing to jest. Unfortunately, every single time mocha "wins".
How can I specify the order of precedence when multiple definitions are detected by the typescript compiler?
My tsconfig.json looks like this:
{
"compilerOptions": {
"target": "es5",
"lib": [ "dom", "dom.iterable", "esnext" ],
"types": [ "jest", "mocha" ],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"strictNullChecks": true,
"forceConsistentCasingInFileNames": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": false,
"noEmit": true,
"jsx": "preserve"
},
"include": [ "src/**/*" ]
}
However, I also tried the following:
{
"compilerOptions": {
"target": "es5",
"lib": [ "dom", "dom.iterable", "esnext" ],
"typeRoots": [ "./node_modules/@types", "./src/types" ],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"strictNullChecks": true,
"forceConsistentCasingInFileNames": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": false,
"noEmit": true,
"jsx": "preserve"
},
"include": [ "src/**/*" ]
}
In both cases mocha is being chosen. How can I switch the type for "describe & co." to jest?
A: CompilerOptions.types allow you to restrict the typings you want to be available in the scope(folder)
You can try the following:
Create a top level tsconfig.json with
CompilerOptions.types = []
Inside test folder create tsconfig.json and choose jest typings
CompilerOptions.types = ['jest']
Similarly inside integration folder, create tsconfig.json and choose mocha typings
CompilerOptions.types = ['mocha']
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/56149741",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "16"
}
|
Q: Webview Custom Back Button I need to make custom back button in WebView.
Its any way to get OnBackPress with custom button?
Just have a full screen webview, and i want to make button to going back in the webview.
Thanks.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/67403897",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Get a scenario-by-scenario pass/fail report with JBehave I want to generate a report from JBehave that just lists the name of each scenario and a PASS/FAIL status. Bonus points if it gives a PASS/FAIL status for a story based on the the scenario results (if all scenarios pass the story passes). Something like:
PASS: Story: Build a widget.
PASS: Scenario: Build a normal widget.
PASS: Scenario: Build a custom widget.
FAIL: Story: Test a widget.
PASS: Scenario: Test a normal widget.
FAIL: Scenario: Test a custom widget.
Text is preferred but I can work with other formats.
This post:
Additional logging JBehave
shows how to use a StoryReporter to capture pass/fail for individual steps, but going through the interface I can't see how to capture the final status of a single scenario.
A commenter later in the same post mentions that there are several view genaration examples in the source distribution. If someone can give more specific pointers to which of the examples do this that would help too.
A: The StoryReporter code below should do what you are looking for. It keeps track of each scenario and the pass/fail status of each step in the scenario. If any step fails, then the scenario is failed. If any scenario fails, then the story is marked as failed. At the end of the story it logs the results.
public class MyStoryReporter implements org.jbehave.core.reporters.StoryReporter {
private Story runningStory;
private boolean runningStoryStatus;
private String runningScenarioTitle;
private boolean runningScenarioStatus;
private List<ScenarioResult> scenarioList;
private Log log = LogFactory.getLog(this.getClass());
private class ScenarioResult {
public String title;
public boolean result;
public ScenarioResult(String title, boolean result) {
this.title = title;
this.result = result;
}
}
public void beforeStory(Story story, boolean b) {
runningStory = story;
runningStoryStatus = true;
scenarioList = new ArrayList<>();
}
public void afterStory(boolean b) {
String storyPrefix = runningStoryStatus ? "PASS: STORY: " : "FAIL: STORY: ";
log.info(storyPrefix + runningStory.getName() + ".");
String scenarioPrefix;
for (ScenarioResult scenario : scenarioList) {
scenarioPrefix = scenario.result ? " PASS: SCENARIO: " : " FAIL: SCENARIO: ";
log.info(scenarioPrefix + scenario.title + ".");
}
}
public void beforeScenario(String s) {
runningScenarioTitle = s;
runningScenarioStatus = true;
}
public void afterScenario() {
scenarioList.add(new ScenarioResult(runningScenarioTitle, runningScenarioStatus));
runningStoryStatus = runningStoryStatus && runningScenarioStatus;
}
public void failed(String s, Throwable throwable) {
runningScenarioStatus = false;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/25212694",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: 1-2-3 star level awards algorithm What I am trying to do is to have individual star counts per level based on player performance. (1-2-3 star awards.) This will be based on what region the player reaches. I know how to award the stars but keeping track of it all is throwing me problems. First lets say a player plays level 2 and receives 1 star for their performance. Then at a later time, s/he returns to the level and gets a 2 star. I would like the star count for that specific scene to update to two stars, while only adding 1 star ( The one extra s/he got this time) to the totalStarCount.
My initial plan was to have variables:
OldStarCount
NewStarCount
TotalStarCount
Then when a player reaches say region1, and is awarded one star, then NewStarCount would be set to one, then
TotalStarCount = TotalStarCount + (NewStarCount - OldStarCount);
Then update OldStarCount = NewStarCount;
Set NewStarCount = 0;
Move On to next Scene;
Am I approaching this the correct way? Any help would be greatly appreciated.
A: You could have something like this
int result = 0;
int totalStars = 0;
int[] starCounts = new int[NumberOfRegions};
...
currentRegion = 42;
result = play(currentRegion);
if(result > starCounts[currentRegion]){
totalStars += result - starCounts[currentRegion];
starCounts[currentRegion] = result;
}
This is just an example of what you could do. There are obvious scalability issues with this (what happens when you want to add new regions, etc), but you get the gist.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/21413668",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to specify probabilities as a command line argument for my dna generator? I wrote some code that can spit out a dna sequence of specified length, number of copies, specified probabilities, etc. In IDLE the program works fine as I preset the probabilities I want. I want this program to run efficiently from the command line.
How can I make my probabilities (weights) run as a command line argument like I've done for length and number of copies? I have no clue how to incorporate the probabilities as an argument in the command line. Thanks for your help!
Here is the code:
#!/usr/bin/env python
import sys
import random
weights=[.25,.25,.25,.25]
dna=['A','G','C','T']
def weighted_choice(weights,dna):
totals = []
running_total = 0
for w in weights:
running_total += w
totals.append(running_total)
rnd = random.random() * running_total
for i, total in enumerate(totals):
if rnd < total:
return dna[i]
def dna_gen(length):
seq=''
for i in range(length):
seq=seq+weighted_choice(weights,dna)
return seq
def dna_gen2(reps,length,weights,dna):
for i in range (reps):
print (dna_gen(length))
def main():
reps=int(sys.argv[1])
length=int(sys.argv[2])
weights=[float (w) for w in sys.argv[3:6]]
dna_gen2(reps,length,weights,dna)
if __name__=='__main__':
main()
A: Here you go:
#!/usr/bin/env python
import sys
import random
#weights=[.25,.25,.25,.25]
dna=['A','G','C','T']
def weighted_choice(weights,dna):
totals = []
running_total = 0
for w in weights:
running_total += w
totals.append(running_total)
rnd = random.random() * running_total
for i, total in enumerate(totals):
if rnd < total:
return dna[i]
def dna_gen(length):
seq=''
for i in range(length):
seq=seq+weighted_choice(weights,dna)
return seq
def dna_gen2(reps,length,weights,dna):
for i in range (reps):
print (dna_gen(length))
if __name__=='__main__':
reps = int(sys.argv[1])
length = int(sys.argv[2])
weights = [float (w) for w in sys.argv[3:6]]
dna_gen2(reps,length,weights,dna)
Now when I try it on the command line:
python nameOfYourScript.py 2 2 0.25 0.25 0.25 0.25
I get:
CG
GA
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/21766248",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: neighbour list with poly2nb() works on 2004 census shapefile but not on 2011 I'm trying to construct neighbours list from polygon list for Lower Layer Super Output Areas (LSOA) in London. I got my shapefiles from the London Datastore, by downloading here: https://data.london.gov.uk/dataset/statistical-gis-boundary-files-london
When I read in the 2004 shapefile (LSOA_2004_London_Low_Resolution.shp) it works perfectly:
ldn <- st_read("statistical-gis-boundaries-london/ESRI/LSOA_2004_London_Low_Resolution.shp")
#make into sp
ldn_sp <- as(ldn, "Spatial")
#create a list of neighbours using the Queen criteria (default, if you want rook chage to queen = FALSE)
w <- poly2nb(ldn_sp)
plot(ldn_sp, border = "grey60")
plot(w, coordinates(ldn_sp), pch = 19, cex = 0.6, add = TRUE)
When I read in the 2011 shapefile (LSOA_2011_London_gen_MHW.shp) however it seems to think that most of the LSOAs don't have neighbours.
When I use the 2011 one with the same code, I get this:
ldn <- st_read("statistical-gis-boundaries-london/ESRI/LSOA_2011_London_gen_MHW.shp")
ldn_sp <- as(ldn, "Spatial")
w <- poly2nb(ldn_sp)
plot(ldn_sp, border = "grey60")
plot(w, coordinates(ldn_sp), pch = 19, cex = 0.6, add = TRUE)
Does anyone have any ideas what I'm doing wrong? LSOAs which clearly should have neighbours show up with 0 links. I have no idea why...!
A: Looks like an issue with how the shapefile has been put together - polygons in LSOA_2011_London_gen_MHW.shp not sharing boundaries completely.
Using the snap argument in poly2nb will force the function to treat boundaries within a certain defined distance to be contiguous, e.g:
w <- poly2nb(ldn_sp, snap=10)
In above example, 10 = decimal degrees as your original data are in WGS84 - might want to convert to BNG and set a reasonable small distance in metres to snap. You'll need to experiment at bit, but 10 decimal degrees in the quick and dirty example above seems to generate something approximating an expected neighbours list.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/57675328",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to release the GIL in Cython for a multithreaded C++ class? I have a C++ class with some methods that use std::thread that I'm making accessible to Python via Cython. Do you know where in my Cython code I'd want to put the nogill directive? Would I want to put it when I declare the class methods or when I create a Cython wrapper class? I've used the example class from the Cython docs below:
Declaring the class:
cdef extern from "Rectangle.h" namespace "shapes":
cdef cppclass Rectangle:
Rectangle() except +
Rectangle(int, int, int, int) except +
int x0, y0, x1, y1
int getArea()
void getSize(int* width, int* height)
void move(int, int)
Cython wrapper class:
cdef class PyRectangle:
cdef Rectangle c_rect # hold a C++ instance which we're wrapping
def __cinit__(self, int x0, int y0, int x1, int y1):
self.c_rect = Rectangle(x0, y0, x1, y1)
def get_area(self):
return self.c_rect.getArea()
def get_size(self):
cdef int width, height
self.c_rect.getSize(&width, &height)
return width, height
def move(self, dx, dy):
self.c_rect.move(dx, dy)
A: You probably don't actually need to use nogil. The GIL only stops multiple Python threads being run simulatenously. However, given you're using C++ threads they can quite happily run in the background irrespective of the GIL, provided they don't try to use PyObjects or run Python code. So my suspicion is that you've misunderstood the GIL and you can get away with not thinking about it.
However, assuming that you do actually want to release it, you need to do 2 things:
*
*Mark the C++ functions as nogil to tell Cython that they don't need the GIL. Note that this doesn't actually release it - it just lets Cython know it isn't a problem if it is released:
cdef cppclass Rectange:
Rectangle(int, int, int, int) nogil except +
int getArea() nogil
# ...
*Use with nogil: blocks in your Cython wrapper class to mark the areas where the GIL is actually released.
cdef class PyRectangle:
# ...
def __cinit__(self, int x0, int y0, int x1, int y1):
with nogil:
self.c_rect = Rectangle(x0, y0, x1, y1)
def get_area(self):
cdef int result
with nogil:
result = self.c_rect.getArea()
return result
get_area becomes slightly more complicated since the return statement can't exist inside the with nogil block since it involves generating a Python object.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/42763186",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
}
|
Q: python logging to terminal, redirect to workspace/file I started tinkering with logging and BLE. Now I got this piece of code I took from the bgapi package. I think I kind of understand how it works, but I'd like to see the output in a file or in the workspace. How would I achieve this?
def pipe_logs_to_terminal(self, level=logging.INFO):
term = logging.StreamHandler(sys.stdout)
formatter = logging.Formatter(self._api._serial.portstr + ': %(asctime)s -
%(name)s - %(levelname)s - %(message)s')
term.setFormatter(formatter)
api_logger = logging.getLogger("bgapi")
api_logger.addHandler(term)
api_logger.setLevel(level=level)
A: You simply use logging.FileHandler(). I tried to implement it in your method:
def pipe_logs_to_terminal(self, level=logging.INFO):
log_path = "." # cwd
file_name = "my_app"
# configure root logger
api_logger = logging.getLogger("bgapi")
api_logger.setLevel(level=level)
# set format
formatter = logging.Formatter(self._api._serial.portstr + ': %(asctime)s - %(name)s - %(levelname)s - %(message)s')
# configure file handler
file_handler = logging.FileHandler("{0}/{1}.log".format(log_path, file_name))
file_handler.setFormatter(formatter)
api_logger.addHandler(file_handler)
# configure console handler
console_handler = logging.StreamHandler(sys.stdout)
console_handler.setFormatter(formatter)
api_logger.addHandler(console_handler)
Optionally you could omit the console_handler (called term in your example) part, if you choose to only pipe your logging into a file.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/50380264",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Can't seem to remove any annotations I have some pins that the user can add. In the callout there is a button.
When the user presses the button, I want a new pin to drop in that location, and I want to get rid of the pin that the user pressed (different types of pins).
Basically the first pin is draggable, and when the user has found a proper location they will "lock" it. (the locked pin acts differently in a few ways, which is why I need to replace the old pin)
anyways, this is the method where I do my processing. When I get to the [mapView removeAnnotation:view.annotation]; part all I get is "Program received signal: “EXC_BAD_ACCESS”."
Can anybody help me out here? (The issue is not that the new annotation does not appear, as it does appear. The issue is that the old annotation does not dissapear).
EDIT: Fixed code as per suggestion.
- (void) mapView:(MKMapView *)MapView
annotationView:(MKAnnotationView *)view
calloutAccessoryControlTapped:(UIControl *)control {
LockedPotholeAnnotation *annotation = [[[LockedPotholeAnnotation alloc] initWithCoordinate:view.annotation.coordinate addressDictionary:nil]autorelease];
NSString *titleString = [NSString stringWithFormat:@"Pothole at %.4f, %.4f", view.annotation.coordinate.latitude, view.annotation.coordinate.longitude];
annotation.title = titleString;
[mapView addAnnotation:annotation];
//[annotation release];
NSLog(@"Added Pin");
NSLog(@"VA: %@", [view.annotation class]);
[mapView removeAnnotation:view.annotation];
//[mapView removeAnnotations:mapView.annotations];
[mapView setNeedsDisplay];
}
A: This may not be the only thing, but the first thing that leaps out is that you autorelease the annotation on the line where you alloc it. Therefore you shouldn't also release it after you've added it to mapView.
As this stands, the annotation will likely be prematurely deallocated when the autorelease pool drains -- and if not exactly then, then at some subsequent point that is still premature. The map view will be stuck with a stale pointer and boom.
Not sure why that would manifest quite as soon as you describe, so there may be something else too...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/3971125",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to create a data frame aggregating the daily ticket numbers to monthly count? I am having the list of ticket numbers for each date. Date column is transformed to data but the ticket number column is a text.
Created Ticket
01-Jan-19 a1
02-Jan-19 a2
03-Jan-19 a3
04-Jan-19 a4
05-Jan-19 a5
06-Jan-19 a6
07-Jan-19 a7
08-Jan-19 a8
09-Jan-19 a9
10-Jan-19 a10
11-Jan-19 a11
12-Jan-19 a12
13-Jan-19 a13
14-Jan-19 a14
15-Jan-19 a15
16-Jan-19 a16
17-Jan-19 a17
18-Jan-19 a18
19-Jan-19 a19
01-Feb-19 a20
02-Feb-19 a21
03-Feb-19 a22
04-Feb-19 a23
Tried to use floor data in R but since the ticket number column is character I am not able to use it.
data <- read.csv(file = 'D:\\DS Data\\SampleTickets.csv', stringsAsFactors = FALSE,header = TRUE)
str(data)
library(readr)
library(lubridate)
library(dplyr)
data <- data %>%
mutate(Created = dmy(Created))
data %>% group_by(month=floor_date(Created, "month")) %>%
summarize(amount=sum(Ticket))
I am expecting a data frame output like..
CreatedMonth CountOfTickets
1/1/2019 18
1/2/2019 4
A: You were nearly there: Just use n() instead of sum(Ticket) to count the number of rows:
library(dplyr)
library(lubridate)
data %>%
mutate(Created = dmy(Created)) %>%
group_by(month = floor_date(Created, "month")) %>%
summarize(amount = n())
# A tibble: 2 x 2
month amount
<date> <int>
1 2019-01-01 19
2 2019-02-01 4
However, there is a shortcut which uses count():
data %>%
count(CreatedMonth = dmy(Created) %>% floor_date("month"))
# A tibble: 2 x 2
CreatedMonth n
<date> <int>
1 2019-01-01 19
2 2019-02-01 4
For the sake of completeness, here is also a data.table version:
library(lubridate)
library(data.table)
setDT(data)[, .N, by = .(CreatedMonth = floor_date(dmy(Created), "month"))]
CreatedMonth N
1: 2019-01-01 19
2: 2019-02-01 4
Data
data <- readr::read_table("Created Ticket
01-Jan-19 a1
02-Jan-19 a2
03-Jan-19 a3
04-Jan-19 a4
05-Jan-19 a5
06-Jan-19 a6
07-Jan-19 a7
08-Jan-19 a8
09-Jan-19 a9
10-Jan-19 a10
11-Jan-19 a11
12-Jan-19 a12
13-Jan-19 a13
14-Jan-19 a14
15-Jan-19 a15
16-Jan-19 a16
17-Jan-19 a17
18-Jan-19 a18
19-Jan-19 a19
01-Feb-19 a20
02-Feb-19 a21
03-Feb-19 a22
04-Feb-19 a23")
A: Using dplyr we can first convert Created column to actual Date and group them by each month and count number of tickets for each group.
library(dplyr)
df %>%
mutate(Created = as.Date(Created, "%d-%b-%y")) %>%
arrange(Created) %>%
mutate(Yearmon = format(Created, "%B-%Y"),
Yearmon = factor(Yearmon, levels = unique(Yearmon))) %>%
group_by(Yearmon) %>%
summarise(count = n())
# Yearmon count
# <fct> <int>
#1 January-2019 19
#2 February-2019 4
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/56689366",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: LINQ Join/Grouping issues So I am stuck again...
I have three tables that I am trying to join and group with linq; Company, Notices and Requests.
*
*A company could have many notices.
*A notice have a SubcategoryId and a CompanyId
*A request have a SubcategoryId.
My aim here is to get a list of companies and for each company get a list of their noticed subcategories and for each noticed subcategory the requests within that subcategory
Ex:
Company x is monitoring the subcategories 4 and 7.
Show him what requests we've got within those subcats.
This is how I do it for only one company. But I can't solve the grouping and joins when I need a list of multiple companies.
Company company = db.Companies.Where(x=>x.UserId == 10).FirstOrDefault();
var requestByNotices =
from notice in company.Notices
join request in db.Requests.Where(z => z.IsApproved &
z.Status.Status == "Active") on notice.SubcategoryId equals
request.Subcategoryid
UPDATE
Let me rephrase my questions.
This query is producing a table with the results I am looking for:
SELECT Companies.CompanyId, Companies.Name, Account.Email, Notices.SubcategoryId, Requests.FriendlyName FROM Companies
INNER JOIN Notices ON Companies.CompanyId = Notices.CompanyId
INNER JOIN Account ON Account.UserId = Companies.Uid
INNER JOIN Requests ON Notices.SubcategoryId = Requests.Subcategoryid
WHERE Requests.StartDate > '2013-12-22';
But instead of generating a flat list I would like to translate this into to linq but also group by CompanyId. So each company is represented by one row only and within that company I can get the requests.
So instead of a list like this:
CompanyId Name Email SubcategoryId FriendlyName
1 Test test@test.com 2 x
1 Test test@test.com 4 y
I would like to have it like this:
CompanyId Name Email GroupOfRequests
1 Test test@test.com contains two
Thankful for any help!
A: UPDATED: if i understand right you want something like this
var result =
from company in db.Companies
from notice in company.Notices
join request in db.Requests.Where(z => z.IsApproved &&
z.Status.Status == "Active") on notice.SubcategoryId equals request.Subcategoryid
group new {notice, request } by company into gr
select new {gr.Key, Value = gr.ToList() }
UPDATE2
for your sql it seems like this
from company in db.Companies
join notice in db.Notices on company.CompanyId equals notice.CompanyId
join account in db.Account on company.Uid equals account.UserId
join request in db.Requests on notice.SubcategoryId equals request.SubcategoryId
group new {notice, request} by new {company, account} into g
select new {g.Key, value = g}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/20722083",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Do WebAudio scriptProcessorNodes *require* an output to be connected? Here is a link to a simple jsFiddle which measures the loudness of a live input using web-audio (it outputs the values as a percentage to the console).
http://jsfiddle.net/XSnsF/
I was planning to have one input and no outputs, since there's no need to delay my audio signal waiting for my custom node to finish working out the volume.
However, it soom became apparent that the scriptProcessor only logs the values if it's connected to context.destination. Am I doing something wrong? Or is this a bug? Or is this the expected behaviour?
function gotStream(stream) {
var mediaStreamSource = context.createMediaStreamSource(stream);
var gainNode = context.createGain();
gainNode.gain.value = 3;
var levelChecker = context.createScriptProcessor(2048);
mediaStreamSource.connect(gainNode);
gainNode.connect(levelChecker);
//Commenting out the line directly below stops the script processor from working!
levelChecker.connect(context.destination);
levelChecker.onaudioprocess = process;
}
function process(e) {
var buffer = e.inputBuffer.getChannelData(0);
var maxVal = 0;
for (var i = 0; i < buffer.length; i++) {
if (maxVal < buffer[i]) {
maxVal = buffer[i];
}
}
console.log(Math.round(maxVal * 100) + "%");
}
A: It's a bug in the Blink & Webkit implementations. From the spec: "audioprocess events are only dispatched if the ScriptProcessorNode has at least one input or one output connected." It doesn't need both.
For now, just connect it to a zero-gain GainNode connected to the audiocontext.destination.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/19482155",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Bootstrap 3 2 Column Full Height Fixed Header and Footer I'm having issues trying to make a 3 column full height layout work, but with a fixed nav, and fixed footer.
I can get the basics to work, 2 columns, with fixed nav and footer, but when I attempt to enable full height on the columns it tends to break completely.
On some attempts to resolve this the content disappears under the footer, and spills out below it. Other times when you resize the browser to test responsive elements, the footer sticks to the content pain when scrolling up the content, and not the bottom of the browser.
Is there any way to achieve this on a responsive framework? Or is it easier just to re-jig the design, or even fake full height, say by using a positioned repeating background. But then again that wouldn't be responsive either.
I've spent over 2-3 hours on this, so I'm throwing myself on the mercy of someone with better front end skills than I. Help!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/23281197",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Problems running FFprobe with Ruby I am fairly new to Ruby and programming, less than a year experience. This is ruby 1.9.3 and the newest ffmpeg for Ubuntu from FFmpeg. Files I am using are basic .avi, some v210 .mov, other quicktime/finalcutpro types of files.
I am trying to write an automated probing tool that will help lessen the manual work load for me when I start testing with and dealing with lots of media files. Basically the script goes through a directory and probes each file, extracting the info I need, and writes it out to csv.
Currently, everytime I run it, the actual capture on command line is failing.
def prober(file)
@the_file = file
stdout,stderr,status = Open3.capture3("ffprobe -v quiet -print_format json - show_format -show_streams #{@the_file}")
STDERR.puts stderr
if status.success?
out = stdout
else
STDERR.puts "There was a problem, please try again."
end
@raw_output = JSON.parse(out)
end
I don't know if it is something to do with how I am running the command (I don't really fully understand I/O streams), or something with ffprobe. When it does make it past the probe it is returning @raw_output as nil, which causes JSON parsing to puke, or my other methods for splitting and parsing the metadata fail on nil.
Any help at all would great, I have been stuck on this for a while. Thanks! I can provide more code if needed for clarification,.
A: After the holidays I came back fresh and found the problem. The filepath string needs to have quotes around it when fed to the stdin for ffprobe, but when I aggregated the files it stripped the quotes. The fix? add quotes around the filepath in the string.
I hope this helps someone, apparently I am the only person in the whole internet to have this problem.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/13939107",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to avoid a reflow when changing box-shadow or text-shadow properties? This is my test css:
.btn {
display: block;
height: 30px;
width: 30px;
background-color: red;
position: relative;
}
.btn:hover {
box-shadow: 0 0 0 1px black;
text-shadow: 0 0 1px black;
}
Applied to a simple div with the "btn" class. Using Firefox's 28 Web Developer Console I discovered that 1 reflow is executed every time the mouse goes hover the div, and another reflow is executed when the mouse is no more hover the div.
If I change the "position" property from "relative" to "absolute" nothing changes, neither if I deactivate the "text-shadow" or the "box-shadow" property. The only way that I've found that doesn't trigger the two reflows is by disablig both the "box-shadow" and the "text-shadow" properties.
Why is this happening and how I can avoid the execution of the two reflows?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/23327725",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Download file from tag library in jsp file I created a tag library to display a table same as 'display tag' with some other features. Now I would like to add download option to the tag library. I tried it with just changing the content type and resetting the response but that was not possible as the contents before in the response are already flushed.
I found the 'display tag' uses a filter namely 'ResponseOverrideFilter' to prevent contents to be sent so that the resetting response would work. But I did not find any line of code in my 'web.xml' about the filter registration and url-mapping as I used the 'display tag'. Please help me. Thanking you in-advance...
taglibrary :
<disp:dipxTable id="outer" style="width:60%; margin-left:20%" list="<%=dtoList %>" >
<disp:dipxColumn sortable="true" href="javascript:showReport('${pageUrl }', '${row.monthName }', '${row.year}')" group="1" style="text-align:center;" property="monthName" title="Month"/>
<disp:dipxColumn group="2" style="text-align:center;" sortable="true" property="distanceRange" title="Distance"/>
<disp:dipxColumn style="text-align:center;" sortable="true" property="vehicleType" title="Cab"/>
<disp:dipxColumn style="text-align:center;" sortable="true" property="totalTrips" expandable="true" title="#.Trips"/>
<disp:dipxColumn style="text-align:center;" sortable="true" property="rate" title="Trip Cost" />
<disp:dipxColumn style="text-align:center;" sortable="true" format="{0,number,0.00}" property="escortRate" title="Escort Cost" />
<div>
<disp:dipxTable id="inner" type="inner" property="trips" parentProperty="totalTrips" >
<disp:dipxColumn property="trip_code" title="Trip Code" />
<disp:dipxColumn property="tripDate" title="Trip Date" />
<disp:dipxColumn property="trip_time" title="Time" />
<disp:dipxColumn property="trip_log" title="Shift" />
<disp:dipxColumn property="tripRate" title="Trip Rate" />
<disp:dipxColumn property="escortRate" title="Escort Cost" />
</disp:dipxTable>
</div>
<disp:DispxGroupSummaryRow groupProperty="monthName" id="grp">
<td></td>
<td></td>
<td></td>
<disp:dipxColumn style="text-align:center; font-weight:bold;" property="totalTrips" />
<disp:dipxColumn style="text-align:center; font-weight:bold;" property="rate" />
<disp:dipxColumn style="text-align:center; font-weight:bold;" property="escortRate" format="{0,number,0.00}" />
</disp:DispxGroupSummaryRow>
<disp:DispxSummaryRow style="background-color:#fff;" >
<td colspan="3"><center>Grand Total </center></td>
<disp:dipxColumn style="text-align:center; font-weight:bold;" property="totalTrips" />
<disp:dipxColumn style="text-align:center; font-weight:bold;" property="rate" />
<disp:dipxColumn style="text-align:center; font-weight:bold;" property="escortRate" format="{0,number,0.00}" />
</disp:DispxSummaryRow>
</disp:dipxTable>
tld file content of tag dispxTable
<tag>
<description>This tag is parent tag to display table </description>
<name>dipxTable</name>
<tag-class>com.nfl.table.DispxTable</tag-class>
<body-content>scriptless</body-content>
<attribute>
<name>list</name>
<required>false</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<name>type</name>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<name>property</name>
<required>false</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<name>parentProperty</name>
<required>false</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<name>id</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<name>name</name>
<required>false</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<name>style</name>
<required>false</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<name>styleClass</name>
<required>false</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<name>headerRowStyleClass</name>
<required>false</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<name>headerRowStyle</name>
<required>false</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<name>rowStyleClass</name>
<required>false</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<name>rowStyle</name>
<required>false</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<name>expanded</name>
<required>false</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
Tag support Class
enter code here
package com.nfl.table;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.SimpleTagSupport;
import com.nfl.dto.SorterFood;
import com.nfl.dto.support.NflJSONObject;
import com.nfl.dto.support.Sorter;
import com.nfl.dto.support.exception.NflJSONException;
import com.nfl.table.container.ColumnContainer;
public class DispxTable extends SimpleTagSupport implements ColumnContainer {
/* type of table , inner or outer */
private String type;
/* property name of object to be displayed */
private String property;
/* property name of parent table where this table is drawn as child table of the given property */
private String parentProperty;
/* class attribute of table */
private String styleClass;
/* style attribute of table */
private String style;
/* style attribute of th within thead */
private String headerRowStyle;
/* style attribute of tr within thead */
private String headerRowStyleClass;
/* style attribute of tr within tbody */
private String rowStyle;
/* class attribute of tr within tbody */
private String rowStyleClass;
/* this is a property of inner table to render as expanded by default */
private boolean expanded;
/* id attribute of table */
private String id;
private int colomns;
private boolean groupPropegation;
public String getHeaderRowStyle() {
return headerRowStyle;
}
public void setHeaderRowStyle(String headerRowStyle) {
this.headerRowStyle = headerRowStyle;
}
public String getHeaderRowStyleClass() {
return headerRowStyleClass;
}
public void setHeaderRowStyleClass(String headerRowStyleClass) {
this.headerRowStyleClass = headerRowStyleClass;
}
public String getRowStyle() {
return rowStyle;
}
public void setRowStyle(String rowStyle) {
this.rowStyle = rowStyle;
}
public String getRowStyleClass() {
return rowStyleClass;
}
public void setRowStyleClass(String rowStyleClass) {
this.rowStyleClass = rowStyleClass;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
private Object row;
/* each dto is kept as NflJSONObject as a generic */
private NflJSONObject summaryItem;
/* keeps summary attributes */
private Map<String, NflJSONObject> groupSummaryMap = new HashMap<String, NflJSONObject>();
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getProperty() {
return property;
}
public void setProperty(String property) {
this.property = property;
}
private int level;
private Object innerList;
private Object list;
private NflJSONObject item;
private NflJSONObject preItem;
private NflJSONObject nextItem;
public NflJSONObject getPreItem() {
return preItem;
}
public void setPreItem(NflJSONObject preItem) {
this.preItem = preItem;
}
private String name="sddfd";
private boolean isHeader;
private int rowCount;
private HashMap<Integer, SorterFood> groupMap= new HashMap<Integer, SorterFood>();
private HashMap<Integer, SorterFood> sortMap= new HashMap<Integer, SorterFood>();
private HashMap<Integer, SorterFood> putAll(HashMap<Integer, SorterFood> pgMap,HashMap<Integer, SorterFood> psMap) {
HashMap<Integer, SorterFood> allMap=new HashMap<Integer, SorterFood>();
Set<Integer> keys=null;
int i=0;
if(pgMap!=null&&pgMap.size()>0) {
keys= pgMap.keySet();
for(int key:keys) {
allMap.put(key, pgMap.get(key));
//System.out.println("pg keys " + key+" i:"+i);
//System.out.println("putting ("+key+", "+" "+psMap.get(key)+")");
if(key>i) {
i=key;
}
}
}
if(psMap!=null&&psMap.size()>0) {
keys= psMap.keySet();
for(int key:keys) {
Set <Integer> gkeys=pgMap.keySet();
boolean contains=false;
for(int gkey:gkeys) {
SorterFood gSf=pgMap.get(gkey);
SorterFood sSf= psMap.get(key);
if(gSf.getProperty().equals(sSf.getProperty())) {
contains=true;
allMap.put(gkey,sSf);
break;
}
}
if(!contains) {
allMap.put(i+1, psMap.get(key));
}
i++;
}
}
return allMap;
}
public NflJSONObject getItem() {
return item;
}
public void setItem(NflJSONObject item) {
this.item = item;
}
public HashMap<Integer, SorterFood> getGroupMap() {
return groupMap;
}
public void setGroupMap(HashMap<Integer, SorterFood> groupMap) {
this.groupMap = groupMap;
}
public HashMap<Integer, SorterFood> getSortMap() {
return sortMap;
}
public void setSortMap(HashMap<Integer, SorterFood> sortMap) {
this.sortMap = sortMap;
}
public Object getList() {
return list;
}
public void setList(Object list) {
this.list = list;
}
private String returnClass() {
String styleString="";
if(styleClass==null||styleClass.trim().equals("") ) {
styleString="class=\"displaytag\"";
}else {
// System.out.println("=================================class=="+styleClass);
styleString="class=\""+ styleClass+"\"";
}
return styleString;
}
private String returnHeaderClass() {
String styleString="";
if(headerRowStyleClass ==null||headerRowStyleClass.trim().equals("") ) {
styleString="";
}else {
// System.out.println("=================================class=="+styleClass);
styleString="class=\""+ headerRowStyleClass+"\"";
}
return styleString;
}
private String returnHeaderStyle() {
String styleString="";
if(headerRowStyle!=null&&headerRowStyle.trim().equals("")==false ) {
styleString=" style=\""+ headerRowStyle+"\" ";
}
return styleString;
}
private String returnRowClass(int index) {
String styleString="";
String commonClass= ((index%2==0)?"even":"odd") ;
if(rowStyleClass ==null||rowStyleClass.trim().equals("") ) {
styleString= "class=\"" + commonClass+ "\"";
}else {
// System.out.println("=================================class=="+styleClass);
styleString="class=\"" + commonClass + " "+ rowStyleClass+"\"";
}
return styleString;
}
private String returnRowStyle() {
String styleString="";
if(rowStyle!=null&&rowStyle.trim().equals("")==false ) {
styleString=" style=\""+ rowStyle+"\" ";
}
return styleString;
}
private String returnStyle() {
String styleString="";
if(style!=null&&style.trim().equals("")==false ) {
styleString=" style=\""+ style+"\" ";
}
return styleString;
}
@Override
public void doTag() throws JspException, IOException {
// TODO Auto-generated method stub
PageContext ctx = (PageContext)getJspContext();
HttpServletRequest request = (HttpServletRequest) ctx.getRequest();
HttpServletResponse response = (HttpServletResponse) ctx.getResponse();
String download=request.getParameter("download");
if(download!=null&&download.equals("xls")) {
String mimeType = "application/vnd.ms-excel";
//response.flushBuffer();
// response.reset();
// ctx.getOut().clearBuffer();
// response.flushBuffer();
/* for(String s:response.getHeaderNames()) {
// System.out.println("Header "+s + " value "+response.getHeader(s));
}*/
response.setContentType(mimeType);
String fname = new Date().toString();
response.setHeader("Content-Disposition", "inline; filename = APL" + fname + ".xls");
response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
response.setHeader("Cache-Control", "post-check=0, pre-check=0");
response.setHeader("Pragma", "no-cache");
response.setHeader("Pragma", "public");
response.setHeader("Expires", "Mon, 1 Jan 1995 05:00:00 GMT");
Boolean b = (Boolean) ctx.getAttribute("pageStarted");
/* if(b==null||b==false) {
ctx.getOut().write("<html><head></head><body><form>");
ctx.setAttribute("pageStarted", true);
}*/
}
JspWriter out = getJspContext().getOut();
List list = (List) getList();
preItem=null;
if(type!=null&&type.equals("inner"))
{
/*
* inner table starts
*/
DispxTable t= (DispxTable) getParent();
int myRowCount=t.getRowCount();
if(!t.isHeader())
{
if(t!=null)
{
// System.out.println("inner table row ");
//org.json.JSONObject obj= new org.json.JSONObject(t.getItem());
NflJSONObject obj;
/*catch (JSONException e) {
// TODO Auto-generated catch block
// e.printStackTrace();
// System.out.println(""+e);
out.write("</tr><tr><td>"+e+"</td></tr><tr>");
}*/
//// System.out.println("Param "+ request.getParameter("expandableProperty"));
String paramRowCount=request.getParameter(t.getId()+"-rowCount");
String exandablePropery=request.getParameter(t.getId()+"-expandableProperty");
parentProperty= parentProperty==null?"":parentProperty;
exandablePropery= exandablePropery==null?"":exandablePropery;
if((parentProperty.equals("")||exandablePropery.equals("")) ==false&& parentProperty.equals(exandablePropery)&&String.valueOf(myRowCount).equals(paramRowCount) || isExpanded())
{
try {
obj= t.getItem();
level=t.getLevel()+1;
// // System.out.println("subjects : "+obj.get(property));
Object object= obj.get(property);
list = (List) object;
if(list!=null&&list.size()>0)
{
setList(list);
out.write(" </tr> ");
out.write("<tr><td colspan='" + t.getColomns() + "' >");
String tableStart=String.format("<a onClick=\"closeMyParent('%s')\" >Close</a><br/><table %s %s %s> <thead> <tr %s %s >",id,returnStyle(), returnClass(),"id=\""+id+"\"", returnHeaderClass(), returnHeaderStyle() );
isHeader=true;
out.write(tableStart);
row=list.get(0);
getJspBody().getJspContext().setAttribute("row", row);
getJspBody().invoke(out);
out.write(" </tr> </thead> <tbody>");
isHeader=false;
Map<Integer,SorterFood> allMap= putAll(getGroupMap(), getSortMap());
//System.out.println("Sort map size :"+ sortMap.size());
//System.out.println("All map size :"+ allMap.size());
if(allMap!=null&&allMap.size()>0) {
list=Sorter.sort(list, allMap);
}
rowCount=0;
for(Object o:list){
setGroupPropagation(true);
setColomns(0);
row=o;
item=new NflJSONObject( row);
if(list.indexOf(o)<(list.size()-1)) {
nextItem = new NflJSONObject( list.get(list.indexOf(o)+1));
} else {
nextItem = new NflJSONObject();
}
getJspBody().getJspContext().setAttribute("row", row);
getJspBody().getJspContext().setAttribute("rowCount",list.indexOf(row));
out.write(String.format(" <tr %s %s > ", returnRowClass(list.indexOf(row)), returnRowStyle()) );
getJspBody().invoke(null);
preItem=item;
out.write("</tr>");
rowCount++;
}
out.write(" </tbody> </table></div>");
out.write(" </td></tr> ");
out.write("<tr style='display:none;'> <td colspan='" + t.getColomns() + "'> </td> ");
}
} catch ( NflJSONException e) {
// TODO Auto-generated catch block
throw new IOException(""+e);
}
}
}
}
/*
* inner table ends
*/
} else if(list!=null&&list.size()>0)
{
String tableStart=String.format("<table %s %s %s > <thead> <tr %s %s >",returnStyle(), returnClass(),"id=\""+id+"\" ", returnHeaderClass(), returnHeaderStyle() );
isHeader=true;
out.write(tableStart);
row=list.get(0);
getJspBody().getJspContext().setAttribute("row", row);
getJspBody().invoke(null);
out.write("</tr> </thead> <tbody>");
isHeader=false;
Map<Integer,SorterFood> allMap= putAll(getGroupMap(), getSortMap());
//System.out.println("Group map size >"+ getGroupMap().size());
//System.out.println("Sort map size >"+ getSortMap().size());
//System.out.println("All map size >"+ allMap.size());
if(allMap!=null&&allMap.size()>0) {
list=Sorter.sort(list, allMap);
}
rowCount=0;
for(Object o:list){
setGroupPropagation(true);
setColomns(0);
row=o;
// System.out.println("outer table row open");
try {
item=new NflJSONObject( o);
if(list.indexOf(o)<(list.size()-1)) {
nextItem = new NflJSONObject( list.get(list.indexOf(o)+1));
} else {
nextItem = new NflJSONObject();
}
} catch (NflJSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//ctx.setAttribute("row", item);
getJspBody().getJspContext().setAttribute("row", row);
getJspBody().getJspContext().setAttribute("rowCount",list.indexOf(row));
out.write(String.format(" <tr %s %s > ", returnRowClass(list.indexOf(row)), returnRowStyle() ) );
getJspBody().invoke(out);
preItem=item;
out.write(" </tr> ");
// System.out.println("outer table row close");
rowCount++;
}
out.write("</tbody> </table>");
}else
{
out.write("<div> No display </div>");
}
/* if(download!=null&&download.equals("xls")) {
Boolean b = (Boolean) ctx.getAttribute("pageStarted");
if(b!=null&&b==true) {
out.write("</form></body></html>" );
ctx.setAttribute("pageStarted", true);
}
}
*/
}
public boolean isHeader() {
return isHeader;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Object getInnerList() {
return innerList;
}
public String getParentProperty() {
return parentProperty;
}
public void setParentProperty(String parentProperty) {
this.parentProperty = parentProperty;
}
public int getRowCount() {
return rowCount;
}
public void setRowCount(int rowCount) {
this.rowCount=rowCount;
}
public int getColomns() {
return colomns;
}
public void setColomns(int colomns) {
this.colomns = colomns;
}
public String getStyleClass() {
return styleClass;
}
public void setStyleClass(String styleClass) {
this.styleClass = styleClass;
}
public NflJSONObject getSummaryItem() {
return summaryItem;
}
public void setSummaryItem(NflJSONObject summaryItem) {
this.summaryItem = summaryItem;
}
public Object getRow() {
return row;
}
public void setRow(Object row) {
this.row = row;
}
public int getLevel() {
return level;
}
public String getStyle() {
return style;
}
public void setStyle(String style) {
this.style = style;
}
@Override
public void setGroupPropagation(boolean flag) {
// TODO Auto-generated method stub
groupPropegation = flag;
}
@Override
public boolean hasGroupPropagation() {
// TODO Auto-generated method stub
return groupPropegation;
}
public NflJSONObject getNextItem() {
return nextItem;
}
public void setNextItem(NflJSONObject nextItem) {
this.nextItem = nextItem;
}
public Map<String, NflJSONObject> getGroupSummaryMap() {
return groupSummaryMap;
}
public boolean isExpanded() {
return expanded;
}
public void setExpanded(boolean expanded) {
this.expanded = expanded;
}
}
I dont think you need all this details to answer on how to just register a filter which is defined in taglibary.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/22625347",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Gitlab - path to git command I have took over sel-hosted gitlab from former co-worker. I have a qustion about git version/location which gitlab use because I wanted to do upgrade which require git 2.31.x and later. Server is CentOS 7.9. I have found several different versions in the system. How do I find which one is used by gitlab?
By "yum list installed":
git.x86_64 1.8.3.1-23.el7_8 @updates
"git --version"
git version 2.8.0
Gitlab web intefrace -> Admin area -> Overview -> Gitaly Servers
git version 2.29.0
"whereis git":
git: /usr/bin/git /usr/local/git /usr/local/git/bin/git /usr/share/man/man1/git.1.gz /usr/src/git-2.8.0/git.c /usr/src/git-2.8.0/git.rc /usr/src/git-2.8.0/git.spec /usr/src/git-2.8.0/git.o /usr/src/git-2.8.0/git
Thank you
EDIT:
su git
which git
=> /usr/local/git/bin/git
/usr/local/git/bin/git --version
=> git version 2.8.0
gitlab.yml:
git: /opt/gitlab/embedded/bin/git
/opt/gitlab/embedded/bin/git --version
=> git version 2.29.0
So I can yum remove git and rm -rf /usr/local/git/ because gitlab use /opt/gitlab/embedded/bin/git?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/70080191",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: What does SomeMethod(() => x.Something) mean in C# (Note the code is an example)
I have the following syntax:
SomeMethod(() => x.Something)
What do the first brackets mean in the expression?
I'm also curious how you can get the property name from argument that is being passed in. Is this posssible?
A:
What do the first brackets mean in the expression?
It's the lambda syntax for a method that takes no parameters. If it took 1 parameter, it'd be:
SomeMethod(x => x.Something);
If it took n + 1 arguments, then it'd be:
SomeMethod((x, y, ...) => x.Something);
I'm also curious how you can get the property name from argument that is being passed in. Is this possible?
If your SomeMethod takes an Expression<Func<T>>, then yes:
void SomeMethod<T>(Expression<Func<T>> e) {
MemberExpression op = (MemberExpression)e.Body;
Console.WriteLine(op.Member.Name);
}
A: The () is an empty argument list. You're defining an anonymous function that takes no arguments and returns x.Something.
Edit: It differs from x => x.Something in that the latter requires an argument and Something is called on that argument. With the former version x has to exist somewhere outside the function and Something is called on that outside x. With the latter version there does not have to be an outside x and even if there is, Something is still called on the argument to the function and nothing else.
A: It's a lambda expression. That is, it's a way to create an anonymous function or delegate.
The general form is:
(input parameters) => expression
If you have
() => expression
then you have created a function that takes no arguments, and returns the result of the expression.
C# uses type inference to figure out what the types of the values are, and it captures local variables (like your "x" variable) by means of a lexical closure.
A: I assume x is declared in somewhere inside your method, if yes, you can compare this lambda expression with a delegate that has no paramaters and return the type of x.someproperty
delegate{
return x.someproperty;
}
that is the same as:
() => x.someproperty
A: the () mean that this method doesn't take any parameters.
for example, if you assign a normal event handler using a lambda expression, it would look like this:
someButton.Click += (s, e) => DoSomething();
A: See also the following two blog posts that discuss exactly your second question and provide alternative approaches:
How to Find Out Variable or Parameter Name in C#?
How to Get Parameter Name and Argument Value From C# Lambda via IL? (Or "How NOT to Use .NET Linq Expressions in Order to Get Parameter Name and Argument Value From C# Lambda?")
A: To get the name of the property you need SomeMethod to have an argument of the type of System.Linq.Expressions.Expression<System.Func<object>>. You can then go through the expression to determine the property name.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/1370236",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: Input definition optional keys I generated an action with sails generate action task/update-task. I now am trying to create an input parameter that should be an object with optional keys:
inputs: {
fields: {
type: {
body: 'string?',
rruleSetStr: 'string?',
},
required: true,
description: 'All keys are not required, but at least one is'
},
However I keep getting error:
The action `task/update-task` could not be registered. It looks like a machine definition (actions2), but it could not be used to build an action.
Details: ImplementationError: Sorry, could not interpret "task/update-task.js" because its underlying implementation has a problem:
------------------------------------------------------
• Invalid input definition ("fields"). Unrecognized `type`. (Must be 'string', 'number', 'boolean', 'json' or 'ref'. Or set it to a type schema like `[{id:'number', name: {givenName: 'Lisa'}}]`.)
------------------------------------------------------
If you are the maintainer of "task/update-task.js", then you can change its implementation to solve the problem above. Otherwise, please file a bug report with the maintainer, or fork your own copy and fix that.
[?] See https://sailsjs.com/support for help.
at machineAsAction (C:\Users\Mercurius\Documents\GitHub\Homie-Web\node_modules\machine-as-action\lib\machine-as-action.js:271:28)
at helpRegisterAction (C:\Users\Mercurius\Documents\GitHub\Homie-Web\node_modules\sails\lib\app\private\controller\help-register-action.js:63:27)
at C:\Users\Mercurius\Documents\GitHub\Homie-Web\node_modules\sails\lib\app\private\controller\load-action-modules.js:146:13
Does anyone know where the documentation is on how to make optional keys in this? I tried here - http://node-machine.org/spec/machine#inputs - but no luck.
A: Type must be 'string', 'number', 'boolean', 'json' or 'ref' like error say.
So u need set type to 'ref' (object or array), and u can use custom function for validate.
inputs: {
fields: {
type: 'ref',
custom: function (data) {
// some logic
// example
if (typeof data.body !== "string") {
return false;
// or u can use trow Error('Body is not a string')
}
return true;
},
required: true,
description: 'All keys are not required, but at least one is'
}
Now input is type object and in custom function return false or trow Error('Some problem') break validation.
If u use schema type, just remove ? from your example:
inputs: {
fields: {
type: {
body: 'string',
rruleSetStr: 'string'
},
required: true,
description: 'All keys are not required, but at least one is'
}
This is Runtime (recursive) type-checking for JavaScript., please check documentation for writing rules.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/55113532",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: iteration with the list monad I'm having trouble understanding how the iterative behavior of the list monad can be derived from its definition.
instance Monad [] where
m >>= f = concatMap f m
return x = [x]
fail s = []
Discussions I've read seem to pass over the question of how >>= creates a control structure, as shown most clearly with do notation:
allEvenOdds :: Int -> [(Int,Int)]
allEvenOdds n = do
evenValue <- [2,4 .. n]
oddValue <- [1,3 .. n]
return (evenValue,oddValue)
Is this built in to Haskell, the way I assume the IO monad's interface to actual i/o is?
A: There's nothing built-in, everything is a simple consequence of the Monad instance you quoted (and, since this example uses do notation, how that desugars to uses of the >>= operator):
allEvenOdds n = do
evenValue <- [2,4 .. n]
oddValue <- [1,3 .. n]
return (evenValue,oddValue)
-- desugaring the do notation
allEvenOdds n =
[2,4 .. n] >>= \evenValue ->
[1,3 .. n] >>= \oddValue ->
return (evenValue, oddValue)
-- using the list instance of Monad to replace >>= and return
allEvenOdds n =
concatMap (\evenValue ->
concatMap (\oddValue -> [(evenvalue, oddValue)]) [1,3 .. n]
) [2,4 .. n]
which you can hopefully easily see "iterates over" both lists and results in a list of all pairs of (even, odd) with values taken from both lists.
At a high level, we can say that the list monad results in iteration simply because concatMap, like map, executes the given function for each element of the list, so it implicitly iterates over the list.
A: The list instance of the Monad typeclass models nondeterminism: you can see each var <- someList as a for loop like in Python.
The do notation is desugared to [2,4 .. n] >>= (\evenValue -> [1, 3 .. n] >>= (\oddValue -> return (evenValue, oddValue))), so this is equivalent to something in Python like:
result = []
for evenValue in range(2, n, 2):
for oddValue in range(1, n, 2):
result.append((evenValue, oddValue))
or with list comprehension:
result = [
(evenValue, oddValue)
for evenValue in range(2, n, 2)
for oddValue in range(1, n, 2)
]
This works since for instance Monad [], the expression [2,4 .. n] >>= (\evenValue -> [1, 3 .. n] >>= (\oddValue -> return (evenValue, oddValue))) is thus equivalent to:
concatMap (\evenValue -> [1, 3 .. n] >>= (\oddValue -> return (evenValue, oddValue))) [2,4 .. n]
and thus:
concatMap (\evenValue -> concatMap (\oddValue -> [(evenValue, oddValue)]) [1, 3 .. n]) [2,4 .. n]
But do notation is not "hardwired" to IO: IO is just an instance of Monad that is implemented in such way that one IO action will run before the second one. For lists, it thus is implemented in an equivalent way as spanning Python for loops.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/71540156",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Need help converting a expression in python to C# Maybe someone in either of the camps can tell me whats going on here:
Python:
temp = int('%d%d' % (temp2, temp3)) / 10.0;
I'm working on parsing temperature data, and found a piece of python that I can't understand. What is going on here? Is python adding together two numbers here and casting them to int, and then divide by 10?
C# might look like:
temp = ((int)(temp2+temp3))/10;
But I am not sure what that % does? Data is jibberish so I don't know what is correct translation for that line in python to C#
A: In C# it looks like:
var temp = int.Parse(temp2.ToString() + temp3.ToString())/10f;
or:
var temp = Convert.ToInt32(string.Format("{0}{1}", temp2, temp3))/10f;
A: this is similar: What's the difference between %s and %d in Python string formatting?
name = 'marcog'
number = 42
print '%s %d' % (name, number)
will print marcog 42. Note that name is a string (%s) and number is an integer (%d for decimal).
See
http://docs.python.org/library/stdtypes.html#string-formatting-operations
for details.
So it seems like the "%" is just telling python to put the values on the right into the placeholders on the left.
from the documentation linked in the answer I quoted:
Given format % values (where format is a string or Unicode object), % conversion specifications in format are replaced with zero or more elements of values. The effect is similar to the using sprintf() in the C language. If format is a Unicode object, or if any of the objects being converted using the %s conversion are Unicode objects, the result will also be a Unicode object.
Would probably want to set up a python script and try it out, placing your own values into the variables.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/24551020",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How can I create only one button to perform multiple tasks? I have created one button named as battery-saver in the android, now i want that when i click on the battery saver button then the "WIFI" and "BLUETOOTH" should be turned off. So, can anybody help me for the code of this that when I click on the button then i can turn off the "WIFI" and "BLUETOOTH" both ?
A: *
*Add permission
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"></uses-permission>
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
*Try this
btnLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(false);
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
bluetoothAdapter.disable();
}
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/49497066",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: Understanding std::move and unique_ptr I am new to c++11 and trying to understand to meaning of std::move and unique_ptr and wrote the following code, which I use std::move on a unique_ptr in two different ways:
void unique_ptr_plain_move() {
unique_ptr<int> intptr(new int(10));
unique_ptr<int> intptr2;
printf("*intptr = %d\n", *intptr);
intptr2 = std::move(intptr);
printf("*intptr2 = %d\n", *intptr2);
// as expected, crash here as we have already moved intptr's ownership.
printf("*intptr = %d\n", *intptr);
}
/////////////////////////////////////////////
void function_call_move(unique_ptr<int>&& intptr) {
printf("[func] *intptr = %d\n", *intptr);
}
void unique_ptr_function_call_move() {
unique_ptr<int> intptr(new int(10));
printf("*intptr = %d\n", *intptr);
function_call_move(std::move(intptr));
// this does not crash, intptr still has the ownership of its pointed instance ....
printf("*intptr = %d\n", *intptr);
}
In unique_ptr_plain_move(), intptr2 takes the ownership of intptr after std::move and therefore we can no longer use intptr. However, in unique_ptr_function_call_move(), when using std::move in a function call, intptr still have its ownership of its pointed instance. Can I know what exactly happened when we pass a std::move(unique_ptr) to a function? Thank you.
A: The key concept here is that std::move by itself won't do any moving.
You can think of it as marking the object as a object that can be moved from.
The signature for function_call_move is
void function_call_move( unique_ptr<int>&& ptr );
Which means it can only receive objects that could be moved from, formally known as rvalues, and bind that to a reference. The act of associating an rvalue to a rvalue reference don't invalidate the state of the original object either.
So, unless function_call_move actually moves ptr to another std::unique_ptrinside it, your call to function_call_move(std::move(intptr)); won't invalidate intptr and your usage will be perfectly fine.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/21537935",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Springboot jersey with multiple source paths (servlets) I am starting to use Springboot in my application. My web.xml looks like this
<servlet>
<servlet-name>Internal Tools</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>in.playment.internal.api;in.playment.auditor.api</param-value>
</init-param>
<init-param>
<param-name>jersey.config.server.provider.classnames</param-name>
<param-value>org.glassfish.jersey.filter.LoggingFilter;org.glassfish.jersey.media.multipart.MultiPartFeature;in.playment.gateway.RequestFilter;in.playment.gateway.ResponseFilter;in.playment.gateway.DebugExceptionMapper;in.playment.gateway.security.Binder</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Internal Tools</servlet-name>
<url-pattern>/v0/internal/*</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>External Apis</servlet-name>
<servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>in.playment.rutherford.api;in.playment.payment.api;in.playment.payment.resource</param-value>
</init-param>
<init-param>
<param-name>jersey.config.server.provider.classnames</param-name>
<param-value>org.glassfish.jersey.filter.LoggingFilter;org.glassfish.jersey.media.multipart.MultiPartFeature;in.playment.gateway.RequestFilter;in.playment.gateway.ResponseFilter;in.playment.gateway.DebugExceptionMapper;in.playment.gateway.security.Binder;in.playment.payment.exception.PaymentExceptionMapper</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>External Apis</servlet-name>
<url-pattern>/api/*</url-pattern>
</servlet-mapping>
I want to use two different base paths for urls. I have different packages and different exception mappers. How can I achieve this in Springboot embedded tomcat. So far, I am able to achieve only one of these. If I try to do two registries, it throws me Exception saying org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'org.glassfish.jersey.server.ResourceConfig' available: expected single matching bean but found 2: jerseyConfig,getResourceConfig
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/41312473",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: SVG Rect Ignores Height? Here is a working demo of a rectangle. I'd like to move the height property to css and well, it doesn't work and gives me a blank. It happens in firefox and chrome.
Is there a different name for it? I don't understand why I can't use a css file. The fill color works.
Working example.
css:
rect {
fill:rgb(0, 0, 255);
/*doesnt work height:100;*/
}
html:
<svg xmlns="http://www.w3.org/2000/svg" version="1.1">
<rect width="100" height="100" style="stroke-width:1;stroke:rgb(0,0,0)"/>
</svg>
A: The width of a <rect> element isn't a CSS property in SVG, it's only usable as an attribute. It's for example like the size of a <select> element in HTML. You can only set it as an attribute.
A: SVG doesn't have a straightforward support for CSS for setting shape dimensions.
However there's a workaround for rects, which can also be used to generate horizontal and vertical lines:
*
*Set width and height to 1, and use CSS transform: scale(width, height)
*Don't specify x,y location, and use transform: translate(x, y)
E.g.
.svg {
width: 100px;
height: 30px;
}
.rectangle {
transform: scale(30, 10);
fill: orange;
}
.horiz-line {
transform: translate(15px,5px) scale(50, 1);
fill: red;
}
.vert-line {
transform: translate(10px, 5px) scale(1, 30);
fill: blue;
}
<svg>
<rect class="rectangle" width="1" height="1" />
<rect class="horiz-line" width="1" height="1" />
<rect class="vert-line" width="1" height="1" />
</svg>
A: In SVG the x, y, width and height of <rect> elements are attributes rather than CSS properties. Only CSS properties can be styled using CSS.
A: workaround for symmetric rectangles:
rect:hover {
stroke-width: 20 !important;
}
<svg width="100" height="100">
<rect
stroke-width="0"
fill="blue" stroke="blue"
x="30" y="30" width="40" height="40"
/>
</svg>
(darkreader will use different colors for stroke and fill)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/14383014",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: Can I develop Windows 8 Apps without installing 2012 Express for Windows 8?
Microsoft provides two free tools, designed to work together, that help you develop, test, and deploy Windows Store apps: Microsoft Visual Studio Express 2012 for Windows 8 and Blend for Visual Studio. (These tools require Windows 8.)
I already have too many IDE's on my box. One of them is Visual Studio 2012 Pro. If I want to develop Windows 8 Apps, expecially the HTML5 variety, do I really need to install that huge SDK along with Visual Studio Express 2012 for Windows 8?? Or can I just install some templates and add some nuget packages?
A: you can install the Windows 8 SDK http://msdn.microsoft.com/en-us/windows/desktop/hh852363.aspx
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/14588066",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Construct json with multiple identical keys in Qt5 I want to generate a json that looks like this:
{
"myRepeatedKey": "test_data_1",
"myRepeatedKey": "test_data_2",
"myRepeatedKey": "test_data_3",
"myRepeatedKey": "test_data_4"
}
using Qt5. My naive approach looks like this:
QVariantMap map;
map_fill["myRepeatedKey"]="test_data_1";
map_fill["myRepeatedKey"]="test_data_2";
map_fill["myRepeatedKey"]="test_data_3";
map_fill["myRepeatedKey"]="test_data_4";
QJsonDocument doc=QJsonDocument::fromVariant(map);
qDebug()<<doc.toJson();
Since this replaces data for the entry, this outputs (not surprisingly) this:
}
"myRepeatedKey": "test_data_4"
}
So how could I do this in Qt5?
PS: According to RFC4627 it is recommended but not required for names in name/value pairs in json data to be unique, so even though what I am asking for is not recommended practice, I would still know how to do it.
Thanks!
A: I think adding duplicate keys is a bad idea. You should use json array (QJsonArray) in this case.
QJsonArray array;
array.append("test_data_1");
array.append("test_data_2");
array.append("test_data_3");
array.append("test_data_4");
QJsonObject o;
o["myArray"] = array;
QJsonDocument doc(o);
qDebug() << doc.toJson();
Output will be
{
"myArray": [
"test_data_1",
"test_data_2",
"test_data_3",
"test_data_4"
]
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/28653461",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: .Net Xml Deserialization I have the following XElement
<Issue Type="Duplicate" Distance="1">
<Record>
<ID>6832</ID>
<Name_First>JAMES </Name_First>
<Name_Last>SMITH</Name_Last>
<Company>SMITH CO.</Company>
</Record>
<Record>
<ID>6831</ID>
<Name_First>JAMES</Name_First>
<Name_Last>SMITH</Name_Last>
<Company>SMITH CO.</Company>
</Record>
</Issue>
I'm trying to Deserialize it into this object
public class Issue
{
[XmlAttribute]
public string Type { get; set; }
[XmlArrayItem(typeof(XElement), ElementName = "Record")]
public List<XElement> Record { get; set; }
}
The type works no problem, but I can't get the two Record nodes into the Record list of the object.
Is it possible without overriding ISerializable and writing custom code?
A: Try this:
public class Issue
{
[XmlAttribute]
public string Type { get; set; }
[XmlAnyElement("Record")]
public List<XElement> Record { get; set; }
}
I think that tells the serializer that multiple Record elements will go in the list.
A: Implement Record class which has ID, Name_First, Name_Last and Company fields
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/3866107",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Get Model name in a partial view Is there any way to get the name of current model in a partial view?
I want to do something like:
@if(Model.Name=="Something"){
....
}
else{
...
}
A: you can use try something like
@model.GetType().Name
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/40828259",
"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.