text
stringlengths 15
59.8k
| meta
dict |
---|---|
Q: What is the path of the cache directory on Android and iOS? I need to insert the path of the cache directory, that the image will be saved on android and iOS, by the library, but I don't know which path this is. Can someone please tell me which way it is?
export const openImage = (setFunc, w, h) => {
ImagePicker.openPicker({
cropping: true,
path: "INSERT PATH HERE",
mediaType: 'photo',
width: p42(w) * 2.5,
height: p42(h) * 2.5,
})
.then(response => {
// alert(JSON.stringify(response));
setFunc(response.path);
})
.catch(error => console.log('>>>>', error))
.finally(() => ImagePicker.clean());
};
A: You can use react-native-fs for that.
CachesDirectoryPath (String) The absolute path to the caches directory
ExternalCachesDirectoryPath (String) The absolute path to the external caches directory (android only)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60866745",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Javascript Promise.all() inside of a loop I am trying to make a web API call twice inside of a loop, then wait until the webAPI has returned before pushing the returned values as a subarray within a larger array. Here's my code:
var latlngPairs = [];
function extractLatLongPairs(jsonobj){
for(var i = 0; i<10; i++){
let promises = [googlePlace(jsonobj[i]['From LID']), googlePlace(jsonobj[i]['To LID'])];
Promise.all(promises).then((results) => {
var temp2 = [results[0], results[1]];
latlngPairs.push(temp2);
console.log(latlngPairs);
});
}
}
The googlePlace function being called in promises:
function googlePlace(airport){
https.get('https://maps.googleapis.com/maps/api/place/findplacefromtext/json?input=' + airport + '&inputtype=textquery&fields=geometry', (resp) => {
let data = '';
// A chunk of data has been recieved.
resp.on('data', (chunk) => {
data += chunk;
});
//All data is returned
resp.on('end', () => {
data = JSON.parse(data);
let obj = {
name: airport,
location: data.candidates[0].geometry.location
};
console.log('latlong should print after this');
return Promise.resolve(obj);
});
}).on("error", (err) => {
console.log("Error: " + err.message);
});
}
I am expecting console.log('latlong should print after this') to print out before latlngPairs is printed. Because the order is vice versa, latlngPairs is filled with subarrays with undefined values. The output is something like:
[
[ undefined, undefined ],
[ undefined, undefined ],
[ undefined, undefined ],
[ undefined, undefined ],
[ undefined, undefined ],
[ undefined, undefined ],
[ undefined, undefined ],
[ undefined, undefined ],
[ undefined, undefined ],
[ undefined, undefined ]
]
latlong should print after this
latlong should print after this
latlong should print after this
latlong should print after this
latlong should print after this
latlong should print after this
latlong should print after this
latlong should print after this
latlong should print after this
latlong should print after this
latlong should print after this
latlong should print after this
latlong should print after this
latlong should print after this
latlong should print after this
latlong should print after this
latlong should print after this
latlong should print after this
latlong should print after this
latlong should print after this
To be clear, the order I'm rying to achieve is 'latlong should print after this' then ' [[obj, obj], [obj, obj]]. I think I must have some fundamental misunderstanding about how promise.all works, and any help would be much appreciated!
A: You need to make your googlePlace function actually return a promise:
function googlePlace(airport) {
// notice the new Promise here
return new Promise((resolve, reject) => {
https
.get(
"https://maps.googleapis.com/maps/api/place/findplacefromtext/json?input=" +
airport +
"&inputtype=textquery&fields=geometry",
(resp) => {
let data = "";
// A chunk of data has been recieved.
resp.on("data", (chunk) => {
data += chunk;
});
//All data is returned
resp.on("end", () => {
data = JSON.parse(data);
let obj = {
name: airport,
location: data.candidates[0].geometry.location,
};
console.log("latlong should print after this");
// notice the resolve here
resolve(obj);
});
}
)
.on("error", (err) => {
console.log("Error: " + err.message);
reject(err.message);
});
});
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/64774397",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Zend Framework 2: setAttribute() on a non-object error occurs when trying to edit I'm new to the PHP Zend Framework 2 and I'm going through one of the online tutorials in learning how to use it. The tutorial involves having you create and edit albums. The problem is when I try to edit an album by clicking on the edit links, I get an error stating:
Call to a member function setAttribute() on a non-object
Controller:
public function editAction()
{
$id = (int) $this->params()->fromRoute('id', 0);
if (!$id) {
return $this->redirect()->toRoute('album', array(
'action' => 'add'
));
}
// Get the Album with the specified id. An exception is thrown
// if it cannot be found, in which case go to the index page.
try {
$album = $this->getAlbumTable()->getAlbum($id);
}
catch (\Exception $ex) {
return $this->redirect()->toRoute('album', array(
'action' => 'index'
));
}
$form = new AlbumForm();
$form->bind($album);
$form->get('submit')->setAttribute('value', 'Edit');
$request = $this->getRequest();
if ($request->isPost()) {
$form->setInputFilter($album->getInputFilter());
$form->setData($request->getPost());
if ($form->isValid()) {
$this->getAlbumTable()->saveAlbum($album);
// Redirect to list of albums
return $this->redirect()->toRoute('album');
}
// EDIT: This bracket below was missing originally
// This is what was causing the 'setAttribute' error when
// Clicking on the edit links for any of my albums
}
return array(
'id' => $id,
'form' => $form,
);
}
View:
<?php
//module/Album/view/album/album/edit.phtml:
$title = 'Edit album';
$this->headTitle($title);
?>
<h1><?php echo $this->escapeHtml($title); ?> </h1>
<?php
$form = $this->form;
$form->setAttribute('action', $this->url(
'album',
array(
'action' => 'edit',
'id' => $this->id,
)
));
$form->prepare();
echo $this->form()->openTag($form);
echo $this->formHidden($form->get('id'));
echo $this->formRow($form->get('title'));
echo $this->formRow($form->get('artist'));
echo $this->formSubmit($form->get('submit'));
echo $this->form()->closeTag();
?>
EDIT: Here is the code from AlbumForm.php
AlbumForm.php:
<?php
namespace Album\Form;
use Zend\Form\Form;
class AlbumForm extends Form
{
public function __construct($name = null)
{
// we want to ignore the name passed
parent::__construct('album');
$this->add(array(
'name' => 'id',
'type' => 'Hidden',
));
$this->add(array(
'name' => 'title',
'type' => 'Text',
'options' => array(
'label' => 'Title',
),
));
$this->add(array(
'name' => 'artist',
'type' => 'Text',
'options' => array(
'label' => 'Artist',
),
));
$this->add(array(
'name' => 'submit',
'type' => 'Submit',
'attributes' => array(
'value' => 'Go',
'id' => 'submitbutton',
),
));
}
}
?>
I'm not really sure why this occurring since I'm following the tutorial exactly, so any help is greatly appreciated!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30628384",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Ionic native advanced Admob functionality I am implementing a new mobile app using ionic/angular/capacitor .I would like to know if it is possible to create native advanced Admob formats with any plugin that you might recommend? Not banner,interstitial or reward. Just native advanced one.
I want banners to be displayed inside certain div's not on top, bottom, or center of the screen.How can I achieve that ?
Thanks,
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75543575",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: system Audio Processing Objects (sAPO) and Skype in windows 8.1 I have googled and searched a number of forums and developer websites without any success; I believe it is a specific question that needs direct expertise or knowledge, so please read on!
BACKGROUND:
I have an audio enhancement algorithm that is implemented as a system Audio Processing Object (sAPO) that was developed and tested successfully in Windows 7. As an APO, it applies processing to all audio stream through an end point device, including audio originating from Skype.
QUESTION:
Is it true that this is not applicable to Windows 8.x ( 8.1 or greater)? More specifically, does sAPO processing still work for Skype? Does Skype disable any and all APO processing on its stream?
WHAT HAS BEEN TRIED SO FAR:
(1) I have succeeded in following the standard procedure of loading an unsigned APO from Windows 7 in Windows 8.
(2) I have tested this with Skype audio stream and that works as well.
HOWEVER:
(1) above, fails in Windows 8.1 developer preview. As a result I have not been able to test (2).
Please note that I am specifically asking about Windows 8.1, in a laptop or desktop. This is not for mobile phones or tablets. Any information or links regarding this is much appreciated!
A: I am also trying to update an APO which have been developed for W7/8 to the new format introduced by W8.1, however it doesn't seem like much documentation has been released yet.
What I have found so far, is that Windows 8.1 requires some new methods for discovery and control of effects to be implemented into the APO. This means that Skype would be able to discover certain APO effects and disable them if it needs to.
The new interface IAudioSystemEffects2:
link
Some updated code can be found in the new SwapAPO example:
link
Not much, but hopefully it can help you get going in the right direction.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/19236318",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Connect React App served on dockerized Nginx to Express server For production, I have a Dockerfile which serves a React app using Nginx:
# Stage 1
FROM node:15.6.0-alpine3.10 as react-build
WORKDIR /app/client/
COPY package*.json ./
RUN npm install
COPY ./ ./
RUN npm run build
# Stage 2 - the production environment
FROM nginx:1.19.6
COPY nginx.conf /etc/nginx/conf.d/default.conf
COPY --from=react-build /app/client/build /usr/share/nginx/html
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
While for the backend written in Node / Express, I have the following Dockerfile:
FROM node:15.6.0-alpine3.10
WORKDIR /app/server/
COPY package*.json ./
RUN npm install
COPY ./ ./
EXPOSE 8080
CMD ["npm", "start"]
These containers are managed with this docker-compose.yml:
version: "3.0"
services:
# React Client
web:
image: xxx.dkr.ecr.eu-west-2.amazonaws.com/client:latest
ports:
- "80:80"
# Node Server
server:
image: xxx.dkr.ecr.xxx.amazonaws.com/server:latest
command: npm start
ports:
- "8080:8080"
Here the nginx.conf:
server {
listen 80;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
try_files $uri $uri/ /index.html =404;
}
include /etc/nginx/extra-conf.d/*.conf;
}
PREMISES
*
*On local everything works fine, I run React through react-scripts and the backend with docker-compose (and so without the React client)
*Both images have been pushed to AWS ECR, their content is the equivalent of the Dockerfile above
*When fetching the server, endpoints look like fetch("/users/:id", {..})
*On package.json, I've set "proxy": "http://localhost:8080/"
*Both images have both been tested and are working, both on dev and prod
PROBLEM
When hitting an api endpoint from the client, I get a 405 (Not Allowed).
That's actually expected, as I'm not really telling the client (Nginx) where to redirect these calls to.
Inspecting the network tab I can see the request is made against xxx.xxx.xxx.xxx:80 (which represents the client), when it should be redirected to same address but port 8080 instead (where the Express server stands).
On development it works since there's proxy set on package.json, but that's for development only, so it won't affect production.
WHAT I TRIED
*
*Using links on docker-compose, not supported from AWS
*Using driver networks on docker-compose, not supported from AWS
*Adding proxy_pass on nginx.conf, but haven't been able to make it working
CONCLUSIONS
So premised all this, how can I connect a React build served with Nginx (client) to a Node server when both dockerized and on production?
I believe it should need some configuration on nginx.conf, but what I tried didn't land me that far.
Thank you in advance for your help!
A: First you need to specify proxy pass directive for your api calls - I would propose to add /api in your fetch calls. Than provide upstream using the same name for your backend service as specified in docker-compose.yml. It is important that backend service proceed the web service in docker-compose.yml, otherwise you would get connection error in nginx like this nginx: [emerg] host not found in upstream "backend:8080" You can update your nginx.conf as follows:
upstream backend {
server backend:8080;
}
server {
listen 80;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
try_files $uri $uri/ /index.html =404;
}
location /api {
rewrite /api/(.*) /$1 break;
proxy_pass http://backend;
}
include /etc/nginx/extra-conf.d/*.conf;
}
Or simply in your case provide a proxy pass to localhost as follows:
server {
listen 80;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
try_files $uri $uri/ /index.html =404;
}
location /api {
rewrite /api/(.*) /$1 break;
proxy_pass http://localhost:8080;
}
include /etc/nginx/extra-conf.d/*.conf;
}
A: Sample Docker file, Included the Production build in the docker file
FROM node:15.6.0-alpine3.10 as react-build
# install and cache app dependencies
COPY package.json package-lock.json ./
RUN npm install && mkdir /react-frontend && mv ./node_modules ./react-frontend
WORKDIR /app/client/
COPY . .
RUN npm run build
# ------------------------------------------------------
# Production Build
# ------------------------------------------------------
FROM nginx:1.16.0-alpine
COPY --from=builder /react-frontend/build /usr/share/nginx/html
RUN rm /etc/nginx/conf.d/default.conf
COPY nginx/nginx.conf /etc/nginx/conf.d
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
To add nginx as a server to our app we need to create a nginx.conf in the project root folder. Below is the sample file
server {
listen 80;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
try_files $uri $uri/ /index.html;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/65981289",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Payment for uploading app into android market Registration fee is 25$. It will only be for one year? After one year we have to pay 25$ or it will expire? How much do we have to pay for renewal?
A: "There is a one time $25 registration fee"
Extracted from here
| {
"language": "en",
"url": "https://stackoverflow.com/questions/9515058",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Why my jetstream application in Laravel not showing proper CSS and JS path when uploading in Cpanel? I have built a project in laravel using jetstream. The project is running smoothly in my local machine (localhost) but the CSS and JS path is not working when I am uploading in server. Can anyone help?
My cpanel directory is
public_html/pro1/admin/
Error
Falied to load resource : app.js
Falied to load resource : app.css
Falied to load resource : app.css
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74798882",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to modify Djongo ArrayModelField as shown in Django Admin I'm experimenting with Djongo right now. So far a great project! What I don't like yet is the way ArrayModelField fields are integrated in the Django admin. I am missing something like an add-button. At the moment only one additional empty inline Form is shown for the nested model.
Is there a possibility to add new inline models with an "add-button"?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/52236475",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: "This will merge 0 commits." I have somehow messed up my git branch badly. Certain branches didn't seem to be merged properly. I'm not sure how to explain, things just aren't how I wanted. I was working on different branches branched from master and then pushing them to one called development, but I think because I merged some of those branches together while working on them, that has somehow messed up the final result.
I went into development and reverted all the merges from when I started working. This should be OK since I have the original branches still. But when I try merge these branches back into development, the GitHub app app says there are no changes to commit. How can this be if I reverted everything?
A: Reverting does not delete commits, it creates a new commit that is the inverse of the patch set. So if you're cherry picking previous commits into a new branch, the old ones won't be identified as needing to be merged.
You could attempt to rebase those same commits into a new branch, then merge those back in. The rebasing would replay and create new commits for your reverted items. Since you don't provide a lot of details, I can't give an exact answer.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31897939",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: How do I bind the Header of a TextBox? In windows phone 8.1, I can bind the text in a textbox to a string resource in my Resources.resw.
How do I do the same thing for the Header="My Header" tag?
i.e. bind the Header text to another string resource in Resources.resw
<TextBox Header="My Header" Text="{Binding textboxtext}" x:Name="TextBox"/>
A: Same way you Bind the Text field.
<TextBox Header="{Binding myBinding}" Text="{Binding textboxtext}" x:Name="TextBox"/>
If you want to point it to a Resource then
<Page.Resources>
<x:String x:Key="myTextBoxHeader">this is a textbox header</x:String>
</Page.Resources>
<TextBox Text="{Binding textboxtest}"
Header="{StaticResource myTextBoxHeader}"></TextBox>
If you pointing to a .resw file then in most cases you will need a x:Uid like this
<TextBox x:Uid="MyLocalizeTextBox"></TextBox>
Then you need to edit the strings for the stuff you want to display, in this case your Header + Text
Look at the highlighted section very carefully, you see the pattern? It won't show up on the designer and will show up when you deploy [See Image Below]
So by now you may be wondering if you combine both methods? (one to show in the designer and one to show while deploy because you're localizing). This is actually the prefer method.
2 in 1 (Both methods)
<TextBox x:Uid="MyLocalizeTextBox"
Text="{Binding textboxtest}" Header="{StaticResource myBinding}"></TextBox>
During design time it will use your local resouces, when deploy it will use the resources in the resw file.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/27267698",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to convert full path of a file to only the file name in batch scripting I have a variable called %file% and it contains path to a file, i want that ONLY the file name in a new variable called %file_name% (without the extension like .exe). I am new to batch scripting so this might be very easy...
Thanks in advance!
A: for %%i in (%file%) do @echo %%~nxi
n for name
x for extension
for more options see for /?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/27607278",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: PHP Related items from database I have been googling for a while and searching SO but I still can't find an answer.
So my problem is that I want to pull related content from mySQL database on what id is currently being displayed on the page. In the database I have a column dedicated to keywords, and I am using the LIKE query to pull id's based on those keywords. However, I get only one id because the LIKE query looks at the keyword literally. For example, keyword1 = 'apples berries oranges' is not the same as keywords2 = 'apples' 'berries' 'oranges'. I want the latter so it can pull in more related data.
I also think I may be approaching this wrong, but I don't know any other way to pull related items.
Here's my code...
<?php
include 'data/data_connect.php';
if ($sugg_qs = $db->query("SELECT * FROM questions WHERE keywords LIKE '$keywords' LIMIT 4")) {
if ($q_count = $sugg_qs->num_rows) {
echo $q_count;
while($row = $sugg_qs->fetch_assoc()) {
echo $row->title;
}
$sugg_qs->free();
} else {
die('error');
}
} else {
die('error');
}
?>
UPDATE
if ($sugg_qs = $db->query("SELECT * FROM questions WHERE keywords LIKE CONCAT('%', '$keywords' ,'%') LIMIT 3")) {
if ($q_count = $sugg_qs->num_rows) {
$row = $sugg_qs->fetch_all(MYSQLI_ASSOC);
foreach ($row as $rows) {
echo $rows['title'];
}
} else {
die('error');
}
This code does work with id's that only have one keyword. So I guess a possible (but undesired) solution would be to create a new column for each new keyword and use LIKE for each keyword.
Is there a way to avoid creating more columns?
THANKS for those who helped already :)
FINAL UPDATE?
Ok. So I figured it out in probably the messiest way to write code, but apparently it works for me. So first of all I standardized my table where each element is limited to only 5 keywords and 1 category. So in the query I call for items with similar keywords, and if there aren't similar results I then call for items from the same category from the original item.
Here is the (messy) code for those looking for a solution!
$q_kw_arr = explode(' ', $keywords);
if ($sugg_qs = $db->query("SELECT keywords, category, title FROM questions WHERE keywords LIKE CONCAT('%', '$q_kw_arr[0]' ,'%') OR CONCAT('%', '$q_kw_arr[1]' ,'%') OR CONCAT('%', '$q_kw_arr[2]' ,'%') OR CONCAT('%', '$q_kw_arr[3]' ,'%') OR CONCAT('%', '$q_kw_arr[4]' ,'%') OR category= '$category' LIMIT 4")) {
if ($q_count = $sugg_qs->num_rows) {
$row = $sugg_qs->fetch_all(MYSQLI_ASSOC);
foreach ($row as $rows) {
echo $rows['title'];
}
} else {
echo 'error';
}
}
SPECIAL THANKS TO..
Terminus, Grzegorz J, and infidelsawyer
A: You might need some checking if there are any keywords in the $keywords variable but here is a solution that works with your current structure.
Presuming each keyword in the string is separated by a space:
$keywordSeparator = " ";
$keywords = explode($keywordSeparator, $keywords);
$keywordsWhere = " WHERE keywords LIKE '%" . implode("%' OR keywords LIKE '%", $keywords) . "%'";
$query = "SELECT *
FROM questions
" . $keywordsWhere;
if ($sugg_qs = $db->query($query)) {
Edit
Paul Spiegel made some good comments (not just pointing out the error in my code:)
If you want to avoid partial matches on keywords then you should wrap all keywords in a separator.
So to avoid apple matching appliepie you would store the keyword with spaces around the keyword. So apple oranges becomes apple oranges. A search for those keywords would be WHERE keywords LIKE '% apple %' OR keywords LIKE '% oranges %'.
However, at that point, you should see performance improvements if you store the keywords in there own table, one keyword per row. A sample table structure for a modified questions table and the new question_keywords table below:
--
-- Table structure for table `questions`
--
CREATE TABLE IF NOT EXISTS `questions` (
`question_id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(254) NOT NULL,
PRIMARY KEY (`question_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
--
-- Table structure for table `question_keywords`
--
CREATE TABLE IF NOT EXISTS `question_keywords` (
`keyword_id` int(11) NOT NULL AUTO_INCREMENT,
`question_id` int(11) NOT NULL,
`keyword` varchar(50) NOT NULL,
PRIMARY KEY (`keyword_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
--
-- Indexes for table `question_keywords`
--
ALTER TABLE `question_keywords`
ADD KEY `question_id_keyword` (`question_id`,`keyword`);
Some sample data
INSERT INTO `questions` (`title`) VALUES ('Question #1'), ('Question #2'), ('Question #3');
INSERT INTO `question_keywords` (`question_id`, `keyword`)
VALUES
(1, 'apple')
,(2, 'orange')
,(3, 'ILikeFruit')
,(3, 'banana')
,(3, 'grape')
,(3, 'apple');
You can then search like this
$keywordSeparator = " ";
$keywords = explode($keywordSeparator, $keywords);
$keywordsAnd = "'" . implode("','", $keywords) . "'";
$query = "
SELECT DISTINCT q.*
FROM questions q
INNER JOIN question_keywords k
ON q.question_id = k.question_id
AND k.keyword IN (" . $keywordsAnd . ")";
if ($sugg_qs = $db->query($query)) {
The search might seem more complicated since we now need that JOIN but it should speed up since it doesn't have to search using % and can take advantage of the index we have of the keyword column.
A: You could try:
if ($sugg_qs = $db->query("SELECT * FROM questions WHERE keywords LIKE CONCAT('%', $keywords ,'%') LIMIT 4")) {
| {
"language": "en",
"url": "https://stackoverflow.com/questions/35386773",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Deleting the Contents of the Selected Folder with the Checkbox when the Button is Clicked? If checkbox is selected, what is the code used to delete the contents of the folder when the button is pressed? Also, if it is not selected, it should not be deleted.
private void button1_click(object sender, EventArgs e)
{
string[] folder = Directory.GetFiles(@"D:\java\");
foreach (string _file in folder)
{
File.Delete(_file);
}
}
A: One of many ways to do achieve your objective:
*
*Make an array of checkboxes on your current form that are checked.
*Go through the array to build the folder name based on the Text.
*Delete the entire folder, then replace it with an empty one.
You may want to familiarize yourself with System.Linq extension methods like Where and Any if you haven't already.
The [Clear] button should only be enabled if something is checked.
Making an array of the checkboxes will be handy. It can be used every time you Clear. At the same time, the [Clear] button shouldn't be enabled unless one or more of the checkboxes are marked.
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
// Make an array of the checkboxes to use throughout the app.
_checkboxes = Controls.OfType<CheckBox>().ToArray();
// This provides a way to make sure the Clear button is
// only enabled when one or more checkboxes is marked.
foreach (CheckBox checkBox in _checkboxes)
{
checkBox.CheckedChanged += onAnyCheckboxChanged;
}
// Attach the 'Click' handler to the button if you
// haven't already done this in the form Designer.
buttonClear.Enabled = false;
buttonClear.Click += onClickClear;
}
const string basePath = @"D:\java\";
CheckBox[] _checkboxes;
.
.
.
}
Set the Clear button Enabled (or not)
Here we respond to changes in the checkbox state.
private void onAnyCheckboxChanged(object sender, EventArgs e)
{
buttonClear.Enabled = _checkboxes.Any(_=>_.Checked);
}
Exec Clear
Build a subfolder path using the Text of the checkboxes. If the checkbox is selected, delete the entire folder, replacing it with a new, empty one.
private void onClickClear(object sender, EventArgs e)
{
// Get the checkboxes that are selected.
CheckBox[] selectedCheckBoxes =
_checkboxes.Where(_ => _.Checked).ToArray();
foreach (CheckBox checkBox in selectedCheckBoxes)
{
// Build the folder path
string folderPath = Path.Combine(basePath, checkBox.Text);
// Can't delete if it doesn't exist.
if (Directory.Exists(folderPath))
{
// Delete the directory and all its files and subfolders.
Directory.Delete(path: folderPath, recursive: true);
}
// Replace deleted folder with new, empty one.
Directory.CreateDirectory(path: folderPath);
}
}
A: I understand, you have this structure
D
|-java
|-Document
|-Person
|-Picture
And you said "delete the contents of the folder". So, I assume you need to keep folders
In this case
public void EmptyFolder(string root, IEnumerable<string> subfolders)
{
foreach(string folder in subfolders)
{
string dirPath = Path.Combine(root, folder);
foreach (string subdir in Directory.EnumerateDirectories(dirPath))
Directory.Delete(subdir, true);
foreach (string file in Directory.EnumerateFiles(dirPath))
File.Delete(file);
}
}
// (assuming check box text is the name of folder. Or you can use tag property to set real folder name there)
private IEnumerable<string> Getfolders()
{
foreach(control c in this.Controls) // "this" being a form or control, or use specificControl.Controls
{
if (c is Checkbox check && check.Checked)
yield return check.Text;
}
}
// USAGE
EmptyFolder(@"D:\java\", Getfolders());
NOTE: written from memory and not tested
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75632342",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Declaring RequireJS dependencies with TypeScript I am using TypeScript with RequireJS. As you can see in the following image, I define some imports using the RequireJS config; of course these imports are sourced via <script> tags:
TypeScript cannot see those declarations, so I was thinking of just declaring them as globals or something, to avoid transpilation errors.
What might be the best thing to do in this situation? Everything seems to run fine, but I do get more compilation errors and of course red syntax highlighting everywhere.
In the first image we see that requirejs is not recognized, also in the below image we see that TypeScript doesn't know what 'redux' is, (but it's in the RequireJS config).
So what I would like to do is tell TypeScript about the following dependencies: requirejs, redux, react, rxjs, socketio, etc
A: So part of the problem was I needed to run:
npm install -D @types/requirejs
npm install -D @types/redux
and then in my tsconfig.json, add:
"types": [
"node",
"lodash",
"react",
"react-dom",
"redux",
"react-redux",
"async",
"requirejs"
],
"typeRoots": [
"node_modules/@types"
],
but also, to address the problem of TypeScript not understand where <script> tag dependencies come from in the front-end, it looks like we can do something like this:
https://weblog.west-wind.com/posts/2016/Sep/12/External-JavaScript-dependencies-in-Typescript-and-Angular-2
De-referencing Globals In order to keep the Typescript compiler happy
and not end up with compilation errors, or have a boat load of type
imports you may only use once or twice, it's sometimes easier to
simply manage the external libraries yourself. Import it using a
regular script tag, or packaged as part of a separate vendor bundle
and then simply referenced in the main page.
So rather than using import to pull in the library, we can just import
using tag as in the past:
Then in any Typescript class/component where you want to use these
libraries explicitly dereference each of the library globals by
explicitly using declare and casting them to any:
declare var redux:any;
declare var socketio: any;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41761172",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Can Dart or Flutter unit tests be automatically repeated? When unit testing with Dart or Flutter
If there are 100 unit tests, if you run the flutter test command, 100 test codes will be tested once.
But I want to repeat this N times.
Is there a command or way to automatically start the test again after one full test and report if the test is broken?
A: I'm not sure why this would be necessary, but I suppose you could wrap the tests you want to repeat in a for loop from 0 to N.
If you define N using int.fromEnvironment then you can pass in a value for N at the command line.
flutter test --dart-define=N=100
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:example/main.dart';
const N = int.fromEnvironment('N', defaultValue: 1);
void main() {
for (int i = 0; i < N; i++) {
testWidgets('Counter increments smoke test $i',
(WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(const MyApp());
// Verify that our counter starts at 0.
expect(find.text('0'), findsOneWidget);
expect(find.text('1'), findsNothing);
// Tap the '+' icon and trigger a frame.
await tester.tap(find.byIcon(Icons.add));
await tester.pump();
// Verify that our counter has incremented.
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsOneWidget);
});
}
}
Alternatively you could write a program that runs flutter test N times.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75380753",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: configure NodeJS process on two different machine I have two different nodejs web app running on two different machine.
But I need to have one endpoint to user api1.abc.com/v1 to go one process and api2.abc.com/v2 go to another process.
how can i do this kind of request with the single endpoint to user (abc.com). need a nginx setup guide ?
I need this setup because internally I need to call user authenticated api from one server to another.
A: On one server you need to receive the data (using express & router):
router.get('/v1', function(req, res) {
// TODO
res.render('something');
});
and on the other you need to fetch:
var express = require('express');
var router = express.Router();
var app = express()
app.use('api1.abc.com', router);
router.post('/v1', function(req, res) {
// process res
});
A: You can write code at version two apis. In request you can pass version on which you need to call.
Call all api's on version 2. If it required to call on second server. Write code on version one to identify the call from version 2. So that it can by pass the basic authentication.
Thanks,
| {
"language": "en",
"url": "https://stackoverflow.com/questions/43255998",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Power BI duration filter for hours minutes and seconds I have data in following format define as Time (hh:mm:ss) in Modeling tab:
When I try to turn on filter (Power BI filter or in filter in Visuals) all I can do is filter to day granularity.
I tried some of the custom filters but none of them is working.
How can I filter based on hh/mm/ss?
A: Acepted answer is data warehouse aproach with creation of separate tables and relations to time table. That's bit too long for me.
But if you can do it easily like this:
Calculate duration using DATEDIFF formula:
time_in_sec= DATEDIFF([time_end];[time_start];SECOND)
Than you can use that to calculate your 3 custom columns for hours, minutes and seconds using this:
For hours:
duration_hh = if([time_in_sec]>0;FLOOR( [time_in_sec] / 3600; 1);0)
For minutes:
duration_mm = if([time_in_sec]>0;FLOOR( MOD( [hpm_trajanje_poziva_sec]; 3600) / 60; 1);0)
For seconds:
hpm_trajanje_poziva_ss = if([hpm_trajanje_poziva_sec]>0; FLOOR( MOD ( MOD( [hpm_trajanje_poziva_sec]; 3600) ;60 ); 1) ;0)
Than you can use those 3 calculated columns to filter your data in visuals.
A: The best approach would be to create a new time dimension, link it to your time fields and then use that to apply the filter rather than filtering those fields directly.
Here's a helpful guide giving a couple of was to apply this.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58199350",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Java application using Maven Build My project team is using maven build. We have a package name as **/**/**/RCS under which all the classes are getting generated. But the jar does not contain these classes for some reason. Is there a way to include these classes into the RCS.jar?
We are using maven build to compile all the modules in the application. There is no problem with other packages having a similar format.
Please suggest where the issue can be.
Thanks in advance!!!
This is the pom.xml for the package. Have removed certain dependencies.
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion>
<groupId>XX.4-1.Components.Oracle</groupId>
<artifactId>RCS</artifactId>
<version>4.1</version>
<packaging>jar</packaging>
<name>RCS</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<archDeliveryPath>/home/user/BuildWorkspace/Product_Deployment/Dependent_Jars</archDeliveryPath>
</properties>
<dependencies><dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>Oracle</groupId>
<artifactId>ojdbc5</artifactId>
<version>1.0</version>
<type>jar</type>
<exclusions>
<exclusion>
<groupId>*</groupId>
<artifactId>*</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>Oracle</groupId>
<artifactId>j2ee</artifactId>
<version>1.0</version>
<type>jar</type>
<exclusions>
<exclusion>
<groupId>*</groupId>
<artifactId>*</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>Oracle</groupId>
<artifactId>ErrorMessages</artifactId>
<version>1.0</version>
<type>jar</type>
<exclusions>
<exclusion>
<groupId>*</groupId>
<artifactId>*</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>ThirdpartyLicensedDependencyPOM</groupId>
<artifactId>License-Base</artifactId>
<version>1.0</version>
<type>pom</type>
</dependency>
<dependency><groupId>com.sum</groupId><artifactId>rt</artifactId><version>0.1</version><scope>system</scope><systemPath>${java.home}/lib/rt.jar</systemPath></dependency>
<dependency><groupId>com.sun</groupId><artifactId>tools</artifactId><version>0.1</version><scope>system</scope><systemPath>${java.home}/../lib/tools.jar</systemPath></dependency>
<dependency>
<groupId>XX.4-1.Components.Oracle</groupId>
<artifactId>XX</artifactId>
<version>(,4.1]</version>
<scope>compile</scope>
<exclusions>
<exclusion>
<groupId>*</groupId>
<artifactId>*</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>XX.4-1.Components.Oracle</groupId>
<artifactId>XX</artifactId>
<version>(,4.1]</version>
<scope>compile</scope>
<exclusions>
<exclusion>
<groupId>*</groupId>
<artifactId>*</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>ARCHPOM</groupId>
<artifactId>XX</artifactId>
<version>1.0</version>
<scope>system</scope>
<systemPath>${archDeliveryPath}/XX.jar</systemPath>
</dependency>
<dependency>
<groupId>ARCHPOM</groupId>
<artifactId>CommonFunctionality</artifactId>
<version>1.0</version>
<scope>system</scope>
<systemPath>${archDeliveryPath}/CommonFunctionality.jar</systemPath>
</dependency>
</dependencies>
<repositories>
<repository>
<id>id1</id>
<name>Artifactory</name>
<url>http://URL</url>
</repository>
<repository>
<id>Artifactory</id>
<name>Artifactory</name>
<url>http://URL</url>
</repository>
<repository>
<id>Artifactory</id>
<name>Artifactory-releases</name>
<url>http://URL</url>
</repository>
<repository>
<id>Licensed Artifactory</id>
<name>Artifactory-releases</name>
<url>http://URL</url>
</repository>
<repository>
<id>id4</id>
<name>Artifactory</name>
<url>http://URL</url>
</repository>
<repository>
<id>id3</id>
<name>Artifactory</name>
<url>http://URL</url>
</repository>
</repositories>
<distributionManagement>
<repository>
<id>id2</id>
<name>Artifactory</name>
<url>http://URL</url>
</repository>
</distributionManagement>
</project>
A: the problem is resolved. Changed the default excludes in plexus-utils-2.0.5.jar/org/codehaus/plexus/util/AbstractScanner.java which was excluding **/RCS & **/RCS/**. Commented the RCS line and voila, it worked.
A: Try adding this to your pom.xml
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.6</version>
<configuration>
<includes>
<include>**/RCS/*</include>
</includes>
</configuration>
</plugin>
</plugins>
</build>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30891112",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: Spring : Singleton VS Prototype i'm new to Spring starting to learn new concepts , and i found topic speaking about bean Scopes :
- Singleton : returns the same instance every time.
- Prototype : returns new instance of the object per every request.
my question is : how is this helpful for me what is the difference between the same instance , and new instance of the object , or why the prototype scope exists !
A: Same instance would mean any call (from anywhere) to getBean() from ApplicationContext or BeanFactory will land you with the same instance, i.e. constructor is called just once when Spring is being initialized (per Spring container).
However, there are scenarios when you would want different object instances to work with.
For example, if you have a Point object as a member variable in a Triangle class, in case of Singleton, when the Triangle class is being instantiated, the Point object also is instantiated as it is dependent.
If you require a different instance of Point to work with elsewhere, then you will need to define the Point as a prototype, else it carries the same state.
Googling would surely help you find answers and examples demonstrating the use case.
Hope this helps.
A: In case if the same instance is injected everywhere as Singleton, you can use it's shared state for containing any kind of data. In case if new instance is created any time bean is being injected - it's state is not shared. By default all beans are Singletons. Prototype scope stands for cases when bean's inner data should be unique for each place you inject bean into.
Example: you have the bean which represents REST client. Different parts of application use different REST services, each requires some specific request headers - for security purposes, for example. You can inject the same REST client in all these beans to have it's own REST client bean with some specific headers. At the same time you can configure client's politics in common for the whole application - request timeouts, etc.
See also: When to use Spring prototype scope?
A: It helps in designing a software, refer java design patterns you fill find much useful information, In case of singleton you will be able to create only object, it will helps cases like 1.saving time in creating a very complex object (we can reuse the same object) 2.Some times we need to use the same object throughout the application E.g if you want count the total number of active users in the application, you can use singleton object to store it, because there will be only one object so you can easily update and retrieve data. In case of Prototype it will always give you different object, it is necessary in some cases like some access token, you should always get the new /valid token to proceed further, so prototype pattern /Bean is useful.
A: My understanding for Singleton is more likely used in the situation like return single Utility instance.
//SomeUtil is Singleton
var util = SomeUtil.getInstance();
print(util.doTask1());
print(util.doTask2());
If another thread goes into these code, SomeUtil.getInstance() just return the SomeUtil instance other than creating a new one (which might cost much to create a new one).
As to Prototype, I just found this situation using Prototype:
Lets understand this pattern using an example. I am creating an entertainment application that will require instances of Movie,
Album and Show classes very frequently. I do not want to create their instances everytime as it is costly.
So, I will create their prototype instances, and everytime when i will need a new instance,
I will just clone the prototype.
Example code locates https://github.com/keenkit/DesignPattern/tree/master/src/PrototypePattern
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41264211",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: XLRD cannot read multiindex column name I have a problem with multiindex column name. I'm using XLRD to convert excel data to json using json.dumps but instead it gives me only one row of column name only. I have read about multilevel json but i have no idea how to do it using XLRD.
Here is my sample of table column name
Sample of code:
for i in path:
with xlrd.open_workbook(i) as wb:
print([i])
kwd = 'sage'
print(wb.sheet_names())
for j in range(wb.nsheets):
worksheet = wb.sheet_by_index(j)
data = []
n = 0
nn = 0
keyword = 'sage'
keyword2 = 'adm'
try:
skip = skip_row(worksheet, n, keyword)
keys = [v.value for v in worksheet.row(skip)]
except:
try:
skip = skip_row2(worksheet, nn, keyword2)
keys = [v.value for v in worksheet.row(skip)]
except:
continue
print(keys)
for row_number in range(check_skip(skip), worksheet.nrows):
if row_number == 0:
continue
row_data = {}
for col_number, cell in enumerate(worksheet.row(row_number)):
row_data[keys[col_number]] = cell.value
data.append(row_data)
print(json.dumps({'Data': data}))
ouh by the way, each worksheet have different number to skip before column name so that's why my code got function of skip row. After I skip the row and found the exact location of my column name. Then i start to read the values. But it yah there is where the problem raise from my view because i got two rows of column name. And still confuse how to do multi level json with XLRD or at least join the column name with XLRD (which i guess can't).
Desired outcome multilevel json:
{ "Data":[{ "ID" : "997", "Tax" : [{"Date" : "9/7/2019", "Total" : 2300, "Grand Total" : 340000"}], "Tax ID" : "ST-000", .... }]}
pss:// I've tried to use pandas but it gives me a lot of trouble since i work with big data.
A: You can use multi indexing in panda, first you need to get header row index for each sheet.
header_indexes = get_header_indexes(excel_filepath, sheet_index) #returns list of header indexes
You need to write get_header_indexes function which scans sheet and return header indexes.
you can use panda to get JSON from dataframe.
import pandas as pd
df = pd.read_excel(excel_filepath, header=header_indexes, sheet_name=sheet_index)
data = df.to_dict(orient="records")
for multiple headers data containts list of dict and each dict has tuple as key, you can reformat it to final JSON as per your requirement.
Note: Use chunksize for reading large files.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58423944",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to efficiently count each element in a list in Python? Suppose that we have the following list:
["aa", "abc", "aa", "bc", "abc", "abc", "a"]
I would like to get the following result about the occurrence of each element:
"abc": 3
"aa" 2
"a": 1
"bc": 1
What would the best way in this case?
The following is an approach I came up with.
#!/usr/bin/python
word_list = ["aa", "abc", "aa", "bc", "abc", "abc", "a"]
word_count_list = [[word, word_list.count(word)] for word in set(word_list)]
print (sorted(word_count_list, key = lambda word_count : word_count[1], reverse=True))
But I'm not quite sure whether the above approach is efficient. Could you suggest a good way for doing this?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/59580979",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: regular expression for French characters I need a function or a regular expression to validate strings which contain alpha characters (including French ones), minus sign (-), dot (.) and space (excluding everything else)
Thanks
A: Try:
/^[\p{L}-. ]*$/u
This says:
^ Start of the string
[ ... ]* Zero or more of the following:
\p{L} Unicode letter characters
- dashes
. periods
spaces
$ End of the string
/u Enable Unicode mode in PHP
A: /^[a-zàâçéèêëîïôûùüÿñæœ .-]*$/i
Use of /i for case-insensitivity to make things simpler. If you don't want to allow empty strings, change * to +.
A: The character class I've been using is the following:
[\wÀ-Üà-øoù-ÿŒœ]. This covers a slightly larger character set than only French, but excludes a large portion of Eastern European and Scandinavian diacriticals and letters that are not relevant to French. I find this a decent compromise between brevity and exclusivity.
To match/validate complete sentences, I use this expression:
[\w\s.,!?:;&#%’'"()«»À-Üà-øoù-ÿŒœ], which includes punctuation and French style quotation marks.
A: Simplified solution:
/^[a-zA-ZÀ-ÿ-. ]*$/
Explanation:
^ Start of the string
[ ... ]* Zero or more of the following:
a-z lowercase alphabets
A-Z Uppercase alphabets
À-ÿ Accepts lowercase and uppercase characters including letters with an umlaut
- dashes
. periods
spaces
$ End of the string
A: Simply use the following code :
/[\u00C0-\u017F]/
A: This line of regex pass throug all of cirano de bergerac french text:
(you will need to remove markup language characters
http://www.gutenberg.org/files/1256/1256-8.txt
^([0-9A-Za-z\u00C0-\u017F\ ,.\;'\-()\s\:\!\?\"])+
A: All French and Spanish accents
/^[a-zA-ZàâäæáãåāèéêëęėēîïīįíìôōøõóòöœùûüūúÿçćčńñÀÂÄÆÁÃÅĀÈÉÊËĘĖĒÎÏĪĮÍÌÔŌØÕÓÒÖŒÙÛÜŪÚŸÇĆČŃÑ .-]*$/
A: /[A-Za-z-\.\s]/u should work.. /u switch is for UTF-8 encoding
A: This might suit:
/^[ a-zA-Z\xBF-\xFF\.-]+$/
It lets a few extra chars in, like ÷, but it handles quite a few of the accented characters.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/1922097",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "23"
} |
Q: Django best practice for storing access keys What's the best way to store API access keys that you need in your settings.py but that you don't want to commit into git?
A: I use an environment file that stays on my computer and contains some variables linked to my environment.
In my Django settings.py (which is uploaded on github):
# MANDRILL API KEY
MANDRILL_KEY = os.environ.get('DJANGO_MANDRILL_KEY')
On dev env, my .env file (which is excluded from my Git repo) contains:
DJANGO_MANDRILL_KEY=PuoSacohjjshE8-5y-0pdqs
This is a "pattern" proposed by Heroku: https://devcenter.heroku.com/articles/config-vars
I suppose there is a simple way to setit without using Heroku though :)
To be honest, the primary goal to me is not security-related, but rather related to environment splitting. But it can help for both I guess.
A: I use something like this in settings.py:
import json
if DEBUG:
secret_file = '/path/to/development/config.json'
else:
secret_file = '/path/to/production/config.json'
with open(secret_file) as f:
SECRETS = json.loads(f)
secret = lambda n: str(SECRETS[n])
SECRET_KEY = secret('secret_key')
DATABASES['default']['PASSWORD'] = secret('db_password')
and the JSON file:
{
"db_password": "foo",
"secret_key": "bar"
}
This way you can omit the production config from git or move it outside your repository.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/24086718",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Save Audio to SD CARD I have been looking to save an audio to SdCard.
File dir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC) + "/AUDIO/");
boolean success1;
if (!dir.exists()) {
MessageSystem("SAVING FOLDER: " + dir + " -- DON'T EXISTS ");
//CASE NOT - We create
success1 = dir.mkdir();
if (success1) {
// Do something on success
MessageSystem("foldersd: " + dir.toString() + " CREATED!!");
} else {
// Do something else on failure
MessageSystem("foldersd: " + dir.toString() + " NOT CREATED!!");
}
}
I have tried to save also to:
File dir = new File(Environment.getExternalStorageDirectory() + "/AUDIO/");
On both cases it worked but it saves to INTERNAL STORAGE. NEVER TO SD CARD
I used getExternalFilesDirs() to. But the user will loose the files if he uninstalls the app.
I don't want that.
How can I save the audios in a SD card public folder or create a new one.
Any times it creates into Internal Storage.
Any solution???
I tried with this and I could create a document in the SD CARD. And empty one. Now I would like to save a MediaRecorder audio into it. But I need the path. How can I get it?
Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("application/mpeg");
intent.putExtra(Intent.EXTRA_TITLE, audio_name);
// Optionally, specify a URI for the directory that should be opened in
// the system file picker when your app creates the document.
intent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, pickerInitialUri);
startActivityForResult(intent, CREATE_FILE);
A: you can try this,
public static final String DEFAULT_STORAGE_LOCATION = "/sdcard/AudioRecording";
File dir = new File(DEFAULT_STORAGE_LOCATION);
if (!dir.exists()) {
try {
dir.mkdirs();
} catch (Exception e) {
Log.e("CallRecorder", "RecordService::makeOutputFile unable to create directory " + dir + ": " + e);
Toast t = Toast.makeText(getApplicationContext(), "CallRecorder was unable to create the directory " + dir + " to store recordings: " + e, Toast.LENGTH_LONG);
t.show();
return null;
}
} else {
if (!dir.canWrite()) {
Log.e(TAG, "RecordService::makeOutputFile does not have write permission for directory: " + dir);
Toast t = Toast.makeText(getApplicationContext(), "CallRecorder does not have write permission for the directory directory " + dir + " to store recordings", Toast.LENGTH_LONG);
t.show();
return null;
}
*you can get the sd card location by querying the system as,
Environment.getExternalStorageDirectory();
and don't forget to add the user permission
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/63997165",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: In-App purchase with Windows phone8 I have developed an Win-Phone8 application, Initially for 15 days I am giving my application for trail period and after 15 days the user have to subscribe the application (They can purchase) to use it uninterruptedly rest of the time , I was planning to use third party payment gateways like (Stripe,Paypal) but I think the Platform like Windows only allowing third party payment gateways for selling physical goods like (Books , Electronics items etc. ) But in our case we just going to sell an upgraded App which is a digital content.My Question is can we sell the App Upgrade features through Stripe payment gateway or any third party payment gateway??? IF not I found the platform Windows providing Service API's for In-App Purchase inside the App. So My Question is, Do i need only In-App purchase service for selling App in Windowsstore???
A: Yes. In-app purchase given by Microsoft is enough for selling apps in windows store. You don't need to worry about third party payment gateway etc.
refer to this link https://msdn.microsoft.com/en-in/library/windows/apps/jj206949(v=vs.105).aspx
examples given on this page are useful.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39576650",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Dealing with a nested ng-repeat with AngularJS. Cannot get a button with ng-click to click I apologize but I'm very new to Angular and I'm even sure how to ask the question. My end goal is to make a bike shop "website" where the user can edit the bikes. Furthermore, they can add accessories to the bikes. Currently everything works unless I'm trying to add in new accessories.
If you look at the button with ng-click="store.appendAcc()" and try to click, it won't work on a NEW bike. It only works if I manually add in the bike information into self.products or if I get rid of the ng-repeat in the div with class "add-parts". I appreciate the help!
html:
<div class="name">
<form>
<div ng-show="store.showPromo" class="showing">
<div class="promo-showing" ng-repeat="bike in store.products">
<div class="promo-bikes">
<p>{{bike.name}}</p>
<p>{{bike.price}}</p>
<div ng-repeat="accessory in bike.accessories" class="accesories">
<p>{{accessory.name}}</p>
<p>{{accessory.price}}</p>
</div>
</div>
</div>
<button ng-click="store.switchToEdit()">Edit</button>
</div>
<div ng-show="!store.showPromo" class="editing">
<div ng-repeat="bike in store.products">
<input ng-model="bike.name">
<input ng-model="bike.price">
<button ng-click="store.appendAcc()">add accessories</button>
<div ng-show="store.showAcc" ng-repeat="accessory in bike.accessories" class="add-parts">
<input class="accessory-input" ng-model="accessory.name">
<input class="accessory-input" ng-model="accessory.price">
<button ng-click="store.hideAcc()">submit accessories</button>
</div>
</div>
<button ng-click="store.newBike()" type="submit">Create New</button>
<button ng-click="store.switchToPromo()">See Promo Screen</button>
</div>
</form>
</div>
js:
(function() {
var app = angular.module('bike', []);
app.controller('storeCtrl', function() {
var self = this;
self.showPromo;
self.showAcc;
self.products = [
{
name: 'bike',
price: '$$$',
accessories: [{
name: 'handles',
price: 99
}, {
name: 'seat',
price: 60
}]
}
];
self.newBike = function(named, priced, partName, partPrice) {
self.products.push({
name: named || 'edit bike',
price: priced || 'edit price',
});
}
self.switchToPromo = function () {
self.showPromo = 'on';
// for (var i = self.parts.length - 1; i >= 0; i--) {
// console.log(self.parts[i])
// document.querySelector('.promo-bikes').appendChild(self.parts[i])
// };
}
self.switchToEdit = function () {
self.showPromo = undefined;
}
self.appendAcc = function () {
self.showAcc = 'on';
}
self.hideAcc = function (named, priced) {
self.showAcc = undefined;
}
})
})();
A: I've never seen anyone use this the way you are in Angular. I always use $scope but you must inject it into your controller. Any properties you add to $scope are available in the view.
app.controller('storeCtrl', ['$scope', function($scope)
{
$scope.showPromo = false;
$scope.showAcc = false;
...
$scope.appendAcc = function () {
$scope.showAcc = 'on';
}
}
You will also need to remove the store prefix from your view and reference properties off of $scope directly like this:
<div ng-show="!showPromo" class="editing">
<div ng-repeat="bike in products">
<input ng-model="bike.name">
<input ng-model="bike.price">
<button ng-click="appendAcc()">add accessories</button>
<div ng-show="showAcc" ng-repeat="accessory in bike.accessories" class="add-parts">
<input class="accessory-input" ng-model="accessory.name">
<input class="accessory-input" ng-model="accessory.price">
<button ng-click="hideAcc()">submit accessories</button>
</div>
</div>
<button ng-click="newBike()" type="submit">Create New</button>
<button ng-click="switchToPromo()">See Promo Screen</button>
</div>
Also, without seeing the rest of your code, I'm not sure why you have your code wrapped in a closure. I don't believe that is necessary, and could cause issues.
A: I think it's probably that accessories is undefined when you create a new bike, so there is nothing to "repeat" in the ng-repeat. I suggest initializing a new bike with
self.newBike = function(named, priced, partName, partPrice) {
self.products.push({
name: named || 'edit bike',
price: priced || 'edit price',
accessories: [{
name: partName || 'add part',
price: partPrice || 'add price'
}]
});
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/28686369",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Call an object using a function in R I have R objects:
"debt_30_06_2010" "debt_30_06_2011" "debt_30_06_2012" ...
and need to call them using a function:
paste0("debt_",date) ## "date" being another object
The problem is that when I assign the call to another object it takes only the name not the content:
debt_a <- paste0("endeud_", date1)
> debt_a
[1] "debt_30_06_2014"
I've tried to use the function "assign" without success:
assign("debt_a", paste0("debt_", date))
> debt_a
[1] "debt_30_06_2014"
I would like to know there is any method to achieve this task.
A: We could use get to get the value of the object. If there are multiple objects, use mget. For example, here I am assigning 'debt_a' with the value of 'debt_30_06_2010'
assign('debt_a', get(paste0('debt_', date[1])))
debt_a
#[1] 1 2 3 4 5
mget returns a list. So if we are assigning 'debt_a' to multiple objects,
assign('debt_a', mget(paste0('debt_', date)))
debt_a
#$debt_30_06_2010
#[1] 1 2 3 4 5
#$debt_30_06_2011
#[1] 6 7 8 9 10
data
debt_30_06_2010 <- 1:5
debt_30_06_2011 <- 6:10
date <- c('30_06_2010', '30_06_2011')
A: I'm not sure if I understood your question correctly, but I suspect that your objects are names of functions, and that you want to construct these names as characters to use the functions. If this is the case, this example might help:
myfun <- function(x){sin(x)**2}
mychar <- paste0("my", "fun")
eval(call(mychar, x = pi / 4))
#[1] 0.5
#> identical(eval(call(mychar, x = pi / 4)), myfun(pi / 4))
#[1] TRUE
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31501616",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to find the angle between two coordinatess in mapbox I was working on mapbox and on the basis of my current latlong, a random distance of 226mt and a random degree of 179 degrees, I calculated another latlong as follows.
function findpos(){
var ptt = new mapboxgl.LngLat(latitude,longitude);
var ptt2 = destinationPoint(179.85, 0.226, ptt);
return ptt2;
}
Number.prototype.toRad = function() {
return this * Math.PI / 180;
}
Number.prototype.toDeg = function() {
return this * 180 / Math.PI;
}
function destinationPoint(brng, dist, pointA) {
dist = dist / 6378.1;
brng = brng.toRad();
var lat1 = pointA.lat.toRad(), lon1 = pointA.lng.toRad();
var lat2 = Math.asin(Math.sin(lat1) * Math.cos(dist) +
Math.cos(lat1) * Math.sin(dist) * Math.cos(brng));
var lon2 = lon1 + Math.atan2(Math.sin(brng) * Math.sin(dist) *
Math.cos(lat1),
Math.cos(dist) - Math.sin(lat1) *
Math.sin(lat2));
if (isNaN(lat2) || isNaN(lon2)) return null;
console.log("des ",lon2,lat2);
return new mapboxgl.LngLat(lat2.toDeg(), lon2.toDeg());
}
It was okay till this point.But Now I wanted to find the angle or bearing between two latlongs and found this
// Converts from degrees to radians.
function toRadians(degrees) {
return degrees * Math.PI / 180;
};
// Converts from radians to degrees.
function toDegrees(radians) {
return radians * 180 / Math.PI;
}
function bearing(startLat, startLng, destLat, destLng){
startLat = toRadians(startLat);
startLng = toRadians(startLng);
destLat = toRadians(destLat);
destLng = toRadians(destLng);
y = Math.sin(destLng - startLng) * Math.cos(destLat);
x = Math.cos(startLat) * Math.sin(destLat) -
Math.sin(startLat) * Math.cos(destLat) * Math.cos(destLng - startLng);
brng = Math.atan2(y, x);
brng = toDegrees(brng);
return (brng + 360) % 360;
// return brng;
}
It calculates a degree and gives a result. But when i decided to double check this function by putting the already calculated latlongs by the function findpos() above, i should have got the answer as 179.85 degrees, but instead I get the angle as 270 degree.
Which part of the code is correct? I have created a working example here, and have logged the values in the console. Can anyone help me out here please?
A: You are using the mapboxgl.LngLat() function. The function name already contains the order in which it expects you to pass longitude and latitude -- > first longitude then latitude. You are passing first latitude then longitude. This will definitely cause a problem.
Your code:
function findpos(){
var ptt = new mapboxgl.LngLat(latitude,longitude);
var ptt2 = destinationPoint(179.85, 0.226, ptt);
return ptt2;
}
Try this:
function findpos(){
var ptt = new mapboxgl.LngLat(longitude,latitude);
var ptt2 = destinationPoint(179.85, 0.226, ptt);
return ptt2;
}
Similar for this part of your code:
return new mapboxgl.LngLat(lat2.toDeg(), lon2.toDeg());
A: Have a look on Turf documentation
It provide's two different methods. You can try :
http://turfjs.org/docs/#bearing
http://turfjs.org/docs/#rhumbBearing
| {
"language": "en",
"url": "https://stackoverflow.com/questions/61815979",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: .htaccess change a path to a query strings I have files in example.com/
contact.php
recent.php
videos.php
watch.php
example.com/page/ > /page/ is not a folder. but i want to work other folders
contact.php (no pagination)
example.com/page/contact
recent.php (pagination > recent.php?page=2)
example.com/page/recent
example.com/page/recent?page=2
watch.php (no pagination > watch.php?title=drama-name)
example.com/page/watch/drama-name
videos.php (pagination with get name > videos.php?name=drama-name&page=2)
example.com/page/videos/drama-name
example.com/page/videos/drama-name?page=2
Here is my full htaccess codes (example.com/.htaccess)
RewriteEngine on
RewriteBase /
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,NE,L]
RewriteRule ^page/playlist$ /playlist.php [L]
RewriteRule ^page/submit$ /submit.php [L]
RewriteRule ^page/contact$ /contact.php [L]
RewriteRule ^page/search$ /search.php [L]
RewriteRule ^page/recent$ /recent.php [L]
RewriteRule ^page/watch/([^/]+)? /watch.php?title=$1
RewriteRule ^page/videos/([^/]+)? /videos.php?name=$1
But not work in /page/videos/drama-name?page=2 how to fix it? it has another problem?
A: You can combine regex and shorten your rules in your .htaccess with QSA flag:
RewriteEngine on
RewriteBase /
# add www in host name
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*?)/?$ http://www.%{HTTP_HOST}/$1 [R=301,NE,L]
# Unless directory, remove trailing slash
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)/$ /$1 [NE,R=301,L]
RewriteRule ^page/(submit|contact|search|recent|playlist)/?$ $1.php [L,NC]
RewriteRule ^page/(videos|watch)/([^/]+)/?$ $1.php?title=$2 [L,QSA,NC]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39381679",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: putting multiple input line to the console | curses I have started to write console with Python language. It is amazing. But, I have tried to create input box with curses as shown below. I have stucked in how I can put input line and get the input written on the input place on the console. Can you help me for this part ? I forget to ask _is it possible to create input box as shown below with curses ? If not, what should I use ?
I just want to see the methods/algorithms not the whole and complete code.
sketch of console
|------------------------------------------------------|
| |
| |
| |
| |
| username ===> | // user can write name
| password ===> | // user can write password
| procedure ===> | // user can write proc name
| |
| |
| |
| |
| |
|------------------------------------------------------|
I am developing on the Linux platform ( Ubuntu 12.04 lts )
A: Somehow my previous answer got deleted...
To get user input in Python, assign a variable to the results of the built-in input() function:
user_input = input("Type something: ")
print("You typed: " + user_input)
In Python 2, the raw_input() function is also available, and is preferred over input().
To get the password without it echoing back to the screen, use the getpass module:
import getpass
user_password = getpass.getpass("Enter password: ")
I'm not that familiar with curses, but it would seem that you could position your cursor, then call input() or getpass.getpass(). Just briefly reading over the documentation, there are apparently options to turn screen echoing on and off at will, so those may be better options. Read The Fine Manual :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/15378705",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Twitter login POST request in Periscope API I am trying to use Periscope API (https://github.com/gabrielg/periscope_api/blob/master/API.md) in my application. As in the API link I am trying to send POST request to https://api.periscope.tv/api/v2/loginTwitter?build=v1.0.2
with request body as following
{
"bundle_id": "com.bountylabs.periscope",
"phone_number": "",
"session_key": "<twitter_user_oauth_key>",
"session_secret": "<twitter_user_oauth_secret>",
"user_id": "<twitter_user_id>",
"user_name": "<twitter_user_name>",
"vendor_id": "81EA8A9B-2950-40CD-9365-40535404DDE4"
}
I already have an application in https://apps.twitter.com/ but I don't know what to use as twitter_user_oauth_key and twitter_user_oauth_secret. Can you help?
A: I must say https://github.com/gabrielg/periscope_api/ implementation is a bit complicated. Author using 2 sets of keys (IOS_* and PERISCOPE_*) when you actually need only one to access API. I didn't tried to broadcast but in my PHP library all other functions works without troubles with only what he call PERISCOPE_* set of keys.
You will get session_secret and session_key from Twitter after getting access to it as Periscope application.
So Periscope's login via Twitter process looks like
*
*Request OAuth token via https://api.twitter.com/oauth/request_token
*Redirect user to https://api.twitter.com/oauth/authorize?oauth_token=[oauth_token]
*Wait for user login and get oauth_token and oauth_verifier from redirect url
*Get oauth_token, oauth_token_secret, user_id and user_name via request to https://api.twitter.com/oauth/access_token?oauth_verifier=[oauth_verifier]
*Send request to https://api.periscope.tv/api/v2/loginTwitter
{
"bundle_id": "com.bountylabs.periscope",
"phone_number": "",
"session_key": "oauth_token",
"session_secret": "oauth_token_secret",
"user_id": "user_id",
"user_name": "user_name",
"vendor_id": "81EA8A9B-2950-40CD-9365-40535404DDE4"
}
*Save cookie value from last response and add it to all JSON API calls as some kind of authentication token.
Requests in 1 and 4 steps should be signed with proper Authorization header which requires Periscope application's consumer_key and consumer_secret. While consumer_key can be sniffed right in first step (if you are able to bypass certificate pinning) consumer_secret never leaves your device and you can't get it with simple traffic interception.
There is PHP example of login process https://gist.github.com/bearburger/b4d1a058c4f85b75fa83
A: Periscope's API is not public and the library you are referring to is sort of a hack.
To answer the original question, oauth_key & oauth_secret are keys sent by your actual device to periscope service. You can find them by sniffing network traffic sent by your device.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31854771",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: docker python:3.9 image gives error for scripts We are using python:3.9 image for the base, and run some command on that.
Base Image
########################
# Base Image Section #
########################
#
# Creates an image with the common requirements for a flask app pre-installed
# Start with a smol OS
FROM python:3.9
# Install basic requirements
RUN apt-get -q update -o Acquire::Languages=none && apt-get -yq install --no-install-recommends \
apt-transport-https \
ca-certificates && \
apt-get autoremove -yq && apt-get clean && rm -rf "/var/lib/apt/lists"/*
# Install CA certs
# Prefer the mirror for package downloads
COPY ["ca_certs/*.crt", "/usr/local/share/ca-certificates/"]
RUN update-ca-certificates && \
mv /etc/apt/sources.list /etc/apt/sources.list.old && \
printf 'deb https://mirror.company.com/debian/ buster main contrib non-free\n' > /etc/apt/sources.list && \
cat /etc/apt/sources.list.old >> /etc/apt/sources.list
# Equivalent to `cd /app`
WORKDIR /app
# Fixes a host of encoding-related bugs
ENV LC_ALL=C.UTF-8
# Tells `apt` and others that no one is sitting at the keyboard
ENV DEBIAN_FRONTEND=noninteractive
# Set a more helpful shell prompt
ENV PS1='[\u@\h \W]\$ '
#####################
# ONBUILD Section #
#####################
#
# ONBUILD commands take effect when another image is built using this one as a base.
# Ref: https://docs.docker.com/engine/reference/builder/#onbuild
#
#
# And that's it! The base container should have all your dependencies and ssl certs pre-installed,
# and will copy your code over when used as a base with the "FROM" directive.
ONBUILD ARG BUILD_VERSION
ONBUILD ARG BUILD_DATE
# Copy our files into the container
ONBUILD ADD . .
# pre_deps: packages that need to be installed before code installation and remain in the final image
ONBUILD ARG pre_deps
# build_deps: packages that need to be installed before code installation, then uninstalled after
ONBUILD ARG build_deps
# COMPILE_DEPS: common packages needed for building/installing Python packages. Most users won't need to adjust this,
# but you could specify a shorter list if you didn't need all of these.
ONBUILD ARG COMPILE_DEPS="build-essential python3-dev libffi-dev libssl-dev python3-pip libxml2-dev libxslt1-dev zlib1g-dev g++ unixodbc-dev"
# ssh_key: If provided, writes the given string to ~/.ssh/id_rsa just before Python package installation,
# and deletes it before the layer is written.
ONBUILD ARG ssh_key
# If our python package is installable, install system packages that are needed by some python libraries to compile
# successfully, then install our python package. Finally, delete the temporary system packages.
ONBUILD RUN \
if [ -f setup.py ] || [ -f requirements.txt ]; then \
install_deps="$pre_deps $build_deps $COMPILE_DEPS" && \
uninstall_deps=$(python3 -c 'all_deps=set("'"$install_deps"'".split()); to_keep=set("'"$pre_deps"'".split()); print(" ".join(sorted(all_deps-to_keep)), end="")') && \
apt-get -q update -o Acquire::Languages=none && apt-get -yq install --no-install-recommends $install_deps && \
if [ -n "${ssh_key}" ]; then \
mkdir -p ~/.ssh && chmod 700 ~/.ssh && printf "%s\n" "${ssh_key}" > ~/.ssh/id_rsa && chmod 600 ~/.ssh/id_rsa && \
printf "%s\n" "StrictHostKeyChecking=no" > ~/.ssh/config && chmod 600 ~/.ssh/config || exit 1 ; \
fi ; \
if [ -f requirements.txt ]; then \
pip3 install --no-cache-dir --compile -r requirements.txt || exit 1 ; \
elif [ -f setup.py ]; then \
pip3 install --no-cache-dir --compile --editable . || exit 1 ; \
fi ; \
if [ -n "${ssh_key}" ]; then \
rm -rf ~/.ssh || exit 1 ; \
fi ; \
fi
We build this image last year, and it was working fine, but we decided to use latest changes and build new base image, once we build it, it start failing for last RUN command.
DEBU[0280] Deleting in layer: map[]
INFO[0281] Cmd: /bin/sh
INFO[0281] Args: [-c if [ -f setup.py ] || [ -f requirements.txt ]; then install_deps="$pre_deps $build_deps $COMPILE_DEPS" && uninstall_deps=$(python3 -c 'all_deps=set("'"$install_deps"'".split()); to_keep=set("'"$pre_deps"'".split()); print(" ".join(sorted(all_deps-to_keep)), end="")') && apt-get -q update -o Acquire::Languages=none && apt-get -yq install --no-install-recommends $install_deps && if [ -n "${ssh_key}" ]; then mkdir -p ~/.ssh && chmod 700 ~/.ssh && printf "%s\n" "${ssh_key}" > ~/.ssh/id_rsa && chmod 600 ~/.ssh/id_rsa && printf "%s\n" "StrictHostKeyChecking=no" > ~/.ssh/config && chmod 600 ~/.ssh/config || exit 1 ; fi ; if [ -f requirements.txt ]; then pip3 install --no-cache-dir --compile -r requirements.txt || exit 1 ; elif [ -f setup.py ]; then pip3 install --no-cache-dir --compile --editable . || exit 1 ; fi ; if [ -n "${ssh_key}" ]; then rm -rf ~/.ssh || exit 1 ; fi ; fi]
INFO[0281] Running: [/bin/sh -c if [ -f setup.py ] || [ -f requirements.txt ]; then install_deps="$pre_deps $build_deps $COMPILE_DEPS" && uninstall_deps=$(python3 -c 'all_deps=set("'"$install_deps"'".split()); to_keep=set("'"$pre_deps"'".split()); print(" ".join(sorted(all_deps-to_keep)), end="")') && apt-get -q update -o Acquire::Languages=none && apt-get -yq install --no-install-recommends $install_deps && if [ -n "${ssh_key}" ]; then mkdir -p ~/.ssh && chmod 700 ~/.ssh && printf "%s\n" "${ssh_key}" > ~/.ssh/id_rsa && chmod 600 ~/.ssh/id_rsa && printf "%s\n" "StrictHostKeyChecking=no" > ~/.ssh/config && chmod 600 ~/.ssh/config || exit 1 ; fi ; if [ -f requirements.txt ]; then pip3 install --no-cache-dir --compile -r requirements.txt || exit 1 ; elif [ -f setup.py ]; then pip3 install --no-cache-dir --compile --editable . || exit 1 ; fi ; if [ -n "${ssh_key}" ]; then rm -rf ~/.ssh || exit 1 ; fi ; fi]
error building image: error building stage: failed to execute command: starting command: fork/exec /bin/sh: exec format error
We label the image, based on date, to know when it was working, we have base image, build on 12-09-22 works fine.
Something new in python:3.9 cause this issue. Same script was working.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75375116",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Ugly LINQ statement, a better way? I have a LINQ statement which is adding up the values of multiple columns, each beginning with 'HH' although there are other columns available:
//TODO Clean up this mess
var query1 = (from e in Data
where e.SD == date
select e).Select(x => x.HH01 + x.HH16 + x.HH17 + x.HH18 + x.HH19 + x.HH20 + x.HH21 + x.HH22 + x.HH23 +
x.HH24 + x.HH25 + x.HH26 + x.HH27 + x.HH28 + x.HH29 + x.HH30 + x.HH31 + x.HH32 +
x.HH33 + x.HH34 + x.HH35 + x.HH36 + x.HH37 + x.HH38 + x.HH39 + x.HH40 + x.HH41 +
x.HH42 + x.HH43 + x.HH44 +x.HH45 + x.HH46 + x.HH47 + x.HH48 + x.HH49.GetValueOrDefault()+
x.HH50.GetValueOrDefault());
return query1.FirstOrDefault();
Is there any way to tidy this up? I have to do lots of variations of this (in different methods) so it would clear out a lot of 'fluff' if it could be.
Also I'd like to call .GetValueOrDefault() on each column, but currently I've taken this out due to the mess except for the last two columns.
Suggestions much appreciated!
A: I guess you can use Reflections for this:
double GetHHSum<T>(T x) where T : class
{
double result = 0;
var properties = typeof(T).GetProperties();
foreach (var property in properties)
{
if (property.Name.StartsWith("HH"))
sum += Convert.ToSingle(property.GetValue(x)).GetValueOrDefault();
}
return result;
}
And then use it like this:
return (from e in Data
where e.SD == date
select e).ToList().Select(x => GetHHSum(x)).FirstOrDefault();
Code is not tested
A: I might be wrong because I don't know your data, but it seems to me that they are not fully normalized (repetitive attributes).
You might consider going to the 3rd form normal - thus create a/some separate table that will contain one value by row - and then to join your 2 tables in your linq query.
The link query will look much much better, and you will later be able to change your HH fields without changing your queries.
A: One suggestion is to refactor the above code to use LINQ method chains and lambdas (personal preference), then extract the select lambda into a separate method. For instance:
// Note select e and .Select(x => x..) is redundant. Only need one
var query1 = Data.Where(e => e.SD == date).Select(SumOfHValues);
return query1.FirstOrDefault();
// Note types are unclear in your question so I've put dummy placeholders
private static QueryResultType SumOfHValues(YourInputClassType x)
{
// Nothing wrong with this syntactically, it will be faster than a
// reflection solution
//
// Algorithmic code tends to have this sort of look & feel.
// You could make it more readable
// by commenting exactly what the summation is doing and
// with a mathematical notation or link to documentation / web source
return x.HH01 + x.HH16 + x.HH17 + x.HH18 +
x.HH19 + x.HH20 + x.HH21 + x.HH22 +
x.HH23 + x.HH24 + x.HH25 + x.HH26 +
x.HH27 + x.HH28 + x.HH29 + x.HH30 +
x.HH31 + x.HH32 + x.HH33 + x.HH34 +
x.HH35 + x.HH36 + x.HH37 + x.HH38 +
x.HH39 + x.HH40 + x.HH41 + x.HH42 +
x.HH43 + x.HH44 + x.HH45 + x.HH46 +
x.HH47 + x.HH48 +
x.HH49.GetValueOrDefault() +
x.HH50.GetValueOrDefault()
}
In addition if you wanted to call GetValueOrDefault() on each HHxx property you could wrap this in a further helper function. this really boils down to code preference. Which do you prefer? Seeing .GetValueOrDefault() on the end of each property access or a function around it? e.g.
return x.HH01 + x.HH16 + x.HH17 + x.HH18
becomes
return Get(x.HH01) + Get(x.HH16) + Get(x.HH17) + Get(x.HH18) ...
private static HClassType Get(HClassType input)
{
return input.GetValueOrDefault();
}
Personally I would just go with ordering my HHxx + HHyy code in columns and calling .GetValueOrDefault() on each one. If it's put in a helper method at least its only written once, even if it is verbose.
Best regards,
| {
"language": "en",
"url": "https://stackoverflow.com/questions/8909055",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Making formulas to somehow automate my data binding in a inventory system I wanna extract some specific values in a string
For example, in the table below, i wanna automate the extraction of Unit of Measure and Pack Size based on the data on ITEM column.
ITEM
Unit of Measure
Pack Size
BRAND A 2X6X150ML
ML
150
BRAND B 4X3X25G
G
25
BRAND C 12X30ML
ML
30
BRAND D 12X1.5L
L
1.5
Specifically, i want to automate the Pack Size column to fetch the numeric values after the non-numeric value from the right.
I have tried using RIGHT function for this instance. I somehow fetched and automate the values in the Unit of Measure correctly using right(cell, 2) but i need to do some data cleaning because single characters like G and L arent 2 characters.
A: This formula works for your data set. It extracts everything after the last X in the Item and removes the Unit of Measure text as it is specified in the second column.
=SUBSTITUTE(RIGHT(A2,LEN(A2)-FIND("@",SUBSTITUTE(A2,"X","@",LEN(A2)-LEN(SUBSTITUTE(A2,"X",""))),1)),B2,"")+0
A: With O365 you have the following approach in cell C1:
=LET(x, TEXTAFTER(A2:A5,"X", -1), size, TEXTSPLIT(x, {"ML","G","ML","L"}),
unit, SUBSTITUTE(x, size, ""), VSTACK({"Unit of Measure","Pack Size"},
HSTACK(unit, size)))
Here is the output, it generates the header, and extract the unit of measure and the pack size, spilling the entire output at once:
It assumes the information to find comes after the first X character in reverse order. If you want the pack size as numeric, then replace size inside HSTACK with: 1*size.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75330774",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Angular how to enable/disable form but prefer attribute value on single controls? Let's see the next simple code snippet
@Component({
selector: 'app'
template: `
<form #form>
<input name="car" [(ngModel)]="car" [disabled]="true" />
<input name="bottle" [(ngModel)]="bottle" />
<button (click)="form.disable()">Disable Form</button>
<button (click)="form.enable()">Enable Form</button>
</form>
`
})
class AppComponent {
car: string;
bottole: string;
}
if click on enable/disable the state of the form will be updated and the [disabled] attribute on the car input will be ignored.
In my code, I have create appForm directive to manage state of controls on the form, f.e.
<form appForm [disabled]="canEdit"></form>
and in directive in ngOnChanges if disabled changed the form.enable()/form.disable() called, but there is an issue, that like on the first code snippet above, all the controls disabled, and [disabled] bindings are ignored.
Is it possible somehow to enable/disable form, but with disabled attribute higher prioirity for children controls? I thought about something like this
if(disabled) {
this.form.disable();
} else {
this.form.enable();
}
this.form.updateDisableStateFromAttributes();
So for clarity if it is the first code snippet, then enable/disable buttons should enable/disable all controls, but the car should be always disabled, because attribute disabled is set to true
| {
"language": "en",
"url": "https://stackoverflow.com/questions/70927421",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is this error an encoding error? How do I solve it? I am doing web scraping.
Below is the code I used.
I wrote few comments on the comment.
library(httr)
library(rvest)
library(stringr)
# Bulletin board url
List.of.questions.url<- 'http://kin.naver.com/qna/list.nhn?m=noanswer&dirId=70108'
# Vector to store title and body
answers <- c()
# get the posts from page 1 to page 2.
for(i in 1:2){
url <- modify_url(List.of.questions.url, query=list(page=i))
list <- read_html(url, encoding = 'utf-8') #I think I encoded, but I'm getting an error.
# Gets the url of the post.
# TLS = title.links, CLS = content.links
TLS <- html_nodes(list, '.basic1 dt a')
CLS <- html_attr(TLS, 'href')
CLS <- paste0("http://kin.naver.com",CLS)
#Gets the required properties.
for(link in CLS){
h <- read_html(link)
# answer
answer <- html_text(html_nodes(h, '#contents_layer_1'))
answer <- str_trim(repair_encoding(answer)) #I think I encoded, but I'm getting an error.
answers<-c(answers,answer)
print(link)
}
}
However, this error occurs while scraping.
Maybe it's about encoding.
(But as I wrote in the comments, I think I did the encoding properly.)
[1] "http://kin.naver.com/qna/detail.nhn?d1id=7&dirId=70111&docId=280474910"
Error: No guess has more than 50% confidence
In addition: There were 43 warnings (use warnings() to see them)
> warnings()
1: In stringi::stri_conv(x, from = from) :
the Unicode codepoint \U000000a0 cannot be converted to destination encoding
2: In stringi::stri_conv(x, from = from) :
the Unicode codepoint \U000000a0 cannot be converted to destination encoding
3: In stringi::stri_conv(x, from = from) :
the Unicode codepoint \U000000a0 cannot be converted to destination encoding
4: In stringi::stri_conv(x, from = from) :
the Unicode codepoint \U000000a0 cannot be converted to destination encoding
5: In stringi::stri_conv(x, from = from) :
#All the same contents, so omitted
How do I fix it?
Thank you for your advice
| {
"language": "en",
"url": "https://stackoverflow.com/questions/45126399",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Groovy elegant solution for avg array str = """
0.6266197101540969 , 0.21279720289932263 , 0.7888811159800816 , 0.3374125902260934 , 0.8299999833106995 , 0.4300000071525574 , 0.6000000238418579 , 0.1599999964237213
0.6286013903734567 , 0.21750000088165203 , 0.780979019361776 , 0.33202797309918836 , 0.8299999833106995 , 0.4300000071525574 , 0.6000000238418579 , 0.1599999964237213
0.6211805507126782 , 0.20285714375121253 , 0.7563043448372163 , 0.32666666932562566 , 0.8299999833106995 , 0.4300000071525574 , 0.6000000238418579 , 0.1599999964237213
0.5912230165956689 , 0.20713235388564713 , 0.7197058783734546 , 0.31335821047202866 , 0.8299999833106995 , 0.4300000071525574 , 0.6000000238418579 , 0.1599999964237213
0.6073239363834891 , 0.21000000010145473 , 0.7486428560955184 , 0.3176595757827691 , 0.8070422478125129 , 0.41928571494562283 , 0.5272857129573822 , 0.18029411882162094
0.6049999973513711 , 0.204892086360952 , 0.7618382347418982 , 0.3195035475577023 , 0.8021985744753628 , 0.44760563193072733 , 0.5268794330933415 , 0.18000000185320075
0.6292380872226897 , 0.1993396225965248 , 0.7613461521955637 , 0.3325471729040146 , 0.8194392418192926 , 0.4333644839369248 , 0.5276415085174003 , 0.180841121927043
"""
i need to count num of items in row, create array for it, then the array should have the sum of each colounm
end result:
//no saying this is the actualt avg of the colunm just pointing out...
sumArray = [0.62,0.41,0.61, ....]
averageTests = returnAvg(data)
println(averageTests)
def returnAvg(tmpData){
tmpData = tmpData.replaceAll("( )+", "")
def avgs = []//will hold array of avg
numOfDaysTest=tmpData.split("\n").size()
for (line in tmpData.split("\n")){
index=0
for (value in line.split(",")){
if (avgs[index] == null){
avgs[index] = 0
}
tmpnum = value as Double
avgs[index] += tmpnum
index++
}
}
for (i=0; i<avgs.size(); i++){
tmp = (avgs[i]/numOfDaysTest).toString()
avgs[i] = tmp.substring(0,tmp.indexOf('.')+3)
}
return avgs
}
the end result is ok but im sure theres a much more elegant way?
A: This one-liner must certainly be possible to further simplify, but I haven't managed to come up with one that's readable. I'm sure you can improve it.
def means = str.trim().split('\n')*.split(',').collect{it*.trim().collect{e -> new BigDecimal(e)}.withIndex()}.collect{e -> e.collect{ee->[(ee[1]): [ee[0]]].entrySet()}}.flatten().groupBy{it.key}.collectEntries{key, val -> [(key):val*.value.flatten().average()]}
With your test input, it produces
[0:0.6155980983990644, 1:0.20778834435382369, 2:0.7596710859407870,
3:0.32559653419534601, 4:0.8212399996214238, 5:0.43146512277478637,
6:0.5688295357050794, 7:0.16873360404239284]
Where the keys are the column indices and the values are the corresponding means.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/71377491",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Dropdown remains empty -populating with json data Hi im populating dropdown on change event of another dropdown from sql server using json data,
I got json data when i checked in firefox
but still my dropdown remains empty
Could somebody please help me what im doing wrong here
here is my code
function OnCathwordPopulated(response) {
var xx = (typeof response.d) == 'string' ? eval('(' + response.d + ')') : response.d;
$("#<%=ddlCatchword.ClientID %>").removeAttr("disabled");
$("#<%=ddlCatchword.ClientID %>").children().remove();
$("#<%=ddlCatchword.ClientID %>").empty().append("<option selected='selected' value='0'>Please select</option>");
var listItems = "";
for (var i = 0; i < xx.length; i++) {
var val1 = xx[i];
var text1 = xx[i];
listItems += "<option value='" + val1+ "'>" + text1 + "</option>";
} $("#<%=ddlCatchword.ClientID%>").html(listItems);
}
I used another method also
here is
$("#<%=ddlCatchword.ClientID%>").append($("<option></option>").val(val1).text(text));
A: Modded the code to remove properly. I'm assuming this is selecting the correct list based off the code above. Also, a fiddle for example: http://jsfiddle.net/Tkt2B/
$("#<%=ddlCatchword.ClientID %>").removeAttr("disabled");
$("#<%=ddlCatchword.ClientID %>").find("option").remove().end()
$("#<%=ddlCatchword.ClientID %>").append("<option selected='selected' value='0'>Please select</option>");
var listItems = "";
for (var i = 0; i < xx.length; i++) {
var val1 = xx[i];
var text1 = xx[i];
listItems += "<option value='" + val1+ "'>" + text1 + "</option>";
}
$("#<%=ddlCatchword.ClientID%>").append(listItems);
A: I have tried this method to test out data
var h = ' <select name="test" id="ss" class="country" data-native-menu="false">';
h = h + listItems;
var w = window.open(); $(w.document.body).html(h);
And it opens new dropdwon with all json data in new window..
I dont know what strange thing is wrong ...
please note im using jquery mobile using asp.net
A: it solved by using following trick,
$("#<%=ddlCatchword.ClientID%>").html(listItems); $("#<%=ddlCatchword.ClientID%>").selectmenu('refresh', true);
Got it working with the help from http://ozkary.blogspot.no/2010/12/jquery-mobile-select-controls-populated.html
Thanks!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/15411480",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: os to remove files with Python (trying to removed from multiple file directories) I'm still very new to Python so I'm trying to apply Python in to my own situation for some experience
One useful program is to delete files, in this case by file type from a directory
import os
target = "H:\\documents\\"
for x in os.listdir(target):
if x.endswith(".rtf"):
os.unlink(target + x)
Taking this program, I have tried to expand it to delete ost files in every local profiles:
import os
list = []
folder = "c:\\Users"
for subfolder in os.listdir(folder):
list.append(subfolder)
ost_folder = "c:\\users\\%s\\AppData\\Local\\Microsoft\\Outlook"
for users in list:
ost_list = os.listdir(ost_folder%users)
for file in ost_list:
if file.endswith(".txt"):
print(file)
This should be printing the file name but spits an error that the file directory cannot be found
A: Not every folder under C:\Users will have a AppData\Local\Microsoft\Outlook subdirectory (there are typically hidden directories there that you may not see in Windows Explorer that don't correspond to a real user, and have never run Outlook, so they don't have that folder at all, but will be found by os.listdir); when you call os.listdir on such a directory, it dies with the exception you're seeing. Skip the directories that don't have it. The simplest way to do so is to have the glob module do the work for you (which avoids the need for your first loop entirely):
import glob
import os
for folder in glob.glob(r"c:\users\*\AppData\Local\Microsoft\Outlook"):
for file in os.listdir(folder):
if file.endswith(".txt"):
print(os.path.join(folder, file))
You can simplify it even further by pushing all the work to glob:
for txtfile in glob.glob(r"c:\users\*\AppData\Local\Microsoft\Outlook\*.txt"):
print(txtfile)
Or do the more modern OO-style pathlib alternative:
for txtfile in pathlib.Path(r'C:\Users').glob(r'*\AppData\Local\Microsoft\Outlook\*.txt'):
print(txtfile)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/72532708",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
} |
Q: SQL Server Interest calculations on transactions I'm looking for advice on best way to build a compound interest module in SQL server. Basic set up:
Table: Transactions {TransID, MemberID, Trans_Date, Trans_Code, Trans_Value).
Table: Interest {IntID, Int_eff_Date, Int_Rate}
In the interest table, there may be different rates with an effective date - can never have an over lapping date though. For example:
Int_Eff_Date Int_Rate
01/01/2016 7%
01/10/2016 7.5%
10/01/2017 8%
I want to calculate the interest based on the transaction date and transaction value, where the correct interest rate is applied relative to transaction date.
So if Table transaction had:
TransID MemberID Trans_Date Trans_Value
1 1 15/04/2016 150
2 1 18/10/2016 200
3 1 24/11/2016 200
4 1 15/01/2017 250
For transID 1 it would use 7% from 15/04/2016 until 30/09/2016 (168 days) from 1/10/2016 to 09/01/2017 it would use 7.% and then from 10/01/2007 to calculation date (input parameter) it would use 8%.
It would apply similar methodology for all transactions, add them up and display the interest value.
I'm not sure if I should use cursors, UDF, etc.
A: This should provide an outline of what you're trying to do.
--Build Test Data
CREATE TABLE #Rates(Int_Eff_Date DATE
, Int_Rate FLOAT)
CREATE TABLE #Transactions(TransID INT
,MemberID INT
,Trans_Date DATE
,Trans_Value INT)
INSERT INTO #Rates
VALUES ('20160101',7)
,('20161001',7.5)
,('20170110',8)
INSERT INTO #Transactions
VALUES
(1,1,'20160415',150)
,(2,1,'20161018',200)
,(3,1,'20161124',200)
,(4,1,'20170115',250)
;WITH cte_Date_Rates
AS
(
SELECT
S.Int_Eff_Date
,ISNULL(E.Int_Eff_Date,'20490101') AS "Expire"
,S.Int_Rate
FROM
#Rates S
OUTER APPLY (SELECT TOP 1 Int_Eff_Date
FROM #Rates E
WHERE E.Int_Eff_Date > S.Int_Eff_Date
ORDER BY E.Int_Eff_Date) E
)
SELECT
T.*
,R.Int_Rate
FROM
#Transactions T
LEFT JOIN cte_Date_Rates R
ON
T.Trans_Date >= R.Int_Eff_Date
AND
T.Trans_Date < R.Expire
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41852136",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Different format JSON deserializing to object I have a memory stream of data I have received from Poloniex's API.
https://docs.poloniex.com/#ticker-data
The data in the API looks in the format below:
[
1002,
null,
[
149,
"382.98901522",
"381.99755898",
"379.41296309",
"-0.04312950",
"14969820.94951828",
"38859.58435407",
0,
"412.25844455",
"364.56122072",
0,
0
]
]
I can see that this is valid json on https://jsonlint.com/
My end goal is I want to deserialize this into an object in C# which I can send elsewhere.
I've never seen JSON like this before and unsure how I would deserialize this structure into my own model. I'm used to see JSON as keyvaluepairs
I've deserialized into a JArray and going from there but I'm unsure of the best approach.
var deserialized =
(JArray)_serializer.Deserialize(new JsonTextReader(new StreamReader(stream))
{
CloseInput = false
});
What would be the best way to do this?
Example model structure to deserialize into:
public class PoloniexResponseDataRoot
{
public List<PoloniexResponseDataParent> Children { get; set; }
}
public class PoloniexResponseDataParent
{
public int ChannelNumber { get; set; }
public int? OtherNumber { get; set; }
public List<PoloniexResponseDataChild> Children { get; set; }
}
public class PoloniexResponseDataChild
{
public object Data { get; set; }
}
Thanks
A: This JSON is basically an Array of objects.
List<object> items = _serializer.Deserialize<List<object>>(jsonString);
You could then create a new class and assign the object to the class
Or simple use it as it.
A: If your structure is as simple as the one in your example and that the first 2 numbers always represent ChannelNumber and OtherNumber followed by 1 level array, then you can do something like this:
private static PoloniexResponseDataParent Parse(JArray objects)
{
var parent = new PoloniexResponseDataParent();
var channelNumber = objects[0];
var otherNumber = objects[1];
var children = objects[2];
parent.ChannelNumber = Convert.ToInt32(channelNumber);
parent.OtherNumber = (otherNumber as JValue).Value<int?>();
parent.Children = children.Select(item => new PoloniexResponseDataChild
{
Data = item switch
{
JValue jValue => jValue.Value,
_ => throw new ArgumentOutOfRangeException(nameof(item))
}
}).ToList();
return parent;
}
var jArray = Newtonsoft.Json.JsonConvert.DeserializeObject<JArray>(jsonStr);
var parent = Parse(jArray);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/67813753",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Meteor: Update across all browsers I'm working on my first Meteor app, but I can't figure out how I can update something across all browsers.
This is the situation: When one person is typing, I want to display "typing..." across all browsers (so to each user), but I can't figure out how to do that.
This is my code so far:
Messages = new Meteor.Collection("messages");
if( Meteor.isClient ) {
// Templating
Template.messages.entries = function() {
return Messages.find();
};
// Events
Template.messages.events({
'click #new_post' : function() {
var new_message = document.getElementById("new_message").value;
if( new_message.length > 0 ) {
Messages.insert({ text: new_message });
document.getElementById("new_message").value = "";
}
},
'focus #new_message' : function() {
// Say "typing..."
},
'blur #new_message' : function() {
// Say nothing
}
});
}
As you can see, I want to say: typing when a textfield is focussed. Now I tried this before (but it didn't work out):
'focus #new_message' : function() {
// Say "typing..."
Template.messages.typing = function() {
return "typing...";
};
},
But it didn't update my HTML. I got the {{typing}} tag in my template and it's the template messages, so that's right. But it won't update..
You guys have a clue?
A: only Collections are synced across browsers with publish/subscribe in Meteor.
Maybe you can have something like a Users collection with an is_typing field and create a reactive template helper with it?
Very basic example:
Template.messages.is_typing = function() {
return Users.find({is_typing:true}).count() > 0
};
and in the template
<template name="messages">
{{#if is_typing}}
typing
{{else}}
idle
{{/if}}
</template>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/12603145",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Android fixed RTL and LTR orientation Hi Im building an app in my native language which is rtl orientation Is there a way to make all supported devices to show the same UI not depending on ltr or rtl orientation?
A: RTL support was introduced in Android 4.2 (API 17). You can specify android:layoutDirection="rtl" for all top layouts of your app. By default, it will be inherited by all child layouts and views.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/53398385",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Would using the std::vector object for DSP applications be ineffiecient? I'm currently trying to implement some DSP algorithms using C++ and am curious as to whether or not I'm being efficient.
I'm specifically trying to design a 'DigitalFilter' class which will produce a filtered output when given a series of inputs. Now the issue that I'm facing is that the size of the filter (i.e. the number of filter coefficients) can vary. Thus the size of the a DigitalFilter class instance will vary. So for example, one instance of DigitalFilter may only need to hold 4 filter coefficients, while another may need to hold 90 filter coefficients.
The obvious and easy way to hold these coefficients would be to hold them using the std::vector object. This object essentially can vary in size, which seems like it would be appropriate for my application.
However, I also know that this implemented using heap allocated memory (as opposed to stack memory). Thus, once I set up my filter and start using it to do mathematically intensive calculations, it will constantly be referencing heap data. I realize the expensiveness typically associated with vectors is the need to completely reallocate memory location in case the vector becomes too big to fit in its original place in memory, however, this shouldn't be a big concern in my application because none of the vectors will be sized before filtering operations begin. However, I'm still curious about the efficiency.
So my question(s): What kind of time hit would be involved with referencing heap data vs stack data? Is it possible that the processor's cache memory hold onto this heap data for faster access?
A: The access time of heap memory versus stack memory is the same on any standard PC hardware.
Since you are not resizing the vector in your filtering algorithm, you can specify the size of the vector when you create it:
std::vector<int> coef(90);
You could also use an array directly.
int * coef = new int[90];
A: Your point is moot. I assure you, handling data for DSP within std::vector is not only perfectly possible, it's also commonly done – for example, GNU Radio and its highly optimized DSP primitive library, libVOLK, use vectors extensively.
There's a lot of very strange literature that suggests that heap and stack memory behave differently – that's absolutely not the case on any platform that I've worked with (those are limited to x86, x86_64, ARMv7, and H8300 so far) and you can safely disregard these.
Memory is memory, and the memory controller/cache controller of your CPU will keep locally what was used last/most frequently. As long as your memory model is sequential (Bjarne Stroustrup has held a nice presentation with the topic "I don't know your data structure, but I'm sure my vector will kick its ass"), your CPU cache will hold it locally if you access it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40451126",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Unable to Find Mean and Var in Single Kernel Code Dear Scholars,
I am unable to implement mean and var in single kernel call.
Goal: I need to find mean and var of sub matrixs in a matrix. so I wrote following kernels
functions:
global void kernelMean(d_a, d_mean, ...);
global void kernelVar(d_a, d_var, ...);
global void kernelMeanVar(d_a, d_mean, d_var,...);
Issue:
a) if I compute the kernelMean and kernelVar individually it works fine
b) if I want to compute kernelMeanVar in single kernel is does not work.
Below is my code, kindly let me know on possible any errors.
Thanking you in advance.
Regards,
Nagaraju
global void kernelMean(float* device_array, float* device_mean, int globalRows, int globalCols,int localRows,int localCols, int numRowElts, int total_num_threads)
{
int block_id = blockIdx.x + gridDim.x * blockIdx.y;
int thread_id = (blockDim.x*blockDim.y)* block_id + threadIdx.x;
int my_rowIdx = thread_id/globalCols ;
int my_colIdx = thread_id%globalCols ;
int i,j;
float temp;
float sum = 0;
float sumsq = 0.0;
float mean;
float ltotal_elts = (float) (localRows*localCols);
device_mean[thread_id] = 0;
if(thread_id <total_num_threads)
{
for(i=0; i < localRows ; i++)
{
for(j=0 ; j < localCols; j++)
{
temp = device_array[(i+ my_rowIdx)*numRowElts + (j+ my_colIdx)];
sumsq = sumsq + (temp*temp);
sum = sum + temp;
}
}
mean = sum/ltotal_elts;
device_mean[thread_id] = mean;
}
}
global void kernelVar(float* device_array,float* device_var, int globalRows, int globalCols,int localRows,int localCols, int numRowElts, int total_num_threads)
{
int block_id = blockIdx.x + gridDim.x * blockIdx.y;
int thread_id = (blockDim.x*blockDim.y)* block_id + threadIdx.x;
int my_rowIdx = thread_id/globalCols ;
int my_colIdx = thread_id%globalCols ;
int i,j;
float temp;
float sum = 0;
float sumsq = 0;
float mean = 0;
float var = 0;
float ltotal_elts = (float) localRows*localCols;
device_var[thread_id] = 0;
if(thread_id < total_num_threads)
{
for(i=0; i < localRows ; i++)
{
for(j=0 ; j < localCols; j++)
{
temp = device_array[(i+ my_rowIdx)*numRowElts + (j+ my_colIdx)];
sum = sum + temp;
sumsq = sumsq + (temp*temp);
}
}
mean = sum/ltotal_elts;
device_var[thread_id] = (sumsq/ltotal_elts) - (mean*mean);
}
}
global void kernelMeanVar(float* device_array, float* device_mean,float* device_var, int globalRows, int globalCols,int localRows,int localCols, int numRowElts, int total_num_threads)
{
int block_id = blockIdx.x + gridDim.x * blockIdx.y;
int thread_id = (blockDim.x*blockDim.y)* block_id + threadIdx.x;
int my_rowIdx = thread_id/globalCols ;
int my_colIdx = thread_id%globalCols ;
int i,j;
float temp;
float sum = 0;
float sumsq = 0.0;
float mean;
float ltotal_elts = (float) (localRows*localCols);
device_mean[thread_id] = 0;
device_var[thread_id] = 0;
if(thread_id < total_num_threads)
{
for(i=0; i < localRows ; i++)
{
for(j=0 ; j < localCols; j++)
{
temp = device_array[(i+ my_rowIdx)*numRowElts + (j+ my_colIdx)];
sumsq = sumsq + (temp*temp);
sum = sum + temp;
}
}
mean = sum/ltotal_elts;
device_mean[thread_id] = mean;
device_var[thread_id] = (sumsq/ltotal_elts) - (mean*mean);
}
}
Kernel Call Functions
void convertToFloat(float** float_ary, double* double_ary, int num_elts)
{
for(int i = 0; i < num_elts ; i++)
{
(*float_ary)[i] = (float) double_ary[i];
//printf("float_ary[%d] : %f \n", i, (*float_ary)[i]);
}
return;
}
void convertToDouble(double** double_ary, float* float_ary, int num_elts)
{
for(int i = 0; i < num_elts ; i++)
{
(*double_ary)[i] = (double) float_ary[i];
}
return;
}
void computeMeanAndVarArray(double* host_array, int num_elts, int globalRows, int globalCols, int localRows, int localCols, int numRowElts, double** mean_ary, double** var_ary)
{
float* host_array_float;
float* device_array;
float* host_mean;
float* host_var;
float* device_mean;
float* device_var;
double total_bytes =0;
host_array_float = (float*) malloc (num_elts*sizeof(float));
convertToFloat(&host_array_float, host_array, num_elts);
//printf("num_elts %d \n", num_elts);
cudaMalloc((void**) &device_array, sizeof(float)* num_elts);
cudaMemset(device_array, 0, sizeof(float)* num_elts);
cudaMemcpy(device_array, host_array_float,sizeof(float)* num_elts, cudaMemcpyHostToDevice);
int numBlockThreads = MAX_THREADS_PER_BLOCK;
int num_blocks = 0;
int remain_elts = 0;
int total_num_threads = globalRows * globalCols;
cudaMalloc((void**) &device_mean, sizeof(float)* total_num_threads);
cudaMemset(device_mean, 0, sizeof(float)* total_num_threads);
cudaMalloc((void**) &device_var, sizeof(float)* total_num_threads);
cudaMemset(device_var, 0, sizeof(float)* total_num_threads);
num_blocks = total_num_threads/numBlockThreads;
remain_elts = total_num_threads%numBlockThreads;
if(remain_elts > 0)
{
num_blocks++;
}
dim3 gridDim(num_blocks,1);
dim3 blockDim(numBlockThreads,1);
//kernelMean<<< gridDim,blockDim >>>(device_array, device_mean,globalRows, globalCols, localRows,localCols, numRowElts, total_num_threads);
//kernelVar<<< gridDim,blockDim >>>(device_array, device_var,globalRows, globalCols, localRows,localCols, numRowElts, total_num_threads);
kernelMeanVar<<< gridDim,blockDim >>>(device_array, device_mean, device_var,globalRows, globalCols, localRows,localCols, numRowElts, total_num_threads);
host_mean = (float*) malloc( sizeof(float) * total_num_threads);
memset(host_mean, 0, sizeof(float) * total_num_threads);
host_var = (float*) malloc( sizeof(float) * total_num_threads);
memset(host_var, 0, sizeof(float) * total_num_threads);
cudaThreadSynchronize();
cudaError_t error = cudaGetLastError();
//if(error!=cudaSuccess) {
printf("ERROR: %s\n", cudaGetErrorString(error) );
//}
cudaMemcpy(host_mean, device_mean, sizeof(float)*total_num_threads, cudaMemcpyDeviceToHost);
convertToDouble(mean_ary, host_mean, total_num_threads);
cudaMemcpy(host_var, device_var, sizeof(float)*total_num_threads, cudaMemcpyDeviceToHost);
for(int i = 0 ; i < 300 ; i++)
printf("host_var[%d] %f \n",i, host_var[i]);
convertToDouble(var_ary, host_var, total_num_threads);
cudaFree(device_array);
cudaFree(device_mean);
cudaFree(device_var);
free(host_mean);
free(host_var);
free(host_array_float);
}
Results with enabling
global void kernelMean(d_a, d_mean, ...);
global void kernelVar(d_a, d_var, ...);
ERROR: no error
host_var[0] 4.497070
host_var[1] 5.061768
host_var[2] 5.687500
host_var[3] 6.347534
host_var[4] 6.829102
host_var[5] 12.940308
host_var[6] 14.309937
host_var[7] 15.141113
host_var[8] 18.741577
host_var[9] 21.323608
host_var[10] 21.727417
host_var[11] 192.348389
host_var[12] 579.911621
host_var[13] 800.821045
host_var[14] 1071.960938
host_var[15] 1077.261719
host_var[16] 993.262207
host_var[17] 924.379883
host_var[18] 839.437012
host_var[19] 810.847656
host_var[20] 835.007813
host_var[21] 1124.365723
host_var[22] 1241.685547
host_var[23] 1376.504150
host_var[24] 1196.745850
host_var[25] 1097.473877
host_var[26] 1008.840088
host_var[27] 867.585083
host_var[28] 794.241699
host_var[29] 1322.409790
host_var[30] 1556.029785
host_var[31] 1564.997803
host_var[32] 1870.985840
host_var[33] 1929.829590
host_var[34] 1822.189453
host_var[35] 1662.321777
host_var[36] 1372.886719
host_var[37] 1074.727539
host_var[38] 833.003906
host_var[39] 632.514648
host_var[40] 380.227539
host_var[41] 87.345703
host_var[42] 82.544922
host_var[43] 78.756836
host_var[44] 68.541016
host_var[45] 61.981445
host_var[46] 60.413086
host_var[47] 60.128906
host_var[48] 59.767578
host_var[49] 59.223633
host_var[50] 56.569336
host_var[51] 53.866211
host_var[52] 51.186523
host_var[53] 55.270508
host_var[54] 59.956055
host_var[55] 66.516602
host_var[56] 70.348633
host_var[57] 71.706055
host_var[58] 70.494141
host_var[59] 69.897461
host_var[60] 66.286133
host_var[61] 67.926758
host_var[62] 160.753906
host_var[63] 447.221191
host_var[64] 831.740723
host_var[65] 1076.513672
host_var[66] 1193.666992
host_var[67] 1208.239746
host_var[68] 1126.845947
host_var[69] 948.397461
host_var[70] 669.399414
host_var[71] 340.465576
host_var[72] 67.161865
host_var[73] 7.421082
host_var[74] 5.485626
host_var[75] 5.135620
host_var[76] 3.460419
host_var[77] 3.853577
host_var[78] 5.221100
host_var[79] 5.890381
host_var[80] 7.139618
host_var[81] 7.517609
host_var[82] 6.865875
host_var[83] 5.053909
host_var[84] 2.781616
host_var[85] 2.021912
host_var[86] 2.130417
host_var[87] 3.113586
host_var[88] 4.024399
host_var[89] 4.582413
host_var[90] 4.077118
host_var[91] 3.024384
host_var[92] 2.287506
host_var[93] 1.793579
host_var[94] 1.567474
host_var[95] 1.829895
host_var[96] 2.325928
host_var[97] 3.429993
host_var[98] 3.885559
host_var[99] 3.835602
host_var[100] 5.566406
host_var[101] 8.065582
host_var[102] 18.767456
host_var[103] 35.395599
host_var[104] 64.148407
host_var[105] 125.937866
host_var[106] 176.445618
host_var[107] 216.073059
host_var[108] 272.109985
host_var[109] 307.972412
host_var[110] 289.652344
host_var[111] 238.253662
host_var[112] 178.304932
host_var[113] 116.925049
host_var[114] 74.773926
host_var[115] 61.227295
host_var[116] 55.238525
host_var[117] 55.387451
host_var[118] 49.241699
host_var[119] 38.396240
host_var[120] 28.304932
host_var[121] 20.225342
host_var[122] 18.043457
host_var[123] 21.418457
host_var[124] 26.120117
host_var[125] 25.899414
host_var[126] 26.641602
host_var[127] 23.747437
host_var[128] 18.927368
host_var[129] 21.664307
host_var[130] 142.432373
host_var[131] 1575.141602
host_var[132] 2901.855957
host_var[133] 4195.149902
host_var[134] 5047.758789
host_var[135] 5450.164063
host_var[136] 5249.767578
host_var[137] 4577.365234
host_var[138] 3352.496094
host_var[139] 1641.593750
host_var[140] 352.242188
host_var[141] 224.824219
host_var[142] 194.578125
host_var[143] 178.875000
host_var[144] 175.148438
host_var[145] 174.117188
host_var[146] 172.707031
host_var[147] 169.578125
host_var[148] 176.308594
host_var[149] 181.968750
host_var[150] 191.507813
host_var[151] 198.500000
host_var[152] 206.824219
host_var[153] 213.273438
host_var[154] 220.312500
host_var[155] 218.859375
host_var[156] 213.941406
host_var[157] 205.474609
host_var[158] 190.722656
host_var[159] 178.414063
host_var[160] 169.302734
host_var[161] 3.750366
host_var[162] 4.333252
host_var[163] 4.901855
host_var[164] 5.527466
host_var[165] 6.201782
host_var[166] 11.921631
host_var[167] 14.135376
host_var[168] 14.885864
host_var[169] 19.083618
host_var[170] 21.290283
host_var[171] 21.415649
host_var[172] 209.747559
host_var[173] 580.304932
host_var[174] 800.949951
host_var[175] 1119.857422
host_var[176] 1129.382324
host_var[177] 1032.616211
host_var[178] 972.797363
host_var[179] 915.440918
host_var[180] 905.890137
host_var[181] 943.649902
host_var[182] 1207.445801
host_var[183] 1345.912109
host_var[184] 1478.704590
host_var[185] 1224.895508
host_var[186] 1105.403564
host_var[187] 1031.981201
host_var[188] 914.456421
host_var[189] 835.127441
host_var[190] 1320.454102
host_var[191] 1561.439941
host_var[192] 1599.149902
host_var[193] 1912.232910
host_var[194] 1993.473145
host_var[195] 1913.377441
host_var[196] 1784.035645
host_var[197] 1554.712891
host_var[198] 1244.698242
host_var[199] 926.668945
Reusults with enabling
global void kernelMeanVar(d_a, d_mean, d_var,...);
ERROR: no error
host_var[0] 0.000000
host_var[1] 0.000000
host_var[2] 0.000000
host_var[3] 0.000000
host_var[4] 0.000000
host_var[5] 0.000000
host_var[6] 0.000000
host_var[7] 0.000000
host_var[8] 0.000000
host_var[9] 0.000000
host_var[10] 0.000000
host_var[11] 0.000000
host_var[12] 0.000000
host_var[13] 0.000000
host_var[14] 0.000000
host_var[15] 0.000000
host_var[16] 0.000000
host_var[17] 0.000000
host_var[18] 0.000000
host_var[19] 0.000000
host_var[20] 0.000000
host_var[21] 0.000000
host_var[22] 0.000000
host_var[23] 0.000000
host_var[24] 0.000000
host_var[25] 0.000000
host_var[26] 0.000000
host_var[27] 0.000000
host_var[28] 0.000000
host_var[29] 0.000000
host_var[30] 0.000000
host_var[31] 0.000000
host_var[32] 0.000000
host_var[33] 0.000000
host_var[34] 0.000000
host_var[35] 0.000000
host_var[36] 0.000000
host_var[37] 0.000000
host_var[38] 0.000000
host_var[39] 0.000000
host_var[40] 0.000000
host_var[41] 0.000000
host_var[42] 0.000000
host_var[43] 0.000000
host_var[44] 0.000000
host_var[45] 0.000000
host_var[46] 0.000000
host_var[47] 0.000000
host_var[48] 0.000000
host_var[49] 0.000000
host_var[50] 0.000000
host_var[51] 0.000000
host_var[52] 0.000000
host_var[53] 0.000000
host_var[54] 0.000000
host_var[55] 0.000000
host_var[56] 0.000000
host_var[57] 0.000000
host_var[58] 0.000000
host_var[59] 0.000000
host_var[60] 0.000000
host_var[61] 0.000000
host_var[62] 0.000000
host_var[63] 0.000000
host_var[64] 0.000000
host_var[65] 0.000000
host_var[66] 0.000000
host_var[67] 0.000000
host_var[68] 0.000000
host_var[69] 0.000000
host_var[70] 0.000000
host_var[71] 0.000000
host_var[72] 0.000000
host_var[73] 0.000000
host_var[74] 0.000000
host_var[75] 0.000000
host_var[76] 0.000000
host_var[77] 0.000000
host_var[78] 0.000000
host_var[79] 0.000000
host_var[80] 0.000000
host_var[81] 0.000000
host_var[82] 0.000000
host_var[83] 0.000000
host_var[84] 0.000000
host_var[85] 0.000000
host_var[86] 0.000000
host_var[87] 0.000000
host_var[88] 0.000000
host_var[89] 0.000000
host_var[90] 0.000000
host_var[91] 0.000000
host_var[92] 0.000000
host_var[93] 0.000000
host_var[94] 0.000000
host_var[95] 0.000000
host_var[96] 0.000000
host_var[97] 0.000000
host_var[98] 0.000000
host_var[99] 0.000000
host_var[100] 0.000000
host_var[101] 0.000000
host_var[102] 0.000000
host_var[103] 0.000000
host_var[104] 0.000000
host_var[105] 0.000000
host_var[106] 0.000000
host_var[107] 0.000000
host_var[108] 0.000000
host_var[109] 0.000000
host_var[110] 0.000000
host_var[111] 0.000000
host_var[112] 0.000000
host_var[113] 0.000000
host_var[114] 0.000000
host_var[115] 0.000000
host_var[116] 0.000000
host_var[117] 0.000000
host_var[118] 0.000000
host_var[119] 0.000000
host_var[120] 0.000000
host_var[121] 0.000000
host_var[122] 0.000000
host_var[123] 0.000000
host_var[124] 0.000000
host_var[125] 0.000000
host_var[126] 0.000000
host_var[127] 0.000000
host_var[128] 18.927368
host_var[129] 21.664307
host_var[130] 142.432373
host_var[131] 1575.141602
host_var[132] 2901.855957
host_var[133] 4195.149902
host_var[134] 5047.758789
host_var[135] 5450.164063
host_var[136] 5249.767578
host_var[137] 4577.365234
host_var[138] 3352.496094
host_var[139] 1641.593750
host_var[140] 352.242188
host_var[141] 224.824219
host_var[142] 194.578125
host_var[143] 178.875000
host_var[144] 175.148438
host_var[145] 174.117188
host_var[146] 172.707031
host_var[147] 169.578125
host_var[148] 176.308594
host_var[149] 181.968750
host_var[150] 191.507813
host_var[151] 198.500000
host_var[152] 206.824219
host_var[153] 213.273438
host_var[154] 220.312500
host_var[155] 218.859375
host_var[156] 213.941406
host_var[157] 205.474609
host_var[158] 190.722656
host_var[159] 178.414063
host_var[160] 169.302734
host_var[161] 3.750366
host_var[162] 4.333252
host_var[163] 4.901855
host_var[164] 5.527466
host_var[165] 6.201782
host_var[166] 11.921631
host_var[167] 14.135376
host_var[168] 14.885864
host_var[169] 19.083618
host_var[170] 21.290283
host_var[171] 21.415649
host_var[172] 209.747559
host_var[173] 580.304932
host_var[174] 800.949951
host_var[175] 1119.857422
host_var[176] 1129.382324
host_var[177] 1032.616211
host_var[178] 972.797363
host_var[179] 915.440918
host_var[180] 905.890137
host_var[181] 943.649902
host_var[182] 1207.445801
host_var[183] 1345.912109
host_var[184] 1478.704590
host_var[185] 1224.895508
host_var[186] 1105.403564
host_var[187] 1031.981201
host_var[188] 914.456421
host_var[189] 835.127441
host_var[190] 1320.454102
host_var[191] 1561.439941
host_var[192] 1599.149902
host_var[193] 1912.232910
host_var[194] 1993.473145
host_var[195] 1913.377441
host_var[196] 1784.035645
host_var[197] 1554.712891
host_var[198] 1244.698242
host_var[199] 926.668945
End of Results
A: Suggestions:
*
*[First priority] Check return values from CUDA functions to see whether any errors are reported.
*Run this through cuda-memcheck. I'm not sure what the relationship is between globalRows, globalCols, localRows, localCols, num_elts etc. is but reading out-of-bounds seems like a candadite for problems.
*Remember that summing the squares can lead to rounding errors fairly quickly if you don't take care. Consider using a running mean/variance or doing a tree-based reduction.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/4122104",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to call and run next function if previous function runs in infinite loop? I have two different python files, one runs a web socket connection that runs in infinite loop until stopped and the second one has code that calculates data based on the first file data stored in DB.
I have created a function in both the files and calling them in a third file for easy execution. But the problem is when I execute the first function the code never goes to the second function as first one is on infinite loop.
Is there any way to solve this?
What I am trying to do is gathering data from web socket connection and parallelly run the next file and do some calculation in real time based on the data.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/72873165",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Adding the last element to string after array My storage string gives me all the digits in want besides the last, I know its because the last digit has nothing to compare to the right. Can I add the last digit to the end of my string somehow,
for(int i = 0;i < othercontent.length -1 ;i++ )
{
if(othercontent[i] != othercontent[i + 1])
{
storage = storage + othercontent[i];
}
}
A: for(int i = 0; i < othercontent.length ;i++ )
{
if(i == 0 || othercontent[i] != othercontent[i - 1])
{
storage = storage + othercontent[i];
}
}
A: if othercontent is String array :
TreeSet<String> set = new TreeSet<>(Arrays.asList(othercontent));
othercontent = set.toArray(new String[0]);
for (String string : othercontent) {
System.out.println(string);
}
if othercontent is String :
String othercontent = "ZZZZQQWEDDODRAABBNNNNO";
LinkedList<Character> list = new LinkedList<>();
for (Character character : othercontent.toCharArray()) {
list.add(character);
}
TreeSet<Character> set = new TreeSet<>(list);
StringBuilder builder = new StringBuilder();
for (Character character : set) {
builder.append(character);
}
System.out.println(builder.toString());
not only sorting , but also removing dublicates are solved with this code
OUTPUT :
ABDENOQRWZ
A: You can check if you reached the last element:
for(int i = 0;i < othercontent.length -1; i++ ) {
if(othercontent[i] != othercontent[i + 1]) {
storage = storage + othercontent[i];
}
//only gets executed if the last iteration is reached
if(i==othercontent.length-2) {
storage = storage + othercontent[i+1];
}
}
Or, instead of using a condition, just write this after your loop:
storage = storage + othercontent[othercontent.length-1];
A: You can add the last digit to your string outside of for loop as it doesn't require to check any condition
for(int i = 0;i < othercontent.length -1; i++ ) {
if(othercontent[i] != othercontent[i + 1]) {
storage = storage + othercontent[i];
}
}
storage = storage + othercontent[othercontent.length - 1];
A: for(int i = 0; i < othercontent.length -1 ; ++i ) {
if(othercontent[i] != othercontent[i + 1]) {
storage = storage + othercontent[i];
}
}
if(othercontent.length>0){
storage = storage + othercontent[othercontent.length-1];
}
A: If you are checking for the duplicates, you should do something like this outside the loop.
if(othercontent.length>0 && storage[storage.length-1] ! = othercontent[othercontent.length-1])
{
storage = storage+othercontent[othercontent.length-1];
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/18870933",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Dividing two tables in PowerBi I have two tables, say table 1 and table 2.
Table 1:
Region2
Apr
May
North
50
1200
South
75
1500
East
100
750
West
150
220
Table 2:
Region2
Apr
May
North
5
12
South
10
15
East
10
15
West
15
11
I need a table 3 that is a division of table 1 and table 2
Table 3:
Region2
Apr
May
North
10
100
South
7.5
100
East
10
50
West
15
20
A: I managed to solve it by creating a measure which is a ratio.
In my case, table 1 had values in say rupees.
table 2 had values in say, litres
So, I created a measure which is a division of sum total rupees and sum total of litres and when I added the measure to values in pivot matrix, it automatically divided the two tables.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/72424906",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to verify ECDSA/SHA2 S-MIME signature with python? We need to choose between two signature schemes:
*
*RSA/SHA2 S-MIME signatures
*ECDSA/SHA2 S-MIME signatures
For that our python software needs to support one of this scheme. Currently for some political reasons the ECDSA solution is prefered.
Is the ECDSA solution supported by any of the python crypto modules (M2Crypto, ...) and do you have an example for that ?
The ECDSA support seems very young even for openssl.
Thanks in advance
A: ECDSA is supported in M2Crypto, but it can be optionally disabled. For example Fedora-based systems ship with ECDSA disabled in OpenSSL and M2Crypto. M2Crypto has some SMIME support as well, but since I haven't used it much I am not sure if that would be of help in this case. See the M2Crypto SMIME doc and SMIME unit tests, as well as ec unit tests.
A: Ecliptic Curve Cryptography (ECDSA) as well as the more common RSA is supported by the OpenSSL library. I recommend using the pyOpenSSL bridge.
A: You can try using the python ecdsa package, using Python3:
pip3 install ecdsa
Usage:
from ecdsa import SigningKey
sk = SigningKey.generate() # uses NIST192p
vk = sk.get_verifying_key()
sig = sk.sign(b"message")
vk.verify(sig, b"message") # True
To verify an existing signature with a public key:
from ecdsa import VerifyingKey
message = b"message"
public_key = '7bc9c7867cffb07d3443754ecd3d0beb6c4a2f5b0a06ea96542a1601b87892371485fda33fe28ed1c1669828a4bb2514'
sig = '8eb2c6bcd5baf7121facfe6b733a7835d01cef3d430a05a4bcc6c5fbae37d64fb7a6f815bb96ea4f7ed8ea0ab7fd5bc9'
vk = VerifyingKey.from_string(bytes.fromhex(public_key))
vk.verify(bytes.fromhex(sig), message) # True
The package is compatible with Python 2 as well
| {
"language": "en",
"url": "https://stackoverflow.com/questions/2238128",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: SpringBoot MongoDB returns "Id must be assignable to Serializable! Object of class [null] must be an instance of interface java.io.Serializable" I tried adding a new collection to my API/DB today, and when I try to POST or GET, I get this 500 error response:
{
"cause": null,
"message": "Id must be assignable to Serializable! Object of class [null] must be an instance of interface java.io.Serializable"
}
However the POST is actually successful, I can see the new data in the DB.
Model:
@Setter
@Getter
public class League {
private String name;
private String shortName;
private List<Team> teams;
}
Repository:
@RepositoryRestResource(collectionResourceRel = "leagues", path = "leagues", excerptProjection = LeagueProjection.class)
public interface LeagueRepository extends MongoRepository<League, String> {
}
Projection:
@Projection(name="LeagueProjection", types={League.class})
public interface LeagueProjection {
String getName();
String getShortName();
}
I am not doing anything special. I have multiple other collections that work fine.
I am using spring-boot 1.5.1.
Thanks!
A: Adding the field:
@Id private String id;
to my model seems to have resolved the issue.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42604007",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: CakePHP Entity contain without foreign key I have an entity Villa, and I want this Entity to contain other Villas which have the same 'complex' (Varchar(255)).
class VillasTable extends Table
{
/**
* Initialize method
*
* @param array $config The configuration for the Table.
* @return void
*/
public function initialize(array $config)
{
$this->table('villas');
$this->displayField('name');
$this->primaryKey('id');
$this->hasMany('Complexs', [
'className' => 'Villas',
'foreignKey' => false,
'propertyName' => 'complexs',
'conditions' => ['Complexs.complex' => 'Villas.complex']
]);
}
}
?>
I don't know if it's possible. I don't want to add a find in each function who need those entity. Also I would like to make a function in the Entity which uses this new field.
``
A: Despite the fact that using a VARCHAR(255) as a foreign key is probably highly inefficient and/or will require huge indices, I guess that generally an option that defines the foreign key of the other table would come in handy here, similar to targetForeignKey for belongsToMany associations. You may to want to suggest that as an enhancement.
Result formatters
Currently this doesn't seem to be possible out of the box using associations, so you'd probably have to select and inject the associated records yourself, for example in a result formatter.
$Villas
->find()
->formatResults(function($results) {
/* @var $results \Cake\Datasource\ResultSetInterface|\Cake\Collection\Collection */
// extract the custom foreign keys from the results
$keys = array_unique($results->extract('complex')->toArray());
// find the associated rows using the extracted foreign keys
$villas = \Cake\ORM\TableRegistry::get('Villas')
->find()
->where(['complex IN' => $keys])
->all();
// inject the associated records into the results
return $results->map(function ($row) use ($villas) {
if (isset($row['complex'])) {
// filters the associated records based on the custom foreign keys
// and adds them to a property on the row/entity
$row['complexs'] = $villas->filter(function ($value, $key) use ($row) {
return
$value['complex'] === $row['complex'] &&
$value['id'] !== $row['id'];
})
->toArray(false);
}
return $row;
});
});
This would fetch the associated rows afterwards using the custom foreign keys, and inject the results, so that you'd end up with the associated records on the entities.
See also Cookbook > Database Access & ORM > Query Builder > Adding Calculated Fields
There might be other options, like for example using a custom eager loader that collects the necessary keys, combined with a custom association class that uses the proper key for stitching the results together, see
*
*API > \Cake\ORM\EagerLoader::_collectKeys()
*API > \Cake\ORM\Association\SelectableAssociationTrait::_resultInjector()
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30251374",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to cancel the click trigger of the mouse input if the it moved after clicking? I've been trying for almost 24 hours to resolve this
I have an object in my scene that, when clicked, will trigger to move to another scene. I would like the behavior of this object click to be exactly like a UI Button.
I'm currently using the Input.GetMouseButtonUp(0) to trigger this event. The problem is I have a script attached to the main camera that makes it rotate, zoom, and pan around in the scene. If the user accidentally ends up releasing the mouse on that object after moving the camera around, this will trigger the event since the object is considered clicked.
I would like to prevent that from happening. I was thinking about cancelling the event in case a mouse movement was detected, I couldn't execute it. Or maybe there would be a better approach to solve the problem.
I would really appreciate the help
My code below:
private void LateUpdate()
{
//When mouse button is released
if (Input.GetMouseButtonUp(0))
{
RaycastHit hit;
//Create a ray that projects at the position of the clicked mouse position
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
//If the ray hits the target object
if (Physics.Raycast(ray, out hit, 100.0f))
{
//Load the scene that corresponds to the clicked object
LoadScene(hit.transform.gameObject);
}
}
}
public void LoadScene(GameObject go)
{
//Load the level that corresponds to the clicked object
SceneManager.LoadScene(go.name);
//Print the name of the clicked object
print(go.name);
}
A: I guess I just found a solution, I added a term that if the mouse moves to do nothing, my new code:
private void LateUpdate()
{
//When mouse button is released
if (Input.GetMouseButtonUp(0))
{
//If the mouse moves after clicking
if (Input.GetAxis("Mouse X") < 0 || (Input.GetAxis("Mouse X") > 0))
{
//Do nothing
}
else {
//If no movement is detected, then send ray to object and trigger event
RaycastHit hit;
//Create a ray that projects at the position of the clicked mouse position
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
//If the ray hits the target object
if (Physics.Raycast(ray, out hit, 100.0f))
{
//Load the scene that corresponds to the clicked object
LoadScene(hit.transform.gameObject);
}
}
}
}
A: Most click implementations detect both the mouse down and mouse up events to determine if an object was clicked.
I would suggest something like this...
if(Input.GetMouseButtonDown(0)) {
mouseWasPressedOverObject = IsMouseOverObject();
} else if(Input.GetMouseButtonUp(0)) {
if(mouseWasPressedOverObject && IsMouseOverObject()) {
//Object clicked
}
mouseWasPressedOverObject = false;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60466934",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Spring Boot cannot successfully POST data to db (ORA-00942) I'm new to Spring Boot. I've stucked in the problem of creating new data (POST) for a whole day.
The error shows that I did not connect successfully to the db (ORA-00942).
Due to some privacy issues, I cannot copy-paste my work through my device. Therefore, I'm going to try my best to describe my logic and type out part of my codes. Any ideas would be a huge help! Thanks a million!
*
*I have five packages here, which are basically classified by
(1.)SpringBootApplication package, (2.)Repository package(3.)Service package (4.)Controller
package (5.)Entity package
*Basically, I do not edit in (1.)SpringBootApplication package, it's
kept originally as default.
*In my (5.)Entity package, I have written an Entity class that matches
my db. Let's say the class name of this Entity is called TitleOfMyDb. Here, Ive written the correspond @id properly, and I also write the setters and getters correctly.
*In the (3.)Service package, there is an Interface and a class. The class
is basically the implementation of the interface. Now, this is the trimmed
implementation of the service class.
@Autowired
private ExRepository exRepository;
@Overrride
public TitleOfMyDb createExampleMethod(String a, String b){
TitleOfMyDb titleOfMyDb = new TitleOfMyDb();
titleOfMyDb .setA(a);
titleOfMyDb .setB(b);
return exRepository.save(titleOfMyDb) //save method is originated from Repository instinctively.
*In my (4.)Controller package, i have a class which is ExController:
@Autowired
private ExService exService;
@GetMapping("/test")
public TitleOfMyDb createSomething
(@RequestParam(value="aa") String a, @RequestParam(value="bb") String b){
TitleOfMyDb object = exService.createExampleMethod(a, b)
return object;
}
*In my (2.)Repository package, I do not add more codes there, it's kept originally as well. because it already has the instinctive method that allows me to save() my entity with the repository.
Afterwards, when I try to run my spring boot, it shows error of ORA-00942. Also, when I type http://localhost:8080/test through my browser, I can only see nothing but error. The error message was quite complex, sorry that I really cannot copy-paste it through my device. Basically, it does not connect to my db properly.
Any help or guide on my logic and thinking process is really appreciated. Thank you!!!
A: ORA-00942: table or view does not exist
"You tried to execute a SQL statement that references a table or view that either does not exist, that you do not have access to, or that belongs to another schema and you didn't reference the table by the schema name."
I'd see if the database table is correct and double check the SQL query.
Ref: https://www.techonthenet.com/oracle/errors/ora00942.php
A: Error mean you don't have permision or your table incorrect. Please check entity. Make sure table : TitleOfMyDb exist in database. If you don't specific table with anotation @table hibernate automatic pick your name entity TitleOfMyDb
| {
"language": "en",
"url": "https://stackoverflow.com/questions/62199143",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What parameters does google closure compiler appspot use? I am using google's closure compiler to minimize my js files. When I use the website version here with the advanced options it works just fine, but when I downloaded their Java application, from here, and set the flag like this:
java -jar compiler.jar --compilation_level ADVANCED_OPTIMIZATIONS --js /code/built.js --js_output_file compiledCode.js
Then some features of my program stops working. I guess it's not compatible with the ooptimization algorithm. So my question is, what flags should I use to replicate the optimization used on the appspot version?
Thank you
A: The web service does not enable the type-based optimizations by default. So to get the equivalent functionality:
java -jar compiler.jar --compilation_level ADVANCED_OPTIMIZATIONS
--use_types_for_optimization=false
--js /code/built.js --js_output_file compiledCode.js
The web service also assumes any undefined symbol is an external library. For this reason it is not recommended for production use.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42145717",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Get available dates between range of dates I have a property rental site
So I want to know if property is available for a range of dates
First of all I defined the range of dates as:
DECLARE @AvailableRentalStartingDate DATETIME = '2022-04-11'
, @AvailableRentalEndingDate DATETIME = '2022-04-24'
Now the property rent like:
DECLARE @Rentals AS TABLE
(
[PropertyId] UNIQUEIDENTIFIER,
[StartingDate] DATE,
[EndingDate] DATE
)
INSERT INTO @Rentals ([PropertyId], [StartingDate], [EndingDate])
VALUES ('A5B2B505-EC6F-EC11-A004-00155E014807','2022-04-11 16:47:20.897', '2022-04-14 16:47:20.897'),
('A5B2B505-EC6F-EC11-A004-00155E014807','2022-04-16 16:47:20.897','2022-04-21 16:47:20.897')
As you can see we have available date 2022-04-15
Dates table
DECLARE @Dates AS TABLE
(
DateName DATE
)
DECLARE @TotalDays INT = 365;
WHILE @TotalDays > 0
BEGIN
INSERT INTO @Dates ([DateName])
SELECT DATEADD(DAY, @TotalDays, '2021-12-31');
SELECT @TotalDays = @TotalDays - 1;
END
Then the select
SELECT [R].[PropertyId], [D].[DateName], CASE WHEN [R].[StartingDate] IS NULL THEN 1 ELSE 0 END AS [IsAvailable]
FROM @Dates AS D
LEFT JOIN @Rentals R ON [D].[DateName] >= [R].[StartingDate] AND [D].[DateName] <= [R].[EndingDate]
WHERE [D].[DateName] BETWEEN @AvailableRentalStartingDate AND @AvailableRentalEndingDate
AND [R].[PropertyId] = 'A5B2B505-EC6F-EC11-A004-00155E014807'
ORDER BY [D].[DateName]
The problem is it does not identify the null on the available date 2022-04-15, it just return the not available dates.
I just want to know if that propertyId it's available, in this case it should be available because 2022-04-15 is available. How can I get only one row showing available true? Regards
A: your problem is the where clause of propertyid;
you should have that as a JOIN condition.
WHERE clause and ON conditions can be interchangeably used in INNER JOIN but in OUTER JOIN they impact the meaning.
demo link
SELECT [R].[PropertyId], [D].[DateName], CASE WHEN [R].[StartingDate] IS NULL THEN 1 ELSE 0 END AS [IsAvailable]
FROM @Dates AS D
LEFT JOIN @Rentals R ON [D].[DateName] >= [R].[StartingDate] AND [D].[DateName] <= [R].[EndingDate]
AND [R].[PropertyId] = 'A5B2B505-EC6F-EC11-A004-00155E014807'
WHERE [D].[DateName] BETWEEN @AvailableRentalStartingDate AND @AvailableRentalEndingDate
ORDER BY [D].[DateName]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/71847645",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How can table_name be a property in my post query? I want this query to be generic on the table_name meaning that there is in my JSON file a new property named "device" which indicates in which table the data will be inserted.
the problem is that in my SQL request I can't specify it. Here is what I tried:
INSERT INTO ${device} (adc_v, adc_i, acc_axe_x, acc_axe_y, acc_axe_z, temperature, spo2, pa_diastolique, pa_systolique, indice_confiance, received_on, bpm)' +
'values(${adc_v}, ${adc_i}, ${acc_axe_x}, ${acc_axe_y}, ${acc_axe_z}, ${temperature}, ${spo2}, ${pa_diastolique}, ${pa_systolique}, ${indice_confiance}, ${received_on}, ${bpm})'
here is my JSON on postman:
{
"device": "tag_7z8eq73",
"adc_v": 130,
"adc_i": {{RandomCourant}},
"acc_axe_x": {{RandomAccX}},
"acc_axe_y": {{RandomAccY}},
"acc_axe_z": {{RandomAccZ}},
"temperature": {{RandomTemp}},
"spo2": {{RandomSpo2}},
"pa_diastolique": {{RandomDias}},
"pa_systolique": {{RandomSys}},
"indice_confiance": {{RandomIndiceConf}},
"received_on": "{{$isoTimestamp}}",
"bpm": {{RandomBpm}}}
The table name is : tag_7z8eq73
here is the error that is returned to me:
error: erreur de syntaxe sur ou près de « 'tag_7z8eq73' »
Looks like I am close to the solution but there is a syntax problem, the quote ? is my way the right one?
A: const device = req.body.device;
console.log(device)
return db.none('INSERT INTO '+device+' (adc_v, adc_i, acc_axe_x, acc_axe_y, acc_axe_z, temperature, spo2, pa_diastolique, pa_systolique, indice_confiance, received_on, bpm)' +
'values(${adc_v}, ${adc_i}, ${acc_axe_x}, ${acc_axe_y}, ${acc_axe_z}, ${temperature}, ${spo2}, ${pa_diastolique}, ${pa_systolique}, ${indice_confiance}, ${received_on}, ${bpm})',
req.body)
try this
| {
"language": "en",
"url": "https://stackoverflow.com/questions/73153847",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Javascript - replace broken image by text (div; css class) I am trying to replace all broken image by JS. I use this code to replace all broken images by notfound.png image.
$(document).ready(function() {
$('img').attr('onError', 'this.src="notfound.png"');
});
Anyway, I would like to replace them by a text notice instead of image. I cannot find the proper way how to do it, thank you very much for your help. JS is not my cup of coffee :(
I would like to use this for the text part:
Text to to shown...
EDIT:
OK, I have found this solution working fine, but doesnt accept CSS class
<script type="text/javascript">
$(document).ready(function() {
$('.post_body img').one('error', function() {
$(this).replaceWith('<div>Image not found (error 404)</div>').addClass('error404');
});
});
</script>
Anyway as I wrote CSS class is not added, so this solution is not complete :(
CSS will be:
.error404 {
display: block;
color: #667d99;
font-weight: bold;
font-size: 11px;
border: 1px dotted;
border-radius: 3px;
padding: 5px;
margin: 10px;
background: #e7edf3;
text-aling: center;
}
A: You can create a text node and append it to the parent of img, and optionally remove img if needed. This code goes inside the error handler for img
$('img').on('error', function(){
$(this).parent().append($('<div>Broken image</div>'));
$(this).remove();
})
A: Ok, I think I have found a solution for you. I tried to use jQuery error function. This one helped me:
To replace all the missing images with another, you can update the src attribute inside the callback passed to .error(). Be sure that the replacement image exists; otherwise the error event will be triggered indefinitely.
In your example this would be the best:
$('img').each(function() {
var img = $(this);
img.error(function() {
img.replaceWith('<div class="error404">Image not found (error 404)</div>');
}).attr('src', img.attr('src'));
});
I also made a jsFiddle example for you, which is working great for me.
A: If you really need to use javascript for this try
$(document).ready(function() {
$('img').attr('alt', 'Alternative text');
});
But the same is achievable by barebone HTML
<img src="path/to/image.jpg" alt="Alternative text">
A: You can change the alt if an error is thrown just like you're doing with the image.
function imgMissing(image) {
image.onerror = "";
image.alt = "Image not Found";
return true;
}
The HTML:
<img src="image.jpg" onerror="imgMissing(this);" >
A: EDIT: OK, I have found this solution working fine:
<script type="text/javascript">
$(document).ready(function() {
$('.post_body img').one('error', function() {
$(this).replaceWith('<div>Image not found (error 404)</div>');
});
});
</script>
Anyway one more think, I need to add CSS class "error404" for this "div", how to do that in JS? Thank you very much!
CSS will be:
.error404 {
display: block;
color: #667d99;
font-weight: bold;
font-size: 11px;
border: 1px dotted;
border-radius: 3px;
padding: 5px;
margin: 10px;
background: #e7edf3;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42890024",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: When Joining a Domain, How to Remove Pre-Domain Accounts and Change Permissions? Is there an application to remove the Computer\Administrators group and the Computer\Administrator account and their permissions across the registry and file system and replace them with the Enterprise|Domain\Administrators group after joining a system to a domain?
A: Solution is to add the Domain | Enterprise Administrator groups to the Local Administrators Group, not deleting it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/50783571",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: MongoDB - Find first and last in the embedded array for a single matching document I have a collection of websites, which each contain a list of websites and their keywords that are being tracked. I also have another collection called "rankings" which for each of the keywords in the website contains a ranking. The collection so far looks like this:
{
"_id" : ObjectId("58503934034b512b419a6eab"),
"website" : "https://www.google.com",
"name" : "Google",
"keywords" : [
"Search",
"Websites",
],
"tracking" : [
{
"_id" : ObjectId("5874aa1df63258286528598d"),
"position" : 0,
"created_at" : ISODate("2017-01-1T09:32:13.831Z"),
"real_url" : "https://www.google.com",
"keyword" : "Search"
},
{
"_id" : ObjectId("5874aa1ff63258286528598e"),
"keyword" : "Search",
"real_url" : "https://www.google.com",
"created_at" : ISODate("2017-01-2T09:32:15.832Z"),
"found_url" : "https://google.com/",
"position" : 3
},
{
"_id" : ObjectId("5874aa21f63258286528598f"),
"keyword" : "Search",
"real_url" : "https://www.foamymedia.com",
"created_at" : ISODate("2017-01-3T09:32:17.017Z"),
"found_url" : "https://google.com/",
"position" : 2
},
{
"_id" : ObjectId("5874aa21f63258286528532f"),
"keyword" : "Websites",
"real_url" : "https://www.google.com",
"created_at" : ISODate("2017-01-1T09:32:17.017Z"),
"found_url" : "https://google.com/",
"position" : 1
},
{
"_id" : ObjectId("5874aa21f63258286528542f"),
"keyword" : "Websites",
"real_url" : "https://www.google.com",
"created_at" : ISODate("2017-01-1T09:32:17.017Z"),
"found_url" : "https://google.com/",
"position" : 2
},
]
}
What I want to do is:
1) Group all of the keywords together by their keyword
2) Find the starting position (at the very start of the month)
3) Find the current position (as of today)
So in theory I want to be given an object like:
{
"_id" : ObjectId("58503934034b512b419a6eab"),
"website" : "https://www.google.com",
"tracking" : [
{
"_id" : ObjectId("5874aa1df63258286528598d"),
"keyword": "Search",
"start_position": 0,
"todays_position": 3,
},
{
"_id" : ObjectId("5874aa1df63258286528598d"),
"keyword": "Website",
"start_position": 0,
"todays_position": 2,
},
]
I am confused about how to do the grouping on another field, though. I have tried the following so far:
db.getCollection('websites').aggregate([
{
$lookup: {
from: "seo_tracking",
localField: "website",
foreignField: "real_url",
as: "tracking"
}
},
{
$match: {
"_id" : ObjectId("58503934034b512b419a6eab")
}
},
{
$group: {
"_id" : "$_id",
"keyword" : {
$first: "$tracking.keyword",
},
}
}
]);
But this is not grouping by the keyword, nor can I figure out how I would get the expected value.
A: You can try something like this. $unwind the tracking array followed by $sort on tracking.keyword and tracking.created_at. $group by tracking.keyword and $first to get starting position, $avg to get average position and $last to get the today's position. Final $group to roll up everything back to tracking array.
db.website.aggregate([{
$match: {
"_id": ObjectId("58503934034b512b419a6eab")
}
}, {
$lookup: {
from: "seo_tracking",
localField: "website",
foreignField: "real_url",
as: "tracking"
}
}, {
$unwind: "$tracking"
}, {
$sort: {
"tracking.keyword": 1,
"tracking.created_at": -1
}
}, {
$group: {
"_id": "$tracking.keyword",
"website": {
$first: "$website"
},
"website_id": {
$first: "$_id"
},
"avg_position": {
$avg: "$tracking.position"
},
"start_position": {
$first: "$tracking.position"
},
"todays_position": {
$last: "$tracking.position"
}
}
}, {
$group: {
"_id": "$website_id",
"website": {
$first: "$website"
},
"tracking": {
$push: {
"keyword": "$_id",
"avg_position":"$avg_position",
"start_position": "$start_position",
"todays_position": "$todays_position"
}
}
}
}]);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41566378",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: using react-native webview component, can the website access the camera and audio of the device? I am unable to get the web-view component in React Native to access the device camera and audio when loading a html5 website that requires camera/audio to take a video via the front-facing camera.
I have tried using the solution from https://github.com/facebook/react-native/issues/11610 however, the web-view still cannot access the camera/audio function
<View style={{flex: 1,backgroundColor:color.main_background}}>
<NavBar navigation={this.props.navigation}>
<WebView
source={{uri:url }}
javaScriptEnabled={true}
/>
</NavBar>
</View>
A: If you can base64 serialize the data, then seems like you should be able to use this component to send data to your Webview. Not sure how performant it would be though.
https://github.com/R1ZZU/react-native-webview-messaging
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46472844",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Linux semaphores I'm looking for help with synchronization problem in Linux. I'm newbie, and I think I don't really understand how to use semaphores to synchronize. My task is to sync two processes that access a file - one reads from fifo from another process, writes to this file, then another reads. I know that my code lacks synchronization, but i have no clue how to do this.
Code:
sem_t writer, reader;
void readFromFifoSendToFile(void) {
sem_init(&writer, 1, 1);
FILE *fp;
char buffer[100];
FILE *file;
file = fopen("file", "w+");
fclose(file);
while(1) {
sem_wait(&writer);
fp = fopen("fifo", "r");
fscanf(fp, "%s", buffer);
fclose(fp);
file = fopen("file", "a+");
fputs(buffer, file);
fclose(file);
sem_post(&writer);
}
}
void readFromFileAndPrint(void) {
sem_init(&reader, 1, 1);
FILE *fp;
char buffer[100];
int counter = 0;
while(1) {
sem_wait(&reader);
counter++;
if(counter == 1) {
sem_wait(&writer);
sem_post(&reader);
fp = fopen("file", "r");
fscanf(fp, "%s", buffer);
fclose(fp);
printf("%s", buffer);
sem_wait(&reader);
if(counter == 0) {
sem_post(&writer);
}
sem_post(&reader);
}
}
A: Your main problem appears to be related to the concept of how a semaphore works. Semaphores are best viewed as a signal between a producer and consumer. When the producer have done something they post a signal on the semaphore, and the consumer will wait on the semaphore until the producer post a signal.
So in your case, there should only be one semaphore between the consumer and the producer -- they should share this semaphore for their synchronization. Also, the semaphore should start at the value zero since nothing have been produced yet. Every time the producer post to the semaphore the value will increase by one, the consumer when it waits on the semaphore will sleep if the value is zero, until such a time when the producer post and the value increases and becomes one. If the producer is much faster than the consumer the value of the semaphore can go up and be more than one which is fine, as long as the consumer is consuming the output in the same size of units as the producer produces them.
So a working example here, but without any error handling -- adding error handling is beyond the scope of this -- I have used threads but you can do the same with processes as long as you can share the semaphore between them
#include <semaphore.h>
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
sem_t thereBeData;
void* readFromFifoSendToFile(void*) {
FILE *fp = stdin;
char buffer[100];
FILE *file;
file = fopen("file", "a+");
while(1) {
fscanf(fp, "%s", buffer);
fprintf(file,"%s\n",buffer);
fflush(file);
sem_post(&thereBeData); // signal the consumer
}
}
void* readFromFileAndPrint(void*) {
FILE *fp = 0;
char buffer[100];
int counter = 0;
while(1) {
sem_wait(&thereBeData); // Waiting for the producer
if (!fp) fp = fopen("file", "r");
fscanf(fp, "%s", buffer);
printf("%s\n", buffer);
}
}
int main(void)
{
pthread_attr_t attr;
pthread_t thread1;
pthread_t thread2;
sem_init(&thereBeData, 0,0);
pthread_attr_init(&attr);
pthread_create(&thread1, &attr, readFromFifoSendToFile, (void*)0);
pthread_create(&thread2, &attr, readFromFileAndPrint, (void*)0);
sleep(10);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41761796",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: Getting associated models with $this->Auth in Cakephp I am using CakePHP 2.0's integrated Auth component.
I have the following tables :
*
*Users
*Groups
*Profiles
My model relations are as follows:
User belongsTo Group
User hasMany Profiles
While logged in to the site, I noticed the Auth session contains only User table information, but I need the information of Groups and Profiles tables too for the logged in user.
Is there any way to do that with the Auth component?
A: There is no way to do this with the AuthComponent because of the way it handles the session keys. You can, however, just save it to the session yourself.
The only way to do this is to add to the session when the user logs in:
function login() {
if ($this->Auth->login($this->data)) {
$this->User->id = $this->Auth->user('id');
$this->User->contain(array('Profile', 'Group'));
$this->Session->write('User', $this->User->read());
}
}
Then in your beforeFilter() in your AppController, save a var for the controllers to get to:
function beforeFilter() {
$this->activeUser = $this->Session->read('User');
}
// and allow the views to have access to user data
function beforeRender() {
$this->set('activeUser', $this->activeUser);
}
Update: As of CakePHP 2.2 (announced here), the AuthComponent now accepts the 'contain' key for storing extra information in the session.
A: As far as I'm aware the Auth component only caches the data from your Users model. You can use that information to retrieve the desired data from the other models, by for example using this in your controller:
$group_data = $this->Group->findById($this->Auth->user('group_id'));
Or
$profile_data = $this->Profile->findByUserId($this->Auth->user('id'));
But I don't think you can get it from the Auth component directly, as it doesn't cache the related model data out of the box.
A: Two ways:
1) Extend the FormAuthenticate class (see /Controller/Component/Auth) or whatever you use to login and override the _findUser() method and tell the Auth component to use this authorize class. See this page how to do all of that http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html
2) Simply implement a method in the model that will fetch all data you want and call it in the login method of your controller and write the data into the session. IMO it is handy to have such a method because sometimes you need to refresh the session data anyways.
Because of your comment on the other answer:
You will have to write a method and some code in a model that will return you the data. CakePHP can't read your mind and a database without code. No matter which of both suggested ways you're going to use, you'll have to write code.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/9785551",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: "extended initializer lists only available with -std=c++11 or -std=gnu++11", I'm Getting this error #include <iostream>
#include <vector>
using namespace std;
int main(){
vector <int> num = {2,3,4};
return 0;
}
A: Below style of initialization is only introduced in C++ 11.
vector <int> num = {2,3,4};
This is not available in initial C++ version. That is what your gcc compiler is complaining. You need to tell the compiler to use C++11 version. Use below command.
g++ -std=c++11 myProgram.cpp
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58824442",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to change the color of a specific pixel of an image in Android? I'm quite new to Android and am doing my own mini-project and I want to change a specific pixel's color. searching for how to do so, I came across this question from a couple of years back. I tried myBitmap.setPixel(10, 10, Color.rgb(45, 127, 0));, but when I am actually activating it on my phone, it just crashes the second I activate this line of code. It seems to crash whenever I'm interacting with the bitmap. int x =myBitmap.getHeight(); this line also crashes the app.
Yet, the initial creation of the bitmap doesn't cause any problems:
background = (ImageView) findViewById(R.id.dangeon);
background.setDrawingCacheEnabled(true);
background.buildDrawingCache(true);
dang = background.getDrawingCache();
Do I have to install any package or activate anything to use the setPixel or getHeight functions? Alternatively, is there any other way to change a specific pixel?
logcat error when trying @jayanth suggestion:
2021-10-09 20:23:18.276 24894-24894/Aviv.Aviv E/AndroidRuntime: FATAL EXCEPTION: main
Process: Aviv.Aviv, PID: 24894
java.lang.NullPointerException: Attempt to invoke virtual method 'android.graphics.Bitmap android.graphics.Bitmap.copy(android.graphics.Bitmap$Config, boolean)' on a null object reference
at Aviv.Aviv.MainActivity.onClick(MainActivity.java:247)
at android.view.View.performClick(View.java:7339)
at android.view.View.performClickInternal(View.java:7305)
at android.view.View.access$3200(View.java:846)
at android.view.View$PerformClick.run(View.java:27787)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7089)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:965)
A: If you are trying setPixel() method on the immutable bitmap. it will throw a IllegalStateException.
first, create a mutable copy of your bitmap. and then you can change the color of the pixel in your bitmap.
Bitmap mutableBitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true);
int red = 255; //replace it with your color
int green = 255; //replace it with your color
int blue = 255; //replace it with your color
int color = Color.argb(0xFF, red, green, blue);
mutableBitmap.setPixel(indexI, indexJ, color);
//now if you apply it to any image view to see change.
imageView.setImageBitmap(mutableBitmap);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/69508275",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Model validation with viewModel don't works I use viewModels to communicate between my controller and my view.
To get model validation, i use a partial class like this :
[MetadataType(typeof(EvaluationValidation))]
public partial class Evaluation
{
public class EvaluationValidation
{
[DisplayName("Title of evaluation")]
[Required( ErrorMessage="Please give a title")]
public string Title { get; set; }
}
}
The Displayname is binded to view with no problem but when i try to submit the view, i get this error :
The model item passed into the
dictionary is of type
'FOOBAR.Models.Evaluation',
but this dictionary requires a model
item of type
'FOOBAR.Areas.Evaluation.ViewModels.EvaluationFormViewModel'.
This is the code used in my controller
[HttpPost]
public ActionResult Create(FormCollection formValues)
{
Models.Evaluation data = new Models.Evaluation();
if (TryUpdateModel(data, "evaluations"))
{
this.daoe.Create(data);
return RedirectToAction("Index");
}
return View(data);
}
And this is my viewModel
public class EvaluationFormViewModel
{
public FOOBAR.Models.Evaluation evaluations;
public SelectList selectlist_evaluationtypes { get; set; }
public SelectList selectlist_evaluationstatus { get; set; }
}
Have you got an idea ?
Thank's by advance
A: You are passing a Models.Evaluation instance to your view, which is bound to a model of another type.
Models.Evaluation data = new Models.Evaluation();
if (TryUpdateModel(data, "evaluations"))
{
// ...
}
return View(data);
If TryUpdateModel returns false (which happens when the form does not pass validation, for example), you are effectively passing data to the View, which is of type Models.Evaluation.
Try mapping it to type FOOBAR.Areas.Evaluation.ViewModels.EvaluationFormViewModel before passing it to the view.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/4401045",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Difference between these 2 pieces of code for pre-flight in NodeJS Express First of all, I am a beginner with NodeJS, I am just watching some tutorials to get my feet wet: this question will probably sound very silly to anyone who has any Node experience.
In short, I am trying to allow pre-flight requests on my server, and the docs suggest I do this before my routes:
app.use(cors());
app.options('*', cors());
The tutorial I am following, on the other hand, proposes this:
app.use(cors())
app.options("*", (req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "GET, PUT, POST, OPTIONS");
res.header("Access-Control-Allow-Headers", "Authorization, Content-Length, X-Requested-With");
})
So, what is the difference between these 2 pieces of code?
My current hypothesis is that
app.options('*', cors());
and
res.header("Access-Control-Allow-Origin", "*");
are equivalent, but I am not sure
A: TL;DR yes, is the same
This cors() is from cors package.
CORS is a node.js package for providing a Connect/Express middleware that can be used to enable CORS with various options.
Basically is just a beautiful way to enable cors in routes with middleware.
You can check in source code to see how it works, and check documentation other usage ways
A: The second one allows you to set custom values for the allowed origin/methods/headers, but the CORS middleware actually supports this anyway - see the "Configuration Options" section on this page.
To explain a bit what's going on here:
*
*app.use(cors()) means "use the cors() middleware for all methods and all paths".
*app.options('*', cors()) means "use the cors() middleware for the OPTIONS method, for all paths (*)".
*app.options('*', (req, res, next) => { /* ... */ }) means "use the provided function as a middleware for all OPTIONS requests, for all paths (*)".
| {
"language": "en",
"url": "https://stackoverflow.com/questions/72513294",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What would be the fastest method? I'm building a dashboard using ASP.Net MVC, Angular.js, SQL Server and Fusion charts. All my data for charting is stored in database and I'm getting them via stored procedure. Now I need to pass the results from stored procedure to Json/XML, only formats Fusion Charts supports. What would be the best method to convert this data:
Hour Input Output InTarget OutTarget
7 22314 18537 6500 4875
8 36395 29931 6500 4875
9 32661 28518 6500 4875
10 34895 29793 6500 4875
11 30300 26538 6500 4875
12 31011 26898 6500 4875
13 16363 13716 6500 4875
into this Json?
{
"chart": {
"caption": "Input and Output",
"numberprefix": "$",
"plotgradientcolor": "",
"bgcolor": "FFFFFF",
"showalternatehgridcolor": "0",
"divlinecolor": "CCCCCC",
"showvalues": "0",
"showcanvasborder": "0",
"canvasborderalpha": "0",
"canvasbordercolor": "CCCCCC",
"canvasborderthickness": "1",
"yaxismaxvalue": "30000",
"captionpadding": "30",
"yaxisvaluespadding": "15",
"legendshadow": "0",
"legendborderalpha": "0",
"palettecolors": "#f8bd19,#008ee4,#33bdda,#e44a00,#6baa01,#583e78",
"showplotborder": "0",
"showborder": "0"
},
"categories": [
{
"category": [
{
"label": "7"
},
{
"label": "8"
},
{
"label": "9"
},
{
"label": "10"
},
{
"label": "11"
},
{
"label": "12"
},
{
"label": "13"
}
]
}
],
"dataset": [
{
"seriesname": "Input",
"data": [
{
"value": "22314"
},
{
"value": "36395"
},
{
"value": "32661"
},
{
"value": "34895"
},
{
"value": "30300"
},
{
"value": "31011"
},
{
"value": "16363"
}
]
},
{
"seriesname": "Output",
"data": [
{
"value": "18537"
},
{
"value": "29931"
},
{
"value": "28518"
},
{
"value": "29793"
},
{
"value": "26538"
},
{
"value": "26898"
},
{
"value": "13716"
}
]
},
{
"seriesname": "InTarget",
"renderas": "Line",
"data": [
{
"value": "6500"
},
{
"value": "6500"
},
{
"value": "6500"
},
{
"value": "6500"
},
{
"value": "6500"
},
{
"value": "6500"
},
{
"value": "6500"
}
]
},
{
"seriesname": "OutTarget",
"renderas": "Line",
"data": [
{
"value": "4875"
},
{
"value": "4875"
},
{
"value": "4875"
},
{
"value": "4875"
},
{
"value": "4875"
},
{
"value": "4875"
},
{
"value": "4875"
}
]
}
]
}
What I'm thinking to do is:
*
*stored procedure into datatable
*put each column into separate array
*convert array to Json in the format below
Is this going to be the best (performance) approach?
EDIT:
public Series[] GetGraphData(string sp)
{
var connection = ConfigurationManager.ConnectionStrings["EFDbContext"].ConnectionString;
using (var da = new SqlDataAdapter("exec " + sp, connection))
{
var dt = new DataTable();
da.Fill(dt);
da.FillSchema(dt, SchemaType.Mapped);
Series[] arrSeries = new Series[dt.Columns.Count];
foreach(DataColumn dc in dt.Columns)
{
if (dc.Ordinal == 0)
{
//Category here
}
else
{
var strarr = dt.Rows.Cast<DataRow>().Select(row => row[dc.Ordinal]).ToList();
Series s = new Series()
{
seriesname = dc.ColumnName,
renderas = "Line",
data = strarr.Select(o => new SeriesValue { value = o.ToString() }).ToList()
};
arrSeries[dc.Ordinal] = s;
}
}
return arrSeries;
}
}
A: I would load all the data into a datatable as you said, then have a Series object:
class Series{
public string seriesname{get;set;}
public string renderas{get;set;}
public IList<SeriesValue> data{get;set;}
}
class SeriesValue{
public string value{get;set;}
}
and return an array of Series to the frontend, serialized as JSON. Then you have the dataset array already built and you don't need to do any other processing on it.
I expect the performance bottleneck to be in loading the data from the db and sending it to the client .. the actual conversion to json shouldn't matter in the grand scheme of things.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30483963",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to filter the apps that show up when sharing intent Android? I know this has been asked before and I reference one of the answers but I can't get my code to work the way it should. I have a simple note-taking app, which allows the user to share notes through external applications. The code is supposed to filter the apps so the user can only share to facebook, twitter, mms, gmail, and email (so I thought). I took it from the top answer here How to filter specific apps for ACTION_SEND intent (and set a different text for each app). When I click on the button that launches the method to share intents, I do get mms, gmail, facebook twitter, and email, but I also get google drive, android beam, evernote, twitter direct message, facebook messenger and snapchat.
The only apps that the information gets sent correctly to are mms, email and gmail. Facebook doesn't work, there's some comments below on why, and twitter I'm not sure of because I don't have an account to test it out. I don't have the code to check if the packageName contains "drive" or "googledrive", but I can still share to drive and the data from my note gets passed along. I want to be able to send the note text and the note title however (2 editText fields in my app), but I don't know how to since I don't know what the package name is.
For the apps that don't work or I want to remove from the list of choices, how can I get rid of them? Here is the code:
public void sendNote(View view) {
Resources resources = getResources();
Intent emailIntent = new Intent();
emailIntent.setAction(Intent.ACTION_SEND);
// Native email client doesn't currently support HTML, but it doesn't hurt to try in case they fix it
emailIntent.putExtra(Intent.EXTRA_TEXT, titleEditor.getText().toString());
emailIntent.putExtra(Intent.EXTRA_SUBJECT, noteEditor.getText().toString());
emailIntent.setType("message/rfc822");
PackageManager pm = getPackageManager();
Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.setType("text/plain");
Intent openInChooser = Intent.createChooser(emailIntent, titleEditor.getText().toString() + ": " + noteEditor.getText().toString());
List<ResolveInfo> resInfo = pm.queryIntentActivities(sendIntent, 0);
List<LabeledIntent> intentList = new ArrayList<LabeledIntent>();
for (int i = 0; i < resInfo.size(); i++) {
// Extract the label, append it, and repackage it in a LabeledIntent
ResolveInfo ri = resInfo.get(i);
String packageName = ri.activityInfo.packageName;
if(packageName.contains("android.email")) {
emailIntent.setPackage(packageName);
} else if(packageName.contains("twitter") || packageName.contains("facebook") || packageName.contains("mms") || packageName.contains("android.gm")) {
Intent intent = new Intent();
intent.setComponent(new ComponentName(packageName, ri.activityInfo.name));
intent.setAction(Intent.ACTION_SEND);
intent.setType("text/plain");
if(packageName.contains("twitter")) {
intent.putExtra(Intent.EXTRA_TEXT, titleEditor.getText().toString() + ": " + noteEditor.getText().toString());
} else if(packageName.contains("facebook")) {
// Warning: Facebook IGNORES our text. They say "These fields are intended for users to express themselves. Pre-filling these fields erodes the authenticity of the user voice."
// One workaround is to use the Facebook SDK to post, but that doesn't allow the user to choose how they want to share. We can also make a custom landing page, and the link
// will show the <meta content ="..."> text from that page with our link in Facebook.
intent.putExtra(Intent.EXTRA_TEXT, titleEditor.getText().toString() + ": " + noteEditor.getText().toString());
} else if(packageName.contains("mms")) {
intent.putExtra(Intent.EXTRA_TEXT, titleEditor.getText().toString() + ": " + noteEditor.getText().toString());
} else if(packageName.contains("android.gm")) { // If Gmail shows up twice, try removing this else-if clause and the reference to "android.gm" above
intent.putExtra(Intent.EXTRA_TEXT, noteEditor.getText().toString());
intent.putExtra(Intent.EXTRA_SUBJECT, titleEditor.getText().toString());
intent.setType("message/rfc822");
}
//else if (packageName.contains("drive")) {
//intent.putExtra(Intent.EXTRA_TEXT, titleEditor.getText().toString() + ": " + noteEditor.getText().toString());
//}
else {
}
intentList.add(new LabeledIntent(intent, packageName, ri.loadLabel(pm), ri.icon));
}
}
// convert intentList to array
LabeledIntent[] extraIntents = intentList.toArray( new LabeledIntent[ intentList.size() ]);
openInChooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, extraIntents);
startActivity(openInChooser);
}
I have an else if near the bottom that is commented out. That was my attempt in finding the google drive packageName and sending the intent so the user can still use that application, it didn't work. Like I said earlier, drive gets information sent to it, but it's just the note text, not the title and text like I want it to be.
So I have 2 questions.
*
*How can I filter out all of the apps that I don't want the user to be able to send information to so they don't even show up as an option, lets take twitter for example.
*If the above is not possible, how can I find the package names for these different apps? For Google Drive, I tried using the commented out else if statement to send an intent to the app there but it never executed. I've searched everywhere to get intents for google drive but I can't get the package name to get my code working.
Thanks in advance
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39056765",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: getting sum using sql with multiple conditions I m having data in columns as: -
Process Volume TAT
1 1 Pass
1 2 Fail
2 5 Fail
2 5 Pass
3 1 Pass
4 6 Fail
4 4 Pass
Now grouping by Process, i want the sum of volume (not taking into account whatever TAT), sum of volume where TAT = Pass, sum of Volume where TAT = Fail.
Like this
Process Total Volume Volume(TAT=Pass) Volume(TAT = Fail)
1 3 1 2
2 10 5 5
...
...
A: For SQL Server, you can use CASE expressions to conditionally determine the amount you need to add, then SUM them together, like this:
SELECT Process, SUM(Volume) AS TotalVolume,
SUM(CASE WHEN TAT = 'Pass' THEN Volume ELSE 0 END) AS Pass,
SUM(CASE WHEN TAT = 'Fail' THEN Volume ELSE 0 END) AS Fail
FROM (
-- Dummy data here for testing
SELECT 1 AS Process, 1 as Volume, 'Pass' AS TAT
UNION SELECT 1, 2, 'Fail'
UNION SELECT 2, 5, 'Fail'
UNION SELECT 2, 5, 'Pass'
UNION SELECT 3, 1, 'Pass'
UNION SELECT 4, 6, 'Fail'
UNION SELECT 4, 4, 'Pass'
) MyTable
GROUP BY Process
ORDER BY Process
For Microsoft Access, CASE isn't supported, so you can use SWITCH or IIF, like so:
SUM(IIF(TAT = 'Pass', Volume, 0)) AS Pass
| {
"language": "en",
"url": "https://stackoverflow.com/questions/11722852",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Deleting rows based on multiple columns conditions Given the following table have, I would like to delete the records that satisfy the conditions based on the to_delete table.
data have;
infile datalines delimiter="|";
input id :8. item :$8. datetime : datetime18.;
format datetime datetime18.;
datalines;
111|Basket|30SEP20:00:00:00
111|Basket|30SEP21:00:00:00
111|Basket|31DEC20:00:00:00
111|Backpack|31MAY22:00:00:00
222|Basket|31DEC20:00:00:00
222|Basket|30JUN20:00:00:00
;
+-----+----------+------------------+
| id | item | datetime |
+-----+----------+------------------+
| 111 | Basket | 30SEP20:00:00:00 |
| 111 | Basket | 30SEP21:00:00:00 |
| 111 | Basket | 31DEC20:00:00:00 |
| 111 | Backpack | 31MAY22:00:00:00 |
| 222 | Basket | 31DEC20:00:00:00 |
| 222 | Basket | 30JUN20:00:00:00 |
+-----+----------+------------------+
data to_delete;
infile datalines delimiter="|";
input id :8. item :$8. datetime : datetime18.;
format datetime datetime18.;
datalines;
111|Basket|30SEP20:00:00:00
111|Backpack|31MAY22:00:00:00
222|Basket|30JUN20:00:00:00
;
+-----+----------+------------------+
| id | item | datetime |
+-----+----------+------------------+
| 111 | Basket | 30SEP20:00:00:00 |
| 111 | Backpack | 31MAY22:00:00:00 |
| 222 | Basket | 30JUN20:00:00:00 |
+-----+----------+------------------+
In the past, I used to operate with the catx() function to concatenate the conditions in a where statement, but I wonder if there is a better way of doing this
proc sql;
delete from have
where catx('|',id,item,datetime) in
(select catx('|',id,item,datetime) from to_delete);
run;
+-----+--------+------------------+
| id | item | datetime |
+-----+--------+------------------+
| 111 | Basket | 30SEP21:00:00:00 |
| 111 | Basket | 31DEC20:00:00:00 |
| 222 | Basket | 31DEC20:00:00:00 |
+-----+--------+------------------+
Please note that it should allow the have table to have more columns than the table to_delete.
A: You can use except from to compute difference set of two sets:
proc sql;
create table want as
select * from have except select * from to_delete
;
quit;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/72274367",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: how to open a url from the barcode scanner in phonegap build i'am using the Barcode Scanner for phonegap build, How would i retrieve the QR Codes URL data and display the webpage into a Iframe or div
$(document).ready(function(e) {
$("#scanner_mode").click(function() {
cordova.plugins.barcodeScanner.scan(
function (result) {
alert("We got a barcode\n" +
"Result: " + result.text + "\n" +
"Format: " + result.format + "\n" +
"Cancelled: " + result.cancelled);
},
function (error) {
alert("Scanning failed: " + error);
}
);
});
});
Right i have tried this but its not working, so how would i get the src of a iframe to load result.text url
$(document).ready(function(e) {
$("#scanner_mode").click(function() {
cordova.plugins.barcodeScanner.scan(
function (result) {
document.getElementById("frame").src = result.text;
},
function (error) {
alert("Scanning failed: " + error);
}
);
});
});
A: yep so its working :)
$(document).ready(function(e) {
$("#scanner_mode").click(function() {
cordova.plugins.barcodeScanner.scan(
function (result) {
document.getElementById("frame").src = result.text;
},
function (error) {
alert("Scanning failed: " + error);
}
);
});
});
that works :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/28661750",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: AJAX RETURN help on php/mysql dynamic drop down menu I am trying to populate one drop down menu based on the selection of the first drop down. The first drop down is a list of tables in my database, and the second drop down menu would populate from the providers within that table.
I am having trouble with the ajax script. I DO NOT KNOW how I can test ajax returns, I am fairly new to all this. But as of right now when I select the table from the first drop down menu, nothing happens(the second drop down menu is supposed to populate). I believe my issue lies within retrieving results from the ajax but that is only a guess.
Any help would be greatly appreciated.
My Javascript which sends the selction info from my specialist table to the ajax file...
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery("flip").click(function(){
jQuery("#panel").slideToggle("slow");
});
//provider drop down menu
jQuery(".wrap").on('change','#specialist', function() {
var querystr = 'specialist='+jQuery('#specialist :selected').val();
jQuery.post("ajax.php", querystr, function(data) {
if(data.errorcode ==0){
jQuery('#providercbo').html(data.chtml)
}else{
jQuery('#providercbo').html(data.chtml)
}
}, "json");
});
});
</script>
My ajax file
$specialist = isset($_POST['specialist']) ? $_POST['specialist'] : 0;
if ($specialist <> 0) {
$errorcode = 0;
$strmsg = "";
$sql="SELECT * from $specialist ORDER BY provider";
$result=mysql_query($sql);
$cont=mysql_num_rows($result);
if(mysql_num_rows($result)){
$chtml = '<select name="provider" id="provider"><option value="0">--Select Provider--</option>';
while($row = mysql_fetch_array($result)){
$chtml .= '<option value="'.$row['id'].'">'.$row['provider'].'</option>';
}
$chtml .= '</select>';
echo json_encode(array("errorcode"=>$errorcode,"chtml"=>$chtml));
}else{
$errorcode = 1;
$strmsg = '<font style="color:#F00;">No Provider available</font>';
echo json_encode(array("errorcode"=>$errorcode,"chtml"=>$strmsg));
}
}
The HTML
<table id="dynamictable" cellpadding="5" cellspacing="5" border="3" align="center">
<tr><td>
<div class="wrap" align="left">
<h3><strong>1.</strong>Specialist</h3>
<select id="specialist" name="specialist" required>
<option value="">--Select Specialist--</option>
<option value="addiction_specialist">Addiction Specialist</option>
</select
</div></td>
<td><h3 align="left"><strong>2.</strong>Provider</h3>
<div class="wrap" id="providercbo" align="left"></div></td>
<table>
A: Set up debugging on the PHP Side (XDebug works pretty well in most scenarios). Also, for ANY AJAX/web request functionality, I run fiddler (http://www.telerik.com/fiddler) to see what is being returned to the client from the web server (it will give you a complete view of the web request).
Hope this helps!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/27930490",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: can I implement a kill switch into a .bat fork bomb? I want to show a friend how big the impact of a fork bomb can be on performance, but without needing to restart the computer afterwards.
Assuming the following fork bomb:
%0|%0
Is there a way to add a kill switch to this which, with one button press, will stop all running copies of this file, stop any new from being created and hopefully save the machine? I'm not really familiar with the command prompt syntax, so I'm not sure.
A: Two ideas:
a) limit the depth your "bomb" is going to fork:
@echo off
set args=%*
if "%args%" EQU "" (set args=0) else set /a args=%args%+1
if %args% LSS 8 start /min thisfile.bat
(this will produce 2^9 -1 command windows, but only your main window is open.)
b) kill the cmd.exe process in the main batch file
@echo off
SET args=%*
:repeat
start /min thisfile.bat.bat some_arg
if "%args%" NEQ "" goto repeat
pause
taskkill /im cmd.exe
pressing any key in the initial batch file will instamntly kill all cmd windows currently open.
These solutions were tested with some restrictions, so if they work in a "hot" forkbomb, please let me know.
hope this helps.
EDIT:
c)implement a time switch in the original bat:
(still stops even if you can't get past pause)
@echo off
set args=%*
:repeat
start /min thisfile.bat some_arg
if "%args%" NEQ "" goto repeat
timeout /T 10
taskkill /im cmd.exe
or, using the smaller "bomb":
@echo off
set args=%*
if "%args%" NEQ "" (%0 some_arg|%0 some_arg) else start /min thisfile.bat some_arg
timeout /T 10
taskkill /im cmd.exe
A: If you're out to just show your friend fork bombs why not go for a silent but deadly approach? The fork bomb is in vbs, the cleanup is in batch.
Do note, the vbs fork bomb does nothing turning your pc off/on wont fix, it just floods your session proccess's.
The fork bomb:
Do until true = false
CreateObject("Wscript.Shell").Run Wscript.ScriptName
Loop
Source
Cleanup:
title=dontkillme
FOR /F "tokens=2 delims= " %%A IN ('TASKLIST /FI ^"WINDOWTITLE eq
dontkillme^" /NH') DO SET tid=%%A
echo %tid%
taskkill /F /IM cmd.exe /FI ^"PID ne %tid%^"
Source
A: If it runs in an accessible directory, you could try
IF EXIST kill.txt (exit /b) ELSE (%0|%0)
and make a file called kill.txt in the directory to stop the bomb.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/32193220",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: appium script starting off I have installed appium. I want to use it with android apps using Python on a win 7 machine. I do not know how to start a script off to use appium and do not know to use Python IDLE or something else? I have checked examples and discussion groups and found them not helpful. If there is better examples on how to use appium this would be appreciated as well.
A: Here are some links to get started provided from people working on Appium. Some documentation is not up to date since this is still pre Appium 1.0 but should be updated by May 1st.
http://appium.github.io/training/
https://github.com/appium/appium/tree/master/docs
| {
"language": "en",
"url": "https://stackoverflow.com/questions/17912895",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Lazy fetching OneToMany collection throws NPE in Collections.processReachableCollection when referenced column is null I have a problem with lazy loading when in a one to many unidirectional mapping the referenced column is null. Here is my "dummy" code example:
public class A {
@Column(name = "id")
private UUID id;
@Column(name = "b_reference")
private UUID bReference;
@OneToMany
@JoinColumn(name = "b_id", referencedColumnName = "b_reference", insertable = false, updatable = false)
private List<B> bList;
}
public class B {
@Column(name = "id")
private UUID id;
@Column(name = "b_id")
private UUID bId;
}
With eager loading, everything works fine, but I have too many entries so it really affects the performance.
I am working with the latest quarkus version (2.7.1 - also tried with 2.31) and in order to test this I also wrote just a simple named query:
@NamedQuery(name = A.FIND, query = "SELECT a FROM A a").
org.hibernate.resource.transaction.backend.jta.internal.synchronization.RegisteredSynchronization@4699241e >: java.lang.NullPointerException
at org.hibernate.engine.internal.Collections.processReachableCollection(Collections.java:149)
at org.hibernate.event.internal.FlushVisitor.processCollection(FlushVisitor.java:53)
at org.hibernate.event.internal.AbstractVisitor.processValue(AbstractVisitor.java:104)
at org.hibernate.event.internal.AbstractVisitor.processValue(AbstractVisitor.java:65)
at org.hibernate.event.internal.AbstractVisitor.processEntityPropertyValues(AbstractVisitor.java:59)
at org.hibernate.event.internal.DefaultFlushEntityEventListener.onFlushEntity(DefaultFlushEntityEventListener.java:183)
at org.hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:107)
at org.hibernate.event.internal.AbstractFlushingEventListener.flushEntities(AbstractFlushingEventListener.java:229)
at org.hibernate.event.internal.AbstractFlushingEventListener.flushEverythingToExecutions(AbstractFlushingEventListener.java:93)
at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:39)
at org.hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:107)
at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1402)
at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:493)
at org.hibernate.internal.SessionImpl.flushBeforeTransactionCompletion(SessionImpl.java:3285)
at org.hibernate.internal.SessionImpl.beforeTransactionCompletion(SessionImpl.java:2420)
at org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.beforeTransactionCompletion(JdbcCoordinatorImpl.java:449)
at org.hibernate.resource.transaction.backend.jta.internal.JtaTransactionCoordinatorImpl.beforeCompletion(JtaTransactionCoordinatorImpl.java:356)
at org.hibernate.resource.transaction.backend.jta.internal.synchronization.SynchronizationCallbackCoordinatorNonTrackingImpl.beforeCompletion(SynchronizationCallbackCoordinatorNonTrackingImpl.java:47)
at org.hibernate.resource.transaction.backend.jta.internal.synchronization.RegisteredSynchronization.beforeCompletion(RegisteredSynchronization.java:37)
at com.arjuna.ats.internal.jta.resources.arjunacore.SynchronizationImple.beforeCompletion(SynchronizationImple.java:76)
at com.arjuna.ats.arjuna.coordinator.TwoPhaseCoordinator.beforeCompletion(TwoPhaseCoordinator.java:360)
at com.arjuna.ats.arjuna.coordinator.TwoPhaseCoordinator.end(TwoPhaseCoordinator.java:91)
at com.arjuna.ats.arjuna.AtomicAction.commit(AtomicAction.java:162)
at com.arjuna.ats.internal.jta.transaction.arjunacore.TransactionImple.commitAndDisassociate(TransactionImple.java:1295)
at com.arjuna.ats.internal.jta.transaction.arjunacore.BaseTransaction.commit(BaseTransaction.java:128)
at io.quarkus.narayana.jta.runtime.CDIDelegatingTransactionManager.commit(CDIDelegatingTransactionManager.java:105)
at io.quarkus.narayana.jta.runtime.CDIDelegatingTransactionManager_Subclass.commit$$superforward1(Unknown Source)
at io.quarkus.narayana.jta.runtime.CDIDelegatingTransactionManager_Subclass$$function$$6.apply(Unknown Source)
at io.quarkus.arc.impl.AroundInvokeInvocationContext.proceed(AroundInvokeInvocationContext.java:54)
at io.quarkus.arc.runtime.devconsole.InvocationInterceptor.proceed(InvocationInterceptor.java:62)
at io.quarkus.arc.runtime.devconsole.InvocationInterceptor.monitor(InvocationInterceptor.java:49)
at io.quarkus.arc.runtime.devconsole.InvocationInterceptor_Bean.intercept(Unknown Source)
at io.quarkus.arc.impl.InterceptorInvocation.invoke(InterceptorInvocation.java:41)
at io.quarkus.arc.impl.AroundInvokeInvocationContext.perform(AroundInvokeInvocationContext.java:41)
at io.quarkus.arc.impl.InvocationContexts.performAroundInvoke(InvocationContexts.java:32)
at io.quarkus.narayana.jta.runtime.CDIDelegatingTransactionManager_Subclass.commit(Unknown Source)
at io.quarkus.narayana.jta.runtime.interceptor.TransactionalInterceptorBase.endTransaction(TransactionalInterceptorBase.java:365)
at io.quarkus.narayana.jta.runtime.interceptor.TransactionalInterceptorBase.invokeInOurTx(TransactionalInterceptorBase.java:165)
at io.quarkus.narayana.jta.runtime.interceptor.TransactionalInterceptorBase.invokeInOurTx(TransactionalInterceptorBase.java:103)
at io.quarkus.narayana.jta.runtime.interceptor.TransactionalInterceptorRequiresNew.doIntercept(TransactionalInterceptorRequiresNew.java:41)
at io.quarkus.narayana.jta.runtime.interceptor.TransactionalInterceptorBase.intercept(TransactionalInterceptorBase.java:57)
at io.quarkus.narayana.jta.runtime.interceptor.TransactionalInterceptorRequiresNew.intercept(TransactionalInterceptorRequiresNew.java:32)
at io.quarkus.narayana.jta.runtime.interceptor.TransactionalInterceptorRequiresNew_Bean.intercept(Unknown Source)
at io.quarkus.arc.impl.InterceptorInvocation.invoke(InterceptorInvocation.java:41)
at io.quarkus.arc.impl.AroundInvokeInvocationContext.perform(AroundInvokeInvocationContext.java:41)
at io.quarkus.arc.impl.InvocationContexts.performAroundInvoke(InvocationContexts.java:32)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/71263565",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Using 'not' in Prolog in logic statements I'm working on a condition in Prolog but the not operator is not working as expected. I see not being used in an example here http://www.cs.trincoll.edu/~ram/cpsc352/notes/prolog/factsrules.html
I have the following statements. What i want is for is_not_immune_to to return the result, but not seems to not be working here. Without the not it works fine, and returns whether the Pokemon is immune.
weak(fire, ground).
immune(flying, ground).
is_type(charizard, fire).
is_type(charizard, flying).
is_not_immune_to(Pkmn, AtkType) :-
is_type(Pkmn, Type), not(immune(Type, AtkType)).
I get the following error when calling is_not_immune_to with charizard and any type..:
uncaught exception: error(existence_error(procedure,not/1),is_not_immune_to/0)
What i want is for is_not_immune_to to return what it should. I want to be able to use not in logic statements. How should i do that?
A: Your code uses the old and deprecated not/1 predicate, which apparently is not supported in the Prolog system you're using, hence the existence error. Use instead the standard \+/1 predicate/prefix operator:
is_not_immune_to(Pkmn, AtkType) :-
is_type(Pkmn, Type), \+ immune(Type, AtkType).
With this change, you get for your sample call:
| ?- is_not_immune_to(charizard, ground).
true ? ;
no
| {
"language": "en",
"url": "https://stackoverflow.com/questions/61104383",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Moving PictureBox with Timer I want to create a program wherein when I click a Button, the PictureBox that is of the same width and height as the form moves down but I want the Timer to stop right after the PictureBox leaves the frame/form. And when I click another Button, the PictureBox will move back up but it will stop when it's at the center of the form, basically at the same location it was before moving down. The form's size is 700, 1000 if that helps. This is my code:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Timer1.Enabled = True
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
PictureBox1.Location = New Point(PictureBox1.Location.X, PictureBox1.Location.Y + 9)
If (PictureBox1.Location = New Point(700, 1100)) Then
Timer1.Enabled = False
End If
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Timer2.Enabled = True
End Sub
Private Sub Timer2_Tick(sender As Object, e As EventArgs) Handles Timer2.Tick
PictureBox1.Location = New Point(PictureBox1.Location.X, PictureBox1.Location.Y - 9)
If (PictureBox1.Location = New Point((Me.Width / 700) - (PictureBox1.Width / 700), (Me.Height / 1000) - (PictureBox1.Height / 1000))) Then
Timer2.Enabled = False
End If
End Sub
A: Let's assume your PictureBox starts in the top, left corner of the containing control (i.e. the Form, or a Panel, or whatever). This is Point(0,0).
In this event handler...
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
PictureBox1.Location = New Point(PictureBox1.Location.X, PictureBox1.Location.Y + 9)
If (PictureBox1.Location = New Point(700, 1100)) Then
Timer1.Enabled = False
End If
End Sub
...you are checking if the top left corner of PictureBox1 is at position 700,1100 instead of checking if it is at 0,1100. Also, since you're adding + 9 each timer tick, it'll never be at a Y position of exactly 1100.
And then in this event...
Private Sub Timer2_Tick(sender As Object, e As EventArgs) Handles Timer2.Tick
PictureBox1.Location = New Point(PictureBox1.Location.X, PictureBox1.Location.Y - 9)
If (PictureBox1.Location = New Point((Me.Width / 700) - (PictureBox1.Width / 700), (Me.Height / 1000) - (PictureBox1.Height / 1000))) Then
Timer2.Enabled = False
End If
End Sub
You want to check if PictureBox1.Location is now 0,0 (the starting position) instead of all of that position math you are doing.
Here is a cleaned-up version of your code. Note that it first checks the position of the PictureBox and only moves it if necessary.
Private Const INCREMENT As Integer = 9
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Timer1.Enabled = True
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
If PictureBox1.Location.Y >= 1100 Then
Timer1.Enabled = False
Else
PictureBox1.Location = New Point(PictureBox1.Location.X, PictureBox1.Location.Y + INCREMENT)
End If
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Timer2.Enabled = True
End Sub
Private Sub Timer2_Tick(sender As Object, e As EventArgs) Handles Timer2.Tick
If PictureBox1.Location.Y <= 0 Then
Timer2.Enabled = False
Else
PictureBox1.Location = New Point(PictureBox1.Location.X, PictureBox1.Location.Y - INCREMENT)
End If
End Sub
| {
"language": "en",
"url": "https://stackoverflow.com/questions/69550666",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Flutter Firesbase is returning Null final db = FirebaseFirestore.instance.collection('dutyStatus');
Future<void> readOnDutyStatus() async {
//The function is being called in the authentication bloc
try {
List status = [];
// await db.add({'onDuty': true});
var data = await db.doc('driver1').get();
var temp = data.data();
status.add(temp);
print(
'_______________________________________________________________________________________');
print(status.toString());
print(
'_______________________________________________________________________________________');
} catch (e) {
print(e);
}
}
The result :
I/flutter (25466): _______________________________________________________________________________________
I/flutter (25466): [null]
I/flutter (25466): _______________________________________________________________________________________
W/er_drive_mobil(25466): Accessing hidden method Lsun/misc/Unsafe;->putObject(Ljava/lang/Object;JLjava/lang/Object;)V (greylist, linking, allowed)
W/er_drive_mobil(25466): Accessing hidden method Lsun/misc/Unsafe;->putInt(Ljava/lang/Object;JI)V (greylist, linking, allowed)
Note: The same code when used on another account of firebase works as intended and I can't seem to figure out the issue.
A: Most likely driver1 doesn't exist.
Try this
var temp = data.exists ? data.data() : "Doc does not exist";
Print list should return [Doc does not exist] instead of null.
Check if there is a white space before driver1 i.e _driver1 or after it. Otherwise there's no other explanation.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/68460777",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Replicate Excel's IF and COUNTIF functions in pandas I am trying to replicate the ability of Excel countif and if statements in Pandas.
In Excel, I have the following table:
+---------+-------+------+--------+
| Row/Col | A | B | C |
+---------+-------+------+--------+
| 1 | Name | Date | Type |
| 2 | John | 21/4 | New |
| 3 | John | 22/4 | Update |
| 4 | Jacob | 23/6 | New |
| 5 | Mary | 24/7 | New |
| 6 | Jacob | 26/8 | Update |
+---------+-------+------+--------+
In order to get the Type values, I would use the following code in all of column C (for row 2):
=IF(COUNTIF($A2:A2, A2)>1, "Update", "New")
For the same data in a df, how would I implement it, so that I counts only from the first row of the column down, and does not include any row below the row it is calculating for?
A: In panda we have groupby with cumcount
df['C']=df.groupby('A').cumcount().gt(0).map({False:'New',True:'Update'})
| {
"language": "en",
"url": "https://stackoverflow.com/questions/63251777",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to replace next button with mat-chip in Angular Material stepper? I am using angular material stepper, in the stepper i want to replace next button with mat-chip and act as same functionality as next button.
Here is angular stepper stackblitz example
This is what i want:
A: I you just want the button to look like a material chip (rather than actually be a material chip), you could remove 'mat-button' from the next button and add your own class, e.g. 'next_btn':
<button class="next_btn" matStepperNext>Next</button>
You can then just style the button so it looks like a chip:
button.next_btn {
padding: 7px 12px;
border-radius: 16px;
min-height: 32px;
background-color: #e0e0e0;
color: rgba(0,0,0,.87);
box-shadow:none;
border:none;
cursor: pointer;
outline:none;
}
button.next_btn:focus
{
outline:none;
}
Example here.
A: How about inserting the button inside the chip? and managing the look... take a look here for demo
HTML:
<mat-chip-list>
<mat-chip><button mat-button matStepperPrevious>Back</button></mat-chip>
<mat-chip><button mat-button matStepperNext>Next</button></mat-chip>
</mat-chip-list>
CSS:
mat-chip{padding:0;}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/55634592",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Streaming cameras by ip with python I have a remote camera streaming through rtsp protocol and am trying to access it in OpenCV 2.13.1 using python with following code.
camera = cv2.VideoCapture("rtsp://admin:<pass>@<ip>:<port>/xyz/video.smp")
However, when I do that I get the following warning
[tcp @ 00000188ed4e9b00] Connection to tcp://ip failed: Error number -138 occurred
warning: Error opening file (/build/opencv/modules/videoio/src/cap_ffmpeg_impl.hpp:901)
warning: http://ip (/build/opencv/modules/videoio/src/cap_ffmpeg_impl.hpp:902)
I dont know how to fix that
| {
"language": "en",
"url": "https://stackoverflow.com/questions/54344321",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Trouble in implementing link list sorting in c# I am having trouble implementing a sort algo (merge) for singly list as defined below
My mergesort method always gives me null..I am not able to figure out what is wrong
Can you guys help me out?
Node class
public class Node
{
private int data;
private Node next;
}
Linked List class
public class SSL
{
private Node head;
}
My merge sort code
public static void MergeSort(SSL a)
{
SSL x = new SSL();
SSL y = new SSL();
if (a.Head == null || a.Head.Next == null) // base case if list has 0 or 1 element
return;
AlternateSplitting(a, x, y);
MergeSort(x);
MergeSort(y);
a = SortedMerge(x, y);
}
I implemented following helper methods to implement merge sort
AlternateSplitting: This method will split the list into 2 lists
public static void AlternateSplitting(SSL src, SSL odd, SSL even)
{
while (src.Head != null)
{
MoveNode(odd, src);
if (src.Head != null)
MoveNode(even, src);
}
} // end of AlternateSplitting
This method will merge the 2 list and return a new list
public static SSL SortedMerge(SSL a, SSL b)
{
SSL c = new SSL();
if (a.Head == null)
return b;
else
if (b.Head == null)
return a;
else
{
bool flagA = false;
bool flagB = false;
Node currentA = new Node();
Node currentB = new Node();
while (!flagA && !flagB)
{
currentA = a.Head;
currentB = b.Head;
if (currentA.Data < currentB.Data)
{
MoveNodeToEnd(a, c);
currentA = a.Head;
if (currentA== null)
flagA = true;
}
else
if (currentA.Data > currentB.Data)
{
MoveNodeToEnd(b, c);
currentB = b.Head;
if (currentB== null)
flagB = true;
}
} // end of while
if (flagA)
{
while (currentB != null)
{
MoveNodeToEnd(b, c);
currentB = b.Head;
}
}
else
if(flagB)
{
while (currentA != null)
{
MoveNodeToEnd(a, c);
currentA = a.Head;
}
}
return c;
} // end of outer else
} // end of function sorted merge
A:
I am not able to figure out what is
wrong Can you guys help me out?
Find a bug and you fix it for a day. Teach how to find bugs and believe me, it takes a lifetime to fix the bugs. :-)
Your fundamental problem is not that the algorithm is wrong -- though, since it gives incorect results, it certainly is wrong. But that's not the fundamental problem. The fundamental problem is that you don't know how to figure out where a program goes wrong. Fix that problem first! Learn how to debug programs.
Being able to spot the defect in a program is an acquired skill like any other -- you've got to learn the basics and then practice for hundreds of hours. So learn the basics.
Start by becoming familiar with the basic functions of your debugger. Make sure that you can step through programs, set breakpoints, examine local variables, and so on.
Then write yourself some debugging tools. They can be slow -- you're only going to use them when debugging. You don't want your debugging tools in the production version of your code.
The first debugging tool I would write is a method that takes a particular Node and produces a comma-separated list of the integers that are in the list starting from that node. So you'd say DumpNode(currentB) and what would come back is, say "{10,20,50,30}". Obviously doing the same for SSL is trivial if you can do it for nodes.
I would also write tools that do things like count nodes in a list, tell you whether a given list is already sorted, and so on.
Now you have something you can type into the watch window to more easily observe the changes to your data structures as they flow by. (There are ways to make the debugger do this rendering automatically, but we're discussing the basics here, so let's keep it simple.)
That will help you understand the flow of data through the program more easily. And that might be enough to find the problem. But maybe not. The best bugs are the ones that identify themselves to you, by waving a big red flag that says "there's a bug over here". The tool that turns hard-to-find bugs into self-identifying bugs is the debug assertion.
When you're writing your algorithm, think "what must be true?" at various points. For example, before AlternateSplitting runs, suppose the list has 10 items. When it is done running, the two resulting lists had better have 5 items each. If they don't, if they have 10 items each or 0 items each or one has 3 and the other has 7, clearly you have a bug somewhere in there. So start writing debug-only code:
public static void AlternateSplitting(SSL src, SSL odd, SSL even)
{
#if DEBUG
int srcCount = CountList(src);
#endif
while (src.Head != null) { blah blah blah }
#if DEBUG
int oddCount = CountList(odd);
int evenCount = CountList(even);
Debug.Assert(CountList(src) == 0);
Debug.Assert(oddCount + evenCount == srcCount);
Debug.Assert(oddCount == evenCount || oddCount == evenCount + 1);
#endif
}
Now AlternateSplitting will do work for you in the debug build to detect bugs in itself. If your bug is because the split is not working out correctly, you'll know immediately when you run it.
Do the same thing to the list merging algorithm -- figure out every point where "I know that X must be true at this point", and then write a Debug.Assert(X) at that point. Then run your test cases. If you have a bug, then the program will tell you and the debugger will take you right to it.
Good luck!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/1183091",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Test DeltaSpike Repositories cannot inject EntityManager I am trying to run a simple test for DeltaSpike repository. However, I cannot get the Entity Manager injected. I am using producer which is located and test sources:
@ApplicationScoped
public class EntityManagerProducer {
@Produces
public EntityManager getEntityManager() {
return Persistence
.createEntityManagerFactory("primary-test")
.createEntityManager();
}
}
In META-INF folder under test resources I have a persistence.xml file with primary-test persistence unit defined:
<persistence version="2.0"
xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="primary-test" transaction-type="RESOURCE_LOCAL">
<properties>
<!-- Configuring JDBC properties -->
<property name="javax.persistence.jdbc.url" value="jdbc:h2:mem:test"/>
<property name="javax.persistence.jdbc.driver" value="org.h2.Driver"/>
<!-- Hibernate properties -->
<property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect"/>
<property name="hibernate.hbm2ddl.auto" value="create-drop"/>
<property name="hibernate.format_sql" value="false"/>
<property name="hibernate.show_sql" value="true"/>
</properties>
</persistence-unit>
</persistence>
In very simple Unit I am trying to inject Entity Manager:
@RunWith(CdiTestRunner.class)
public class UserRepositoryTest {
@Inject
private EntityManager entityManager;
@Test
public void shouldReturnEmptyListWhenDBIsEmpty() {
// dummy test here
}
}
However, when I am running it I am getting the exception:
WELD-001408 Unsatisfied dependencies for type [EntityManager] with qualifiers [@Default] at injection point [[field] @Inject private com.repository.UserRepositoryTest.entityManager]
My pom.xml has dependencies to Apache DeltaSpike Test Module and Weld:
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<deltaspike.version>1.8.2</deltaspike.version>
<weld.version>1.1.10.Final</weld.version>
</properties>
<dependency>
<groupId>org.apache.deltaspike.modules</groupId>
<artifactId>deltaspike-test-control-module-api</artifactId>
<version>${deltaspike.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.deltaspike.modules</groupId>
<artifactId>deltaspike-test-control-module-impl</artifactId>
<version>${deltaspike.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.deltaspike.cdictrl</groupId>
<artifactId>deltaspike-cdictrl-weld</artifactId>
<version>${deltaspike.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jboss.weld.se</groupId>
<artifactId>weld-se-core</artifactId>
<version>${weld.version}</version>
<scope>test</scope>
</dependency>
Any ideas why Entity Manager cannot be injected? I do not want to use Arquillian.
EDIT:
Current pom.xml:
<groupId>com.us</groupId>
<artifactId>deltaspike-samples</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>DeltaSpike samples</name>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<deltaspike.version>1.8.1</deltaspike.version>
<weld.version>3.0.4.Final</weld.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.apache.deltaspike.distribution</groupId>
<artifactId>distributions-bom</artifactId>
<version>${deltaspike.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.wildfly.bom</groupId>
<artifactId>jboss-javaee-7.0-with-hibernate</artifactId>
<version>8.2.2.Final</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.deltaspike.core</groupId>
<artifactId>deltaspike-core-api</artifactId>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.apache.deltaspike.core</groupId>
<artifactId>deltaspike-core-impl</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.apache.deltaspike.modules</groupId>
<artifactId>deltaspike-data-module-api</artifactId>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.apache.deltaspike.modules</groupId>
<artifactId>deltaspike-data-module-impl</artifactId>
<scope>runtime</scope>
</dependency>
<!--Test dependencies-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.deltaspike.modules</groupId>
<artifactId>deltaspike-test-control-module-api</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.deltaspike.modules</groupId>
<artifactId>deltaspike-test-control-module-impl</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.deltaspike.cdictrl</groupId>
<artifactId>deltaspike-cdictrl-api</artifactId>
<version>${deltaspike.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.apache.deltaspike.cdictrl</groupId>
<artifactId>deltaspike-cdictrl-weld</artifactId>
<version>${deltaspike.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.enterprise</groupId>
<artifactId>cdi-api</artifactId>
<version>2.0</version>
</dependency>
<dependency>
<groupId>org.jboss.weld.se</groupId>
<artifactId>weld-se-shaded</artifactId>
<version>3.0.4.Final</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.1-api</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.jboss.spec.javax.annotation</groupId>
<artifactId>jboss-annotations-api_1.2_spec</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
A: Using CDI in JAVA SE requires the beans.xml to be put in META-INF
although this is optional since Java EE 7.
Then, set discovery mode to annotated and your producer should be detected.
Here is a working configuration :
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.source>1.8</maven.compiler.source>
<deltaspike.version>1.8.2</deltaspike.version>
<weld.version>3.0.4.Final</weld.version>
</properties>
Now, here is how you setup the base DeltaSpike dependency :
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.apache.deltaspike.distribution</groupId>
<artifactId>distributions-bom</artifactId>
<version>${deltaspike.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
In the dependencies, you should have theses specs :
<dependency>
<groupId>javax.enterprise</groupId>
<artifactId>cdi-api</artifactId>
<version>2.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.transaction</groupId>
<artifactId>javax.transaction-api</artifactId>
<version>1.3</version>
</dependency>
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>javax.persistence-api</artifactId>
<version>2.2</version>
</dependency>
Now it's time to depend on implementations.
First, Deltaspike itself :
<dependency>
<groupId>org.apache.deltaspike.core</groupId>
<artifactId>deltaspike-core-api</artifactId>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.apache.deltaspike.core</groupId>
<artifactId>deltaspike-core-impl</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.apache.deltaspike.cdictrl</groupId>
<artifactId>deltaspike-cdictrl-api</artifactId>
<scope>compile</scope>
</dependency>
Then JBoss Weld 3 (CDI 2.0 impl)
<dependency>
<groupId>org.jboss.weld.se</groupId>
<artifactId>weld-se-shaded</artifactId>
<version>${weld.version}</version>
<scope>runtime</scope>
</dependency>
And Weld controler for DeltaSpike :
<dependency>
<groupId>org.apache.deltaspike.cdictrl</groupId>
<artifactId>deltaspike-cdictrl-weld</artifactId>
<scope>runtime</scope>
</dependency>
Then the DeltaSpike Data module :
<dependency>
<groupId>org.apache.deltaspike.modules</groupId>
<artifactId>deltaspike-data-module-api</artifactId>
<version>${deltaspike.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.apache.deltaspike.modules</groupId>
<artifactId>deltaspike-data-module-impl</artifactId>
<version>${deltaspike.version}</version>
<scope>runtime</scope>
</dependency>
Now it's time for the JPA implementation (EclipseLink JPA 2.7.1) and an embedded database server H2 :
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>org.eclipse.persistence.jpa</artifactId>
<version>2.7.1</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.197</version>
<scope>runtime</scope>
</dependency>
To create unit test with JUnit 5, you need this :
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.1.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.1.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<version>5.1.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-launcher</artifactId>
<version>1.1.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-runner</artifactId>
<version>1.1.0</version>
<scope>test</scope>
</dependency>
And to be able to launch CDI with a single annotation in a JUnit class, you need this as well :
<dependency>
<groupId>org.jboss.weld</groupId>
<artifactId>weld-junit5</artifactId>
<version>1.2.2.Final</version>
<scope>test</scope>
</dependency>
To enable JUnit 5 in Maven, you must configure maven-surefire-plugin :
<build>
<plugins>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.19.1</version>
<dependencies>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-surefire-provider</artifactId>
<version>1.0.3</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.0.3</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>
And, I'll use Lombok and SLF4J :
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.20</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.25</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.7.25</version>
<scope>test</scope>
</dependency>
Here is my project structure :
main/java/fr/fxjavadevblog
+-- VideoGame.java (JPA Entity)
+-- VideoGameFactory.java
+-- VideoGameRepository.java (interface)
+-- InjectedUUID.java (annotation def.)
+-- Producers.java (produces EntityManager and UUID has string)
/resources/META-INF
+-- beans.xml
+-- persistence.xml
test/java/fr/fxjavadevblog
+-- VideoGameReposityTest.java (JUnit 5)
/resources/META-INF
+-- beans.xml
+-- persistence.xml
Here is are my CDI producers, needed by DeltaSpike Data and to inject UUID as private keys :
package fr.fxjavadevblog;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.inject.Produces;
import javax.persistence.EntityManager;
import javax.persistence.Persistence;
import java.util.UUID;
/**
* composite of CDI Producers.
*
* @author robin
*/
@ApplicationScoped
public class Producers
{
public static final String UNIT_NAME = "cdi-deltaspike-demo";
/**
* produces the instance of entity manager for the application and for DeltaSpike.
*/
@Produces
@SuppressWarnings("unused") // just remove the warning, because the field serves as CDI Producer and the IDE cannot detect it.
private static EntityManager em = Persistence.createEntityManagerFactory(UNIT_NAME).createEntityManager();
/**
* produces randomly generated UUID for primary keys.
*
* @return UUID as a HEXA-STRING
*
*/
@Produces
@InjectedUUID
@SuppressWarnings("unused") // just remove the warning, because the method serves as CDI Producer and the IDE cannot detect it.
public String produceUUIDAsString()
{
return UUID.randomUUID().toString();
}
}
this class uses a custom CDI Qualifier called @InjectedUUID :
package fr.fxjavadevblog;
import javax.inject.Qualifier;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
/**
* CDI Qualifier for UUID Producers
*
* @author robin
*/
@Qualifier
@Retention(RUNTIME)
@Target({METHOD, FIELD, PARAMETER, TYPE})
public @interface InjectedUUID
{
}
Here is my JPA entity, using Lombok and CDI annotations :
package fr.fxjavadevblog;
import lombok.*;
import javax.enterprise.context.Dependent;
import javax.inject.Inject;
import javax.persistence.*;
import java.io.Serializable;
/**
* simple JPA Entity, using Lombok and CDI Injected fields (UUID).
*
* @author robin
*/
// lombok annotations
@NoArgsConstructor(access = AccessLevel.PROTECTED) // to avoid direct instanciation bypassing the factory.
@ToString(of = {"id","name"})
@EqualsAndHashCode(of="id")
// CDI Annotation
@Dependent
// JPA Annotation
@Entity
public class VideoGame implements Serializable {
@Id
@Inject @InjectedUUID // ask CDI to inject an brand new UUID
@Getter
private String id;
@Getter @Setter
private String name;
// this field will work as a flag to know if the entity has already been persisted
@Version
@Getter
private Long version;
}
Here is a simple factory for my entity class :
/**
* simple Factory for creation VideoGame instances populated with UUID, ready to persist.
* This factory is need to get a proper Entity. Entities must not be created with the "new" operator, but must be build
* by invoking CDI.
*
* @author robin
*/
public class VideoGameFactory
{
/**
* creates and brand new VideoGame instance with its own UUID as PK.
*
* @return instance of a VideoGame
*/
public static VideoGame newInstance()
{
// ask CDI for the instance, injecting required dependencies.
return CDI.current().select(VideoGame.class).get();
}
}
And last but not least, the DeltaSpike Data Resposity for my entity :
package fr.fxjavadevblog;
import org.apache.deltaspike.data.api.EntityRepository;
import org.apache.deltaspike.data.api.Repository;
/**
* CRUD (and much more) interface, using DeltaSpike Data module.
*
* @author robin
*/
@Repository
interface VideoGameRepository extends EntityRepository <VideoGame, String>
{
// nothing to code here : automatic Repo generated by DeltaSpike
}
Here are the configuration files :
beans.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/beans_2_0.xsd"
bean-discovery-mode="annotated" version="2.0">
</beans>
persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.2" xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
http://xmlns.jcp.org/xml/ns/persistence/persistence_2_2.xsd">
<persistence-unit name="cdi-deltaspike-demo" transaction-type="RESOURCE_LOCAL">
<class>fr.fxjavadevblog.VideoGame</class>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:h2:mem:test"/>
<property name="javax.persistence.jdbc.driver" value="org.h2.Driver"/>
<property name="javax.persistence.schema-generation.database.action" value="create"/>
</properties>
</persistence-unit>
</persistence>
These files are duplicated into the test/resources/META-INF folder as well.
And finally, here is the unit test :
package fr.fxjavadevblog;
import org.jboss.weld.junit5.EnableWeld;
import org.jboss.weld.junit5.WeldInitiator;
import org.jboss.weld.junit5.WeldSetup;
import org.junit.Assert;
import org.junit.jupiter.api.Test;
import lombok.extern.slf4j.Slf4j;
import javax.inject.Inject;
/**
* simple test class for the VideoGameRepository, using LOMBOK and WELD.
*
* @author robin
*/
@Slf4j
@EnableWeld
class VideoGameRepositoryTest
{
@WeldSetup // This is need to discover Producers and DeltaSpike Repository functionality
private WeldInitiator weld = WeldInitiator.performDefaultDiscovery();
@Inject
private VideoGameRepository repo;
@Test
void test()
{
VideoGame videoGame = VideoGameFactory.newInstance();
videoGame.setName("XENON");
repo.save(videoGame);
// testing if the ID field had been generated by the JPA Provider.
Assert.assertNotNull(videoGame.getVersion());
Assert.assertTrue(videoGame.getVersion() > 0);
log.info("Video Game : {}", videoGame);
}
}
Usage of Lombok and the UUID producer is optional.
You can find the full code source, and clone the repo, on github : https://github.com/fxrobin/cdi-deltaspike-demo
A: I had similar issues with Deltaspike and a Junit5 integration test of a database repository.
Basically, I could not inject the repository when using Junit5 @Test annotations. I had to use Junit4 @Test annotations as a workaround.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/50688919",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Linking GSL statically using Cmake I'm linking GNU GSL with a pybind11 module. It works if GSL is linked as a shared library:
cmake_minimum_required(VERSION 2.8.12)
project(st)
# Paths
set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_SOURCE_DIR}/cmake/")
# Packages
add_subdirectory(pybind11)
find_package(GSL REQUIRED)
# Includes
set(DIRS ${GSL_INCLUDE_DIRS} ${GSLCBLAS_INCLUDE_DIRS})
include_directories(${DIRS})
# Python module
pybind11_add_module(st src/st.cpp)
# Libraries
set(LIBS ${LIBS} ${GSL_LIBRARIES} ${GSLCBLAS_LIBRARIES})
target_link_libraries(st PRIVATE ${LIBS})
How can I link it statically? I've tried a lot of different options but it doesn't work.
A: The trouble is that CMake resets the contents of CMAKE_FIND_LIBRARY_SUFFIXES during the PROJECT statement, see the file Modules/CMakeGenericSystem.cmake in the installation of CMake. For example, this CMakeLists.txt
cmake_minimum_required(VERSION 2.8.12)
message("CMAKE_FIND_LIBRARY_SUFFIXES = ${CMAKE_FIND_LIBRARY_SUFFIXES}")
project(st)
message("CMAKE_FIND_LIBRARY_SUFFIXES = ${CMAKE_FIND_LIBRARY_SUFFIXES}")
set(CMAKE_FIND_LIBRARY_SUFFIXES ".a") # <--- this is needed to replace the default
# Packages
find_package(GSL REQUIRED)
# Libraries
message("Libraries: ${GSL_LIBRARIES} ${GSLCBLAS_LIBRARIES}")
when executed as
cmake -D CMAKE_FIND_LIBRARY_SUFFIXES=".a" .
produces the output
CMAKE_FIND_LIBRARY_SUFFIXES = .a
-- The C compiler identification is GNU 9.2.1
-- The CXX compiler identification is GNU 9.2.1
-- Check for working C compiler: /usr/bin/cc
-- Check for working C compiler: /usr/bin/cc -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Detecting C compile features
-- Detecting C compile features - done
-- Check for working CXX compiler: /usr/bin/c++
-- Check for working CXX compiler: /usr/bin/c++ -- works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Detecting CXX compile features
-- Detecting CXX compile features - done
CMAKE_FIND_LIBRARY_SUFFIXES = .so;.a
-- Found PkgConfig: /usr/bin/pkg-config (found version "1.6.3")
-- Found GSL: /opt/gsl-2.6/include (found version "2.6")
Libraries: /opt/gsl-2.6/lib64/libgsl.a;/opt/gsl-2.6/lib64/libgslcblas.a
-- Configuring done
-- Generating done
Apparently, a possible solution seems to be to redefine the variable (by manually modifying the script) right after the PROJECT statement, as done in the above sample code.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/53247599",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: C: speed up for permutation of bits from given permutation table; searching for the minimum I'm searching for a fast permutation of bits within a number in C.
I have an integer value and table of permutation positions. Not all possible permutations are listet, just n!*2n of the 2n! possible permutations.
For simplicity I will show the data as 4-Bit numbers (n=2, lutsize = 8), in reality they are 32-Bit numbers (n=5, lutsize=3840):
static const uint8_t lut[lutsize][4] = {
{0, 1, 2, 3},
{1, 0, 3, 2},
{2, 3, 0, 1},
{3, 2, 1, 0},
{0, 2, 1, 3},
{1, 3, 0, 2},
{2, 0, 3, 1},
{3, 1, 2, 0}};
So the first entry is the identity, for the second entry the bits 1&2 and 2&3 switch places and so on. I wrote a method which calculates the values and returns the minimal value:
#include <stdio.h>
#include <stdint.h>
#include <assert.h>
enum { n = 2 };
enum { expn = 1<<n };
enum { lutsize = 8 };
static const uint8_t lut[lutsize][4] = {
{0, 1, 2, 3},
{1, 0, 3, 2},
{2, 3, 0, 1},
{3, 2, 1, 0},
{0, 2, 1, 3},
{1, 3, 0, 2},
{2, 0, 3, 1},
{3, 1, 2, 0}
};
uint32_t getMin(uint32_t in, uint32_t* ptr){
uint32_t pos, i, tmp, min;
uint8_t bits[expn];
tmp = in;
for (i = 0; i < expn; ++i){ // extract bits into array
bits[i] = tmp & 1;
tmp = tmp >> 1;
}
min = in;
for (pos = 0; pos < lutsize; ++pos){ // for each row in the permutation table
tmp = 0;
for (i = 0; i < expn; ++i){ // for each bit
tmp = tmp | (bits[i] << lut[pos][i]); // put bit i on position lut[pos][i]
}
ptr[pos] = tmp; // store result (optional)
//printf("%d: %d\n", pos, tmp);
if (tmp<min) { min = tmp; } // track minimum
}
//printf("min: %d\n", min);
return min;
}
void main(int argc, const char * argv[]) {
uint32_t ptr[lutsize];
printf("%u\n", (unsigned)getMin(5, ptr));
assert(getMin(5, ptr) == 3);
assert(getMin(0b0110, ptr) == 6);
}
gives the output for the example number 5 if you uncomment the printf's:
0: 5
1: 10
2: 5
3: 10
4: 3
5: 3
6: 12
7: 12
min: 3
I do calculate each permutation in a naive way by separating the bits into an array and then pushing them into their new position. I write the results into an array and keep track of the minimum which is returned at the end.
How do improve the performance of the procedure getMin for n=5?
I'm primarily interested in the minimum.
Additional input:
*
*the permutation table can be read as "bit value comes from position" or "bit value shifts to position". The results are the same, just the order of the entries differs.
*it is not necessary (but a bonus) to use the array (ptr)
*the goal is to reduce the time to compute the smallest bit permutation number for all 32-bit numbers in random order. Precalculating all possible minimum numbers is ok. Using multiple versions of the lut is ok. Anything is ok as long it does not take more than 4GB of ram like storing all possible input/output pairs would do.
*sorry for the not so c-like code. I'm out of training.
Here is the python code to generate the look up table for n=5:
from itertools import permutations
import numpy as np
import math
for n in [5]:
expn = 1<<n #2:4 3:8; 4:16; 5:32
order = np.zeros((int(math.factorial(n))*expn, expn), dtype=np.int8) # n!*2^n x 2^n matrix
cnt = 0 # current entry
permneg = np.zeros(expn, dtype=int)
for perm in permutations(list(range(n))): #shuffle order
ini = np.array(list(range(expn)), dtype=int) # list 0 to expn-1
out = np.zeros(expn, dtype=int)
for i in range(n): # apply permutation on position level
tmp = ini & 1 # get value on least bit
out += tmp << perm[i] #put it on the right postion
ini = ini >> 1 # next bit as least bit
for neg in range(expn): # include 0/1 swaps (negation)
for i in range(len(out)): # for all 2^n negation cases
permneg[i] = out[i] ^ neg # negate on negation bits
order[cnt]=permneg # store
cnt += 1 # increase counter
print("enum { lutsize = "+str(len(order))+" };")
s='},\n{'.join(', '.join(map(str,sl)) for sl in order)
print("static const uint8_t lut[lutsize]["+str(expn)+"] = {\n{"+s+"}\n};")
A: I would suggest two optimizations : 1) store the value of the set bit in the table instead. 2) Don't store each bit in an array but compute it on the fly instead. The result is the same, but it's probably a little bit faster.
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#define lutsize 8
static const uint8_t lutn[lutsize][4] = {
{1, 2, 4, 8},
{2, 1, 8, 4},
{4, 8, 1, 2},
{8, 4, 2, 1},
{1, 4, 2, 8},
{2, 8, 1, 4},
{4, 1, 8, 2},
{8, 2, 4, 1}};
uint32_t getMin(uint32_t in, uint32_t* ptr)
{
uint32_t pos, i, tmp, min;
uint8_t bits[expn];
tmp = in;
min = in;
for (pos = 0; pos < lutsize; ++pos){
tmp = 0;
for (i = 0; i < expn; ++i) {
// If the bit is set
if (in & (1<<i))
// get the value of the permuted bit in the table
tmp = tmp | lutn[pos][i];
}
ptr[pos] = tmp;
//printf("%d: %d\n", pos, tmp);
if (tmp<min) { min = tmp; } // track minimum
}
//printf("min: %d\n", min);
return min;
}
void main(int argc, const char * argv[]) {
uint32_t *ptr;
ptr = (uint32_t*) malloc(lutsize * sizeof(uint32_t));
getMin(5, ptr);
}
A: It seems to me that, not having all the possible permutations, you need to check all of those you have. Calculating the best permutation is not fruitful if you aren't sure that permutation is available.
So, the two optimizations remaining you can hope for are:
*
*Stop the search if you achieve a minimum.
For example, if I have understood, you have the binary number 11001101. What is the minimum permutation value? Obviously 00011111, with all ones to the right. What exact permutation does this for you - whether the last 1 is the first, second, fifth, sixth or eight bit - matters not to you.
As soon as a permutation hits the magic value, that is the minimum and you know you can do no better, so you can just as well stop searching.
In your own example you hit the minimum value 3 (or 0011, which is the minimum from 1001 or 5) at iteration 4. You gained nothing from iterations five to seven.
*If you have 1101, Go from { 0, 1, 3, 2 } to the bit-permutated value "1110" as fast as possible.
Not sure about the performances, but you could try precalculating the values from the table, even if this requires a 32x32 = 1024 32-value table - 4M of memory.
Considering the first position (our number is 1101), the permutation can have in position 0 only these values: 0, 1, 2, or 3. These have a value of 1___, 1___, 0___ or 1___. So our position 0 table is { 1000, 1000, 0000, 1000 }.
The second position is identical: { 1_, 1_, 0_, 1_ } and so we have { 0100, 0100, 0000, 0100 }.
The next two rows are { 0010, 0010, 0000, 0010 }
{ 0001, 0001, 0000, 0001 }.
Now, you want to calculate the value if permutation { 3, 0, 1, 2 } is applied:
for (i = 0; i < 4; i++) {
value |= table[i][permutation[i]];
}
===
But (again, if I understood the problem), let us say that the number has one fourth zeroes (it is made up of 24 1's, 8 0's) and the table is sizeable enough.
There is a very significant chance that you very soon hit both a permutation that puts a bit 1 in the 31st position, yielding some 2 billion, and another that puts a 0 there, yielding one billion.
The minimum will then surely be below two billions, so from now on, as soon as you check the first permutated bit and find it is a 1, you can stop calculating, you won't get a better minimum out of that permutation. Skip immediately to the next.
If you do this check at every cycle instead of only the first,
for (i = 0; i < 4; i++) {
value |= table[i][permutation[i]];
if (value > minimum) {
break;
}
}
I fear that you might eat any gains, but on the other hand, since values are automatically ordered in descending order, the first bits would get eliminated the most, avoiding the subsequent checks. It might be worth checking.
Nothing stops you from doing the calculation in two steps:
for (i = 0; i < 8; i++) {
value |= table[i][permutation[i]];
if (value > minimum) {
break;
}
}
if (value < minimum) {
for (; i < 32; i++) {
value |= table[i][permutation[i]];
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/64959509",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: WEB API returning TSV instead of XML/Json How can i make MVC or WEBAPI return TSV instead of XML or Json?
Is there any converter that will make this possible for me?
I have this API which returns either XML or Json, but i now want it to return tsv:
http://api.friliv.dk/api/miintoproducts
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56338316",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Why i get CAMERA_ERROR (3) when using flutter camera the following error occurs when using flutter camera plugin, I've added the permission to the manifest file, and still not working.
Launching lib\main.dart on sdk gphone x86 in debug mode...
Parameter format not correct -
✓ Built build\app\outputs\flutter-apk\app-debug.apk.
Installing build\app\outputs\flutter-apk\app.apk...
Connecting to VM Service at ws://127.0.0.1:64116/dm5AqTZrDK0=/ws
I/CameraManagerGlobal(20232): Connecting to camera service
W/Gralloc4(20232): allocator 3.x is not supported
E/CameraCaptureSession(20232): Session 0: Exception while stopping repeating:
E/CameraCaptureSession(20232): android.hardware.camera2.CameraAccessException: CAMERA_ERROR (3): The camera device has encountered a serious error
E/CameraCaptureSession(20232): at android.hardware.camera2.impl.CameraDeviceImpl.checkIfCameraClosedOrInError(CameraDeviceImpl.java:2231)
E/CameraCaptureSession(20232): at android.hardware.camera2.impl.CameraDeviceImpl.stopRepeating(CameraDeviceImpl.java:1241)
E/CameraCaptureSession(20232): at android.hardware.camera2.impl.CameraCaptureSessionImpl.close(CameraCaptureSessionImpl.java:578)
E/CameraCaptureSession(20232): at io.flutter.plugins.camera.Camera.closeCaptureSession(Camera.java:480)
E/CameraCaptureSession(20232): at io.flutter.plugins.camera.Camera.close(Camera.java:486)
E/CameraCaptureSession(20232): at io.flutter.plugins.camera.Camera$2.onError(Camera.java:187)
E/CameraCaptureSession(20232): at android.hardware.camera2.impl.CameraDeviceImpl.notifyError(CameraDeviceImpl.java:1629)
E/CameraCaptureSession(20232): at android.hardware.camera2.impl.CameraDeviceImpl.lambda$oDs27OTfKFfK18rUW2nQxxkPdV0(Unknown Source:0)
E/CameraCaptureSession(20232): at android.hardware.camera2.impl.-$$Lambda$CameraDeviceImpl$oDs27OTfKFfK18rUW2nQxxkPdV0.accept(Unknown Source:8)
E/CameraCaptureSession(20232): at com.android.internal.util.function.pooled.PooledLambdaImpl.doInvoke(PooledLambdaImpl.java:278)
E/CameraCaptureSession(20232): at com.android.internal.util.function.pooled.PooledLambdaImpl.invoke(PooledLambdaImpl.java:201)
E/CameraCaptureSession(20232): at com.android.internal.util.function.pooled.OmniFunction.run(OmniFunction.java:97)
E/CameraCaptureSession(20232): at android.os.Handler.handleCallback(Handler.java:938)
E/CameraCaptureSession(20232): at android.os.Handler.dispatchMessage(Handler.java:99)
E/CameraCaptureSession(20232): at android.os.Looper.loop(Looper.java:223)
E/CameraCaptureSession(20232): at android.app.ActivityThread.main(ActivityThread.java:7656)
E/CameraCaptureSession(20232): at java.lang.reflect.Method.invoke(Native Method)
E/CameraCaptureSession(20232): at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
E/CameraCaptureSession(20232): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
I/flutter (20232): CameraException(Previous capture has not returned yet., takePicture was called before the previous capture returned.)
A: You can also now use this plugin : CamerAwesome
Official plugin has been quite abandonned. This plugin includes flash, zoom, auto focus... and no initialisation required.
A: I also received this error when using Flutter camera plugin example when I changed it from CameraController.startVideoRecording() to CameraController.startImageStream(Function<CameraImage>).
To resolve this issue I commented/removed imageFormatGroup: ImageFormatGroup.jpeg at CameraController instantiation:
controller = CameraController(
cameraDescription,
ResolutionPreset.medium,
enableAudio: enableAudio,
//imageFormatGroup: ImageFormatGroup.jpeg, //remove or comment this line
);
This may happen because CameraImage received at startImageStream uses YUV image encoding.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/63712720",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: custome user serializer giving error on is_valid() - django For some reason I am not using form model to create the user form and so on so I am not using the form.is_valid()
I went through online and was taught to create a serializer like this
from django.contrib.auth.models import User
from rest_framework import serializers
class UserModelSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ['id', 'username', 'email', 'password']
I tried creating a new user object in python shell then use the serializers on the object then uses the is_valid() but it gives me false instead of true, also the password being created is not hashed too, it was just a string
I did something like this in python shell. (also tried one that has id too but the result is the same so I didn't bother pasting it again)
user1 = User.objects.create(username='username', email='[email protected]', password='password')
user1_s = UserModelSerializer(user1)
when I run user1_s this came up
UserModelSerializer(<User: username>):
id = IntegerField(label='ID', read_only=True)
username = CharField(help_text='Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.', max_length=150, validators=[<django.contrib.auth.validators.ASCIIUsernameValidator object>, <UniqueValidator(queryset=User.objects.all())>])
email = EmailField(allow_blank=True, label='Email address', max_length=254, required=False)
password = CharField(max_length=128)
run user1_s.data
{'username': u'username', 'password': u'password', 'id': 4, 'email': u'[email protected]'}
run user1_s = UserModelSerializer(data=user1)
run user1_s.is_valid() and False is returned
run user1_s.errors
{u'non_field_errors': [u'Invalid data. Expected a dictionary, but got User.']}
-----------------------------------
Can someone please let me know how I am doing this wrong and direct me to the right direction please?
Thanks in advance
A: You have a number of misconceptions here.
Firstly, the password is not hashed because you are not calling any method that hashes it. When you create a user, you must always call create_user, not create; it is the former that hashes the password.
user1 = User.objects.create_user(username='username', email='[email protected]', password='password')
Secondly, the reason user1_s is invalid is clearly explained in the error message: when you want to pass data into a serializer and get a User object out, you need to actually pass a dictionary of data in and not a User object.
So, as a test, this would work:
user1_serialize = UserModelSerializer(user1)
data = user1_serialize.data
user1_deserialize = UserModelSerializer(data=data)
user1_deserialize.is_valid()
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41780633",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Issue with GET form php/Ajax I am trying to build a dynamic site. I have an input form across the top that when it has been submitted show the output from an asynchronous request to a PHP page (which utilizes echo), showing what was submitted.
However it is not working. I submit it and the whole form disappears (this should not be happening either). I am at my wits ends with getting it to work and I can not seem to figure out what I am missing. Can anyone explain why it is not working as desired?
I am having trouble with the code page DomainDiagnostics.php. Excuse the bare bones- eventually I plan to populate the divs with AJAX calls to functions, but A.T.M. I just want it to echo out the input, and keep the Input form at the top...
Code - Index.php
</head>
<body>
<!--- This Keeps the navbar from staying right near top -->
<div class="header">
</div>
<!---- Nav bar, Using bootstrap ----->
<nav class="navbar navbar">
<div class="container-fluid">
<div class="navbar-header">
<div class="nav-bar-logo">
<a href="index.php" class="navbar-left"><img src="cwcs-logo.png"></a>
</div>
</div>
<div class="nav-list-container">
<ul class="nav navbar-nav">
<li><a id="dd" href="#">Domain Diagnostics</a></li>
<li><a id="sd" href="#">Server Diagnostics</a></li>
<li class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown" href="#">Second Line Tools
<span class="caret"></span></a>
<ul class="dropdown-menu">
<li><a id="dc" href="#">Daily Checklist</a></li>
<li><a id="bt" href="#">Backup Tracker</a></li>
<li><a id="tl" href="#">Task List</a></li>
</ul>
</li>
</ul>
</div>
</div>
</nav>
<!------- End of nav bar ---->
<!----- All content is initally loaded into this page-container --->
<div id="page-container">
</div>
</body>
</html>
Javascript - this loads the pages depending on which Button the Nav is clicked. I have only actually done the domain diagnostic page,
// Executes when document is ready
$(document).ready(function($)
{
// On click divs for the navigation bar that load the different views (pages)
$( "#dd" ).click(function()
{
$("#page-container").load("./views/domaindiagnostics.php");
});
$( "#sd" ).click(function()
{
$("#page-container").load("./views/serverdiagnostics.php");
});
$( "#dc" ).click(function()
{
$("#page-container").load("./views/dailychecklist.php");
});
$( "#bt" ).click(function()
{
$("#page-container").load("./views/backuptracker.php");
});
$( "#tl" ).click(function()
{
$("#page-container").load("./views/tasklist.php");
});
// end of nav bar
});
Domain Diagnostics page, so the input form shows as expected, but this is the bit thats not working
<?php
/// Grabs the domainclass php file and also grabs the users input and places in $domainName variable
require '../php/domainclass.php';
if (isset($_GET['userInput']))
{
$domainName = $_GET['userInput'];
echo $domainName;
}
?>
<form class="form">
<div class="domainquery">
<div class="input-group">
<input id="domainName" name="userInput" class="form-control input-md" type="text" placeholder="aaexamddple.org" value="<?php if (isset($domainName)) echo $domainName ?>" autocomplete="off" autofocus>
<div class="input-group-btn">
<button type="submit" class="btn btn-primary btn-md">Query Domain</button>
</div>
</div>
</div>
</form>
<div class="domain-d-container">
</div>
</div>
<script>
$(document).ready(function()
{
$( ".form" ).submit(function()
{
$(".domain-d-container").load("domaindiagnosticsresults.php",
{
d: "<?php echo $domainName ?>"
});
});
});
</script>
</body>
</html>
domaindiangosticsresults.php
<?php
$domainName = $_POST['d'];
echo $domainName;
?>
A: The cause
The form disappears because when the user clicks the button labeled Query Domain, the form is submitted. Because the form has no action method, it basically reloads index.php.
Changes
As have been pointed out in comments, there are a few things that need to be changed in order to get it working:
*
*in the form submission handler - prevent the default form submission by either
*
*calling preventDefault() on the event object (i.e. e in the example below), which is passed to the callback function:
$( ".form" ).submit(function(e)
{
//stop form submission
e.preventDefault();
*returning false at the end of the function
*pass the value of the input to the diagnostics results by appending it to the query string (e.g. use jQuery's $.val()):
$(".domain-d-container").load("domaindiagnosticsresults.php",
{
d: $('#domainName').val()
*there was an excess closing div tag (i.e. </div>) that should be removed after <div class="domain-d-container"></div> in the domaindiagnostics.php page.
*The (closing) </html> and </body> tags should be removed from the nested pages (e.g. domaindiagnostics.php), lest those tags exist as child tags of the body of the index page (those would not be permitted content of a <div> - only flow content is allowed).
See it demonstrated in this phpfiddle. Bear in mind that only one PHP page is allowed in that environment so I had to combine the three pages and use $_SERVER['PHP_SELF'] for the URLs and pass data via the query string, so some of the checks on $_POST were converted to checks on $_GET.
A: Maybe this link con help you. https://dailygit.com/create-a-simple-ajax-contact-form-with-jquery-and-php/
Remove the "send mail" part and focus on the form submission part. as said in other comments, prevent default is really important and the DOM structure must be cleaner as possible.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/44530124",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to insert JSON into MySQL with JQuery AJAX and CodeIgniter? I'm using Jquery Form Wizard/Form-Repeater and unable to insert value from multiple form using Form-Repeater into database using CodeIgniter. How to do this?
Let say, my database "table_data" as below:
| req_id | req_custname | req_type | req_data | req_comment |
CI View: Form Wizard & Form-Repeater:
<div class="main-panel">
<div class="content-wrapper">
<div class="row">
<div class="col-12 grid-margin">
<div class="card">
<div class="card-body">
<h4 class="card-title">New Request</h4>
<form id="req-form" action="" method="post">
<div>
<h3>Type</h3>
<section>
<h3>Type</h3>
<div class="form-group">
<form>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label name="errorl" id="error_req_type"></label>
<div class="form-check">
<label class="form-check-label">
<input type="radio" class="form-check-input" name="req_type" id="req_type" value="Urgent">URGENT
Urgent
</label>
</div>
<div class="form-check">
<label class="form-check-label">
<input type="radio" class="form-check-input" name="req_type" id="req_type" value="Normal">NORMAL
Normal
</label>
</div>
</div>
</div>
</div>
</form>
</div>
</section>
<h3>Customer Information</h3>
<section>
<h3>Customer Information</h3>
<div class="form-group">
<label>Customer's Name:</label>
<input name="req_custname" id="req_custname" type="text" class="form-control required" style="text-transform:uppercase" placeholder="Enter customer's name" value="" autofocus >
</div>
</section>
<h3>Details</h3>
<section>
<h3>BW Upgrade Details</h3>
<div class="form-group">
<label>Data:</label>
<div class="row">
<div class="col-lg-12">
<div class="card-body">
<form class="form-inline repeater">
<div data-repeater-list="group-a">
<div data-repeater-item class="d-flex mb-2">
<div class="input-group mr-sm-2 mb-sm-0">
<input type="text" name="fruit" class="form-control" id="inlineFormInputGroup1">
</div>
<div class="input-group mr-sm-2 mb-sm-0">
<input type="text" name="order" class="form-control" id="inlineFormInputGroup1">
</div>
<button data-repeater-delete type="button" class="btn btn-danger btn-sm icon-btn ml-2" >
<i class="mdi mdi-delete"></i>
</button>
</div>
</div>
<button data-repeater-create type="button" class="btn btn-info btn-sm icon-btn ml-2 mb-2">
<i class="mdi mdi-plus"></i>
</button>
</form>
</div>
</div>
</div>
</div>
</section>
<h3>Submit</h3>
<section>
<h3>Comments</h3>
<div class="form-group">
<label>Requestor's Comments</label>
<textarea type="text" class="form-control" rows="3" name="req_recomment" autofocus> </textarea>
</div>
</section>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
Ajax Post to CI:
var req_custname = $("input[name='req_custname']").val();
var req_type = $("input[name='req_type']:checked").val();
var req_recomment = $("textarea[name='req_recomment']").val();
var repeatval = $('.repeater').repeaterVal();
if(req_custname && req_type && req_recomment && repeatval)
{
$.ajax({
type: "POST",
url: BASE_URL+"/req/add",
dataType: "json",
data:
{
req_custname:req_custname,
req_type:req_type,
req_recomment:req_recomment,
repeatval:repeatval
},
});
};
CI Controller (Req_.php):
public function add()
{
$post = $this->input->post(null, TRUE);
$id = $this->req_m->add($post);
if ($this->db->affected_rows() > 0 ) {
$this->db->from('table_data');
$this->db->where('req_id', $id);
$result = $this->db->get()->result();
}
}
CI Model (Req_m.php):
public function add($post)
{
$params['req_custname'] = $post['req_custname'];
$params['req_type'] = $post['req_type'];
$params['req_comment'] = $post['req_comment'];
$params['req_data'] = $post['req_data'];
if ($this->db->table_exists('table_data') ) {
$this->db->insert('table_data', $params);
}
}
Above code works inserting into the database if I tried without the ajax post the form-repeater value
What I want is to insert JSON into the "req_data" from the Form Repeater.
Expected result in the database should as below:
| req_id | req_custname | req_type | req_data | req_comment |
| 1 | John | Manual | {“0”: {“fruit”: “apple”, “order”: “22”}, “1”: {“fruit”: “orange”, “order”: “4”} } | No comment |
| 2 | Mary | Urgent | {“0”: {“fruit”: “banana”, “order”: “6”} } | KIV |
A: Your json isn't correctly declared in your POST function.
Try changing:
if(req_custname && req_type && req_recomment && repeatval)
{
$.ajax({
type: "POST",
url: BASE_URL+"/req/add",
dataType: "json",
data:
{
req_custname:req_custname,
req_type:req_type,
req_recomment:req_recomment,
repeatval:repeatval
},
});
};
to:
if(req_custname && req_type && req_recomment && repeatval)
{
var postData = { "req_custname":req_custname,
"req_type":req_type,
"req_comment":req_recomment,
"req_data":repeatval };
var json = JSON.stringify(postData);
$.ajax({
type: "POST",
url: BASE_URL+"/req/add",
dataType: "json",
data: json,
});
};
See https://codepen.io/verdant-spark/pen/mdyyoXG for a working PoC of the json string creation.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/59147228",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Positioning of Divs - centered + fixed insues I have a div "general" which is centered on the page. Inside I have a fixed div at the top. Outside of that div "general" have the "footer" that is fixed to the bottom of the page. So far so good .. the problem is that the div "content" must be centered vertically and horizontally within that div "general ".... Can someone give me some tips there positioning?
<body>
<div id="mb_background" class="mb_background">
<img class="mb_bgimage" src="images/default.jpg" alt="Background"/>
<div class="mb_loading"></div>
</div>
<div id="mb_geral">
<div id="mb_topo">
<div id="mb_logo">
<a href=""><img src="images/logo_dentro.png" alt="Logotipo"/></a>
</div>
<div id="mb_menu">
</div>
<br clear="all"/>
</div>
<div id="mb_conteudo">
alguma coisa aqui
</div>
</div>
<div class="mb_footer">
<a class="mb_left" href="" target="_blank"><img src="images/facebook.png"/></a>
<a class="mb_left" href="" target="_blank"><img src="images/twitter.png"/></a>
<a class="mb_left" href="" target="_blank"><img src="images/news.png"/></a>
</div>
</body>
A: margin:0 auto;
in your css will centre the content div horizontally, to center it vertically, youd need
top:50%;
margin-top:-[insert half of the content div's height here];
| {
"language": "en",
"url": "https://stackoverflow.com/questions/8850111",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Paypal REST api support for China I just come across this link
https://www.paypal-forward.com/innovation/paypal-s-new-rest-apis-available-globally/
and was wondering where i can see list of country supported and currency supported, as when i login to my developer account, the sandbox account is still limited to few countries.
My use case is around providing payment using paypal in China ideally using RMB but fallback to USD will be acceptable too. Is this supported?
Thanks
A: Here is a link to the countries and currencies supported by the PayPal REST Payment API: https://developer.paypal.com/docs/integration/direct/rest_api_payment_country_currency_support/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/19925684",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Cout String and int in ternary operator A line in my c++ code reads:
cout<<(i%3==0 ? "Hello\n" : i) ;//where `i` is an integer.
But I get this error:
operands to ?: have different types 'const char*' and 'int
How can I modify the code (with minimum characters)?
A: Ugly:
i%3==0 ? cout<< "Hello\n" : cout<<i;
Nice:
if ( i%3 == 0 )
cout << "Hello\n";
else
cout << i;
Your version doesn't work because the result types of the expressions on each side of : need to be compatible.
A: You can't use the conditional operator if the two alternatives have incompatible types. The clearest thing is to use if:
if (i%3 == 0)
cout << "Hello\n";
else
cout << i;
although in this case you could convert the number to a string:
cout << (i%3 == 0 ? "Hello\n" : std::to_string(i));
In general, you should try to maximise clarity rather than minimise characters; you'll thank yourself when you have to read the code in the future.
A: operator<< is overloaded, and the two execution paths don't use the same overload. Therefore, you can't have << outside the conditional.
What you want is
if (i%3 == 0) cout << "Hello\n"; else cout << i;
This can be made a bit shorter by reversing the condition:
if (i%3) cout << i; else cout << "Hello\n";
And a few more characters saved by using the ternary:
(i%3)?(cout<<i):(cout<<"Hello\n");
A: std::cout << i % 3 == 0 ? "Hello" : std::to_string(i);
But, as all the other answers have said, you probably shouldn't do this, because it quickly turns into spaghetti code.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/14649845",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: In a SELECT how can I change what shows when I select a BIT column? I have a table with a column like this:
[p3] BIT DEFAULT ((0)) NOT NULL,
In a select statement I want to return "p3" if this is set to 1 and "" if it is set to 0.
Is there an easy way that I can do this?
A: Use Choose or IIF function
Select Choose([p3]+1 , '' ,'p3')
From yourtable
Select IIF([p3]=0 , '' ,'p3')
From yourtable
for older versions use CASE statement
Select Case when [p3] = 0 then '' else 'p3' End
From yourtable
A: select
case when p3 = 1 then 'p3' else '' end
from yourTable
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41984389",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: akka cluster fast handover I'm using an akka cluster singleton feature to have a single master node and multiple worker nodes. Worker nodes send results to the master and master persists them in a database.
The problem is that it takes akka about 10 seconds to hand the singleton over, which results in 10 seconds downtime every time I deploy. Is there a way to make the singleton handover faster? Or is there some other approach to a single master - multiple workers pattern?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/55724371",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Minimizing the scope of a variable in do ... while loop [Java] - ERROR: Symbol cannot be found I would like to minimize the scope of arr to a do ... while loop, so it can be destroyed once the loop is exited.
If I declare arr within the do while loop, I get the error:
symbol cannot be found
I can declare it right before the cycle, but then I keep bloated arr in memory even though I don't need it any more.
//int[] arr = {0}; // this works, but the scope is outside the loop
do {
int[] arr = {0}; // causes "cannot find symbol" on `while` line
arr = evolve(arr); // modifies array, saves relevant results elsewhere
} while (arr.length < 9999);
What is the correct way to deal with this situation?
A: You have:
*
*An initial state
*A terminating state
*An iterative operation
So you have everything needed to use a for loop (albeit without a body):
for (int[] arr = {0}; arr.length < 9999; arr = evolve(arr));
Another solution, but nowhere near as neat, is to add this after the loop:
arr = null;
which still allows the allocated memory to be garbage collected and has a similar practical effect to restricting scope. Sometimes you need this approach if you can't refactor the code another way.
A: You have a couple of ways. You can declare boolean token outside of a cicle and check against it. You can encapsulate the whole thing in a method that ends right after do while.
A: @Bohemian's solution is elegant.
But, if you still wan't to achieve this using do.. while, then following solution should work
int l = 9999;
do {
int[] arr = { 0 }; // causes "cannot find symbol" on `while` line
arr = evolve(arr); // modifies array, saves relevant results elsewhere
l = arr.length;
} while (l < 9999);
A: You could also define the array outside the do-while loop and wrap the whole thing in a small method. The array will then be garbage collected when the method ends. This also helps to structure your code.
A: Yet another option - although arguably not better than any of those already mentioned - would be to wrap it into a block:
{
int[] arr = {0}; // this works, but the scope is outside the loop
do {
int[] arr = {0};
arr = evolve(arr); // modifies array, saves relevant results elsewhere
} while (arr.length < 9999);
}
I'd prefer @martinhh's solution though - just extract it to a method with a meaningful name.
The body-less for loop is fine, too - but it would probably be a good idea to leave a comment there that it was indeed intentional to omit the body - things like that tend to get highlighted by static analysis tools and may cause some confusion.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/38773628",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Generate report from a table I have a table like:
+====+========+========+
| Id | name | value |
+====+========+========+
| 1 | a | 7 |
+----+--------+--------+
| 2 | c | 7 |
+----+--------+--------+
| 1 | g | 1 |
+----+--------+--------+
| 2 | c | 2 |
+----+--------+--------+
| 4 | g | 5 |
+----+--------+--------+
| 6 | t | 4 |
+----+--------+--------+
I need to write two (2) queries to generate two reports, according to this two conditions:
Report Output1=if id and name same (id,name,val)
Report Output2=if id same but different name(id,name,val)
How to write those two queries?
A: Your conditions is not clear, but mybe this what you want:
DECLARE @T TABLE (Id INT, Name VARCHAR(25), Value INT);
DECLARE @YourId INT = 1;
DECLARE @YourName VARCHAR(25) ='a';
/**/
INSERT INTO @T VALUES
(1, 'a', 7),
(2, 'c', 7),
(1, 'g', 1),
(2, 'c', 2),
(4, 'g', 5),
(6, 't', 4);
/*First query*/
SELECT *
FROM @T
WHERE ID = @YourID AND Name = @YourName;
/*Second query*/
SELECT *
FROM @T
WHERE ID = @YourID;
If you want the result of both queries in one result, then you can use UNION ALL as:
SELECT *
FROM @T
WHERE ID = @YourID AND Name = @YourName
UNION ALL
SELECT *
FROM @T
WHERE ID = @YourID;
Demo.
A: Well, I am not sure, what OP wanted, but maybe it was something like this?
// records where id and value are the same
SELECT * FROM @T WHERE ID=Value;
// other records having the same ids as abobe, but DIFFERENT values
SELECT * FROM @T WHERE ID IN
(SELECT ID FROM @T WHERE ID=Value)
AND Id!=Value;
Results:
Id Name Value
1 g 1
2 c 2
Id Name Value
1 a 7
2 c 7
Thanks to @Sami for providing the fiddle which I modified into this DEMO.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46392895",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: in sql server when deadlock occured, WHICH transaction will be abort when deadlock occurs in sql server, which of transactions will be aborted. I mean what's the plan of sql server to decide which of transactions should be killed!
consider the two transaction below
Transaction A
begin transaction
update Customers set LastName = 'Kharazmi'
waitfor delay '00:00:5'; -- waits for 5 second
update Orders set OrderId=13
commit transaction
Transaction B
begin transaction
update Orders set OrderId=14
waitfor delay '00:00:5'; -- waits for 5 second
update Customers set LastName = 'EbneSina'
commit transaction
if both transaction are executed at the same time, transaction A locks and updates Customers table whereas transaction B locks and updates Orders table. After a delay of 5 second, transaction A looks for the lock on Orders table which is already held by transaction B and transaction B looks for the lock on Customers table which is already held by transaction A. So both the transactions can not proceed further, the deadlock occurs.
my question is that, when deadlock occurs, which of the both transaction will be aborted.
first, i executes transaction A then transaction B, sql server aborts transaction A and then first executes transaction B then A the result is the same and transaction A is alorted again. it confused me!
thanks for any help.
A: You can learn the criteria in SET DEADLOCK_PRIORITY (Transact-SQL):
Which session is chosen as the deadlock victim depends on each
session's deadlock priority:
*
*If both sessions have the same deadlock priority, the instance of SQL Server chooses the session that is less expensive to roll back as
the deadlock victim. For example, if both sessions have set their
deadlock priority to HIGH, the instance will choose as a victim the
session it estimates is less costly to roll back.
*If the sessions have different deadlock priorities, the session with the lowest deadlock priority is chosen as the deadlock victim.
For your case, A should be considered by DBMS the less expensive transaction to roll back.
A: There's no way to know just be looking at the queries. Basically, so far as I understand things, the engine considers all transactions involved in the deadlock and tries to work out which one will be the "cheepest" to roll back.
So, if, say, there are 2 rows in your Customers table, and 9000000 rows in your Orders table, it will be considerably cheeper to rollback the UPDATE applied to Customers than the one that was applied to Orders.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/22966732",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: X button not closing bootstrap error alert I have an error div that displays errors:
<div *ngIf="isScreenError" class="alert alert-danger alert-dismissible">
<button class="close" type="button" data-dismiss="alert" (click)='closeAlert()'>×</button>
ERROR: {{errorMessage.error.message}}</div>
The close alert function just sets 'isScreenError' to false.
closeAlert(){
this.isScreenError=false;
}
Why isn't my div closing? Not sure what I'm doing wrong here.
Thank you!
A: What kind change detection do you use? Is OnPush?
https://angular.io/api/core/ChangeDetectionStrategy
enum ChangeDetectionStrategy {
OnPush: 0
Default: 1
}
OnPush: 0
Use the CheckOnce strategy, meaning that automatic change detection is deactivated until reactivated by setting the strategy to Default (CheckAlways). Change detection can still be explicitly invoked. This strategy applies to all child directives and cannot be overridden.
If you using OnPush you should start change detection manually.
https://angular.io/api/core/ChangeDetectorRef detectChanges() or markForCheck()
Example:
import { Component, ChangeDetectionStrategy, ChangeDetectorRef } from '@angular/core';
@Component({
selector: 'alert',
template: `
<div *ngIf="isScreenError" class="alert alert-danger alert-dismissible">
<button class="close" type="button" data-dismiss="alert" (click)='closeAlert()'>×</button>
ERROR: {{errorMessage.error.message}}
</div>
`,
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class AlertComponent {
public errorMessage = {
error: {
message: 'Some message'
}
};
public isScreenError = true;
constructor(
private cd: ChangeDetectorRef,
) { }
public closeAlert(): void {
this.isScreenError = false;
this.cd.markForCheck();
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56690225",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.