text
stringlengths 15
59.8k
| meta
dict |
|---|---|
Q: how to manage file for import in Python? I want to get a common library from several files.
In order to reduce the amount of code, I want to create and manage a separate file for import.
Will it be possible?
import_lib.py
from django.shortcuts import render, get_object_or_404
other_1.py
import import_lib
render()
get_object_or_404()
other_2.py
import import_lib
render()
get_object_or_404()
A: Don't try to hide the imports needed in your module in another module - it'll make your code harder to read. And good editors will allow you to collapse the import section if it gets in the way of editing. There's ways of doing this, but they'll make your code harder to understand and it'll increase the odds of errors that are hard to figure out for yourself.
Having said that - this is how it can be done, if for some reason you know better, or actually have that rare use case where it makes sense:
import_lib.py
from django.shortcuts import render, get_object_or_404
other.py
from import_lib.py import * # a rare case where a * import actually makes sense
Since * imports everything and makes it part of the name space of the module doing the importing, you get exactly what you need.
If you feel your use case does warrant this, at least consider a name for the imported module that's a bit more descriptive, like django_imports.py, or whatever the logical grouping for the imports in that file is.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73836470",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Paypal Callback url for android Am calling PayPal Here APpp from my application using the following url
"paypalhere://takePayment/?returnUrl={{returnUrl}}&invoice=%7B%22merchantEmail%22%3A%22%22,%22payerEmail%22%3A%22spotireddy-biz%40paypal.com%22,%22itemList%22%3A%7B%22item%22%3A%5B%7B%22name%22%3A%22{{name}}%22,%22description%22%3A%22{{description}}%22,%22quantity%22%3A%221.0%22,%22unitPrice%22%3A%22{{price}}%22,%22taxName%22%3A%22Tax%22,%22taxRate%22%3A%220.0%22%7D%5D%7D,%22currencyCode%22%3A%22{{currency}}%22,%22paymentTerms%22%3A%22DueOnReceipt%22,%22discountPercent%22%3A%220.0%22%7D";
Any idea how to replace the merchantEmail and payerEmail from this url
A: fixed.. :)
here s the code
"paypalhere://takePayment/?returnUrl={{returnUrl}}&invoice=%7B%22merchantEmail%22%3A%22{{merchantEmails}}%22,%22payerEmail%22%3A%22{{payerEmails}}%22,%22itemList%22%3A%7B%22item%22%3A%5B%7B%22name%22%3A%22{{name}}%22,%22description%22%3A%22{{description}}%22,%22quantity%22%3A%221.0%22,%22unitPrice%22%3A%22{{price}}%22,%22taxName%22%3A%22Tax%22,%22taxRate%22%3A%220.0%22%7D%5D%7D,%22currencyCode%22%3A%22{{currency}}%22,%22paymentTerms%22%3A%22DueOnReceipt%22,%22discountPercent%22%3A%220.0%22%7D"
url = url.replace("{{merchantEmails}}", "merchantEmails@merchantEmails.com");
url = url.replace("{{payerEmails}}", "test@tesma.com");
url = url.replace("{{price}}", "1");
url = url.replace("{{name}}", Title);
url = url.replace("{{description}}", "Title");
url = url.replace("{{currency}}", "currencyType");
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/19043380",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: how to efficiently decode h264 encoded rtsp stream and use it to opencv-python at 30 FPS I'm just doing yolo object detection with opencv code snippet:
cap = cv2.VideoCapture("rtsp://admin:asv@123@192.168.1.24:554/main?tcp", cv2.CAP_FFMPEG)
show = True
while show:
ref, img = cap.read()
img = cv2.resize(img, (1024, 720))
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
res = model(img)
so, this is a normal code snippet for yolo object detection with opencv and torch
It's working good on with USB webcam, video files etc.
But with the RTSP stream and h264/h265 codec the cv2.VideoCapture() cannot decode it efficiently(at 30 FPS). But if it's on 6 FPS,it can. But I need to do it on 30 FPS.
I saw some documentation, i.e. opencv VideoCapture officially doesn't support h264/h265 codec. so is there any way to decode h264 encoded stream efficiently at 30 FPS in python and the use it to opencv and object detection?
Thanks.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72447392",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Simple Chechlist PHP Application Help needed I am building a simple PHP checklist application which takes sentences as input which are stored in MYSQL database then the list is echoed out with remove buttons in front of each list item such as:
*
*1) Do breakfast [remove button]
*2) Go to College [remove button]
*3) Eat Lunch [remove button]
*4) Get back Home [remove button]
Now what would be function that will be executed to remove the current list item being removed.
Here is how I am retrieving the list from database and their corresponding remove buttons:
$sql2 = "SELECT * FROM `info` LIMIT 0, 30 ";
$arr = mysql_query($sql2);
while($data = mysql_fetch_array($arr)){
echo '<strong>'.$data['id'].')</strong>'.' '.$data['text'].'<form action="list.php" method="POST">
<input type="submit" value="Remove" />
</form>'.'<br />';
Please help me how can we approach to a situation like this.
P.S The database has two columns only "ID" and the "List item"
A: You can use < input type='hidden' name='data' value="<?php echo $data[text]; ?>" > in the form
Finally, you can put this block to remove.
if(isset($_POST['submit']) {
$query = "delete from info where text = '$_POST[data]'";
//run the query here
}
A: What is it that you want particularly?
Do you mean you want the application to get check box elements and store them in the database.
Then get that data and apply to each a delete command?
be specific my friend and we can help.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/14413597",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Is there a onselect event for non-form elements? Say I want to hide a span when the user highlights a bit of text containing that span, with the intention of copying that text on to his clipboard.
For example:
<p>The dragon <span class="tooltip">a large, mythical beast</span> belched
fire at St. George.</p>
I have found that in Firefox Mac, span.tooltip will disappear from view (in accordance with my CSS declarations) but will show up in the clipboard when it's copied there. I figured (wrongly?) that if I said "onHighlight, hide tooltip," maybe this wouldn't happen.
A: Though it may be more complicated, why not just have an onmousedown event on the <p> element, and thet event will then attach an onmousemove event and onmouseout event, so that if there is a mouse movement, while the button is down, then remove the class on the span elements, and once the user exits, the element then you can put them back.
It may be a bit tricky, and you may want to also look for key presses, or determine other times you want to know when to put back the css classes, but this would be one option, I believe.
A: It sounds like you need to go one step further and on highlight, remove the <span> and save a reference to it. Once the highlight is finished, re-insert the reference to the object.
// copy start detected
var savedTooltip = $('.tooltip').remove();
// later that day when copy finished
$('p').append(savedTooltip);
If position of the <span> in your markup is important, you'd have to create a temporary reference element so you'd know where to re-insert it in the DOM.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/3326914",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How do I draw a triangle? I know how to draw a rectangle and circles and ect with g.drawRect or g.drawOval. But there is no g.drawtriangle. Is there a way to draw a triangle with out me having to draw it out each side of the triangle?
A: You may use Graphics.drawPolygon(int[], int[], int) where the first int[] is the set of x values, the second int[] is the set of y values, and the int is the length of the array. (In a triangle's case, the int is going to be 3)
Example:
graphics.drawPolygon(new int[] {10, 20, 30}, new int[] {100, 20, 100}, 3);
Output:
A: I would use a Path2D object, and would place my first point with its moveTo(...) method, and then add additional points with its lineTo(...) method. Then I could draw it or fill it via Graphics2D#draw(...) and Graphics2D#fill(...). Also calling closePath() on it will make sure that your triangle closes appropriately.
For example, the following code produces:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.RenderingHints;
import java.awt.geom.Path2D;
import javax.swing.*;
public class Path2DExample extends JPanel {
private static final int PREF_W = 600;
private static final int PREF_H = PREF_W;
private static final Color COLOR_1 = Color.blue;
private static final Color COLOR_2 = Color.red;
private static final Paint GRADIENT_PAINT = new GradientPaint(0, 0, COLOR_1, 20, 20, COLOR_2, true);
private Path2D myPath = new Path2D.Double();
public Path2DExample() {
double firstX = (PREF_W / 2.0) * (1 - 1 / Math.sqrt(3));
double firstY = 3.0 * PREF_H / 4.0;
myPath.moveTo(firstX, firstY);
myPath.lineTo(PREF_W - firstX, firstY);
myPath.lineTo(PREF_W / 2.0, PREF_H / 4.0);
myPath.closePath();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
// to smooth out the jaggies
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.setPaint(GRADIENT_PAINT); // just for fun!
g2.fill(myPath); // fill my triangle
}
@Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
private static void createAndShowGui() {
Path2DExample mainPanel = new Path2DExample();
JFrame frame = new JFrame("Path2DExample");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
An additional benefit to use of a Path2D object is that if you want to drag the Shape, it's not hard to do with a MouseListener and MouseMotionListener, say something like:
private class MyMouseAdapter extends MouseAdapter {
private Point pPressed = null;
@Override
public void mousePressed(MouseEvent e) {
if (e.getButton() != MouseEvent.BUTTON1) {
return;
}
if (myPath.contains(e.getPoint())) {
pPressed = e.getPoint();
}
}
public void mouseDragged(MouseEvent e) {
drag(e);
}
@Override
public void mouseReleased(MouseEvent e) {
drag(e);
pPressed = null;
}
private void drag(MouseEvent e) {
if (pPressed == null) {
return;
}
Point p = e.getPoint();
int tx = p.x - pPressed.x;
int ty = p.y - pPressed.y;
AffineTransform at = AffineTransform.getTranslateInstance(tx, ty);
myPath.transform(at);
pPressed = p;
repaint();
};
}
The whole thing could look like:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.Point;
import java.awt.RenderingHints;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.AffineTransform;
import java.awt.geom.Path2D;
import javax.swing.*;
@SuppressWarnings("serial")
public class Path2DExample extends JPanel {
private static final int PREF_W = 600;
private static final int PREF_H = PREF_W;
private static final Color COLOR_1 = Color.blue;
private static final Color COLOR_2 = Color.red;
private static final Paint GRADIENT_PAINT = new GradientPaint(0, 0, COLOR_1,
20, 20, COLOR_2, true);
private Path2D myPath = new Path2D.Double();
public Path2DExample() {
double firstX = (PREF_W / 2.0) * (1 - 1 / Math.sqrt(3));
double firstY = 3.0 * PREF_H / 4.0;
myPath.moveTo(firstX, firstY);
myPath.lineTo(PREF_W - firstX, firstY);
myPath.lineTo(PREF_W / 2.0, PREF_H / 4.0);
myPath.closePath();
MyMouseAdapter myMouseAdapter = new MyMouseAdapter();
addMouseListener(myMouseAdapter);
addMouseMotionListener(myMouseAdapter);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.setPaint(GRADIENT_PAINT);
g2.fill(myPath);
}
@Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
private class MyMouseAdapter extends MouseAdapter {
private Point pPressed = null;
@Override
public void mousePressed(MouseEvent e) {
if (e.getButton() != MouseEvent.BUTTON1) {
return;
}
if (myPath.contains(e.getPoint())) {
pPressed = e.getPoint();
}
}
public void mouseDragged(MouseEvent e) {
drag(e);
}
@Override
public void mouseReleased(MouseEvent e) {
drag(e);
pPressed = null;
}
private void drag(MouseEvent e) {
if (pPressed == null) {
return;
}
Point p = e.getPoint();
int tx = p.x - pPressed.x;
int ty = p.y - pPressed.y;
AffineTransform at = AffineTransform.getTranslateInstance(tx, ty);
myPath.transform(at);
pPressed = p;
repaint();
};
}
private static void createAndShowGui() {
Path2DExample mainPanel = new Path2DExample();
JFrame frame = new JFrame("Path2DExample");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/29447994",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: limit the max value for an input in haml I'm pretty new in coding with RoR and I'm using Haml, and since I'm doing a school project I decided to give it a try. The thing is that I encountered an issue. There's an attribute in my object producto, req_quantity which is the quantity of a certain product a client requested. In my views, I have an input box for the admin to authorize the quantity the client requested
.col-xs-2
.text-center
= product.input :auth_quantity, label: false, required: "required"
I'd like to limit :auth_quantity to be less or equal to req_quantity since currently is allowing values greater than req_quantity.
This is my first question since I googled and I don't seem to find the answer.
A: This is how I'd do it in haml:
.col-xs-2
.text-center
= product.input :auth_quantity, type: "number", max: "<%= producto.req_quantity %>" label: false, required: "required"
Where producto.req_quantity is the numerical value of the quantity of a certain product a client requested.
A: So I basically solved it like this. Thanks for the answer, made me think a lot!!
.col-xs-2
.text-center
= producto.input :auth_quantity, input_html: { min: '0', max: product.object.req_quantity, step: 'any' }, label: false, required: "required"
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/46571083",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to run-android a shoutem clone project? When I react-native run-android a shoutem clone project, first it was showing a development server error code 500..I changed the react-native and babel preset for react native from package.json. And now there is no error but the app crashes right after build. What can I do to fix this?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/55607893",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Python os.listdir and path with escape character I have a string variable that I have read from a file which is a path that contains an escape character i.e.
dir="...Google\\ Drive"
I would like to then list all the files and directories in that path with os.listdir i.e.
os.listdir(dir)
But I get this error (because I really only want one escape):
OSError: [Errno 2] No such file or directory: '....Google\\ Drive/'
I have tried using
os.listdir(r'....Google\ Drive')
os.listdir(dir.replace("\\","\"))
os.listdir(dir.decode('string_escape'))
all to no avail. I read this Python Replace \\ with \, but "...Google\ drive".decode('string_escape') != "...Google\ Drive".
Any ideas?
A: If the path could be arbitrary , you can split the the strings using \\ removing any '' you may get along the way and then do os.path.join , Example -
>>> import os.path
>>> l = "Google\Drive\\\\ Temp"
>>> os.path.join(*[s for s in l.split('\\') if l != ''])
'Google\\Drive\\ Temp'
Then you can use that in os.listdir() to list the directories.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/31064190",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Charts in Ionic 2 I need to create charts in an app, which uses Ionic 2. I searched the web but found some very scarce models. And also http://www.chartjs.org, but his documentation is very poor.
I mostly need donut charts, with click events. Or is it possible for me to have a click event on the chartjs donut chart? How can I do this?
A: You should use ng2-charts which is a ChartJS wrapper for Angular 2/4.
Using this you can create a simple doughnut chart (with click event) as follows :
template
<div id="chart-container">
<canvas baseChart
[chartType]="chartType"
[data]="chartData"
[labels]="chartLabels"
(chartClick)="chartClicked($event)">
</canvas>
</div>
component
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
public chartType: string = 'doughnut';
public chartLabels: Array<string> = ['Jan', 'Feb', 'Mar'];
public chartData: Array<number> = [1, 1, 1];
public chartClicked(e: any): void {
if (!e.active.length) return; //return if not clicked on chart/slice
alert('Clicked on Chart!');
}
}
LIVE DEMO
( this shouldn't be too hard to implement in Ionic 2 )
note: this is just a basic example of a doughnut chart and you can customize it further to fit your need, following the official documentation.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/46303615",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: View Screen And Print Screen is Diverent on Laravel PHP This is The Problem Picture
View Screen
Print Screen
Why Screen is Diverent, I want All Screen is Same, I search for tutorial and not working on me
I create this for my report Invoice
This is The View Code all in one page
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Kwitansi</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<style>
body{
font-family:'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif;
color:#333;
font-size:12pt;
}
.container{
margin:0 auto;
width:21cm;
height:11cm;
background-size: 8cm;
background-repeat: no-repeat;
background-position-x: 50%;
background-position-y: 50%;
background-image: url({{ asset('appy/images/logo2.png')}});
}
table{
width: 20cm;
height: 10cm;
border-collapse:collapse;
}
table th, table td{
width: 5cm;
border-style: none !important;
}
.tg {border-collapse:collapse;border-spacing:0;}
.tg td{font-family:Arial, sans-serif;font-size:14px;padding:10px 1em;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:black;}
.tg th{font-family:Arial, sans-serif;font-size:14px;font-weight:normal;padding:10px 1em;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:black;}
.tg .tg-pstd{font-family:Tahoma, Geneva, sans-serif !important;border-color:#000000;text-align:left;vertical-align:top}
.tg .tg-i09r{font-family:Tahoma, Geneva, sans-serif !important;border-color:#000000;text-align:left;vertical-align:middle}
.tg .tg-rk7a{font-size:16px;font-family:Tahoma, Geneva, sans-serif !important;text-align:left;vertical-align:middle}
.tg .tg-rm9j{font-size:12px;font-family:Tahoma, Geneva, sans-serif !important;border-color:#000000;text-align:right;vertical-align:middle}
.tg-pstd2{text-transform: uppercase;font-family:"Comic Sans MS", cursive, sans-serif !important;background-color: #e6e6e6;-webkit-transform: skew(-20deg);-moz-transform: skew(-20deg);-o-transform: skew(-20deg);transform: skew(-20deg);}
.tg-pstd2_1{font-size:20px;width:7cm;height:1cm;margin:0 auto;text-align:center;text-transform:uppercase;font-family:"Comic Sans MS", cursive, sans-serif !important;background-color: #e6e6e6;-webkit-transform: skew(-20deg);-moz-transform: skew(-20deg);-o-transform: skew(-20deg);transform: skew(-20deg);padding:1px 1px !important;}
.tg-pstd2_2{text-align: center}
</style>
</head>
<body>
<div class="container">
<table class="tg" id="print">
<tr>
<th class="tg-rk7a" colspan="3">Invoice #{{ $kwitansi->id }}</th>
<th class="tg-rm9j"><img height="25cm" src="{{ asset('appy/images/PIKSI.jpg') }}" alt=""></th>
</tr>
<tr>
<td class="tg-i09r"><u>Received From</u> <br> Telah Diterima Dari</td>
<td class="tg-i09r" colspan="3">{{ $kwitansi->received }} <br> ..........................................................................................................................</td>
</tr>
<tr>
<td class="tg-i09r"><u>Received From</u> <br> Telah Diterima Dari</td>
<td class="tg-i09r" colspan="3">{{ "Rp. ". format_uang($kwitansi->registration) }} <br> ..........................................................................................................................</td>
</tr>
<tr>
<td class="tg-i09r"><u>Received From</u> <br> Telah Diterima Dari</td>
<td class="tg-i09r" colspan="3">{{ "Rp. ". format_uang($kwitansi->course) }} <br> ..........................................................................................................................</td>
</tr>
<tr>
<td class="tg-i09r"><u>Received From</u> <br> Telah Diterima Dari</td>
<td class="tg-i09r" colspan="3">{{ "Rp. ". format_uang($kwitansi->trasnportation) }} <br> ..........................................................................................................................</td>
</tr>
<tr>
<td class="tg-pstd"><u>Received From</u> <br> Telah Diterima Dari</td>
<td class="tg-pstd2" colspan="3"><b>{{ terbilang($kwitansi->sum_rp) }}</b> <br> .....................................................................................................................................................</td>
</tr>
<tr>
<td class="tg-pstd"><u>Received From</u> <br> Telah Diterima Dari</td>
<td class="tg-pstd" colspan="3"><b>{{ $kwitansi->payment }}</b> <br> ..........................................................................................................................</td>
</tr>
<tr>
<td class="tg-pstd" colspan="2"><div class="tg-pstd2_1"><b>{{ "Rp. ". format_uang($kwitansi->sum_rp) }}</b></div></td>
<td class="tg-pstd2_2">
</td>
<td class="tg-pstd2_2">
<div>
<p>
Bandung, {{ $kwitansi->register_at }} <br>
Penerima <br><br><br><br>
{{ $kwitansi->received }}
</p>
</div>
</td>
</tr>
</table>
</div>
</body>
</html>
I Use Single Page for it css and js in one page
What is my mistake
Can Help Me Please
Thanks for Helping
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/60261247",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Hex number to area I am using VB.net 2012 and I am trying to convert a HEX number to a checkbox.
I have 96 check boxes on a form. d1, d2, d3.. d96 (that is the name of the checkbox's).
I have a HEX number that I need to convert and tick the check box based on it's value.
For Example:
If the HEX value equals 0x5 then checkbox's d1 and d3 need to be ticked only.
If the HEX value equals 0x20 then only checkbox d6 need to be ticked.
If the HEX value equals 0x42400 then checkbox's d10, d13, d18 need to be ticked only.
I haven't been able to work out how to convert this hex value and select the checkbox based on this value.
I then need to do it the other way around. select the check boxes and then click on a button to work out the HEX value based on what has been selected.
Any help would be great.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/36494152",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to restore my System Python 2.6 on OS X 10.6.8 I was messing around with Python in Library/Frameworks as well as System/Library/Frameworks. I deleted System/Library/Frameworks/Python.framework/Version/2.6. Then I copied in the equivalent directory from Library/Frameworks...
Will that break my OSX? If so, is there any way to restore the system python setup.
Not sure if this is relevant:
$ which python
usr/local/bin
$ python -V
Python 2.6
A: There's a subtlety between /Library and /System/Library that I do not understand. Therefore, this answer is flawed.
However. Even with that gap, I suggest you do this.
*
*Backup your data. All of it. Backup any apps you installed.
*Buy 10.7 Lion.
*Install. I don't think you need to do a "fresh" install. But some Mac users strongly suggest fresh installs of each new OS release.
*Restore your files.
Don't delete Python. iLife (for one) requires it.
A: Don't mess with the pre-installed python. It will break dependencies on your mac. It happened to me, I had to re-install to fix it. A better thing to do is to install a new version of python.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/8961126",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Using the jQuery autocomplete widget in SharePoint search box I implemented the autocomplete widget for jQuery for my SharePoint 2010 text box. But I see that the suggestion terms appearing with a Bullet point as shown below. Can anyone tell how can it be averted.
Thanks in advance.
A: That's something you can fix with CSS. However, if you have a proper reference to the jQueryUI CSS file, I don't think you should be seeing this. Make sure that reference is present and correct.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/8284669",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: phpmailer eml file with rfc/822 not opening on outlook but open on gmail I am implementing some code to send an eml file with phpmailer.
When I'm using mime_type for eml attachements of rfc/822, it's opening in Gmail but not opening in Outlook. If I change mime_type to application/octet-stream, it's opening in Outlook but not in Gmail.
application/octet-stream -> gmail(not working) outlook(working)
application/vnd.ms-outlook -> gmail(not working) outlook(working)
application/CDFV2-encrypted -> gmail(not working) outlook(working)
message/rfc822 -> gmail(working) outlook(not working)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/55473956",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Skobbler Map : FreeDrive function integration in other app In skobbler map, Which frameworks or files should be imported in our app in order to use 'freedrive' function of NavigationUI? thanks
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/38561274",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Image.open can't handle random selected image-variable Python This is my first Python-script/program so I have googled everything and starting to get the grip a little.
I am trying to make a program that randomly picks a picture in a directory and display it as a label.
Everything goes well except one thing. I have made the random picture as a variable and try to tell Image.open to use the path in the variable. Thing is that Image.open does not recognise the variable as a filename/path but instead it recognize it as
"PIL.PngImagePlugin.PngImageFile image mode=P size=980x93 at 0xF185A8".
I have googled all night but cant find an answer or solution to this. If I print both img1-variable and path1-variable it comes out right.
Anyone have a clue how to solve this? I would be very grateful for any answers!
I have Python 2.7.3
And this is my script (not finished).
#! /usr/bin/env python
from Tkinter import *
import Tkinter
import random
from PIL import Image, ImageTk
import os
root = Tkinter.Tk()
w, h = root.winfo_screenwidth(), root.winfo_screenheight()
root.geometry("%dx%d+0+0" %(w, h))
root.configure(background="darkgreen")
dir = 'decks/'
img1 = random.choice(os.listdir(dir))
path1 = dir+img1
card1 = Image.open(path1)
card1 = card1.resize((140, 190), Image.ANTIALIAS)
magicback = Image.open("datapics/magicback.jpg")
magicback = magicback.resize((140, 190), Image.ANTIALIAS)
magicbutton = ImageTk.PhotoImage(magicback)
label = Label(root, image=magicbutton)
label.image = magicbutton
label.place(x=1, y=20)
label1 = Label(root, image=card1)
label1.image = card1
label1.place(x=1, y=230)
label2 = Label(root, image=magicbutton)
label2.image = magicbutton
label2.place(x=151, y =230)
label3 = Label(root, image=magicbutton)
label3.image = magicbutton
label3.place(x=301, y=230)
label4 = Label(root, image=magicbutton)
label4.image = magicbutton
label4.place(x=451, y=230)
label5 = Label(root, image=magicbutton)
label5.image = magicbutton
label5.place(x=601, y=230)
label6 = Label(root, image=magicbutton)
label6.image = magicbutton
label6.place(x=751, y=230)
label7 = Label(root, image=magicbutton)
label7.image = magicbutton
label7.place(x=901, y=230)
root.mainloop(0)
A: If I understand the question correctly, your issue is with image.open(), I believe the problem is that you are treating the directory and file name as strings when you join them together:
path1 = dir + img1
Instead you should try using the os.path module to combine the two:
path1 = os.path.join(dir, img1)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/12030905",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: saml2 bearer oAuth : audience verification failed I try to implement a SSO mechanism with SAM2 bearer oAuth over WSO2.
1. User call WebAPP1
2. WebAPP1 (SP) redirect the user on the IDP login Page (OpenAM)
3. WebAPP1 (SP) call oAuth server (WSO2 IS or AM) with SAML2 to get oAuth token
At this step WSO2 IS (or AM) fails with the error : "SAML assertion audience verification failed".
I don't understand why because the audience value set in my SAML2 sent to oAuth server is the same as defined in the "Trusted Identity Provider" on IS or AM.
I don't understand why ... please help me !
Nicolas
A: I guess SAML assertion may not contain the all audience urls. In Trusted IDP UI, you can configure identity provider audiences. If you have defined them, those urls must be in the assertion. Also.. value that is defined by "OAuth2 Token Endpoint Name:" must be also as an audience url in assertion.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/20275542",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Disable Path MTU discovery on per socket on OS X Is there a way to disable Path MTU discovery on per socket basis on OS X?
This is how to set don't fragment bit on socket on Linux
But IP_MTU_DISCOVER is not recognized on OS X.
Only recognized options as per netinet/in.h on OS X are:
/*
* Options for use with [gs]etsockopt at the IP level.
* First word of comment is data type; bool is stored in int.
*/
#define IP_OPTIONS 1 /* buf/ip_opts; set/get IP options */
#define IP_HDRINCL 2 /* int; header is included with data */
.....
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/36230027",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Visual Studio 2010 script debugger doesn't work for me I just installed VS 2010 Beta 2 and wanted to play with an ASP.NET MVC 2 project. I simply added some script (alert('hello');) into the Home controller's index.aspx view, and I can see it executing. When I try to set a breakpoint, however, it never gets hit. I also tried to use the "debugger" keyword, and when I do, I get a disappointing "there is no source code available for the current location" message. I also get this message when I try to independently attach to an IE process where my app is running.
What do I need to do to get a friendly script debugging experience? (I have successfully used Firebug to debug this, but for some reason I prefer the VS debugger.)
Here are some details of my configuration:
*
*I am launching my stuff in VS 2010 Beta 2.
*IE8 version 8.0.7600.16385 is my default browser.
*The "Disable script debugging (Internet Explorer)" advanced option is unchecked.
*The "Disable script debugging (Other)" option is unchecked.
*In my ASP.NET MVC 2 project's "web" properties tab, the ASP.NET debugger is checked. All others are unchecked.
*Visual Studio 2008 script debugging seems to work just fine.
A: I was having the same issues. I was not able to get the IDE to even break at a breakpoint set inside a script tag. However when I added "debugger;" as the first line in the script tag was able to get the IDE to respond but then only to say that the disassebly was not availble.
However, I was able to click on the debug tools like "step into" and "step over". When I did this the IDE did progress into some of the external scripts that I am using (JQuery and Google Maps). So I took the JavaScript code block out of the view and put it into a separate .js file in the "Content" folder. Then I added a script tag to reference this new .js file (url = "/Content/Test.js").
It worked... a little bothersome that you have to go through this effort but maybe there is something to be said for JavaScript not being included directly in a view. I hope this is a bug they intend to fix.
A: When debugging on IE, VS seems to add a folder called 'Script Documents' to the Solution Explorer. Inside this folder there is another folder called 'Windows Internet Explorer', and inside of it I see all the loaded js scripts and the (compiled) HTML file currently being displayed on IE. Setting breakpoints on the script tags in this HTML file does work for me.
A: The debugger cannot debug both Silverlight code and Script code at the same time, if the Silverlight debugger is selected JavaScript debugging is switched off.
*
*Go to the Project's Properties (Alt+Enter).
*For a Web Site Project: Select "Start Options". Or for a Web Appliction: Go to the Web tab and at the bottom you will see the Debuggers option.
*Check that the Silverlight checkbox is NOT ticked if you want to be able to debug JavaScript. (It is unfortunate that the UI here is not clear about this side effect.)
A: To resolve this go to the Project's Properties and select "Start Options". Then Check the Native Code Check Box. and Uncheck the Silverlight Checkbox because both options not works together.
A: CTRL+Alt+P (Attach to Process), select IE, select 'script' for the debugging type.
A: As Ryan noted above, I moved my script to a seperate file under the Scripts folder.
I also added debug into the name of the script so it became MyTestScript.debug.js. I included the script via a script tag and could set break points in the script file which the debugger hit.
A: I have found that the Google Chrome devloper tool shows the JavaScript perfectly. In my case, I'm normally loading the script with jQuery's getScript function and execution of the code is typically by way of a jQuery callback upon loading a page or handling an event. With Visual Studio 2010, I frequently encountered the "No source" bug. Sad I need Chrome to debug JavaScript that is part of my Visual Studio project.
A: Using a separate js file has its drawbacks. For instance, you can't use MVC helpers. Microsoft really needs to figure this one out.
Intellisense also does not work properly in script blocks on a view, even if you include the reference comments like this:
/// <reference path="/Scripts/jquery-1.6-vsdoc.js" />
/// <reference path="/Scripts/jquery-1.6.js" />
Intellisense works fine in the js file with this approach though.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/1625903",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "35"
}
|
Q: Liskov substitution principle VS Interface Segregation principle I have some troubles with understanding these two principles. This is a bit long-read-question, so be patient.
Lets assume that we have a class
abstract class Shape {
abstract void onDraw();
}
and interface
interface SideCountable {
int getSidesCount();
}
And then we create two children classes
class Quad extends Shape {
@Override
public void onDraw() {
//some draw logic here
}
}
class Triangle extends Shape {
@Override
public void onDraw() {
//some draw logic here
}
}
And now we will make Shape implements SideCountable
abstract class Shape implements SideCountable{
abstract void onDraw();
}
and make changes in children classes
class Quad extends Shape {
@Override
public int getSidesCount() {
return 4;
}
@Override
public void onDraw() {
//some draw logic here
}
}
class Triangle extends Shape {
public int getSidesCount() {
return 3;
}
public void onDraw() {
//some draw logic here
}
}
And create test function for this structure (following LSP) :
public void printSidesCount(List<Shape> shapes) {
for(int i=0; i < shapes.size(); i++) {
System.out.println(shapes.get(i).getSidesCount());
}
}
And here I want to stop because actually in the next step I was stucked.
What if we'll create a third class Circle?
class Circle extends Shape {
public int getSidesCount() {
return ???;
}
@Override
public void onDraw() {
//some draw logic here
}
}
Circle has no sides, so implementation of SideCountable for this children sounds ridiculous. Ok, we can move implementation to Quad and Triangle only, but in this case LSP will not working anymore. Can someone describe what the best way I should to do?
*
*Leave SideCountable in Shape class and return 0 for Circle and break interface segregation principle?
*Move SideCountable to Quad and Triangle and break LSP principle?
A: First of all, your method printSidesCount only needs to know that the list contains SideCountable objects. So giving its parameter the type List<Shape> is more specific than necessary. Give it a List<SideCountable> instead:
public void printSidesCount(List<SideCountable> sideCountables) {
for(int i=0; i < (); i++) {
System.out.println(sideCountables.get(i).getSidesCount());
}
}
Or even List<? extends SideCountable> which means "a list of some arbitrary unknown type that implements SideCountable":
public void printSidesCount(List<? extends SideCountable> sideCountables) {
for(int i=0; i < sideCountables.size(); i++) {
System.out.println(sideCountables.get(i).getSidesCount());
}
}
If not all shapes have a countable number of sides, then class Shape should not implement interface SideCountable. Instead, make classes Quad and Triangle implement interface SideCountable besides extending class Shape:
class Quad extends Shape implements SideCountable {
// ...
}
class Triangle extends Shape implements SideCountable {
// ...
}
And make class Circle extend Shape but not implement SideCountable:
class Circle extends Shape { // Not SideCountable
// ...
}
When you do it like this, the type system will help you:
*
*you can pass a List<Quad> or List<Triangle> to printSidesCount since those types implement SideCountable
*you cannot pass a List<Circle> to printSidesCount, which is good because trying to do this would not make sense for a list of circles
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/59372197",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: EBNF: one or more and zero or more, in no particular order In an EBNF grammar I have two tokens shape and attr. How would I express that shape should occur one or more times and attr zero or more times, but in no particular order, i.e.:
shape1 shape2 shape3
attr1 shape1
shape1 attr1
shape1 shape2 attr1 shape3
Would all be parsed, but
attr1 attr2 ..
would not?
A: Answering my own question:
seq = shape as_seq | attr seq
as_seq = (shape | attr)*
does the trick
(where shape and attr are defined elsewhere in the grammar.
e.g. shape = 'a' and attr = 'b'. Then 'a' 'ab' 'aaab' 'bbbab' will all match but 'b' 'bb' 'bbb..' etc will not)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75179115",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: XML string to JSON javascript I have a xml string which i want to convert in JSON string
var txt = "<?xml version='1.0' encoding='UTF-8' ?>
<result>
<info>
<id>1</id>
<type>HL</type>
<ven>DEMOMA</ven>
</info>
<info>
<id>2</id>
<type>HL</type>
<ven>DEMOMB</ven>
</info>
<result>";
i tried to initially convert it in DOM object using parser but it throws parsing error.
parser = new DOMParser();
xmlDoc = parser.parseFromString(txt,"text/xml");
i want my output json string like only by using Javascript
{"result":[{"id":"1","type":"HL","ven":"DEMOMA"},{"id":"2","type":"HL","ven":"DEMOMB"}]}
A: I will try to explain with an example with use x2js.js https://github.com/abdmob/x2js and jquery (and without jQuery) library.
GET XML data from the API and convert this data to JSON
With jQuery
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.2.3.js"></script>
<script type="text/javascript" src="xml2json.js"></script>
</head>
<body>
<script type="text/javascript">
var x2js = new X2JS();
$.ajax({
url: 'http://ip-api.com/xml',
dataType: 'XML',
success: function(data) {
var xmlText = data; // XML
var jsonObj = x2js.xml2json(xmlText); // Convert XML to JSON
console.log(jsonObj);
}
});
</script>
</body>
</html>
without jQuery
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript" src="xml2json.js"></script>
</head>
<body>
<script type="text/javascript">
function loadXMLDoc(dname) {
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else {
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET", dname, false);
xhttp.send();
return xhttp.responseXML;
}
var xmlDoc = loadXMLDoc("http://ip-api.com/xml"); // XML
var x2js = new X2JS();
var jsonObj = x2js.xml2json(xmlDoc); // Convert XML to JSON
console.log(jsonObj);
</script>
</body>
</html>
and using the example that you gave in question. Fix closed <result> to </result>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript" src="xml2json.js"></script>
</head>
<body>
<script type="text/javascript">
var txt = "<?xml version='1.0' encoding='UTF-8' ?> <result> <info> <id>1</id> <type>HL</type> <ven>DEMOMA</ven> </info> <info> <id>2</id> <type>HL</type> <ven>DEMOMB</ven> </info> </result>";
var x2js = new X2JS();
var jsonObj = x2js.xml_str2json(txt);
console.log(jsonObj);
</script>
</body>
</html>
A: Check out this https://github.com/metatribal/xmlToJSON
Its a very small and useful script. Usage is very easy.
Include the src
<script type="text/javascript" src="path/xmlToJSON.js"></script>
and enjoy! xmlToJSON is packaged as a simple module, so use it like this
testString = '<xml><a>It Works!</a></xml>'; // get some xml (string or document/node)
result = xmlToJSON.parseString(testString); // parse
'result' is your JSON object.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/36929478",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
}
|
Q: Buffer implementing io.WriterAt in go I'm using the aws-sdk to download a file from an s3 bucket. The S3 download function want's something that implements io.WriterAt however bytes.Buffer doesn't implement that. Right now I'm creating a file which implements io.WriterAt but I'd like something in memory.
A: For cases involving the AWS SDK, use aws.WriteAtBuffer to download S3 objects into memory.
requestInput := s3.GetObjectInput{
Bucket: aws.String(bucket),
Key: aws.String(key),
}
buf := aws.NewWriteAtBuffer([]byte{})
downloader.Download(buf, &requestInput)
fmt.Printf("Downloaded %v bytes", len(buf.Bytes()))
A: I don't know of any way to do this in the standard library, but you can write your own buffer.
It really wouldn't be all that hard...
EDIT: I couldn't stop thinking about this, and I ended up acidentally the whole thing, enjoy :)
package main
import (
"errors"
"fmt"
)
func main() {
buff := NewWriteBuffer(0, 10)
buff.WriteAt([]byte("abc"), 5)
fmt.Printf("%#v\n", buff)
}
// WriteBuffer is a simple type that implements io.WriterAt on an in-memory buffer.
// The zero value of this type is an empty buffer ready to use.
type WriteBuffer struct {
d []byte
m int
}
// NewWriteBuffer creates and returns a new WriteBuffer with the given initial size and
// maximum. If maximum is <= 0 it is unlimited.
func NewWriteBuffer(size, max int) *WriteBuffer {
if max < size && max >= 0 {
max = size
}
return &WriteBuffer{make([]byte, size), max}
}
// SetMax sets the maximum capacity of the WriteBuffer. If the provided maximum is lower
// than the current capacity but greater than 0 it is set to the current capacity, if
// less than or equal to zero it is unlimited..
func (wb *WriteBuffer) SetMax(max int) {
if max < len(wb.d) && max >= 0 {
max = len(wb.d)
}
wb.m = max
}
// Bytes returns the WriteBuffer's underlying data. This value will remain valid so long
// as no other methods are called on the WriteBuffer.
func (wb *WriteBuffer) Bytes() []byte {
return wb.d
}
// Shape returns the current WriteBuffer size and its maximum if one was provided.
func (wb *WriteBuffer) Shape() (int, int) {
return len(wb.d), wb.m
}
func (wb *WriteBuffer) WriteAt(dat []byte, off int64) (int, error) {
// Range/sanity checks.
if int(off) < 0 {
return 0, errors.New("Offset out of range (too small).")
}
if int(off)+len(dat) >= wb.m && wb.m > 0 {
return 0, errors.New("Offset+data length out of range (too large).")
}
// Check fast path extension
if int(off) == len(wb.d) {
wb.d = append(wb.d, dat...)
return len(dat), nil
}
// Check slower path extension
if int(off)+len(dat) >= len(wb.d) {
nd := make([]byte, int(off)+len(dat))
copy(nd, wb.d)
wb.d = nd
}
// Once no extension is needed just copy bytes into place.
copy(wb.d[int(off):], dat)
return len(dat), nil
}
A: Faking AWS WriterAt with an io.Writer
This isn't a direct answer to the original question but rather the solution I actually used after landing here. It's a similar use case that I figure may help others.
The AWS documentation defines the contract such that if you set downloader.Concurrency to 1, you get guaranteed sequential writes.
downloader.Download(FakeWriterAt{w}, s3.GetObjectInput{
Bucket: aws.String(bucket),
Key: aws.String(key),
})
downloader.Concurrency = 1
Therefore you can take an io.Writer and wrap it to fulfill the io.WriterAt, throwing away the offset that you no longer need:
type FakeWriterAt struct {
w io.Writer
}
func (fw FakeWriterAt) WriteAt(p []byte, offset int64) (n int, err error) {
// ignore 'offset' because we forced sequential downloads
return fw.w.Write(p)
}
A: I was looking for a simple way to get io.ReadCloser directly from an S3 object. There is no need to buffer response nor reduce concurrency.
import "github.com/aws/aws-sdk-go/service/s3"
[...]
obj, err := c.s3.GetObject(&s3.GetObjectInput{
Bucket: aws.String("my-bucket"),
Key: aws.String("path/to/the/object"),
})
if err != nil {
return nil, err
}
// obj.Body is a ReadCloser
return obj.Body, nil
A: With aws-sdk-go-v2, the codebase-provided example shows:
// Example:
// pre-allocate in memory buffer, where headObject type is *s3.HeadObjectOutput
buf := make([]byte, int(headObject.ContentLength))
// wrap with aws.WriteAtBuffer
w := s3manager.NewWriteAtBuffer(buf)
// download file into the memory
numBytesDownloaded, err := downloader.Download(ctx, w, &s3.GetObjectInput{
Bucket: aws.String(bucket),
Key: aws.String(item),
})
Then use w.Bytes() as the result.
Import "github.com/aws/aws-sdk-go-v2/feature/s3/manager" and other needed components
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/46019484",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "28"
}
|
Q: Override Function In WordPress Plugin Widget I need to override a setting in a widget included in a WordPress plugin (the plugin is woocommerce). I've found in the plugin's widget code where I need to make the change (for the product_categories widget, I want to add a $cat_args['depth'] = 1; so that I only see the parent categories) and everything works fine, but I want to be able to do it in a way so that if the plugin ever updates, it doesn't wipe out the change. I have a custom theme that I have developed...is there any way to make the change in that theme so that I can still update woocommerce safely?
A: The only way to do that would be to ask the Widget developer to do something like this:
$cat_args_depth = 1;
$cat_args_depth = apply_filters('woocommerce_cat_args_depth', $cat_args_depth );
$cat_args['depth'] = $cat_args_depth;
and then you could just use
add_filter( 'woocommerce_cat_args_depth', function( $cat_args_depth ) {
$cat_args_depth = 2; // your value
return $cat_args_depth ;
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/9395154",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to constructor in constructor I need add data in array Person. But program is not bug .
I do not know how to constructor with type class in constructor .
public Person[] personData =
{
new Person {PersonId = 1, FirstName = "Adam", LastName ="Freeman",
HomeAddress = { City = "SoKa" , Country = "Look" } },
new Person {PersonId = 2, FirstName = "Nhan", LastName ="Ga",
HomeAddress = { City = "Dalat" , Country = "VungTau" } },
};
Declarations
public class Person
{
public int PersonId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public Address HomeAddress { get; set; }
public class Address
{
public string City { get; set; }
public string Country { get; set; }
}
}
A: You need to use
HomeAddress = new Person.Address{ City = "SoKa" , Country = "Look" }
instead of
HomeAddress = { City = "SoKa" , Country = "Look" }
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/65982335",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-5"
}
|
Q: Trigger Outlook Mail Body using VBA In VBA scripting ,I am trying to write a Sub Function which has the following signature
Sub(taskName As String , myGroup As String, myFile As String ,myPer As String, RelatedTasks() As String )
Dim olApp As Outlook.Application
Dim m As Outlook.MailItem
Set olApp = New Outlook.Application
Set m = olApp.CreateItem(olMailItem)
With m
.display
.To = "somewhere@someplace.com"
.Subject = "Test Events"
.HTMLBody/.body = ...
End Sub
Email Body is as follows:
Hello All,
Please find the following information.
TASK: taskName
RELATED TASK:RelatedTasks()
FILE : myFile
PERSON : myPer
In the Sub function , the pattern to the left of colon is always constant.And the right side will change based on the inputs to the function.
For that I am reading the Template.htm which contains the required signature.
Template.htm contains:
Hello All,
Please find the following information.
TASK: {{mytask}}
RELATED TASK:{{myRelatedTasks}}
FILE : {{myFile}}
PERSON : {{myPerson}}
In VBA code,I am replacing all the fields.
The issue that I am facing is {{mytask}} and {{related tasks}} also should have a HTML reference. I have succeeded in adding the link to mytask .Clicking on the mytask in the mail will jump to the respective weblink.
<a href = "www.something.com&id ={{taskID}}>
{{mytask}}.....<a href = "www.xxx.com&id={{}}>{{myRelatedTasks}}
but having trouble in adding the same to Related tasks since it is an array.
My VBA code :
Option Explicit
Sub CreateNewMail()
Dim olApp As Outlook.Application
Dim m As Outlook.MailItem
Dim sigPath As String, sigText As String
Dim fso As Scripting.FileSystemObject
Dim ts As Scripting.TextStream
Dim t As String
Dim r(5) As Variant
t = "233444:dshfjhdjfdhjfhjdhfjdhfjd"
r(0) = "122343:dsjdhfjhfjdh"
r(1) = "323243:jfjfghfjhjddj"
r(2) = "834783:gffghjkjkgjkj"
Set olApp = New Outlook.Application
Set m = olApp.CreateItem(olMailItem)
sigPath = "C:\Users\Pavan-Kumar\Desktop\vbs\TestEvents.htm"
Set fso = New Scripting.FileSystemObject
Set ts = fso.OpenTextFile(sigPath)
sigText = ts.ReadAll
ts.Close
Set fso = Nothing
sigText = Replace(sigText, "{{mytask}}", t)
sigText = Replace(sigText, "{{myRelatedTasks}}", Join(r, "<br>"))
With m
.display
.To = "somewhere@someplace.com"
.Subject = "Test Events"
.HTMLBody = sigText
End With
End Sub
And also when I am joining the related tasks , I want them to come one below another with indentation. I tried it with giving "\t" as the delimiter with no success.
I want to give references to my Related tasks and also want them to neatly align them. Thanks.
This is what I am able to print in my outlook mail:
Hello All,
Please find the following information.
TASK: 233444:dshfjhdjfdhjfhjdhfjdhfjd
RELATED TASK:122343:dsjdhfjhfjdh
"\t"323243:jfjfghfjhjddj
"\t"834783:gffghjkjkgjkj
"\t"
"\t"
"\t"
FILE : TImers
PERSON : Charvaka
A: For the Alignments: You can either drop the Related Tasks into a Table, or you can use a Tab (vbTab, not "\t")
For the multiple-rows: This would be simpler if you had a 2D Array (e.g. r(0,0)="RelatedTaskName" and r(0,1)="RelatedTaskID") instead of splitting it based on a Colon, but it's doable, and there are several different ways to go about it.
The method that I am going to use here is to build all of your string at once, then use Replace to dump the finished product: (using Tab instead of a Table for the indents)
Dim taskID As String, taskName As String, lTaskNum As Long, TaskList As String
TaskList = "" 'Start with an empty list
For lTaskNum = LBound(r) To UBound(r)
If Len(TaskList) > 0 Then TaskList = TaskList & vbTab 'We are using Tab instead of a table here
taskName= r(lTaskNum) 'Grab element from the array
taskID = Left(taskName, InStr(taskName, ":") - 1) 'Just the number
taskName = Replace(taskName, taskID & ":", "",count:=1) 'Just the Link text
TaskList = TaskList & "<a href = ""www.xxx.com&id=" & taskID & """>" & taskName & "</a><br />" 'Add the task to the stack
Next lTaskNum
'If Len(TaskList) < 1 Then TaskList = "No Related Tasks" 'Optional bonus!
sigText = Replace(sigText, "{{myRelatedTasks}}", TaskList) 'Push the finished list into the email
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/50118988",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: PHPUnit - Problem generating Code Coverage report with Zend Framework application I have been searching for an answer to this problem for hours in Google and various other sites with no luck. I have created some unit tests for my Zend Framework project using PHPUnit. All goes well with the tests up until the point of the the PHPUnit Code Coverage report. At this point I get the following error:
Generating code coverage report, this
may take a moment. Fatal error: Call
to a member function pushStack() on a
non-object in
C:\htdocs\ZendFWTutorials\ZendStorefront\library\SF\Plugin\Action.php
on line 32
This error references the following block of code:
public function
dispatchLoopStartup(Zend_Controller_Request_Abstract $request)
{
$stack = $this->getStack();
// category menu
$categoryRequest = new Zend_Controller_Request_Simple();
$categoryRequest->setControllerName('category')
->setActionName('index')
->setParam('responseSegment', 'categoryMain');
// push requests into the stack
$stack->pushStack($categoryRequest);
}
public function getStack()
{
if (null === $this->_stack) {
$front = Zend_Controller_Front::getInstance();
if (!$front->hasPlugin('Zend_Controller_Plugin_ActionStack'))
{
$stack = new Zend_Controller_Plugin_ActionStack();
$front->registerPlugin($stack);
} else {
$stack = $front->getPlugin('ActionStack');
}
$this->_stack = $stack;
}
return $this->_stack;
}
This code is from a library that I did not write so that probably adds complexity to my problem because I'm less likely to understand what is going on. I also don't know what the PHPUnit logic is doing when it creates the code coverage report so I don't know how to remedy the problem. This problem only occurs when I run PHPUnit and I have run xdebug to trace the code in this function under normal operational conditions. I have a feeling that PHPUnit enters a condition where the variable is null but in normal operation $stack and $categoryRequest are not null.
My directory structure is as follows:
application
----->bootstrap
----->config
----->layouts
----->modules
-------->storefront
-------------->controllers
-------------->forms
-------------->models
-------------->services
-------------->views
build
data
library
----->SF
----->Zend
Public
----->css
----->images
tests
----->application
------------->modules
------------->controllers
------------->models
----TestHelper.php
----phpunit.xml
phpunit.xml is as follows:
./application/
<filter>
<whitelist>
<directory suffix=".php">../application/</directory>
<exclude>
<directory suffix=".phtml">../application/</directory>
<directory suffix=".php">../library/</directory>
</exclude>
</whitelist>
</filter>
<logging>
<log type="coverage-html" target="./log/report" charset="UTF-8"
yui="true" highlight="true" lowUpperBound="50"
highLowerBound="80"/>
TestHelper.php:
<?php // set our app paths and
environments define('BASE_PATH',
realpath(dirname(__FILE__) . '/../'));
define('APPLICATION_PATH', BASE_PATH .
'/application'); define('TEST_PATH',
BASE_PATH . '/tests');
define('APPLICATION_ENV', 'testing');
//include path set_include_path('.' .
PATH_SEPARATOR . BASE_PATH .
'/library' . PATH_SEPARATOR .
get_include_path());
// set the default timezone
date_default_timezone_set('America/Argentina/Buenos_Aires');
require_once 'Zend/Application.php';
$application = new Zend_Application(APPLICATION_ENV, APPLICATION_PATH . '/config/store.ini');
$application->bootstrap();
A: After talking to @derickr on twitter, I used xdebug.auto_trace=1 in my PHP INI to trace the problem. The problem was in this line of code:
$stack = $front->getPlugin('ActionStack');
This is found in the function above named getStack(). The auto_trace showed that the first time getStack() runs, it runs correctly. The reason that PHPUnit was causing the error to show up is that when it runs the Code Coverage report, the dispatcher runs multiple times thus entering getStack() again and triggering the aforementioned line of code. The code needed the following change to remove the error and properly locate the plug-in in memory:
$stack = $front->getPlugin('Zend_Controller_Plugin_ActionStack');
The Code Coverage report now generates properly. Hopefully this will help explain the problem for others who find themselves with similar errors.
-Ross
A: Properly your PHPUnit test is not correct.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/5085846",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Force a right-click to act as a left-click? I have looked at other code, and I just can't get any of it to work. I'm able to suppress the right-click context menu, but I need more than that. I need every right-click to act as if the left button were clicked, and I need to know exactly where to put it in my html code. This is a hot issue, as I can't progress on an important project until I can make this happen reliably. HELP!
A: You can use the following code to convert the right button click into left button click.
Here when you click inside the div the right button click is converted into left button. So that when you press left or right button both will behave on the same way.
$(document).ready(function() {
$("#rightclickDemo").bind('contextmenu', function(event) {
if (event.which == 3)
{
// prevent right click from being interpreted by the browser:
event.preventDefault();
$(this).click(); // simulate left click
}
});
$('#rightclickDemo').click(function() {
$(this).html("Left clicked!");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
</head>
<body>
<p>This is a web page Demo.</p>
<div id="rightclickDemo" style="width:200px; height:100px; background-color: orange">
Click me with the right or left mouse button. Both will work as left button clicked!
</div>
</body>
</html>
A: I found my answer after MUCH research. this code works exactly the way I want it to! Added the jquery.min.js to my file structure and it works perfectly for standalone use!
<script src="scripts/jquery.min.js"></script>
<script type="text/javascript">
$(document).on("contextmenu", function(e){
e.preventDefault();
e.target.click();
});
</script>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/46097190",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
}
|
Q: FileMaker :- Compare textbox values with OBBC SQL DB I am trying to implement an Login module where,I need to Compare the list of values in SQL DB. Here i want to compare text box entered values with SQL DB.
Please share any views.
A: Depends on your SQL DB. You can add your SQL DB as ESS or you can use "Execute SQL" and run a SQL query on ODBC DNS to your database.
If you are in 16 and your SQL has any API, you can call them through CURL. You can do the same with previous versions of FileMaker using plugins.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/44375510",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Acessing textutil source code Is it possible open the source code of the textutil command-line utility?
I'm not finding anything in google.
Thanks.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/37825469",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Laravel Ajax working fine on page reload but when I use Ajax to filter data pagination with jsscroll does not work Pagination links working fine as normal pages when I refresh the whole page but when i reload just data with ajax pagination does not loading next pages
$.ajax({
url: '{{route('apply.filters')}}',
type:'get',
data: {cities:cities,
category:category
},
success: function (data) {
// $(".contentlist").load(location.href + " .contentlist");
$('.contentlist').html(data);
},
error: function(xhr, status, errorThrown) {
console.log(xhr.responseText);
}
});
this is my controller function
public function filter(Request $request)
{
try {
set_time_limit(390);
$country=null;
if(Auth::check() && $country==null){
$country=Auth::user()->lat->country??'';
}if(Session::has('country') && $country==null){
$country=Session::get('country.0');
}
if(isset($request->cities)){
$data =[
'products' => Product::where([['category',$request->category],['country',$country??'']])->whereIn('city',$request->cities)->where('status',1)->Orderby('id','desc')->paginate(8),
];
}
if(isset($data)){
return response()->json(view('front.home.ajaxindex',$data)->render());
}else{
return redirect()->route('home');
}
} catch(\Exception $e) {
return back()->with('error',$e->getMessage());
}
}
this is my jsscroll function working normally fine but not loading data comes with ajax
$('ul.pagination').hide();
$(function() {
$('.contentlist').jscroll({
autoTrigger: true,
loadingHtml: '<img class="center-block" src="{{asset('front_assets/images/Spinner-1s-200px.gif')}}" width="100" alt="Loading..." />', // MAKE SURE THAT YOU PUT THE CORRECT IMG PATH
padding: 0,
nextSelector: '.pagination li.active + li a',
contentSelector: 'div.contentlist',
loadOnScroll: false,
callback: function() {
$('ul.pagination').remove();
$('.elements').each(function(){
var thisH = $(this).height();
if (thisH > maxHeight) {
maxHeight = thisH;
}
$(this).height(maxHeight);
});
}
});
});
this is my ajaxindex page this is new page only created for making html which is appended in the main page if data exists
@foreach($products as $product)
<div class="col-lg-3 col-md-4 col-sm-6 col-xs-12 item-cell">
<div class="listingscontent elements">
@if(\Illuminate\Support\Facades\Auth::guard('admin')->check())
<i id="{{$imgs->id??''}}" onclick="deletes('{{$product->id}}',this)" class="fa fa-close fa-lg pull-right" style="margin-left: -20px; mix-blend-mode: hard-light; color: rgb(0, 255, 255); "></i>
<a style=" position: absolute;" class="pull-left" href="{{route('edit.add',['id' => preg_replace('/-{2,}/','-',str_replace([" ", "'", "/","(",")","@","#"], '-',$product->title??'')).'-'.$product->id??''])}}"> <i class="fa fa-pencil-square-o fa-lg" style="mix-blend-mode: hard-light; color: rgb(0, 255, 255); "></i></a>
@endif
<a style="color: #ea1b25" href="{{route('details',['id' => preg_replace('/-{2,}/','-',str_replace([" ", "'", "/","(",")","@","#"], '-',$product->title??'')).'-'.$product->id??''])}}">
@if(isset($product->atachedImage))
<img class="listings" src="{{asset($product->atachedImage->path.$product->atachedImage->name??'noimage.jpg')}}" title="{{$product->title??''}}_image" alt="">
@else
<img class="listings" src="{{asset('images/noimage.jpg')}}" title="{{$product->title??''}}_image">
@endif
<h5 class="text-capitalize title" title="{{$product->title??''}}">{{str_limit($product->title??'',19)}}</h5></a>
</div>
</div>
@endforeach
{{$products->appends(request()->except('page'))->links()??''}}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/60702730",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: C# - XML Document Won't Save document = new XmlDocument();
XmlNode docNode = document.CreateXmlDeclaration("1.0", "UTF-8", null);
document.CreateAttribute("EncryptionKey");
document.CreateAttribute("SaltKey");
document.CreateAttribute("VIKey");
document.CreateAttribute("EmailUsername");
document.CreateAttribute("EmailPassword");
document.AppendChild(docNode);
document.Save("Credentials.xml");
Apparently the root doesn't exist, even though I made one and applied it.
EDIT: What it should come out with: https://imgur.com/a/Crk3A
A: Maybe you need something like this. With a root node named "Credentials"
private void CreateXml()
{
var document = new XmlDocument();
XmlNode rootNode = document.CreateElement("Credentials");
document.AppendChild(rootNode);
rootNode.AppendChild(document.CreateElement("EncryptionKey"));
rootNode.AppendChild(document.CreateElement("SaltKey"));
rootNode.AppendChild(document.CreateElement("VIKey"));
rootNode.AppendChild(document.CreateElement("EmailUsername"));
rootNode.AppendChild(document.CreateElement("EmailPassword"));
XmlNode declaration = document.CreateXmlDeclaration("1.0", "UTF-8", null);
document.InsertBefore(declaration, rootNode);
document.Save("Credentials.xml");
}
EDIT: Added declaration
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/48740982",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Incremental build with GCC and manual makefile? I am coding to the NRF51822 bluetooth chip, in Eclipse with GCC and a makefile that I maintain myself.
My problem is that every time I press build, it will compile everything, which is beginning to take quite some time. I am not that experienced in creating and maintaining make-files, so I have no idea where to start in order to get it to build incremtal instead?
My makefile is composed like this (I know there's a lot, and I haven't created this myself - found it in a tutorial, so I don't know what's relevant and what's not :-) ):
PROJECT_NAME := my_project
export OUTPUT_FILENAME
#MAKEFILE_NAME := $(CURDIR)/$(word $(words $(MAKEFILE_LIST)),$(MAKEFILE_LIST))
MAKEFILE_NAME := $(MAKEFILE_LIST)
MAKEFILE_DIR := $(dir $(MAKEFILE_NAME) )
TEMPLATE_PATH = nrf51_sdk/toolchain/gcc
ifeq ($(OS),Windows_NT)
include $(TEMPLATE_PATH)/Makefile.windows
else
include $(TEMPLATE_PATH)/Makefile.posix
endif
MK := mkdir
RM := rm -rf
#echo suspend
ifeq ("$(VERBOSE)","1")
NO_ECHO :=
else
NO_ECHO := @
endif
# Toolchain commands
CC := "$(GNU_INSTALL_ROOT)/bin/$(GNU_PREFIX)-gcc"
AS := "$(GNU_INSTALL_ROOT)/bin/$(GNU_PREFIX)-as"
AR := "$(GNU_INSTALL_ROOT)/bin/$(GNU_PREFIX)-ar" -r
LD := "$(GNU_INSTALL_ROOT)/bin/$(GNU_PREFIX)-ld"
NM := "$(GNU_INSTALL_ROOT)/bin/$(GNU_PREFIX)-nm"
OBJDUMP := "$(GNU_INSTALL_ROOT)/bin/$(GNU_PREFIX)-objdump"
OBJCOPY := "$(GNU_INSTALL_ROOT)/bin/$(GNU_PREFIX)-objcopy"
SIZE := "$(GNU_INSTALL_ROOT)/bin/$(GNU_PREFIX)-size"
#function for removing duplicates in a list
remduplicates = $(strip $(if $1,$(firstword $1) $(call remduplicates,$(filter-out $(firstword $1),$1))))
#source common to all targets
C_SOURCE_FILES += \
main.c \
file1.c \
file2.c \
file3.c \
file4.c \
#assembly files common to all targets
ASM_SOURCE_FILES = nrf51_sdk/toolchain/gcc/gcc_startup_nrf51.s
#includes common to all targets
INC_PATHS = -I Dir1/
INC_PATHS = -I Dir2
INC_PATHS += -I Dir3
INC_PATHS += -I Dir4
OBJECT_DIRECTORY = _build
LISTING_DIRECTORY =$(OBJECT_DIRECTORY)
OUTPUT_BINARY_DIRECTORY =$(OBJECT_DIRECTORY)
# Sorting removes duplicates
BUILD_DIRECTORIES := $(sort $(OBJECT_DIRECTORY) $(OUTPUT_BINARY_DIRECTORY) $(LISTING_DIRECTORY) )
#flags common to all targets
CFLAGS = -DSOFTDEVICE_PRESENT
CFLAGS += -DNRF51
CFLAGS += -DS110
CFLAGS += -DBOARD_PCA10028
CFLAGS += -DBLE_STACK_SUPPORT_REQD
CFLAGS += -mcpu=cortex-m0
CFLAGS += -mthumb -mabi=aapcs --std=gnu99
CFLAGS += -Wall -O0 -g3
CFLAGS += -mfloat-abi=soft
# keep every function in separate section. This will allow linker to dump unused functions
CFLAGS += -ffunction-sections -fdata-sections -fno-strict-aliasing
#CFLAGS += -flto -fno-builtin
# keep every function in separate section. This will allow linker to dump unused functions
LDFLAGS += -Xlinker -Map=$(LISTING_DIRECTORY)/$(OUTPUT_FILENAME).map
LDFLAGS += -mthumb -mabi=aapcs -L $(TEMPLATE_PATH) -T$(LINKER_SCRIPT)
LDFLAGS += -mcpu=cortex-m0
# let linker to dump unused sections
LDFLAGS += -Wl,--gc-sections
# use newlib in nano version
LDFLAGS += --specs=nano.specs -lc -lnosys
# Assembler flags
ASMFLAGS += -x assembler-with-cpp
ASMFLAGS += -DSOFTDEVICE_PRESENT
ASMFLAGS += -DNRF51
ASMFLAGS += -DS110
ASMFLAGS += -DBOARD_PCA10028
ASMFLAGS += -DBLE_STACK_SUPPORT_REQD
#default target - first one defined
default: clean nrf51422_xxac_s110
#building all targets
all: clean
$(NO_ECHO)$(MAKE) -f $(MAKEFILE_NAME) -C $(MAKEFILE_DIR) -e cleanobj
$(NO_ECHO)$(MAKE) -f $(MAKEFILE_NAME) -C $(MAKEFILE_DIR) -e nrf51422_xxac_s110
#target for printing all targets
help:
@echo following targets are available:
@echo nrf51422_xxac_s110
@echo flash_softdevice
C_SOURCE_FILE_NAMES = $(notdir $(C_SOURCE_FILES))
C_PATHS = $(call remduplicates, $(dir $(C_SOURCE_FILES) ) )
C_OBJECTS = $(addprefix $(OBJECT_DIRECTORY)/, $(C_SOURCE_FILE_NAMES:.c=.o) )
ASM_SOURCE_FILE_NAMES = $(notdir $(ASM_SOURCE_FILES))
ASM_PATHS = $(call remduplicates, $(dir $(ASM_SOURCE_FILES) ))
ASM_OBJECTS = $(addprefix $(OBJECT_DIRECTORY)/, $(ASM_SOURCE_FILE_NAMES:.s=.o) )
vpath %.c $(C_PATHS)
vpath %.s $(ASM_PATHS)
OBJECTS = $(C_OBJECTS) $(ASM_OBJECTS)
nrf51422_xxac_s110: OUTPUT_FILENAME := nrf51422_xxac_s110
nrf51422_xxac_s110: LINKER_SCRIPT=ble_app_hrs_gcc_nrf51.ld
nrf51422_xxac_s110: $(BUILD_DIRECTORIES) $(OBJECTS)
@echo Linking target: $(OUTPUT_FILENAME).out
$(NO_ECHO)$(CC) $(LDFLAGS) $(OBJECTS) $(LIBS) -o $(OUTPUT_BINARY_DIRECTORY)/$(OUTPUT_FILENAME).out
$(NO_ECHO)$(MAKE) -f $(MAKEFILE_NAME) -C $(MAKEFILE_DIR) -e finalize
## Create build directories
$(BUILD_DIRECTORIES):
echo $(MAKEFILE_NAME)
$(MK) $@
# Create objects from C SRC files
$(OBJECT_DIRECTORY)/%.o: %.c
@echo Compiling file: $(notdir $<)
@echo arm-none-eabi-gcc $(CFLAGS) $(INC_PATHS) -c -o $@ $<
$(NO_ECHO)$(CC) $(CFLAGS) $(INC_PATHS) -c -o $@ $<
# Assemble files
$(OBJECT_DIRECTORY)/%.o: %.s
@echo Compiling file: $(notdir $<)
$(NO_ECHO)$(CC) $(ASMFLAGS) $(INC_PATHS) -c -o $@ $<
# Link
$(OUTPUT_BINARY_DIRECTORY)/$(OUTPUT_FILENAME).out: $(BUILD_DIRECTORIES) $(OBJECTS)
@echo Linking target: $(OUTPUT_FILENAME).out
$(NO_ECHO)$(CC) $(LDFLAGS) $(OBJECTS) $(LIBS) -o $(OUTPUT_BINARY_DIRECTORY)/$(OUTPUT_FILENAME).out
## Create binary .bin file from the .out file
$(OUTPUT_BINARY_DIRECTORY)/$(OUTPUT_FILENAME).bin: $(OUTPUT_BINARY_DIRECTORY)/$(OUTPUT_FILENAME).out
@echo Preparing: $(OUTPUT_FILENAME).bin
$(NO_ECHO)$(OBJCOPY) -O binary $(OUTPUT_BINARY_DIRECTORY)/$(OUTPUT_FILENAME).out $(OUTPUT_BINARY_DIRECTORY)/$(OUTPUT_FILENAME).bin
## Create binary .hex file from the .out file
$(OUTPUT_BINARY_DIRECTORY)/$(OUTPUT_FILENAME).hex: $(OUTPUT_BINARY_DIRECTORY)/$(OUTPUT_FILENAME).out
@echo Preparing: $(OUTPUT_FILENAME).hex
$(NO_ECHO)$(OBJCOPY) -O ihex $(OUTPUT_BINARY_DIRECTORY)/$(OUTPUT_FILENAME).out $(OUTPUT_BINARY_DIRECTORY)/$(OUTPUT_FILENAME).hex
finalize: genbin genhex echosize
genbin:
@echo Preparing: $(OUTPUT_FILENAME).bin
$(NO_ECHO)$(OBJCOPY) -O binary $(OUTPUT_BINARY_DIRECTORY)/$(OUTPUT_FILENAME).out $(OUTPUT_BINARY_DIRECTORY)/$(OUTPUT_FILENAME).bin
## Create binary .hex file from the .out file
genhex:
@echo Preparing: $(OUTPUT_FILENAME).hex
$(NO_ECHO)$(OBJCOPY) -O ihex $(OUTPUT_BINARY_DIRECTORY)/$(OUTPUT_FILENAME).out $(OUTPUT_BINARY_DIRECTORY)/$(OUTPUT_FILENAME).hex
echosize:
-@echo ""
$(NO_ECHO)$(SIZE) $(OUTPUT_BINARY_DIRECTORY)/$(OUTPUT_FILENAME).out
-@echo ""
clean:
$(RM) $(BUILD_DIRECTORIES)
cleanobj:
$(RM) $(BUILD_DIRECTORIES)/*.o
flash: $(MAKECMDGOALS)
@echo Flashing: $(OUTPUT_BINARY_DIRECTORY)/$<.hex
nrfjprog --reset --program $(OUTPUT_BINARY_DIRECTORY)/$<.hex)
## Flash softdevice
flash_softdevice:
@echo Flashing: s110_softdevice.hex
nrfjprog --reset --program nrf51_sdk/softdevice/s110/hex/s110_softdevice.hex
A:
all: clean
check this line. The default (first) Target of your Makefile depends on clean, so before any build is started, the clean target is executed that likely will remove all built files, to rebuild them.
Drop the clean and you should get the incremental behaviour make was designed for.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/31082409",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: How to send a lexicon to text-to-speech I'd like help with incorporating a new lexicon into the Azure Text-to-Speech API.
https://learn.microsoft.com/en-us/previous-versions/office/developer/speech-technologies/hh378492%28v%3doffice.14%29
I've successfully sent text and have gotten mp3 files that work. Now I'm trying to incorporate a lexicon with difficult pronunciations.
I'm using the Python SDK for Text-to-Speech and have few questions from the documentation.
*
*Is this reference 'lexicon Element SSML (Microsoft.Speech)' outdated?
*What URI do I use?
*When I use the instructions in this document, I get the following error message: Status code: 400. Something went wrong. Check your subscription key and headers. How do I fix or investigate this?
*What format does the lexicon have to be in? I saw an example in the document that referenced a lexicon in a .pls format. How do I create this? Here is the reference:
<?xml version="1.0"?>
<speak
version="1.0"
xmlns="http://www.w3.org/2001/10/synthesis"
xml:lang="en-US">
<lexicon
uri="c:\Test\whatchamacallit.pls"
type="application/pls+xml"/>
Gimme the whatchamacallit. </speak>
Here's part of the Python that I'm using:
xml_body = ElementTree.Element('speak', version='1.0')
xml_body.set('{http://www.w3.org/XML/1998/namespace}lang', 'en-us')
lexicon = ElementTree.SubElement(xml_body, 'lexicon')
lexicon.set('uri', '/User/.../Desktop/MedLex.pls')
lexicon.set('type', 'application/pls+xml')
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/55736260",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Create conditional variables grouping by time and id I have a data frame that contains the product and destination (dest_prod) consumed by individuals (id), observed during different years (year) in the data frame df:
id <- c("1", "1", "1", "1", "2", "2", "2", "2", "3", "3", "3", "3")
year <- c("2000", "2001", "2002", "2003", "2002", "2003", "2004", "2005", "2001", "2002", "2003", "2005")
dest_prod <- c("FRA_coke", "FRA_coke", "USA_coke", "FRA_coke+USA_coke",
"FRA_coke", "SPA_ham", "FRA_coke+SPA_ham", "GER_coke",
"CHN_water", "CHN_oil", "CHN_water+CHN_oil+FRA_coke", "CHN_water+CHN_oil+FRA_coke")
df <- data.frame(id, year, dest_prod)
I would like to apply the following logic:
*
*Create a new variable "new_dest" if an individual consumes a prod_dest in year (t) that comes from a new destination (3 first letters of "dest_prod") than in year (t-1).
*Create a new variable "new_prod" if an individual consumes a prod_dest in year (t) that contains a new product (letters after the "_" symbol in "dest_prod") than in year (t-1).
Note!: If there is no observed year before (t) for a given individual or the last observation comes from 2 years or longer, I will assign "NA" value.
The new dataframe looks like df_mod:
new_dest <- c("NA", "0", "1", "1",
"NA", "1", "1", "1",
"NA", "0", "1", "NA")
new_prod <- c("NA", "0", "0", "0",
"NA", "1", "1", "0",
"NA", "1", "1", "NA")
df_mod <- data.frame(id, year, dest_prod, new_dest, new_prod)
I have tried to use ifelse in dplyr, but it does not work as it is impossible to capture the sense of time and group (id).
Any idea on how to create new_dest and new_prod in dplyr?
A: The first step is to parse the dest_prod column into a usable format:
library(tidyverse)
parsed <- df %>%
mutate_at(c("id", "year"), as.integer) %>%
separate_rows(dest_prod, sep = "[+]") %>%
separate(dest_prod, into = c("dest", "prod"))
parsed
#> # A tibble: 18 × 4
#> id year dest prod
#> <int> <int> <chr> <chr>
#> 1 1 2000 FRA coke
#> 2 1 2001 FRA coke
#> 3 1 2002 USA coke
#> 4 1 2003 FRA coke
#> 5 1 2003 USA coke
#> 6 2 2002 FRA coke
#> 7 2 2003 SPA ham
#> 8 2 2004 FRA coke
#> 9 2 2004 SPA ham
#> 10 2 2005 GER coke
#> 11 3 2001 CHN water
#> 12 3 2002 CHN oil
#> 13 3 2003 CHN water
#> 14 3 2003 CHN oil
#> 15 3 2003 FRA coke
#> 16 3 2005 CHN water
#> 17 3 2005 CHN oil
#> 18 3 2005 FRA coke
Then:
parsed %>%
# Add previous year's data in a list column
nest_join(
mutate(., year = year + 1L),
name = "previous",
by = c("id", "year")
) %>%
# Check if any dest/prod appeared in previous year
rowwise() %>%
mutate(
new_dest = !dest %in% previous$dest,
new_prod = !prod %in% previous$prod,
) %>%
# Set to missing if previous year was not observed
mutate(
across(c(new_dest, new_prod), replace, !nrow(previous), NA)
) %>%
# Aggregate indicators on year level
group_by(id, year) %>%
summarise(
new_dest = any(new_dest),
new_prod = any(new_prod),
)
#> # A tibble: 12 × 4
#> # Groups: id [3]
#> id year new_dest new_prod
#> <int> <int> <lgl> <lgl>
#> 1 1 2000 NA NA
#> 2 1 2001 FALSE FALSE
#> 3 1 2002 TRUE FALSE
#> 4 1 2003 TRUE FALSE
#> 5 2 2002 NA NA
#> 6 2 2003 TRUE TRUE
#> 7 2 2004 TRUE TRUE
#> 8 2 2005 TRUE FALSE
#> 9 3 2001 NA NA
#> 10 3 2002 FALSE TRUE
#> 11 3 2003 TRUE TRUE
#> 12 3 2005 NA NA
A: If you do want to fight the way dplyr wants to work, here's a non-pivot solution :)
library(dplyr)
library(purrr)
library(stringr)
df %>%
mutate(year = as.numeric(year)) %>%
left_join(., mutate(., year = year + 1), by = c('id', 'year'), suffix = c('', '_previous')) %>%
rowwise() %>%
mutate(dests = str_extract_all(dest_prod, '\\w{3}_'),
prods = str_extract_all(dest_prod, '_\\w+'),
new_dest = max(map_int(dests, \(x) !str_detect(dest_prod_previous, x))),
new_prod = max(map_int(prods, \(x) !str_detect(dest_prod_previous, x)))) %>%
select(-c(dests, prods, dest_prod_previous)) %>%
ungroup()
#> # A tibble: 12 × 5
#> id year dest_prod new_dest new_prod
#> <chr> <dbl> <chr> <int> <int>
#> 1 1 2000 FRA_coke NA NA
#> 2 1 2001 FRA_coke 0 0
#> 3 1 2002 USA_coke 1 0
#> 4 1 2003 FRA_coke+USA_coke 1 0
#> 5 2 2002 FRA_coke NA NA
#> 6 2 2003 SPA_ham 1 1
#> 7 2 2004 FRA_coke+SPA_ham 1 1
#> 8 2 2005 GER_coke 1 0
#> 9 3 2001 CHN_water NA NA
#> 10 3 2002 CHN_oil 0 1
#> 11 3 2003 CHN_water+CHN_oil+FRA_coke 1 1
#> 12 3 2005 CHN_water+CHN_oil+FRA_coke NA NA
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73235948",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: MYSQL:filter query based on user input Maybe this is a simple question but i am struggled to find the answer.
I am trying to implement a filter feature based on category,subject and medium fields value from the table art.
that means if user select only category the result will be the query
SELECT * FROM ART WHERE category=val
if user select category and subject it should be SELECT * FROM ART WHERE category=val AND subject=val
and so on
But i don't how i dynamically build this query one approach is write all possible combinations query and execute based on conditions but i don't think its a good approach
A: $sql=" SELECT * FROM ART where 1=1 ";
if(!empty($category) {
$sql.=" and category= $value";
}
if(!empty($subject) {
$sql.=" and subject= $value";
}
if(!empty($medium) {
$sql.=" and medium= $value";
}
where 1=1 is just to keep the syntax correct else you need to have some login to add where accordingly as you can't add where in all three checks (will make incorrect sql string).
Read about sql injection. Use parameter binding to add parameter, this is just for you to get an idea, this will work but is vulnerable to sql injection
A: Try all the filters in the where condition with OR not AND as shown below
SELECT * FROM ART WHERE category=val OR subject=val OR medium=val;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/46639689",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Decrpyting using pkcs#11 tool I'm trying too encrypt and decrypt using pkcs#11-tool
echo 'Hello word !' | openssl pkeyutl -encrypt -pubin \
-inkey pub.pem \
-pkeyopt rsa_padding_mode:oaep \
-pkeyopt rsa_oaep_md:sha512 \
-pkeyopt rsa_mgf1_md:sha512 \
-out encrypted.data
This work find but trying to decrypt it fail
pkcs11-tool --module /usr/local/lib/softhsm/libsofthsm2.so --decrypt \
--mechanism RSA-PKCS-OAEP \
--input-file encrypted.data \
--label keyp \
--hash-algorithm SHA512 --pin Jojo
I'm having this error :
Using slot 0 with a present token (0x607f2e7f)
Using decrypt algorithm RSA-PKCS-OAEP
OAEP parameters: hashAlg=SHA512, mgf=MGF1-SHA512, source_type=0, source_ptr=(nil), source_len=0
error: PKCS11 function C_DecryptInit failed: rv = CKR_ARGUMENTS_BAD (0x7)
Aborting.
I'm following this tutorial : https://docs.nitrokey.com/nethsm/guides/pkcs11_with_pkcs11-tool and can't what wrong.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75177797",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Aligning multiple divs side by side I am trying to align multiple divs side by side.
I have searched stackoverflow and based my code on this: How to align two divs side by side using the float, clear, and overflow elements with a fixed position div/.
I've played around with it, and ended up with this css:
.frontpageBoxLeft, .frontpageBoxRight {
border-radius: 5px;
border-color: lightgrey;
background: #ffffff;
height: 150px;
}
.frontpageBoxLeft {
margin-bottom:15px;
width: 750px;
min-height: 100px;
position: relative;
}
.frontpageBoxRight {
width: 320px;
float: right;
height: 300px;
position: relative;
vertical-align: top;
}
.frontpageBoxContainer {
width: 70%;
height: 500px;
position: absolute;
top:0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
}
and this html:
<div class="frontpageBoxContainer">
<p class="newsfeedheadline">NEWS FEED</p>
<hr class="hrstarter">
<div class="frontpageBoxLeft" id="1">
et eksempel på en kasse1
</div>
<div class="frontpageBoxLeft" id="2">
et eksempel på en kasse2
</div>
<div class="frontpageBoxLeft" id="3">
et eksempel på en kasse3
</div>
<div class="frontpageBoxRight">
et eksempel på en anden kasse
</div>
</div>
The result is this:
div alignment
I would like to be able to put multiple divs on the left side, and multiple divs on the right side.
Right now the code works fine when iam only using one right and one left div, but with multiple divs it act like in the picture.
Best regards.
A: I guess this might help you
div{
width: 48%;
height: 100px;
background-color: red;
float: left;
margin: 1%;
}
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
or this one
div{
width: 23%;
height: 100px;
background-color: red;
float: left;
margin: 1%;
}
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
A:
.frontpageBoxLeft,
.frontpageBoxRight {
border-radius: 5px;
border-color: lightgrey;
background: #ffffff;
height: 150px;
}
.left-container {
float: left;
width: 750px;
}
.frontpageBoxLeft {
margin-bottom: 15px;
width: 750px;
display: inline-block;
min-height: 100px;
float: right;
position: relative;
outline: 1px solid red;
}
.frontpageBoxRight {
width: 540px;
float: right;
height: 300px;
position: relative;
vertical-align: top;
outline: 1px solid red;
}
.frontpageBoxContainer {
width: 1300px;
height: 500px;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
}
<div class="frontpageBoxContainer">
<p class="newsfeedheadline">NEWS FEED</p>
<hr class="hrstarter">
<div class="left-container">
<div class="frontpageBoxLeft" id="1">
et eksempel på en kasse1
</div>
<div class="frontpageBoxLeft" id="2">
et eksempel på en kasse2
</div>
<div class="frontpageBoxLeft" id="3">
et eksempel på en kasse3
</div>
</div>
<div class="frontpageBoxRight">
et eksempel på en anden kasse
</div>
</div>
A: Put float: left to the .frontpageBoxLeft selector will solve the problem.
A: *
*Try set the frontpageBoxContainer to position:relative
*Float the left AND the right Containers.
*set left or right Offset to the divs you want to align.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/40125435",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Parse 6-byte IP/Port string to in_addr structure in c I'm trying to build a little bittorrent client to store data in the bittorrent dht.
Since much of the bittorrent functionality is not needed I'm trying to stay as simple as possible, since it only needs to function in a couple of limited use cases.
I'm trying to parse information about new nodes from a message, which I get from a bootstrap node. The information about each node is 26-bytes long. 20-bytes is node ID, 4 bytes IP address and 2 bytes port number. All the info is in binary.
I want to store the ip address and port number in a struct (myNode) which has got an in_addr parameter for the IP and unsinged short for the port.
typedef struct myNode {
unsigned char id[21];
struct in_addr ip;
unsigned short port;
} myNode;
The parsing of the ID works fine. But the parsing of the IP and port fails. Sometimes it works, mostly it does not and never both work at the same time. I think there might be something wrong with the bitwise shift I'm doing, but I don't know what. When I printf the IP in hex after parsing I mostly get something like this:
0xffffed3a
So it seems like the first to shifts are not working. The other bits are correct. What am I doing wrong?
int get_nodes_from_find_node(char *msg, myNode *setme) {
char *fnstr = "nodes";
char *pos, *ptr;
long lenNodes;
int nrNodes, i = 0, k = 0;
pos = strstr(msg, fnstr); // Find nodes section.
if(pos == NULL) { return -1; }
pos += strlen(fnstr);
lenNodes = strtoul(pos, &ptr, 10); // Save the length of the nodes section in lenNodes
nrNodes = lenNodes / 26; // Get number of nodes, about which info is delivered.
pos = ptr+1; // Set pos to first node.
while(nrNodes > 0) {
for(k=0;k<20;k++,pos++) { // First 20 bytes are ID.
setme[i].id[k] = *pos;
}
setme[i].id[20] = '\0'; // Make ID a Null-terminated string.
setme[i].ip.s_addr = (*pos << 24) | (*(pos+1) << 16) | (*(pos+2) << 8) | *(pos+3); // Next 4 bytes are IP in network byte order.
pos += 4;
setme[i].port = (*pos << 8) | *(pos+1); // Last 2 bytes are port.
pos += 2;
nrNodes--;
i++;
}
return 0;
}
A: Your problem is in (*pos << 24) | (*(pos+1) << 16) | (*(pos+2) << 8) | *(pos+3).
If any of the values in pos[0,...,3] is negative, then the entire expression is negative.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/39162259",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: BEM Convention with SASS - Problem to understand I am a beginner in front-end and I try to assimilate the notions of SASS and BEM.
I have great difficulty understanding the naming convention and how it is organized with SASS.
I wrote a product section which contains three div (column) which themselves contain child elements.
I have no idea how to organize the names well. For example the img are children of product__preview, but I'm tempted to name the class product__img .... but it looks like it's not correct? If there are several images in the product section but some of them must be different, how do we handle the names? (product__img seems to be too vague).
Do I need to add a product__preview__img class for special cases?
Can you help me correct this block so that I understand the naming correctly?
Thank you in advance!
<section class="product">
<img class="product__cover product__item" src="./images/nintendo/marioodyssey/marioodyssey-1.jpg" alt=""
srcset="">
<div class="product__preview product__item">
<img class="product__img" src="./images/nintendo/marioodyssey/marioodyssey-2.jpg" alt="" srcset="">
<img class="product__img" src="./images/nintendo/marioodyssey/marioodyssey-3.jpg" alt="" srcset="">
<img class="product__img" src="./images/nintendo/marioodyssey/marioodyssey-3.jpg" alt="" srcset="">
</div>
<div class="product__content product__item">
<h4 class="product__title">Super Mario Odyssey</h4>
<p><span> Date: </span> 2017</p>
<p><span> Story: </span> Super Mario Odyssey[b] is a platform game developed and published by Nintendo for
the Nintendo Switch on October 27, 2017. An entry in the Super Mario series, it follows Mario and Cappy,
a sentient hat that allows Mario to control other characters and objects, as they journey across various
worlds to save Princess Peach from his nemesis Bowser, who plans to forcibly marry her. In contrast to
the linear gameplay of prior entries, the game returns to the primarily open-ended, 3D platform gameplay
featured in Super Mario 64 and Super Mario Sunshine.[1] </p>
<p><span> Review: </span></p>
<button class="product__btn btn-orange-tiger">Add to cart</button>
<button class="product__btn btn-orange-tiger">Go to cart</button>
<button class="product__btn btn-orange-tiger">Keep buying</button>
</div>
</section>
A: The structure you have now is perfectly fine and valid. Therefore, you would not want to use product__preview__img. You would be defeating the purpose of BEM if you were to create those kind of selectors as you would be creating complex/unorganised code. If you feel the name is vague, you could try product__img-preview as this still ties in with the block element selector and not a stacked block element selector.
One more thing I could suggest since you are using BEM and to utilise it fully, is to change your modifier class names for the buttons you have to product__btn product__btn--orange as it will help keep your code maintainable as you have the block element selector along side a modifier which is the orange button in this case.
.product {
...
&__features {
...
}
&__btn {
...
&--orange {
...
}
}
}
As you can see, the deepest nesting level is the modifiers of the block element.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/63762541",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to configure spring controller to use different objectMapper for the response (serialization) I configured my own ObjectMapper for my SpringBoot application, Let say the object mapper is something like below (simplified):
@Bean
@Primary
public ObjectMapper objectMapper() {
return new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
}
Since the ObjectMapper is a singleton, all my REST Controller use that same ObjectMapper.
But, there is some controller that I want to ignore the null value, but I want to keep the rest of my controller to send the null value response.
Is there a way to configure it? So the best result is I can configure something like this:
*
*Controller A,B,C -> ObjectMapper X (ignore null value)
*Controller D -> ObjectMapper Y (ignore empty value)
*Default (all other controller) -> ObjectMapper Z (return null value)
Requirement Note:
*
*I can't change the POJO since it's autogenerated, and I don't want to update the codegen lib or the mustache template for this.
*Specific content negotiation is not an option
A: In addition to your ObjectMapper annotated with @Primary
you can configure more ObjectMappers qualified with bean names of your choice.
@Bean
@Primary
public ObjectMapper objectMapper() {
ObjectMapper objectMapper = new ObjectMapper()
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
return objectMapper;
}
@Bean("mySpecialObjectMapper")
public ObjectMapper anotherObjectMapper() {
ObjectMapper objectMapper = new ObjectMapper()
/* do some other configuration */;
return objectMapper;
}
Then you can refer to them in your controllers like this:
*
*Just giving @Autowired will inject the primary ObjectMapper.
*Giving @Autowired together with @Qualifier("anyName") will inject
the ObjectMapper configured with @Bean("anyName")
@Autowired
private ObjectMapper objectMapper;
@Autowired
@Qualifier("mySpecialObjectMapper")
private ObjectMapper otherObjectMapper;
A: Maybe you just need to use @JsonInclude(JsonInclude.Include.NON_NULL). Try to fix it in the response model level.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/66706199",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: how to hide blinking cursor in input text? I want to make something which would look like a select input but is actually not, here are the steps.
I made an <input type="text">.
I added a background-image, which will show a "select arrow", giving the impression that it's a select box.
I added a default value to this input.
There will be a hidden div which will SlideDown() right under this input when I click on it.
I tried the read only thing so that the value cannot be changed, but the blinking cursor will show up.
If I use disabled, the blinking cursor will not show up, but the .click() or .focus function in jQuery will not work. The drop down menu will not SlideDown().
How can I make it clickable while not showing the blinking cursor?
Here's the code
<div style="padding-top:17px; overflow:hidden;">
<div style="float:left;">
<label for="secretquestion">Secret Question</label><br>
<input type="text" class="inputselect" id="secretquestion" name="secretquestion" value="Choose a Secret Question" tabindex=10 /><br>
<div class="selectoptions" id="secretquestionoptions">
<b>test</b>
</div>
</div>
</div>
CSS
.selectoptions
{
display: none;
background-color: white;
color: rgb(46,97,158);
width: 250px;
margin:auto;
border-style: solid;
border-width:1px;
border-color: rgb(46,97,158);
font-size: 14px;
text-align: center;
}
.inputselect {
color: white;
cursor: pointer;
background-image: url('inputselect.png');
padding-top: 5px;
padding-bottom: 5px;
padding-left:10px;
padding-right:-10px;
width:240px;
border-style: solid;
border-color: rgb(46,97,158);
border-width: 1px;
}
.inputselect:hover {
outline:none;
color:aqua;
cursor: pointer;
background-image: url('inputselecthover.png');
}
.inputselect:focus {
outline:none;
color:aqua;
cursor: pointer;
background-image: url('inputselecthover.png');
}
A: I think this is a perfect solution: make the input wide enough, align right to screen right, thus make cursor and content locate at the outside of the screen, while it's still clickable
A: The color of the cursor matches the color of the text.
<input type="text" style="color: transparent">
If you actually want to show text in the input box (my, some people are needy), you can use a text shadow.
<style>
body, div, input {
color: #afa;
text-shadow: 0px 0px 1px #fff;
}
<style>
(tested Firefox and Safari).
A: try this code it worked on me :-
<div class="input-parent" style="margin-left: 30px;">
<input type="text" />
</div>
input-parent {
width: 100px;
height: 30px;
overflow: hidden;
}
.input-parent input {
width: 120px;
height: 30px;
margin-left: -20px;
text-align: left;
caret-color: transparent;
}
A: Just add this to "inputselect" class:
caret-color: transparent;
A: I just used a blur to get rid of the cursor.
$('input').mousedown(function(e){
e.preventDefault();
$(this).blur();
return false;
});
A: I finally find a trick solution.
<div class="wrapper">
<input type="text" />
</div>
.wrappr {
width: 100px;
height: 30px;
overflow: hidden;
}
.wrapper input {
width: 120px;
height: 30px;
margin-left: -20px;
text-align: left;
}
and in my sitation, it works!
A: This may be helpful (though not a complete response) - I used it to disable input in a recent project:
document.getElementById('Object').readOnly = true;
document.getElementById('Object').style.backgroundColor = '#e6e6e6';
document.getElementById('Object').onfocus = function(){
document.getElementById('Object').blur();
};
The user focuses on the input when the click in it, the blur() function then removes the focus. Between this, setting the readOnly to "True" and setting the background color to grey (#e6e6e6), your user shouldn't get confused.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/9333044",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "77"
}
|
Q: Facebook Integration in IOS to fetch users data I had registered my application in facebook developers. I got app id and client key.
Is there any tutorials for an application to fetch users data?
Any third parties suggested ?
A: This tutorial is the best for me http://www.raywenderlich.com/44640/integrating-facebook-and-parse-tutorial-part-1
A: Why third party? What's wrong with Facebooks documentation? It's perfectly clear
https://developers.facebook.com/docs/ios/getting-started
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/21165403",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: wxPython: How to Show status/progress window and update the progress from another python code? I have a regular python app (not wx) , and i want to add a wxStatusWindow (Guage Class) in order to show the progress in my App.
There are many examples in web for wxGuage /Status windows but in all examples the progress is handled within the wxFrame.
How can i call the statusWIndow from my python code while the python code is running ?
I did some reading...is it running on separate thread??
I will appreciate an example...how can i do that?
alternatively..I though of just opening a wxDialog from my app and showing info about the progress (and than closing it and raising another wxDialog with new info)...but again..
I need the message to be displayed and in parallel the code in my app to continue running..and than to be able to close the message box from my python app
any Idea's?
code examples?
10x
Yodash
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/57611577",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Problem when I try to move socket creation code to another activity? I have an android application created by eclipse.
This application works as a client connecting to a server wirelessly across a socket connection.
I have a problem with the code of socket creation.
When I try to move the code from an activity to another in my application, then it doesn't work.
Here is the first activity, where the code works:
public class MyNewAndroidActivity extends Activity {
protected Socket socket;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Button button_connect = (Button) findViewById(R.id.button1);
final Button button_disconnect = (Button) findViewById(R.id.button2);
final Button b_forward = (Button) findViewById(R.id.b_forward);
final Button b_backward = (Button) findViewById(R.id.b_backward);
final Button b_right = (Button) findViewById(R.id.b_right);
final Button b_left = (Button) findViewById(R.id.b_left);
final Button b_stop = (Button) findViewById(R.id.b_stop);
button_connect.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
// Create socket with time out
//192.168.1.76
// my code which I want to transfer it.
int port = 2005;
SocketAddress sockaddr = new InetSocketAddress("192.168.1.15", port);
socket = new Socket();
int timeoutMs = 2000;
socket.connect(sockaddr, timeoutMs);
}
catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
when I convert it to method in another activity then it doesn't work:
public class IBMEyes extends Activity implements SensorListener{
protected static Socket socket;
final String tag = "MyProject";
String state ="off";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sm = (SensorManager) getSystemService(SENSOR_SERVICE);
setContentView(R.layout.main);
Button b_connect = (Button) findViewById(R.id.button1);
b_connect.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
SocketConnect();
}
});
// here is my code that I've transferred it.
public void SocketConnect() {
// TODO Auto-generated method stub
try {
int port = 2005;
SocketAddress sockaddr = new InetSocketAddress("192.168.1.15", port);
socket = new Socket();
int timeoutMs = 2000;
socket.connect(sockaddr, timeoutMs);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7064627",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to fix "unhashable type: 'list'" error I am trying to run a function to get column name corresponding to 2 in data frame
Input Dataframe:
df1
A|B|C|D
1|0|2|4
2|9|1|3
Output DataFrame:
A|B|C|D|new|
1|0|2|4|C|
2|9|1|3|A|
I have made the function but for some reason I am getting TypeError: ("unhashable type: 'list'", 'occurred at index 0')
def colname(x):
b = (df1.loc[x]==2)
return b.idxmax()
df1["new"]=df1.apply(colname,axis=1)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/55541823",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: JSF : convertNumber MonetaryAmount not working in dataTable I wanted to display MonetaryAmounts inside a dataTable. Curiously it doesn't work : the currencyCode appears to be empty (but not null).
Note : it works outside a dataTable for a single MonetaryAmount.
Tested with wildfly 25.0.1 (Mojarra 2.3.14.SP04) and Payara5
The bean :
@Named("dtBasicView")
@ViewScoped
public class BasicView implements Serializable {
private List<MonetaryAmount> amounts;
@PostConstruct
public void init() {
amounts = new ArrayList<>();
CurrencyUnit unit = Monetary.getCurrency("EUR");
MonetaryAmount amount = Monetary.getDefaultAmountFactory().setCurrency(unit).setNumber(200).create();
amounts.add(amount);
}
public List<MonetaryAmount> getAmounts() {
return amounts;
}
}
Facelet :
<h:dataTable var="item" value="#{dtBasicView.amounts}" >
<h:column>
<f:facet name="header">Amount</f:facet>
<h:outputText value="#{item.number}">
<f:convertNumber currencyCode="#{item.currency.currencyCode}" type="currency" />
</h:outputText>
</h:column>
</h:dataTable>
It blows in java.util.Currency because the currencyCode is empty :
if (currencyCode.length() != 3) {
throw new IllegalArgumentException();
}
Here is the error.
17:17:58,946 SEVERE [javax.enterprise.resource.webcontainer.jsf.application] (default task-11) Error Rendering View[/ui/data/datatable/basic.xhtml]: javax.faces.convert.ConverterException: j_idt303:j_idt305:0:j_idt307: Could not convert '200' to a string.
at javax.faces.api@3.0.0.SP04//javax.faces.convert.NumberConverter.getAsString(NumberConverter.java:686)
at com.sun.jsf-impl@2.3.14.SP04//com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.getFormattedValue(HtmlBasicRenderer.java:491)
at com.sun.jsf-impl@2.3.14.SP04//com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.getFormattedValue(HtmlBasicRenderer.java:509)
at com.sun.jsf-impl@2.3.14.SP04//com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.getCurrentValue(HtmlBasicRenderer.java:330)
at com.sun.jsf-impl@2.3.14.SP04//com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.encodeEnd(HtmlBasicRenderer.java:143)
at javax.faces.api@3.0.0.SP04//javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:595)
at javax.faces.api@3.0.0.SP04//javax.faces.component.UIComponent.encodeAll(UIComponent.java:1654)
at deployment.primefaces-showcase-11.0.0.war//org.primefaces.component.column.Column.renderChildren(Column.java:90)
at deployment.primefaces-showcase-11.0.0.war//org.primefaces.component.datatable.DataTableRenderer.encodeCell(DataTableRenderer.java:1356)
at deployment.primefaces-showcase-11.0.0.war//org.primefaces.component.datatable.DataTableRenderer.encodeRow(DataTableRenderer.java:1272)
at deployment.primefaces-showcase-11.0.0.war//org.primefaces.component.datatable.DataTableRenderer.encodeRows(DataTableRenderer.java:1179)
at deployment.primefaces-showcase-11.0.0.war//org.primefaces.component.datatable.DataTableRenderer.encodeTbody(DataTableRenderer.java:1119)
at deployment.primefaces-showcase-11.0.0.war//org.primefaces.component.datatable.DataTableRenderer.encodeTbody(DataTableRenderer.java:1072)
at deployment.primefaces-showcase-11.0.0.war//org.primefaces.component.datatable.DataTableRenderer.encodeRegularTable(DataTableRenderer.java:401)
at deployment.primefaces-showcase-11.0.0.war//org.primefaces.component.datatable.DataTableRenderer.encodeMarkup(DataTableRenderer.java:331)
at deployment.primefaces-showcase-11.0.0.war//org.primefaces.component.datatable.DataTableRenderer.render(DataTableRenderer.java:106)
at deployment.primefaces-showcase-11.0.0.war//org.primefaces.component.datatable.DataTableRenderer.encodeEnd(DataTableRenderer.java:97)
at javax.faces.api@3.0.0.SP04//javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:595)
at javax.faces.api@3.0.0.SP04//javax.faces.component.UIComponent.encodeAll(UIComponent.java:1654)
at javax.faces.api@3.0.0.SP04//javax.faces.render.Renderer.encodeChildren(Renderer.java:152)
at javax.faces.api@3.0.0.SP04//javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:566)
at javax.faces.api@3.0.0.SP04//javax.faces.component.UIComponent.encodeAll(UIComponent.java:1647)
at javax.faces.api@3.0.0.SP04//javax.faces.component.UIComponent.encodeAll(UIComponent.java:1650)
at javax.faces.api@3.0.0.SP04//javax.faces.component.UIComponent.encodeAll(UIComponent.java:1650)
at com.sun.jsf-impl@2.3.14.SP04//com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:468)
at com.sun.jsf-impl@2.3.14.SP04//com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:170)
at javax.faces.api@3.0.0.SP04//javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:132)
at javax.faces.api@3.0.0.SP04//javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:132)
at javax.faces.api@3.0.0.SP04//javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:132)
at com.sun.jsf-impl@2.3.14.SP04//com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:102)
at com.sun.jsf-impl@2.3.14.SP04//com.sun.faces.lifecycle.Phase.doPhase(Phase.java:76)
at com.sun.jsf-impl@2.3.14.SP04//com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:199)
at javax.faces.api@3.0.0.SP04//javax.faces.lifecycle.LifecycleWrapper.render(LifecycleWrapper.java:88)
at javax.faces.api@3.0.0.SP04//javax.faces.webapp.FacesServlet.executeLifecyle(FacesServlet.java:708)
at javax.faces.api@3.0.0.SP04//javax.faces.webapp.FacesServlet.service(FacesServlet.java:451)
at io.undertow.servlet@2.2.12.Final//io.undertow.servlet.handlers.ServletHandler.handleRequest(ServletHandler.java:74)
at io.undertow.servlet@2.2.12.Final//io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:129)
at deployment.primefaces-showcase-11.0.0.war//org.primefaces.showcase.filter.CharacterEncodingFilter.doFilter(CharacterEncodingFilter.java:41)
at io.undertow.servlet@2.2.12.Final//io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61)
at io.undertow.servlet@2.2.12.Final//io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131)
at io.opentracing.contrib.opentracing-jaxrs2//io.opentracing.contrib.jaxrs2.server.SpanFinishingFilter.doFilter(SpanFinishingFilter.java:52)
at io.undertow.servlet@2.2.12.Final//io.undertow.servlet.core.ManagedFilter.doFilter(ManagedFilter.java:61)
at io.undertow.servlet@2.2.12.Final//io.undertow.servlet.handlers.FilterHandler$FilterChainImpl.doFilter(FilterHandler.java:131)
at io.undertow.servlet@2.2.12.Final//io.undertow.servlet.handlers.FilterHandler.handleRequest(FilterHandler.java:84)
at io.undertow.servlet@2.2.12.Final//io.undertow.servlet.handlers.security.ServletSecurityRoleHandler.handleRequest(ServletSecurityRoleHandler.java:62)
at io.undertow.servlet@2.2.12.Final//io.undertow.servlet.handlers.ServletChain$1.handleRequest(ServletChain.java:68)
at io.undertow.servlet@2.2.12.Final//io.undertow.servlet.handlers.ServletDispatchingHandler.handleRequest(ServletDispatchingHandler.java:36)
at org.wildfly.security.elytron-web.undertow-server@1.10.0.Final//org.wildfly.elytron.web.undertow.server.ElytronRunAsHandler.lambda$handleRequest$1(ElytronRunAsHandler.java:68)
at org.wildfly.security.elytron-base@1.17.1.Final//org.wildfly.security.auth.server.FlexibleIdentityAssociation.runAsFunctionEx(FlexibleIdentityAssociation.java:103)
at org.wildfly.security.elytron-base@1.17.1.Final//org.wildfly.security.auth.server.Scoped.runAsFunctionEx(Scoped.java:161)
at org.wildfly.security.elytron-base@1.17.1.Final//org.wildfly.security.auth.server.Scoped.runAs(Scoped.java:73)
at org.wildfly.security.elytron-web.undertow-server@1.10.0.Final//org.wildfly.elytron.web.undertow.server.ElytronRunAsHandler.handleRequest(ElytronRunAsHandler.java:67)
at io.undertow.servlet@2.2.12.Final//io.undertow.servlet.handlers.RedirectDirHandler.handleRequest(RedirectDirHandler.java:68)
at io.undertow.servlet@2.2.12.Final//io.undertow.servlet.handlers.security.SSLInformationAssociationHandler.handleRequest(SSLInformationAssociationHandler.java:117)
at io.undertow.servlet@2.2.12.Final//io.undertow.servlet.handlers.security.ServletAuthenticationCallHandler.handleRequest(ServletAuthenticationCallHandler.java:57)
at io.undertow.core@2.2.12.Final//io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at io.undertow.core@2.2.12.Final//io.undertow.security.handlers.AbstractConfidentialityHandler.handleRequest(AbstractConfidentialityHandler.java:46)
at io.undertow.servlet@2.2.12.Final//io.undertow.servlet.handlers.security.ServletConfidentialityConstraintHandler.handleRequest(ServletConfidentialityConstraintHandler.java:64)
at io.undertow.core@2.2.12.Final//io.undertow.security.handlers.AbstractSecurityContextAssociationHandler.handleRequest(AbstractSecurityContextAssociationHandler.java:43)
at org.wildfly.security.elytron-web.undertow-server-servlet@1.10.0.Final//org.wildfly.elytron.web.undertow.server.servlet.CleanUpHandler.handleRequest(CleanUpHandler.java:38)
at io.undertow.core@2.2.12.Final//io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at org.wildfly.extension.undertow@25.0.1.Final//org.wildfly.extension.undertow.security.jacc.JACCContextIdHandler.handleRequest(JACCContextIdHandler.java:61)
at io.undertow.core@2.2.12.Final//io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at org.wildfly.extension.undertow@25.0.1.Final//org.wildfly.extension.undertow.deployment.GlobalRequestControllerHandler.handleRequest(GlobalRequestControllerHandler.java:68)
at io.undertow.servlet@2.2.12.Final//io.undertow.servlet.handlers.SendErrorPageHandler.handleRequest(SendErrorPageHandler.java:52)
at io.undertow.core@2.2.12.Final//io.undertow.server.handlers.PredicateHandler.handleRequest(PredicateHandler.java:43)
at io.undertow.servlet@2.2.12.Final//io.undertow.servlet.handlers.ServletInitialHandler.handleFirstRequest(ServletInitialHandler.java:280)
at io.undertow.servlet@2.2.12.Final//io.undertow.servlet.handlers.ServletInitialHandler.access$100(ServletInitialHandler.java:79)
at io.undertow.servlet@2.2.12.Final//io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:134)
at io.undertow.servlet@2.2.12.Final//io.undertow.servlet.handlers.ServletInitialHandler$2.call(ServletInitialHandler.java:131)
at io.undertow.servlet@2.2.12.Final//io.undertow.servlet.core.ServletRequestContextThreadSetupAction$1.call(ServletRequestContextThreadSetupAction.java:48)
at io.undertow.servlet@2.2.12.Final//io.undertow.servlet.core.ContextClassLoaderSetupAction$1.call(ContextClassLoaderSetupAction.java:43)
at org.wildfly.extension.undertow@25.0.1.Final//org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1544)
at org.wildfly.extension.undertow@25.0.1.Final//org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1544)
at org.wildfly.extension.undertow@25.0.1.Final//org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1544)
at org.wildfly.extension.undertow@25.0.1.Final//org.wildfly.extension.undertow.deployment.UndertowDeploymentInfoService$UndertowThreadSetupAction.lambda$create$0(UndertowDeploymentInfoService.java:1544)
at io.undertow.servlet@2.2.12.Final//io.undertow.servlet.handlers.ServletInitialHandler.dispatchRequest(ServletInitialHandler.java:260)
at io.undertow.servlet@2.2.12.Final//io.undertow.servlet.handlers.ServletInitialHandler.access$000(ServletInitialHandler.java:79)
at io.undertow.servlet@2.2.12.Final//io.undertow.servlet.handlers.ServletInitialHandler$1.handleRequest(ServletInitialHandler.java:100)
at io.undertow.core@2.2.12.Final//io.undertow.server.Connectors.executeRootHandler(Connectors.java:387)
at io.undertow.core@2.2.12.Final//io.undertow.server.HttpServerExchange$1.run(HttpServerExchange.java:852)
at org.jboss.threads@2.4.0.Final//org.jboss.threads.ContextClassLoaderSavingRunnable.run(ContextClassLoaderSavingRunnable.java:35)
at org.jboss.threads@2.4.0.Final//org.jboss.threads.EnhancedQueueExecutor.safeRun(EnhancedQueueExecutor.java:1990)
at org.jboss.threads@2.4.0.Final//org.jboss.threads.EnhancedQueueExecutor$ThreadBody.doRunTask(EnhancedQueueExecutor.java:1486)
at org.jboss.threads@2.4.0.Final//org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1377)
at org.jboss.xnio@3.8.4.Final//org.xnio.XnioWorker$WorkerThreadFactory$1$1.run(XnioWorker.java:1280)
at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: java.lang.reflect.InvocationTargetException
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at javax.faces.api@3.0.0.SP04//javax.faces.convert.NumberConverter.configureCurrency(NumberConverter.java:775)
at javax.faces.api@3.0.0.SP04//javax.faces.convert.NumberConverter.getAsString(NumberConverter.java:674)
... 86 more
Caused by: java.lang.IllegalArgumentException
at java.base/java.util.Currency.getInstance(Currency.java:315)
at java.base/java.util.Currency.getInstance(Currency.java:296)
... 92 more
Error with Payara5
[2022-11-30T18:18:45.713+0100] [Payara 5.2021.3] [WARNING] [] [javax.enterprise.web] [tid: _ThreadID=83 _ThreadName=http-thread-pool::http-listener-1(2)] [timeMillis: 1669828725713] [levelValue: 900] [[
StandardWrapperValve[Faces Servlet]: Servlet.service() for servlet Faces Servlet threw exception
java.lang.IllegalArgumentException
at java.base/java.util.Currency.getInstance(Currency.java:315)
at java.base/java.util.Currency.getInstance(Currency.java:296)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at javax.faces.convert.NumberConverter.configureCurrency(NumberConverter.java:775)
at javax.faces.convert.NumberConverter.getAsString(NumberConverter.java:674)
at com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.getFormattedValue(HtmlBasicRenderer.java:491)
at com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.getFormattedValue(HtmlBasicRenderer.java:509)
at com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.getCurrentValue(HtmlBasicRenderer.java:330)
at com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.encodeEnd(HtmlBasicRenderer.java:143)
at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:595)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/74631354",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: What is the difference between Child and Element of a container? What is the difference between Child and Element of a container?
Why do the containers like Spark VGroup have different sets of methods for both Child and Elements?
Can anyone explain me the difference in the simplest way?
Thanks in advance..
A: The addChild method is used for adding a DisplayObject, which is a method from pure actionscript. So you would typically add Sprite, MovieClips etc. Widely used in action script based projects
The Flex classes like VGroup are written on top of the base actionscript classes, and therefore have an extra addElement method to be able to add an IVisualElement, which can also be an FXG for example, or other Flex based components such as UIComponent, Group etc.
However, I doubt that calling addChild on a VGroup will actually provide desired results and may result in errors.
Hope this answers your question.
A: The type IVisualElement and with it all the *Element methods from IVisualElementContainer were introduced in Flex SDK 4.0 as part of the spark layout and lifecycle features.
You are still free to build your own components based on UIComponents without having the spark features and only with the *Child methods.
All classes that extend DisplayObjectContainer of course inherit the *Child methods but in classes like Group (and SkinnableComponent) those methods have been overwritten to throw an error, as one needs to use the *Element methods to use the Spark features.
As Flex 4 supports using the MX layout as well as the Spark layout (there are options to use only one of them or both side by side when compiling) those methods could not be marked as deprecated in Group and SkinnableComponent, wich would at least trigger a compiler warning instead of a runtime error.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/32021800",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How can I list the all Discord servers ID where my bot are in the console? | discord.js I tried on googling but all of the errors was "is not a function", that's because i'm using discord.js V12?
I can't find it on google, there is less question about this one. This was my code.
var serverArray = client.guilds.array();
for(i = 0; i < serverArray.length; i++) {
console.log("Server ID: " + serverArray[i].id);
}
A: client.guilds.cache.forEach(guild => {
console.log(`${guild.name} | ${guild.id}`);
})
A: let clientguilds = client.guilds.cache()
console.log(clientguilds.map(g => g.id) || "None")
This should do the trick! It's going to cache all the guilds your bot is in and then it will map the guilds as an array. We then get the id of each guild or, if it's not in any guilds "none".
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/62602195",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Can someone explain to me on runQueryOnBackgroundThread? Can someone just explain to me what is runQueryOnBackgroundThread as I already read through some sources but still not understand with it?
@Override
public Cursor runQueryOnBackgroundThread(CharSequence constraint){
FilterQueryProvider filter = getFilterQueryProvider();
if (filter != null){
return filter.runQuery(constraint);
}
Uri uri = Uri.withAppendedPath(
ContactsContract.CommonDataKinds.Phone.CONTENT_FILTER_URI, Uri.encode(constraint.toString()));
return content.query(uri, CONTACT_PROJECTION, null, null, null);
}
A: A handle of my Activity in the Adapter and the runQuery call in the filter makes a call to startManagingCursor on the Activity whenever the runQuery is called. This is not ideal because a background thread is calling startManagingCursor and also there could be a lot of cursors remaining open until the Activity is destroyed.
I added the following to my Adapter which has a handle on the Activity it is used within
@Override
public void changeCursor(Cursor newCursor) {
Cursor oldCursor = getCursor();
super.changeCursor(newCursor);
if(oldCursor != null && oldCursor != newCursor) {
// adapter has already dealt with closing the cursor
activity.stopManagingCursor(oldCursor);
}
activity.startManagingCursor(newCursor);
}
This makes sure that the current cursor used by the adapter is also managed by the activity. When the cursor is closed by the adapter management by the activity is removed. The last cursor held by the adapter will be closed by the activity by way of it still be managed by the activity.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/12793274",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: How to unmount webcomponent used inside react component? I am using web component inside react component. when I unmount react component, it seems web component inside react component is not being unmounted properly, because when I mount the react component again, webcomponent props update method is being called and then throws error
Uncaught TypeError: Cannot read property 'appendChild' of null
I am using skate js to create webcomponent.
How to properly unmount the web component. please help, I would always be thakful.
Please let me know if any more information is required.
A: I solved this. The Widget component was not being unmounted properly. I have to remove it forcefully form dom using
Mozilla docs removeChild
After that it works fine.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/56537242",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How can I print/echo/get all attributes from each of the objects in this code? How can I print/echo all properties/attributes values from all Country objects in this code? I thought of using 'foreach' but I don't know the sintaxis.
The echo statement is in the last line of code.
Thanks!
<?php
class Country {
public $nombre;
public $poblacion;
public $idioma;
public $moneda;
public $economia;
public $deporte;
}
$country1 = new Country ();
$country1->nombre = 'Argentina';
$country1->poblacion = '40 millones';
$country1->idioma = 'Castellano';
$country1->moneda = 'Peso argentino';
$country1->economia = 'Agro';
$country1->deporte = 'Futbol';
$country2 = new Country ();
$country2->nombre = 'USA';
$country2->poblacion = '200 millones';
$country2->idioma = 'Ingles';
$country2->moneda = 'Dolar estadounidense';
$country2->economia = 'Multiples industrias';
$country2->deporte = 'Basket,Baseball,Futbol Americano';
$country3 = new Country ();
$country3->nombre = 'Alemania';
$country3->poblacion = '50 millones';
$country3->idioma = 'Aleman';
$country3->moneda = 'Euro';
$country3->economia = 'Multiples industrias';
$country3->deporte = 'Futbol';
$countries = [$country1,$country2,$country3];
foreach ($countries as $country)
{
**echo $country->¿? "<br>";**
}
A: foreach ($countries as $country) {
foreach ($country as $k => $v) {
echo $k . ': ' . $v . '<br>'; // nombre: Argentina ...
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/57031473",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
}
|
Q: jquery-ajax-php: error message not shown on other empty input fields after it's updated I’m trying to validate post data using jquery and ajax for my registration form where an error message will be shown below each input fields. I manage to get the error message initially. But when some of the empty fields were updated with an input, the error message does not shown in the remaining empty field. Would somebody please be kind to point out if is there is any problem with below script?
<script type="text/javascript">
$(document).ready(function(){
$('#reg-form').submit(function(event){
// stop refreshing the page
event.preventDefault();
$('.reg_form').removeClass('has-error'); // remove the error class
$('.localError').remove(); // remove the error text
$('#response').html("<b>Processing your info..</b>");
var formMessages = $('#response');
var form = $('#reg-form');
var formData = $(this).serialize();
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData,
dataType: 'JSON'
})
.done(function(data){
// log data to the console
console.log(data);
if (data !== '') {
// handle errors for username
if (data.username) {
$('#username-div').addClass('has-error'); // add the error class to show red input
$('#username-div').append('<div class="localError">' + data.username + '</div>'); // add the actual error message under our input
}
// handle errors for password ---------------
if (data.password) {
$('#password-div').addClass('has-error'); // add the error class to show red input
$('#password-div').append('<div class="localError">' + data.password + '</div>'); // add the actual error message under our input
}
// handle errors for conf_pass ---------------
if (data.conf_pass) {
$('#conf_pass-div').addClass('has-error'); // add the error class to show red input
$('#conf_pass-div').append('<div class="localError">' + data.conf_pass + '</div>'); // add the actual error message under our input
}
}
else {
//Turn the response alert into a success alert
$('#response').addClass('alert-success');
$('#response').removeClass('alert-error');
//Add the success message text into the alert
$('#response').html("<i class='success'></i> Form validated successfully!").fadeIn();
}
})
.fail(function() {
// just in case posting your form failed
alert( "Error.." );
});
return false;
});
});
</script>
regsiter.php
<div id="reg">
<!-- where the response will be displayed -->
<div id='response'></div>
<form action="register-handler.php" method="POST" id="reg-form">
<div id='username-div' class='reg_form'>
<label for="username" >Username:</label></br>
<input type="text" name="username" id="username" autocomplete="off">
</div>
<div id='password-div' class='reg_form'>
<label for="password" >Password:</label></br>
<input type="password" name="password" id="password" >
</div>
<div id='conf_pass-div' class='reg_form'>
<label for="conf_pass" >Confirm Password:<label></br>
<input type="password" name="conf_pass" id="conf_pass" >
</div>
<div></div>
<input type="hidden" name="token" value="<?php echo Token::generate(); ?>">
<input type="submit" value="submit"></td>
</form>
</div>
register-handler.php
<?php
require_once 'core/init.php';
if(Input::exists()){
if(Token::check(Input::get('token'))) {
$validate = new Validate();
$validation = $validate->check($_POST, array(
'username' => array(
'required' => true,
'min' => 2,
'max' => 20,
'unique' => 'users'
),
'password' => array(
'required' => true,
'min' => 6
),
'conf_pass' => array(
'required' => true,
'matches' => 'password'
)
));
if($validation->passed()) {
//register user
$user = new User();
$salt = Hash::salt(32);
try {
$user->create(array(
'username' => Input::get('username'),
'password' => Hash::make(Input::get('password'), $salt),
'salt' => $salt
));
Session::flash('home', 'You have been registered and can now log in!');
Redirect::to('index.php');
} catch(Exception $e) {
die($e->getMessage());
}
}
else {
//output errors
header('Content-Type: application/json');
echo json_encode($validation->errors());
}
}
}
}
?>
validate.php
<?php
class Validate {
private $_passed = false,
$_errors = array()
public function check($source, $items = array()) {
foreach ($items as $item => $rules) {
foreach ($rules as $rule => $rule_value) {
$value = trim($source[$item]);
$item = escape($item);
if ($rule === 'required' && empty($value)) {
$this->addError($item, "{$item} is empty");
} else if (!empty($value)) {
switch ($rule) {
case 'min':
if (strlen($value) < $rule_value) {
$this->addError($item, "{$item} must be a minimum of {$rule_value} characters.");
}
break;
case 'max':
if (strlen($value) > $rule_value) {
$this->addError($item, "{$item} must be a maximum of {$rule_value} characters.");
}
break;
case 'matches':
if ($value != $source[$rule_value]) {
$this->addError($item, "{$rule_value} must match {$item}");
}
break;
}
}
}
}
if (empty($this->_errors)) {
$this->_passed = true;
}
return $this;
}
private function addError($key, $error) {
$this->_errors[$key] = $error;
}
public function errors() {
return $this->_errors;
}
public function passed() {
return $this->_passed;
}
}
?>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/29777441",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: setting low rlimit_nproc value doesn't allow even a single fork I am trying to use setrlimit to limit the number of processes a program can create. Here is my code:
struct rlimit limiter;
getrlimit( RLIMIT_NPROC, &limiter );
limiter.rlim_max = limiter.rlim_cur = 10;
setrlimit( RLIMIT_NPROC, &limiter );
int val = fork();
printf( "Error number %d\n", errno ); //gives 11
if( val == -1 ) {
printf( "Fork failed\n" );
} else if( val ) {
printf( "parent\n" );
} else {
printf("child\n" );
}
return 0;
Since the value of rlim_max and rlim_cur is 10, my program should be allowed to fork 10 processes. But right now it is failing even for a single fork call. Though it works if I set the values to around 250. I don't understand why is that. I want a way to limit the number of forks to n.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/32649829",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Silex: How to create a loop in Form The following lines of code get me a Silex Form. One text-field and one checkbox. The text-field contains the name of a team. The checkboxes should contain the username of a user, so that I can add them to the team.
$form = $app['form.factory']->createBuilder(FormType::class)
->add('name', TextType::class, array(
'constraints' => array(new Assert\NotBlank(), new Assert\Length(array('min' => 4,'max' => 64))),
'label' => 'Team Name',
'required' => 'required',
'attr' => array('class' => 'input-field', 'autocomplete' => 'off', 'value' => $team->data()->name),
'label_attr' => array('class' => 'label')
))
->add('players', CheckboxType::class, [
'constraints' => array(new Assert\NotBlank()),
'label' => $player->username,
'attr' => array('class' => 'input-field', 'value' => $player->username),
'label_attr' => array('class' => 'label')
])
->add('submit', SubmitType::class, [
'label' => 'Edit',
'attr' => array('class' => 'submit'),
])
->getForm();
I can get my list of users using the following lines:
$user = new User()
$user->getList();
foreach($user->data() as $player){
->add('players', CheckboxType::class, [
'constraints' => array(new Assert\NotBlank()),
'label' => $player->username,
'attr' => array('class' => 'input-field', 'value' => $player->username),
'label_attr' => array('class' => 'label')
])
}
However, I don't know how to combine these two parts, since the $form variable is defined in one 'line' with a ';' at the end. How can I break this $form into parts so that I can loop through my users and add a checkbox for every user?
A: The form is "generated" once you execute ->getForm(); so if you want to add anyfield before generating it, you should finish by ->getForm();
So your code should probably look like:
// add you "static" fields
$formBuilder = $app['form.factory']->createBuilder(FormType::class)
->add('name', TextType::class, array(
'constraints' => array(new Assert\NotBlank(), new Assert\Length(array('min' => 4,'max' => 64))),
'label' => 'Team Name',
'required' => 'required',
'attr' => array('class' => 'input-field', 'autocomplete' => 'off', 'value' => $team->data()->name),
'label_attr' => array('class' => 'label')
))
->add('players', CheckboxType::class, [
'constraints' => array(new Assert\NotBlank()),
'label' => $player->username,
'attr' => array('class' => 'input-field', 'value' => $player->username),
'label_attr' => array('class' => 'label')
])
->add('submit', SubmitType::class, [
'label' => 'Edit',
'attr' => array('class' => 'submit'),
]);
$user = new User();
$user->getList();
// then add your "dynamic" fields
foreach($user->data() as $player) {
$formBuilder->add('players', CheckboxType::class, [
'constraints' => array(new Assert\NotBlank()),
'label' => $player->username,
'attr' => array('class' => 'input-field', 'value' => $player->username),
'label_attr' => array('class' => 'label')
]);
}
// then generate your form
$form = $formBuilder->getForm();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/43586972",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Facebook messenger webview not allow to access camera and audio I am developing a messenger chat bot, user get a doctor consultation url via bot.
Here is the payload I have use
"message": {
"attachment": {
"type": "template",
"payload": {
"template_type": "generic",
"elements": [
{
"title": "Dr.ABC has initiaed the call. Click on the Call below to Join.",
"subtitle": "NOTE: This link will expire in 30 minutes.",
"image_url": "https://doctorconsult.com/images/doc.jpg",
"buttons": [
{
"type": "web_url",
"title": "Call",
"url": "https://doctorconsult.com/patientconversation/665161e3-0f50-4930-aefb-404d5c3f584f",
"webview_height_ratio": "full",
"messenger_extensions": true,
"webview_share_button": "HIDE"
}
]
}
]
}
}
}
this send the web_url for doctor consultation URL ( that need access camera and audio ) when we open up URL in a browser this works, but when I open url using bot button click, it doesn't not allow camera and audio. How do we allow to access camera and audio to "https://doctorconsult.com/" in messenger web view ?
I am getting permission issue when its loading inside messenger web view when accessing media
navigator.mediaDevices.getUserMedia(this.videoConstraints).then(stream => {
this.localStream = stream;
this.localVideoPlayer.srcObject = stream;
this.localMediaReady = true;
this.socketService.emitCallingToPatient({
customerCode: this.conversation.customerCode,
currentConversationCallId: this.currentConversationCallId
});
});
A: That's the expected behavior due to limitations applied to webviews loaded via the in-app-browser/Messenger/Facebook app.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/59951751",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: jquery refactor: traversing Here is some awesome code I'd like to make better.
select: function(event, ui)
{
jQuery(this).siblings('div.hidden_fields').children('.poly_id').val(ui.item.user)
}
It is part of a select in jquery UI autocomplete.
A: You could try this
jQuery('div.hidden_fields .poly_id',jQuery(this).parent()).val(...);
Remember you can always provide a context to a jQuery Selector
jQuery("someselector", context)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/10463771",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: MathGL libmgl.so.7.2.0 not found I have downloaded and compiled MathGL following the instructions on sourceforge without any errors occuring.
When I ran my first test-program:
(The <> brackets in line 1 seem so delete it but they are there in the code)
#include mgl2/mgl.h
int main(){
mglGraph gr;
gr.FPlot("sin(pi*x)");
gr.WriteFrame("test.png");
}
the compilation with g++ -lmgl went fine.
When trying to run the programm i get:
./a.out: error while loading shared libraries: libmgl.so.7.2.0: cannot open shared object file: No such file or directory
I triple checked to be sure and libmgl.so.7.2.0 is definetely in /usr/local/lib/.
I tried telling g++ this via the -L option but that didn't work either.
Any help would be greatly appreciated
A: g++ -lmgl -lpng /shitfile.cpp -o /shitfile
care friend
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/24905495",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How To Append String To Dictionary in Python within Forloop i need to append a value of string to a specific key in dictionary in python within forloop, and if the data in forloop is empty then give the value of empty string which i'm not able to get it right, here is some of the code,
top100 = {}
for product in product_list:
title = product.xpath('a[@class="someClass"]/text()') # LIST of 100
price = product.xpath('div[@class="someClass"]/text()') # LIST of 100
# the value in the title is list of 100 title
# more like ['title1', 'title2', ...] and so the price [100, 230, ...]
# how to append each pairs of title and price so i have list of dictionary
top100['title'].append(title)
top100['price'].append(price)
print( top100)
output:
KeyError: 'title'
but i need something more like:
top100 = [{'title': 'title1', 'price': 'price1'},
{'title': 'title2', 'price': 'price2'}
]
A: The top 100 variable should be a list, then append a dictionary
top100 = []
for product in product_list:
title = product.xpath('a[@class="someClass"]/text()') # LIST of 100
price = product.xpath('div[@class="someClass"]/text()') # LIST of 100
top100.append({'title':title,'price':price})
print( top100)
A: You need to make top100 a list with many nested dictionaries, with the following code:
top100 = []
for product in product_list:
title = product.xpath('a[@class="someClass"]/text()') # LIST of 100
price = product.xpath('div[@class="someClass"]/text()') # LIST of 100
top100.append({'title':title,'price':price})
A: Here for the another version of result
top100 = {'title':[],'price':[]}
for product in product_list:
title = product.xpath('a[@class="someClass"]/text()') # LIST of 100
price = product.xpath('div[@class="someClass"]/text()') # LIST of 100
top100['title'].append(title)
top100['price'].append(price)
print( top100)
This should output
{'title':[..., ..., ... ],'price':[..., ..., ...]}
A: thanks for the answer i was able to find my own solution,
top100 = []
for product in product_list:
titles = product.xpath('a[@class="someLink"]/text()')
prices = product.xpath('div[@class="somePrice"]/text()')
for title, price, in zip(titles, prices):
top100.append({'title':title, 'price':price})
output:
top100 = [{'title': 'title1', 'price': '100'},
{'title': 'title2', 'price': '200'}]
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/63108853",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: jQuery getting all input elements of type text where the id ends in "Source" I am trying to get all text boxes that have an id that ends in a particular string.
So far I have tried
$("input[id$='Source']").each(function() {
$("input[type=text][id$='Source']").each(function() {
and also
$("input[type=text] , [id$='Source']").each(function() {
none of these seem to work, could some one maybe point me in the right direction.
I have tried clearing my web browsers cache just to make sure it was not caching any old code.
A: This works:
<input type="text" id="mysource">
<input type="text" id="yoursource">
<input type="text" id="nope">
js (the context 'this' inside of the each function will be the matched elements):
$("input[type='text'][id$='source']").each(function() {
console.log(this);
});
console result:
<input type="text" id="mysource">
<input type="text" id="yoursource">
A: Clean up your quotes and you should be OK -
$('input[id$="Source"]').each(function() {
$('input[type="text"][id$="Source"]').each(function() {
Here is an example fiddle - http://jsfiddle.net/C5v4H/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/23020999",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Function overloading by function pointer there is a question about overloading functions. Look at this code:
#include<iostream>
void fv(int){}
void fc(const int){}
void fvr(int&){}
void fcr(const int&){}
void fm(void(*fun)(const int))
{
std::cout << "Constant called" << std::endl;
}
//void fm(void(*fun)(int))
//{
// std::cout << "non Constant called" << std::endl;
//}
void fm(void(*fun)(const int&))
{
std::cout << "Constant ref called" << std::endl;
}
void fm(void(*fun)(int&))
{
std::cout << "non Constant ref called" << std::endl;
}
int main()
{
fm(&fc);
fm(&fv);
fm(&fvr);
fm(&fcr);
return 0;
}
if you uncomment void fm(void(*fun)(int)) function you find that compiler can't statically overload function by pointer on function that accept parameter by value and pointer on function that accept const value. Also, if you uncomment void(*fun)(const int) and comment void(*fun)(const int) then all compiles sucessfully. But, if we using references it compiles OK. Don't get why, could you explain me please? Does this mean that pointers to function that accept parameter by value and by const value is same types?
UPD:
Top-level const doesn't influence a function signature
There is a good explanation why top-level const should be removed.
A: Yes, top-level const will be just dropped. Error from gcc
redefinition of ‘void fm(void (*)(int))’
As you can see const is dropped.
Quote from N3376 8.3.5/5
After producing the list of parameter types, any top-level
cv-qualifiers modifying a parameter type are deleted when forming the
function type.
A: Yes you cannot overload functions based on the const ness of a non pointer / non-reference argument, see:
Functions with const arguments and Overloading
Which in turn implies that pointers to function that accept parameter by value and const value are same type.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/29140223",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: Staf Copy on same Machine : Error registering with STAF, RC: 10 I want to copy a file from one directory to another directory. For doing this I am using staf which gets invoked in one php script, but getting below error, even if I run staf command like below
[root@balveer ConfigManagement_phps]# /usr/local/staf/bin/staf local FS COPY FILE /prd/mdp/Config_Manager/Configuration_files/configfiles/PCEF1/pcef.conf tomachine 172.19.13.53 todirectory /prd/mdp/Config_Manager/Configuration_files/updatedconfigs/
Error registering with STAF, RC: 10
At the time of starting staf, it says staf initialized
Ping test also gives same error
[root@balveer bin]# STAF LOCAL PING PING
Error registering with STAF, RC: 10
I am running staf version 3.4.11 on RHEL 6.3
A: I did following :
$ echo "/usr/local/staf/lib" > /etc/ld.so.conf.d/staf.conf
$ ldconfig
Basically, adding STAF library path in /etc/ld.so.conf.d/staf.conf
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/24160183",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: flex textflow dyniamic height In my flex application I have scenerio like this:
parent to child
Vbox->Canvas->Sprite->Textflow
In this scenerio now I need to have dynamic height of the textflow & its parents. Here the root parent is the itemrenderer of the datagrid I have.
I need the heights of rows to be adjust according the content in it.
Right now I am importing the xml to textflow, then getting the number of lines, text height. Then removing the textflow & adding it again with the measured height according to the number of lines & text height.
How can I achieve it without removing & adding it again, coz it is taking much time in updating?
Thanks in advance.
A: Right might be a little late to answer this but someone else may benefit.
On the canvas or display object housing the TextFlow and sprite add a creationComplete functon.
I don't know if this step is necessary, but it works for me. Add a label with the text thats going to go into TextFlow (with the same font and fontSize), add a creation complete listener to that as well.
Get the height and width from the newly created label e.target.width e.target.height (in the function listening to the creation of label). Set the displayObjects (in the above case Canvas) height and width to these values, then proceed to add the sprite and textflow.
Note: this was a lazy way for me, label uses measureText which would be a more efficent way of doing this.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/1037447",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to open multiple nodejs command prompts in windows? For a class, I am using a node js command prompt. In windows only when i search node js command prompt am I able to open the command prompt. This command prompt is basically the regular windows command prompt with edhanced features of node. For example I use the node js command prompt to do things like npm install, npm run serve, etc. I know that to open another window of regular windows command prompt, i can run start cmd.exe but how so can I do with my node js command prompt?
A: On my machine if I run "Node Command Prompt" a 2nd time, it opens a 2nd window.
If you want to do the same thing, the shortcut that Node installs just runs:
C:\Windows\System32\cmd.exe /k "C:\Program Files\nodejs\nodevars.bat"
so you should be able to run that, assuming your node install location is Program Files\nodejs.
A: Open your environment variables config, and add these 2 directories to Path variable.
C:\Program Files\nodejs\
C:\Users\your_user_name\AppData\Roaming\npm
And then every time you open a regular cmd window, the node.js commands will be available to you.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/36538473",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Hide installed app in android i want to hide the installed app by another app in android application, lets say user has installed 3rd party app called Skype, Watsapp, facebook etc...
is there a way we can hide and show them upon click of a button from another app?. i tried below code. No luck, nothing happened to my launcher
PackageManager packageManager = context.getPackageManager();
ComponentName componentName = new ComponentName(context,
LauncherActivity.class);
packageManager.setComponentEnabledSetting(componentName, PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP);
But here i was not getting how to hide a particular application?, i also followed these SO link
but i could not get to know how to hide a perticular application.
A: To hide/unhide an app, your app need to be the DevicePolicyManager. You can find more information about the device policy manager at http://developer.android.com/reference/android/app/admin/DevicePolicyManager.html and you may need to use https://developer.android.com/reference/android/app/admin/DevicePolicyManager.html#setApplicationHidden(android.content.ComponentName,%20java.lang.String,%20boolean)
DevicePolicyManager dpm =
(DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE);
ComponentName ownerComponent = new ComponentName(context, DeviceAdminReceiverImpl.class);
boolean newHiddenValue = true;
dpm.setApplicationHidden(ownerComponent, packageName, newHiddenValue);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/22754398",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Flutter/Dart security scans I'm looking for software/method to perform a security scan (looking for security vulnerabilities) on my apps being developed in Flutter. I'm having troubles find one that supports Dart. Has anyone been doing security scans and have any recommendations for what to use? Thanks.
A: There's no great security scanning support at the moment although there are some discussions. The first step would be for Google to start to track Dart vulnerabilities in their existing Open Source Vulnerability (OSV) database, you could watch or get involved here: https://github.com/google/osv/issues/62
A: I would suggest the open source framework called mobsf. It's great at scanning a mobile app. I have been using it ever since and I could start patching up my security vulnerability right away.
link : https://github.com/MobSF/Mobile-Security-Framework-MobSF
A: Mobile-Security-Framework-MobSF Great Tools For Doing Mobile Applications Security Test
A: I appreciate this might be a necropost but for anyone else who comes across this, you could look into Black Duck (https://www.blackducksoftware.com/) for licensing risks and Checkmarx CxSAST (https://checkmarx.com/) for security issues. Both support Dart/Flutter code (we've integrated into our ADO pipelines).
These would be for organisations rather than individuals though.
For private projects, I guess you could look into this integration into SonarQube?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/59953485",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
}
|
Q: daterangepicker Month and year hard to view I have the following daterangepicker code. the code is functioning however the Month, Year and toggle buttons are very hard to view. I am using a bootstrap theme that is not working well with this. I have been trying to figure out how to change the CSS to make the month, year and toggle buttons more viewable.
What I am seeing
This is what it should look like
<!-- Include Required Prerequisites -->
<script type="text/javascript" src="//cdn.jsdelivr.net/jquery/1/jquery.min.js"></script>
<script type="text/javascript" src="//cdn.jsdelivr.net/momentjs/latest/moment.min.js"></script>
<!-- Include Date Range Picker -->
<script type="text/javascript" src="//cdn.jsdelivr.net/bootstrap.daterangepicker/2/daterangepicker.js"></script>
<link rel="stylesheet" type="text/css" href="//cdn.jsdelivr.net/bootstrap.daterangepicker/2/daterangepicker.css" />
<form class="" action="{{ url_for('about') }}" name="Item_1" method="POST">
<input style="width: 30%" type="text" name="daterange" value="01/01/2015 01/31/2015" />
<button type="submit" class="btn btn-success">Submit</button>
</form>
<script type="text/javascript">
$('input[name="daterange"]').daterangepicker(
{
locale: {
format: 'MM-DD-YYYY'
},
startDate: '01-01-2017',
endDate: moment()
},
function(start, end, label) {
console.log("A new date range was chosen: " + start.format('MM-DD-YYYY') + ' to ' + end.format('MM-DD-YYYY'));
});
</script>
A: Marking it here as an answer, since the comment worked. The color css attribute controls font-colors, including those for glyphicons. So the fix is to change the corresponding table elements and glyphicons to use color: #000 or color: black.
Adding !important simply ensures no other CSS files change the color (unless they use !important too and have priority, through either more specific selectors, or the same selectors but appearing after this rule - which was apparently not the case here).
.calendar-table, .glyphicon-calendar {color: #000 !important;}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/46739033",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Declaring arrow functions as variables In a previous project using webpack and babel writing es2015 I was able to declare an arrow function with a name like this:
x = () => console.log("test");
Using a real function it would look like this:
fetch = () => {
fetch(`https://www.data.com`)
.then(response => response.json() {
console.log(response);
})}
However when trying to use this code in a browserify and gulp configuration I get the error
Unexpected token, expected ,
Can you tell me why this code only works when I use webpack?
A: You have a syntax error in your code. response => response.json() { } is invalid JS.
To log the response:
fetch('https://www.data.com')
.then(response => console.log(response))
To convert the response to JSON before logging it:
fetch('https://www.data.com')
.then(response => response.json())
.then(json => console.log(json))
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/43344863",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to create a list from existing list in python I am having a list in below format. How can i create another list from the existing one with just selected elements.
[{'UserDiscount': 0.0, 'CostTotalInvEOPAmount': 940.0, 'WeekEndingData': u'2016-10-08', 'WeeksOnHand': 0.0, 'UnitTotalInvEOPQuantity': 250.0, 'WeeksOfSales': 0.0, 'UnitCostAmount': 3.76, 'Week': u'2016 Wk 36', 'CostReceiptAmount': 940.0, 'UnitSalesQuantity': 0.0, 'UnitReceiptQuantity': 250.0, 'Demand': 0.0, 'InventoryBOP': 0.0, 'PEMDiscount': 0.0, 'ElasticLift': 0.0, 'StoreCount': 0, 'PriceStatus': 4, 'UnitOnOrderQuantity': None, 'ReceiptSizeContributions': [{u'sizeId': u'e1656ac7-1cc1-40ce-b485-989bba9d758d', u'contribution': 1.0}], 'CostSalesAmount': 0.0, 'LifeCycleProperties': {u'IsAtRegularPrice': False, u'IsAtMarkdown': False, u'IsFinished': False, u'IsPreSeason': True}, 'MardownDiscount': 0.0, 'RecommendedReceipt': 250.0, 'RecommendedReceiptSizeContributions': [{u'sizeId': u'e1656ac7-1cc1-40ce-b485-989bba9d758d', u'contribution': 1.0}], 'UnitTotalInvBOPQuantity': 0.0, 'CostOnOrderAmount': None, 'InventoryEOP': 250.0, 'CostTotalInvBOPAmount': 0.0, 'Receipt': 250.0, 'Sales': 0.0, 'LostSales': 0.0, 'TotalDiscount': 0.0, 'RetailSalesAmount': 0.0},
{'UserDiscount': 0.0, 'CostTotalInvEOPAmount': 940.0, 'WeekEndingData': u'2016-10-15', 'WeeksOnHand': 0.0, 'UnitTotalInvEOPQuantity': 250.0, 'WeeksOfSales': 15.784951285314385, 'UnitCostAmount': 3.76, 'Week': u'2016 Wk 37', 'CostReceiptAmount': 0.0, 'UnitSalesQuantity': 0.0, 'UnitReceiptQuantity': 0.0, 'Demand': 0.0, 'InventoryBOP': 250.0, 'PEMDiscount': 0.0, 'ElasticLift': 0.0, 'StoreCount': 0, 'PriceStatus': 4, 'UnitOnOrderQuantity': None, 'ReceiptSizeContributions': [], 'CostSalesAmount': 0.0, 'LifeCycleProperties': {u'IsAtRegularPrice': False, u'IsAtMarkdown': False, u'IsFinished': False, u'IsPreSeason': True}, 'MardownDiscount': 0.0, 'RecommendedReceipt': 0.0, 'RecommendedReceiptSizeContributions': [], 'UnitTotalInvBOPQuantity': 250.0, 'CostOnOrderAmount': None, 'InventoryEOP': 250.0, 'CostTotalInvBOPAmount': 940.0, 'Receipt': 0.0, 'Sales': 0.0, 'LostSales': 0.0, 'TotalDiscount': 0.0, 'RetailSalesAmount': 0.0}]
My new list will having below elements.
[{'UserDiscount': 0.0, 'CostTotalInvEOPAmount': 940.0, 'WeekEndingData': u'2016-10-08', 'WeeksOnHand': 0.0, 'UnitTotalInvEOPQuantity': 250.0, 'WeeksOfSales': 0.0, 'UnitCostAmount': 3.76, 'Week': u'2016 Wk 36', 'CostReceiptAmount': 940.0, 'UnitSalesQuantity': 0.0, 'UnitReceiptQuantity': 250.0, 'Demand': 0.0, 'InventoryBOP': 0.0, 'PEMDiscount': 0.0, 'ElasticLift': 0.0, 'StoreCount': 0, 'PriceStatus': 4, 'UnitOnOrderQuantity': None, 'CostSalesAmount': 0.0, 'RecommendedReceipt': 250.0, 'RetailSalesAmount': 0.0},
{'UserDiscount': 0.0, 'CostTotalInvEOPAmount': 940.0, 'WeekEndingData': u'2016-10-15', 'WeeksOnHand': 0.0, 'UnitTotalInvEOPQuantity': 250.0, 'WeeksOfSales': 15.784951285314385, 'UnitCostAmount': 3.76, 'Week': u'2016 Wk 37', 'CostReceiptAmount': 0.0, 'UnitSalesQuantity': 0.0, 'UnitReceiptQuantity': 0.0, 'Demand': 0.0, 'InventoryBOP': 250.0, 'PEMDiscount': 0.0, 'ElasticLift': 0.0, 'StoreCount': 0, 'PriceStatus': 4, 'UnitOnOrderQuantity': None, 'CostSalesAmount': 0.0, 'RecommendedReceipt': 0.0, 'RetailSalesAmount': 0.0}]
A: You have a list with two dictionaries. To filter the dictionaries you can try
keep=[key1,key2] #keys you wanna keep
newList = []
for item in mylist:
d = dict((key,value) for key, value in item.iteritems() if key in keep)
newlist.append(d)
del mylist
Also using funcy you can do a
import funcy
mydict={1:1,2:2,3:3}
keep=[1,2]
funcy.project(mydict,keep)
=> {1: 1, 2: 2}
which is much prettier imho.
A: You could use the list comprehension https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions
[l for l in your_list if l['UserDiscount'] >= 1 ]
[{'UserDiscount': l['UserDiscount'],'CostTotalInvEOPAmount': l['CostTotalInvEOPAmount']} for l in your_list ]
Using this way you can filter the elements in your list and change the structure of your dicts in the list
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/41012902",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: PHP Select random second value I have a file called file.txt and inside I have this text:
Text 1
Vivamus arcu neque, ullamcorper vel eleifend id, euismod viverra nisi.
Text 2
Cras posuere neque vitae fringilla lobortis.
Text 2
Phasellus eu sapien sit amet diam eleifend ultricies a vitae tellus.
Text 3
Nulla at ipsum et quam euismod porttitor sit amet sed odio.
I select from this file 'Text 2' line and description under that line.
I want to select a random 'Text 2' line and its description not all of them. I tried to break that but it shows me only the first value of course and I tried to shuffle %trimmed but it didn't worked as I expected.
$trimmed = file('file.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$value = 2;
foreach ($trimmed as $line) {
if ($line == "Text $value") {
echo $line."<br>";
echo current($trimmed);
}
}
Thanks
A: Try this, it might be bulky :
<?php
function get_random_line($number, $file='file.txt'){
$trimmed = file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$string = "Text $number";
$array = array();
foreach ($trimmed as $key => $line) {
if($key % 2 == 0){
$arr_key = $line;
if(!array_key_exists($arr_key,$array)){
$array[$arr_key]['total'] = 0;
}
}else{
$array[$arr_key]['total']++;
$array[$arr_key]['rows'][] = $line;
}
}
if(key_exists($string,$array)){
$key = array_rand($array[$string]['rows'],1);
return $array[$string]['rows'][$key];
}else
{
return 'Provide a Valid Key';
}
}
echo '<pre>';
print_r(get_random_line(3,'file.txt')); // Get Random Lines based on Label Value
echo '</pre>';
?>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/18188684",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Long waiting time between PHP and Oracle OCI I installed XAMPP on Windows server. There are 2 application on my server:
First Application: PHP and MySQL application. This application runs quickly without and waiting time between links/pages.
Second Appilcation: PHP and Oracle application. I use “Oracle Instant Client (OCI) for Windows (32 bit)” to connect Oracle Server (on another machine). I have 8 tables with max 1000 row-data on each table. My queries are very simple. Everyting is working correctly when querying my Oracle database.
But, sometimes I’m waiting more than 20 seconds between pages/links. The is too much time to recieve page. This mostly occurs when entering the site for the first time. Additionaly, it occurs when trying to click on another page or link in application, after waiting 5-10 minutes on a page.
How can I reduce or terminate this delay when connecting Oracle database using OCI?
A: How are you connecting? If you are using oci_connect, then that's probably a large part of the problem - switch to oci_pconnect.
Failing that, do make sure that DNS A and PTR records are available for both ends (or make sure you're only using ip addresses rather than names to connect).
C.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/3203372",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Swift 2.2 - uploadTaskWithRequest - How can I upload a text file from my app to my server I'm really struggling to upload a text file from my apps documents directory to my php script. All I want to do is upload a text file from the app onto my server.
The Apple documentation makes it sound so simple but its just not in depth enough and I can't get it working so I'm hoping someone may be able to help.
Filtering out some of the classes and functions here is the main part of what I have in Swift 2.2:
lazy var config: NSURLSesionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration()
lazy var session: NSURLSession = NSURLSession(configuration: self.config, delgate: self, delegateQueue: NSOperationQueue.mainQueue())
let phpURL = "https://test-server.test/upload.php?"
let uploadStringURL: NSURL = NSURL(string: phpURL)!
let uploadRequest = NSMutableURLRequest(URL: uploadStringURL)
let fileManager = NSFileManager.defaultManager()
let docs = fileManager.URLsForDirectory(.DocumentDirectory, inDomains: .userDomainMask).first
let fullFilePath = docs!/URLByAppendingPathComponent("upload.dat")
uploadRequest.HTTPMethod = "POST"
let uploadTask = session.uploadTaskWithRequest(uploadRequest, fromFile: fullFilePath, completionHandler: {(let data, let response, let error) in
})
uploadTask.resume()
The uploadTask should be pushing the file to the server and it gets a response 200 showing that it was successful.
Here is the PHP part which I think is where the problem may lie:
<?php
$target_dir = "/var/www/html/test-files/uploads";
$target_dir = $target_dir . "/" . basename($_FILES["file"]["name"]);
echo '{"target":'.$target_dir.'},';
echo '{"base":'.basename($_FILES["file"]["name"]).'}';
if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_dir)) {
echo json_encode([
"Message" => "The file ". basename( $_FILES["file"]["name"]). " has been uploaded.",
"Status" => "OK"
]);
}
else {
echo json_encode([
"Message" => "Sorry, there was an error uploading your file.",
"Status" => "Error"
]);
}
?>
I don't know too much about PHP but the $_FILES variable is blank.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/37812127",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Is it possible to use .NET 4.6.1 for Xamarin on Mac? I want to use .NET PCL library from a NuGet that target .Net 4.6.1 in Xamarin PLC project.
I can add it to the project, it will build fine. But, I cannot reference it in the project itself, it just doesn't allow because of .NET versions differences. The maximum version that I can set for my PCL projects is 4.5.
I can select 4.5.1 for example but it will jump back to 4.5 due to missing profiles for that version.
I was not able to find those profiles or update .NET Framework.
If I'm doing something completely dumb, please, tell me :)
A: If you are using visual studio 2017, you need to go to the visual studio installer, and select a few more checkboxes:
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/44944841",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to set up IRIS database with Quarkus I'm trying to use Intersystems IRIS Database with
Quarkus, but I'm getting problems making it work
does anyone knows how to set up the Intersystems IRIS Database
on Quarkus ?
I did that on my pom.xml and also I added the jar
hibernate-iris-1.0.0.jar and intersystems-jdbc-3.2.0.jar but it's not working
<dependency>
<groupId>com.intersystems</groupId>
<artifactId>intersystems-jdbc</artifactId>
<version>3.2.0</version>
<scope>system</scope>
<systemPath>${project.basedir}/src/main/resources/intersystems-jdbc-3.2.0.jar</systemPath>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-iris</artifactId>
<version>1.0.0</version>
<scope>system</scope>
<systemPath>${project.basedir}/src/main/resources/hibernate-iris-1.0.0.jar</systemPath>
</dependency>
This is my application.properties
quarkus:
datasource:
db-kind: other
username: _system
password: *****
jdbc:
url: jdbc:IRIS://localhost:1972/USER
driver: com.intersystems.jdbc.IRISDriver
hibernate-orm:
dialect: org.hibernate.dialect.InterSystemsIRISDialect
jdbc:
timezone: UTC
A: I found the solution, to set up Intersystems IRIS on Quarkus you need to add manually the jar file, and also you need to set up the pom.xml also some setup from Intersystems was made as a java class. you can see the solution looking at my project on GitHub
this is the link: https://github.com/JoseAdemar/quarkus-project-with-intersystems-ris-database
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/71027568",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Unknown provider error when trying to inject a service from another module I've seen several posts on unknown provider errors but none of them have addressed my particular problem. I'm getting the following error:
Error: [$injector:unpr] Unknown provider: userAccountResourceProvider <- userAccountResource <- AdminUserAccountsCtrl
Here is my index.html:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" ng-app="rpms">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>
<!-- Library Scripts -->
<script src="Scripts/angular.js"></script>
<script src="Scripts/angular-resource.js"></script>
<script src="Scripts/angular-mocks.js"></script>
<!-- Application Script -->
<script src="App/app.js"></script>
<!-- Services -->
<script src="Common/services/common.services.js"></script>
<script src="Common/services/userAccountResource.js"></script>
<script src="Common/services/userAccountResourceMock.js"></script>
<!-- Admin Controller Scripts -->
<script src="App/admin/adminUserAccountsCtrl.js"></script>
</head>
<body onload="doOnLoad()" class="administration-page user-account-page">
<div id="main" ng-controller="AdminUserAccountsCtrl as vm">
<div class="main-content with-sidebar">
<h2>User Accounts</h2>
<div id="managed-user-accounts" class="module">
<table>
<thead>
<tr>
<th>Username</th>
<th>Full Name</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="account in vm.userAccounts">
<td>{{ account.username }}</td>
<td>{{ account.firstName}} {{ account.lastName }}</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</body>
</html>
Here is my app.js;
(function() {
"use strict";
var app = angular.module("rpms",
["common.services"]);
}());
Here is my second module - common.services.js:
(function() {
"use strict";
angular
.module("common.services",
["ngResource"]);
}());
And here is my userAccountResource service declaration in the common.services module:
(function() {
"use strict";
angular
.module("common.services")
.factory("userAccountResource"
["$resource",
userAccountResource]);
function userAccountResource($resource) {
return $resource("/api/accounts/:accountId");
}
}());
Finally, here is my AdminUserAccountsCtrl controller declaration - using this is causing the error:
(function() {
"use strict";
angular
.module("rpms")
.controller("AdminUserAccountsCtrl",
["userAccountResource",
adminUserAccountsCtrl]);
function adminUserAccountsCtrl(userAccountResource) {
var vm = this;
userAccountResource.query(function(data) {
vm.userAccounts = data;
});
}
}());
I know that the userAccountResource is created under the common.services module but the common.services module is included as a dependency of the rpms module. Why is it considered an unknown provider?
Thanks.
A: Try to add , after "userAccountResource" like this
.factory("userAccountResource", //, here was missing
["$resource",
userAccountResource]);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/31391537",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Find Repeated Digits In List with Java I am working on Pi Finder app.I know there is a lot of apps about it but i want to do it myself.I did it with Leibniz formula but it is working very slow because of repeated numbers.I am using lists for storage.Can you help me about find repeated numbers in lists or arrays?
Example
{1,2,5,4,7,6,4,7,6,4,7,....}
I need to find 4,7,6
A: You can find the duplicate elements by using a Set as the accumlator and then utilise Collections.frequency to check if a given number occurs more than once within the List<Integer> like this:
List<Integer> elements = new ArrayList<>(Arrays.asList(1,2,5,4,7,6,4,7,6,4,7));
Set<Integer> accumulator = new LinkedHashSet<>();
for (Integer number : elements) {
if(Collections.frequency(elements, number) > 1)
accumulator.add(number);
}
now the accumulator contains:
[4, 7, 6]
LinkedHashSet is utilised here to maintain insertion order. if that is not required then you can use a HashSet instead.
or a better performant solution as suggested by JB Nizet:
List<Integer> elements = new ArrayList<>(Arrays.asList(1,2,5,4,7,6,4,7,6,4,7));
Set<Integer> tempAccumulator = new LinkedHashSet<>();
Set<Integer> resultSet = new LinkedHashSet<>();
for (Integer number : elements) {
if(!tempAccumulator.add(number))
resultSet.add(number);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/48248401",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Android Studio emulator (AVD) on Mac OSX : AVD icon quickly appears and immediately disappears I am trying to launch an AVD in Android Studio on Mac OSX. I create it and then I launch it.
The problem is that the AVD icon quickly appears in the dock and immediately disappears.
Note that the default emulators present in Android Studio work properly.
Do you know how to solve this problem?
Thanks !
A: Maybe you don't create AVD correctly. Try that: Nexus 5x with Marshmallow x86_64 OS. I'm using that emulator and works perfectly.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/43910896",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: ButterKnife OnClick listeners runs shortly after view created in custom view I have a strange problem with ButterKnife's OnClick listeners. When my custom view opened below OnClick listeners are running automatically when view opened. Below code helps you to understand what my problem is.
public class UserMenuFragment extends LinearLayout {
@BindView(R.id.buttonBlockUser)
Button buttonBlockUser;
@BindView(R.id.buttonMuteUser)
Button buttonMuteUser;
@BindView(R.id.buttonHideYourPreset)
Button buttonHideYourPreset;
@BindView(R.id.buttonTurnOnNotifs)
Button buttonTurnOnNotifs;
public UserMenuFragment(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
initView();
}
public UserMenuFragment(Context context, AttributeSet attrs) {
super(context, attrs);
initView();
}
public UserMenuFragment(Context context) {
super(context);
initView();
}
private void initView() {
View view = inflate(getContext(), R.layout.fragment_user_menu, null);
addView(view);
bindViewWithButterKnife(this, view);
onButtonReportUserClicked();
onButtonBlockUserClicked();
onButtonMuteUserClicked();
onButtonHideYourPresetClicked();
onButtonCopyProfileLinkClicked();
onButtonTurnOnNotifsClicked();
}
@OnClick(R.id.buttonReportUser)
void onButtonReportUserClicked() {
Toast.makeText(getContext(), "User Reported!", Toast.LENGTH_SHORT).show();
}
@OnClick(R.id.buttonBlockUser)
void onButtonBlockUserClicked() {
Toast.makeText(getContext(), "User Blocked!", Toast.LENGTH_SHORT).show();
changeButtonText(buttonBlockUser, R.string.unblock_user_text);
}
@OnClick(R.id.buttonMuteUser)
void onButtonMuteUserClicked() {
Toast.makeText(getContext(), "User Muted!", Toast.LENGTH_SHORT).show();
changeButtonText(buttonMuteUser, R.string.unmute_user_text);
}
@OnClick(R.id.buttonHideYourPreset)
void onButtonHideYourPresetClicked() {
Toast.makeText(getContext(), "User preset hided!", Toast.LENGTH_SHORT).show();
buttonHideYourPreset.setText(getContext().getString(R.string.show_your_preset_text));
changeButtonText(buttonHideYourPreset, R.string.show_your_preset_text);
}
@OnClick(R.id.buttonCopyProfileLink)
void onButtonCopyProfileLinkClicked() {
Toast.makeText(getContext(), "User's profile link copied!", Toast.LENGTH_SHORT).show();
}
@OnClick(R.id.buttonTurnOnNotifs)
void onButtonTurnOnNotifsClicked() {
Toast.makeText(getContext(), "User's notification is off now!!", Toast.LENGTH_SHORT).show();
changeButtonText(buttonTurnOnNotifs, R.string.turn_off_notification_text);
}
private void changeButtonText(Button button, int newText) {
button.setText(getContext().getString(newText));
}
private void bindViewWithButterKnife(UserMenuFragment whichFragment, View view) {
ButterKnife.bind(whichFragment, view);
}
}
IMO this is happening because I called the OnClick listeners in my constructor so while view creating(after created) naturally they are running. Could somebody help me to understand where is the exact problem is and how to fix it?
My ButterKnife versions:
implementation 'com.jakewharton:butterknife:8.8.1'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'
A: Change initView() to :
private void initView() {
View view = inflate(getContext(), R.layout.fragment_user_menu, null);
addView(view);
bindViewWithButterKnife(this, view);
}
I don't think you need to call the methods, the annotations already do the job to set the listeners, right ?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/52793104",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Paste Values into new worksheet for all Open Worksheets including pictures I am trying to create a renamed copy of all active workbooks (even non macro-enabled ones) without formulas, possibly by pasting values but without modifying images. I am working with Excel 2007.
My process would ideally be to:
1) Create a do while there are xls files loop that converts all xls files to xlsm. One possible addition would be an array to store A)the worksheet name(s) B)Its tabs name and their status
2) Run a for each or for loop that automatically pastes values for all active worksheets include those with graphs or other images into a new document that has the same name with all small addition at the end.
3) Convert my newly-named files containing values only into xls.
One issue I am running into when I try to do this has to do with links. The initial worksheets have formulas with links that do not automatically update. When I do this, the formulas in the original worksheet with link references tend to get corrupted.
Here is a general macro I found for pasting values:
Sub test()
Dim MyNames As Range, MyNewSheet As Range
Set MyNames = Range("R5").CurrentRegion ' load contigeous range into variable
For Each MyNewSheet In MyNames.Cells ' loop through cell children of range variable
Sheets.Add.Name = MyNewSheet.Value
Next MyNewSheet
MyNames.Worksheet.Select ' move selection to original sheet
End Sub
A: I think this is what you're asking for:
Sub test()
Dim wb As Workbook
Dim ws As Worksheet
Dim counter As Integer
Dim filePath As String
Set wb = ActiveWorkbook
countet = 1
filePath = "c:/" 'Enter your destination folder here
For Each ws In wb.Sheets
Sheets("Sheet1").Copy
With ActiveSheet.UsedRange
.Value = .Value
End With
ActiveWorkbook.SaveAs filePath & counter & ".xlsx", FileFormat:=51
counter = counter + 1
Next ws
End Sub
This is mostly taken from here.
The counter is a bit of a hack to make sure that the files aren't all being saved as the same name and overwriting each other. Maybe there's a more appropriate way that you can get around this.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/38470684",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Converting DirectX SDK code to new Windows 8.1 SDK Code I'm currently creating a Video Game + Engine. I found some really amazing tutorials on DirectX 11 programming at RasterTek. They unfortunately use the depreciated DirectX SDK, and I am using VS 2013 with the new DirectX SDK included in the Windows SDK.
I am converting the code to use the Windows SDK, but I've run into some problems on tutorial 4 (yes I will be converting all 49 tutorials, and there will probably be more issues)
From Working with D3DXMath, I am told that D3DXVECTOR3 should be converted to XMFLOAT3.
I am then trying to use these XMFLOAT3 in D3DXVec3TransformCoord, which has been converted to XMVector3TransformCoord.
Example:
XMFLOAT3 up, position, lookAt;
// Setup the vector that points upwards.
up.x = 0.0f
up.y = 1.0f
up.z = 0.0f
// Setup the position of the camera in the world.
position.x = m_positionX;
position.y = m_positionY;
position.z = m_positionZ;
// Setup where the camera is looking by default.
lookAt.x = 0.0f;
lookAt.y = 0.0f;
lookAt.z = 1.0f;
// Transform the lookAt and up vector by the rotation matrix so the view is correctly rotated at the origin.
XMVector3TransformCoord(lookAt, rotationMatrix);
XMVector3TransformCoord(up, rotationMatrix);
I get an error:
IntelliSense: no suitable user-defined conversion from
"DirectX::XMFLOAT3" to "DirectX::XMVECTOR" exists
I have found that I can TypeCast lookAt and up using XMLoadFloat3:
XMVector3TransformCoord(XMLoadFloat3(&lookAt), rotationMatrix);
XMVector3TransformCoord(XMLoadFloat3(&up), rotationMatrix);
Should I be doing this at all, and / or is it the best way to do this?
After doing this, I try to:
// Translate the rotated camera position to the location of the viewer.
lookAt = position + lookAt;
and get the error:
IntelliSense: no operator "+" matches these operands
operand types are: DirectX::XMFLOAT3 + DirectX::XMFLOAT3
I was able to use the + operator on D3DXVECTOR3, but now not XMFLOAT3? How do I add these together?
A:
Should I be doing this at all, and / or is it the best way to do this?
Use XMVECTOR instead of XMFLOAT3 since most of the functions in DriectXMath use XMVECTOR. thus you can avoid the boring type cast and make your code clean.
I was able to use the + operator on D3DXVECTOR3, but now not XMFLOAT3?
How do I add these together?
Again, use XMVECTOR instead of XMFLOAT3
XMVECTOR also has some disadvantage(I mean the code seems a little complicated sometimes). with D3DXVECTOR3, you can simply initialize a variable as D3DXVECTOR3 a(x, y, z, w) and get it's component as a.x, a.y, ... but XMVECTOR use a different way.
To initialize an XMVECTOR, use XMVectorSet function.
XMVECTOR lookAt = XMVectorSet(x, y, z, w);
To get component of an XMVECTOR, use the following functions.
*
*XMVectorGetX
*XMVectorGetY
*XMVectorGetZ
*XMVectorGetW
A: 1. Should I?
Should I be doing this at all, and / or is it the best way to do this?
Generally speaking, you use Windows SDK to write your new code, but you don't have to convert any old code (yours or, especially, others). It`s just a waste of time. You can install DirectX SDK to be able to build it.
On the other hand, it is a good opportunity to learn a little more about DrectX and its infrastructure. For example, portng from D3DXMath to DirectXMath (previously XMMath), you will learn pros and cons of SSE-based math libraries, and it is a good place to begin to write your own.
2. How to?
If you really decided to do this hard work, then 90% of info you will find in a good article by Chuck Walbourn - MSFT:
Living without D3DX.
Another 9.9% you will figure out by yourself from documentation, and 0.1% more from looking at DirectXMath source code (it is a header library, all functions inlined and you cann freely learn them).
You will, probably, also interested in another articles by that guy on MSDN.
3. operator+ problem
Instead of single D3DXVECTORn type (where n is a number of components), new math contains two types: XMFLOATn and XMVECTOR. Same for matrices: XMMATRIX and XMFLOATaXb (where a and b is a dimensions of matrix).
*
*XMFLOAT folks are to be used to just store values. It is just a plain floats. No operators defined for them and no functions, except XMLoad*/XMStore* accept them.
*XMVECTOR and XMMATRIX is a work horses: they used in all functions and also have overloaded operators (which is not recommended to use. Use XM* functions instead). They use supersonic speed SSE internals. But.. it is a hard to use it to store values. For example, you will have alignment problems if you make XMVECTOR class member.
*So, basically, you store and moving around your values in XMFLOATs, but before any calculations, you transform them to XMVECTOR and XMMATRIX, using XMLoad* functions (as you've done with XMVector3TransformCoord()), and after calculations, you transform them back to XMFLOATs, using XMStore* functions. Or you can gain a little more profit, by aligning properly your classes and structs, so you can store XMVECTOR and XMMATRIX directly (probably, you will need aligned memory allocator).
Well, now you are ready to go. Happy porting! =)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/18706760",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Only do validation for control if another radion button on the page is selected : Only allowed to alter the regular expression I have an entry form that has regular expressions attached to each of the fields in the form.
Each regular expression is updateable.
I have a field that currently has a regular expression test|tset
which will basicly return true if the field contains one of those words.
Now I should only do this test if a specific radio button on the page is selected.
Please note that i would need to do this in the regular expression.
in logic -
If (CorrectRadioButton is selected)
then the validation should do the test|tset
else do not do validation
My programming language of choice is c# but this question does not require a codebehind solution.
Can anyone please help with this regular expression ?
A: Regex in C# cannot check for external conditions: the result of the match is only dependent on the input string.
If you cannot add any other code and you are only able to change the expressions used then it cannot be done.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/11152733",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Prevent join table being empty Relationships
class Promotion < ActiveRecord::Base
has_many :promotion_sweepstakes,
has_many :sweepstakes,
:through => :promotion_sweepstakes
end
class PromotionSweepstake < ActiveRecord::Base
belongs_to :promotion
belongs_to :sweepstake
end
class Sweepstake < ActiveRecord::Base
# Not relevant in this question, but I included the class
end
So a Promotion has_many Sweepstake through join table PromotionSweepstake. This is a legacy db schema so the naming might seem a bit odd and there are some self.table_name == and foreign_key stuff left out.
The nature of this app demands that at least one entry in the join table is present for a promotionId, because not having a sweepstake would break the app.
First question
How can I guarantee that there is always one entry in PromotionSweepstake for a Promotion? At least one Sweepstake.id has to be included upon creation, and once an entry in the join table is created there has to be a minimum of one for each Promotion/promotion_id.
Second question (other option)
If the previous suggestion would not be possible, which I doubt is true, there's another way the problem can be worked around. There's a sort of "default Sweepstake" with a certain id. If through a form all the sweepstake_ids would be removed (so that all entries for the Promotion in the join table would be deleted), can I create a new entry in PromotionSweepstake?
pseudo_code (sort of)
delete promotion_sweepstake with ids [1, 4, 5] where promotion_id = 1
if promotion with id=1 has no promotion_sweepstakes
add promotion_sweepstake with promotion_id 1 and sweepstake_id 100
end
Thank you for your help.
A: A presence validation should solve the problem in case of creation and modification of Promotions.
class Promotion < ActiveRecord::Base
has_many :promotion_sweepstakes
has_many :sweepstakes,
:through => :promotion_sweepstakes
validates :sweepstakes, :presence => true
end
In order to assure consistency when there's an attempt to delete or update a Sweepstake or a PromotionSweepstake you'd have to write your own validations for those two classes. They would have to check whether previously referenced Promotions are still valid, i.e. still have some Sweepstakes.
A simple solution would take and advantage of validates :sweepstakes, :presence => true in Promotion. After updating referenced PromotionSweepstakes or Sweepstakes in a transaction you would have to call Promotion#valid? on previously referenced Promotions. If they're not valid you roll back the transaction as the modification broke the consistency.
Alternatively you could use before_destroy in both PromotionSweepstake and Sweepstake in order to prevent changes violating your consistency requirements.
class PromotionSweepstake < ActiveRecord::Base
belongs_to :promotion
belongs_to :sweepstake
before_destroy :check_for_promotion_on_destroy
private
def check_for_promotion_on_destroy
raise 'deleting the last sweepstake' if promotion.sweepstakes.count == 1
end
end
class Sweepstake < ActiveRecord::Base
has_many :promotion_sweepstakes
has_many :promotions, :through => :promotion_sweepstakes
before_destroy :check_for_promotions_on_destroy
private
def check_for_promotions_on_destroy
promotions.each do |prom|
raise 'deleting the last sweepstake' if prom.sweepstakes.count == 1
end
end
end
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/9932799",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to get the correct connection string for c# to teradata? I have been trying to establish connection to teradata.
Since there is already a odbc on my computer, for Java the string looks like
String connURL = "jdbc:odbc:DatabaseName" // and it works!
I need to establish the connection in c#.
So I tried
TdConnection cn = new TdConnection ("Data Source = odbc:DatabaseName; User ID = xxx; Password = ooo;")
But it did not accept this string.
What is the correct way to write the Data Source ? What is the jdbc counterpart in c# ?
A: You are using ODBC so you must only specify DSN:
DSN=myDsn;Uid=myUsername;Pwd=;
The jdbc:odbc is just a designation that the java driver uses and is not carried over to ODBC in .NET. I would suggest you use ADO.NET if that is an option.
or this for the TDConnection:
Data Source=myDsn;User Id=uid;Password=pwd;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/21145291",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Django Test - I can't save my object when I use queryset to get it I have an model, let's say something like:
class Invoice(models.Model):
client_name = models.CharField(max_length=100)
And I have a file that looks like:
def foo_1():
for inv in Invoice.objects.all():
inv.client_name = "Joe"
inv.save()
def foo_2(inv):
inv.client_name = "Joe"
inv.save()
My issue occurred when I test it:
class FooCase(TestCase):
def test_foo(self):
inv = Invoice("Jack")
print inv.client_name # output Jack, OK
foo_1()
print inv.client_name # output Jack, KO !
print inv.client_name # output Jack, OK
foo_2(inv)
print inv.client_name # output Joe, OK
I don't understand why there is two differents behaviour :(
I added a modification date to my model, and try to output it in foo_1 before and after the loop for, the save seems to work properly, but it is like the object is different...
I don't know if that can help but I also output vars(invoice) from test_foo and then from foo_1() and finally from foo_2(). The state was the same in test_foo and foo_2() (<django.db.models.base.ModelState object at 0x32ca090>), but not in foo_1() (<django.db.models.base.ModelState object at 0x32cc650>)
A: Django returns a different object each time you retrieve a record from the database:
>>> i1 = Invoice.objects.all()[0]
>>> i2 = Invoice.objects.get(pk=i1.pk)
>>> i1 == i2
True // since model instances compare by their id field only
>>> id(i1) == id(i2)
False // since they are actually separate instances
You instantiate inv = Invoice("Jack") before calling foo_1, so after foo_1 updates all invoices, you still have your old inv instance, which hasn't been updated (since foo_1 instantiates its model objects itself, which are separate instances and do not affect inv) and hasn't been reloaded from the database — nothing has modified inv.client_name, although the record in the database has been updated. foo_2, on the other hand, works on that specific instance that you pass as an argument, so you see the changed client_name; you would actually see that change even if you don't save the instance.
A: Jack isn't saved in the DB when you save it. You haven't created an object to the database for your query to iterate over. However, you do have an obj you can pass around. Which is why you can change the objects attribute and save them.
A: Your inv object is stored locally so has not changed in the first instance. If you wish to continue to use the object just refresh the object from the db to get the latest attribute saved.
print inv.client_name
foo_1()
inv.refresh_from_db()
print inv.client_name
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/22048098",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Returning from nested functions function outer() {
$(['hi', 'there']).each(function(idx, e) {
console.log(e);
return;
});
alert("I don't want to be called");
}
function outer() {
$.get('http://test.com', function (data) {
console.log(data)
return; // I want to terminate the entire outer() function here.
});
alert("I don't want to be called");
}
What's the convention of breaking out of nested functions in cases like this? When using for loops, returning inside them terminates the entire function that encloses them. However, since $.each() is an individual function call, returning from it only ends itself, not the outer function. I could simply return twice, once inside and once outside in that case, but I am not sure how I would deal with $.ajax() because it is necessary to terminate the function only when I get a successful response.
A: For $.each(), you can stop the iteration with return false; in the callback, as described in the jQuery documentation.
This won't return from the calling function, but you can set a flag and test it in the outer function.
If you want an easy way to return from the outer function from inside the loop, you're better off with a simple for loop:
var array = [ 'hi', 'there' ];
for( var i = 0; i < array.length; ++i ) {
var e = array[i];
console.log(e);
return;
}
alert("I don't want to be called");
For $.get(), you should add some console.log() calls to your code and observe the order in which they are called:
function outer() {
console.log( 'in outer before $.get is called' );
$.get('http://test.com', function (data) {
console.log( 'inside $.get callback' );
});
console.log( 'in outer after $.get returns' );
}
Now what you'll notice is the order of the log messages:
in outer before $.get is called
in outer after $.get returns
inside $.get callback
See how the callback is the last thing? It's called after the outer function finishes. Therefore, there is nothing this callback can do to prevent the rest of outer from executing.
So you need to think some more about what you need to do and figure out a different way to accomplish it.
A: Here is a summary of how it all works.
.each()
return true; // skips to the next iteration of .each()
return false; // exits the .each() loop
In short there's no way of breaking out of the function containing .each() in a single statement.
$.get()
return [true|false]; // makes no sense at all.
As the return in $.get() does not get executed until the ajax call is complete, it wont serve much purpose. Even when you make a synchronous ajax call, a return statement in the success callback still does not do anything substantive. Think of a return from a function as a value to be assigned to the calling statement.
What's making it necessary to break out of your functions?
A: If you use $.ajax() instead of the short hand $.get(), it is possible to specify that it be executed synchronously.
$.ajax({
url: 'http://test.com',
success: function (data) {
},
async: false
});
Typically, when you want to make a decision based on the return value of a function you have it return a value and then use a conditional statement to determine what happens next.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/23771929",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Not to allow time picker to pick past time values I'm implementing a time picker dialog in my project. It should not pick past values with respect to current time. I mean to set minimum and maximum time for picking.
Below is the process for timepicker I have done:
// Current Hour
hour = cal.get(Calendar.HOUR_OF_DAY);
// Current Minute
minute = cal.get(Calendar.MINUTE);
return new TimePickerDialog(this, timePickerListener, hour, minute, false);
I have done the below process to date picker dialog. It worked, but for time picker I can't find any process.
For date picker :
Calendar calendar = Calendar.getInstance();
dialog = new DatePickerDialog(this, onDateSet, cYear, cMonth, cDay);
dialog.getDatePicker().setMinDate(calendar.getTimeInMillis());
So please help how to achieve this in time picker dialog.
A: You can use this as a starting point.
You extend TimePickerDialog and added 2 methods setMin and setMax.
In the onTimeChanged method check that the new time is valid with respect to the min/max times.
It still needs some polishing though...
public class BoundTimePickerDialog extends TimePickerDialog {
private int minHour = -1, minMinute = -1, maxHour = 100, maxMinute = 100;
private int currentHour, currentMinute;
public BoundTimePickerDialog(Context context, OnTimeSetListener callBack, int hourOfDay, int minute, boolean is24HourView) {
super(context, callBack, hourOfDay, minute, is24HourView);
}
public void setMin(int hour, int minute) {
minHour = hour;
minMinute = minute;
}
public void setMax(int hour, int minute) {
maxHour = hour;
maxMinute = minute;
}
@Override
public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
super.onTimeChanged(view, hourOfDay, minute);
boolean validTime;
if(hourOfDay < minHour) {
validTime = false;
}
else if(hourOfDay == minHour) {
validTime = minute >= minMinute;
}
else if(hourOfDay == maxHour) {
validTime = minute <= maxMinute;
}
else {
validTime = true;
}
if(validTime) {
currentHour = hourOfDay;
currentMinute = minute;
}
else {
updateTime(currentHour, currentMinute);
}
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/20040957",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Retrieving information from a web page in Python? I have the following page:
http://www.noncode.org/keyword.php
from where I want to extract some information from it by performing an external search by Python. Maybe it will sound simple, but I have not programmed web applications before.
So I would like to put in the search box something like:
NONHSAT146018.2
to perform a search and from the resulting webpage, which is this:
From the results I need to extract the field that it says Sequence. I have read some information about the BeatifulSoup library and some examples, but they do not include in the address the php form. I will really appreciate your help on this matter. Thanks.
Update: Following the advice of the users and with the help of @Lukas Newman, I made the following:
data="NONHSAT146018.2"
page = requests.get("http://www.noncode.org/show_rna.php?id=" + data)
soup=BS(page.content,'html.parser')
target = soup.find('h2',text='Sequence')
print(target)
target = soup.find('table',text='table-1')
print(target)
table = soup.find('table', attrs={'class'},text='table-1')
print(table)
when I inspect the results I got that the sequence is in the following field:
How can I extract that part by using Python?
A: Look at the url
http://www.noncode.org/show_rna.php?id=NONHSAT000002
The search is just passed as a get parameter. So to access the side just set the start url to something like:
import requests
from bs4 import *
id = "NONHSAT146018"
page = requests.get("http://www.noncode.org/show_rna.php?id=" + id)
soup = BeautifulSoup(page.content, "html.parser")
element = soup.findAll('table', class_="table-1")[1]
element2 = element.findAll('tr')[1]
element3 = element2.findNext('td')
your_data = str(element3.renderContents(), "utf-8")
print(your_data)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/65467558",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: Calling event handlers in dom elements I'll start the question giving an example. In React, we can pass a event handler to the element without calling it directly and it will receives the event as a argument.
But using pure JS and HTML, we can't do that.
I tried to execute the following code:
<i
class="material-icons remove-button"
onclick="PhotoUpload.removeOldPhoto"
>
clear
</i>
Instead of:
<i
class="material-icons remove-button"
onclick="PhotoUpload.removeOldPhoto(event)"
>
clear
</i>
And just the second one is called. Why is reason for that behavior?
A: Because inline, DOM level-zero events like this, when specified in HTML, are evaluated.
So you have to imagine that what's specified in the attribute is evaluated as JS, and:
PhotoUpload.removeOldPhoto
...when specified as JavaScript, is a reference to a function, not an invocation of one.
PhotoUpload.removeOldPhoto()
...is an invocation.
Contrast this with the property equivalent to the onclick attribute, where the situation is reversed - you would specify a function reference, not invocation.
someElement.onclick = myfunc; //not myfunc();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/61269755",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: difficulties exposing my express docker container to the world I have a node app running using express to run a webserver in a docker container. My node app looks a little like this:
'use strict'
const childProcess = require('child_process');
const express = require('express');
... // so many requires
const main = async () => {
var app = express();
app.get('/status', function (req, res) {
res.send('Hello World')
});
app.listen(8080,'0.0.0.0');
... // so much more code
}
main().catch((err) => {
console.error(err);
});
I don't believe there is anything wrong with my node app, because when I log into my docker container using: docker exec -it blacklist-service_blacklist-service_run_1 /bin/bash
And running: curl localhost:8080/status
It returns Hello World
So it leads me to believe that there is something wrong with my docker config, as when I run: curl localhost:8080/status from my host machine, I receive: curl: (7) Failed to connect to localhost port 8080: Connection refused
So... my Dockerfile looks like this:
FROM ubuntu:bionic
RUN apt-get update && apt-get -qq install \
curl \
git \
gnupg2 \
locales \
netcat \
python3-pip
RUN locale-gen en_US.UTF-8
ENV LANG en_US.UTF-8
ENV LANGUAGE en_US:en
ENV LC_ALL en_US.UTF-8
RUN pip3 install abydos \
num2words \
simplejson \
unidecode
RUN curl -sL https://deb.nodesource.com/setup_10.x | bash
RUN apt-get -qq install nodejs
RUN npm install npm@latest -g
RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app
RUN npm install -g \
Eficode/wait-for
RUN npm install \
express \
googleapis \
uuid
COPY src/ .
COPY bin/ ./bin
EXPOSE 8080
ENTRYPOINT /usr/lib/node_modules/wait-for/wait-for ${WAIT_FOR} -t 20 -- node server.js
(i know, i know, but it's a requirement to use ubuntu as our docker image)
I then have a docker-compose file that looks like this:
version: "3.6"
services:
rabbitmq:
image: "rabbitmq:latest"
ports:
- "15672:15672"
- "5672:5672"
volumes:
- "./enabled_plugins:/etc/rabbitmq/enabled_plugins"
blacklist-service:
environment:
NODE_ENV: development
image: ${DOCKER_REGISTRY}unicorn/blacklist-service:${DOCKER_IMAGE_LABEL:-latest}
build:
context: .
dockerfile: ./debugging/Dockerfile
ports:
- "0.0.0.0:8080:8080"
depends_on:
- rabbitmq
environment:
- WAIT_FOR=rabbitmq:5672
- AMQP_SHARED_HOST=rabbitmq
- AMQP_USERNAME=guest
- AMQP_PASSWORD
- AMQP_EXCHANGE=amq.topic
- AMQP_TOPIC=topic
- AMQP_JOB=state51::Job::RunQAForFormat
- AMQP_QUEUE
- AMQP_PATTERN=#
- AMQP_SHARED_PORT=5672
- AMQP_SEND_EXCHANGE=firehose
- BLACKLIST_SERVICE_SECRET
- GOOGLE_PRIVATE_KEY
- GOOGLE_CLIENT_EMAIL
- GOOGLE_CLIENT_ID
- GOOGLE_API_KEY
The ./debugging/Dockerfile refers to the Dockerfile I listed above.
I then build my image via: docker-compose -f docker-compose.local.yml build and run it with: docker-compose -f docker-compose.local.yml run blacklist-service (with docker-compose.local.yml being the name of the above docker-compose file).
So where have I gone wrong with exposing my server? running Docker community: Version 18.06.1-ce-mac73 (26764) on my Mac
A: I need to add the parameter --service-ports when using docker-compose run [service-name].
So the right command is: docker-compose -f docker-compose.local.yml run --service-ports blacklist-service which allows me to curl to localhost:8080/status and get the response I was expecting.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/53213726",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: TextBox - Issue with validation using IDataErrorInfo with integer Value more than int.MaxValue (2147483647) In my WPF text box i have bound the integer entity variable and set the IntegerValidationAttribute.
when i input text IDataErrorInfo is triggered with proper error info.
The issue is when i input the integer value more then int.MaxValue(2147483647) say i input
2147483649 the IDataErrorInfo error is not triggered.
I need to disable/Enable button depends on proper integer value validation.
Please suggest for the same.
Regards,
Vivek
A: when you put somthing like "cclks" in your textbox, your validation will also not happen or?
if not then you have some sort of "numeric only textbox" and if you have such a textbox you can go further and create a "integer numeric only textbox"
i always use string properties in my viewmodels so i can easily validate all input, but of course i have to cast to the real type for my models
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/8252828",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: use of smalloc in io.js The first release for io.js is out this month, I was reading the docs when I found smalloc a new module introduced in io.js.
Till today I have never felt a need of doing so in JavaScript.
My questions are:
*
*I wonder if there is really a need of raw memory allocation in
javscript using smalloc?
*If its needed then why?
*what would be the use case for using smalloc?
*and if not then why did io.js members add this module?
It also says
It's possible is to specify the type of external array data you would like. All possible options are listed in smalloc.Types.
Example usage:
var doubleArr = smalloc.alloc(3, smalloc.Types.Double);
and here is the list of types supported for allocation
smalloc.Types#
Int8
Uint8
Int16
Uint16
Int32
Uint32
Float
Double
Uint8Clamped
*Are we trying to make javascript a strongly typed language?
A: First of all, buffers are backed by the smalloc module and this module was not added by io.js devs, it was initiated in node 0.11 branch, io.js just imported it. Raw memory allocation means a lower level of memory manipulation and thus - faster operations, better performance, which is what aims both node.js and io.js. So if you need to implement something in the binary world without being limited to current Buffer API you should use smalloc to create your own ways to manipulate the memory. As the docs say:
This can be used to create your own Buffer-like classes. No other properties are set, so the user will need to keep track of other necessary information (e.g. length of the allocation).
Also, this is not a try to make javascript a strongly typed language, this is just memory manipulations, it can't be done in other way ensuring higher performance.
A: Thanks @micnic for answering the question well. I would like to offer some supplemental information about why I implemented smalloc.
Don't think raw memory allocations in JS are some strange new thing. It's the same type of mechanism that's used by Typed Arrays under the hood. So, anywhere you can use a Typed Array you could also use smalloc. The advantage of smalloc is that it doesn't define anything for you. Allowing the maximum flexibility of your API. It's also safe, because the GC will clean up your allocations when the object is no longer being used.
One usage would be for a math library. Especially if writing a native module. I personally use it for tricky performance optimizations of allocating memory on an object then sharing that memory between JS and C++ to enable shared state between the two. It's by far the fastest way to do so, and has lead to some impressive optimizations in Node and io.js.
Remember that you can allocate onto existing objects. Which is where the power lies. For example:
function Alloc(n) {
n >>>= 0; // uint32 conversion
this.length = n;
smalloc.alloc(n, this);
}
var a = new Alloc(16);
There's a simple new construct that just allocates a Uint8 external data array onto the instance.
I'll quickly reiterate answers to your questions:
*
*I wonder if there is really a need of raw memory allocation in javscript using smalloc?
Yes. Think Typed Arrays.
*If its needed then why?
Answered above. Also, search for anything that uses Typed Arrays.
*what would be the use case for using smalloc?
Answered above. In addition, there are many other uses that developers are finding for it.
*and if not then why did io.js members add this module?
I wrote it long before io.js was around. :)
*Are we trying to make javascript a strongly typed language?
Absolutely no. The two are not even related.
UPDATE: Because of breaking changes coming in V8 v4.4, smalloc has been marked "deprecated" starting in io.js v2.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/28066317",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Drupal: Stay on same page after registration I have a block with the registration form in it, I need people to register and stay on that same exact page, is that possible?
I tried the login destination module but that feature only seem to work on the login not register. Register keep sending to user profile page.
A: As you can see in the user_register_submit submit handler, $form_state['submit'] is hardcoded.
That means that user_register_submit will define the destination, unless you override it.
You can do that by adding your own submit handler (pseudo code).
function mymodule_form_alter(&$form, &$form_state, $form_id) {
if ($form_id == "user_register") {
//Look at the code in user_register_submit for all the ifs and switches to only
// add this extra handler when a normal user signs up.
$form['#submit'][] = "_mymodule_user_register_submit";
}
}
function _mymodule_user_register_submit($form, &$form_state) {
$form_state['redirect'] = $_GET['q']; //Adds the current url as redirect.
}
Then, using the weights in the system table, make sure your modulestarts after the user module. Otherwise they are called alphabetically, user module coming after mymodule; resetting the redirect again.
And never, ever, use drupal_goto() in submit handlers, because they will stop all processing and redirect the user, causing many modules to fail and often even causing broken and inconsistent databases.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/6659812",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How display tag a from behind to front? I create a menu has sub-menu at top of page and a slide image under of menu.
Result: Please reference to image file attached:
submenu is displaying behind of Slide image:
How can move submenu display front of slide image?
This is my css of top menu:
But If i add slide image , sub menu display behind.
{
margin: 0;
padding: 0;
}
#menu {
text-align: center;
padding: 10px;
}
#menu ul {
list-style-type: none;
text-align: center;
}
#menu li {
display: inline-block;
padding: 10px;
position: relative;
}
#menu a {
color: #4C9CF1;
text-decoration: none;
font-weight: bold;
display: block;
font-size: 16px;
}
#menu a:hover {
color: #444;
}
.sub-menu {
display: none;
position: absolute;
}
.sub-menu li {
display: none;
margin-left: 0 !important;
white-space: nowrap;
}
.sub-menu li a {
display: none;
margin-left: 0 !important;
}
#menu li:hover .sub-menu {
display: block;
}
<header>
<div id="menu">
<ul>
<li><a href="home">Home</a></li>
<li><a href="about">Product</a>
<ul class="sub-menu">
<li><a href="#">Product 1</a></li>
<li><a href="#">Product 2</a></li>
<li><a href="#">Product 3</a></li>
</ul>
</li>
<li><a href="login">Login</a></li>
<li><a href="signup">SignUp</a></li>
<li><a href="#">Contact</a></li>
</ul>
</div>
</header>
<!-- display the slider -->
<div>
<div id="amazingslider-1" style="display:block;position:relative;margin:0 auto;">
<ul class="amazingslider-slides" style="">
<li><img src="https://via.placeholder.com/1024x768" alt="1" title="1" />
</li>
</ul>
</div>
</div>
<!-- End -->
A: try this
add z-index: 100; so its work
.sub-menu {
z-index: 100;
}
{
margin: 0;
padding: 0;
}
#menu {
text-align: center;
padding: 10px;
}
#menu ul {
list-style-type: none;
text-align: center;
}
#menu li {
display: inline-block;
padding: 10px;
position: relative;
}
#menu a {
color: #4C9CF1;
text-decoration: none;
font-weight: bold;
display: block;
font-size: 16px;
}
#menu a:hover {
color: #444;
}
.sub-menu {
display: none;
position: absolute;
z-index: 100;
}
.sub-menu li {
display: none;
margin-left: 0 !important;
white-space: nowrap;
}
.sub-menu li a {
display: none;
margin-left: 0 !important;
}
#menu li:hover .sub-menu {
display: block;
}
<body>
<header>
<div id="menu">
<ul>
<li><a href="home">Home</a></li>
<li><a href="about">Product</a>
<ul class="sub-menu">
<li><a href="#">Product 1</a></li>
<li><a href="#">Product 2</a></li>
<li><a href="#">Product 3</a></li>
</ul>
</li>
<li><a href="login">Login</a></li>
<li><a href="signup">SignUp</a></li>
<li><a href="#">Contact</a></li>
</ul>
</div>
</header>
<!-- display the slider -->
<div>
<div id="amazingslider-1" style="display:block;position:relative;margin:0 auto;">
<ul class="amazingslider-slides" style="">
<li><img src="https://static.pexels.com/photos/34950/pexels-photo.jpg" alt="1" title="1" />
</li>
</ul>
</div>
</div>
<!-- End -->
</body>
A: Set the z-index higher for the item that you want to show in-front.
{
margin: 0;
padding: 0;
}
#menu {
text-align: center;
padding: 10px;
}
#menu ul {
list-style-type: none;
text-align: center;
}
#menu li {
display: inline-block;
padding: 10px;
position: relative;
}
#menu a {
color: #4C9CF1;
text-decoration: none;
font-weight: bold;
display: block;
font-size: 16px;
}
#menu a:hover {
color: #444;
}
.sub-menu {
display: none;
position: absolute;
z-index: 100;
}
.sub-menu li {
display: none;
margin-left: 0 !important;
white-space: nowrap;
}
.sub-menu li a {
display: none;
margin-left: 0 !important;
}
#menu li:hover .sub-menu {
display: block;
}
<header>
<div id="menu">
<ul>
<li><a href="home">Home</a></li>
<li><a href="about">Product</a>
<ul class="sub-menu">
<li><a href="#">Product 1</a></li>
<li><a href="#">Product 2</a></li>
<li><a href="#">Product 3</a></li>
</ul>
</li>
<li><a href="login">Login</a></li>
<li><a href="signup">SignUp</a></li>
<li><a href="#">Contact</a></li>
</ul>
</div>
</header>
<body>
<!-- display the slider -->
<div>
<div id="amazingslider-1" style="display:block;position:relative;margin:0 auto;">
<ul class="amazingslider-slides" style="">
<li><img src="https://via.placeholder.com/1024x768" alt="1" title="1" />
</li>
</ul>
</div>
</div>
</body>
<!-- End -->
A: #menu {
z-index:9000
text-align: center;
padding: 10px;
}
A: #menu {
text-align: center;
padding: 10px;
position:relative
z-index:99;
}
try this,must add position
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/51077443",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Getting root on a Sony TV? I recently read this post over at Hack a Day Getting root on a Sony TV, which uses a script that can be found here for use on Sony Bravia TVs. The script uses BusyBox and my question is based on the README found here. I have two questions about this: 1. What are the steps I have to take in order to compile BusyBox for the mipsel architecture? 2. How do I include the GLibc / Linux kernel versions for your TV in my BusyBox binary?
Has anyone else gotten this trick to work successfully?
Thanks in advance for your help and time.
A: Compiling for another architecture is called cross compiling, but of course you would have read that on the Busybox FAQ. Not to mention the link provided there to cross-compilers for all architectures you could ask for.
You could try find a pre-built MIPS binary, the best would be to ask the Busybox list directly if in doubt :)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/11182691",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Why is casting a sub-classed collection of subclassed objects to its superclass collection of superclass objects not allowed in java? The code is also at https://github.com/timp21337/java-generics-example
package a;
import java.util.List;
public interface Container<T> {
List<T> getThings();
}
public class ContainerContainer {
public Container<Thing> getThingContainer() {
return new ThingContainer<Thing>();
}
}
public class ThingContainer<T extends a.Thing> implements Container<T> {
@Override
public List<T> getThings() {
return null;
}
}
public class Thing {
}
Package b
package b;
import java.util.List;
public class ContainerContainer extends a.ContainerContainer {
ThingContainer<Thing> thingContainer = new ThingContainer<Thing>();
@SuppressWarnings("unchecked")
public a.Container<a.Thing> getContainer() {
return (a.Container<a.Thing>)(Object)thingContainer; //YUCK
}
}
public class ThingContainer<T extends a.Thing>
implements a.Container<T> {
@Override
public List<T> getThings() {
return null;
}
}
public class Thing extends a.Thing {
}
My question is why do I have to coerce the b.ThingContainer (marked YUCK above) when it is a subclass of a.ThingContainer and the Things it contains are subclasses of a.Thing?
A: Let's consider a much simpler example, to remove all the irrelevant details. (Here, instead of b.Thing we will use String, and instead of a.Thing we will use Object; String is a subclass of Object, so it is analogous. Instead of a.Container, we will use List. The subclassing of the container is irrelevant, as you will see.) If you can understand why this example doesn't work, you will understand your problem.
List<String> foo = new ArrayList<String>();
List<Object> bar = foo; // why doesn't this work?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/9832396",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: File to import not found or unreadable: bulma-extensions/extensions. with create-react-app Encounter error when importing bulma extentions like this @import 'bulma-extensions/extensions';. I was able to import bulma this way @import 'bulma/bulma'; so I was wondering why I can't do that with bulma-extensions. I am using ReactJS by the way. I'd like to know it I am the one doing something wrong or it's a common error when integrating sass with react because bulma works well with other frameworks e.i. Vuejs/Angular.
{
"status": 1,
"file": "D:/Study/Andro/admin-exchange/src/index.scss",
"line": 2,
"column": 1,
"message": "File to import not found or unreadable: bulma-extensions/extensions.",
"formatted": "Error: File to import not found or unreadable: bulma-extensions/extensions.\n on line 2 of src/index.scss\n>> @import 'bulma-extensions/extensions';\n\n ^\n"
}
{
"status": 1,
"file": "D:/Study/Andro/admin-exchange/src/index.scss",
"line": 2,
"column": 1,
"message": "File to import not found or unreadable: bulma-extensions/extensions.",
"formatted": "Error: File to import not found or unreadable: bulma-extensions/extensions.\n on line 2 of src/index.scss\n>> @import 'bulma-extensions/extensions';\n\n ^\n"
}
Note: I understand that I can do it like this @import '../node_modules/bulma-extensions/dist/css/bulma-extensions.sass'; but that is not without changing the path for each extension inside the file as well for it to work.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/52754489",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Extract a value in column A given the maximum value in column B within each group (column C) in an R dataframe? My question is related to Extract the maximum value within each group in a dataframe.
*
*The question there is essentially: how do you select the max value in one column based on repeated groups in a separate column in the same data frame?
*In that post, user EDi provides a ton of examples for how to accomplish this task.
My question: how do I accomplish the same task, but instead of reporting the max value, I instead report a value in a third column associated with that max value?
For example:
*
*Assume I have a data.frame:
Group Value Year
A 12 1933
A 10 2010
B 3 1935
B 5 1978
B 6 2011
C 1 1954
D 3 1933
D 4 1978
*For each level of my grouping variable, I wish to extract the year that the maximum value occurred. The result should thus be a data frame with one row per level of the grouping variable:
Group Year
A 1933
B 2011
C 1954
D 1978
I know I could use any of the answers from EDi's post mentioned above and then just use something like which,match or sapply to figure out the year, but that seems too sloppy.
Is there a quick way to extract a value in column A given the maximum value in column B within each group (column C) in a dataframe?
Update: Could someone please provide a base R solution?
A: library(dplyr)
df %>% group_by(Group) %>% slice(which.max(Value)) %>% select(-Value)
#Source: local data frame [4 x 2]
#Groups: Group [4]
# Group Year
# <fctr> <int>
#1 A 1933
#2 B 2011
#3 C 1954
#4 D 1978
Note this only keeps one max value per group if ties exist.
A method that keeps tied max values:
library(dplyr)
df %>% group_by(Group) %>% filter(Value == max(Value)) %>% select(-Value)
#Source: local data frame [4 x 2]
#Groups: Group [4]
# Group Year
# <fctr> <int>
#1 A 1933
#2 B 2011
#3 C 1954
#4 D 1978
A: Here is a base R and a data.table solution:
df <- structure(list(Group = c("A", "A", "B", "B", "B", "C", "D", "D"
), Value = c(12L, 10L, 3L, 5L, 6L, 1L, 3L, 4L), Year = c(1933L,
2010L, 1935L, 1978L, 2011L, 1954L, 1933L, 1978L)), .Names = c("Group",
"Value", "Year"), row.names = c(NA, -8L), class = "data.frame")
# Base R - use aggregate to get max Value per group, then merge with df
merge(df, aggregate(Value ~ Group, df, max), by.all = c("Group", "Value"))[
, c("Group", "Year")]
# Group Year
# 1 A 1933
# 2 B 2011
# 3 C 1954
# 4 D 1978
# data.table solution
library(data.table)
dt <- data.table(df)
dt[, .SD[which.max(Value), .(Year)], by = Group]
# Group Year
# 1: A 1933
# 2: B 2011
# 3: C 1954
# 4: D 1978
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/43791480",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Postgresql - Check if a given string starts with any element of the array of strings Given two strings we can do:
select 'aaa123' ilike 'aaa'||'%'
The result will be TRUE. I would like to do the same thing with a string and an array - if the given string starts with any of the elements of the array of strings than the result would show TRUE.
For example (array and string):
select array['aaa123'::text,'bbb123'::text] as text_array
select 'aaa12345' as string
I would like to do something like this:
select string ilike ANY(text_array || '%')
And I would expect TRUE since aaa12345 starts with aaa123 (element of the array).
Thanks a lot for the help!
A: You could unnest() the array of strings and then compare your input string with every element like you wanted.
You would get as many rows in the output as there are elements in your array. Since you need a clear indicator whether any of the comparison against array element yields true use bool_or() aggregate function:
select
bool_or('string12345' ilike arr_element||'%')
from
unnest(ARRAY['string123','something']::text[]) x(arr_element);
This would give you TRUE since:
SELECT 'string12345' ilike 'string123%' -- true
Note: bool_or() returns true if at least one input value is true, otherwise false.
A: select string ilike ANY(
select s || '%'
from unnest(text_array) s(s)
)
A: You can use EXISTS with unnest as follows:
SELECT EXISTS (SELECT * FROM unnest(text_array) a WHERE 'aaa1234' ILIKE a||'%')
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/39019715",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: Limiting a SQL Select query I am connecting to an SQL database in my PHP script and am having trouble with the LIMIT command:
$result = mysql_query("
SELECT *
FROM product
WHERE `category` like \"" . $_GET['category'] . "\"
LIMIT 0, 16
");
This all works, except that if I only have 10 rows then $result contains rows 0~10 and then 0~6 as well.
I am using a a while loop while($row = mysql_fetch_assoc($result)) to check if there is a result and then run an action. Is there any way of having it limit the select statement to only show rows 0~10?
A: $result = mysql_query("SELECT * FROM product
WHERE `category` like '" . mysql_real_escape_string($_GET['category']) . "' LIMIT 0, 10");
is it what are you looking for? It will give you ten rows maximally..
Additionally, please read this article about SQLi
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/6804125",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.