text
stringlengths 15
59.8k
| meta
dict |
---|---|
Q: Search Using IN Condition in MySql I am writing Web services for IOS In cakePhp and stuck in IN condition.
I have a table dog_temperaments and it has values "happy,dependent,shy".
Now if IOS send me array (happy,shy) Then I search Like this
Select dog_temperaments.* where temperaments IN(happy,shy)
Its work fine but if IOS send me array 0 or any(means search by any temperament) Then How I will Search........
Any means Search by all temperaments
A: If it is 0 or any any then no need for that condition as it ishould return all of them.
So aassuming $type will contain the temperaments as an array and 0/any will be single element for that case.
if(count($type) == 1 && in_array(($type[0], array('0', 'any'))) {
$condition = "";
} else {
$condition = "WHERE temperaments IN ('" . implode("','", $type) . "')";
}
And the query will be like -
"Select dog_temperaments.* from dog_temperaments ".$condition
A: Either you can check that the array is empty or not like
if(is_array($array)) {
Use
Select dog_temperaments.* where temperaments IN('happy','shy');
} else {
notify Enter proper search key
}
Else you anyways get the empty results by using the same query if the array is empty like
Select dog_temperaments.* where temperaments IN(0);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/30258959",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Python copying multiple files simultaneously (Multithreading) I have some python code that I use to copy files from one directly to another, however it is a very slow process and is sequential. I would like to find a way to do multithreading, copying more that one by one file, but rather have 10 or 100 processes running doing this. Here is my current core that process one by one file:
import os
import shutil
directory = "All_files"
with open('files.txt','w') as f:
for filename in os.listdir(directory):
src = directory+"/"+filename+"/02-Partners.pdf"
file_exists = os.path.exists(src)
if file_exists == True:
dst="part/"+filename+"_"+"02-Partners.pdf"
shutil.copyfile(src,dst)
f.write('%s \n' % (filename))
Any assistance in getting multiple files copying at the same time will be appreciated.
A: Take a look at python's threading basic package and see if it fits you.
https://docs.python.org/3/library/threading.html
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72617538",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Python Module issues Im pretty new to python, and have been having a rough time learning it. I have a main file
import Tests
from Tests import CashAMDSale
CashAMDSale.AMDSale()
and CashAMDSale
import pyodbc
import DataFunctions
import automa
from DataFunctions import *
from automa.api import *
def AMDSale():
AMDInstance = DataFunctions.GetValidAMD()
And here is GetValidAMD
import pyodbc
def ValidAMD(GetValidAMD):
(short method talking to a database)
My error comes up on the line that has AMDInstance = DataFunctions.GetValidAMD()
I get the error AttributeError: 'module' object has no attribute 'GetValidAMD'
I have looked and looked for an answer, and nothing has worked. Any ideas? Thanks!
A: When you create the file foo.py, you create a python module. When you do import foo, Python evaluates that file and places any variables, functions and classes it defines into a module object, which it assigns to the name foo.
# foo.py
x = 1
def foo():
print 'foo'
>>> import foo
>>> type(foo)
<type 'module'>
>>> foo.x
1
>>> foo.foo()
foo
When you create the directory bar with an __init__.py file, you create a python package. When you do import bar, Python evaluates the __init__.py file and places any variables, functions and classes it defines into a module object, which it assigns to the name bar.
# bar/__init__.py
y = 2
def bar():
print 'bar'
>>> import bar
>>> type(bar)
<type 'module'>
>>> bar.y
2
>>> bar.bar()
bar
When you create python modules inside a python package (that is, files ending with .py inside directory containing __init__.py), you must import these modules via this package:
>>> # place foo.py in bar/
>>> import foo
Traceback (most recent call last):
...
ImportError: No module named foo
>>> import bar.foo
>>> bar.foo.x
1
>>> bar.foo.foo()
foo
Now, assuming your project structure is:
main.py
DataFunctions/
__init__.py
CashAMDSale.py
def AMDSale(): ...
GetValidAMD.py
def ValidAMD(GetValidAMD): ...
your main script can import DataFunctions.CashAMDSale and use DataFunctions.CashAMDSale.AMDSale(), and import DataFunctions.GetValidAMD and use DataFunctions.GetValidAMD.ValidAMD().
A: DataFunctions is a folder, which means it is a package and must contain an __init__.py file for python to recognise it as such.
when you import * from a package, you do not automatically import all it's modules. This is documented in the docs
so for your code to work, you either need to explicitly import the modules you need:
import DataFunctions.GetValidAMD
or you need to add the following to the __init__.py of DataFunctions:
__all__ = ["GetValidAMD"]
then you can import * from the package and everything listen in __all__ will be imported
A: Check out this.
It's the same problem. You are importing DataFunctions which is a module. I expct there to be a class called DataFunctions in that module which needs to be imported with
from DataFunctions import DataFunctions
...
AMDInstance = DataFunctions.GetValidAMD()
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/31078140",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: how to insert an array into database in python? I have a database called my_python and I have a table called my_transport. There are 3 columns in the table: id, transport, and fee. for the first columns "id", I make it auto increment so that I don't have to insert any value into it. My question is how to insert the value of my_trans and my_fee into the database table?
import mysql.connector
my_trans=['car','train','ship','train']
my_fee=[200,300,150,200]
try:
connection = mysql.connector.connect(host='localhost',
database='my-python',
user='root',
password='')
sql_insert_query = """INSERT INTO my_transport
(`transport`, `fee`) VALUES (my_trans, my_fee)"""
cursor = connection.cursor()
result = cursor.execute(sql_insert_query)
connection.commit()
print ("Record inserted successfully into table") except mysql.connector.Error as error :
connection.rollback() #rollback if any exception occured
print("Failed inserting record into table {}".format(error)) finally:
#closing database connection.
if(connection.is_connected()):
cursor.close()
connection.close()
print("MySQL connection is closed")
I have try below code but it said:
"Failed inserting record into table 1054 (42S22): Unknown column 'my_trans' in 'field list'"
A: use .executemany to insert array of records as mentioned here
my_trans = []
my_trans.append('car', 200)
my_trans.append('train', 300)
my_trans.append('ship', 150)
my_trans.append('train', 200)
sql_insert_query = 'INSERT INTO my_transport
(transport, fee) VALUES (%s, %s)'
cursor = connection.cursor()
result = cursor.executemany(sql_insert_query, my_trans)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/57156097",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: how to make autocommit false work in kafkajs scenario:
im setting autocommit false,
producing 12 messages
consuming them.. (say from offset 100)
shutting down consumer
start a new consumer
in that stage, I expect to the 2nd consumer to read all messages again starting offset 100 (because no committing was done)
but when producing new messages I see that the 2nd consumer starts from the new offset (113) i.e the commit still occurs somehow..
what do I get wrong?
that is my consumer code
const { Kafka } = require('kafkajs');
const kafka = new Kafka({
clientId: 'my-app',
brokers: ['192.168.14.10:9095']
});
const admin = kafka.admin();
const consumer = kafka.consumer({ groupId: 'test-group' });
const run = async () => {
// admin
await admin.connect();
// Consuming
await consumer.connect();
await consumer.subscribe({ topic: 'topic-test2'});
await consumer.run({
autoCommit: false,
eachMessage: async ({ topic, partition, message }) => {
console.log({
partition,
offset: message.offset,
value: message.value.toString()
});
}
}
});
};
run().catch(console.error);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/62193441",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Cannot use the count() function in a query containing subquery I have the below query working fine.
SELECT
(SELECT MAX(LOG_DATE) FROM LOGTABLE WHERE ID=A.ID AND STATUS = 'NEW') AS DATE1,
(SELECT MAX(LOG_DATE) FROM LOGTABLE WHERE ID=A.ID AND STATUS= 'OLD') AS DATE
FROM TABLE1 A
WHERE
A.STATUS ('NEW') OR
A.ID IN (
SELECT DISTINCT ID
FROM LOGTABLE
WHERE LOG_DATE BETWEEN @DATETIME AND @DATETIME AND STATUS = 'OLD'
)
Now I wanted to count the MAX(LOG_DATE).
Below is what I have tried.
SELECT
COUNT((SELECT MAX(LOG_DATE) FROM LOGTABLE WHERE ID=A.ID AND STATUS = 'NEW')) AS DATE1,
COUNT((SELECT MAX(LOG_DATE) FROM LOGTABLE WHERE ID=A.ID AND STATUS= 'OLD')) AS DATE
FROM TABLE1 A
WHERE
A.STATUS ('NEW') OR
A.ID IN (
SELECT DISTINCT ID
FROM LOGTABLE
WHERE LOG_DATE BETWEEN @DATETIME AND @DATETIME AND STATUS = 'OLD'
)
It resulted in a below error:
Cannot perform an aggregate function on an expression containing an
aggregate or a subquery.
A: I think filtering the Raw data and after that applying, the count would be good option,
;WITH CTE AS (SELECT
(SELECT MAX(LOG_DATE) FROM LOGTABLE WHERE ID=A.ID AND STATUS = 'NEW') AS DATE1,
(SELECT MAX(LOG_DATE) FROM LOGTABLE WHERE ID=A.ID AND STATUS= 'OLD') AS DATE
FROM TABLE1 A
WHERE
A.STATUS ('NEW') OR
A.ID IN (
SELECT DISTINCT ID
FROM LOGTABLE
WHERE LOG_DATE BETWEEN @DATETIME AND @DATETIME AND STATUS = 'OLD'
))
SELECT COUNT(DATE1),COUNT(Date) FROM CTE
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73661076",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: How to fix 'PHP code not working in laravel public folder' I embed a php in one of my views with:
<iframe src="{{URL::to('/')}}/game/game.blade.php" width="1519" height="690"></iframe>
In this file I have the following code:
<script>
var userID = {{ auth()->user()->id }};
var userCredit = {{ auth()->user()->id }};
</script>
I get the following error:
Uncaught SyntaxError: Unexpected token '{'
I already tried to use {{ Auth::user()->name }} etc.
I also tried to embed a link that used a route to another view but with this I got a 403 forbidden error.
Does anyone know how I could fix this? or have another solution for me?
A: First, iframe src is never .blade.php file. You can create a route /game and map that route to controller which then returns the .blade.php view. So, in your view:
<iframe src="{{URL::to('/')}}/game" width="1519" height="690"></iframe>
And then in web.php
Route::get('game', 'HomeController@game');
And in HomeController.php:
public function game(){
return view('game');
}
In which file are you writing tag? What's the full error that you are getting? Maybe enclosing your variables inside quotes like this will solve the problem.
<script>
var userID = "{{ auth()->user()->id }}";
var userCredit = "{{ auth()->user()->id }}";
</script>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/58142451",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Beginner Scoring program button development in Java I'm trying to add a "green team" to an example scoring GUI I found online. For some reason, the code compiles, but it runs with only the original two teams. I've tried playing around with the sizes/locations somewhat clumsily, and since no change was observed with these modications (NO change at ALL), I admit that I must be missing some necessary property or something. Any help? Here's the code:
import javax.swing.*;
import java.awt.Color;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class ButtonDemo_Extended3 implements ActionListener{
// Definition of global values and items that are part of the GUI.
int redScoreAmount = 0;
int blueScoreAmount = 0;
int greenScoreAmount = 0;
JPanel titlePanel, scorePanel, buttonPanel;
JLabel redLabel, blueLabel,greenLabel, redScore, blueScore, greenScore;
JButton redButton, blueButton, greenButton,resetButton;
public JPanel createContentPane (){
// We create a bottom JPanel to place everything on.
JPanel totalGUI = new JPanel();
totalGUI.setLayout(null);
// Creation of a Panel to contain the title labels
titlePanel = new JPanel();
titlePanel.setLayout(null);
titlePanel.setLocation(0, 0);
titlePanel.setSize(500, 500);
totalGUI.add(titlePanel);
redLabel = new JLabel("Red Team");
redLabel.setLocation(300, 0);
redLabel.setSize(100, 30);
redLabel.setHorizontalAlignment(0);
redLabel.setForeground(Color.red);
titlePanel.add(redLabel);
blueLabel = new JLabel("Blue Team");
blueLabel.setLocation(900, 0);
blueLabel.setSize(100, 30);
blueLabel.setHorizontalAlignment(0);
blueLabel.setForeground(Color.blue);
titlePanel.add(blueLabel);
greenLabel = new JLabel("Green Team");
greenLabel.setLocation(600, 0);
greenLabel.setSize(100, 30);
greenLabel.setHorizontalAlignment(0);
greenLabel.setForeground(Color.green);
titlePanel.add(greenLabel);
// Creation of a Panel to contain the score labels.
scorePanel = new JPanel();
scorePanel.setLayout(null);
scorePanel.setLocation(10, 40);
scorePanel.setSize(500, 30);
totalGUI.add(scorePanel);
redScore = new JLabel(""+redScoreAmount);
redScore.setLocation(0, 0);
redScore.setSize(40, 30);
redScore.setHorizontalAlignment(0);
scorePanel.add(redScore);
greenScore = new JLabel(""+greenScoreAmount);
greenScore.setLocation(60, 0);
greenScore.setSize(40, 30);
greenScore.setHorizontalAlignment(0);
scorePanel.add(greenScore);
blueScore = new JLabel(""+blueScoreAmount);
blueScore.setLocation(130, 0);
blueScore.setSize(40, 30);
blueScore.setHorizontalAlignment(0);
scorePanel.add(blueScore);
// Creation of a Panel to contain all the JButtons.
buttonPanel = new JPanel();
buttonPanel.setLayout(null);
buttonPanel.setLocation(10, 80);
buttonPanel.setSize(2600, 70);
totalGUI.add(buttonPanel);
// We create a button and manipulate it using the syntax we have
// used before. Now each button has an ActionListener which posts
// its action out when the button is pressed.
redButton = new JButton("Red Score!");
redButton.setLocation(0, 0);
redButton.setSize(30, 30);
redButton.addActionListener(this);
buttonPanel.add(redButton);
blueButton = new JButton("Blue Score!");
blueButton.setLocation(150, 0);
blueButton.setSize(30, 30);
blueButton.addActionListener(this);
buttonPanel.add(blueButton);
greenButton = new JButton("Green Score!");
greenButton.setLocation(250, 0);
greenButton.setSize(30, 30);
greenButton.addActionListener(this);
buttonPanel.add(greenButton);
resetButton = new JButton("Reset Score");
resetButton.setLocation(0, 100);
resetButton.setSize(50, 30);
resetButton.addActionListener(this);
buttonPanel.add(resetButton);
totalGUI.setOpaque(true);
return totalGUI;
}
// This is the new ActionPerformed Method.
// It catches any events with an ActionListener attached.
// Using an if statement, we can determine which button was pressed
// and change the appropriate values in our GUI.
public void actionPerformed(ActionEvent e) {
if(e.getSource() == redButton)
{
redScoreAmount = redScoreAmount + 1;
redScore.setText(""+redScoreAmount);
}
else if(e.getSource() == blueButton)
{
blueScoreAmount = blueScoreAmount + 1;
blueScore.setText(""+blueScoreAmount);
}
else if(e.getSource() == greenButton)
{
greenScoreAmount = greenScoreAmount + 1;
greenScore.setText(""+greenScoreAmount);
}
else if(e.getSource() == resetButton)
{
redScoreAmount = 0;
blueScoreAmount = 0;
greenScoreAmount = 0;
redScore.setText(""+redScoreAmount);
blueScore.setText(""+blueScoreAmount);
greenScore.setText(""+greenScoreAmount);
}
}
private static void createAndShowGUI() {
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("[=] JButton Scores! [=]");
//Create and set up the content pane.
ButtonDemo_Extended demo = new ButtonDemo_Extended();
frame.setContentPane(demo.createContentPane());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(1024, 768);
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
A: import javax.swing.*;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class ButtonDemo_Extended3 implements ActionListener{
// Definition of global values and items that are part of the GUI.
int redScoreAmount = 0;
int blueScoreAmount = 0;
int greenScoreAmount = 0;
JPanel titlePanel, scorePanel, buttonPanel;
JLabel redLabel, blueLabel,greenLabel, redScore, blueScore, greenScore;
JButton redButton, blueButton, greenButton,resetButton;
public JPanel createContentPane (){
// We create a bottom JPanel to place everything on.
JPanel totalGUI = new JPanel();
totalGUI.setLayout(null);
// Creation of a Panel to contain the title labels
titlePanel = new JPanel();
titlePanel.setLayout(new FlowLayout());
titlePanel.setLocation(0, 0);
titlePanel.setSize(500, 500);
redLabel = new JLabel("Red Team");
redLabel.setLocation(300, 0);
redLabel.setSize(100, 30);
redLabel.setHorizontalAlignment(0);
redLabel.setForeground(Color.red);
titlePanel.add(redLabel, 0 );
blueLabel = new JLabel("Blue Team");
blueLabel.setLocation(900, 0);
blueLabel.setSize(100, 30);
blueLabel.setHorizontalAlignment(0);
blueLabel.setForeground(Color.blue);
titlePanel.add(blueLabel, 1);
greenLabel = new JLabel("Green Team");
greenLabel.setLocation(600, 0);
greenLabel.setSize(100, 30);
greenLabel.setHorizontalAlignment(0);
greenLabel.setForeground(Color.green);
titlePanel.add(greenLabel);
// Creation of a Panel to contain the score labels.
scorePanel = new JPanel();
scorePanel.setLayout(null);
scorePanel.setLocation(10, 40);
scorePanel.setSize(500, 30);
redScore = new JLabel(""+redScoreAmount);
redScore.setLocation(0, 0);
redScore.setSize(40, 30);
redScore.setHorizontalAlignment(0);
scorePanel.add(redScore);
greenScore = new JLabel(""+greenScoreAmount);
greenScore.setLocation(60, 0);
greenScore.setSize(40, 30);
greenScore.setHorizontalAlignment(0);
scorePanel.add(greenScore);
blueScore = new JLabel(""+blueScoreAmount);
blueScore.setLocation(130, 0);
blueScore.setSize(40, 30);
blueScore.setHorizontalAlignment(0);
scorePanel.add(blueScore);
// Creation of a Panel to contain all the JButtons.
buttonPanel = new JPanel();
buttonPanel.setLayout(null);
buttonPanel.setLocation(10, 80);
buttonPanel.setSize(2600, 70);
// We create a button and manipulate it using the syntax we have
// used before. Now each button has an ActionListener which posts
// its action out when the button is pressed.
redButton = new JButton("Red Score!");
redButton.setLocation(0, 0);
redButton.setSize(30, 30);
redButton.addActionListener(this);
buttonPanel.add(redButton);
blueButton = new JButton("Blue Score!");
blueButton.setLocation(150, 0);
blueButton.setSize(30, 30);
blueButton.addActionListener(this);
buttonPanel.add(blueButton);
greenButton = new JButton("Green Score!");
greenButton.setLocation(250, 0);
greenButton.setSize(30, 30);
greenButton.addActionListener(this);
buttonPanel.add(greenButton);
resetButton = new JButton("Reset Score");
resetButton.setLocation(0, 100);
resetButton.setSize(50, 30);
resetButton.addActionListener(this);
buttonPanel.add(resetButton);
totalGUI.setOpaque(true);
totalGUI.add(buttonPanel);
totalGUI.add(scorePanel);
totalGUI.add(titlePanel);
return totalGUI;
}
// This is the new ActionPerformed Method.
// It catches any events with an ActionListener attached.
// Using an if statement, we can determine which button was pressed
// and change the appropriate values in our GUI.
public void actionPerformed(ActionEvent e) {
if(e.getSource() == redButton)
{
redScoreAmount = redScoreAmount + 1;
redScore.setText(""+redScoreAmount);
}
else if(e.getSource() == blueButton)
{
blueScoreAmount = blueScoreAmount + 1;
blueScore.setText(""+blueScoreAmount);
}
else if(e.getSource() == greenButton)
{
greenScoreAmount = greenScoreAmount + 1;
greenScore.setText(""+greenScoreAmount);
}
else if(e.getSource() == resetButton)
{
redScoreAmount = 0;
blueScoreAmount = 0;
greenScoreAmount = 0;
redScore.setText(""+redScoreAmount);
blueScore.setText(""+blueScoreAmount);
greenScore.setText(""+greenScoreAmount);
}
}
private static void createAndShowGUI() {
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("[=] JButton Scores! [=]");
//Create and set up the content pane.
ButtonDemo_Extended3 demo = new ButtonDemo_Extended3();
frame.setContentPane(demo.createContentPane());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(1024, 768);
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
You have to use a layout manager in order to display your widgets. In this case I used a FlowLayout(). Also, make sure that you add the elements first in the panel and then you add the panel to its parent panel.
Now, the code works as you probably want, but again you should use a particular layout in order to arrange the panels inside the frame.
A: If I run your code unmodified, I see just the "Red Team" label, and some buttons which are too small to read the text (and some of them only appear when moused over).
If you comment out all the null layouts:
//buttonPanel.setLayout(null);
then all three buttons and labels appear properly.
Doing without a layout manager, and using absolute positioning, is possible (see the Java Swing tutorial page on this exact topic) but not usually recommended. There is a lot of information on using layout managers in the Laying Out Components Within a Container lesson of the Swing tutorials.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/12944744",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: function calls not working on baremetal c code for cortex m0 with gnu toolchain I am building a custom soc based on the arm cortex m0 design start. The SOC now has a cortex mo core attached to a AHB lite bus with some ram on it and a gpio module. I am currently struggling to write and compiling code for it using the gnu tool chain. The function calls are not working. I tried many things but nothing seems to work. The interesting part is if i compile the same code with keil, it works. I guess the problem is somewhere in how i am setting up the stack and/or the liker script or I am missing some compiler/linker options.
This works
#include<stdint.h>
volatile uint8_t* led_reg;
int main() {
led_reg=(uint8_t*)0x50000000;
while (1) {
*led_reg=0x8;
for(int i=0;i<=0x2FFFFF;i++);
*led_reg=0x4;
for(int i=0;i<=0x2FFFFF;i++);
*led_reg=0x2;
for(int i=0;i<=0x2FFFFF;i++);
*led_reg=0x1;
for(int i=0;i<=0x2FFFFF;i++);
}
}
But this doesn't
#include<stdint.h>
volatile uint8_t* led_reg;
void wait(void){
for(int i=0;i<=0x2FFFFF;i++);
}
void on(uint8_t pat){
*led_reg=pat;
}
int main() {
led_reg=(uint8_t*)0x50000000;
while (1){
on(0x8);
wait();
on(0x4);
wait();
on(0x2);
wait();
on(0x1);
wait();
}
}
This is the linker script
ENTRY(Reset_Handler)
STACK_SIZE = 0x1000;
SECTIONS
{
. = 0x00000000;
.ram :
{
. = ALIGN(4);
_stext = .;
KEEP(*(.vectors .vectors.*))
*(.text .text.*)
*(.rodata .rodata*)
. = ALIGN(4);
_sbss = . ;
*(.bss .bss.*)
*(COMMON)
. = ALIGN(4);
_ebss = . ;
. = ALIGN(4);
_sdata = .;
*(.data .data.*);
. = ALIGN(4);
_edata = .;
. = ALIGN(8);
_sstack = .;
. = . + STACK_SIZE;
. = ALIGN(8);
_estack = .;
. = ALIGN(4);
_end = . ;
}
}
Relevant portion of the startup code
/* Exception Table */
__attribute__ ((section(".vectors")))
const DeviceVectors exception_table = {
/* Configure Initial Stack Pointer, using linker-generated symbols */
.pvStack = (void*) (&_estack),
.pfnReset_Handler = (void*) Reset_Handler,
.pfnNMI_Handler = (void*) NMI_Handler,
.pfnHardFault_Handler = (void*) HardFault_Handler,
Here is the compiling and linking command examples
arm-none-eabi-gcc -Wall -Werror -g -O0 -std=c99 -ffreestanding -ffunction-sections -fdata-sections -mcpu=cortex-m0 -mfloat-abi=soft -march=armv6-m -mthumb -Wall -Iinclude/headers -o build/main.o -c src/main.c
arm-none-eabi-gcc -Wall -Werror -g -O0 -std=c99 -ffreestanding -ffunction-sections -fdata-sections -mcpu=cortex-m0 -mfloat-abi=soft -march=armv6-m -mthumb -Wall -Iinclude/headers -Wl,-Map=build/firmware.map,--gc-sections -T vcoresoc.lds --specs=nano.specs build/main.o build/startup_vcoresoc.o build/syscall.o -o build/firmware.elf
A: You have several smaller bugs in this code. It is likely that gcc optimizes the code better than Keil and therefore the function could simply be removed. In some cases you are missing volatile which may break the code:
*
*led_reg=(uint8_t*)0x50000000; should be led_reg=(volatile uint8_t*)0x50000000u;, see How to access a hardware register from firmware?
*void wait(void){ for(int i=0;i<=0x2FFFFF;i++); } should be volatile as well or the loop will just get removed.
Additionally, I don't know if you wrote the startup code or if the tool vendor did, but it has bugs. Namely .pvStack = (void*) (&_estack) invokes undefined behavior, since C doesn't allow conversions from function pointers to object pointers. Instead of void* you need to use an unsigned integer or a function pointer type. As mentioned in comments, putting some alignment keyword on a Cortex M vector table is fishy - it should be at address 0 so how can it be misaligned? It would be interesting to see the definition of DeviceVectors.
Also, bare metal microcontroller systems do not return from main(). You should not use int main(), since that is likely to cause a bit of stack overhead needlessly. Use an implementation-defined form such as void main (void) then compile for embedded ("freestanding") systems. With gcc that is -ffreestanding.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/68610294",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Can I use delete clause in Case Clause in teradata I am newbie to teradata.
I need to delete a row once the case condition is satisfied.
Eg: case condition true delete the selected row.
A: Maybe I am misinterpreting what you are trying to accomplish with the CASE statement, but based on my understanding you can use the WHERE clause to conditionally remove data from a table:
DELETE
FROM MyDB.MyTable
WHERE Col1 = 31
AND "Desc" = 'xxxxxx';
EDIT:
Based on your comment then you need to apply the CASE logic to each column returned in the SELECT statement that you wish to obscure.
SELECT CASE WHEN Col1 = 31 and "DESC" = 'yyyyy'
THEN NULL
ELSE ColA
END AS ColA_,
/* Repeat for each column you wish to "delete" */
FROM MyDB.MyTable;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/11745334",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: HttpModule fires several times I have ASP.NET MVC 4 with an HttpModule. I am aware that module's Init method may be called several times, once for each HttpApplication object, but I expect the actual BeginRequest event to fire only ONCE for each incoming web request. That's not what's happening.
I noticed that BeginRequest consistently fires twice for a simple POST I am sending to the server. I am sure I am sending only one request -- there are no images.
Why would BeginRequest be called multiple times for a simple POST to the server?
Thanks.
A: Its fire on every request, it may be images, scripts, handlers, pages, what ever.
If you debug and step on it you can see what files calls it. You can also place this line inside to see what is calling it live.
Debug.Write("call from: " + HttpContext.Current.Request.Path);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/13932742",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Why forwarding unit in MIPS processor does not store always data from WB stage to ID stage? Hey to everyone I am trying to understand 5 stage pipeline MIPS with forwarding unit
So I found a problem which has raw data hazards
The problem is the following :
Ι1 and $1, $1, $2
Ι2 add $2, $1, $2
Ι3 lw $2, –20($3)
Ι4 sub $4, $2, $4
Dependencies : (Ι1, Ι2, $1) , (Ι3, Ι4, $2)
the pipeline with hazards is the following :
enter image description here
The solution of the forwarding unit is :
enter image description here
But I could not understand why forwarding unit store data from (EX to EX , WB to EX) And not to WB to ID for these two dependencies
Also why we have to use a NOP instruction between I3 and I4 instruction
My solution is the following :
enter image description here
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73705644",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: redis redis.client rq Queue job.result # => None I'm trying to figure out rq queuing with redis. I have simple test_job function which I want to use in queue.
def test_job():
return "OK"
And the script taken mainly from rq documentation:
#!/usr/bin/env python
import redis.client
from rq import Queue
import time
from helpers import test_job
def main():
q = Queue(connection=redis.client.Redis('localhost',6379))
job = q.enqueue(test_job)
print job.result # => None
while not job.result:
time.sleep(2)
print job.result # => None
if __name__ == "__main__":
main()
The problem is that I'm not leaving while loop. job.result remains None. However, redis connection seems to work, according to log:
[1279] 30 Dec 12:08:20.041 - 0 clients connected (0 slaves), 612560 bytes in use
[1279] 30 Dec 12:08:21.371 - Accepted 127.0.0.1:58541
[1279] 30 Dec 12:08:25.337 - DB 0: 23 keys (0 volatile) in 32 slots HT.
[1279] 30 Dec 12:08:25.337 - 1 clients connected (0 slaves), 633664 bytes in use
A: Did you start a worker to process the task?
It looks like no worker is running (as only your client connected to Redis). Run rqworker from your project's root.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/14090215",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to use excel_sheets() for multiple .xls files in a folder? I'm trying to use excel_sheets() from the read.xl package to get the workbook info from multiple Excel sheets in a folder. Here's the folder:
I can use excel_sheets() to process one file, and then then continue with lapply():
library(readxl)
path = "/Users/cgill22/Desktop/GTEx_WGCNA_sex_combined_signed/Adipose-Subcutaneous_0.8125Pathway_Enrichment_all_results.xls"
sheets <- excel_sheets(path)
data <- lapply(sheets, function(x) read_excel(path, sheet = x))
names(data) <- sheets
But when I try to create a for loop using a data frame with the files, I get this error:
files <- data.frame(filename = list.files("/Users/cgill22/Desktop/GTEx_WGCNA_sex_combined_signed",
pattern = "*.xls",
full.names = TRUE))
for(i in files){
sheets <- excel_sheets(i)
data <- apply(sheets, function(x) read_excel(i, sheet = x))
names(data) <- sheets
Error: `path` must be a string
How would I create a for loop that generates a string path for each file in this folder?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/74272499",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Insert static rows in Target Table
So I have a scenario based on the picture attached.
In my source table, I only have TIER 1 available value and will be inserted in the target table.
But the requirement requires that even if TIER 2 to 7 is not available, I should still insert it to the target table regardless if there is a value or not, and append a value of 0.
I tried making another flow and putting the condition in router but it seems to be tedious as the Department is dynamic and can be multiple depending on the source.
I would like to ask if there is another approach for this
A: There are two ways you can do it that I know of. First is to use a java transformation, where you can check how many rows are coming from source and generate the remaining using the generateRow() function within a for loop. The second option is to use a active lookup transformation, with a query like below. In the condition put rec_cnt>=src_cnt where src_cnt being the number records from source.
select rownum as rec_cnt
from dual
connect by rownum <= 7
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/55162296",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Understanding scope correctly in PHP (versus Javascript) I know that scope works differently in PHP and in Javascript.
When I first started learning Javascript (after a couple of years learning PHP), I did not initially realise that variables declared outside a function were also accessible from inside the function.
Now (after a few years of focusing much more on Javascript), I am stumped by how to return a PHP function-scope variable back to the extra-function environment.
Example:
$myArray = array();
function addItemsToMyArray($myArray) {
$myArray[] = 'apple';
$myArray[] = 'banana';
$myArray[] = 'coconut';
return $myArray;
}
addItemsToMyArray($myArray);
echo count($myArray); /* Gives 0 */
Why does count($myArray) give 0 instead of 3?
A: The function addItemsToMyArray() has correctly been set up to return the array to the main PHP code but you forgot to catch that return value and put it in a variable. One way to write this code and make the difference easier to see could be like this:
function addItemsToMyArray($tmpArray) {
$tmpArray[] = 'apple';
$tmpArray[] = 'banana';
$tmpArray[] = 'coconut';
return $tmpArray;
}
$myArray = array();
$myArray = addItemsToMyArray($myArray);
echo count($myArray); /* Gives 3 */
The variable used inside the function is a different variable than the $myArray variable outside of the function.
A: Unless you specify otherwise, function/method arguments are pass-by-value, meaning you get a copy of them inside the function. If you want the function to change the variable that was passed to it, you need to pass-by-reference. As described here:
By default, function arguments are passed by value (so that if the
value of the argument within the function is changed, it does not get
changed outside of the function). To allow a function to modify its
arguments, they must be passed by reference.
To have an argument to a function always passed by reference, prepend
an ampersand (&) to the argument name in the function definition:
Note the ampersand before $array in the doc page for sorting functions like asort() and ksort():
bool asort ( array &$array [, int $sort_flags = SORT_REGULAR ] )
bool ksort ( array &$array [, int $sort_flags = SORT_REGULAR ] )
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/47096660",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to create an event with Setup in vue js? So I want to update my graph which I am creating using v-network-graphs, when a user enters a value in the input box.
setup(props,oa) {
const nodes={}
const edges={}
const { prac } = toRefs(props)
const n = reactive( prac.value )
// const n= prac.length
for (let i = 0; i < n.length; i++) {
nodes[`${n[i].oa}`] = {
name: `${n[i].oa}`
},
nodes[`${n[i].Title}`] = {
name: `${n[i].Title}`
};
}
for (let i=0;i<n.length;i++){
edges[`edge${i}`]={
source:`${n[i].oa}`,
target:`${n[i].Title}`
}
}
return { nodes, edges }
}
So basically I want to replace oa with the value that the user enters and update the graph.
I tried writing a method and updating the graph but it's not working, the graph just shows undefined as oa doesn't exist in the data.
This is my div
<div>
<GraphWorld :nodes='nodes' :edges='edges'/>
<input @keyup.enter="o" v-model="name2" />
</div>
and this is my method (I have tried writing the method in other ways to, nothing is working)
methods: {
o(){
this.oa = this.name2
console.log(this.oa)
}
}
I am new to javascript and vue, I will be grateful if you guys have any suggestions.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/72355731",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Does a javascript library for parsing URL path segment (matrix) parameters exist? Given the URL:
var urlString = "http://somehost:9090/cars;color=red;make=Tesla?page=1&perPage=10"
I'd like some javascript (node) library which i can use to get the matrix parameters (color and make) for the cars path segment, for example:
var url = URL.parse(urlString)
url.pathSegments["cars"].params
would yield
{
"color": "red",
"make": "Tesla"
}
Also, ideally such a library should take into consideration proper decoding for path segment parameters, which is not the same decoding as query parameters.
These params (along with a bunch of other useful information concerning urls) are described in more detail in the following article:
https://www.talisman.org/~erlkonig/misc/lunatech%5Ewhat-every-webdev-must-know-about-url-encoding/
I've done plenty of googling, but have come up empty, but hopefully I'm just blind!
A: I found URI.js. However, if you don't want to use that library, I think this function will do what you're looking for (not so sure about decodeURIComponent):
var urlString = "http://somehost:9090/cars;color=red;make=Tesla?page=1&perPage=10"
var getParams = function (urlString) {
return decodeURIComponent(urlString) // decode the URL (?)
.match(/\/((?!.+\/).+)\?/)
// the regex looks for a slash that is NOT
// followed by at least one character and eventually another slash
// given var urlString = "http://somehost:9090/cars;color=red;make=Tesla?page=1&perPage=10"
// we don't want -------^ ^ ^
// we want this slash ------| |
// all the way until this question mark --------------------------------|
// regex explanation:
/*
\/ first slash
( open capturing group
(?! lookbehind for NOT
.+\/ any character followed by a slash (/)
)
.+ capture one or more characters (greedy) past
) the close of the capturing group and until
\? a question mark
*/
[1] // match will return two groups, which will look like:
// ["/cars;color=red;make=Tesla?", "cars;color=red;make=Tesla"]
// we want the second one (otherwise we'd have to .slice(1,-1) the string)
.split(";")
// split it at the semicolons
// if you know you're always going to have "name" followed by a semicolon,
// you might consider using .slice(1) on this part, so you can get rid of
// the if statement below (still keep the p[c[0]] = c[1] part though )
.reduce(function (p, c) {
// split it at the equals sign for a key/value in indices 0 and 1
c = c.split("=");
// if the length is greater than one, aka we have a key AND a value
// e.g., c == ["color", "red"]
if (c.length > 1) {
// give the previous object a key of c[0] equal to c[1]
// i.e., p["color"] = "red"
p[c[0]] = c[1];
}
return p; // return p, so that we can keep adding keys to the object
}, {}); // we pass an object, which will act as p on the first call
}
console.log(getParams(urlString)); // { color: "red", make: "Tesla" }
Instead of the regular expression, you can also use what I posted in my comment above:
urlString.split("?")[0].split("/").pop().split(";").reduce( /* etc */)
Now I want a Tesla…
A: I recently wrote a Node.js Middleware for parsing Matrix Parameters.
I've specified the rules that it follows and the format of the output that it generates.
So for instance, here's what your app.js looks like:
let app = require ('express') (),
matrixParser = require ('matrix-parser');
app.use (matrixParser ());
app.get ('/cars*', (req, res) => {
//notice the asterisk after '/cars'
console.log (JSON.stringify (req.matrix, null, 2));
res.send ('Thanks=)');
});
app.listen (9090);
and your URI looks like:
http://localhost:9090/cars;color=red;make=Tesla?page=1&perPage=10
then, you could test the matrix parser feature with curl like:
curl "http://localhost:9090/cars;color=red;make=Tesla?page=1&perPage=10"
Then req.matrix is set to the following object:
[
{
"segment": "cars",
"matrix": {
"color": "red",
"make": "Tesla"
}
}
]
The query strings (page, per_page) are left untouched (you can see this by simply writing req.query)
Probably too late in writing an answer at this point, but it might still come handly in future.
Here's the repo:
https://github.com/duaraghav8/matrix-parser
npm install matrix-parser
EDIT: Sorry for not providing a more elaborate answer with code earlier, this is my first contribution to SO, I'll take some time to get the hang of it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/29001857",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Ending a Loop with EOF (without enter) i am currently trying to end a while loop with something like this:
#include <stdio.h>
int main()
{
while(getchar() != EOF)
{
if( getchar() == EOF )
break;
}
return 0;
}
When i press CTRL+D on my Ubuntu, it ends the loop immediately. But on Windows i have to press CTRL+Z and then press ENTER to close the loop. Can i get rid of the ENTER on Windows?
A: The getchar behavior
For linux the EOF char is written with ctrl + d, while on Windows it is written by the console when you press enter after changing an internal status of the CRT library through ctrl + z (this behaviour is kept for retrocompatibility with very old systems). If I'm not wrong it is called soft end of file. I don't think you can bypass it, since the EOF char is actually consumed by your getchar when you press enter, not when you press ctrl + z.
As reported here:
In Microsoft's DOS and Windows (and in CP/M and many DEC operating systems), reading from the terminal will never produce an EOF. Instead, programs recognize that the source is a terminal (or other "character device") and interpret a given reserved character or sequence as an end-of-file indicator; most commonly this is an ASCII Control-Z, code 26. Some MS-DOS programs, including parts of the Microsoft MS-DOS shell (COMMAND.COM) and operating-system utility programs (such as EDLIN), treat a Control-Z in a text file as marking the end of meaningful data, and/or append a Control-Z to the end when writing a text file. This was done for two reasons:
*
*Backward compatibility with CP/M. The CP/M file system only recorded the lengths of files in multiples of 128-byte "records", so by convention a Control-Z character was used to mark the end of meaningful data if it ended in the middle of a record. The MS-DOS filesystem has always recorded the exact byte-length of files, so this was never necessary on MS-DOS.
*It allows programs to use the same code to read input from both a terminal and a text file.
Other information are also reported here:
Some modern text file formats (e.g. CSV-1203[6]) still recommend a trailing EOF character to be appended as the last character in the file. However, typing Control+Z does not embed an EOF character into a file in either MS-DOS or Microsoft Windows, nor do the APIs of those systems use the character to denote the actual end of a file.
Some programming languages (e.g. Visual Basic) will not read past a "soft" EOF when using the built-in text file reading primitives (INPUT, LINE INPUT etc.), and alternate methods must be adopted, e.g. opening the file in binary mode or using the File System Object to progress beyond it.
Character 26 was used to mark "End of file" even if the ASCII calls it Substitute, and has other characters for this.
If you modify your code like that:
#include <stdio.h>
int main() {
while(1) {
char c = getchar();
printf("%d\n", c);
if (c == EOF) // tried with also -1 and 26
break;
}
return 0;
}
and you test it, on Windows you will see that the EOF (-1) it is not written in console until you press enter. Beore of that a ^Z is printed by the terminal emulator (I suspect). From my test, this behavior is repeated if:
*
*you compile using the Microsoft Compiler
*you compile using GCC
*you run the compiled code in CMD window
*you run the compiled code in bash emulator in windows
Update using Windows Console API
Following the suggestion of @eryksun, I successfully written a (ridiculously complex for what it can do) code for Windows that changes the behavior of conhost to actually get the "exit when pressing ctrl + d". It does not handle everything, it is only an example. IMHO, this is something to avoid as much as possible, since the portability is less than 0. Also, to actually handle correctly other input cases a lot more code should be written, since this stuff detaches the stdin from the console and you have to handle it by yourself.
The methods works more or less as follows:
*
*get the current handler for the standard input
*create an array of input records, a structure that contains information about what happens in the conhost window (keyboard, mouse, resize, etc.)
*read what happens in the window (it can handle the number of events)
*iterate over the event vector to handle the keyboard event and intercept the required EOF (that is a 4, from what I've tested) for exiting, or prints any other ascii character.
This is the code:
#include <windows.h>
#include <stdio.h>
#define Kev input_buffer[i].Event.KeyEvent // a shortcut
int main(void) {
HANDLE h_std_in; // Handler for the stdin
DWORD read_count, // number of events intercepted by ReadConsoleInput
i; // iterator
INPUT_RECORD input_buffer[128]; // Vector of events
h_std_in = GetStdHandle( // Get the stdin handler
STD_INPUT_HANDLE // enumerator for stdin. Others exist for stdout and stderr
);
while(1) {
ReadConsoleInput( // Read the input from the handler
h_std_in, // our handler
input_buffer, // the vector in which events will be saved
128, // the dimension of the vector
&read_count); // the number of events captured and saved (always < 128 in this case)
for (i = 0; i < read_count; i++) { // and here we iterate from 0 to read_count
switch(input_buffer[i].EventType) { // let's check the type of event
case KEY_EVENT: // to intercept the keyboard ones
if (Kev.bKeyDown) { // and refine only on key pressed (avoid a second event for key released)
// Intercepts CTRL + D
if (Kev.uChar.AsciiChar != 4)
printf("%c", Kev.uChar.AsciiChar);
else
return 0;
}
break;
default:
break;
}
}
}
return 0;
}
A: while(getchar() != EOF)
{
if( getchar() == EOF )
break;
}
return 0;
Here it is inconsistent.
If getchar() != EOF it will enter the loop, otherwise (if getchar() == EOF) it will not enter the loop. So, there is no reason to check getchar() == EOF inside the loop.
On the other hand, you call getchar() 2 times, you wait to enter 2 characters instead of only 1.
What did you try to do ?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/46950315",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: how to instantiate objects inside the class to be tested is an abstract class in Junit testing? I have a class below for which I want to write a unit test
abstract class ProductImpl{
@Inject DataServices ds; // using Guice
public Response parse(String key, Long value){
Response res = ds.getResponseObject(); // Response object is created using DataServices object
res.id = key;
res.code = value;
}
}
And I have a test as below
class ProductImplTest{
@InjectMocks ProductImpl impl;
Map<String, Long> map;
@Before
map.put("abc", 10L);
map.put("xyz", 11L);
}
@Test
public void test(){
for(String key: map.keySet()){
Response res = impl.parse(key, map.get(key));
// and check if fields of Response object are set correctly i.e res.id is abc and value is 10L
}
}
But when i debug the test and control goes to parse method , DataServices object ds is null. How to instantiate this object through test . I do not want to use mocking, I want real response objects to be created and test the values set in them.
A: You can use Mockito
@RunWith(MockitoJUnitRunner.class)
class ProductImplTest {
@Mock DataService dService;
@InjectMocks ProductImpl sut;
@Test
public void test() {
ResponseObject ro = new ResponseObject();
String string = "string";
Long longVal = Long.valueOf(123);
sut.parse("string", longVal);
verify(dService).getResponseObject();
assertThat(ro.getId()).isEqualTo("string");
// you should use setters (ie setId()), then you can mock the ResponseObject and use
// verify(ro).setId("string");
}
}
EDIT:
With ResponseObject being an abstract class or preferably an interface, you'd have
interface ResponseObject {
void setId(String id);
String getId();
// same for code
}
and in your test
@Test public void test() {
ResponseObject ro = mock(ResponseObject.class);
// ... same as above, but
verify(dService).getResponseObject();
verify(ro).setId("string"); // no need to test getId for a mock
}
A: Try with constructor injection:
class ProductImpl{
DataServices ds;
@Inject
public ProductImpl(DataServices ds) {
this.ds = ds;
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/59051580",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: HTML div with A4 dimensions is larger than A4 I set the size of a parent div to A4 (size="21cm 29.7cm"). However, in Chrome print preview, with A4 and no margins, the HTML page won't fit on A4. I have to scale it to 80%.
Is there something in my HTML causing this? I expected the size="21cm 29.7cm" to force the page to be A4.
UPDATE I found this:
CSS to set A4 paper size
And tried the below CSS, but not working:
@page {
size: A4;
margin: 0;
}
@media print {
html, body {
width: 210mm;
height: 297mm;
}
}
HTML:
<!Doctype>
<html>
<head>
<style>
.background
{
position: relative;
top: 0;
left: 0;
}
.text
{
position: absolute;
top: 0px;
left: 0px;
width: 1449px;
height: 2050px;
}
</style>
</head>
<body>
<div style="position: relative; left: 0; top: 0;" size="21cm 29.7cm">
<img src='page0022.jpg' class="background"/>
<img src='0022.svg' class="text"/>
</div>
</body>
</html>
A: Read about size: https://developer.mozilla.org/en-US/docs/Web/CSS/@page/size
Add these code to your HTML file:
<div class="page">...</div>
Add these code to your CSS file
@page {
size: 21cm 29.7cm;
margin: 30mm 45mm 30mm 45mm;
/* change the margins as you want them to be. */
}
@media print {
body{
width: 21cm;
height: 29.7cm;
margin: 30mm 45mm 30mm 45mm;
/* change the margins as you want them to be. */
}
}
In case you think you really need pixels (you should actually avoid using pixels), you will have to take care of choosing the correct DPI for printing:
*
*72 dpi (web) = 595 X 842 pixels
*300 dpi (print) = 2480 X 3508 pixels
*600 dpi (high quality print) = 4960 X 7016 pixels
Yet, I would avoid the hassle and simply use cm (centimetres) or mm (millimetres) for sizing as that avoids rendering glitches that can arise depending on which client you use.
A: You should define size within an @page rule in your CSS stylesheet. It is not intended to be an attribute as you have done in your example.
https://developer.mozilla.org/en-US/docs/Web/CSS/@page
@page {
size: A4;
}
size as an attribute is used to define the width of <input> and <select> elements, either by pixels or number of characters depending on type
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/65862676",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Serilog and ASP.NET Core enrich `WithUserName` and `WithHttpRequestUserAgent`? Is there a way to enrich Serilog log data in ASP.NET Core 2.1 application, similar to how enrichers WithUserNameand WithHttpRequestUserAgent work for classic ASP.NET (System.Web)?
I tried implementing ILogEventEnricher interface, but it does not work, because I am not able to gain access to RequestContext from my custom enricher.
A: As pointed out in the comments it seems like Add Username into Serilog would serve your purpose and would also be the duplicate of this issue.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/51420093",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Required field 'reversed' was not found in serialized data I have this code:
sliceRange.Start = UTF8StringToBytes(strStart)
sliceRange.Finish = UTF8StringToBytes(strFinish)
sliceRange.Reversed = True
sliceRange.Count = intCount
predicate.Slice_range = sliceRange
Dim results As List(Of ColumnOrSuperColumn) = client.get_slice(UTF8StringToBytes(rowKey), columnFamily, predicate, ConsistencyLevel.ONE)
When I use this code this results in the following error from cassandra / thrift:
Required field 'reversed' was not found in serialized data!
What's wrong?
A: You appear to have an issue with the underlying generated Thrift code. Unless you have a specific reason to do so, using Thrift directly to access Cassandra is not recommended. There are many client libraries available that will abstract this for you.
Having said that, I have used the Thrift-generated C# code to write my own library in the past, and have not run into this issue. Perhaps your problem has something to do with your use of VB? If you have some reason to use Thrift directly, you might try the same code in C# to see if that resolves the issue. If not, make sure you have the right versions of Cassandra and Thrift, as incompatibilities there can cause issues such as this.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/13382869",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: silex and twig css cache issues - odd behavior I've run into a very frustrating bug. I can't reload changes in my css file.
style.css seen in PhpStorm looks like:
body {
background-color: blue;
}
Yet seen in Chrome shows:
body {
background-color: green;
}
Here's the odd behaviour: If I change style.css to "foo bar testing"
Chrome displays it as:
body {
backgrou
And also, if I dump a lot of arbitary text into style.css, Chrome displays it as:
body {
background-color: green;
}
���������������������������������������������������������������...etc
So Chrome recognizes that it's changed, but is fixed with the original text.
My twig options are:
$app['twig.options'] = array('cache' => false, 'auto_reload' => true);
I've also tried appending ?{{ random() }} to style.css in a effort to force reloading with no joy.
A: Turns out the issue is with running Nginx withing VirtualBox.
in /etc/nginx/nginx.conf sendfile needs to be off
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/29942153",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Auto adjusting web page to screen size (HTML) I have tried several different sources on the Internet. I am not using bootstrap; I enjoy doing my site from scratch. It helps me program.
I can't get my web page to auto adjust to the screen size. For example if you make the browser smaller the page collapse nice and neat.
I tried these codes from here: http://www.gonzoblog.nl/2013/01/16/11-useful-css-code-snippets-for-responsive-web-design/
but my web page doesn't collapse like the example.
<!--
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="HandheldFriendly" content="true">
-->
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="sunpacking.css">
<title>Sun Packing WebSite</title>
<link href="../../Documents/Sun Packing/sun.css" rel="stylesheet" type="text/css" />
<style type="text/css">
.div1 {
margin: 20px;
}
</style>
</head>
<body>
<div style="width:800px; margin:0 auto;">
<div id="container">
data
</div>
/*Sun Packing CSS */
/*
body{
padding:0px;
margin:0px;
width:100%;
height:100%;
}
*/
#container {
float: none;
border-style: dashed;
border-color: red;
width: 100%; /* 95px*/
height: 100%; /*1400px*/
color: red;
}
A: You could start by closing your HTML containers, and giving a good example of what you've tried.
If you set an explicit width, width: 800px;, that's the width it will be rendered at.
Try setting the container's max-width for that and set the width to expand to that
The way that I usually do it:
.container {
max-width: 800px;
width: 100%;
}
A: Try using percentages instead of pixels. Pixels will give you a fixed width. Percentage with keep thing proportional.
Here is a good article to help you understand what the different measurements mean.
Once you understand what they mean, you should be able to make a better selection depending on the usage you expect.
https://www.w3schools.com/cssref/css_units.asp
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/25817589",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-6"
}
|
Q: BeginForm overload that accepts RouteValueDictionary and Dictionary as htmlParameters I came across this old question from 2009 that is asking the exact same question as I am now, but the solution no longer appears to work. I am currently using MVC 5.
I am calling BeginForm like this:
helper.BeginForm("Edit", controllerName, new { id }, FormMethod.Post, htmlAttributes.Attributes);
htmlAttributes.Attributes is Dictionary<string, object>. The form ends up generating this markup:
<form
comparer="System.OrdinalComparer"
count="2"
keys="System.Collections.Generic.Dictionary`2+KeyCollection[System.String,System.Object]"
values="System.Collections.Generic.Dictionary`2+ValueCollection[System.String,System.Object]"
action="/CustomerDocumentTypeAdmin/Edit/1"
method="post">
You can clearly see that it's reflecting over the dictionary class itself and using its properties as the HTML attributes.
Previously, I was declaring my attributes like this:
new { id = "formId" }
I changed it to a dictionary because I need to be able to modify the value collection at any stage in the call stack.
The HtmlHelper extension overload that my call resolves to is this:
MvcForm BeginForm(this HtmlHelper htmlHelper, string actionName, string controllerName, object routeValues, FormMethod method, object htmlAttributes);
The signature of my call certainly matches it, and the question I linked to seems to as well. Not sure why it's not working for me now.
A: So I found an overload that I can use which means I need to change the type of one of my parameters. This is the overload:
MvcForm BeginForm(this HtmlHelper htmlHelper, string actionName, string controllerName, RouteValueDictionary routeValues, FormMethod method, IDictionary<string, object> htmlAttributes);
This means I need to pass new { id } into a RouteValueDictionary like so:
helper.BeginForm("Edit", controllerName, new RouteValueDictionary(new { id }), FormMethod.Post, htmlAttributes.Attributes)
I could also pass a dictionary into the RouteValueDictionary, but not sure how marginal the performance difference would be. At any rate, this now works.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/43941585",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do I populate data in Entity Framework code first on database creation? I'm using code first entity framework and I would like to know how to run some code when the database is being created so that I can populate my database with some data. (note that I'm asking for on database creation, not everytime the application starts).
Does anybody know if there's a method or event I can use for this?
A: You can use custom database initializer - it means implementing IDatabaseInitializer and registering this initializer by calling Database.SetInitializer.
A: I'd like to add to Ladislav's answer. The article he pointed to shows how to create an initializer but does not show how to use an initializer to populate a newly created database. DbInitializer has a method called Seed that you can overwrite. You can see an example of how to use this in this article (or video if you prefer, which is on the same page) http://msdn.microsoft.com/en-us/data/hh272552
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/4591014",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: Show serializer attribute only for current user and certain role I need the auth_token attribute to only be outputted for the current authenticated user.
My User controller has
class Api::V1::UsersController < ApplicationController
before_action :authenticate_with_token!, only: [:show, :create, :update, :destroy]
respond_to :json
def show
authorize User
respond_with User.find(params[:id])
end
...
The serializer:
class UserSerializer < ActiveModel::Serializer
attributes :id, :email, :created_at, :updated_at, :auth_token
has_one :role
The http request goes something like:
GET http://api.domain.com/users/1
With Headers: Accept, Content-Type and Authorization
(Authorization is the auth_token).
What's returned is:
{
"user": {
"id": 1,
"email": "[email protected]",
"created_at": "2015-12-01T07:36:55.276Z",
"updated_at": "2015-12-01T07:36:55.276Z",
"auth_token": "8xxoZjZyx313cx2poabz",
"role": {
"id": 1,
"name": "admin",
"created_at": "2015-12-01T07:36:55.190Z",
"updated_at": "2015-12-01T07:36:55.190Z"
}
}
}
I only want auth_token to be shown if the user that it belongs to requests it or a user with the super role requests it. I have a method in my user model that can check for a role like has_role? :super.
In the serializer I've tried this but it was really just a shot in the dark. I have no idea how to accomplish this:
...
def filter(keys)
if scope.auth_token == :auth_token
keys
else
keys - [:auth_token]
end
end
Edit
Using active_model_serializer version 0.9.3
A: Saw this in the source and something clicked in my head.
Changing the filter method above to the following gave me the desired results.
def filter(keys)
if (scope == object) or scope.has_role?(:super)
keys
else
keys - [:auth_token]
end
end
Hope this helps anyone else using version 0.9.x
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/34016598",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Storing function returns in a table in R (quant finance) For the purposes of this question, I would like to construct a data frame or similar to be able to "stack rank" and sort various metrics that are generated from functions.
Let's take an example from the Performance Analytics package:
*
*I have the close-close returns of 3 indices from 2001: SPX, NASDAQ (CCMP) and EuroStoxx (SX5E).
*I'd like to get the 95% 1day VaR for each of these, place them into a table and then sort them from high to low (or low to high etc).
To illustrate my question, I will use the table.DownsideRisk function in the Performance Analytics package rather than just calling VaR().
So, I can get these results individually:
SPX.cc
Semi Deviation 0.0095
Gain Deviation 0.0096
Loss Deviation 0.0102
Downside Deviation (MAR=210%) 0.0142
Downside Deviation (Rf=0%) 0.0094
Downside Deviation (0%) 0.0094
Maximum Drawdown 0.5678
Historical VaR (95%) -0.0203
Historical ES (95%) -0.0317
Modified VaR (95%) -0.0193
Modified ES (95%) -0.0273
Or I can place them all in an xts object together and then run table.DownsideRisk:
SPX.cc CCMP.cc SX5E.cc
Semi Deviation 0.0095 0.0114 0.0111
Gain Deviation 0.0096 0.0117 0.0114
Loss Deviation 0.0102 0.0116 0.0113
Downside Deviation (MAR=210%) 0.0142 0.0161 0.0161
Downside Deviation (Rf=0%) 0.0094 0.0113 0.0112
Downside Deviation (0%) 0.0094 0.0113 0.0112
Maximum Drawdown 0.5678 0.6103 0.6219
Historical VaR (95%) -0.0203 -0.0260 -0.0249
Historical ES (95%) -0.0317 -0.0370 -0.0372
Modified VaR (95%) -0.0193 -0.0231 -0.0237
Modified ES (95%) -0.0273 -0.0293 -0.0330
but, let's say I ran the individual example either as an lapply or for loop as part of a broader analytical program - what I would like to do is extract each of the Historical VaR (95%) figures from the output of the table.DownsideRisk function as the loop / apply function is running on each element and place those extracted values in a table in the .GlobalEnv() and then sort that table along the lines of (Low to High)
Historical VaR (95%)
SPX.ccl -.0203
SX5E.ccl -.0249
CCMP.ccl -.0260
I know this will seem rather basic to data frame / table users but any assistance is much appreciated.
Cheers.
A: I'm not sure what your intent is with the GlobalEnv, but this might be of help:
swapped = data.frame(t(xts))
ordered = swapped[with(swapped, order(Historical.VaR..95..)),]
result = subset(ordered, select=Historical.VaR..95..)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/17847219",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Is mat-expansion-panel lazy rendering broken? See this Stackblitz.
Angular Material mat-expansion-panel allows lazy rendering,
<mat-expansion-panel>
<mat-expansion-panel-header>
This is the expansion title
</mat-expansion-panel-header>
<ng-template matExpansionPanelContent>
Some deferred content
</ng-template>
</mat-expansion-panel>
When rendered inside a hidden component, for example, a closed mat-sidenav, the mat-expansion-panel renders incorrectly (Stackblitz example):
This is a mess in many ways, not least because I define mat-expansion-panel to be collapsed (expanded="false"):
<mat-expansion-panel expanded="false">
<mat-expansion-panel-header>
<mat-panel-title>
<span>First</span>
</mat-panel-title>
</mat-expansion-panel-header>
<ng-template matExpansionPanelContent>
<!-- Deferred initialization until the panel is open. -->
<span>You shouldn't see me yet!</span></ng-template>
<mat-action-row>
<button mat-button>Click me</button>
</mat-action-row>
</mat-expansion-panel>
Clicking the expansion-panel's header expands the panel (as it should) and renders the content correctly:
Interestingly, collapsing the panel shows how the panel should have rendered initially:
Both my Stackblitz example and the screenshots in this question show two expansion panels within a mat-accordion:
<mat-tab-group>
<mat-tab label="Empty">
<p>This is an empty tab</p>
</mat-tab>
<mat-tab label="Accordion">
<div class="mat-typography">
<mat-accordion>
<mat-expansion-panel expanded="true">
<mat-expansion-panel-header>
<mat-panel-title>
<span>First</span>
</mat-panel-title>
</mat-expansion-panel-header>
<ng-template matExpansionPanelContent>
<!-- Deferred initialization until the panel is open. -->
<span>You shouldn't see me yet!</span></ng-template>
<mat-action-row>
<button mat-button>Click me</button>
</mat-action-row>
</mat-expansion-panel>
<mat-expansion-panel expanded="false">
<mat-expansion-panel-header>
<mat-panel-title>
<span>Second</span>
</mat-panel-title>
</mat-expansion-panel-header>
<ng-template matExpansionPanelContent>
<!-- Deferred initialization until the panel is open. -->
<span>Shouldn't see me either!</span></ng-template>
<mat-action-row>
<button mat-button>Click me</button>
</mat-action-row>
</mat-expansion-panel>
</mat-accordion>
</div>
</mat-tab>
</mat-tab-group>
The CSS just adds some colour for debugging:
mat-expansion-panel {
background-color: grey;
}
mat-expansion-panel:first-child mat-expansion-panel-header {
background-color:red;
}
mat-expansion-panel:last-child mat-expansion-panel-header {
background-color:blue;
}
mat-expansion-panel button {
background-color: yellow;
}
The mat-sidenav is about as bare-bones as it's possible to get:
<mat-sidenav-container>
<mat-sidenav #snav class="mat-elevation-z8">
<app-side-menu></app-side-menu>
</mat-sidenav>
<mat-sidenav-content>
<div>
<button mat-icon-button (click)="snav.toggle()">
<mat-icon>menu</mat-icon>
</button>
</div>
</mat-sidenav-content>
</mat-sidenav-container>
Update
A lengthy discussion on this has taken place on GitHub, issues/5269. While the issue remains open, it is being reported that the issue was fixed in angular/material v7.
A: The problem is all about *ngIf. First time its not able to make it true. that's why I am setting it true using setTimeout().
If you still have issue do let me know. I will try to help.
Working link
https://stackblitz.com/edit/deferred-expansion-panel-broken-b2vurz?file=app%2Fside-menu%2Fside-menu.component.ts
A: This is definitely problem with 5.x version, this should work out of the box.
Nothing worked if I had expansion panel [expanded] property set in html or initialised during constructor or component life cycle events.
Even working example from stackblitz is not working locally inside dynamic component!
https://stackblitz.com/angular/bbjxooxpqmy?file=app%2Fexpansion-overview-example.html
However if structural directives are used with async data / Observables that are emitting after component is initialised and rendered it will work...
Using interval or timeouts works, but its not good solution because load and render times differ greatly on different devices such as desktop and mobile!
A: Just a note on this, that it might be because you need to wrap the expanded property in square brackets, otherwise you are passing in a string of "false", which will evaluate to true.
It should be:
<mat-expansion-panel [expanded]="false">
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/49498639",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Display two images with SRCSET at different screen size issue I have looked over examples online, yet I believe I am overlooking something. I have two similar images that need to be rendered when the screen is at a different size. One image at 1440px screen size and one at 375px screen size. Right now with my code I have set the initial source to render the "mobile view" of the image, and with the srcset of the desktop view image at 1440w. When I load up live server it shows the desktop image, and not the initial source of the mobile view. So it seems to be working but missing a step.. any tips are greatly appreciated!
<img
class="future__container--img"
src="./images/illustration-editor-mobile.svg"
srcset="./images/illustration-editor-desktop.svg 1440w"
alt="illustration-editor-mobile"
/>
So when the browser first loads it is showing the desktop.svg, but when I set the browser to 375px it still displays the desktop.svg. I first had this written in javascript ..
const resizeEditiorImg = () => {
const reswidth = screen.width;
let image = document.querySelector(".future__container--img");
if (reswidth >= 1440) {
image.src = "../images/illustration-editor-desktop.svg";
} else {
image.src = "../images/illustration-editor-mobile.svg";
}
};
window.addEventListener("resize", resizeEditiorImg);
But the issue here is that when the browser first loads on desktop view, it is displaying the mobile image unless the user manually resizes the browser, which is what I believed at first. I hope this post makes sense!
A: This only work in resize browser because this code resizeEditiorImg
you need run this command resizeEditiorImg in your load page.
example
<body onload="resizeEditiorImg()">
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/67511523",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Any way to do conditional including in javascript? We're developing a portal with lots of portlets (independent application within the page/portal). Each portlets have to be independent : They have to be able to run on stand-alone page from within the portal.
We've been ask not to add tons of javascript files to the portal base-page (the one that calls everything). It also comes with dojo (but no one uses it).
Are there any way to load javascript files (including jQuery aka, it can't be the solution) if they are not loaded yet? The answer can use dojo
Right now we though of
if (!window.jQuery) {
document.write('<script src="/Scripts/jquery-1.5.1.min.js" type="text/javascript"><' + '/script>');
}
if (!window.jQuery.ui) {
document.write('<script src="/Scripts/jquery-ui-1.8.11.min.js" type="text/javascript"></scr' + 'ipt>');
}
[...] other includes
The problem with this is that jquery isn't loaded when the jQuery.ui test is done, so an error is thrown and the 2nd file is not loaded.
Edit
Re-writing the issue : The problem is that we could have 4 portlets, each requiring jQuery + jQuery-ui + differents others plugins/files. So they need to all include code to load all those files independantly. But we don't want to load jQuery and jQuery-ui 4 times either.
A: The solution to this seems to be to use separate script blocks. Apparently the document.write will not effect the loading of the scripts, until the script block closes.
That is, try this:
<script>
if (!window.jQuery) {
document.write('<script src="/Scripts/jquery-1.5.1.min.js" type="text/javascript"><' + '/script>');
}
</script>
<script>
if (!window.jQuery.ui) {
document.write('<script src="/Scripts/jquery-ui-1.8.11.min.js" type="text/javascript"></scr' + 'ipt>');
}
</script>
Works for me. Tested in IE and Firefox.
A: I've always injected js files via js DOM manipulation
if (typeof jQuery == 'undefined') {
var DOMHead = document.getElementsByTagName("head")[0];
var DOMScript = document.createElement("script");
DOMScript.type = "text/javascript";
DOMScript.src = "http://code.jquery.com/jquery.min.js";
DOMHead.appendChild(DOMScript);
}
but it's a bit picky and may not work in all situations
A: Misread the question slightly (can and can't look very similar).
If you're willing to use another library to handle it, there are some good answers here.
loading js files and other dependent js files asynchronously
A: Just write your own modules (in Dojo format, which since version 1.6 has now switched to the standard AMD async-load format) and dojo.require (or require) them whenver a portlet is loaded.
The good thing about this is that a module will always only load once (even when a portlet type is loaded multiple times), and only at the first instance it is needed -- dojo.require (or require) always first checks if a module is already loaded and will do nothing if it is. In additional, Dojo makes sure that all dependencies are also automatically loaded and executed before the module. You can have a very complex dependency tree and let Dojo do everything for you without you lifting a finger.
This is very standard Dojo infrastructure. Then entire Dojo toolkit is built on top of it, and you can use it to build your own modules as well. In fact, Dojo encourages you to break your app down into manageable chunks (my opinion is the smaller the better) and dynamically load them when necessary. Also, leverage class hierachies and mixins support. There are a lot of Dojo intrastructure provided to enable you to do just that.
You should also organize your classes/modules by namespaces for maximal manageability. In my opinion, this type of huge enterprise-level web apps is where Dojo truely shines with respect to other libraries like jQuery. You don't usually need such infrastructure for a few quick-and-dirty web pages with some animations, but you really appreciate it when you're building complicated and huge apps.
For example, pre-1.6 style:
portletA.js:
dojo.provide("myNameSpace.portletA.class1");
dojo.declare("myNameSpace.portletA.class1", myNameSpace.portletBase.baseClass, function() { ...
});
main.js:
dojo.require("myNameSpace.portletA.class1");
var myClass1 = new myNameSpace.portletA.class1(/* Arguments */);
Post-1.6 style:
portletA.js:
define("myNameSpace/portletA/class1", "myNameSpace/portletBase/baseClass", function(baseClass) { ...
return dojo.declare(baseClass, function() {
});
});
main.js:
var class1 = require("myNameSpace/portletA/class1");
var myClass1 = new class1(/* Arguments */);
A: Pyramid is a dependency library that can handle this situation well. Basically, you can define you dependencies(in this case, javascript libraries) in a dependencyLoader.js file and then use Pyramid to load the appropriate dependencies. Note that it only loads the dependencies once (so you don't have to worry about duplicates). You can maintain your dependencies in a single file and then load them dynamically as required. Here is some example code.
File: dependencyLoader.js
//Set up file dependencies
Pyramid.newDependency({
name: 'standard',
files: [
'standardResources/jquery.1.6.1.min.js'
//other standard libraries
]
});
Pyramid.newDependency({
name:'core',
files: [
'styles.css',
'customStyles.css',
'applyStyles.js',
'core.js'
],
dependencies: ['standard']
});
Pyramid.newDependency({
name:'portal1',
files: [
'portal1.js',
'portal1.css'
],
dependencies: ['core']
});
Pyramid.newDependency({
name:'portal2',
files: [
'portal2.js',
'portal2.css'
],
dependencies: ['core']
});
Html Files
<head>
<script src="standardResources/pyramid-1.0.1.js"></script>
<script src="dependencyLoader.js"></script>
</head>
...
<script type="text/javascript">
Pyramid.load('portal1');
</script>
...
<script type="text/javascript">
Pyramid.load('portal2');
</script>
So shared files only get loaded once. And you can choose how you load your dependencies. You can also just define a further dependency group such as
Pyramid.newDependency({
name:'loadAll',
dependencies: ['portal1','portal2']
});
And in your html, just load the dependencies all at once.
<head>
<script src="standardResources/pyramid-1.0.1.js"></script>
<script src="dependencyLoader.js"></script>
<script type="text/javascript">
Pyramid.load('loadAll');
</script>
</head>
Some other features that might also help is that it can handle other file types (like css) and also can combine your separate development files into a single file when ready for a release. Check out the details here - Pyramid Docs
note: I am biased since I worked on Pyramid.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/6903215",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Async deep folder deletion recursively I'm working on a chrome extension that lets users create video annotations. I render an iframe with a file system to help the use sort their files. The representation of the file system in chrome.storage is the following:
const storage = {
"ROOT": {
files: [],
folders: [{id: "folder_id", name: "Folder 1"}]
},
"folder_id": {
files: [{id: "file_id", name: "File 1"}],
folders: []
},
"file_id": {
"bookmarks": {}
},
}
Notice that each key in the storage is the id for a folder, file, or the root. Each folder object contains two arrays of objects representing information to be displayed about its nested files and folders. But each object within those arrays does not contain information nested any further. With this structure, I'm trying to figure out how to enable folder deletion asynchronously, maybe using recursion. Here's what I have:
const deapRemoveFolder = async (uuid) => {
const promiseList = [];
const removeFolder = async (uuid) => {
const storage = await chrome.storage.sync.get(uuid);
if (storage[uuid]) {
const { files, folders } = storage[uuid];
// remove all directly nested files from storage
files.forEach((file) =>
promiseList.push(chrome.storage.sync.remove(file.uuid))
);
// remove the key for the folder itself
promiseList.push(chrome.storage.sync.remove(uuid));
// if no more folders are nested, then exist the function
if (folders.length === 0) return;
folders.forEach((folder) => removeFolder(folder.uuid));
}
};
await removeFolder(uuid);
await Promise.all(promiseList);
};
I'm not sure if this is right, and I don't know if I need to include "await" at the last line of the function "removeFolder". I want to make sure that I'm running these promises in parallel because not all of them depend on each other. I can give more clarification if needed.
A: you said: "But each object within those arrays does not contain information nested any further".
So there are not folder inside first-level folder. Did I understand correctly?
If so, why not to read the whole storage with chrome.storage.sync.get,
delete the substructure you want (i.e delete storage.folder_id or delete storage.file_id")
and finally save the trimmed object with chrome.storage.sync.set ?
Note that elements within chrome.storage are stored as a key + value pair, and it is not possible to delete a subtree directly with the remove method.
EDIT
I may have misunderstood one thing.
If you call await chrome.storage.sync.get(null) you get only one item called "storage" or you get one root item with several folders and files items?
If the right answer is one then my previous answer is still valid (you have to cut\trim the object and then save it at the end of the work in the chrome.storage).
If the right answer is two then the thing is simpler because you can directly delete any item using remove method and the object id without bothering recursion and other things.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73159002",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Setting input of Android TV using android App Currently, my HiSense Q8 android TV has a start up screen that has App, Youtube and Netflix icons. There is a series of clicks on the remote I need to go through to have it show input from HDMI input 1. What I'd like to have is an android app causes HDMI input 1 to be displayed on boot, without me need to use the remote (aka, make it behave like a simple monitor). However, I seem to be flubbing the step of selecting the HDMI input programmatically. Any suggestions or pointers to relevant source code examples?
The TV has android 8 and I'm targeting android 7.1.1 in the app.
With the below calls, I can get a list of inputs to iterate through:
TvInputManager mTvInputManager = (TvInputManager) getSystemService(Context.TV_INPUT_SERVICE);
List<TvInputInfo> inputs = mTvInputManager.getTvInputList();
The id fields of the HDMI TvInputInfo items look like:
"com.mediatex.tvinput/.hdmi.HDMInputService/HW4"
"com.mediatex.tvinput/.hdmi.HDMInputService/HW3"
"com.mediatex.tvinput/.hdmi.HDMInputService/HW2"
I then try to set the displayed input to the HW2 using
TvView view = new TvView(this);
view.tune("com.mediatex.tvinput/.hdmi.HDMInputService/HW2", null);
or similarly for HW4, but nothing happens, I still see the app displayed, not the HDMI input. Adding a callback to TvView object doesn't catch any errors. The way I'm creating a TvView object seems a bit suspect to me.
Below is the entire code:
package org.ericdavies.sethdmi1;
import android.app.Activity;
import android.content.Context;
import android.media.tv.TvContentRating;
import android.media.tv.TvTrackInfo;
import android.media.tv.TvView;
import android.os.Bundle;
import android.util.Log;
import android.media.tv.TvContract;
import android.net.Uri;
import android.media.tv.TvInputManager;
import android.media.tv.TvInputInfo;
import android.media.tv.TvInputService;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.List;
/*
* Main Activity class that loads {@link MainFragment}.
*/
public class MainActivity extends Activity {
TvView view;
TextView tv;
StringBuilder sb;
private void setUpButton(final String inputId, int buttonTag) {
Button bt = findViewById(R.id.buttonhw4);
bt.setEnabled(true);
bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
view.setCallback(new TvView.TvInputCallback() {
});
view.tune(inputId, null);
}
});
}
public void reportState(final String state) {
this.runOnUiThread(new Runnable() {
public void run() {
sb.append(state);
tv.setText(sb.toString());
}
});
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TvInputManager mTvInputManager = (TvInputManager) getSystemService(Context.TV_INPUT_SERVICE);
sb = new StringBuilder();
List<TvInputInfo> inputs = mTvInputManager.getTvInputList();
view = new TvView(this);
tv = findViewById(R.id.mytextfield);
view.setCallback(new TvView.TvInputCallback() {
@Override
public void onConnectionFailed(String inputId) {
super.onConnectionFailed(inputId);
reportState("tvview.onconnectionFailed\n");
}
@Override
public void onDisconnected(String inputId) {
super.onDisconnected(inputId);
reportState("tvview.onDisconnected\n");
}
@Override
public void onChannelRetuned(String inputId, Uri channelUri) {
super.onChannelRetuned(inputId, channelUri);
reportState("tvview.onChannelRetuned\n");
}
@Override
public void onTracksChanged(String inputId, List<TvTrackInfo> tracks) {
super.onTracksChanged(inputId, tracks);
reportState("tvview.onTracksChanged\n");
}
@Override
public void onTrackSelected(String inputId, int type, String trackId) {
super.onTrackSelected(inputId, type, trackId);
reportState("tvview.onTrackSelected\n");
}
@Override
public void onVideoUnavailable(String inputId, int reason) {
super.onVideoUnavailable(inputId, reason);
reportState("tvview.onVideoUnavailable\n");
}
@Override
public void onContentBlocked(String inputId, TvContentRating rating) {
super.onContentBlocked(inputId, rating);
reportState("tvview.onContentBlocked\n");
}
}
);
for (TvInputInfo input : inputs) {
String id = input.getId();
if( input.isPassthroughInput() && id.contains("HDMIInputService")) {
sb.append("inputid = " + input.getId() + "\n");
if( id.contains("HW4")) {
setUpButton(id, R.id.buttonhw4);
}
if( id.contains("HW2")) {
setUpButton(id, R.id.buttonHw2);
}
if( id.contains("HW3")) {
setUpButton(id, R.id.buttonhw3);
}
}
}
if( tv != null) {
tv.setText(sb.toString());
}
}
}
The layout is
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/top"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:visibility="visible">
<EditText
android:id="@+id/mytextfield"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:autoText="false"
android:clickable="false"
android:editable="false"
android:ems="10"
android:enabled="false"
android:focusable="false"
android:focusableInTouchMode="false"
android:gravity="start|top"
android:inputType="textMultiLine"
android:selectAllOnFocus="false"
android:text="-----" />
<Button
android:id="@+id/buttonhw4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="hw4" />
<Button
android:id="@+id/buttonHw2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="hw2" />
<Button
android:id="@+id/buttonhw3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:enabled="false"
android:text="hw3" />
</LinearLayout>
The manifest is
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="org.ericdavies.sethdmi1">
<uses-feature
android:name="android.hardware.touchscreen"
android:required="false" />
<uses-feature
android:name="android.software.leanback"
android:required="true" />
<uses-feature
android:name="android.software.LIVE_TV"
android:required="true" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name=".MainActivity"
android:banner="@drawable/app_icon_your_company"
android:icon="@drawable/app_icon_your_company"
android:label="@string/app_name"
android:logo="@drawable/app_icon_your_company"
android:screenOrientation="landscape">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LEANBACK_LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".DetailsActivity" />
<activity android:name=".PlaybackActivity" />
<activity android:name=".BrowseErrorActivity" />
</application>
</manifest>
The build.gradle for the app is
apply plugin: 'com.android.application'
android {
compileSdkVersion 28
defaultConfig {
applicationId "org.ericdavies.sethdmi1"
minSdkVersion 25
targetSdkVersion 28
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'androidx.leanback:leanback:1.0.0'
implementation 'androidx.appcompat:appcompat:1.0.2'
implementation 'com.github.bumptech.glide:glide:3.8.0'
}
A: Instead of null for the second parameter (URI):
TvView view = new TvView(this);
view.tune("com.mediatex.tvinput/.hdmi.HDMInputService/HW2", null);
You need to make and send a valid Uri:
TvView view = new TvView(this)
mInitChannelUri = TvContract.buildChannelUriForPassthroughInput("com.mediatex.tvinput/.hdmi.HDMInputService/HW2")
view.tune("com.mediatex.tvinput/.hdmi.HDMInputService/HW2", mInitChannelUri)
It's a little goofy because you basically send the same input name string twice. But this works for me.
Finally, to be TV brand independent you should use the input id parameter instead of static string constants (left as an exercise for the reader haha)
A: You don't need to use TvView. Just use an implicit intent with ACTION_VIEW.
I tested this code on my Sony TV and it worked well. (I am using Kotlin)
// Passthrough inputs are "hardware" inputs like HDMI / Components. Non-passthrough input are
// usually internal tv tuners. You can also filter out non-passthrough inputs before this step.
val uri =
if (inputInfo.isPassthroughInput) TvContract.buildChannelUriForPassthroughInput(inputInfo.id)
else TvContract.buildChannelsUriForInput(inputInfo.id)
val intent = Intent(Intent.ACTION_VIEW, uri)
if (intent.resolveActivity(packageManager) != null) {
context.startActivity(intent)
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/59938698",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Bandwidth Source Please sorry if the following question seems stupid. Otherwise direct me to the appropriate place to ask it.
My question is, the webhosting companies where do they lease/get their bandwidth from? Do they rent the bandwidth from telecommunication companies?
thanks
A: Yes. Typical providers include most of the the big telecoms, plus some extra names that are specific to data transit: AT&T, Cogent, Comcast, Level3, NTT, Verizon...
Note that pricing on bandwidth gets weird for large users. Most web hosts pay on a burstable billing plan (typically 95th percentile with a minimum commit), rather than flat-rate or per byte. Some really large companies that run a lot of their own infrastructure (e.g, Google) pay nothing at all for peering.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/9297299",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to replace df column names with df1's I have 2 dfs with an identical amount of columns, however, they have 2 different naming conventions because I got the data from 2 different places. I want df_cont to have the same column names as df1.
I know I could do it like this:
df_cont.rename({'bitcoin':'BTC'}, axis='columns')
But this would take ages because of the many columns I have.
I tried to do:
df_cont = df_cont.rename(columns = df1.columns, inplace = True)
But this throws an error. Based on pandas documentation it looks like it wants me to give the index labels, but the 2 df's have different time-series lengths.
df1
btc eth ltc
df_cont
bitcoin ethereum litcoin
expected:
df_cont
btc eth ltc
A: Set columns names by df1.columns:
df_cont.columns = df1.columns
Sample:
df1 = pd.DataFrame([[1,2,3]], columns=['btc', 'eth', 'ltc'])
print (df1)
btc eth ltc
0 1 2 3
df_cont = pd.DataFrame([[11,22,33]], columns=['bitcoin', 'ethereum', 'litcoin'])
print (df_cont)
bitcoin ethereum litcoin
0 11 22 33
df_cont.columns = df1.columns
print (df_cont)
btc eth ltc
0 11 22 33
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/55086404",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Represent nested list as an array of strings I have a list which could look like this:
let list = [
{
name: "Level 1",
children: [
{
name: "Level 2",
children: [
{
name: "Level 3A",
children: [
{
name: "Level 4A",
children: []
}
],
},
{
name: "Level 3B",
children: [],
},
{
name: "Level 3C",
children: [],
},
],
},
],
},
];
As you can see it consists of elements with 2 properties: name and children. This is simple list but it can be nested many levels down and each element could have a lot of children.
Based on that list i want to create array of arrays of strings e.g.
let levels = [
["Level 1"],
["Level 1", "Level 2"],
["Level 1", "Level 2", "Level 3A"],
["Level 1", "Level 2", "Level 3A", "Level 4A"],
["Level 1", "Level 2", "Level 3B"],
["Level 1", "Level 2", "Level 3C"],
]
So as you can see each 'row' of my list has a representation in my levels array.
Could you help me write achieve that?
A: You can define a function to traverse the tree structure whilst accumulating the path along the way.
function getLevels(list) {
const levels = [];
const searchForLevels = ({ name, children }, path) => {
levels.push([...path, name]);
path.push(name);
children.forEach(child => searchForLevels(child, path));
path.pop();
};
list.forEach(child => searchForLevels(child, []));
return levels;
}
let list = [
{
name: "Level 1",
children: [
{
name: "Level 2",
children: [
{
name: "Level 3A",
children: [
{
name: "Level 4A",
children: []
}
],
},
{
name: "Level 3B",
children: [],
},
{
name: "Level 3C",
children: [],
},
],
},
],
},
];
console.log(getLevels(list));
A: You could do it by writing a recursive function.
Though on SO, usually, people would suggest you try to solve it yourself first. But I myself find that writing recursive functions is not an easy task (in terms of understanding how it works). So I'm happy to give you a hand.
const recursion = ({ name, children }, accumulator = []) => {
if (name) accumulator.push(name);
res.push(accumulator);
children.forEach((element) => recursion(element, [...accumulator]));
// have to store accumulator in new reference,
// so it would avoid override accumulators of other recursive calls
};
let list = [
{
name: "Level 1",
children: [
{
name: "Level 2",
children: [
{
name: "Level 3A",
children: [
{
name: "Level 4A",
children: [],
},
],
},
{
name: "Level 3B",
children: [],
},
{
name: "Level 3C",
children: [],
},
],
},
],
},
];
const res = [];
const recursion = ({ name, children }, accumulator = []) => {
if (name) accumulator.push(name);
res.push(accumulator);
children.forEach((element) => recursion(element, [...accumulator]));
};
list.forEach((element) => recursion(element));
console.log(res);
A: This can be done by traversing the tree and printing the path taken at each step
let list = [
{
name: "Level 1",
children: [
{
name: "Level 2",
children: [
{
name: "Level 3A",
children: [
{
name: "Level 4A",
children: []
}
],
},
{
name: "Level 3B",
children: [],
},
{
name: "Level 3C",
children: [],
},
],
},
],
},
];
let root = list[0]
function Traverse (root, path){
console.log(path + " " + root.name)
root.children.forEach(child => Traverse (child, path + " " + root.name));
}
Traverse(root, "");
A: You could take flatMap with a recursive callback.
const
getPathes = ({ name, children }) => children.length
? children.flatMap(getPathes).map(a => [name, ...a])
: [[name]],
list = [{ name: "Level 1", children: [{ name: "Level 2", children: [{ name: "Level 3A", children: [{ name: "Level 4A", children: [] }] }, { name: "Level 3B", children: [] }, { name: "Level 3C", children: [] }] }] }],
pathes = list.flatMap(getPathes);
console.log(pathes);
.as-console-wrapper { max-height: 100% !important; top: 0; }
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/67018507",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: how can I change this mysql code to mysqli how can i convert this code
$result = mysql_db_query($db, "SHOW FIELDS FROM $table") or mysql_die();
I don't found equivalent of function mysql_db_query() in mysqli
A: Use of mysqli is quite simple actually just need to call the query function of a mysqli object, equivalent would be:
//Instantiate mysqli db object
$sqli = new mysqli('host', 'user', 'password', 'db');
if ($sqli->connect_error)
die ("Could not connect to db: " . $db->connect_error);
//Make query
$sqli->query("SHOW FIELDS FROM $table") or die("Some error " . $sqli->error);
$sqli->close();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/31706045",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Changing Tabs in a Tab Control does not send Child a Message In a C# Windows Forms application using Framework 2.X, clicking on a tab control does not send a message to the child controls (such as a lost focus event). Using Microsoft Spy++, I do not see messages sent to my child control. I do get messages when I click back on the tab hosting the control.
Any ideas on what I need to do to have my child control know that its not displayed after the tab was changed. I would like the code to be in the control, not the parent. I am guessing that I am missing out on some event or registration.
Thanks in advance,
Craig
A:
I am guessing that I am missing out on some event or registration.
I don't think you are.
The a lost focus event would be too soon since it happens before the page changes.
The Child Control's VisibleChanged event only fires when the parent TabPage is shown and not when it is hidden which is not what you want.
You can handle either the TabPage.VisibleChanged or the TabControl.SelectedIndexChanged. This of course is from the Parent not the Child, which is also not what you want.
Incidently I believe the TCM_SETCURSEL message is sent to the control on tab change (again not helping with the "not in the Parent requriement"
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/4491471",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Installing npm live-server on MacOS Catalina I'm trying to install npm live-server but I am getting the following errors:
stl34>>npm install live-server -g
npm WARN deprecated [email protected]: Chokidar 2 will break on node v14+. Upgrade to chokidar 3 with 15x less dependencies.
npm WARN deprecated [email protected]: The package has been renamed to `open`
npm WARN deprecated [email protected]: fsevents 1 will break on node v14+ and could be using insecure binaries. Upgrade to fsevents 2.
npm WARN deprecated [email protected]: https://github.com/lydell/resolve-url#deprecated
npm WARN deprecated [email protected]: Please see https://github.com/lydell/urix#deprecated
npm WARN checkPermissions Missing write access to /usr/local/lib/node_modules
npm ERR! code EACCES
npm ERR! syscall access
npm ERR! path /usr/local/lib/node_modules
npm ERR! errno -13
npm ERR! Error: EACCES: permission denied, access '/usr/local/lib/node_modules'
npm ERR! [Error: EACCES: permission denied, access '/usr/local/lib/node_modules'] {
npm ERR! errno: -13,
npm ERR! code: 'EACCES',
npm ERR! syscall: 'access',
npm ERR! path: '/usr/local/lib/node_modules'
npm ERR! }
npm ERR!
npm ERR! The operation was rejected by your operating system.
npm ERR! It is likely you do not have the permissions to access this file as the current user
npm ERR!
npm ERR! If you believe this might be a permissions issue, please double-check the
npm ERR! permissions of the file and its containing directories, or try running
npm ERR! the command again as root/Administrator.
npm ERR! A complete log of this run can be found in:
npm ERR! /Users/stl34/.npm/_logs/2020-08-10T22_30_11_210Z-debug.log
The issue seems to be that the file permissions for /usr/local/lib/node_modules need to be changed.
I tried restarting in recovery mode and typing into the terminal:
csrutil disable
to disable SIP. Then I restarted and entered the following into the terminal:
sudo mount -uw /
chmod 775 usr/local/lib/node_modules
But the system still will not allow me to modify the file permissions. What can I do to modify them?
Another user asked this same question here:
NPM Live-server not installing on zsh
but received no answers.
A: running "sudo npm install live-server -g" worked for me
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/63349139",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Difference between `vector v;` and `vector v = vector();` What is the difference between
std::vector<int> v;
and
std::vector<int> v = std::vector<int>();
Intuitively, I would never use the second version but I am not sure if there is any difference. It feels to me that the second line is simply a default constructor building a temporary object that is then moved by a move assignment operator.
I am wondering whether the second line is not somehow equivalent to
std::vector<int> v = *(new std::vector<int>());
hence causing the vector itself to be on the heap (dynamically allocated). If it is the case, then the first line would probably be preferred for most cases.
How do these lines of code differ?
A: Starting from C++17 there's no difference whatsoever.
There's one niche use case where the std::vector = std::vector initialization syntax is quite useful (albeit not for default construction): when one wants to supply a "count, value" initializer for std::vector<int> member of a class directly in the class's definition:
struct S {
std::vector<int> v; // Want to supply `(5, 42)` initializer here. How?
};
In-class initializers support only = or {} syntax, meaning that we cannot just say
struct S {
std::vector<int> v(5, 42); // Error
};
If we use
struct S {
std::vector<int> v{ 5, 42 }; // or = { 5, 42 }
};
the compiler will interpret it as a list of values instead of "count, value" pair, which is not what we want.
So, one proper way to do it is
struct S {
std::vector<int> v = std::vector(5, 42);
};
A: The 1st one is default initialization, the 2nd one is copy initialization; The effect is same here, i.e. initialize the object v via the default constructor of std::vector.
For std::vector<int> v = std::vector<int>();, in concept it will construct a temporary std::vector then use it to move-construct the object v (note there's no assignment here). According to the copy elision (since C++17 it's guaranteed), it'll just call the default constructor to initialize v directly.
Under the following circumstances, the compilers are required to omit
the copy and move construction of class objects, even if the copy/move
constructor and the destructor have observable side-effects. The
objects are constructed directly into the storage where they would
otherwise be copied/moved to. The copy/move constructors need not be
present or accessible, as the language rules ensure that no copy/move
operation takes place, even conceptually:
*
*In the initialization of a variable, when the initializer expression
is a prvalue of the same class type (ignoring cv-qualification) as the
variable type:
T x = T(T(f())); // only one call to default constructor of T, to initialize x
(Before C++17, the copy elision is an optimization.)
this is an optimization: even when it takes place and the copy/move (since C++11) constructor is not called, it still must be present and accessible (as if no optimization happened at all),
BTW: For both cases, no std::vector objects (including potential temporary) will be constructed with dynamic storage duration via new expression.
A: You had asked:
What is the difference between
std::vector<int> v;
and
std::vector<int> v = std::vector<int>();
?
As others have stated since C++17 there basically is no difference. Now as for preference of which one to use, I would suggest the following:
*
*If you are creating an empty vector to be filled out later then the first version is the more desirable candidate.
*If you are constructing a vector with either a default value as one of its members and or a specified count, then the later version would be the one to use.
*Note that the following two are different constructors though:
*
*std::vector<int> v = std::vector<int>();
*Is not the same constructor as:
*std::vector<int> v = std::vector<int>( 3, 10 );
*The 2nd version of the constructor is an overloaded constructor.
*Otherwise if you are constructing a vector from a set of numbers than you have the following options:
*
*std::vector<int> v = { 1,2,3,4,5 };
*operator=( std::initializer_list)
*std::vector<int> v{ 1,2,3,4,5 };
*list_initialization
Here is the list of std::vector constructors.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/54937426",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "32"
}
|
Q: AngularJS ng-pattern and required can not work together on number field correctly? I have a form and i need to validate a field with both ng-pattern and required but they can't not work together correctly.
Form have only a number field which expects the value is an integer value.
When i type "0.3" the validation displays correctly. But when i type "abcd.." the validation displays "This field is required". It should be "Must be number"
I have create a plunk that demo my issues :
[link](http://plnkr.co/edit/yxqY51?p=preview)
Thank in advance
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/27313477",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: How to modify mapping for already mapped entities in other assemblies? I'd like to custom mapping for entities in EF
For example, I have an entity:
public class User
{
public int UserId { get;set;}
public string Firstname { get;set;}
public string ColA {get; set;}
public string ColB {get; set;}
}
It's already added mapping in OnModelCreating() in EF in common use. If i have 2 functions in 2 seperate assemblies, call AssemblyA.dll and AssemblyB.dll and they are dynamically loaded by MEF framework.
AssemblyA.dll just needs ColA and has to remove ColB and vice versa for AssemblyB.dll, so i need to define 2 new mapping classes for these 2 services and it will dynamically run to remove column according to its assembly (AssemblyA will Ignore ColB, and AssemblyB ignore ColA). I don't want to modify code of current EF because it's already in production. All changes for each assembly should be in its own.
Do EF support us to do like this ? Or could you give me a direction.
A: It is not very clear what you are trying to do but:
*
*Every EF context can have each table and entity mapped only once
*It means if you load configuration for AssemblyA you cannot use configuration for AssemblyB
*It also means you cannot use default way how EF mapping is constructed inside OnModelCreating because that method is normally called only once for whole application lifetime.
*You can manually construct two DbModel insnaces, compile them to DbCompiledModel and pass them to DbContext constructor - that should allow you to have two different mapping configuration for AssemblyA and AssemblyB but you will never have both of them in the same context instance.
*EF migrations will most probably don't work because they expect single mapping set per database
Anyway if you are using MEF and modular architecture each entity should be either core (not related to any particular module and shared as is among modules) or module (not used by any other modules or core).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/9325741",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Adding rows to gridView I want to add new rows after the inserted rows. I have a button that shows bootstrap modal with some DropDownLists and Textboxes. The button in modal on click should insert the data from modal to the table. The problem is that when i try to add new row it will replace current row. What im doing wrong? Here is sample of my code:
.cs:
protected void addTrip_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dostawca = DropDownDostawca.SelectedValue.ToString();
cel = txtCel.InnerText;
krajZagr = "";
kraj = DropDownKraj.SelectedValue.ToString();
miasto = txtMiasto.Text;
if(rbKraj.Checked == true)
{
krajZagr = "Krajowa";
}
if(rbZag.Checked == true)
{
krajZagr = "Zagraniczna";
}
if(cel=="" || miasto=="" || kraj=="" || dostawca=="" )
{
ClientScript.RegisterStartupScript(this.GetType(), "alert", "ShowPopup2();", true);
}
else
{
if(gridViewTrips.Columns.Count == 0)
{
DataRow dr = dt.NewRow();
DataColumn dc = new DataColumn("DO_KOGO");
DataColumn dc2 = new DataColumn("CEL");
DataColumn dc3 = new DataColumn("KRAJOWA_ZAGRANICZNA");
DataColumn dc4 = new DataColumn("KRAJ");
DataColumn dc5 = new DataColumn("MIASTO");
dt.Columns.Add(dc);
dt.Columns.Add(dc2);
dt.Columns.Add(dc3);
dt.Columns.Add(dc4);
dt.Columns.Add(dc5);
dr["DO_KOGO"] = dostawca;
dr["CEL"] = cel;
dr["KRAJOWA_ZAGRANICZNA"] = krajZagr;
dr["KRAJ"] = kraj;
dr["MIASTO"] = miasto;
dt.Rows.Add(dr);
gridViewTrips.DataSource = dt;
gridViewTrips.DataBind();
}
else
{
DataRow dr = dt.NewRow();
dr["DO_KOGO"] = dostawca;
dr["CEL"] = cel;
dr["KRAJOWA_ZAGRANICZNA"] = krajZagr;
dr["KRAJ"] = kraj;
dr["MIASTO"] = miasto;
dt.Rows.Add(dr);
gridViewTrips.DataSource = dt;
gridViewTrips.DataBind();
}
}
}
.aspx:
<asp:GridView runat="server" id="gridViewTrips">
<EmptyDataTemplate>
<asp:Table ID="TableTrips" runat="server" CssClass="table table-bordered">
<asp:TableHeaderRow>
<asp:TableHeaderCell>Do kogo</asp:TableHeaderCell>
<asp:TableHeaderCell>Cel</asp:TableHeaderCell>
<asp:TableHeaderCell>Krajowa/Zagraniczna</asp:TableHeaderCell>
<asp:TableHeaderCell>Kraj</asp:TableHeaderCell>
<asp:TableHeaderCell>Miasto</asp:TableHeaderCell>
</asp:TableHeaderRow>
</asp:Table>
</EmptyDataTemplate>
</asp:GridView>
EDIT: Now I see when I debug my project the IF what i have: "if(gridViewTrips.Columns.Count == 0)" after inserted one row shows me that I dont have any columns. Any ideas what is going on?
A: What about create GridView column first...
https://msdn.microsoft.com/en-us/library/system.windows.controls.gridviewcolumn(v=vs.110).aspx
and then AddChild method?
https://msdn.microsoft.com/en-us/library/system.windows.controls.gridview(v=vs.110).aspx
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/40436567",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How Apache Mina SignalListner works? I want to terminate the Apache Mina Ssh Server on the basis of Ctrl+c that are basically SigInt I searched on the google and have looked there are SignalListener but not find any good example of it.
Please share any good example and use in ssh server.
A listener will only trigger if any Sigint or a Signal is sent, Am I right ?
A: To get access to signal handling you have to use sun's private classes, which makes your code not portable any mode. Anyway...
import sun.misc.Signal;
public static void main(String[] args) {
registerSignalHandler();
}
@SuppressWarnings("restriction")
private static void registerSignalHandler() {
Signal.handle(new Signal("HUP"), (Signal signal) -> {
System.out.println("Hello signal!");
});
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/42488097",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: What's the most Cocoaish way to show that a text field is invalid? I have a text field which is validated whenever it loses focus. I want to be able to indicate that the value invalid during input so the user has the opportunity to correct their mistake before explicitly moving focus away from the box and triggering validation.
I have seen various implementations, including placing a red border round the field, a little icon that comes up for invalid input, or a bit of warning text.
What is the best way to do this in a way that complies with the conventions of Cocoa and the Apple Human Interface Guidelines?
A: Set its background to light red. This is what Adium does when you go over the message length limit in a Twitter tab.
The specific color Adium uses is:
*
*Hue: 0.983
*Saturation: 0.43
*Brightness: 0.99
*Alpha: 1.0
as a calibrated (Generic RGB) color.
A: What about shaking the text field while making it slightly red? It may or may not work well in practice, but its used in the login field for both MobileMe and user switching on OS X.
A: I like the Windows solution and implemented a small tooltip popup myself.
I don't think that just changing colors doesn't will work. A textual explaination is often required too. Unfortunately MacOSX removed the balloon tips from old MacOS.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/3448416",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: Eclipse fails to build android project Background: this problem occured after an update through the android sdk Manager eclipse plugin.
Currently, when i try to build any android project, this error occurs.
THe information i gathered so far, is that this is a java related issue, as i'm trying to compile newer version code (version 52.0 stands for java 8) and run it in an older one. However, most of the solutions didn't work out.
Here are the compile setting for an android project :
Here are settings from the java compiler in Eclispe:
Here are the installed JREs
Finally, installed packets from the Android SDK:
I've removed the packets for API 23, but with no luck. Could it be that Android tools are causing trouble, since the SKD doesn't support the java version (52)?
A: Problem was with JDK/JRE. They were installed separately. Deleted them and installed from a bundle. Although they were the same version, project building kept on crashing.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/37241270",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: strange
* padding issue chrome (padding only works sometimes in chrome) Ok so I am having a strange problem which only happens in the chrome web browser.
everything works fine in firefox and ie.
I have created a navigation menu using images.
I have place padding on each list item to space them out a bit.
so when using chrome sometimes the padding works, other times it doesn't.
if i refresh the page a few times the padding stops working and the list items have no padding anymore, refresh again a few times and it works again.
I have no idea what is causing this.
I will paste my code here if anyone has any ideas.
I have searched far and wide and cant seem to find anyone else with this issue.
**EDIT : **
I have hosted the images and used codepen,
with codepen padding doesnt work at all with chrome but is fine in firefox
codepen:
http://codepen.io/anon/pen/JEOZBN
HTML
<div class="ground">
<img src="http://res.cloudinary.com/ddoewrnb0/image/upload/v1485620608/ground_dhn37w.png" />
<!--nav menu-->
<ul id="menu">
<li id="home"><a class="current" href="index.html">Home</a></li>
<li id="about"><a href="about.html">About</a></li>
<li id="audio"><a href="audio.html">Audio</a></li>
<li id="art"><a href="design.html">Art</a></li>
<li id="threed"><a href="modeling.html">3d</a></li>
<li id="coding"><a href="coding.html">Programming</a></li>
</ul>
</div>
And the css
.ground{
position:fixed;
left:0px;
bottom:-1%;
height:auto;
width:100%;
background:#999;
}
/*nav menu */
#menu{
position: fixed;
list-style:none;
margin: -5% 0% 0% 18%;
}
#menu li{
float:left; /*--- Make the list go horizontal ---*/
margin:auto;
}
#menu li a{
display:block;
text-indent: -9999px; /*--- Push the text off screen to hide text---*/
padding-left: 10% !important;
padding-right: 10% !important;
}
#menu li#home a{
background: url(http://res.cloudinary.com/ddoewrnb0/image/upload/v1485620607/home_menu_svyjuj.png) no-repeat;
width:150px;
height: 75px;
}
#menu li#home a:hover{
background: url(http://res.cloudinary.com/ddoewrnb0/image/upload/v1485620607/home_menu_hover_g4rwhe.png) no-repeat;
}
#menu li#home a.current{
background: url(http://res.cloudinary.com/ddoewrnb0/image/upload/v1485620607/home_menu_hover_g4rwhe.png) no-repeat;
cursor:default; /*--- Show pointer instead of hand cursor for the current page ---*/
}
/*About*/
#menu li#about a{
background: url(http://res.cloudinary.com/ddoewrnb0/image/upload/v1485620607/about_menu_jcz8yx.png) no-repeat;
width:150px;
height: 75px;
}
#menu li#about a:hover{
background: url(http://res.cloudinary.com/ddoewrnb0/image/upload/v1485620607/about_menu_hover_uurcba.png) no-repeat;
}
#menu li#about a.current{
background: url(http://res.cloudinary.com/ddoewrnb0/image/upload/v1485620607/about_menu_hover_uurcba.png) no-repeat;
cursor:default;
}
/*Graphic design*/
#menu li#art a{
background: url(http://res.cloudinary.com/ddoewrnb0/image/upload/v1485620607/art_menu_mbywzq.png) no-repeat;
width:150px;
height: 75px;
}
#menu li#art a:hover{
background: url(http://res.cloudinary.com/ddoewrnb0/image/upload/v1485620607/art_menu_hover_afaypq.png) no-repeat;
}
#menu li#art a.current{
background: url(http://res.cloudinary.com/ddoewrnb0/image/upload/v1485620607/art_menu_hover_afaypq.png) no-repeat;
cursor:default;
}
/*Modeling/Animation*/
#menu li#threed a{
background: url(http://res.cloudinary.com/ddoewrnb0/image/upload/v1485620607/3d_menu_dptfpv.png) no-repeat;
width:150px;
height: 75px;
}
#menu li#threed a:hover{
background: url(http://res.cloudinary.com/ddoewrnb0/image/upload/v1485620607/3d_menu_hover_pqnxfs.png) no-repeat;
}
#menu li#threed a.current{
background: url(http://res.cloudinary.com/ddoewrnb0/image/upload/v1485620607/3d_menu_hover_pqnxfs.png) no-repeat;
cursor:default;
}
/*Programming*/
#menu li#coding a{
background: url(http://res.cloudinary.com/ddoewrnb0/image/upload/v1485620608/programming_hzslwa.png) no-repeat;
width:150px;
height: 75px;
}
#menu li#coding a:hover{
background: url(http://res.cloudinary.com/ddoewrnb0/image/upload/v1485620608/programming_hover_crywht.png) no-repeat;
}
#menu li#coding a.current{
background: url(.http://res.cloudinary.com/ddoewrnb0/image/upload/v1485620608/programming_hover_crywht.png) no-repeat;
cursor:default;
}
/*Audio*/
#menu li#audio a{
background: url(http://res.cloudinary.com/ddoewrnb0/image/upload/v1485620607/audio_vvgdur.png) no-repeat;
width:150px;
height: 75px;
}
#menu li#audio a:hover{
background: url(http://res.cloudinary.com/ddoewrnb0/image/upload/v1485620607/audio_hover_bnrvb0.png) no-repeat;
}
#menu li#audio a.current{
background: url(http://res.cloudinary.com/ddoewrnb0/image/upload/v1485620607/audio_hover_bnrvb0.png) no-repeat;
cursor:default;
}
Any help is greatly appreciated Thank you.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/41911673",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to change the position of GameObjects with Unity Input.GetMouseButtonDown method? I already know how to click on 3D Objects in the scene by using the Input.GetMouseButtonDown. I'm trying to change the 3D Object position by clicking on the object. I added a Box Collider in the object and I'm calling the following method.
void Update()
{
if (Input.GetMouseButtonDown(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
foreach (GameObject child in floorTiles) {
BoxCollider box = child.GetComponentInChildren<BoxCollider>();
if (hit.transform.name.Equals(box.name))
{
handleOnMouseDown(hit.collider);
}
}
}
}
}
floorTiles is an array of GameObjects.
If I hit one of these objects the below function is called:
void handleOnMouseDown(Collider box)
{
GameObject parent = box.transform.parent.gameObject;
Vector3 position = parent.transform.position;
positionX.GetComponent<TextMeshProUGUI>().text = position.x.ToString();
posXButtonPlus.GetComponent<Button>().onClick.AddListener(() => handleOnChangePosition("posx", parent));
}
This works, however, when I click many objects, all the last objects clicked also keep changing their positions. How can I change one position per time?
A: Each click on an object, adds listener to your button, but you don't ever remove listeners. You end up with multiple listeners, that's why more objects are moved than intended.
You could remove listener after each button click, but that seems like a total overkill.
Instead of adding multiple listeners, consider adding just one which will remember the last clicked object, and clicking your button will move only that object.
Also, if you want to move objects just by clicking on them, not on button click, you can simplify all these, and move the object directly in handleOnMouseDown.
Remove listeners variant:
void handleOnMouseDown(Collider box)
{
posXButtonPlus.GetComponent<Button>().onClick.AddListener(() => handleOnChangePosition("posx", box.gameObject));
}
void handleOnChangePosition(string pos, GameObject go)
{
// I don't have code for moving, but I imagine looks something like this. right * 0.5f can be anything, did it just for tests.
go.transform.position += Vector3.right * 0.5f;
posXButtonPlus.GetComponent<Button>().onClick.RemoveAllListeners();
}
Last clicked variant:
GameObject lastClicked;
void Awake()
{
posXButtonPlus.GetComponent<Button>().onClick.AddListener(() => handleOnChangePosition());
}
void handleOnMouseDown(Collider box)
{
lastClicked = box.gameObject;
}
void handleOnChangePosition()
{
lastClicked.transform.position += Vector3.right * 0.5f;
}
Without buttons and other stuff:
void handleOnMouseDown(Collider box)
{
box.transform.position += Vector3.right * 0.5f;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73737328",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Apply a shadow to a fitted image with Tailwind CSS I wrote this code:
<script src="https://cdn.tailwindcss.com"></script>
<div class="m-6 space-x-3">
<div v-for="m in media" class="w-[200px] h-[200px] inline-block">
<img class="object-contain w-full h-full shadow shadow-black" src="http://placekitten.com/200/300">
</div>
<div v-for="m in media" class="w-[200px] h-[200px] inline-block">
<img class="object-contain w-full h-full shadow shadow-black" src="http://placekitten.com/300/200">
</div>
</div>
It gives this result:
But I want the shadow to apply to the image, not to the box that the image fits in.
A: Try to add drop-shadow instead of shadow
<script src="https://cdn.tailwindcss.com"></script>
<div class="m-6 space-x-3">
<div v-for="m in media" class="w-[200px] h-[200px] inline-block">
<img class="object-contain w-full h-full drop-shadow-[0_5px_5px_rgba(0,0,0,0.5)]" src="http://placekitten.com/200/300">
</div>
<div v-for="m in media" class="w-[200px] h-[200px] inline-block">
<img class="object-contain w-full h-full drop-shadow-[0_5px_5px_rgba(0,0,0,0.5)]" src="http://placekitten.com/300/200">
</div>
</div>
A: You can instead just extend the theme and use tailwind internal custom properties to get the color you want for the shadow.
here is an example in play.tailwind.
EDIT: Tailwind sample code into a snipet
/* ! tailwindcss v3.2.6 | MIT License | https://tailwindcss.com */
/*
1. Prevent padding and border from affecting element width. (https://github.com/mozdevs/cssremedy/issues/4)
2. Allow adding a border to an element by just adding a border-width. (https://github.com/tailwindcss/tailwindcss/pull/116)
*/
*,
::before,
::after {
box-sizing: border-box;
/* 1 */
border-width: 0;
/* 2 */
border-style: solid;
/* 2 */
border-color: #e5e7eb;
/* 2 */
}
::before,
::after {
--tw-content: '';
}
/*
1. Use a consistent sensible line-height in all browsers.
2. Prevent adjustments of font size after orientation changes in iOS.
3. Use a more readable tab size.
4. Use the user's configured `sans` font-family by default.
5. Use the user's configured `sans` font-feature-settings by default.
*/
html {
line-height: 1.5;
/* 1 */
-webkit-text-size-adjust: 100%;
/* 2 */
-moz-tab-size: 4;
/* 3 */
tab-size: 4;
/* 3 */
font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";
/* 4 */
font-feature-settings: normal;
/* 5 */
}
/*
1. Remove the margin in all browsers.
2. Inherit line-height from `html` so users can set them as a class directly on the `html` element.
*/
body {
margin: 0;
/* 1 */
line-height: inherit;
/* 2 */
}
/*
1. Add the correct height in Firefox.
2. Correct the inheritance of border color in Firefox. (https://bugzilla.mozilla.org/show_bug.cgi?id=190655)
3. Ensure horizontal rules are visible by default.
*/
hr {
height: 0;
/* 1 */
color: inherit;
/* 2 */
border-top-width: 1px;
/* 3 */
}
/*
Add the correct text decoration in Chrome, Edge, and Safari.
*/
abbr:where([title]) {
-webkit-text-decoration: underline dotted;
text-decoration: underline dotted;
}
/*
Remove the default font size and weight for headings.
*/
h1,
h2,
h3,
h4,
h5,
h6 {
font-size: inherit;
font-weight: inherit;
}
/*
Reset links to optimize for opt-in styling instead of opt-out.
*/
a {
color: inherit;
text-decoration: inherit;
}
/*
Add the correct font weight in Edge and Safari.
*/
b,
strong {
font-weight: bolder;
}
/*
1. Use the user's configured `mono` font family by default.
2. Correct the odd `em` font sizing in all browsers.
*/
code,
kbd,
samp,
pre {
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
/* 1 */
font-size: 1em;
/* 2 */
}
/*
Add the correct font size in all browsers.
*/
small {
font-size: 80%;
}
/*
Prevent `sub` and `sup` elements from affecting the line height in all browsers.
*/
sub,
sup {
font-size: 75%;
line-height: 0;
position: relative;
vertical-align: baseline;
}
sub {
bottom: -0.25em;
}
sup {
top: -0.5em;
}
/*
1. Remove text indentation from table contents in Chrome and Safari. (https://bugs.chromium.org/p/chromium/issues/detail?id=999088, https://bugs.webkit.org/show_bug.cgi?id=201297)
2. Correct table border color inheritance in all Chrome and Safari. (https://bugs.chromium.org/p/chromium/issues/detail?id=935729, https://bugs.webkit.org/show_bug.cgi?id=195016)
3. Remove gaps between table borders by default.
*/
table {
text-indent: 0;
/* 1 */
border-color: inherit;
/* 2 */
border-collapse: collapse;
/* 3 */
}
/*
1. Change the font styles in all browsers.
2. Remove the margin in Firefox and Safari.
3. Remove default padding in all browsers.
*/
button,
input,
optgroup,
select,
textarea {
font-family: inherit;
/* 1 */
font-size: 100%;
/* 1 */
font-weight: inherit;
/* 1 */
line-height: inherit;
/* 1 */
color: inherit;
/* 1 */
margin: 0;
/* 2 */
padding: 0;
/* 3 */
}
/*
Remove the inheritance of text transform in Edge and Firefox.
*/
button,
select {
text-transform: none;
}
/*
1. Correct the inability to style clickable types in iOS and Safari.
2. Remove default button styles.
*/
button,
[type='button'],
[type='reset'],
[type='submit'] {
-webkit-appearance: button;
/* 1 */
background-color: transparent;
/* 2 */
background-image: none;
/* 2 */
}
/*
Use the modern Firefox focus style for all focusable elements.
*/
:-moz-focusring {
outline: auto;
}
/*
Remove the additional `:invalid` styles in Firefox. (https://github.com/mozilla/gecko-dev/blob/2f9eacd9d3d995c937b4251a5557d95d494c9be1/layout/style/res/forms.css#L728-L737)
*/
:-moz-ui-invalid {
box-shadow: none;
}
/*
Add the correct vertical alignment in Chrome and Firefox.
*/
progress {
vertical-align: baseline;
}
/*
Correct the cursor style of increment and decrement buttons in Safari.
*/
::-webkit-inner-spin-button,
::-webkit-outer-spin-button {
height: auto;
}
/*
1. Correct the odd appearance in Chrome and Safari.
2. Correct the outline style in Safari.
*/
[type='search'] {
-webkit-appearance: textfield;
/* 1 */
outline-offset: -2px;
/* 2 */
}
/*
Remove the inner padding in Chrome and Safari on macOS.
*/
::-webkit-search-decoration {
-webkit-appearance: none;
}
/*
1. Correct the inability to style clickable types in iOS and Safari.
2. Change font properties to `inherit` in Safari.
*/
::-webkit-file-upload-button {
-webkit-appearance: button;
/* 1 */
font: inherit;
/* 2 */
}
/*
Add the correct display in Chrome and Safari.
*/
summary {
display: list-item;
}
/*
Removes the default spacing and border for appropriate elements.
*/
blockquote,
dl,
dd,
h1,
h2,
h3,
h4,
h5,
h6,
hr,
figure,
p,
pre {
margin: 0;
}
fieldset {
margin: 0;
padding: 0;
}
legend {
padding: 0;
}
ol,
ul,
menu {
list-style: none;
margin: 0;
padding: 0;
}
/*
Prevent resizing textareas horizontally by default.
*/
textarea {
resize: vertical;
}
/*
1. Reset the default placeholder opacity in Firefox. (https://github.com/tailwindlabs/tailwindcss/issues/3300)
2. Set the default placeholder color to the user's configured gray 400 color.
*/
input::placeholder,
textarea::placeholder {
opacity: 1;
/* 1 */
color: #9ca3af;
/* 2 */
}
/*
Set the default cursor for buttons.
*/
button,
[role="button"] {
cursor: pointer;
}
/*
Make sure disabled buttons don't get the pointer cursor.
*/
:disabled {
cursor: default;
}
/*
1. Make replaced elements `display: block` by default. (https://github.com/mozdevs/cssremedy/issues/14)
2. Add `vertical-align: middle` to align replaced elements more sensibly by default. (https://github.com/jensimmons/cssremedy/issues/14#issuecomment-634934210)
This can trigger a poorly considered lint error in some tools but is included by design.
*/
img,
svg,
video,
canvas,
audio,
iframe,
embed,
object {
display: block;
/* 1 */
vertical-align: middle;
/* 2 */
}
/*
Constrain images and videos to the parent width and preserve their intrinsic aspect ratio. (https://github.com/mozdevs/cssremedy/issues/14)
*/
img,
video {
max-width: 100%;
height: auto;
}
/* Make elements with the HTML hidden attribute stay hidden by default */
[hidden] {
display: none;
}
*, ::before, ::after {
--tw-border-spacing-x: 0;
--tw-border-spacing-y: 0;
--tw-translate-x: 0;
--tw-translate-y: 0;
--tw-rotate: 0;
--tw-skew-x: 0;
--tw-skew-y: 0;
--tw-scale-x: 1;
--tw-scale-y: 1;
--tw-pan-x: ;
--tw-pan-y: ;
--tw-pinch-zoom: ;
--tw-scroll-snap-strictness: proximity;
--tw-ordinal: ;
--tw-slashed-zero: ;
--tw-numeric-figure: ;
--tw-numeric-spacing: ;
--tw-numeric-fraction: ;
--tw-ring-inset: ;
--tw-ring-offset-width: 0px;
--tw-ring-offset-color: #fff;
--tw-ring-color: rgb(59 130 246 / 0.5);
--tw-ring-offset-shadow: 0 0 #0000;
--tw-ring-shadow: 0 0 #0000;
--tw-shadow: 0 0 #0000;
--tw-shadow-colored: 0 0 #0000;
--tw-blur: ;
--tw-brightness: ;
--tw-contrast: ;
--tw-grayscale: ;
--tw-hue-rotate: ;
--tw-invert: ;
--tw-saturate: ;
--tw-sepia: ;
--tw-drop-shadow: ;
--tw-backdrop-blur: ;
--tw-backdrop-brightness: ;
--tw-backdrop-contrast: ;
--tw-backdrop-grayscale: ;
--tw-backdrop-hue-rotate: ;
--tw-backdrop-invert: ;
--tw-backdrop-opacity: ;
--tw-backdrop-saturate: ;
--tw-backdrop-sepia: ;
}
::backdrop {
--tw-border-spacing-x: 0;
--tw-border-spacing-y: 0;
--tw-translate-x: 0;
--tw-translate-y: 0;
--tw-rotate: 0;
--tw-skew-x: 0;
--tw-skew-y: 0;
--tw-scale-x: 1;
--tw-scale-y: 1;
--tw-pan-x: ;
--tw-pan-y: ;
--tw-pinch-zoom: ;
--tw-scroll-snap-strictness: proximity;
--tw-ordinal: ;
--tw-slashed-zero: ;
--tw-numeric-figure: ;
--tw-numeric-spacing: ;
--tw-numeric-fraction: ;
--tw-ring-inset: ;
--tw-ring-offset-width: 0px;
--tw-ring-offset-color: #fff;
--tw-ring-color: rgb(59 130 246 / 0.5);
--tw-ring-offset-shadow: 0 0 #0000;
--tw-ring-shadow: 0 0 #0000;
--tw-shadow: 0 0 #0000;
--tw-shadow-colored: 0 0 #0000;
--tw-blur: ;
--tw-brightness: ;
--tw-contrast: ;
--tw-grayscale: ;
--tw-hue-rotate: ;
--tw-invert: ;
--tw-saturate: ;
--tw-sepia: ;
--tw-drop-shadow: ;
--tw-backdrop-blur: ;
--tw-backdrop-brightness: ;
--tw-backdrop-contrast: ;
--tw-backdrop-grayscale: ;
--tw-backdrop-hue-rotate: ;
--tw-backdrop-invert: ;
--tw-backdrop-opacity: ;
--tw-backdrop-saturate: ;
--tw-backdrop-sepia: ;
}
.m-6 {
margin: 1.5rem;
}
.inline-block {
display: inline-block;
}
.h-\[200px\] {
height: 200px;
}
.h-full {
height: 100%;
}
.w-\[200px\] {
width: 200px;
}
.w-full {
width: 100%;
}
.space-x-3 > :not([hidden]) ~ :not([hidden]) {
--tw-space-x-reverse: 0;
margin-right: calc(0.75rem * var(--tw-space-x-reverse));
margin-left: calc(0.75rem * calc(1 - var(--tw-space-x-reverse)));
}
.object-contain {
object-fit: contain;
}
.shadow-blue-400 {
--tw-shadow-color: #60a5fa;
--tw-shadow: var(--tw-shadow-colored);
}
.shadow-gray-600 {
--tw-shadow-color: #4b5563;
--tw-shadow: var(--tw-shadow-colored);
}
.drop-shadow-custom {
--tw-drop-shadow: drop-shadow(0 5px 5px var(--tw-shadow-color));
filter: var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow);
}
<div class="m-6 space-x-3">
<div v-for="m in media" class="w-[200px] h-[200px] inline-block">
<img class="object-contain w-full h-full shadow-blue-400 drop-shadow-custom" src="http://placekitten.com/200/300">
</div>
<div v-for="m in media" class="w-[200px] h-[200px] inline-block">
<img class="object-contain w-full h-full shadow-gray-600 drop-shadow-custom" src="http://placekitten.com/300/200">
</div>
</div>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/75541226",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to validate file type in java I have created a text file with some content. I changed its extension to .xlsx.
I used this code to validate file-
String filepath = "C:\\Users\\prabhat.sameer\\Desktop\\test.xlsx";
File f = new File(filepath);
String mimetype= new MimetypesFileTypeMap().getContentType(f);
String type = mimetype.split("/")[0];
System.out.println("type " + type);
if (type.equals("text")) {
System.out.println("It's an text file");
} else {
System.out.println("It's NOT an text file");
}
Its content type also changed with change of extension. How to validate this?
A: If you open the file by double-clicking on it, are you able to read the data? Usually a special library like POI is required to write to excel so I would be surprised if it does.
If your txt file has data in csv(comma separated) format, then changing the extension to .csv should work for you.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/40488973",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: PhpStorm can't resolve @ionic/angular I've got an Ionic v4 project that is running fine, but PhpStorm cannot find my references to @ionic.
It looks like the code is actually in the /dist directory, so if I change the reference to:
import { NavController } from '@ionic/angular/dist'
PhpStorm doesn't complain and I get code completion features for @ionic/angular.
However, when running ng serve the project won't compile and I get errors in the console:
ERROR in ./src/app/pages/home/home.component.ts
Module not found: Error: Can't resolve '@ionic/angular/dist'
How can I fix this?
Why does project compile when not specifying /dist?
Edit:
In PhpStorm, the entire node_modules directory is excluded, but not specifically the @ionic/angular. Note, references to other modules are working fine.
Edit 2:
Here's how the folder coloring shows up:
*
*@ionic/angular doesn't work
*@ionic-native/core works
*@angular/core works
A: I thought I'd share the workaround that I ended up using.
I just added an index.d.ts file in the node_modules/@ionic/angular/ directory, with the following contents:
export * from './dist';
Of course it isn't ideal to modify the contents of your dependencies, but this simple fix keeps my IDE from driving me crazy... :-)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/54936638",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Overloading constructor with 2 same datatype members lets say i have a class with two std::string member and one int value, like:
class DataGroup final {
public:
explicit DataGroup (const std::vector<int>& groupNr,
const std::string& group1,
const std::string& group2)
: groupNr(groupNr)
, group1(group1)
, group2(group2){};
std::vector<int> groupNrs{};
std::string group1{};
std::string group2{};
};
Can i somehow have 2 overloaded constructors where one will initialize groupNr and group1, and other ctor initializes groupNr and group2 ? One of the strings not initialized in ctor call would be empty string then.
A: There are several way to have expected behavior:
*
*Named constructor
class DataGroup final {
public:
// ...
static DataGroup Group1(const std::vector<int>& groupNr,
const std::string& group)
{ return DataGroup{groupNr, group, ""}; }
static DataGroup Group2(const std::vector<int>& groupNr,
const std::string& group)
{ return DataGroup{groupNr, "", group}; }
// ...
};
DataGroup d = DataGroup::Group2({1, 2}, "MyGroup");
*Tagged constructor
struct group1{};
struct group2{};
class DataGroup final {
public:
// ...
DataGroup(group1, const std::vector<int>& groupNr,
const std::string& group) : DataGroup{groupNr, group, ""} {}
DataGroup(group2, const std::vector<int>& groupNr,
const std::string& group) : DataGroup{groupNr, "", group} {}
// ...
};
DataGroup d{group2{}, {1, 2}, "MyGroup");
*named parameters (see there for possible implementation)
// ...
DataGroup d{groupNr = {1, 2}, group2 = "MyGroup");
A: For overloading a function/constructor, they must have 2 distinct signatures. Since your intended types to be supplied are the same for both cases, you have to supply a 3rd parameter with a possibly default value for one of them. But again, watch for uninitialized local fields, since they will be auto-initialized by the compiler-generated code.
A: One of the solutions here would be to simply have base class with "common" member
groupNr(groupNr)
and other two separate member have in each derived class, then you would initialize base member groupNr by calling constructor of base class when initializing derived one:
class DataGroup {
public:
explicit DataGroup (const std::vector<int>& groupNrs)
: groupNrs(groupNr){};
std::vector<int> groupNrs{};
};
class DataGroup1 : public DataGroup {
public:
explicit DataGroup1 (const std::vector<int>& groupNrs,
const std::string& group1)
: DataGroup(groupNrs)
, group1(group1){};
std::string group1{};
};
class DataGroup2 : public DataGroup {
public:
explicit DataGroup2 (const std::vector<int>& groupNrs,
const std::string& group2)
: DataGroup(groupNrs)
, group2(group2){};
std::string group2{};
};
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/61988477",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)cert.PublicKey.Key does not work in .NET Core I have an assembly compiled with .NET Framework 2.0 (yes, pretty old stuff) which performs encryption with a certificate's public key. The code is extremely simple:
X509Certificate2 objCert = new X509Certificate2(path);
RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)objCert.PublicKey.Key;
byte [] EncrRes = rsa.Encrypt(data, false);
This continues to work with all recent versions of .NET Framework, but refuses to work under .NET Core. I got two different but similar error messages.
Windows 10:
Unable to cast object of type 'System.Security.Cryptography.RSACng' to type 'System.Security.Cryptography.RSACryptoServiceProvider'.
Linux:
Unable to cast object of type 'System.Security.Cryptography.RSAOpenSsl' to type 'System.Security.Cryptography.RSACryptoServiceProvider'.
Is there a way to code this simple operation so that it would work on both .NET Framework 2.0+ and .NET core?
Thanks in advance.
A: In .NET Core, X509Certificate2.PublicKey.Key and X509Certificate2.PrivateKey use platform-specific implementation of key. On Windows, there are two implementations, legacy RSACryptoServiceProvider and modern RSACng.
You have to change the way how you access these properties. And do not access them. Instead, use extension methods: X509Certificate2 Extension Methods. They return safe abstract classes you shall use. Do not try to use explicit cast to anything. For RSA keys use RSA class and so on.
X509Certificate2 objCert = new X509Certificate2(path);
// well, it is reasonable to check the algorithm of public key. If it is ECC,
// then call objCert.GetECDsaPublicKey()
RSA rsa = objCert.GetRsaPublicKey();
byte [] EncrRes = rsa.Encrypt(data, RSAEncryptionPadding.Pkcs1);
A: Figured it out on my own. Instead of
RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)objCert.PublicKey.Key;
do
RSA rsa_helper = (RSA)objCert.PublicKey.Key;
RSAParameters certparams = rsa_helper.ExportParameters(false);
RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
RSAParameters paramcopy = new RSAParameters();
paramcopy.Exponent = certparams.Exponent;
paramcopy.Modulus = certparams.Modulus;
rsa.ImportParameters(paramcopy);
Works with .NET 2.0+ and .NET Core!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/60102646",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Why technically does ScrewTurn uses .ashx to create wiki page? Why ScrewTurn Wiki does use ashx type to create wiki page? Isn't it dangerous to create asp.net page on the fly?
update: they didn't create any physical pages. But how do they do that because the url is actually some-newpage.ashx ?
A: I think it uses the .ashx to 1.) trigger the use of the ASP.NET isapi filter and 2.) signal that the requests aren't mapped to any physical files, but URLs mapped to logical pages within the Wiki engine.
And I don't think it's dangerous to create ASP.NET page responses on the fly, which is essentially what they do. It's actually a quite brilliant way to let you, the user of the system, build up the hierarchy of the web site.
A: Does it actually really craete pages on the fiy on disc?
An ashx is a handler. It returns output as it wants. You can have a CMS that exposes it's tree thruogh a .ashx in between (/cms.ashx/some/page) but the pages NEVER EXIST.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/5702115",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to connect sockets and receive Data? I am new to sockets, I was hoping someone knows how to connect sockets on Android Studio and receive data.
This is the websocket which uses socket.io that I am trying to receive data from: https://ws-api.iextrading.com/1.0/stock/aapl/quote
This is a link to the API which explains the websocket: https://iextrading.com/developer/docs/#websockets
I am trying to get realtime stock data for my app, but I do not know how to connect to the socket then receive the data and my app crashes before it even opens, this is my code so far:
package com.example.android.stocksApp;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Socket;
public class MainActivity extends AppCompatActivity {
private static Socket s;
private static InputStreamReader isr;
private static BufferedReader br;
TextView result;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
result = (TextView)findViewById(R.id.result);
stockData();
}
public void stockData (){
myTask mTask = new myTask();
mTask.execute();
}
class myTask extends AsyncTask<Void, Void, Void>{
@Override
protected Void doInBackground(Void... params) {
try {
s = new Socket("https://ws-api.iextrading.com/1.0/stock/aapl/quote", 80);
InputStream is = s.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String quote = br.readLine();
result.setText(quote);
s.close();
is.close();
isr.close();
br.close();
} catch (IOException e){
e.printStackTrace();
}
return null;
}
}
}
A: You're trying to connect to a Web service. Web services may return either a XML or JSON. The actual Socket library isn't needed nor used for this. This specific web service returns a JSON, so what you need is a library that is capable of making a GET request to this URL and parse the response. For Android, I recommend using Volley. You can include Volley in your project by adding this line to your build.gradle.
implementation 'com.android.volley:volley:1.0.0'
This question might help you get started.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/49957964",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How can I use HttpClient-4.5 against a SOCKS proxy? How can I use a ClosableHttpClient from HttpClient-4.5 over a configured SOCKS proxy? Is there a way to accomplish this without specifying a global SOCKS proxy with java -DsocksProxyHost or setting a custom default ProxySelector?
The explicit documention about proxies, is as far as I understand only about HTTP proxies (which I imply by defining such a proxy as HttpHost). For me it looks like "Connection socket factories" is more relevant.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/43292049",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: why won't my text area show up I'm trying to implement a program where the client will send a fix message to the server side, and the UI I have for the server side will show up the FIX message on the text area.
However when I start the program, the textfields and all the labels will show, except the text area. And when I try send a message from the client side, everything works besides the text area.
code
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.awt.*; // using AWT containers and components
import java.awt.event.*; // using AWT events and listener interfaces
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class TcpServerCompareCSV extends Frame implements ActionListener , WindowListener {
private Label lblPort; // declare component Label
private TextField tfPort; // declare component TextField
private int port; // port number
private Label lblLocation; // declare component Label
private TextField tfLocation; // declare component TextField
private String fileLocation; // csv file location
private Button btnCount; // declare component Button //________________________________________________________________________________\\
private Label lblCSVLine; // declare component Label from csv file line, server side
private TextField tfCSVLine; // declare component TextField from csv file line, server side
private String CSVLine; // port number
private Label lblFIXMsg; // declare component Label from csv file line, server side
private JTextArea tfFIXMsg; // declare component TextField from csv file line, server side
private String FIXMsg; // port number
private JScrollPane jScrollPane1;//________________________________________________________________________________\\
/** WindowEvent handlers */
// Called back upon clicking close-window button
@Override
public void windowClosing(WindowEvent e) {
System.exit(0); // terminate the program
}
//constructor for frame
public TcpServerCompareCSV () {
setLayout(new FlowLayout());
// "this" Frame sets its layout to FlowLayout, which arranges the components
// from left-to-right, and flow to next row from top-to-bottom.
lblPort = new Label("Port"); // construct Label
add(lblPort); // "this" Frame adds Label
tfPort = new TextField("0", 40); // construct TextField
tfPort.setEditable(true); //edit text
add(tfPort); // "this" Frame adds tfCount
// tfPort.addActionListener(this); // for event-handling
lblLocation = new Label("CSV File Location"); // construct Label
add(lblLocation); // "this" Frame adds Label
tfLocation = new TextField("text", 40); // construct TextField
tfLocation.setEditable(true); //edit text
add(tfLocation); // "this" Frame adds tfCount
//________________________________________________________________________________\\
setTitle("compare"); // "this" Frame sets title
setSize(800,200); // "this" Frame sets initial window size
setVisible(true); // "this" Frame shows
lblCSVLine = new Label("CSV Line"); // construct Label
add(lblCSVLine); // "this" Frame adds Label
tfCSVLine = new TextField("text", 40); // construct TextField
tfCSVLine.setEditable(false); //edit text
add(tfCSVLine); // "this" Frame adds tfCount
lblFIXMsg = new Label("FIX message from client"); // construct Label
add(lblFIXMsg); // "this" Frame adds Label
tfFIXMsg = new JTextArea(); // construct TextField
tfFIXMsg.setColumns(20);
tfFIXMsg.setLineWrap(true);
tfFIXMsg.setRows(50);
tfFIXMsg.setWrapStyleWord(true);
tfFIXMsg.setEditable(false); //edit text
add(tfFIXMsg); // "this" Frame adds tfCount
jScrollPane1 = new JScrollPane(tfFIXMsg);
add(jScrollPane1);
btnCount = new Button("Enter"); // construct Button
add(btnCount); // "this" Frame adds Button
btnCount.addActionListener(this); // for event-handling
addWindowListener(this);
// "this" Frame fires WindowEvent its registered WindowEvent listener
// "this" Frame adds "this" object as a WindowEvent listener
}
/** ActionEvent handler - Called back when user clicks the button. */
@Override
public void actionPerformed(ActionEvent evt) {
// Get the String entered into the TextField tfPort, convert to int
port = Integer.parseInt(tfPort.getText());
fileLocation = tfLocation.getText();
String csvName = fileLocation;
/*
Scanner console = new Scanner(System.in);
System.out.println("Type in CSV file location: ");
//String csvName = console.nextLine();
String csvName = "C:\\Users\\I593458\\Downloads\\orders.csv";
*/
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(port);
}
catch (IOException e)
{
System.err.println("Could not listen on port: 57635.");
System.exit(1);
}
Socket clientSocket = null;
System.out.println ("Waiting for connection.....");
try {
clientSocket = serverSocket.accept();
}
catch (IOException e)
{
System.err.println("Accept failed.");
System.exit(1);
}
System.out.println ("Connection successful");
System.out.println ("Waiting for input.....");
PrintWriter out = null;
try {
out = new PrintWriter(clientSocket.getOutputStream(),
true);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader in = null;
try {
in = new BufferedReader(
new InputStreamReader( clientSocket.getInputStream()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String inputLine, outputLine;
try {
while ((inputLine = in.readLine()) != null)
{
System.out.println ("Server: " + inputLine);
tfFIXMsg.setText(inputLine);
if (inputLine.trim().equals("Bye.")) {
System.out.println("Exit program");
break;
}
Scanner input1 = new Scanner(new File(csvName));
Scanner input2 = new Scanner(new File(csvName));
Scanner input3 = new Scanner(new File(csvName));
Scanner input4 = new Scanner(new File(csvName));
String csvline = getCsvLineVal (getLocation34CSV(getTag34Value(Tag34Location(getTagCSV( parseFixMsg(inputLine ,inputLine))), getValueCSV( parseFixMsg(inputLine ,inputLine))), getVal34(input1, input2)), getCSVLine( input3, input4) );
outputLine = compareClientFixCSV( getTagCSV( parseFixMsg(inputLine ,inputLine)), getValueCSV(parseFixMsg(inputLine ,inputLine)), getCSVTag(csvline), getCSVValue(csvline));
out.println(outputLine);
tfCSVLine.setText(outputLine);
input1.close();
input2.close();
input3.close();
input4.close();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
out.close();
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
clientSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
serverSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
A: You add the textArea to a JScrollPane, and then never do anything with the pane.
jScrollPane1 = new JScrollPane(tfFIXMsg);
You need add(jScrollPane1);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/18003049",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: PromiseKit flatMapError ReactiveSwift has this great function called flatMapError that allows you to respond with an event stream when an error occurs. A simple example might look like:
authenticationProducer.flatMapError { _ in self.reauthenticate() }
Whenever an error occurs, that error gets mapped into a producer that attempts to re-authenticate.
How would I build a similar operator using PromiseKit? The function signature would look like:
func flatMapError<U>(_ transform: @escaping (Error) -> Promise<U>) -> Promise<U>
My implementation so far:
func flatMapError<U>(_ transform: @escaping (Error) -> Promise<U>) -> Promise<U> {
return Promise<U> { resolve, reject in
self.catch { error in
let promise = transform(error)
let _ = promise.then { value in
resolve(value)
}
}
}
}
A: Use recover, it behaves as you request.
https://github.com/mxcl/PromiseKit/blob/master/Sources/Promise.swift#L254-L278
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/44051126",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Is it possible to use pattern matching on functions in python? Like, a function that will respond to multiple calls I am trying to make a class that acts like a list. However, I would like to be able to use all of the built-in list repr() functions and such, Is there any way to do something like this:
class myList:
...
def __getitem__(self, index):
#custom getitem function
def __setitem(self,index,value):
#custom setitem function
def toList(self):
#returns a list
#and a catch-all case:
def __*__(*args):
return self.toList().__*__(*args)
So, My question is, is it possible to make a catch-all case for something like that in python, to catch things like __repr__, __str__, __iter__, etc.
Thanks!
A: It’s not possible to trap such calls with a single method, in CPython at least. While you can define special methods like __getattr__, even defining the low-level __getattribute__ on a metaclass doesn’t work because the interpreter scans for special method names to build a fast lookup table of the sort used by types defined in C. Anything that doesn’t actually possess such individual methods will not respond to the interpreter’s internal calls (e.g., from repr).
What you can do is dynamically generate (or augment, as below) a class that has whatever special methods you want. The readability of the result might suffer too much to make this approach worthwhile:
def mkfwd(n):
def fwd(self,*a): return getattr(self.toList(),n)(*a)
return fwd
for m in "repr","str":
m="__%s__"%m
setattr(myList,m,mkfwd(m))
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/56300707",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: OpenGL glTexImage2D cube map and width/height parameters I am trying to setup shadow mapping in OpenGL using cube maps so I can do shadows for point lights.
The following throws a GL_INVALID_ENUM at me:
for (uint32_t i = 0; i < 6; i++)
GLCALL(glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_DEPTH_COMPONENT32, windowWidth, windowHeight, 0, GL_DEPTH_COMPONENT32, GL_FLOAT, 0));
According to the docs, it is probably because of this:
GL_INVALID_ENUM is generated if target is one of the six cube map 2D image targets and the width and height parameters are not equal.
And I get if the width/height are different, they aren't really a cube, but when I have a screen resolution like 1920x1080 or any other resolution this is a problem.
Perhaps though I have missunderstod what to supply to the function call - isn't it the window width/height? What are the parameters supposed to be?
A:
Perhaps though I have missunderstod what to supply to the function call - isn't it the window width/height?
How in the world you think that the window resolution influences texture sizes is beyond me. You normally render shadow mapping depth maps using a framebuffer object, so the window dimensions are irrelevant.
What are the parameters supposed to be?
For a cube map: The edge length of the cube map texture.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/19879546",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Granular error handling in Passport authenticate I am authenticating a user in a REST call and I implement a custom callback as explained in the docs.
app.get('/login', function(req, res, next) {
passport.authenticate('local', function(err, user, info) {
//.. do something with user here and send a response
})(req, res, next);
});
Now I would like to pass an error if some validation failed in the strategy.
passport.use(new BasicStrategy(
function(email, password, callback) {
User.findOne({
email: email
}, function(err, user) {
if (err) {
return callback(err);
}
if (!user) {
return callback(new Error('User unknown'), false);
}
// Make sure the password is correct
user.verifyPassword(password, function(err, isMatch) {
if (err) {
return callback(err);
}
// Password did not match
if (!isMatch) {
return callback(new Error('Password mismatch'), false);
}
// Success
return callback(null, user);
});
});
}
But the error is never passed to the callback in authenticate:
function(err, user, info) {
// err is always null
}
How can I pass an error so I can give more granuate feedback to users?
A: I found two issues with your code. The first one is that you request for 'local' authentication strategy while you register a BasicStrategy. In order to do that you should replace 'local' with 'basic'.
The second one is that, if you want to use the BasicStrategy, you have to use the Base Authentication supported by the HTTP protocol, otherwise the BasicStrategy's callback will not be called and your authentication callback will run with err == null and user == false.
I tested this with Postman, and only after I sent Basic Auth info, did the BasicStrategy callback run.
I hope this helps.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/27534766",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Fixed row on the bottom of grid
I have summary row in my table. But user can see it only when he will scroll down all grid. But it could be better, if summary row will be fixed at the bottom of the grid, and it will be visible always, when the grid is shown. How can I modify it?
A: I'm not sure how to fix a row like you're suggesting, but for something that needs to be visible 100% of the time, have you thought about adding a top bar or a bottom bar that displays these values? You can use the displayfield xtype to show text in such a place. I'm doing this in several projects.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/9290319",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to move database calls to application server behind a firewall I would like to use BreezeJS for data access in a Durandal SPA. I have the initial app set up and working fine and uses a MVC 5 backend.
However, one of the requirements is that the public IIS server is not making calls directly to the database. In other words, the Breeze controller should call another IIS server which is behind a firewall which then connects to Sql Server.
Is this possible, and if so, what is the basic architecture?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/30484722",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Handling IAP Fullfilment results for Windows 10 Store When providing consumable In App Purchases on the Windows 10 Store, there are FullfillmentResults when ReportConsumableFullfillmentAsync is called.
The user of my app has had their IAP fullfilled by the time I get this result. This means they have their Coins/Gems/Potatoes.
But if I receive FulfillmentResult.PurchaseReverted, then what happened? How did the user just revert the purchase? Am I meant to withdraw their Coins/Gems/Potatoes?
What are scenarios behind the other error messages?
Note: I'm working with using Windows.ApplicationModel.Store
A:
But if I receive FulfillmentResult.PurchaseReverted, then what
happened? How did the user just revert the purchase? Am I meant to
withdraw their Coins/Gems/Potatoes?
The value PurchaseReverted means the transaction is canceled on the backend and users get their money back. So you should disable the user's access to the cosumable content (withdraw the Coins/Gems/Potatoes) as necessary.
What are scenarios behind the other error messages?
NothingToFulfill : The transaction id has been fulfilled or is otherwise complete
PurchasePending: The purchase is not complete. At this point it is still possible for the transaction to be reversed due to provider failures and/or risk checks. It means the purchase has not yet cleared and could still be revoked.
ServerError: There was an issue receiving fulfillment status. It might be the problem from the Store.
Succeed: The fulfillment is complete and your Coins/Gems/Potatoes can be offered again.
Here is the documentation about FulfillmentResult Enum
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/43197459",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Laravel elements in queue are processed multiple times We use the Laravel Redis Queue and a supervisor setup with multiple parallel running workers. Sometimes it happens that one element in the queue get processed multiple times.
Is there a trick, like a flag i can set or something else to avoid this behavior?
A: This is because the job messages become available for other consumers.
In your config/queue.php configuration file, each queue connection
defines a retry_after option. This option specifies how many seconds
the queue connection should wait before retrying a job that is being
processed. For example, if the value of retry_after is set to 90, the
job will be released back onto the queue if it has been processing for
90 seconds without being deleted. Typically, you should set the
retry_after value to the maximum number of seconds your jobs should reasonably take to complete processing.
See https://laravel.com/docs/5.7/queues#queue-workers-and-deployment
When a consumer receives and processes a message from a queue, the message remains in the queue. The queue doesn’t automatically delete the message. Because a queue is a distributed system, there’s no guarantee that the consumer actually receives the message (for example, due to a connectivity issue, or due to an issue in the consumer application). Therefore, the consumer must delete the message from the queue after receiving and processing it. Immediately after a message is received, it remains in the queue. To prevent other consumers from processing the message again, you should set the retry_after value to the maximum number of seconds your jobs should reasonably take to complete processing.
For Amazon SQS:
The only queue connection which does not contain a retry_after value is SQS. SQS will retry the job based on the Default Visibility Timeout which is managed within the AWS console. Amazon SQS sets a visibility timeout, a period of time during which Amazon SQS prevents other consumers from receiving and processing the message. The default visibility timeout for a message is 30 seconds.This means that other consumers can see and pickup the message again after 30 seconds.
A: If there is an exception or the job inexplicably fails, the job will automatically be retried. This will occur even if most of the job has already ran.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/39873948",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Does it have closed form solution of KL Divergence between Logistic Distributions? KL Divergence between Gaussian Distributions
As above Figure, KL divergence between Gaussian distributions has closed-form solution.
Does it have closed form solution of KL Divergence between Logistic Distributions(https://en.wikipedia.org/wiki/Logistic_distribution)?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73903434",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: how to detect which level on the dom is selected I have the following selector
$('#navigation ul li a').click(function(evt) {}
this get the elements i need, but also retries child elements.
ie i get me this as well
#navigation ul li li a // extra li
Just wondering the best way to detect what level of the dom i am selecting.
A: You can use the > which is a parent > child selector ..
look at Child Selector (“parent > child”)
you could use it something like this
$('#navigation>ul>li>a')
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/2128890",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: parseerror SyntaxError: Unexpected token < in JSON at position 1 I have an error: Unexpected token and uncaught in the promise in my code below.
function getReportData(type,shutdown,period){
var applyButton = $("#apply-filter");
var textApplyButton = applyButton.html();
applyButton.attr("disabled", true);
applyButton.html("Loading...");
startStamp = new Date().getTime();
$("#title-card").text("Loading Data..");
timerInterval = setInterval(updateInterval, 1000);
gridOptions.api.showLoadingOverlay();
$.ajax({
method: "POST",
url: "<?php echo base_url();?>api/reportApi/getPRLinesAll",
data: {type:type,shutdown:shutdown,period:period},
dataType : 'json',
headers:{api_key:"@scm-report@123"},
success : function(data){
var resData = data.data;
var columnsData = resData.columns;
var rowsData = resData.rows;
var lastUpdate = data.last_update;
var excelStyleData = resData.excelStyle;
totalData = rowsData.length;
gridOptions.api.setColumnDefs(columnsData);
gridOptions.api.setRowData(rowsData);
gridOptions.excelStyles = excelStyleData;
autoSizeAll();
if(totalData<=0){
gridOptions.api.showNoRowsOverlay();
}
fileNameExcel = generateFileName(lastUpdate);
$("#update-progress").html("Last Update on : <span class='font-strong'>"+lastUpdate+"</span>");
},
complete: function(jqXHR,textStatus){
gridOptions.api.hideOverlay();
applyButton.attr("disabled", false);
applyButton.html(textApplyButton);
clearInterval(timerInterval);
},
error: function(httpRequest, textStatus, errorThrown){
console.log("Error: " + textStatus + " " + errorThrown + " " + httpRequest);
$("#update-progress").html("Something Error, Please Try Again");
$("#title-card").text("Error happened...");
}
});
}
Error: parsererror SyntaxError: Unexpected token < in JSON at position 1 [object Object]
10.35.2.199/:1 Uncaught (in promise) Error: A listener indicated an asynchronous response by returning true, but the message channel closed before a response was received
10.35.2.199/:1 Uncaught (in promise) {message: 'A listener indicated an asynchronous response by r…age channel closed before a response was received'}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73256948",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How can I get only the object with my arrays returned from a function with a promise? I want the data in res passed to my notes variable. But it's returning a bigger nested object. Why is it happening?
If I inspect in the console the value of cleanArrayOfNotes I get the object that I want, but once its assigned to notes it becomes a quite bigger object. I understand it's part of the nature of the Promises, which at the moment I still trying to understand. Any help?
notes_service.js
var notesService = {notesObjectInService: [], newNote: null};
notesService.getAll = function() {
return $http.get('/notes.json').success(function(data){
//console.log(data)
angular.copy(data, notesService.notesObjectInService);
//console.log(notesService)
})
};
navCtrl.js
var notes = notesService.getAll().then(function(res){
var cleanArrayOfNotes = res.data;
//navCtrl line12
console.log(cleanArrayOfNotes);
return cleanArrayOfNotes;
});
//navCtrl line16
console.log(notes);
A: This should work for you:
notes_service.js
app.factory ('NoteService', function($http) {
return {
getAll: function() {
return $http.get('/notes.json').then(function(response) {
return response.data;
});
}
}
});
navCtrl.js
NotesService.getAll().then(function(res){
$scope.cleanArrayOfNotes = res.data;
});
Or, if you want to return the result rather than the promise, you can:
notes_service.js
app.factory ('NoteService', function($http) {
var notes = [];
var promise = $http.get('/notes.json').then(function(response) {
angular.copy(response.data, notes);
return notes;
});
return {
getAll: function() {
return notes;
},
promise: promise
}
});
navCtrl.js
// get array of notes
scope.cleanArrayOfNotes = NotesService.getAll();
// or use promise
NoteService.promise.then(function(response) {
scope.cleanArrayOfNotes = response.data;
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/31672288",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: WinAPI. How to redraw window which has no background? Hi I have WNDCLASSEX structure which has this data:
m_wndClass.cbSize = sizeof(WNDCLASSEX);
m_wndClass.style = CS_NOCLOSE;
m_wndClass.lpfnWndProc = WndProc;
m_wndClass.cbClsExtra = 0;
m_wndClass.cbWndExtra = 0;
m_wndClass.hInstance = GetModuleHandle(NULL);
m_wndClass.hIcon = NULL;
m_wndClass.hCursor = LoadCursor(NULL, IDC_ARROW);
m_wndClass.hbrBackground = NULL;
m_wndClass.lpszMenuName = NULL;
m_wndClass.lpszClassName = Checkbox::CHECKBOX_CLASS.c_str();
m_wndClass.hIconSm = NULL;
I need to have window without background, because I need to draw text on parent window and text may be any color.
Drawing works fine, code for drawing:
case WM_PAINT:
{
PAINTSTRUCT ps;
HDC dc = BeginPaint(window, &ps);
if (!classInfo->m_text.empty())
{
HDC wdc = GetDC(window);
SetBkMode(wdc,TRANSPARENT);
DrawText(wdc, classInfo->m_text.c_str(), -1, &classInfo->m_textRect, DT_CENTER | DT_VCENTER | DT_SINGLELINE | DT_NOCLIP);
ReleaseDC(window, wdc);
}
EndPaint(window, &ps);
break;
}
However I have method to change text of label:
void Checkbox::SetText(const String& text)
{
m_text = text;
SetTextRectSize(); //calculates size of RECT
if (m_window != NULL)
InvalidateRect(m_window, NULL, TRUE);
}
After I create window with label I see label, however if I want to change text on it, it doesn't change (I need to manualy resize window and it changes after that). However I hadn't have this problem at the time when I used to have colored background, for example my window class had this:
m_wndClass.hbrBackground = HBRUSH(COLOR_3DFACE+1);
I want to ask, how to update window which, has no background.
EDIT: I have tried some stuff
FillRect(dc, &rect, (HBRUSH)GetStockObject(NULL_BRUSH));
also tried to change window procedure:
case WM_CTLCOLORSTATIC:
{
HDC hdc = (HDC) wp;
SetBkMode (hdc, TRANSPARENT);
return (LRESULT)GetStockObject(NULL_BRUSH);
}
And the result is that I draw new text on previous, after setting text into some longer text part of label becomes corupted! see this but after resizing the main window my label becomes readable.
A: Your code doesn't set the device context's text foreground color for DrawText(), although the default is black. See SetTextColor().
SetBkMode(..., TRANSPARENT) just sets the background color/mode for the DrawText() rect, not the entire window.
A: You are asking about how to draw the window so it is transparent, but the problem isn't with the drawing at all.
The answer is essentially that everything you have done so far towards making a transparent window is wrong. It looks like the window is transparent, but in fact it is not, as you can see from the behaviour you describe when you move and resize the window. That's the classic symptom.
In other words, you haven't made the window transparent, you have just stopped drawing the background. What you see as the background is just whatever happened to be underneath the window when it was first drawn.
You need make a Layered window. To find out how to make transparent windows, go here:
*
*http://msdn.microsoft.com/en-us/library/ms997507.aspx
A: Do you want Text/Check/Label be transparent on parent form?
You can Add WS_CLIPSIBLINGS and WS_EX_TRANSPARENT..
Use SetBkMode(hDC, TRANSPARENT) When WM_PAINT message
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/18608852",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: C++: Containers of Arbitrary Template Type In C++, suppose I have a templatized class, like
template <typename T>
class Foo
{
...
};
and suppose that I have several kinds of Foo objects, like
Foo<int> intFoo = Foo<int>();
Foo<double> doubleFoo = Foo<double>();
...
and so on.
Actually, its worse than that. I really want an intFoo object of a class that inherits from Foo< int >, for instance.
I would like to do something like this:
std::vector<Foo<?> > aVector;
aVector.push_back(intFoo);
aVector.push_back(doubleFoo);
Keeping in mind that I have substantially oversimplified my design case, is there a simple way to do this?
A: Foo<int> and Foo<double> are 2 different classes despite they share the name Foo, so you can't just put them to vector as is. But you can use boost::variant and store a vector of variants.
A: A solution would be to have your Foo inheriting from an empty base class
struct CommonBase {};
template<typename T>
class Foo : public CommonBase
{
// ...
};
and then have a container of pointers to the common base
vector<CommonBase*> v;
If you want to keep away from inheritance, you could use boost:any to store any type in your container.
An interesting topic to look into (if you want to manually implement this kind of things) is type erasure
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/23812603",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Prometheus sum of different Counters having common lables I have two counters like below . Both counter have common label interface_name.
Counter A=
{app_kubernetes_io_component="xyz-rest-ep",interface_name="N7",command="create","job="kubernetes-pods",monitor="prometheus",namespace="xyz-foo",pod="xyz-rest-ep-9f5686bc-dvtjr",pod_template_hash="9f5686bc",}
Counter B=
{app_kubernetes_io_component="xyz-rest-ep",interface_name="N7",command="delete",job="kubernetes-pods",monitor="prometheus",namespace="xyz-foo",pod="xyz-rest-ep-9f5686bc-dvtjr",pod_template_hash="9f5686bc",target_base_url="http://192.168.102.50:7044/"}
I would like to have addition of counter A and counter B by interface_name lable.
Note that Counter B have extra label as target_base_url which is absent in Counter A
Kindly let us know how to achieve this in Prometheus query.
A: You should take a look at the Vector matching section, especially at the on/ignoring keywords. If you just want to do an operation like counterA + counterB a query similar to:
counterA + ignoring(target_base_url) counters
should work. This will sum both counters matching on all labels except the target_base_url. If you want to match only on a subset of the labels you could use the on keyword.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/61294395",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Using Stata Variable Labels in R I have a bunch of Stata .dta files that I would like to use in R.
My problem is that the variable names are not helpful to me as they are like "q0100," "q0565," "q0500," and "q0202." However, they are labelled like "psu," "number of pregnant," "head of household," and "waypoint."
I would like to be able to grab the labels ("psu," "waypoint," etc. . .) and use them as my variable/column names as those will be easier for me to work with.
Is there a way to do this, either preferably in R, or through Stata itself? I know of read.dta in library(foreign) but don't know if it can convert the labels into variable names.
A: You can convert the variable labels to variable names from within Stata before exporting it to a R or text file.
As Ian mentions, variable labels usually do not make good variable names, but if you convert spaces and other characters to underscores and if your variable labels aren't too long, you can re-label your vars with the varlabels quite easily.
Below is an example using the inbuilt Stata dataset "cancer.dta" to replace all variable names with var labels--importantly, this code will not try to rename variable with no variable labels. Note that I also picked a dataset where there are lots of characters that aren't useful in naming a variable (e.g.: =, 1, ', ., (), etc)...you can add any characters that might be lurking in your variable labels to the list in the 5th line: "local chars "..." " and it will make the changes for you:
****************! BEGIN EXAMPLE
//copy and paste this code into a Stata do-file and click "do"//
sysuse cancer, clear
desc
**
local chars "" " "(" ")" "." "1" "=" `"'"' "___" "__" "
ds, not(varlab "") // <-- This will only select those vars with varlabs //
foreach v in `r(varlist)' {
local `v'l "`:var lab `v''"
**variables names cannot have spaces or other symbols, so::
foreach s in `chars' {
local `v'l: subinstr local `v'l "`s'" "_", all
}
rename `v' ``v'l'
**make the variable names all lower case**
cap rename ``v'l' `=lower("``v'l'")'
}
desc
****************! END EXAMPLE
You might also consider taking a look at Stat Transfer and it's capabilities in converting Stata to R datafiles.
A: Here's a function to evaluate any expression you want with Stata variable labels:
#' Function to prettify the output of another function using a `var.labels` attribute
#' This is particularly useful in combination with read.dta et al.
#' @param dat A data.frame with attr `var.labels` giving descriptions of variables
#' @param expr An expression to evaluate with pretty var.labels
#' @return The result of the expression, with variable names replaced with their labels
#' @examples
#' testDF <- data.frame( a=seq(10),b=runif(10),c=rnorm(10) )
#' attr(testDF,"var.labels") <- c("Identifier","Important Data","Lies, Damn Lies, Statistics")
#' prettify( testDF, quote(str(dat)) )
prettify <- function( dat, expr ) {
labels <- attr(dat,"var.labels")
for(i in seq(ncol(dat))) colnames(dat)[i] <- labels[i]
attr(dat,"var.labels") <- NULL
eval( expr )
}
You can then prettify(testDF, quote(table(...))) or whatever you want.
See this thread for more info.
A: R does not have a built in way to handle variable labels. Personally I think that this is disadvantage that should be fixed. Hmisc does provide some facilitiy for hadling variable labels, but the labels are only recognized by functions in that package. read.dta creates a data.frame with an attribute "var.labels" which contains the labeling information. You can then create a data dictionary from that.
> data(swiss)
> write.dta(swiss,swissfile <- tempfile())
> a <- read.dta(swissfile)
>
> var.labels <- attr(a,"var.labels")
>
> data.key <- data.frame(var.name=names(a),var.labels)
> data.key
var.name var.labels
1 Fertility Fertility
2 Agriculture Agriculture
3 Examination Examination
4 Education Education
5 Catholic Catholic
6 Infant_Mortality Infant.Mortality
Of course this .dta file doesn't have very interesting labels, but yours should be more meaningful.
A: I would recommend that you use the new haven package (GitHub)
for importing your data.
As Hadley Wickham mentions in the README.md file:
You always get a data frame, date times are converted to corresponding R classes and labelled vectors are returned as new labelled class. You can easily coerce to factors or replace labelled values with missings as appropriate. If you also use dplyr, you'll notice that large data frames are printed in a convenient way.
(emphasis mine)
If you use RStudio this will automatically display the labels under variable names in the View("data.frame") viewer pane (source).
Variable labels are attached as an attribute to each variable. These are not printed (because they tend to be long), but if you have a preview version of RStudio, you’ll see them in the revamped viewer pane.
You can install the package using:
install.packages("haven")
and import your Stata date using:
read_dta("path/to/file")
For more info see:
help("read_dta")
A: When using the haven package:
if the data set you are importing is heavy, viewing the data in Rstudio might not be optimal.
You can instead get a data.frame with column names, column labels and an indicator for whether the column is labelled:
d <- read_dta("your_stata_data.dta")
vars <- data.frame(
"name" = names(d),
"label" = sapply(d, function(x) attr(x, "label")) %>% as.character(),
"labelled" = sapply(d, is.labelled) )
Note: need to use as.characted in order to avoid NULL in the labels being dropped and therefore ending up with different vector lengths.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/2151147",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "23"
}
|
Q: Supported Device - Android I am uploading an app to the playstore and it is showing
Supported devices:
5569
Unsupported devices:
9628
Can someone please confirm me the total supported devices for:
minSdkVersion 21
targetSdkVersion 26
I am not using any hardware dependent features in the app.
How can increase these numbers.
Thanks.
A: The lower an Android API version becomes, the more devices it supports. Thus, if the desire is to increase the amount of supported devices, it is best to decrease the API version, so long as the functionality you have already created is not impeded.
Here is data based on the number of devices that support each API as of January 8th, 2018:
A: The Android version is not the only condition, maybe your application uses devices such as GPS, accelerometers, sensors, telephony, minimal screen resolution etc that not all Android devices have/support them.
In general, more permissions declared in your app manifest means less compatible devices.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/48570245",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Passing parameter between thread C# i have a regular multithread which process a parameter/value
public void testThread (int fib)
{
int a = 1;
int fib2 = fib + a;
Console.WriteLine(" Thread : "+fib);
}
how can i pass the result value back to MainThread or another Thread ?
A: You usually pass data between threads by writing the data into some shared data structure, like a queue that one thread is writing to and another thread is reading from.
There are other explicit ways, however. For example, if you are trying to get data from a background thread to the UI thread, so you can invoke UI API's with that data, then there are techniques to execute bits of code on other thread contexts.
For example, you can use the Task class from System.Threading.Tasks to start a task on the UI thread if you know the TaskScheduler associated with the UI thread. You can get that from TaskScheduler.FromCurrentSynchronizationContext() when your code is executing on the UI thread, and save it in a static variable to use later.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/45490819",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How don't let draggable div go outside of the screen I have this code:
$("#drag").draggable({
cursor: "move",
start: function() {
$("#drag").css("transform", "translate(0, 0)")
}
});
#main-div {
text-align: center;
}
#drag {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
z-index: 200;
}
#content {
position: relative;
background-color: red;
width: 500px;
height: 500px;
}
<div id="main-div">
<h1>Bla bla.. Some text</h1>
</div>
<div id="drag">
<div id="content">
<button>I'm a button</button>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js" integrity="sha256-VazP97ZCwtekAsvgPBSUwPFKdrwD3unUfSGVYrahUqU=" crossorigin="anonymous"></script>
The dragging works good but I found a problem when I drag this div out of the screen. There is no scroll (which is good because I don't want scroll) so I can't drag this div back.
I tried to find solution but the only thing that I found was with scrolling and I don't want scrolling.
How can I prevent from dragging outside of the screen?
Thanks in advance and sorry for my english.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/44330939",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Zipping a directory to a remote location in Java I'm trying to create a zip file from a directory in Java, then place that file on a remote server (a network share). I'm currently getting an error because the Java File object cannot reference a remote location and I'm not really sure where to go from there.
Is there a way to zip a directory in Java to a remote location without using the File class?
A: Create the ZIP file locally and use either commons-net FTP or SFTP to move the ZIP file across to the remote location, assuming that by "remote location" you mean some FTP server, or possibly a blade on your network.
If you are using the renameTo method on java.io.File, note that this doesn't work on some operating systems (e.g. Solaris) where the locations are on different shares. You would have to do a manual copy of the file data from one location to another. This is pretty simple using standard Java I/O.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/1329220",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Wrong owner upon file creation in particular directory I'm facing @subj . If I try to create a file/dir in my home directory it gets created as root:daemon instead of user:staff. I found this behaviour only for one directory ( all the other dirs aren't affected).
It used to create files properly before and now it sets root:daemon with 644.
I can't see any guid or sticky bits, etc.
What do I miss?
$ whoami
user
$ pwd
/home/user
$ touch 1
$ ll 1
-rw-r--r-- 1 root daemon 0 Jul 31 09:50 1
$ ls -ld /home/user/
drwxr-xr-x 13 user staff 4096 Jul 31 09:50 /home/user/
$ ls -ld /home/
drwxr-xr-x 5778 root staff 450560 Jul 31 08:21 /home/
$ umask
0022
A: I might be due to file access control set to root:daemon. If you run
getfacl /home/user
it should tell you if that was the problem. If yes, then you can set per-folder with the command setfacl with the parameters you prefer.
Another cause that comes to my mind is if that is a mountpoint masked with those particular user and group; you can check that with cat /etc/fstab.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/63189839",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Gcloud LoadBalancer: change Google Managed certificate without downtime I intend to use Gcloud managed certificate. The way it works is that I already have a custom certificate managed by Let's Encrypt, which is assigned to my LoadBalancer. Now I want to swich to the Google Managed certificate. In order to achieve this I have to point the domains to the LoadBalncer's IP, then go to Load balancing components page, then I have to create the Google Managed certificate at the CERTIFICATES tab and, finally, edit the LoadBalancer to change its Frontend Configuration of HTTPS protocol and select the newly created certificate. Then, and only then, GCP will be allowed to provision the certificate. The problem is that it may take a few minutes (like 10 minutes) to the certificate to be provisioned. During this time my application will eventually lose the certificate and the browser will block it. This is not an acceptable scenario for us.
So, in short, I need to replace the certificate of the LoadBalancer to another one not yet verifyed which will cause my application to be out for the time it takes to provision it. The ideal scenario would be to provision the certificate first, then edit the LoadBalancer to bind it with the new certificate.
Is there any way to achieve this? Otherwise I will have to still issue my certificates with Let's Encrypt and manually replace it every time it's about to expire.
A: A load balancer front end can have more than one certificate attached.
Create a new managed certificate and attach it to the front end.
Once you have more than one certificate attached, you can then remove the one you no longer want to use without downtime.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/73640772",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: nhibernate: what are the best practices for implementing equality? I think that Entities should implement equality by primary key comparison as default, but the nhibernate documentation recommends using business identity:
The most obvious way is to implement Equals()/GetHashCode() by comparing the identifier value of both objects. If the value is the same, both must be the same database row, they are therefore equal (if both are added to an ISet, we will only have one element in the ISet). Unfortunately, we can't use that approach. NHibernate will only assign identifier values to objects that are persistent, a newly created instance will not have any identifier value! We recommend implementing Equals() and GetHashCode() using Business key equality.
Business key equality means that the Equals() method compares only the properties that form the business key, a key that would identify our instance in the real world (a natural candidate key)
And the example (also from the doc):
public override bool Equals(object other)
{
if (this == other) return true;
Cat cat = other as Cat;
if (cat == null) return false; // null or not a cat
if (Name != cat.Name) return false;
if (!Birthday.Equals(cat.Birthday)) return false;
return true;
}
This got my head spinning because the notion of business identity (according to the example) is the same as comparison by syntax, which is basically the type of semantics I associate with ValueObjects. The reason for not using database primary keys as comparison values is because this will change the hashcode of the object if the primary key is not generated on the client side (for ex incremental) and you use some sort of hashtable collection (such as ISet) for storing your entities.
How can I create a good equality implementation which does not break the general rules for equality/hashcode (http://msdn.microsoft.com/en-us/library/bsc2ak47.aspx) and conforms to nhibernate rules as well?
A: This is a known issue with ORM. Here I outline the solutions I know about and give a few pointers.
1 Surrogate/primary key: auto-generated
As you mentionned, if the object has not been saved, this doesn't work.
2 Surrogate/primary key: assigned value
You can decide to assign the value of the PK in the code, this way the object has always an ID and can be used for comparison. See Don't let hibernate steal your identity.
3 Natural key
If the object has another natural key, other than the primary key, you can use this one. This would be the case for a client entity, which has a numeric primary key and a string client number. The client number identifies the client in the real world and is a natural key which won't change.
4 Object values
Using the object values for equality is possible. But is has other shortcomings has you mentioned. This can be problematic if the values changes and the object is in a collection. For instance, if you have a Set with two objects that were different at first, but then you change the values while they are reference in the set so that they become equal. Then you break the contract of the Set. See Hibernate equals and hashcode.
5 Mixed: value + autogenerate primary/surrogate keys
If the objects to compare have an ID already, use it. Otherwise, use the object values for comparison.
All have some pros and cons. IMHO, the best is 3, if it is possible with your domain model. Otherwise, I've used 5 and it worked, though there are still some trap when using collections. I never used 2 but that sounds also a sensible solution, if you find a way to generate the PK in the code. Maybe other people have pointers for this one.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/2100226",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: how to avoid code duplication with const and non-const member functions being input into templates when attempting to get functions' signatures when they are input into templates its fairly easy, just do the following:
template <class OutType, class... ArgTypes>
void foo(OutType (*func)(ArgTypes...));
it is only marginally more complicated to get a non-static member function:
template <class OutType, class MemberOf, class... ArgTypes>
void foo(OutType (MemberOf::*func)(ArgTypes...));
// or
template <class OutType, class MemberOf, class... ArgTypes>
void foo(OutType (MemberOf::*func)(ArgTypes...) const);
but how exactly do you combine the two function declarations above into one when it doesn't matter whether or not the input method is const?
A: Unfortunately, the presence or absence of const on a non-static member function is not a feature that can be deduced separately from the function type it appertains to. Therefore, if you want to write a single foo template declaration that is limited to accepting pointers to members (but accepts both const and non-const member functions) then it would have to be:
template <class MemberOf, class F>
void foo(F MemberOf::*func);
For example:
#include <type_traits>
template <class MemberOf, class F>
void foo(F MemberOf::*func) {
static_assert(std::is_same<F, void(int) const>::value);
}
struct S {
void bar(int) const {}
};
int main() {
foo(&S::bar);
}
You cannot have F's argument types deduced at that point. You would have to dispatch to a helper function. (But we cannot deduce all the types at once while also writing a single declaration that accepts both const and non-const. If that's the only thing you'll accept, then sorry, it's not possible.) We can do this like so:
template <class T>
struct remove_mf_const;
template <class R, class... Args>
struct remove_mf_const<R(Args...)> {
using type = R(Args...);
};
template <class R, class... Args>
struct remove_mf_const<R(Args...) const> {
using type = R(Args...);
};
template <bool is_const, class F, class OutType, class MemberOf, class... ArgTypes>
void foo_helper(F func, OutType (MemberOf::*)(ArgTypes...)) {
// now you have all the types you need
}
template <class MemberOf, class F>
void foo(F MemberOf::*func) {
static_assert(std::is_function<F>::value, "func must be a pointer to member function");
using NonConstF = typename remove_mf_const<F>::type;
constexpr bool is_const = !std::is_same<F, NonConstF>::value;
foo_helper<is_const>(func, (NonConstF MemberOf::*)nullptr);
}
Coliru link
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/58224846",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Android Thread Pool to manage multiple bluetooth handeling threads? So I have my Android Bluetooth application that has it's host and clients. The problem is, because I am making multiple connections, I need a thread to handle each connection. That's all milk'n'cookies, so I thought I'd stick all the threads in an array. A little research says a better method to doing this is using a Thread Pool, but I can't seem to get my head around how that works. Also, is it actually even possible to hold threads in an array?
A: A thread pool is built around the idea that, since creating threads over and over again is time-consuming, we should try to recycle them as much as possible. Thus, a thread pool is a collection of threads that execute jobs, but are not destroyed when they finish a job, but instead "return to the pool" and either take another job or sit idle if there is nothing to do.
Usually the underlying implementation is a thread-safe queue in which the programmer puts jobs and a bunch of threads managed by the implementation keep polling (I'm not implying busy-spinning necessarily) the queue for work.
In Java the thread pool is represented by the ExecutorService class which can be:
*
*fixed - create a thread pool with a fixed number of threads
*cached - dynamically creates and destroys threads as needed
*single - a pool with a single thread
Note that, since thread pool threads operate in the manner described above (i.e. are recycled), in the case of a fixed thread pool it is not recommended to have jobs that do blocking I/O operations, since the threads taking those jobs will be effectively removed from the pool until they finish the job and thus you may have deadlocks.
As for the array of threads, it's as simple as creating any object array:
Thread[] threads = new Thread[10]; // array of 10 threads
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/9707395",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Uncaught ReferenceError: getSelectedOption is not defined at HTMLButtonElement.document.getElementById.onclick I am a super beginner in javascript and html and doing an experiment to build an webapp.
I ran npm install http-server -g and http-server '' -o and it opened up a browser tab. But in the console, I get this error and cannot identify what is causing the problem.
Uncaught ReferenceError: getSelectedOption is not defined
at HTMLButtonElement.document.getElementById.onclick (app.js:5)
document.getElementById.onclick @ app.js:5
In the browser I see a pull down menu and Refresh button. So why is getSelectedOption not defined?? I'm not sure if it's related to this problem, but even though I click the button, console.log("clicked!") doesn't print anything.
Here is my index.html
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"> </script>
<script type="text/javascript" src="app.js" defer></script>
</head>
<body>
<form>
<div class="form-group">
<label>Store ID</label>
<select class="form-control" id="company">
<option selected>All</option>
<option>Air France</option>
<option>Lufthansa</option>
</select>
<button class="btn btn-primary" type='button' id="button">Refresh</button>
</div>
</form>
</body>
Here is my app.js
console.log("button", document.getElementById("button"))
document.getElementById('button').onclick = function(){
console.log("clicked!")
let company = getSelectedOption('company');
let headers = new Headers()
let init = {
method : 'GET',
headers : headers
}
let params = {
'company':company
}
$.get( "/getmethod/<params>" );
$.get("/getpythondata", function(data) {
console.log($.parseJSON(data))
})
A: You need to use document.getElementById('company').value to get value of select box.i.e :
console.log("button", document.getElementById("button"))
document.getElementById('button').onclick = function() {
console.log("clicked!")
let company = document.getElementById('company').value;//get value of select box
console.log(company)
let headers = new Headers()
let init = {
method: 'GET',
headers: headers
}
let params = {
'company': company
}
$.get("/getmethod/<params>");
$.get("/getpythondata", function(data) {
console.log($.parseJSON(data))
})
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<div class="form-group">
<label>Store ID</label>
<select class="form-control" id="company">
<option selected>All</option>
<option>Air France</option>
<option>Lufthansa</option>
</select>
<button class="btn btn-primary" type='button' id="button">Refresh</button>
</div>
</form>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/62117053",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Java initializing iVars outside the scope of any method New to Java, and I am a little confused about this piece of code:
public class CitiesDialog extends DialogFragment {
private AsyncHttpClient client = new AsyncHttpClient();
}
client is being initialized outside the scope of any method. What does this exactly mean? Does each instance of CititiesDialog have a separate client object? Or is this some sort of static/class variable ?
And lastly, is this the norm in Java? to initialize variables outside the scope of constructors/methods, etc...
Thanks
A: client is an instance variable of CitiesDialog
every CitiesDialog that you make is going to have it's own client.
That kind of initialization is just for when you first make an instance of your class. you can change client afterwards.
A: This is perfectly normal to see in Java.
What you see here is private AsyncHttpClient, which is by itself just a class variable.
Then you see the declaration new AsyncHttpClient(), which gets assigned to client. This will happen for every new object that gets created.
To address whether this is the norm? I think yes, a common use case is lists, it is best to initialize them as early as possible:
public class A {
private final List<String> list = new ArrayList<>();
}
This will prevent that you get a NPE at a later point, because you have forgotten to declare the list.
One other thing that also helps is to declare the field final if it should never be changed after assignment, then it is also ensured by the compiler that the field gets initialized either in the declaration or in a constructor.
A:
Does each instance of CititiesDialog have a separate client object?
Yes, since it is not marked as static.
is this the norm in Java? to initialize variables outside the scope of constructors/methods, etc...
It's not abnormal, especially if you have multiple constructors and do not want to duplicate initialization.
A:
And lastly, is this the norm in Java? to initialize variables outside the scope of constructors/methods
Actually this is just syntactic sugar which eliminates the need to repeat the same initialization in each costructor. When compiled, the initialization code will become a part of each constructor (except those which delegate to other constructors).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/22568456",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Scrolling SwipeRefreshLayout with RecyclerView Refresh anywhere in android 2.2 I have problem with my layout, I created SwipeRefreshLayout with RecyclerView inside.
in android 4.2.2+ all is working good, but in andorid 2.3.4 I cant to scroll up because in any place in the RecyclerView it will refresh, and I must to scroll down and then scroll up.
This is my code:
<android.support.v4.widget.SwipeRefreshLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/forum_swipe_container"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/LVP"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:gravity="center" />
</android.support.v4.widget.SwipeRefreshLayout>
I found this issue:https://code.google.com/p/android/issues/detail?id=78191 but no a solution.
Any idea how to fix it?
A: I fixed the scroll up issue using the following code :
private RecyclerView.OnScrollListener scrollListener = new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
LinearLayoutManager manager = ((LinearLayoutManager)recyclerView.getLayoutManager());
boolean enabled =manager.findFirstCompletelyVisibleItemPosition() == 0;
pullToRefreshLayout.setEnabled(enabled);
}
};
Then you need to use setOnScrollListener or addOnScrollListener depending if you have one or more listeners.
A: Unfortunately, this is a known issue and will be fixed in a future release.
https://code.google.com/p/android/issues/detail?id=78191
Meanwhile, if you need urgent fix, override canChildScrollUp in SwipeRefreshLayout.java and call recyclerView.canScrollVertically(mTarget, -1). Because canScrollVertically was added after gingerbread, you'll also need to copy that method and implement in recyclerview.
Alternatively, if you are using LinearLayoutManager, you can call findFirstCompletelyVisibleItemPosition.
Sorry for the inconvenience.
A: You can disable/enable the refresh layout based on recyclerview's scroll ability
public class RecyclerSwipeRefreshHelper extends RecyclerView.OnScrollListener{
private static final int DIRECTION_UP = -1;
private final SwipeRefreshLayout refreshLayout;
public RecyclerSwipeRefreshHelper(
SwipeRefreshLayout refreshLayout) {
this.refreshLayout = refreshLayout;
}
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
refreshLayout.setEnabled((recyclerView.canScrollVertically(DIRECTION_UP)));
}
}
A: override RecyclerView's method OnScrollStateChanged
mRecyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
// TODO Auto-generated method stub
//super.onScrollStateChanged(recyclerView, newState);
try {
int firstPos = mLayoutManager.findFirstCompletelyVisibleItemPosition();
if (firstPos > 0) {
mSwipeRefreshLayout.setEnabled(false);
} else {
mSwipeRefreshLayout.setEnabled(true);
if(mRecyclerView.getScrollState() == 1)
if(mSwipeRefreshLayout.isRefreshing())
mRecyclerView.stopScroll();
}
}catch(Exception e) {
Log.e(TAG, "Scroll Error : "+e.getLocalizedMessage());
}
}
Check if Swipe Refresh is Refreshing and try to Scroll up then you got error, so when swipe refresh is going on and i try do this mRecyclerView.stopScroll();
A: You can override the method canChildScrollUp() in SwipeRefreshLayout like this:
public boolean canChildScrollUp() {
if (mTarget instanceof RecyclerView) {
final RecyclerView recyclerView = (RecyclerView) mTarget;
RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
if (layoutManager instanceof LinearLayoutManager) {
int position = ((LinearLayoutManager) layoutManager).findFirstCompletelyVisibleItemPosition();
return position != 0;
} else if (layoutManager instanceof StaggeredGridLayoutManager) {
int[] positions = ((StaggeredGridLayoutManager) layoutManager).findFirstCompletelyVisibleItemPositions(null);
for (int i = 0; i < positions.length; i++) {
if (positions[i] == 0) {
return false;
}
}
}
return true;
} else if (android.os.Build.VERSION.SDK_INT < 14) {
if (mTarget instanceof AbsListView) {
final AbsListView absListView = (AbsListView) mTarget;
return absListView.getChildCount() > 0
&& (absListView.getFirstVisiblePosition() > 0 || absListView.getChildAt(0)
.getTop() < absListView.getPaddingTop());
} else {
return mTarget.getScrollY() > 0;
}
} else {
return ViewCompat.canScrollVertically(mTarget, -1);
}
}
A: Following code is working for me, please ensure that it is placed below the binding.refreshDiscoverList.setOnRefreshListener{} method.
binding.swipeToRefreshLayout.setOnChildScrollUpCallback(object : SwipeRefreshLayout.OnChildScrollUpCallback {
override fun canChildScrollUp(parent: SwipeRefreshLayout, child: View?): Boolean {
if (binding.rvDiscover != null) {
return binding.recyclerView.canScrollVertically(-1)
}
return false
}
})
A: Based on @wrecker answer (https://stackoverflow.com/a/32318447/7508302).
In Kotlin we can use extension method. So:
class RecyclerViewSwipeToRefresh(private val refreshLayout: SwipeToRefreshLayout) : RecyclerView.OnScrollListener() {
companion object {
private const val DIRECTION_UP = -1
}
override fun onScrolled(recyclerView: RecyclerView?, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
refreshLayout.isEnabled = !(recyclerView?.canScrollVertically(DIRECTION_UP) ?: return)
}
}
And let's add extension method to RecyclerView to easly apply this fix to RV.
fun RecyclerView.fixSwipeToRefresh(refreshLayout: SwipeRefreshLayout): RecyclerViewSwipeToRefresh {
return RecyclerViewSwipeToRefresh(refreshLayout).also {
this.addOnScrollListener(it)
}
}
Now, we can fix recyclerView using:
recycler_view.apply {
...
fixSwipeToRefresh(swipe_container)
...
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/27641359",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: height of HorizontalFieldManager How to display chatting data on horizontal field manager., because, i m not sure that how long my text length would be. Like as we do chat in Gmail or facebook.
If is there any other way for displaying the chat data. so please let me know now.
A: The HorizontalFieldManager will grow in height to whatever the height of the child field is (as long as the space is available).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/6276604",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Android video streaming from url I use following code to play video from a url. It works fine except that It first downloads video and then plays that video
Uri uri = Uri.parse(URL);
video.setVideoURI(uri);
video.start();
But I want to stream the live video instead of downloading it and then play
A: There are some requirements for streaming to work.
The file might not be encoded "correctly"
http://developer.android.com/guide/appendix/media-formats.html
For video content that is streamed over HTTP or RTSP, there are additional requirements:
*
*For 3GPP and MPEG-4 containers, the moov atom must precede any mdat atoms, but must succeed the ftyp atom.
*For 3GPP, MPEG-4, and WebM containers, audio and video samples corresponding to the same time offset may be no more than 500 KB apart. To minimize this audio/video drift, consider interleaving audio and video in smaller chunk sizes.
You might be on an older version of Android that doesn't support it
HTTP progressive streaming was only added in 2.2, HTTPS only supported 3.0+, Live streaming is only supported in even later versions.
A: I have work on YouTube Video streaming and that was without downloading video.
This will only work if you will play YouTube video .
You have to use YouTube API and using that you can easily manage your task.
You have to enable YouTube service and using Developer Key you can access YouTube API.
How to use YouTube API ? You can Find Here Sample code for same.
Out of that sample example i have use
PlayerViewDemoActivity.java & YouTubeFailureRecoveryActivity.java and that XMl view as per the needs.
Play Video
public class PlayerViewDemoActivity extends YouTubeFailureRecoveryActivity
{
String youtube_id = "_UWXqFBF86U";
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.playerview_demo);
YouTubePlayerView youTubeView = (YouTubePlayerView) findViewById(R.id.youtube_view); // Replace your developer key
youTubeView.initialize(DeveloperKey.DEVELOPER_KEY, this);
}
@Override
public void onInitializationSuccess(YouTubePlayer.Provider provider,
YouTubePlayer player, boolean wasRestored)
{
if (!wasRestored)
{
player.cueVideo(youtube_id);
}
}
@Override
protected YouTubePlayer.Provider getYouTubePlayerProvider()
{
return (YouTubePlayerView) findViewById(R.id.youtube_view);
}
}
Hope this will be help you,Let me know if you have any query.
A: Use Like this:
Uri uri = Uri.parse(URL); //Declare your url here.
VideoView mVideoView = (VideoView)findViewById(R.id.videoview)
mVideoView.setMediaController(new MediaController(this));
mVideoView.setVideoURI(uri);
mVideoView.requestFocus();
mVideoView.start();
Another Method:
String LINK = "type_here_the_link";
VideoView mVideoView = (VideoView) findViewById(R.id.videoview);
MediaController mc = new MediaController(this);
mc.setAnchorView(videoView);
mc.setMediaPlayer(videoView);
Uri video = Uri.parse(LINK);
mVideoView.setMediaController(mc);
mVideoView.setVideoURI(video);
mVideoView.start();
If you are getting this error Couldn't open file on client side, trying server side Error in Android. and also Refer this.
Hope this will give you some solution.
A: For showing buffering you have to put progressbar of ProgressDialog ,... here i post progressDialog for buffering ...
pDialog = new ProgressDialog(this);
// Set progressbar message
pDialog.setMessage("Buffering...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
// Show progressbar
pDialog.show();
try {
// Start the MediaController
MediaController mediacontroller = new MediaController(this);
mediacontroller.setAnchorView(mVideoView);
Uri videoUri = Uri.parse(videoUrl);
mVideoView.setMediaController(mediacontroller);
mVideoView.setVideoURI(videoUri);
} catch (Exception e) {
e.printStackTrace();
}
mVideoView.requestFocus();
mVideoView.setOnPreparedListener(new OnPreparedListener() {
// Close the progress bar and play the video
public void onPrepared(MediaPlayer mp) {
pDialog.dismiss();
mVideoView.start();
}
});
mVideoView.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
if (pDialog.isShowing()) {
pDialog.dismiss();
}
finish();
}
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/17407207",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Use variable to reference named binding in an Ecto Query I'm trying to build a function that searches for a term in a field of a given table in a query.
For a query like
initial_query =
Answer
|> join(:left, [a], q in assoc(a, :question), as: :question)
|> join(:left, [a, q], s in assoc(a, :survey), as: :survey)
I would like to be able to search in the tables referenced by :question and :survey.
Now, this code works:
initial_query
|> or_where(
[question: t], #:question hard coded
fragment(
"CAST(? AS varchar) ILIKE ?",
field(t, ^field),
^"%#{search_term}%"
)
)
However, I want to have a function that takes the named binding as a parameter, but I can't find a way to do it.
My attempts:
defp search_field(initial_query, table, field, search_term) do
initial_query
|> or_where(
[{table, t}],
fragment(
"CAST(? AS varchar) ILIKE ?",
field(t, ^field),
^"%#{search_term}%"
)
)
end
Gives the error
** (Ecto.Query.CompileError) unbound variable t in query. If you are attempting to interpolate a value, use ^var
expanding macro: Ecto.Query.or_where/3
when called like this:
search_field(initial_query, :question, :text, search_text)
and
defp search_field(initial_query, table, field, search_term) do
initial_query
|> or_where(
[{^table, t}],
fragment(
"CAST(? AS varchar) ILIKE ?",
field(t, ^field),
^"%#{search_term}%"
)
)
end
Gives
** (Ecto.Query.CompileError) binding list should contain only variables or {as, var} tuples, got: {^table, t}
expanding macro: Ecto.Query.or_where/3
Is there a way to use a variable to reference a named binding in an Ecto Query?
A: So the answer to this question seems to be that there isn't a way supported by Ecto to do this. @maartenvanvliet solution works nicely, with the downside of relying on internal implementation.
My solution to this problem was to have the function search_field to always search in the last joined table, using the ... syntax described here:
# Searches for the `search_term` in the `field` in the last joined table in `initial_query`.
defp search_field(initial_query, field, search_term) do
initial_query
|> or_where(
[..., t],
fragment(
"CAST(? AS varchar) ILIKE ?",
field(t, ^field),
^"%#{search_term}%"
)
)
end
So this function would be used like this:
Answer
|> join(:left, [a], q in assoc(a, :question), as: :question)
|> search_field(:text, search_text)
|> join(:left, [a, q], s in assoc(a, :survey), as: :survey)
|> search_field(:title, search_text)
Which, in my opinion, still reads nicely, with the downside of requiring that we are able to change the initial_query.
A: The trick is to retrieve the position of the named binding in the bindings. The named bindings are stored in the %Ecto.Query{aliases: aliases} field.
def named_binding_position(query, binding) do
Map.get(query.aliases, binding)
end
def search_field(query, table, field, search_term) do
position = named_binding_position(query, table)
query
|> or_where(
[{t, position}],
fragment(
"CAST(? AS varchar) ILIKE ?",
field(t, ^field),
^"%#{search_term}%"
)
)
end
We first lookup the position of the named binding in the query.aliases. Then use this position to build the query.
Now, when we call
Answer
|> join(:left, [a], q in assoc(a, :question), as: :question)
|> join(:left, [a, q], s in assoc(a, :survey), as: :survey)
|> search_field(:question, :text, "bogus")
It should yield something like
#Ecto.Query<from a in Answer,
left_join: q in assoc(a, :question), as: :question,
or_where: fragment("CAST(? AS varchar) ILIKE ?", q.text, ^"%bogus%")>
Of note is that the {t, position} tuples in %Query.aliases to refer to the position of the named binding is an internal implementation and not documented. Therefore, could be subject to change. See https://github.com/elixir-ecto/ecto/issues/2832 for more information
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/54469604",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: How to get all filtered data rows in excel (with hidden columns)? My data sheet has filters and hidden columns. When filter(s) applies, I need to loop through all filtered data. I use:
Excel.Range visibleRange = this.UsedRange.SpecialCells(XlCellType.xlCellTypeVisible, missing) as Excel.Range;
Now visibleRange.Rows.Count is 0; use foreach loop "foreach(Excel.Range row in visibleRange.Row)" row doesn't have all the columns, chopped from the first hidden column.
How could we loop through the filtered rows?
A: I wouldn't use the SpecialCells property at all. Just iterate through every row in the UsedRange and check the Hidden property as you go.
Not sure what language you are using but here's an example in VBA:
Dim rowIndex As Range
With Worksheets("Sheet1")
For Each rowIndex In .UsedRange.Rows
If (rowIndex.Hidden) Then
' do nothing - row is filtered out
Else
' do something
End If
Next rowIndex
End With
Each row (or rather each Range object referenced by rowIndex) will contain all of the columns including the hidden ones. If you need to determine whether or not a column is hidden then just check the Hidden property but remember that this only applies to entire columns or rows:
Dim rowIndex As Range
Dim colNumber As Integer
With Worksheets("Sheet1")
For Each rowIndex In .UsedRange.Rows
If (rowIndex.Hidden) Then
' do nothing - row is filtered out
Else
For colNumber = 1 To .UsedRange.Columns.Count
' Need to check the Columns property of the Worksheet
' to ensure we get the entire column
If (.Columns(colNumber).Hidden) Then
' do something with rowIndex.Cells(1, colNumber)
Else
' do something else with rowIndex.Cells(1, colNumber)
End If
Next colNumber
End If
Next rowIndex
End With
A: Thread Necro time. Here's what I do.
'Count the total number of used rows in the worksheet (Using Column A to count on)
numFilteredCells = Application.WorksheetFunction.Subtotal(3, Range("A1:A" & Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row))
'Find Last filtered row with content
j = Range("A1").Cells(Rows.Count, 1).End(xlUp).Offset(0, 0).Row
'Subtract the total number of filtered rows with content, + 1
jTargetDataRow = j - numFilteredCells + 1
jTargetDataRow now contains the first filtered row with content, j contains the last, and numFilteredCells contains the total number of filtered rows that have content.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/1296026",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Escaping references - how to legitimately update object data? Been reading and watching escaping references and I get the idea of why and how to fix it, but I'm still confused on one thing...
What if the data does need to be updated? For example, I copied the code from the blog post down below and also added an additional class member of "email". Say the customer changed his email address. If this structure does not allow the object to be modified, how it the update done then?
Interface:
public interface CustomerReadOnly {
public String getName();
}
Customer:
public class Customer implements CustomerReadOnly {
private String name;
private String email;
public Customer(String name) {
this.name = name;
}
@Override
public String getName() {
return this.name;
}
@Override
public String toString() {
return this.name;
}
}
Records
public class CustomerRecords {
private Map<String,Customer> customerRecords;
public CustomerRecords() {
this.customerRecords = new HashMap<>();
}
public CustomerReadOnly getCustomerByName(String name) {
return this.customerRecords.get(name);
}
}
A: Java solves both issues presented in that article:
*
*Shallowly immutable data holders ➙ Records
*Read-only maps ➙ Map.copyOf
Leaking references is an important issue. But that article’s solution seems overwrought to me in its approach.
*
*Certainly creating the CustomerRecords to hold a map seems redundant and useless. Instead, use a non-modifiable map (discussed below).
*As for a "read-only" interface as view onto a mutable object, this might make sense in some limited situations. But you might also wreak havoc when the supposedly immutable "CustomerReadOnly" returns a different email address on the second call to "getEmail" after an update. Trying to be simultaneously both mutable and immutable is unwise. To handle immutability, instead make an immutable copy of the mutable state.
Records
The Records feature being previewed in Java 14 and previewed again in Java 15, and discussed by Brian Goetz, provide for shallowly immutable data holders. This special kind of class handles automatically the constructor, “getter” accessors, equals, hashCode, and toString methods behind the scenes. So your example class Customer turns into this utterly simple code:
record Customer( String name , String email ) {}
You retain the option of implementing those various methods if need be. For this example here, you might want a constructor to do data validation, ensuring non-null arguments, and specifically a non-empty name, and valid-looking email address.
Read-only Map
Java 10 gained the Map::copyOf method to instantiate a non-modifiable Map using the entries of another Map.
Map< String , Customer > customersByNameReadOnly = Map.copyOf( otherMap ) ;
So no need for defining a CustomerRecords class.
To change immutable data, make a copy
You asked:
What if the data does need to be updated? For example, I copied the code from the blog post down below and also added an additional class member of "email". Say the customer changed his email address.
If your goal is thread-safety through immutable data, then you must deal with copies of your data. If the customer represented by a Customer record object changes their email address, then you must create a new fresh Customer record object, swap any references to the old object, and let the old object go out-of-scope to become a candidate for garbage-collection.
Some folks believe in an everything-should-be-immutable approach, with programming languages designed to cater to such an approach.
Personally, I believe that to be practical some classes should be mutable while other kinds of classes should be immutable. In my view, complex business objects such as an invoice or purchase order should often be mutable. Simpler kinds of data, such as a date, should be immutable. When doing an accounting app, I expect changes to an invoice, but if the date of that invoice suddenly changes because some other invoice happens to be pointing to the same mutable date object via an “escaped reference”, then I would be mightily annoyed. To my mind, the invoice should be mutable while the date object member on that invoice should be immutable.
So I appreciate that Java gives us a “middle way”. Rather than be slavishly devoted to the everything-is-immutable approach, or frustrated by mutability in objects I expect to be stable, with Java we can pick and choose an appropriate route.
*
*When immutability is desired, use Java Records for immutable objects, and use Map.of, Set.of, and List.of (or .copyOf) for unmodifiable collections.
*When mutability is appropriate, use regular Java classes and collections.
As for that “read-only” interface on a mutable object, that seems generally to be confusing at best, and dangerous at worst. I think an object should be clearly and truly immutable or mutable, but not try to be both.
Immutable example: java.time
For examples of this, see the java.time classes that years ago supplanted the terrible date-time classes bundled with the earliest versions of Java. In java.time the classes are immutable by design, and therefore thread-safe.
LocalDate today = LocalDate.now() ;
LocalDate tomorrow = today.plusDays( 1 ) ;
In the code above, we capture the current date as seen in JVM’s current default time zone. Then we add a day to move to "tomorrow". But adding a day does not affect the original object referenced by today variable. Rather than alter (“mutate”) the original, we instantiate a new, second LocalDate object. The new object has values based on values from the original, along with our desired change (adding a day).
The java.time framework even worked out some handy naming conventions. The names to…, from…, parse, format, get…, with, and so on makes dealing with the immutability more intuitive. You may want to follow these conventions in your own coding.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/61764986",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Calling delegates in a boxing-like fashion I have often seen code examples of delegate invocation being done as follows:
`
public delegate void DelegateThreadActivity<T, U> (T sender, U e);
public event DelegateThreadActivity<Thread, System.EventArgs> OnStart = null;
public event DelegateThreadActivity<Thread, System.EventArgs> OnStop = null;
// Helper method for invocation.
public void RaiseOnStart ()
{
DelegateThreadActivity<Thread, System.EventArgs> instance = null;
try
{
instance = this.OnStart;
// OR
instance = (DelegateThreadActivity) (object) this.OnStart;
if (instance != null)
{
instance(this, System.EventArgs.Empty);
}
}
catch
{
}
}
`
Why use the [instance] object at all? At first I thought it was corporate convention but have seen seasoned developers do this as well. What is the benefit?
A: This is done because of thread safety, and prevention of exception raising in the case the delegate turns null.
Consider this code:
if (this.OnStart != null)
{
this.OnStart(this, System.EventArgs.Empty);
}
Between the execution of the if and the execution of this.OnStart, the OnStart delegate could have been manipulated (possibly changed to null, which would result in an exception).
In the form you provided in your question, a copy of the delegate is made and used when executing. Any change in the original delegate will not be reflected in the copy, which will prevent an exception from coming up. There is a disadvantage with this though: As any changes in the meantime will not be reflected in the copy, which also includes any non-null state, will result in either calling delegates already removed or not calling delegates recently added to it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/10467467",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to log selected markers in Google fusion table map My fusion table map contains about 5000 markers. I want to generate lists of selected markers. The simplest way to do this would seem te be to click on the relevant markers, and then write the IDs of these markers to a logfile. I think I should be able to use a variation on this blob/upload technique, but I can't see exactly how.
A: Upon further consideration, I decided that the simplest answer is to accumulate the IDs in an empty DIV:
google.maps.event.addListener(layer, 'click', function(e) {
newValue=document.getElementById('album').innerHTML + ':' + e.row['Bestand'].value;
document.getElementById('album').innerHTML=newValue;
});
This is just what I needed (called for help too soon?).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/30383352",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: Clear javascript on dynamic load I have a javascript plugin for a special image scroller. The scroller contains a bunch of timeout methods and a lot of variables with values set from those timeouts.
Everything works perfectly, but for the site I am working on it is required that the pages are loaded dynamically. The problem with this is when i for instance change the language on the site this is made by jquery load function meaning the content is dynamically loaded onto the site - AND the image slider aswell.
NOW here is the big problem! When I load the image slider for the second time dynamically all my previous values remains as well as the timers and everything else. Is there any way to clear everything in the javascript plugin as if it where like a page reload?
I have tried a lot of stuff so far so a little help would be much appreciated!
Thanks a lot!
A: You might want something like that to reload scripts:
<script class="persistent" type="text/javascript">
function reloadScripts()
{ [].forEach.call(document.querySelectorAll('script:not(.persistent)'), function(oldScript)
{
var newScript = document.createElement('script');
newScript.text = oldScript.text;
for(var i=0; i<oldScript.attributes.length; i++)
newScript.setAttribute(oldScript.attributes[i].name, oldScript.attributes[i].value);
oldScript.parentElement.replaceChild(newScript, oldScript);
});
}
// test
setInterval(reloadScripts, 5000);
</script>
As far as I know, there's no other way to reset a script than completely remove the old one and create another one with the same attributes and content. Not even clone the node would reset the script, at least in Firefox.
You said you want to reset timers. Do you mean clearTimeout() and clearInterval()? The methods Window.prototype.setTimeout() and Window.prototype.setInterval() both return an ID wich is to pass to a subsequent call of clearTimeout(). Unfortunately there is no builtin to clear any active timer.
I've wrote some code to register all timer IDs. The simple TODO-task to implement a wrapper callback for setTimeout is open yet. The functionality isn't faulty, but excessive calls to setTimeout could mess up the array.
Be aware that extending prototypes of host objects can cause undefined behavior since exposing host prototypes and internal behavior is not part of specification of W3C. Browsers could change this future. The alternative is to put the code directly into window object, however, then it's not absolutely sure that other scripts will call this modified methods. Both decisions are not an optimal choice.
(function()
{ // missing in older browsers, e.g. IE<9
if(!Array.prototype.indexOf)
Object.defineProperty(Array.prototype, 'indexOf', {value: function(needle, fromIndex)
{ // TODO: assert fromIndex undefined or integer >-1
for(var i=fromIndex || 0; i < this.length && id !== window.setTimeout.allIds[i];) i++;
return i < this.length ? i : -1;
}});
if(!Array.prototype.remove)
Object.defineProperty(Array.prototype, 'remove', { value: function(needle)
{ var i = this.indexOf(needle);
return -1 === i ? void(0) : this.splice(i, 1)[0];
}});
// Warning: Extensions to prototypes of host objects like Window can cause errors
// since the expose and behavior of host prototypes are not obligatory in
// W3C specs.
// You can extend a specific window/frame itself, however, other scripts
// could get around when they call window.prototype's methods directly.
try
{
var
oldST = setTimeout,
oldSI = setInterval,
oldCT = clearTimeout,
oldCI = clearInterval
;
Object.defineProperties(Window.prototype,
{
// TODO: write a wrapper that removes the ID from the list when callback is executed
'setTimeout':
{ value: function(callback, delay)
{
return window.setTimeout.allIds[window.setTimeout.allIds.length]
= window.setTimeout.oldFunction.call(this, callback, delay);
}
},
'setInterval':
{ value: function(callback, interval)
{
return window.setInterval.allIds[this.setInterval.allIds.length]
= window.setInterval.oldFunction.call(this, callback, interval);
}
},
'clearTimeout':
{ value: function(id)
{ debugger;
window.clearTimeout.oldFunction.call(this, id);
window.setTimeout.allIds.remove(id);
}
},
'clearInterval':
{ value: function(id)
{
window.clearInterval.oldFunction.call(this, id);
window.setInterval.allIds.remove(id);
}
},
'clearTimeoutAll' : { value: function() { while(this.setTimeout .allIds.length) this.clearTimeout (this.setTimeout .allIds[0]); } },
'clearIntervalAll': { value: function() { while(this.setInterval.allIds.length) this.clearInterval(this.setInterval.allIds[0]); } },
'clearAllTimers' : { value: function() { this.clearIntervalAll(); this.clearTimeoutAll(); } }
});
window.setTimeout .allIds = [];
window.setInterval .allIds = [];
window.setTimeout .oldFunction = oldST;
window.setInterval .oldFunction = oldSI;
window.clearTimeout .oldFunction = oldCT;
window.clearInterval.oldFunction = oldCI;
}
catch(e){ console.log('Something went wrong while extending host object Window.prototype.\n', e); }
})();
This puts a wrapper method around each of the native methods. It will call the native functions and track the returned IDs in an array in the Function objects of the methods. Remember to implement the TODOs.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/6545736",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: pure virtual destructors in c++ Clion and VS2019 I'm trying do declare pure virtual destructor,
in VS2019 I'm writing like that:
virtual ~A() = 0 {};
and it's fine, but in Clion don't accept that
I'm getting the following message:
pure-specifier on function-definition virtual ~A() = 0{ };
and it forces me to write a different implementation for the function (not that it to much trouble but id like to know why is that)
A: From the C++ 20 (11.6.3 Abstract classes)
*...[Note: A function declaration cannot provide both a pure-specifier and
a definition — end note] [Example:
struct C {
virtual void f() = 0 { }; // ill-formed
};
— end example]
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/58097214",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Bar colors reverting back to original colors I am using angularjs-nvd3-directives.
I have a need to color individual bars based on their values. I can do this with angularjs-nvd3-directives by using a callback that selects the bar and colors it after it is rendered.
<nvd3-multi-bar-chart
data="vm.chartData"
id="chartOne"
width="400"
height="550"
showXAxis="true"
showYAxis="true"
noData="Charts not available"
delay="2400"
yAxisTickFormat="vm.yAxisTickFormatFunction()"
forcey="[0,9]"
callback="vm.colorFunction()"
objectequality="true">
<svg></svg>
</nvd3-multi-bar-chart>
my selector in the callback function looks like this:
d3.selectAll("rect.nv-bar")
.style("fill", function(d, i){
return d.y > 50 ? "red":"blue";
});
Overall, using angularjs-nvd3-directives has been nice and has saved me some time however using selectors to customize charts after they are rendered seems like a lot of work (color individual bars, color x/y axis, etc...).
The problem at hand is that when the window is resized, it reverts back to its original color of blue. Is there a way to preserve my updates to the bar? Do I need to write my own event for window.onresize (which I have tried and doesn't seem to work)?
A: As much as I didn't want to, I ended up writing my own directive for my charts and now I have complete control over the charts without having to write a ton of code to undo what angularjs-nvd3-directives did in a callback.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/27773081",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: CKEditor text value is lost on post in BLAZOR I have a Textarea control in a Blazor applicaiton that is a CKEditor 5 WYSIWYG editor.
<div class="form-group">
<label for="image">Content</label>
<textarea id="editor" class="form-control" @bind="@PostObject.Content" />
<ValidationMessage For="@(() => PostObject.Content)" />
</div>
When the form gets submitted the value of PostObject.Content is always null. If I remove the CKEditor element the posted value is correct.
The CKEditor is initialised by calling a Javascript function called RTF on a button click (launches the form in a modal popup) -
await jsRuntime.InvokeAsync<string>("RTF", "editor");
The function is located in index.html
function RTF(editorId) {
ClassicEditor.create(document.querySelector('#' + editorId));
}
A: For me works with the function CKEDITOR.editor.getData.
https://ckeditor.com/docs/ckeditor4/latest/guide/dev_savedata.html
Your code can be changed to below
<EditForm Model="@postObject" OnValidSubmit="SaveObject">
<div class="form-group">
<DataAnnotationsValidator />
<ValidationSummary />
<InputTextArea id="editor" @bind-Value="@PostObject.Content" Class="form-control" />
</div>
<button type="submit" class="btn btn-primary">Save</button>
</EditForm>
@code {
PostObject postObject= new PostObject();
string contentFromEditor = string.Empty;
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
await jsRuntime.InvokeAsync<string>("RTF", "editor");
await base.OnAfterRenderAsync(firstRender);
}
private async Task SaveObject()
{
contentFromEditor = await JSRuntime.InvokeAsync<string>("CKEDITOR.instances.editor.getData");
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/59921004",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Can Retrofit2 be use on Android 4.1.2? My app results in fatal exception caused by Retrofit2 Is there a way to use Retrofit2 on older Android versions (for me a minimum of 4.x)?
My app works as expected on Android 6, but I get a fatal exception on Android 4.1.2:
E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.ExceptionInInitializerError
at okhttp3.OkHttpClient.newSslSocketFactory(OkHttpClient.java:263)
at okhttp3.OkHttpClient.<init>(OkHttpClient.java:229)
at okhttp3.OkHttpClient.<init>(OkHttpClient.java:202)
at retrofit2.Retrofit$Builder.build(Retrofit.java:628)
at com.example.temperaturemonitor.RESTApi.getClient(RESTApi.java:15)
This is the code causing the error (.build is RESTApi.java:15):
if (retrofit==null) {
retrofit = new Retrofit.Builder()
.baseUrl("http://192.168.1.10:5001/")
.addConverterFactory(GsonConverterFactory.create())
.build();
}
I can see that the root cause of the error appears to be okhttp3.
In build.gradle I have
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
I found at https://developer.squareup.com/blog/okhttp-3-13-requires-android-5/ that "OkHttp 3.13 Requires Android 5+". They are also maintaining 3.12 of okhttp which is Android 4.x compatible. What is not clear to me is what version of okhttp is used by Retrofit2 (I have no implementation line importing okhttp directly into to my project); my assumption is that they are using the latest version.
I would like to be able to use both my Android phones with the app once complete (and if I decide to release into the App store then including earlier versions increases the potential users). I realise that might prevent me from using some newer code features, but I can probably live with that - up to now nothing I've tried has not been possible on both versions.
My thought is that perhaps if I could make Retrofit use the okhttp3.12 library then the error would not occur.
A: It uses version 3.14.9 of okhttp. You can see that in the build.gradle file. Additionally, you could use the command gradlew app:dependencies. You should see something as follows in the output of that command:
+--- com.squareup.retrofit2:retrofit:2.9.0
| \--- com.squareup.okhttp3:okhttp:3.14.9
| \--- com.squareup.okio:okio:1.17.2
If you want to force it to use version 3.12.0 of okhttp, adding the following seems to work:
implementation ('com.squareup.okhttp3:okhttp:3.12.0') {
force = true
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/62721973",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Using a UDF MySQL query from PHP I read from the MySQL doc
For the UDF mechanism to work, functions must be written in C or C++
and your operating system must support dynamic loading.
...
A UDF contains code that becomes part of the running server, so when
you write a UDF, you are bound by any and all constraints that apply
to writing server code
I want to create a MySQL function on the fly (by submitting it with PHP's mysqli) so that I can use it in a subsequent query.
*
*Will I be unable to create a function on a basic web-hosting server's installation of MySQL (e.g. HostGator, 1and1, GoDaddy) since I'm not the root admin user?
*What is wrong with my syntax in the below query? It doesn't work either in the direct MySQL shell (the black box) or through my php script. The error returned is:
Warning: mysqli::query() [mysqli.query]: (42000/1064): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'delimiter // create function IF NOT EXISTS LeaveNumber(str varchar(50)) retur' at line 1 in C:\wamp\www_quac\includes\database.php on line 55
This is my query in php:
if ($Database->query("
delimiter //
create function IF NOT EXISTS LeaveNumber(str varchar(50)) returns varchar(50)
no sql
begin
declare verification varchar(50);
declare result varchar(50) default '';
declare character varchar(2);
declare i integer default 1;
if char_length(str) > 0 then
while(i <= char_length(str)) do
set character = substring(str,i,1);
set verification = find_in_set(character,'1,2,3,4,5,6,7,8,9,0');
if verification > 0 then
set result = concat(result,character);
end if;
set i = i + 1;
end while;
return result;
else
return '';
end if;
end //
delimiter ;")) { echo 'hey the function was written. its called LeaveNumber()'; }
A: You have two syntax errors in your code:
*
*create function does not support if exists
*character is a reserved SQL keyword.
The below appears to work for me. I'd suggest using an SQL 'ide' such as MySQL workbench. It will show you syntax errors straight away.
DROP function IF EXISTS LeaveNumber;
delimiter //
create function LeaveNumber(str varchar(50)) returns varchar(50)
no sql
begin
declare verification varchar(50);
declare result varchar(50) default '';
declare nextChar varchar(2);
declare i integer default 1;
if char_length(str) > 0 then
while(i <= char_length(str)) do
set nextChar = substring(str,i,1);
set verification = find_in_set(nextChar,'1,2,3,4,5,6,7,8,9,0');
if verification > 0 then
set result = concat(result,nextChar);
end if;
set i = i + 1;
end while;
return result;
else
return '';
end if;
end //
delimiter ;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/23707101",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Select more than one columns when using Group By Is it possible to select more than one columns in entity framework than just key & value when doing Group By.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/24872693",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.