text
stringlengths 15
59.8k
| meta
dict |
---|---|
Q: Where to find the size of SQL Server data types I am trying to calculate the size of my database. I will have a table with 3 columns (id, int, money) I will have 26 million rows with all columns being occupied. How big will my database be? Also, where can I find the size of all SQL Server data types?
A: T-SQL has a function for that: DATALENGTH for all SQL Server versions.
Example:
DECLARE @lat DECIMAL(10, 7) = 3.14151415141514151415;
SELECT @lat, DATALENGTH(@lat);
Result:
3.1415142 and 5 (because DECIMAL(10,7) uses 5 bytes to be stored).
Documentation: https://learn.microsoft.com/en-us/sql/t-sql/functions/datalength-transact-sql?view=sql-server-ver15
For example, I have a table called Applications with these columns: (id VARCHAR(32), debug BIT, connectionString VARCHAR(2048), firebaseKey VARCHAR(4096)). As we know, VARCHAR doesn't allocate all the space (just what you need, so 'A' is 1 byte in VARCHAR).
These queries:
SELECT
SUM(DATALENGTH(id)) AS idSize,
SUM(DATALENGTH(debug)) AS debugSize,
SUM(DATALENGTH(connectionString)) AS connectionStringSize,
SUM(DATALENGTH(firebaseKey)) AS firebaseKeySize
FROM Applications;
SELECT
SUM(
DATALENGTH(id) +
DATALENGTH(debug) +
DATALENGTH(connectionString) +
DATALENGTH(firebaseKey)
) AS totalSize
FROM Applications;
will return my data size (in my case, with my rows, is 8, 2, 366, 4698 (total: 5074). There are 2 rows in that table.
Notice that this does NOT represent the total size of my database (there are pages, descriptors, indexes, etc. involved.)*
MSSQL has internal stored procedures to tell you the exactly size of your database in disk:
*
*EXEC sp_spaceused; for all database;
*EXEC sp_spaceused N'schema.TableName'; for a specific table;
*EXEC sp_helpdb N'DatabaseName'; if you want details from each file.
A: Your can use below query :
SELECT * FROM sys.types
result of above query is below :
name system_type_id user_type_id schema_id principal_id max_length precision scale collation_name is_nullable is_user_defined is_assembly_type default_object_id rule_object_id is_table_type
-------------------- -------------- ------------ --------- ------------ ---------- --------- ----- ----------------- ----------- --------------- ---------------- ----------------- -------------- -------------
image 34 34 4 NULL 16 0 0 NULL 1 0 0 0 0 0
text 35 35 4 NULL 16 0 0 Persian_100_CI_AI 1 0 0 0 0 0
uniqueidentifier 36 36 4 NULL 16 0 0 NULL 1 0 0 0 0 0
date 40 40 4 NULL 3 10 0 NULL 1 0 0 0 0 0
time 41 41 4 NULL 5 16 7 NULL 1 0 0 0 0 0
datetime2 42 42 4 NULL 8 27 7 NULL 1 0 0 0 0 0
datetimeoffset 43 43 4 NULL 10 34 7 NULL 1 0 0 0 0 0
tinyint 48 48 4 NULL 1 3 0 NULL 1 0 0 0 0 0
smallint 52 52 4 NULL 2 5 0 NULL 1 0 0 0 0 0
int 56 56 4 NULL 4 10 0 NULL 1 0 0 0 0 0
smalldatetime 58 58 4 NULL 4 16 0 NULL 1 0 0 0 0 0
real 59 59 4 NULL 4 24 0 NULL 1 0 0 0 0 0
money 60 60 4 NULL 8 19 4 NULL 1 0 0 0 0 0
datetime 61 61 4 NULL 8 23 3 NULL 1 0 0 0 0 0
float 62 62 4 NULL 8 53 0 NULL 1 0 0 0 0 0
sql_variant 98 98 4 NULL 8016 0 0 NULL 1 0 0 0 0 0
ntext 99 99 4 NULL 16 0 0 Persian_100_CI_AI 1 0 0 0 0 0
bit 104 104 4 NULL 1 1 0 NULL 1 0 0 0 0 0
decimal 106 106 4 NULL 17 38 38 NULL 1 0 0 0 0 0
numeric 108 108 4 NULL 17 38 38 NULL 1 0 0 0 0 0
smallmoney 122 122 4 NULL 4 10 4 NULL 1 0 0 0 0 0
bigint 127 127 4 NULL 8 19 0 NULL 1 0 0 0 0 0
hierarchyid 240 128 4 NULL 892 0 0 NULL 1 0 1 0 0 0
geometry 240 129 4 NULL -1 0 0 NULL 1 0 1 0 0 0
geography 240 130 4 NULL -1 0 0 NULL 1 0 1 0 0 0
varbinary 165 165 4 NULL 8000 0 0 NULL 1 0 0 0 0 0
varchar 167 167 4 NULL 8000 0 0 Persian_100_CI_AI 1 0 0 0 0 0
binary 173 173 4 NULL 8000 0 0 NULL 1 0 0 0 0 0
char 175 175 4 NULL 8000 0 0 Persian_100_CI_AI 1 0 0 0 0 0
timestamp 189 189 4 NULL 8 0 0 NULL 0 0 0 0 0 0
nvarchar 231 231 4 NULL 8000 0 0 Persian_100_CI_AI 1 0 0 0 0 0
nchar 239 239 4 NULL 8000 0 0 Persian_100_CI_AI 1 0 0 0 0 0
xml 241 241 4 NULL -1 0 0 NULL 1 0 0 0 0 0
sysname 231 256 4 NULL 256 0 0 Persian_100_CI_AI 0 0 0 0 0 0
CalculatedCreditInfo 243 257 9 NULL -1 0 0 NULL 0 1 0 0 0 1
udt_QoutaDetail 243 258 21 NULL -1 0 0 NULL 0 1 0 0 0 1
BeforeUpdate 243 259 22 NULL -1 0 0 NULL 0 1 0 0 0 1
udt_StoreInventory 243 260 26 NULL -1 0 0 NULL 0 1 0 0 0 1
udt_WKFHistory 243 261 32 NULL -1 0 0 NULL 0 1 0 0 0 1
IDTable 243 262 1 NULL -1 0 0 NULL
you can use max_length for size of each data type.
A: http://msdn.microsoft.com/en-us/library/ms187752.aspx
Money : 8 bytes
int : 4 bytes
id - depends on what you mean.
A: If the table specified in the where clause contains a nvarchar, this query will give you how many characters there are for that column correctly!
This detects if the column is "wide" and essentially divides by 2. More broad than just nvarchar.
SELECT c.name, (CASE WHEN LEFT(ts.name, 1) = 'n' AND ts.[precision] = 0 AND ts.[scale] = 0 THEN c.max_length / ts.[bytes] ELSE c.max_length END) AS [length]
FROM sys.columns AS c
INNER JOIN sys.tables AS t
ON t.object_id = c.object_ID
INNER JOIN
(
SELECT *, (CASE WHEN [bits] = -1 THEN -1 ELSE ([bits] + 7) / 8 END) AS [bytes]
FROM (
SELECT *, (CASE WHEN max_length >= 256 THEN (CASE WHEN LEFT(name, 1) = 'n' AND [precision] = 0 AND [scale] = 0 THEN 16 ELSE 8 END) ELSE max_length END) AS [bits]
FROM sys.types AS iits
) AS its
) AS ts
ON ts.user_type_id = c.user_type_id
WHERE t.name LIKE 'tb_tablename' -- LIKE is case insensitive
Of course, you can just divide max_length on sys.columns by 2 if you know the column is an nvarchar. This is more for discovering table schema in a way that seems better for if new sql data types are introduced in the future. And you so-choose to upgrade to it. Pretty small edge case.
Please edit and correct this answer if you find an edge case where
bytes and bits are incorrect.
Details:
-- ([bits] + 7) / 8 means round up
--
-- Proof:
-- o (1 bit + 7 = 8) / 8 = 1 byte used
-- o ((8 + 8 + 1 = 17 bytes) + 7 = 24) / 8 = 3 byes used
-- o ((8 + 8 + 7 = 23 bytes) + 7 = 30) / 8 = 3.75 = integer division removes decimal = 3
SELECT *, (CASE WHEN [bits] = -1 THEN -1 ELSE ([bits] + 7) / 8 END) AS [bytes]
FROM (
SELECT *, (CASE WHEN max_length >= 256 THEN (CASE WHEN LEFT(name, 1) = 'n' AND [precision] = 0 AND [scale] = 0 THEN 16 ELSE 8 END) ELSE max_length END) AS [bits]
FROM sys.types AS its
) AS ts
If someone knows that SQL Server stores the bit and byte sizes for each data type. Or a better way to get sys.columns size, please leave a comment!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/12166025",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: Why is my java animation taking up my entire CPU I made a program to display interference patterns for light waves. I did this by using the paint method on a JPanel to draw 2 sources and then drawing concentric circles around them. This would be double slit interference, so I allowed one of the sources to move around to experiment with the slit width.
The problem is that when I run this, my computer says it is using 80% of my CPU! There's really not much to it. Circle in the middle, circles around it, and it moves. My code follows.
main class:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class main {
static final int UP = -1;
static final int DOWN = 1;
static final int RIGHT = 1;
static final int LEFT = -1;
static final int NOMOVEMENT = 0;
static int verticalMovement = NOMOVEMENT;
static int horizontalMovement = NOMOVEMENT;
public static void main(String[] args) {
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Point s1 = new Point((int)(screenSize.getWidth()/3), 50);
Point s2 = new Point((int)(2*screenSize.getWidth()/3), 50);
JFrame frame = new JFrame("Physics Frame");
frame.setPreferredSize(screenSize);
PhysicsPane pane = new PhysicsPane(screenSize, 15, s1, s2);
pane.setPreferredSize(screenSize);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(pane);
frame.pack();
Timer time = new Timer(1000 / 20, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
switch (verticalMovement){
case UP:
s2.changeY(UP);
break;
case DOWN:
s2.changeY(DOWN);
break;
default:
break;
}
switch (horizontalMovement){
case RIGHT:
s2.changeX(RIGHT);
break;
case LEFT:
s2.changeX(LEFT);
break;
default:
break;
}
pane.repaint();
}
});
frame.addKeyListener(new KeyListener() {
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyPressed(KeyEvent e) {
if(e.getKeyCode()==37){
horizontalMovement = LEFT;
} else if (e.getKeyCode()==38){
verticalMovement = UP;
} else if (e.getKeyCode()==39){
horizontalMovement = RIGHT;
} else if (e.getKeyCode()==40){
verticalMovement = DOWN;
}
if(e.getKeyChar()=='a'){
pane.setWaveLength(2);
}
if(e.getKeyChar()=='s'){
pane.setWaveLength(-2);
}
}
@Override
public void keyReleased(KeyEvent e) {
switch (e.getKeyCode()){
case 37:
horizontalMovement = NOMOVEMENT;
break;
case 38:
verticalMovement = NOMOVEMENT;
break;
case 39:
horizontalMovement = NOMOVEMENT;
break;
case 40:
verticalMovement = NOMOVEMENT;
break;
}
}
});
frame.setVisible(true);
time.start();
}
}
Panel class. If there's an inefficiency with the drawing method, it would be here.
import javax.swing.*;
import java.awt.*;
public class PhysicsPane extends JPanel {
private Dimension size;
private Point[] pointArray = new Point[2];
private double waveLength;
public PhysicsPane(Dimension size, double wavelength, Point source1, Point source2) {
this.size = size;
pointArray[0] = source1;
pointArray[1] = source2;
setPreferredSize(size);
this.waveLength = wavelength;
}
@Override
public void paintComponent(Graphics g){
for (int i = 0; i < 2; i++) {
g.setColor(Color.black);
double x = this.pointArray[i].getX();
double y = this.pointArray[i].getY();
g.fillOval((int)x, (int)y, 2, 2);
for (int j = (int)waveLength; j < 1500; j+=waveLength) {
g.setColor(Color.red);
g.drawOval((int)x-(j/2+1), (int)y-(j/2+1), 2 + j, 2 + j);
}
}
}
public void setWaveLength(double increment){
this.waveLength+=increment;
}
}
Point Class: Really just puts x and y coordinates into one construct. Not important particularly
public class Point {
private double x;
private double y;
public Point(double x, double y) {
this.x = x;
this.y = y;
}
public double getX() {
return x;
}
public void setX(double x) {
this.x = x;
}
public double getY() {
return y;
}
public void setY(double y) {
this.y = y;
}
public void changeX(double dX){
this.x+=dX;
}
public void changeY(double dY){
this.y+=dY;
}
}
So what is wrong with my program? Why is such a simple animation consuming so much of my processor?
UPDATED CODE SECTION:
@Override
public void paintComponent(Graphics g){
BufferedImage bi = new BufferedImage(size.width, size.height, BufferedImage.TYPE_INT_RGB);
Graphics graphics = bi.getGraphics();
for (int i = 0; i < 2; i++) {
graphics.setColor(Color.black);
double x = this.pointArray[i].getX();
double y = this.pointArray[i].getY();
graphics.fillOval((int)x, (int)y, 2, 2);
for (int j = (int)waveLength; j < 1500; j+=waveLength) {
graphics.setColor(Color.red);
graphics.drawOval((int)x-(j/2+1), (int)y-(j/2+1), 2 + j, 2 + j);
}
}
g.drawImage(bi, 0, 0, new ImageObserver() {
@Override
public boolean imageUpdate(Image img, int infoflags, int x, int y, int width, int height) {
return false;
}
});
}
A: The improvement that I recommend is removal of unnecessary tasks being performed, notably how your code updates the pane being drawn on, even when there aren't changes.
The following update reduced CPU usage from 12% to 0% (static frame):
Timer time = new Timer(1000 / 20, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
boolean refresh = false;
switch (verticalMovement) {
case UP:
s2.changeY(UP);
refresh = true;
break;
case DOWN:
s2.changeY(DOWN);
refresh = true;
break;
default:
break;
}
switch (horizontalMovement) {
case RIGHT:
s2.changeX(RIGHT);
refresh = true;
break;
case LEFT:
s2.changeX(LEFT);
refresh = true;
break;
default:
break;
}
if (refresh == true) {
pane.repaint();
}
}
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/35615886",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Use RankX function to calculate date rank per Fiscal Year per Entity ID I would like to use the RankX function (to use the Dense feature for ties) in order to rank the dates in a table per two columns: Fiscal Year and Entity ID.
(I guess it may be easier to concatenate the two columns and just sort by that but I'm having issues with my formula still)
Below is my sample data:
My invalid dax formula which returns all 1's is:
Fiscal Purchase Index =
VAR a = 'Purchases'[Purchase_Date]
VAR b = 'Purchases'[Entity_ID]
var c = 'Purchases'[FISCAL_YEAR]
RETURN
CALCULATE (
RANKX ('Purchases', a,,1,Dense ),
FILTER (all('Purchases'),
'Purchases'[Entity_ID] = b &&
'Purchases'[FISCAL_YEAR] = c
)
)
Any help in fixing the rank formula would be very much appreciated.
Thank you
A: Use the following dax formula:
Fiscal Purchase Index =
VAR __entity = 'Purchases'[Entity ID]
var __year = 'Purchases'[FISCAL YEAR]
var __table = FILTER ( all('Purchases'), 'Purchases'[Entity ID] = __entity && 'Purchases'[FISCAL YEAR] = __year )
var __result =
RANKX(__table, Purchases[Date] ,, 1, Dense)
RETURN __result
Hope it helps.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/62824504",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Rails ActiveRecord: List parent category and sub category from self-join table I want to return a list like the one below. All category records which have a parent. Displaying parent name and category name.
I'm using a self-join (self-associated?) model 'category' in which categories can be parents of other categories.
It works with the pure SQL just below, but how can I do it with ActiveRecord?
> sql="select p.name parent, s.name category from categories s join categories p on s.parent_id=p.id"
> ActiveRecord::Base.connection.execute(sql)
(0.4ms) select p.name parent, s.name category from categories s join categories p on s.parent_id=p.id
=>
[{"parent"=>"Income", "category"=>"Available next month"},
{"parent"=>"Income", "category"=>"Available this month"},
{"parent"=>"1. Everyday Expenses", "category"=>"Fuel"},
{"parent"=>"1. Everyday Expenses", "category"=>"Groceries"},
{"parent"=>"1. Everyday Expenses", "category"=>"Restaurants"},
{"parent"=>"1. Everyday Expenses", "category"=>"Entertainment"},
{"parent"=>"1. Everyday Expenses", "category"=>"Household & Cleaning"},
{"parent"=>"1. Everyday Expenses", "category"=>"Clothing"},
{"parent"=>"1. Everyday Expenses", "category"=>"MISC"},
{"parent"=>"2. Monthly Expenses", "category"=>"Phone"},
{"parent"=>"2. Monthly Expenses", "category"=>"Rent"},
{"parent"=>"2. Monthly Expenses", "category"=>"Internet & Utilities"},
{"parent"=>"2. Monthly Expenses", "category"=>"News Subscriptions"},
{"parent"=>"2. Monthly Expenses", "category"=>"Car Registration"}]
I've been trying several queries. This appears to replicate my SQL closest, but returns nothing usable.
> Category.select('parents_categories.name as parent, categories.name as category').joins(:parent)
Category Load (0.7ms) SELECT parents_categories.name as parent, categories.name as category FROM "categories" INNER JOIN "categories" "parents_categories" ON "parents_categories"."id" = "categories"."parent_id"
=>
[#<Category:0x000055fefee12af0 id: nil>,
#<Category:0x000055fefee12a28 id: nil>,
#<Category:0x000055fefee12960 id: nil>,
#<Category:0x000055fefee12898 id: nil>,
...
This was my other try, but I'm struggling with the syntax, and it just ignores the :parent['name'] phrase
> Category.select(:parent['name'],:name).joins(:parent).first
Category Load (0.2ms) SELECT "categories"."name" FROM "categories" INNER JOIN "categories" "parents_categories" ON "parents_categories"."id" = "categories"."parent_id" ORDER BY "categories"."id" ASC LIMIT ? [["LIMIT", 1]]
=> #<Category:0x000055feff38cd78 id: nil, name: "Available next month">
Schema
create_table "categories", force: :cascade do |t|
t.string "name", null: false
t.integer "parent_id"
...
end
Model
class Category < ApplicationRecord
belongs_to :parent, class_name: "Category", optional: true
has_many :subcategories, class_name: "Category", foreign_key: :parent_id
...
end
I can't find a matching example from the Rails guide here: https://guides.rubyonrails.org/active_record_querying.html
And stackoverflow questions like this (Unable to join self-joins tables in Rails) are close but not getting me across the finish line
UPDATE: I've found a convoluted answer from this website: https://medium.com/@swapnilggourshete/rails-includes-vs-joins-9bf3a8ada00
> c = Category.where.not(parent: nil).includes(:parent)
> c_data = [ ]
> c.each do |c|
c_data << {
parent: c.parent.name,
category: c.name
}
end
[{:parent=>"Income", :category=>"Available next month"},
{:parent=>"Income", :category=>"Available this month"},
{:parent=>"1. Everyday Expenses", :category=>"Fuel"},
{:parent=>"1. Everyday Expenses", :category=>"Groceries"},
{:parent=>"1. Everyday Expenses", :category=>"Restaurants"},...]
But there must be a better way.
A: You are really close my friend. Just a little tweak and you will get what you are looking for
Category.select('parents_categories.name as parent_category, categories.name as category').joins(:parent).as_json(except: :id)
Note if you have belongs_to :parent, parent cannot be named as selected key so we need to change it to parent_category
| {
"language": "en",
"url": "https://stackoverflow.com/questions/72520446",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Rails initial page load extremely slow I've got a rails app in development mode (3.1.12 ruby 1.9.2) running on a windows server via fastcgi (with heliconzoo).
If i wait a certain amount of time from page load to page load, it takes 4-6 seconds to load the page. Afterwards it's loading with normal speed independent on which computer and in every browser.
Does the app/service shutdown if nobody visits the page within a while?
What can I do to prevent this behaviour?
e: For the first entry of today the development.log says it took 500ms to load the page which is 10 times faster...But it took 5s to load actually...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/17168237",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Core Data table to NSArray I have the following Array which retrieved from the Core Data :
NSArray *dataArray = [context executeFetchRequest:request error:&error];
so I wrote this code to get each row data individually to send it to REST API:
for (NSString *str in dataArray) {
NSString *name =[dataArray valueForKey:@"name"];
NSString *dob = [dataArray valueForKey:@"dob"];
int gender =[[dataArray valueForKey:@"gender"]integerValue];
NSString *childId =[dataArray valueForKey:@"id"];
int response = [network sendName:name withDateOfBirth:dob andGender:gender forID:childId];
if (response == 200) {
// [self performSelectorOnMainThread:@selector(postSuccess) withObject:nil waitUntilDone:YES];
NSLog(@"Success");
}
}
but it's not working, because I couldn't know how data is stored in each index in the array!!
Please help, and if I am not doing this correctly please tell me a better way to do it.
Thanks.
A: NSString *name =[dataArray valueForKey:@"name"];
This doesn't do what you think it'll do. valueForKey:, when sent to an array, returns an array of the values corresponding to the given key for all the items in the array. So, that line will assign an array of the "name" values for all the items in dataArray despite the fact that you declared name as a NSString. Same goes for the subsequent lines.
What you probably want instead is:
for (NSManagedObject *item in dataArray) {
NSString *name = [item valueForKey:@"name"];
...
Better, if you have a NSManagedObject subclass -- let's call it Person representing the entity you're requesting, you can say:
for (Person *person in dataArray) {
NSString *name = person.name;
...
which leads to an even simpler version:
for (Person *person in dataArray) {
int response = [network sendName:person.name
withDateOfBirth:person.dob
andGender:person.gender
forID:person.id];
although I'd change the name of that method to leave out the conjunctions and prepositions. -sendName:dateOfBirth:gender:id: is enough, you don't need the "with", "and", and "for."
| {
"language": "en",
"url": "https://stackoverflow.com/questions/18359521",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: actionListener associated with an h:commandLink/h:commandButton is not invoked I have a 2 forms that contain 4 buttons with each button having a an actionListener property set to call a single method in a request scoped bean. This method checks to determine what button is performing the action and then does a few things based on that information (Create, Read, Update, or Delete). The problem is that, out of these four buttons, three work. The last (update) button isn't calling the action.
This question helped a little bit as, after reading it, I managed to get the fourth button to work once (breakpoints and variable watching determined that) -- but then I stopped the program, made a small change because the page failed to not render a portion of the page (dependent of the 'editing' variable), watched it fail again, and then forgot what I did to make it work. I've determined that the problem is not nested forms, that I'm importing the right event class, that there are no validation errors, that there are no iterating tags, that the buttons are rendering and are not disabled, or any of the other points mentioned in @BalusC 's answer to that question except one -- when I use a <h:commandLink>, JS is rendered on the page that returns false although changing to a <h:commandButton> still fails to invoke the actionListener. But what's weird is that the one time is worked and the action was invoked I was using a <h:commandLink>.
Does anyone see what I'm doing wrong?
Form 1 (create; works):
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:c="http://xmlns.jcp.org/jsp/jstl/core"
xmlns:f="http://xmlns.jcp.org/jsf/core">
<h:head></h:head>
<h:body>
<ui:composition template="../../template.xhtml">
<ui:define name="top">
New Location View
</ui:define>
<ui:define name="left"></ui:define>
<ui:define name="content">
<f:view>
<h:form>
<h2><h:outputText value="Create a Location"/></h2>
<h:panelGrid columns="2">
<h:outputLabel for="locationName" value="Name:"/>
<h:inputText id="locationName" value="#{locationBean.locationName}"/>
<h:outputLabel for="locationDesc" value="Description:"/>
<h:inputText id="locationDesc" value="#{locationBean.locationDescription}"/>
<h:commandButton value="Add Location" id="createact" actionListener="#{locationBean.doAction}"/>
</h:panelGrid>
</h:form>
</f:view>
</ui:define>
</ui:composition>
</h:body>
</html>
Form 2 (Read (a details button clicked from a listing page which redirects to this one) works, Update; doesn't work, Delete; works):
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:c="http://xmlns.jcp.org/jsp/jstl/core"
xmlns:f="http://xmlns.jcp.org/jsf/core">
<h:head>
</h:head>
<h:body>
<ui:composition template="../../../template.xhtml">
<ui:define name="top">
Location Details View
</ui:define>
<ui:define name="left">
</ui:define>
<ui:define name="content">
<c:set var="location" value="#{locationBean.l}"/>
<h:form>
<h:panelGrid columns="2" rendered="#{not locationBean.editing}" >
<h:outputLabel value="Name:"/>
<h:outputText id="nameout" value="#{location.locationname}"/>
<h:outputLabel value="Description:" />
<h:outputText id="descout" value="#{location.description}"/>
<h:commandButton id="delact" actionListener="#{locationBean.doAction}" value="Delete"/>
<h:commandButton id="editact" actionListener="#{locationBean.doAction}" value="Edit"/>
</h:panelGrid>
<h:panelGrid columns="2" rendered="#{locationBean.editing}">
<h:outputLabel value="Name:" />
<h:inputText id="namein" value="#{location.locationname}" required="true" requiredMessage="There must be a name."/>
<h:outputLabel value="Description:" />
<h:inputText id="descin" value="#{location.description}" required="true" requiredMessage="There must be a description."/>
<h:commandLink id="cancelact" actionListener="#{locationBean.doAction}" value="Cancel"/>
<h:commandLink id="saveact" actionListener="#{locationBean.doAction}" value="Save"/>
</h:panelGrid>
<h:inputHidden value="#{location.identifier}" id="viewid" />
<c:catch var="error">
<h:outputLabel value="#{error.message}" />
</c:catch>
</h:form>
<h:outputText value="will also show location hours and days open and employees at this location."/>
</ui:define>
</ui:composition>
</h:body>
</html>
doAction method (called from all four buttons):
public void doAction(ActionEvent e) {
String callingID = e.getComponent().getId();
try {
if (callingID.isEmpty()) {//id is empty
FacesContext.getCurrentInstance().addMessage(callingID, new FacesMessage(
"What are you doing wrong? Actions must have a valid id.",
"Empty Strings are not a valid id."));
} else if (callingID.endsWith("delact")) {//component id is delete
this.l = lsb.getLocationToView();
lsb.delete(l);
FacesContext.getCurrentInstance().getExternalContext().redirect("/EmployeeScheduler-war/webpages/view/locations.xhtml");
} else if (callingID.endsWith("editact")) {//component id is edit
this.editing = true;
this.l = lsb.getLocationToView();
} else if (callingID.endsWith("saveact")) {//component id is save, usually after an edit action
this.editing = false;
lsb.edit(l);
} else if (callingID.endsWith("cancelact")) {//component id is cancel. usuallys after edit action
this.editing = false;
} else if (callingID.endsWith("createact")) {//component id is create. always create a new location
FacesContext.getCurrentInstance().getExternalContext().redirect("/EmployeeScheduler-war/webpages/view/locations.xhtml");
lsb.create(l);
} else if (callingID.endsWith("detailsact")) {//component id is details. alwas from list view
this.l = lsb.getLocationToView();
} else {
FacesContext.getCurrentInstance().addMessage(callingID, new FacesMessage(
"What are you doing wrong? Actions must have a valid id.",
callingID + " is not not valid."));
}
//catch any failures
} catch (RollbackFailureException ex) {
FacesContext.getCurrentInstance().addMessage(callingID, new FacesMessage(
"An error occured trying to rollback the deletion of the location: " + ex.getMessage(),
"Details: " + ex.getCause().getMessage()));
} catch (Exception ex) {
FacesContext.getCurrentInstance().addMessage(callingID, new FacesMessage(
"An error occured trying to delete the location: " + ex.getMessage(),
"Details: " + (ex.getCause() == null ? "none" : ex.getCause().getMessage())));
}
}
Template file:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">
<h:head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Employee Scheduler</title>
<link href="resources/styles/main.css" rel="stylesheet" type="text/css"/>
<ui:insert name="head"/>
</h:head>
<h:body style="margin-right:15%;margin-left:15%">
<div id="container">
<div id="header">
<div style="float: left;width:50%;margin-right: auto;">
Welcome to the BMS Employee Scheduler
</div>
<div style="float:right;width:50%;margin-left: auto;">
<h:form id="loginForm">
<h:panelGrid columns="2" cellspacing="2px" style="text-align: right">
<h:outputLabel for="usernameInput">
Username
</h:outputLabel>
<h:inputText disabled="#{login.loginDisabled}" id="usernameInput" value="#{login.username}"
required="true" />
<h:outputLabel for="passwordInput">
Password
</h:outputLabel>
<h:inputSecret disabled="#{login.loginDisabled}" id="passwordInput" value="#{login.password}"
required="true" />
<h:commandButton disabled="#{login.loginDisabled}" value="Login" action="#{login.login}" style="float: right"/>
</h:panelGrid>
</h:form>
</div>
<ui:insert name="top"/>
</div>
<div id="body">
<div id="sidebar">
<h:panelGrid columns="1" style="text-align: left">
<h:outputLink value="./index.xhtml" >Home</h:outputLink>
<h:outputLink value="./webpages/view/users.xhtml">Users</h:outputLink>
<h:outputLink value="./webpages/view/locations.xhtml">Locations</h:outputLink>
<ui:insert name="left" />
</h:panelGrid>
</div>
<div id="content">
<ui:insert name="content" />
</div>
</div>
<br style="clear:both"/>
</div>
</h:body>
</html>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/27644647",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: JavaScript document.write is not working Sorry if this seems dumb, i'm new to JavaScript.
This is in menu.js:
document.write("<a href="index.html">Home</a>");
document.write("<a href="news.html">News</a>");
document.write("<a href="about.html">About us</a>");
This is in index.html:
<head>
</head>
<body>
<script type="text/javascript" src="menu.js"></script>
</body>
</html>
When I load index.html, nothing comes up...
A: The problem is your quotes, you're using " both to delimit your new elements and to set their href attribute, change your code to:
document.write("<a href='index.html'>Home</a>");
document.write("<a href='news.html'>News</a>");
document.write("<a href='about.html'>About us</a>");
Or:
document.write('<a href="index.html">Home</a>');
document.write('<a href="news.html">News</a>');
document.write('<a href="about.html">About us</a>');
Combining single (') and double (") quotes. You could also escape your internal quotes (document.write("<a href=\"index.html\">Home</a>");
BUT it'd be better to use a single call to document.write(), like this:
document.write('<a href="index.html">Home</a>'
+ '<a href="news.html">News</a>'
+ '<a href="about.html">About us</a>');
A: You're not escaping the quotes in your strings. It should be:
document.write("<a href=\"index.html\">Home</a>");
Otherwise, JavaScript thinks the string ends after href= and the rest of the line does not follow valid JavaScript syntax.
As @Felix mentioned, the JavaScript debugger tools will be extremely helpful in letting you know what's going on.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/18276223",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: turn bootstrap button into link with javascript and ajax I have a bootstrap button, that i have embedded into a form. The form requests a php file with ajax. But i Cant get the button to work like a link?
The html code is for the bootstrap button is :
<a id="btn-login" href="#" class="btn btn-success">Login</a>
and the js is :
<script>
$(document).ready(function() {
$('.myform').on('submit',function(){
// Add text 'loading...' right after clicking on the submit button.
$('.output_message').text('Loading...');
var form = $(this);
$.ajax({
url: form.attr('action'),
method: form.attr('method'),
data: form.serialize(),
success: function(result){
if (result == 'success'){
$('.output_message').text('Message Sent!');
} else {
$('.output_message').text('Error Sending email!');
}
}
});
// Prevents default submission of the form after clicking on the submit button.
return false;
});
});
</script>
A: So do I get that correct that the link is supposed to send the form? That will not work, as a link on its own is not able to trigger a submit. You need an input of type submit.
<input type="submit" class="btn btn-success" value="Login">
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42657590",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Dynamically updating string from one div to another I have a list of divs that contain a string in h3 format. Upon clicking these divs (they are all the same class) a screen is displayed (part of the same html doc) containing some sliders for user input.
Is there a way to make it so that when the screen is displayed it contains the string of whatever div was clicked? In other words, if the user taps/clicks the "Push Ups" card, I would like the div "#info" to update to shoe "push Ups", if the user selects "Iquats" I would like "#info" to show "Squats" ec.
I can't think of a way to do this without using JSON or some sort of server magic. CODE!
HTML:
<!--HEADER-->
<div class="header">
<div id="info">
<p>Select Exercise</p> <!--THIS IS WHERE I WOULD LIKE THE STRING TO UPDATE-->
</div>
</div>
<!--EXERCISE LIST-->
<div id="exerciseContainer">
<div class="exerciseL exercise">
<h3>Push Ups</h3>
</div>
<div class="exerciseR exercise">
<h3>Dips</h3>
</div>
<div class="exerciseL exercise">
<h3>Burpees</h3>
</div>
<div class="exerciseR exercise">
<h3>Plank</h3>
</div>
<div class="exerciseL exercise">
<h3>Sit Ups</h3>
</div>
<div class="exerciseR exercise">
<h3>Leg Ups</h3>
</div>
<div class="exerciseL exercise">
<h3>Russian Twists</h3>
</div>
<div class="exerciseR exercise">
<h3>Back Raises</h3>
</div>
</div>
<!--SPECIFY TIMING FOR EXERCISES-->
<div id="specifier">
<div id="containSliders">
<!--Exercise time allocator-->
<h1></h1> <!--I WOULD LIKE THIS TO UPDATE ALSO-->
<div id="containSliderOne">
<p>Time:</p>
<output id="timeValue">60 sec.</output>
<input type="range" id="determineTime" step="10" value="60" min="0" max="180" />
</div>
<!--Exercise time allocator-->
<div id="containSliderTwo">
<p>Rest Time:</p>
<output id="restValue">10 sec.</output>
<input type="range" id="determineRest" step="10" value="10" min="0" max="180" />
</div>
<!--Add rest button-->
<div id="addBreak"><p>Add Break</p></div>
<!--Back Button-->
<div id="cancel">
<a id="exerciseCancel" href="exercises.html">
<img src="images/backButtonUp.png" width="100" alt=""/>
<img src="images/backButtonDown.png" width="85" alt=""/>
</a>
</div>
<!--Confirm Button-->
<div id="confirm">
<a id="exerciseConfirm" href="routineOverview.html">
<img src="images/whiteTickUp.png" width="95" alt=""/>
<img src="images/whiteTickDown.png" width="80" alt=""/>
</a>
</div>
</div>
</div>
JavaScript (jQuery)
$(".exercise").click(function()
{
$("#specifier").css("display", "block");
$(".backButton").css("display", "none");
});
Thanks for any help and ideas given!
A: It would be preferable to create the elements programatically.
var arrExercises = ['Push Ups', 'Dips', 'Burpees'];//add all exercises here
arrExercises.forEach(function(exercise, i){
var $exercise = $('<div>', {id:'div-excercise-'+i, "class":'exercise'});//create the exercise element
//give the on click handler to the exercise
$exercise.on('click', function(e){
$("#specifier").css("display", "block");
$(".backButton").css("display", "none");
$("#info").text(exercise);//set the info to the exercise text
});
$('#exerciseContainer').append($exercise);//append this exercise to the container
});
A: If I understand you correctly, you can get the clicked element text by using $(this).text() inside the click event.
$(function() {
$('.exercise').click(function() {
$('#info').text($(this).text());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<!--HEADER-->
<div class="header">
<div id="info">
<p>Select Exercise</p>
<!--THIS IS WHERE I WOULD LIKE THE STRING TO UPDATE-->
</div>
</div>
<!--EXERCISE LIST-->
<div id="exerciseContainer">
<div class="exerciseL exercise">
<h3>Push Ups</h3>
</div>
<div class="exerciseR exercise">
<h3>Dips</h3>
</div>
<div class="exerciseL exercise">
<h3>Burpees</h3>
</div>
<div class="exerciseR exercise">
<h3>Plank</h3>
</div>
<div class="exerciseL exercise">
<h3>Sit Ups</h3>
</div>
<div class="exerciseR exercise">
<h3>Leg Ups</h3>
</div>
<div class="exerciseL exercise">
<h3>Russian Twists</h3>
</div>
<div class="exerciseR exercise">
<h3>Back Raises</h3>
</div>
</div>
<!--SPECIFY TIMING FOR EXERCISES-->
<div id="specifier">
<div id="containSliders">
<!--Exercise time allocator-->
<h1></h1>
<!--I WOULD LIKE THIS TO UPDATE ALSO-->
<div id="containSliderOne">
<p>Time:</p>
<output id="timeValue">60 sec.</output>
<input type="range" id="determineTime" step="10" value="60" min="0" max="180" />
</div>
<!--Exercise time allocator-->
<div id="containSliderTwo">
<p>Rest Time:</p>
<output id="restValue">10 sec.</output>
<input type="range" id="determineRest" step="10" value="10" min="0" max="180" />
</div>
<!--Add rest button-->
<div id="addBreak">
<p>Add Break</p>
</div>
<!--Back Button-->
<div id="cancel">
<a id="exerciseCancel" href="exercises.html">
<img src="images/backButtonUp.png" width="100" alt="" />
<img src="images/backButtonDown.png" width="85" alt="" />
</a>
</div>
<!--Confirm Button-->
<div id="confirm">
<a id="exerciseConfirm" href="routineOverview.html">
<img src="images/whiteTickUp.png" width="95" alt="" />
<img src="images/whiteTickDown.png" width="80" alt="" />
</a>
</div>
</div>
</div>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46891386",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to push into an existing session array , key and value in laravel With php I used
if (!isset($_SESSION['cart']) || !isset($_SESSION['cart'][$product])) {
$_SESSION['cart'][$product] = 0;
$_SESSION['cart'][$product] = $_SESSION['cart'][$product] + $product_quantity;
}else{
$_SESSION['cart'][$product] = $_SESSION['cart'][$product] + $product_quantity;
}
I tried with put() but it's not working, cause every time I try to insert a new value it replace the first one
session()->put('cart',[request('variant_id') => request('quantity')]);
With push() I put inside the array cart another array with key and value
session()->push('cart',[request('variant_id') => request('quantity')]);
Is there a way to insert into session array with key and value cause right now I can't figure it out how to do it
| {
"language": "en",
"url": "https://stackoverflow.com/questions/71220462",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to Display plain text of api result ( noob question ) I am completely new to api.
I want to display the plain text response of the output of this:
https://vurl.com/api.php?url=https://google.com
to my webpage html but it's not working.
My code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$url = urlencode('https://google.com');
$api_url = 'vurl.com/api.php?url='.$url;
$arr_output = json_decode(file_get_contents($api_url), true);
document.write($arr_output);
</script>
Thanks
A: Not really sure why you're mixing javascript with your php code. Nevertheless, this is the approach you should follow:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
<?php
$url = urlencode("https://google.com");
$api_url = "vurl.com/api.php?url=".$url;
$arr_output = json_decode(file_get_contents($api_url), true);
echo $arr_output;
?>
</script>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/68971257",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: overlaying a div over three floats I need a bit of help overlaying a <div> over 3 other <div> elements which are styled float:left in their own container.
It looks like this now (http://i.imgur.com/2xk4tax.jpg) and i would like the text to overlay on top of the three floated colorlines.
Here's my hmtl/css any help would be appreciated.
HTML
<body>
<div id="introtextcontainer">
<p>hi</p>
</div>
<div id="linecontainer">
<div id="line1">
</div>
<div id="line2">
</div>
<div id="line3">
</div>
</div>
</body>
CSS
#introtextcontainer {
margin: 0px auto 0px auto;
width: 500px;
height: 100px ;
text-align:center;
font-color: black;
float:middle;
}
#linecontainer {
margin: 0px auto 0px auto;
width: 500px;
height: 3000px ;
}
#line1 {
width:160px;
height:2000px;
background-color: #00A7B0;
float:left;
}
#line2 {
width:160px;
height:2000px;
background-color: #D1DE3E;
float:left;
}
#line3{
width:160px;
height:2000px;
background-color: #DE006B;
float:left;
}
A: By just adding position:absolute and width:100% to your introtextcontainer container it seems to work:
#introtextcontainer {
margin: 0px auto 0px auto;
height: 100px;
text-align:center;
font-color: black;
position:absolute;
width:100%;
}
jsFiddle example
Note that there is no such float:middle; property (left or right only).
A: You could also position:absolute the #linecontainer to slide up behind the text (I also centered it with left:50%; margin-left:- 0.5 * width ). You might have to give the text a position:relative; z-index:1; to force it on top.
#introtextcontainer {
margin: 0px auto 0px auto;
height: 100px;
text-align:center;
font-color: black;
position:relative;
width:100%;
z-index:1;
}
#linecontainer {
margin: 0 0 0 -250px;
width: 500px;
height: 3000px;
position:absolute;
top:0;
left:50%;
}
Or even better, use a gradient generator, remove the 3 divs and make the bars a background: http://www.colorzilla.com/gradient-editor/
#introtextcontainer {
margin: 0px auto 0px auto;
height: 100px;
text-align:center;
font-color: black;
position:absolute;
width:100%;
background: rgb(0,167,176); /* Old browsers */
/* IE9 SVG, needs conditional override of 'filter' to 'none' */
background: url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiA/Pgo8c3ZnIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgd2lkdGg9IjEwMCUiIGhlaWdodD0iMTAwJSIgdmlld0JveD0iMCAwIDEgMSIgcHJlc2VydmVBc3BlY3RSYXRpbz0ibm9uZSI+CiAgPGxpbmVhckdyYWRpZW50IGlkPSJncmFkLXVjZ2ctZ2VuZXJhdGVkIiBncmFkaWVudFVuaXRzPSJ1c2VyU3BhY2VPblVzZSIgeDE9IjAlIiB5MT0iMCUiIHgyPSIxMDAlIiB5Mj0iMCUiPgogICAgPHN0b3Agb2Zmc2V0PSIzMyUiIHN0b3AtY29sb3I9IiMwMGE3YjAiIHN0b3Atb3BhY2l0eT0iMSIvPgogICAgPHN0b3Agb2Zmc2V0PSIzMyUiIHN0b3AtY29sb3I9IiNkMWRlM2UiIHN0b3Atb3BhY2l0eT0iMSIvPgogICAgPHN0b3Agb2Zmc2V0PSIzNCUiIHN0b3AtY29sb3I9IiNkMWRlM2UiIHN0b3Atb3BhY2l0eT0iMSIvPgogICAgPHN0b3Agb2Zmc2V0PSI2NiUiIHN0b3AtY29sb3I9IiNkMWRlM2UiIHN0b3Atb3BhY2l0eT0iMSIvPgogICAgPHN0b3Agb2Zmc2V0PSI2NiUiIHN0b3AtY29sb3I9IiNkZTAwNmIiIHN0b3Atb3BhY2l0eT0iMSIvPgogIDwvbGluZWFyR3JhZGllbnQ+CiAgPHJlY3QgeD0iMCIgeT0iMCIgd2lkdGg9IjEiIGhlaWdodD0iMSIgZmlsbD0idXJsKCNncmFkLXVjZ2ctZ2VuZXJhdGVkKSIgLz4KPC9zdmc+);
background: -moz-linear-gradient(left, rgba(0,167,176,1) 33%, rgba(209,222,62,1) 33%, rgba(209,222,62,1) 34%, rgba(209,222,62,1) 66%, rgba(222,0,107,1) 66%); /* FF3.6+ */
background: -webkit-gradient(linear, left top, right top, color-stop(33%,rgba(0,167,176,1)), color-stop(33%,rgba(209,222,62,1)), color-stop(34%,rgba(209,222,62,1)), color-stop(66%,rgba(209,222,62,1)), color-stop(66%,rgba(222,0,107,1))); /* Chrome,Safari4+ */
background: -webkit-linear-gradient(left, rgba(0,167,176,1) 33%,rgba(209,222,62,1) 33%,rgba(209,222,62,1) 34%,rgba(209,222,62,1) 66%,rgba(222,0,107,1) 66%); /* Chrome10+,Safari5.1+ */
background: -o-linear-gradient(left, rgba(0,167,176,1) 33%,rgba(209,222,62,1) 33%,rgba(209,222,62,1) 34%,rgba(209,222,62,1) 66%,rgba(222,0,107,1) 66%); /* Opera 11.10+ */
background: -ms-linear-gradient(left, rgba(0,167,176,1) 33%,rgba(209,222,62,1) 33%,rgba(209,222,62,1) 34%,rgba(209,222,62,1) 66%,rgba(222,0,107,1) 66%); /* IE10+ */
background: linear-gradient(to right, rgba(0,167,176,1) 33%,rgba(209,222,62,1) 33%,rgba(209,222,62,1) 34%,rgba(209,222,62,1) 66%,rgba(222,0,107,1) 66%); /* W3C */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#00a7b0', endColorstr='#de006b',GradientType=1 ); /* IE6-8 */
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/15440868",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: (AudioManager)getSystemService(Context.AUDIO_SERVICE) causing memory leak I had memory leak that was being caused by AudioManager. So I've commented out this line in my code to see if it would solve my problem:
public class FireRoomActivity extends Activity {
AudioManager am;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
am = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
}
}
And it did solve the problem and I don't have memory leak any more. Is that because of Context.AUDIO_SERVICE? If yes then how could I replace it?
If it matters, I have this non-static class inside my activity that is not used elsewhere outside
class GestureListener extends GestureDetector.SimpleOnGestureListener {
RelativeLayout parentLayout;
public void setLayout(RelativeLayout layout){
parentLayout = layout; }
@Override
public boolean onDown(MotionEvent e) {
return true;
}
// event when double tap occurs
@Override
public boolean onDoubleTap(MotionEvent e) {
makeArrowsVisible();
parentLayout.findViewById(R.id.cabinet_zoomed).setVisibility(View.INVISIBLE);
Button key = (Button)parentLayout.findViewById(R.id.key);
if(key!=null){
key.setVisibility(View.INVISIBLE);}
return true;
}
Edit:
screenshot of heap dump
A: Fix mentioned in https://gist.github.com/jankovd/891d96f476f7a9ce24e2 worked for me.
public class ActivityUsingVideoView extends Activity {
@Override protected void attachBaseContext(Context base) {
super.attachBaseContext(AudioServiceActivityLeak.preventLeakOf(base));
}
}
/**
* Fixes a leak caused by AudioManager using an Activity context.
* Tracked at https://android-review.googlesource.com/#/c/140481/1 and
* https://github.com/square/leakcanary/issues/205
*/
public class AudioServiceActivityLeak extends ContextWrapper {
AudioServiceActivityLeak(Context base) {
super(base);
}
public static ContextWrapper preventLeakOf(Context base) {
return new AudioServiceActivityLeak(base);
}
@Override public Object getSystemService(String name) {
if (Context.AUDIO_SERVICE.equals(name)) {
return getApplicationContext().getSystemService(name);
}
return super.getSystemService(name);
}
}
Thanks to Dejan Jankov :)
A: You can avoid memory leak using application context to get audio service.
A: I found in another post that the AudioManager does keep a strong reference, but will still be properly garbage collected. See this google group conversation. Here's what I get out of it:
This means that if you manually launch a couple of garbage collections through the DDMS tab in Eclipse just before taking the head dump, this reference should not be there anymore.
This indeed solved the "problem" for me, as it turned out not to be a problem after all...
It was also mentionned that the debugger should not be on hook (i.e. use Run As... instead of Debug As...). The debugger being active could cause the references to be held by the AudioManager, thus creating a heap overflow (I have not tested this affirmation).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/20244288",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Dynamically List contents of a table in database that continously updates It's kinda real-world problem and I believe the solution exists but couldn't find one.
So We, have a Database called Transactions that contains tables such as Positions, Securities, Bogies, Accounts, Commodities and so on being updated continuously every second whenever a new transaction happens. For the time being, We have replicated master database Transaction to a new database with name TRN on which we do all the querying and updating stuff.
We want a sort of monitoring system ( like htop process viewer in Linux) for Database that dynamically lists updated rows in tables of the database at any time.
TL;DR Is there any way to get a continuous updating list of rows in any table in the database?
Currently we are working on Sybase & Oracle DBMS on Linux (Ubuntu) platform but we would like to receive generic answers that concern most of the platform as well as DBMS's(including MySQL) and any tools, utilities or scripts that can do so that It can help us in future to easily migrate to other platforms and or DBMS as well.
A: To list updated rows, you conceptually need either of the two things:
*
*The updating statement's effect on the table.
*A previous version of the table to compare with.
How you get them and in what form is completely up to you.
The 1st option allows you to list updates with statement granularity while the 2nd is more suitable for time-based granularity.
Some options from the top of my head:
*
*Write to a temporary table
*Add a field with transaction id/timestamp
*Make clones of the table regularly
AFAICS, Oracle doesn't have built-in facilities to get the affected rows, only their count.
A: Not a lot of details in the question so not sure how much of this will be of use ...
*
*'Sybase' is mentioned but nothing is said about which Sybase RDBMS product (ASE? SQLAnywhere? IQ? Advantage?)
*by 'replicated master database transaction' I'm assuming this means the primary database is being replicated (as opposed to the database called 'master' in a Sybase ASE instance)
*no mention is made of what products/tools are being used to 'replicate' the transactions to the 'new database' named 'TRN'
So, assuming part of your environment includes Sybase(SAP) ASE ...
*
*MDA tables can be used to capture counters of DML operations (eg, insert/update/delete) over a given time period
*MDA tables can capture some SQL text, though the volume/quality could be in doubt if a) MDA is not configured properly and/or b) the DML operations are wrapped up in prepared statements, stored procs and triggers
*auditing could be enabled to capture some commands but again, volume/quality could be in doubt based on how the DML commands are executed
*also keep in mind that there's a performance hit for using MDA tables and/or auditing, with the level of performance degradation based on individual config settings and the volume of DML activity
Assuming you're using the Sybase(SAP) Replication Server product, those replicated transactions sent through repserver likely have all the info you need to know which tables/rows are being affected; so you have a couple options:
*
*route a copy of the transactions to another database where you can capture the transactions in whatever format you need [you'll need to design the database and/or any customized repserver function strings]
*consider using the Sybase(SAP) Real Time Data Streaming product (yeah, additional li$ence is required) which is specifically designed for scenarios like yours, ie, pull transactions off the repserver queues and format for use in downstream systems (eg, tibco/mqs, custom apps)
I'm not aware of any 'generic' products that work, out of the box, as per your (limited) requirements. You're likely looking at some different solutions and/or customized code to cover your particular situation.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/48974700",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: New browser tabs for pdf files from glob-created list? To list a large number of sheet-music pdfs on a website, I'm using this at the top of my php/html file:
<?php
header('Content-Type: text/html; charset=utf-8');
function getFiles(){
$files=array();
if($dir=opendir('.')){
while($file=readdir($dir)) {
if($file!='.' && $file!='..'){
$files[]=($file);
}
}
closedir($dir);
}
natsort($files); //sort
return $files;
}
?>
... then in the ul bit of the html section I have this:
<? foreach (glob("*.pdf") as $file)
echo "<li name=\"".$file."\"><a href=\"".$file."\">$file</a></li>";
?>
It works fine, except that when clicked, the pdf replaces the web page content in the browser, and I would prefer it to appear in a separate browser tab.
I've tried inserting "_blank" in various places but it kills the page, so I'm obviously not doing it right (I'm a musician, not a programmer!).
Similar questions on here seem to relate to different set-ups and I don't have the knowledge to apply the answers to my situation.
How can I get my otherwise successful website set-up to trigger a new browser tab for each tune clicked? Thanks.
A: "I've tried inserting "_blank" in various places" -- the correct place is in the a element: <a href="..." target="_blank"...>
The code of your template should read:
<?php
foreach (glob("*.pdf") as $file) {
echo '<li name="'.$file.'"><a href="'.$file.'" target="_blank">'.$file.'</a></li>';
}
?>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/45717307",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Can we use props to pass variable in vue? Slall question:
I have a 2 parent components nesting the same child component inside of them.
I use props so the parents can tell the child what title to show.
this child component is a photo gallery. It makes a query to the database, download photos and show them up. classic.
I need the parents to tell the child where to get the photos from:
Get the photos from All users, for the home page
or
get only the photos from a specific user for a user's page.
I'm wondering if I can pass this information through a prop.
Is that possible? Can we use the info from a prop as a varialble inside of the setup() function?
Is there a better way to do this?
A: Passing objects from one component to a child component is the purpose of props.
You can pass many items through props. VueJS has the following types built-in:
*
*String
*Number
*Boolean
*Array
*Object
*Function
*Promise
In the V3 VueJS guide it gives the following example of a prop being passed into a component and then being logged to the console inside the setup() method.
export default {
props: {
title: String
},
setup(props) {
console.log(props.title)
}
}
However, when using props, you should always mark whether the is required, what its type is and what the default is if it is not required.
For example:
export default {
props: {
title: String, // This is the type
required: false, // If the prop is required
default: () => 'defaultText' // Default needed if required false
},
setup(props) {
console.log(props.title)
}
}
It's important to note that when using default, the value must be returned from a function. You cannot pass a default value directly.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/67036390",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Uncaught ReferenceError: jQuery is not defined at file I am using phonegap and every time it gives me error at this line .I am trying to submit the form through phonegap , javascript works but with jquery it always me this errro Uncaught ReferenceError: jQuery is not defined at file
jQuery(function() {
Here Is my code
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript" charset="utf-8" src="cordova-1.5.0.js">
</script>
<script type="text/javascript" src="jquery-1.6.4.min.js"></script>
<script>
function validation()
{
alert('validation');
}
jQuery(function() {
alert("login");
/* stop form from submitting normally */
event.preventDefault();
/*clear result div*/
/* get some values from elements on the page: */
//var values = $(this).serialize();
var values = "user";
/* Send the data using post and put the results in a div */
jQuery.ajax({
url: server_url,
type: "post",
data: values,
success: function() {
alert("success");
jQuery("#result").html('submitted successfully');
},
error: function() {
alert("failure");
jQuery("#result").html('there is error while submit');
}
});
});
</script>
</head>
A: You need to have jQuery file in the folder your current page is, also try to get the latest jQuery file you are using quite old, you can download latest here.
A: Is Cordova based on jQuery ? If so, you have to include jQuery first.
If not, your jQuery file is probably not found. Press Ctrl+u to see the source code, and then click on the link jquery-1.6.4.min.js in the head, and see if it opens your file ?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/17554287",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: K-Means Clustering having error of "Too many indexers" when multiple columns are given The code below is of K-Means Clustering copied from www.analyticsvidhya.com
K=3
# Select random observation as centroids
Centroids = (X.sample(n=K))
plt.scatter(X["DATE_ID"],X.iloc[:,-1],c='black')
plt.scatter(Centroids["DATE_ID"],Centroids.iloc[:,-1],c='red')
plt.xlabel('Number of Days')
plt.ylabel('POI1 Sales')
plt.show()
Output of above code
diff = 1
j=0
while(diff!=0):
XD=X
i=1
for index1,row_c in Centroids.iterrows():
ED=[]
for index2,row_d in XD.iterrows():
d1=(row_c["DATE_ID"]-row_d["DATE_ID"])**2
d2=(row_c.iloc[:,-1]-row_d.iloc[:,-1])**2
d=np.sqrt(d1+d2)
ED.append(d)
X[i]=ED
i=i+1
C=[]
for index,row in X.iterrows():
min_dist=row[1]
pos=1
for i in range(K):
if row[i+1] < min_dist:
min_dist = row[i+1]
pos=i+1
C.append(pos)
X["Cluster"]=C
Centroids_new = X.groupby(["Cluster"]).mean()[[X.iloc[:,-1],"DATE_ID"]]
if j == 0:
diff=1
j=j+1
else:
diff = (Centroids_new[:,-1] - Centroids[:,-1]).sum() + (Centroids_new['DATE_ID'] - Centroids['DATE_ID']).sum()
print(diff.sum())
Centroids = X.groupby(["Cluster"]).mean()[[X.iloc[:,-1],"DATE_ID"]]
The error I am having:
---------------------------------------------------------------------------
IndexingError Traceback (most recent call last)
<ipython-input-24-19f3132fec6e> in <module>()
9 for index2,row_d in XD.iterrows():
10 d1=(row_c["DATE_ID"]-row_d["DATE_ID"])**2
---> 11 d2=(row_c.iloc[:,-1]-row_d.iloc[:,-1])**2
12 d=np.sqrt(d1+d2)
13 ED.append(d)
3 frames
/usr/local/lib/python3.7/dist-packages/pandas/core/indexing.py in _validate_key_length(self, key)
790 def _validate_key_length(self, key: Sequence[Any]) -> None:
791 if len(key) > self.ndim:
--> 792 raise IndexingError("Too many indexers")
793
794 def _getitem_tuple_same_dim(self, tup: tuple):
IndexingError: Too many indexers
The problem
How can I pass multiple columns in it? the 1st column I have is DATE_ID (it's in float format) and the other columns are sales of different stores (also in float format)
I'm trying to implement this code but the code mentioned in the link before is implemented on only 2 columns, whereas I have to implement it on multiple columns while keeping the DATE_ID column fixed.
A: Here's scikit learns' k-means:
from sklearn.cluster import KMeans
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv('stack_overflow.csv')
X = df.iloc[:,1:]
plt.scatter(
X['DATE_ID'], X.iloc[:, -1],
c='white', marker='o',
edgecolor='black', s=50
)
plt.show()
k = 3
km = KMeans(
n_clusters=k, init='random',
n_init=10, max_iter=300,
tol=1e-04, random_state=0
)
y_km = km.fit_predict(X)
X['label'] = y_km
Output:
Now use the labels to graph the clusters:
import matplotlib.pyplot as plt
# plot the 3 clusters
plt.scatter(
X[X['label'] == 0]['DATE_ID'], X[X['label'] == 0].iloc[:,-2],
s=50, c='lightgreen',
marker='s', edgecolor='black',
label='cluster 1'
)
plt.scatter(
X[X['label'] == 1]['DATE_ID'], X[X['label'] == 1].iloc[:,-2],
s=50, c='orange',
marker='o', edgecolor='black',
label='cluster 2'
)
plt.scatter(
X[X['label'] == 2]['DATE_ID'], X[X['label'] == 2].iloc[:,-2],
s=50, c='lightblue',
marker='v', edgecolor='black',
label='cluster 3'
)
# plot the centroids
plt.scatter(
km.cluster_centers_[:, 0], km.cluster_centers_[:, 1],
s=250, marker='*',
c='red', edgecolor='black',
label='centroids'
)
plt.legend(scatterpoints=1)
plt.grid()
plt.show()
Output:
| {
"language": "en",
"url": "https://stackoverflow.com/questions/71870731",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Rails validate uniqueness between two models I'm still new to rails and I'm having trouble validating across models.
I have two models, Artists and Songs associated with a many to many relationship. I would like to have a validation in the song model that checks that song url_slug is unique for each artist. I have tried using :scope but I don't seem to be able to call the associated artist id.
I'm pretty lost here so any help would be appreciated.
Thanks,
Here is my song model:
class Song< ActiveRecord::Base
has_and_belongs_to_many:artists
#creates Url Slug
#before_create :generate_slug
before_update :generate_slug
validates_uniqueness_of :song_url_slug, :scope => self.artist.id
protected
def generate_slug
self.song_url_slug = song_name.gsub(/\W+/, ' ').strip.downcase.gsub(/\ +/, '-')
end
#def url_slug_uniqueness
#artist_song = self.song_name.find(:artist_id])
#if self.exists?(:conditions => {:song_name => artist_song})
# errors.add(:song_name, :name_taken, :song_name=> "#{artist_song}1")
#end
# end
#end
A: The first thing to do is try getting rid of the before_create :generate_slug and before_update :generate_slug lines and replace them with
before_validation :generate_slug
Your uniqueness validation may work then.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/8108505",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Regex Java word context what I want to achieve is that I want to obtain the context of an acronym. Can you help me pls with the regular expression?
I am looping over the text (String) and looking for dots, after match I am trying to get the context of the particular found acronym, so that I can do some other processing after that, but I cant get the context. I need to take at least 5 words before and 5 words after the acronym.
//Pattern to match each word ending with dot
Pattern pattern = Pattern.compile("(\\w+)\\b([.])");
Matcher matchDot = pattern.matcher(textToCorrect);
while (matchDot.find()) {
System.out.println("zkratka ---"+matchDot.group()+" ---");
//5 words before and after tha match = context
// Matcher matchContext = Pattern.compile("(.{25})("+matchDot.group()+")(.{25})").matcher(textToCorrect);
Pattern patternContext = Pattern.compile("(?:[a-zA-Z'-]+[^a-zA-Z'-]+){0,10}"+matchDot.group()+"(?:[^a-zA-Z'-]+[a-zA-Z'-]+){0,10}");
Matcher matchContext = patternContext.matcher(textToCorrect);
if (matchContext.find()) {
System.out.println("context: "+matchContext.group()+" :");
// System.out.println("context: "+matchContext.group(1)+" :");
// System.out.println("context: "+matchContext.group(2)+" :");
}
}
Example:
input:
Some 84% of Paris residents see fighting pol. as a priority and 54% supported a diesel ban in the city by 2020, according a poll carried out for the Journal du Dimanche.
output:
1-st regex will find pol.
2-nd regex will find "of Paris residents see fighting pol. as a priority and 54%"
Another example with more text
I need to loop through this once and every time I match an acronym to get the context of this particular acronym. After that I am processing some datamining. Here's the original text
neklidná nemocná, vyš. je možné provést pouze nativně
Na mozku je patrna hyperdenzita v počátečním úseku a. cerebri media
vlevo, vlevo se objevuje již smazání hranic mezi bazálními ganglii a
okolní bílou hmotou a mírná difuzní hypointenzita v periventrikulární
bílé hmotě. Kromě těchto čerstvých změn jsou patrné staré
postmalatické změny temporálně a parietookcipitálně vlevo. Oboustranně
jsou patrné vícečetné vaskulární mikroléze v centrum semiovale bilat.
Nejsou známky nitrolebního krvácení. skelet kalvy orientačně nihil tr.
Z á v ě r: Známky hyperakutní ischemie v povodí ACM vlevo, staré
postmalatickéé změny T,P a O vlevo, vaskulární mikroléze v centrum
semiovale bilat.
CT AG: vyš. po bolu k.l..
Po zklidnění nemocné se podařilo provést CT AG. Na krku je naznačený
kinkink na ACC vlevo a ACI vlevo pod bazí. Kalcifikace v karotických
sifonech nepůsobí hemodynamicky významné stenozy. Intrakraniálně je
patrný konický uzávěr operkulárního úseku a. cerebri media vlevo pro
parietální lalok. Ostatní nález na intrakraniálním tepenném řečišti je
v mezích normy.
Z á v ě r: uzávěr operkulárního úseku a. cerebri media vlevo.
Of course if it matches end of sentence is ok for me :-) The question is to find all the acronyms even if they are before new line (\n)
A: I would try this out:
(?:\w+\W+){5}((?:\w.?)+)(?:\w+\W+){5}
Though natural language processing with regular expressions cannot be accurate.
A: ((?:[\w!@#$%&*]+\s+){5}([\w!@#$%&*]+\.)(?:\s+[\w!@#$%&*]+){5})
Try this.See demo.
https://regex101.com/r/aQ3zJ3/9
| {
"language": "cs",
"url": "https://stackoverflow.com/questions/27346080",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: imap function is not working for me with PHP I try to access my gmail account with PHP, but I get an error message in line 2. IMAP is enabled in Gmail, while POP is not enabled.
$mbox = imap_open("{imap.gmail.com:993/ssl}", "[email protected]", "password");
echo "<h1>Mailboxes</h1>\n";
$folders = imap_listmailbox($mbox, "{imap.gmail.com:993}", "*");
if ($folders == false) {
echo "Call failed<br />\n";
}
else {
foreach ($folders as $val) {
echo $val . "<br />\n";
}
}
echo "<h1>Headers in INBOX</h1>\n";
$headers = imap_headers($mbox);
if ($headers == false) {
echo "Call failed<br />\n";
}
else {
foreach ($headers as $val) {
echo $val . "<br />\n";
}
}
imap_close($mbox);
A: You need to enable imap in your php.ini.
I used the wamp menu to edit the php.ini. I enabled the php_imap.dll.
-> http://www.wampserver.com/phorum/read.php?2,23447,printview,page=1
A: I got the solution:
I am running Windows 7 64bit environment with WAMP server, it has two php.ini files:
1] C:\wamp\bin\apache\apache2.2.22\bin
Enable php_imap.dll extension by removing ; at beginning of string
2] C:\wamp\bin\php\php5.3.13
Enable php_imap.dll extension by removing ; at beginning of string
And it works now !
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7685283",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Validation loss and accuracy has a lot of 'jumps' Hello everyone so I made this cnn model.
My data:
Train folder->30 classes->800 images each->24000 all together
Validation folder->30 classes->100 images each->3000 all together
Test folder->30 classes -> 100 images each -> 3000 all together
-I've applied data augmentation. ( on the train data)
-I got 5 conv layers with filters 32->64->128->128->128
each with maxpooling and batch normalization
-Added dropout 0.5 after flattening layers
Train part looks good. Validation part has a lot of 'jumps' though. Does it overfit?
Is there any way to fix this and make validation part more stable?
Note: I plann to increase epochs on my final model I'm just experimenting to see what works best since the model takes a lot of time in order to train. So for now I train with 20 epochs.
A:
Train part looks good. Validation part has a lot of 'jumps' though. Does it overfit?
the answer is yes. The so-called 'jumps' in the validation part may indicate that the model is not generalizing well to the validation data and therefore your model might be overfitting.
Is there any way to fix this and make validation part more stable?
To fix this you can use the following:
*
*Increasing the size of your training set
*Regularization techniques
*Early stopping
*Reduce the complexity of your model
*Use different hyperparameters like learning rate
A:
I've applied data augmentation (on the train data).
What does this mean? What kind of data did you add and how much? You might think I'm nitpicking, but if the distribution of the augmented data is different enough from the original data, then this will indeed cause your model to generalize poorly to the validation set.
Increasing your epochs isn't going to help here, your training loss is already decreasing reasonably. Training your model for longer is a good step if the validation loss is also decreasing nicely, but that's obviously not the case.
Some things I would personally try:
*
*Try decreasing the learning rate.
*Try training the model without the augmented data and see how the validation loss behaves.
*Try splitting the augmented data so that it's also contained in the validation set and see how the model behaves.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75274978",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Git delete stash by name/message As far as I know Git can not delete a stash by name/message (despite it can save it by name with git stash save "name"). However, I really like to have this option for a 'combined alias' that I want to create for my workflow (especially for colleagues that are not that familiar with git and should respect the workflow)
I know I can create a bash script myself but I was thinking maybe someone already has made such a script!? So that I can delete a stash by name...
My "update" alias is roughly like this:
git stash save -u "tempstash"
git fetch origin
[apply our workflow/update strategy]
git stash pop --index (should be: git stash delete "tempstash")
The problem with the current alias is that if there is nothing to stash, it will restore an old stash.
An other option would be to check if stashing is needed but I always wanted a git stash delete by name option so thats why im asking this.
PS: im using posh-git but bash commands should work within an alias.
Thanks
A: You can overcome the problem with checking whether there is anything to stash first. You can use one of the ways to check whether an index is dirty that are suggested in Checking for a dirty index or untracked files with Git
For instance this command will not output anything if there are no changes to stash:
git status --porcelain
Using this command, the script may look like this:
is_stashing=$(git status --porcelain)
test -n "$is_stashing" && git stash save -u
git fetch origin
[apply our workflow/update strategy]
test -n "$is_stashing" && git stash pop --index
A: A solution would be to search the git reflog stash using the name of the stash as a regexp and obtaining its name in the stash@{<number>} format.
Then you can create an alias in git for using it as a command.
A quick and dirty solution, that can be greatly improved, is something like:
[alias]
sshow = "!f() { git stash show `git reflog stash | egrep $* | awk '{printf $2}' | sed 's/://' `; }; f"
ssdrop = "!f() { git stash drop `git reflog stash | egrep $* | awk '{printf $2}' | sed 's/://' `; }; f"
By adding this two aliases in your .git/config you can see the files modified in the stash with:
git sshow <regexp matching the name of the stash>
and you can drop the stash with:
git ssdrop <regexp matching the name of the stash>
A: I found a way to drop a stash by name. You can do it like this:
git stash drop stash@{$((git stash list | grep -w NAME_OF_THE_STASH) | cut -d "{" -f2 | cut -d "}" -f1)}
Here is the breakdown of the script:
*
*I am using the standard git stash drop stash@{n} structure
*We need to get the n of the stash with the name you want to delete. So to do that we list the stashes and grep the item with the matching name. To do that I used the script: git stash list | grep -w NAME_OF_THE_STASH
*Out of that item we need to extract the index which is within brackets {}. We can extract that number by adding to the script in item 2 the following: | cut -d "{" -f2 | cut -d "}" -f1
I tested it and it works great for me.
By the way, if you enter a name that does not exist then nothing gets erased.
Also, only the exact name match will be erased. If you don't want an exact match necessarily then remove the -w after grep.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/20744051",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Image on top of text changing it's color I'm trying to find out how to build something like this (see attachment).
I do not know how to when a image (assuming it's an svg) goes on top of a H1 or any text it changes the text color.
The attachment i print here has a breathing effect on the blob, i wont have that but still it would be great to know.
Thank you.
BlobText
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66474257",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: (ionic solution) Disable android hardware back button for specific view. Back button should work as expected for other views in app On the tap of hardware back button on a specific view, it should not do anything. By Default it nav pop the view but here I don't want to back navigate on click of hardware back button. I want it to stay on that page/view.
I checked all possible solution available but no luck. This is not a duplicate too.
Ionic 2 - Disabling back button for a specific view this is for nav back button. I want a solution for hardware back button.
A: You can Try this
*Simply Override Empty onBackPressed *
@Override
public void onBackPressed(){
// do nothing.
}
A: You can Try this
*Simply Override Empty onBackPressed *
@Override
public void onBackPressed(){
// do nothing.}
A: You have to write an override method
@Override
public void onBackPressed() {
\\you can do whatever you want to here.
\\don't call **super**, if u want disable back button in current screen.
}
A: In your Activity you have to override method:
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
return !disableBackKey ;
}
return super.onKeyDown(keyCode, event);
}
And make disableBackKey True/False depend upon your requirement.
A: If you are using Activity, please add below function to your activity
@Override
public void onBackPressed() {
//super.onBackPressed();
}
if you are using Fragment, please add below function to your fragment
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
return true
}
return false;
}
A: Answer for Ionic 2 or 3
Call the below method at the end of constructor.
Registration in the below code is your class name of current page or component.
if you don't want to do anything on back button, simply remove the code in IF condition below.
overrideHardwareBackButton() {
this.platform.ready().then(() => {
this.platform.registerBackButtonAction(() => {
let activeView:ViewController = this.navCtrl.getActive();
if (activeView != null && ((<any> activeView).instance instanceof Registration)) {
console.log("Registration -> Home");
this.nav.setRoot(HomePage);
} else {
console.log("Somthing is wrong");
}
});
});
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/47135288",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Angular best practice for sharing single API call between two active components I'm trying to figure out what the best practice is for the following situation:
I have two components A and B which are both are integrated on one page. Both components need access to data set C. Data set C is received by an API Call from the server. It should only be received initially and not twice for every component.
My first approach was using observables, but then the API call was done twice. So i switched to BehaviourSubjects, but when called from the controller the initial value was of course null. So i replaced it with ReplySubjects, which are working fine. But im struggling with the intial call. I got it working fine but im looking for the best pracice. Here is the code:
Component A and B are similar
getDataC(): void {
this.dataCService.getData().subscribe(data=>{this.data = data})
}
I want to have the data in my service as well, so i can make a UPDATE on the API with the object to modify the data on the Server. My approach is working fine, but im not sure if i have to subscribe inside my service the this variable or keep it clean.
Then my Service:
import { Injectable } from '@angular/core';
import { DataCAPIService } from '../resources/resources.service'
import { Observable, of, BehaviorSubject, ReplaySubject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class DataCService {
public dataC = new ReplaySubject<any>(1)
dataCInsideService: any
constructor(private dataCAPIService: DataCAPIService) {
}
getDataCAPICall() {
if (this.dataC.observers.length < 2)
this.dataCAPIService.getAll({}).subscribe(data => {
this.dataC.next(data);
this.dataC.subscribe(data => this.dataCInsideService = data)
})
}
getData() {
this.getDataCAPICall();
return this.dataC;
}
saveDataC() {
this.dataCAPIService.update(this.dataCInsideService, {}).subscribe(data => {
this.dataC.next(this.dataCInsideService);
})
}
}
Thanks for any opinions or solutions to a better style.
A:
I have two components A and B which are both are integrated on one
page. Both components need access to data set C.
As long as they are being used in one page, why you are calling them from each components? I think you can call it from the page component and send it to children.
Children can get the data using @Input() decorator. You can send the data directly or you can send it as observable (it's fine if it is behavior subject or subject).
I hope this could help you.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/64846458",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Regular expression in Python sentence extractor I have a script that gives me sentences that contain one of a specified list of key words. A sentence is defined as anything between 2 periods.
Now I want to use it to select all of a sentence like 'Put 1.5 grams of powder in' where if powder was a key word it would get the whole sentence and not '5 grams of powder'
I am trying to figure out how to express that a sentence is between to sequences of period then space. My new filter is:
def iterphrases(text):
return ifilter(None, imap(lambda m: m.group(1), finditer(r'([^\.\s]+)', text)))
However now I no longer print any sentences just pieces/phrases of words (including my key word). I am very confused as to what I am doing wrong.
A: if you don't HAVE to use an iterator, re.split would be a bit simpler for your use case (custom definition of a sentence):
re.split(r'\.\s', text)
Note the last sentence will include . or will be empty (if text ends with whitespace after last period), to fix that:
re.split(r'\.\s', re.sub(r'\.\s*$', '', text))
also have a look at a bit more general case in the answer for Python - RegEx for splitting text into sentences (sentence-tokenizing)
and for a completely general solution you would need a proper sentence tokenizer, such as nltk.tokenize
nltk.tokenize.sent_tokenize(text)
A: Here you get it as an iterator. Works with my testcases. It considers a sentence to be anything (non-greedy) until a period, which is followed by either a space or the end of the line.
import re
sentence = re.compile("\w.*?\.(?= |$)", re.MULTILINE)
def iterphrases(text):
return (match.group(0) for match in sentence.finditer(text))
A: If you are sure that . is used for nothing besides sentences delimiters and that every relevant sentence ends with a period, then the following may be useful:
matches = re.finditer('([^.]*?(powder|keyword2|keyword3).*?)\.', text)
result = [m.group() for m in matches]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/27946742",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: R: Make a new column filled from value in a row I have multiple dataframes all structured as below but with thousands of observations.
(df <- data.frame(
col1 = c("Elem_A", "String", "String", "String", "Elem_A", "String", "String", "Elem_A", "String", "String", "String", "String"),
col2 = c("DOI_1", "String", "String", "String", "DOI_2", "String", "String", "DOI_3", "String", "String", "String", "String")))
#> col1 col2
#> 1 Elem_A DOI_1
#> 2 String String
#> 3 String String
#> 4 String String
#> 5 Elem_A DOI_2
#> 6 String String
#> 7 String String
#> 8 Elem_A DOI_3
#> 9 String String
#> 10 String String
#> 11 String String
#> 12 String String
I am wanting to structure it as below, pulling specifically the value that begins with "DOI" into a new column and filling that value down until it reaches the row with the next "DOI" value.
(df <- data.frame(
col1 = c("Elem_A", "String", "String", "String",
"Elem_A", "String", "String", "Elem_A", "String", "String", "String", "String", "String", "String", "String"),
col2 = c("DOI_1",
"String", "String", "String", "DOI_2", "String", "String",
"DOI_3", "String", "String", "String", "String", "String", "String", "String"),
col3 = c("DOI_1", "DOI_1", "DOI_1", "DOI_1",
"DOI_2", "DOI_2", "DOI_2", "DOI_3", "DOI_3", "DOI_3", "DOI_3", "DOI_3")))
#> col1 col2 col3
#> 1 Elem_A DOI_1 DOI_1
#> 2 String String DOI_1
#> 3 String String DOI_1
#> 4 String String DOI_1
#> 5 Elem_A DOI_2 DOI_2
#> 6 String String DOI_2
#> 7 String String DOI_2
#> 8 Elem_A DOI_3 DOI_3
#> 9 String String DOI_3
#> 10 String String DOI_3
#> 11 String String DOI_3
#> 12 String String DOI_3
I was thinking I should somehow incorporate str_detect but the issue is that sometimes "DOI" is also the beginning of some of the "Strings" values within the same column that the "DOI" values are in.
A: We can use str_detect with case_when/ifelse to retrieve the row element and then use fill to fill the NA values with the previous non-NA
library(dplyr)
library(tidyr)
library(stringr)
df <- df %>%
mutate(col3 = case_when(str_detect(col2, "DOI_") ~ col2)) %>%
fill(col3)
-output
df
col1 col2 col3
1 Elem_A DOI_1 DOI_1
2 String String DOI_1
3 String String DOI_1
4 String String DOI_1
5 Elem_A DOI_2 DOI_2
6 String String DOI_2
7 String String DOI_2
8 Elem_A DOI_3 DOI_3
9 String String DOI_3
10 String String DOI_3
11 String String DOI_3
12 String String DOI_3
If 'DOI_\\d+' is a substring, then use str_extract to extract the substring
df <- df %>%
mutate(col3 = str_extract(col2, "DOI_\\d+")) %>%
fill(col3)
-output
df
col1 col2 col3
1 Elem_A DOI_1 DOI_1
2 String String DOI_1
3 String String DOI_1
4 String String DOI_1
5 Elem_A DOI_2 DOI_2
6 String String DOI_2
7 String String DOI_2
8 Elem_A DOI_3 DOI_3
9 String String DOI_3
10 String String DOI_3
11 String String DOI_3
12 String String DOI_3
A: With Base R way
s <- unlist(gregexpr("DOI_\\d+" , df$col2))
df$col3 <- unlist(Map(\(x,y) rep(df$col2[x] ,length.out = y + 1) ,
which(s > -1) , rle(s)$lengths[which(rle(s)$values == -1)]))
*
*output
col1 col2 col3
1 Elem_A DOI_1 DOI_1
2 String String DOI_1
3 String String DOI_1
4 String String DOI_1
5 Elem_A DOI_2 DOI_2
6 String String DOI_2
7 String String DOI_2
8 Elem_A DOI_3 DOI_3
9 String String DOI_3
10 String String DOI_3
11 String String DOI_3
12 String String DOI_3
| {
"language": "en",
"url": "https://stackoverflow.com/questions/73211348",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: trying to create a loop that returns a logo in the list images and the name cryptolist i have a Widget that is called CoinCard which shows a cyrptoLogo,name and price.
now instead of calling that widget 3 times and providing image and a name, i wanted to create a loop which will return a image from images and the name from cryptoList. code below:
List<String> images = [
"Bitcoin.svg.png",
"256px-Ethereum_logo_2014.svg.png",
"litecoin-ltc-logo.png"
];
const List<String> cryptoList = ['BTC', 'ETH', 'LTC'];
class _HomePageState extends State<HomePage> {
List<Widget> getCard() {
List<CoinCard> cards = [];
for (String image in images) {
cards.add(
CoinCard(
cryptoname: "ggg",
logo: image,
price: "5001918556",
),
);
}
return cards;
}
A: you can use ListView.builder to create dynamic list
example :
class HomePage extends StatelessWidget {
List<String> images = [
"Bitcoin.svg.png",
"256px-Ethereum_logo_2014.svg.png",
"litecoin-ltc-logo.png"
];
@override
Widget build(BuildContext context) {
return ListView.builder(
itemCount:images.length ,
itemBuilder: (context, index) => CoinCard(
cryptoname: "ggg",
logo: images[index],
price: "5001918556",
),
);
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/64958484",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Modify/clean field values before applying a query filter in MongoDB like in SQL Server? I have a SQL Server query that I need to convert into a Mongo Query. As we all know that we can clean up fields in SQL before applying conditions to them e.g
In the 3rd line we are applying ltrim,rtrim on the clinics field before applying the like condition to it. Same with the reverse field in the query multiple times. If this was a single step query I would have done something maybe using aggregation but this is a multistep cleanup using replace, convert, ltrim, rtrim etc in different places.
Can someone please throw some light on how I could convert it. If someone is an expert in this domain and can convert it into Mongo, that would be great as well. Thanks :)
select rule from rules where
isnull(status,0) = '1' AND isnull(deleted,0) = '0'
AND (((ltrim(rtrim(isnull(clinics,'0'))) like '0%') OR
( ',' + replace(replace(isnull(clinics,'0'),' ','') ,' ','') + ','
like '%,' + convert(varchar,"""+category+""") + ',%')) AND
(',' + replace(replace(isnull(clinics,'0'),' ','') ,' ','') + ','
not like '%,-' + replace(convert(varchar,"""+category+"""),' ','') + ',%')) AND
((( (ltrim(rtrim(isnull(reverse,'0'))) like '0%') OR
(( ','+ replace(replace(isnull(reverse,'0'),' ','') ,' ','') + ','
like '%,' + convert(varchar,"""+primary+""") + ',%')))
AND (',' + replace(replace(isnull(reverse,'0'),' ','') ,' ','') + ','
not like '%,-' + replace(convert(varchar,"""+primary+"""),' ','') + ',%') ))
| {
"language": "en",
"url": "https://stackoverflow.com/questions/69295345",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Boost serialization of class handling a possible null pointer I want to serialize the following class wrapping a pointer which can handle a null m_element as you can see when calling the default constructor. This follows this question.
Live MCVE on Coliru
template <typename T>
struct Ptr { // Ptr could use init constructor here but this is not the point
Ptr() { m_elem = 0; }
Ptr(const T* elem) {
if (elem)
m_elem = new T(*elem);
else
m_elem = 0;
}
Ptr(const T& elem)
{
m_elem = new T(elem);
}
Ptr(const Ptr& elem)
{
if (elem.m_elem)
m_elem = new T(*(elem.m_elem));
else
m_elem = 0;
}
virtual ~Ptr() { delete m_elem; m_elem = 0; };
const T& operator*() const { return *m_elem; };
T& operator*() { return *m_elem; };
const T* operator->() const { return m_elem; };
T* operator->() { return m_elem; };
T* m_elem;
};
namespace boost { namespace serialization {
// Not sure about the approach to manage null m_elem here
template<class Archive, class T>
void save(Archive & ar, const Ptr<T> &ptr, const unsigned int version)
{
T elem = 0;
if (ptr.m_elem != 0)
ar& boost::serialization::make_nvp("data", *ptr.m_elem);
else
ar& boost::serialization::make_nvp("data", elem);
}
// How to implement load ?
template<class Archive, class T>
void load(Archive & ar, Ptr<T> &ptr, const unsigned int version)
{
ar& boost::serialization::make_nvp("data", *ptr.m_elem);
}
template<class Archive, class T>
void serialize(Archive & ar, Ptr<T> &ptr, const unsigned int version)
{
boost::serialization::split_free(ar, ptr, version);
}
}} // end namespace
int main()
{
{
Ptr<A> p;
std::ostringstream oss;
boost::archive::xml_oarchive oa(oss);
oa << BOOST_SERIALIZATION_NVP(p);
std::cout << oss.str() << std::endl;
// segfault
Ptr<double> po;
std::istringstream iss;
iss.str(oss.str());
boost::archive::xml_iarchive ia(iss);
ia >> BOOST_SERIALIZATION_NVP(po);
}
{
Ptr<double> p(new double(2.0));
std::cout << *(p.m_elem) << std::endl;
std::ostringstream oss;
boost::archive::xml_oarchive oa(oss);
oa << BOOST_SERIALIZATION_NVP(p);
std::cout << oss.str() << std::endl;
// segfault
Ptr<double> po;
std::istringstream iss;
iss.str(oss.str());
boost::archive::xml_iarchive ia(iss);
ia >> BOOST_SERIALIZATION_NVP(po);
}
}
The serialization seems to work but the deserialization gives a segfault. I am working in C++0x.
*
*How can I provide safe save and load functions to serialize Ptr without changing Ptr if possible ?
*If I need to modify Ptr, what do you propose ?
Edit : thanks to Jarod42 comment I came up with the following save/load functions using a boolean to detect null pointer or not. Now I do not have a segfault anymore when m_elem is null but I have a one when it is not null.
template<class Archive, class T>
void save(Archive & ar, const Ptr<T> &ptr, const unsigned int version)
{
bool is_null;
if (ptr.m_elem != 0) {
is_null = false;
ar& boost::serialization::make_nvp("is_null", is_null);
ar& boost::serialization::make_nvp("data", *ptr.m_elem);
}
else
{
is_null = true;
ar& boost::serialization::make_nvp("is_null", is_null);
}
}
template<class Archive, class T>
void load(Archive & ar, Ptr<T> &ptr, const unsigned int version)
{
bool is_null;
ar& boost::serialization::make_nvp("is_null", is_null);
if (is_null == true) {
ptr.m_elem = 0;
}
else
{
ar& boost::serialization::make_nvp("data", *ptr.m_elem);
}
}
A: boost::archive's save and load methods understand the difference between pointers and object references. You don't need to specify *m_elem. m_elem will do (and work correctly). Boost will understand if the pointer is null and will simply store a value indicating a null pointer, which will be deserialised correctly.
(simplified) example:
#include <vector>
#include <string>
#include <iostream>
#include <sstream>
#include <algorithm>
#include <iterator>
#include <boost/archive/xml_iarchive.hpp>
#include <boost/archive/xml_oarchive.hpp>
#include <boost/serialization/access.hpp>
#include <boost/serialization/nvp.hpp>
#include <boost/serialization/split_free.hpp>
struct A {
A() : a(0) {}
A(int aa) : a(aa) {}
int a;
template <class Archive>
void serialize(Archive& ar, const unsigned int /*version*/)
{
ar& BOOST_SERIALIZATION_NVP(a);
}
};
std::ostream& operator<<(std::ostream& os, const A& a) {
os << "A{" << a.a << "}";
return os;
}
template <typename T>
struct Ptr { // Ptr could use init constructor here but this is not the point
Ptr()
: m_elem(0)
{}
Ptr(T elem)
: m_elem(new T(elem))
{
}
private:
// no copies
Ptr(const Ptr&);
Ptr& operator=(const Ptr&);
public:
// delete is a NOP when called with nullptr arg
virtual ~Ptr() { delete m_elem; };
T* get() const {
return m_elem;
}
T& operator*() const {
return *m_elem;
}
template <class Archive>
void serialize(Archive& ar, const unsigned int /*version*/)
{
ar& BOOST_SERIALIZATION_NVP(m_elem);
}
private:
T* m_elem;
};
template<class T>
std::ostream& operator<<(std::ostream& os, const Ptr<T>& p) {
if (p.get()) {
os << *p;
}
else {
os << "{nullptr}";
}
return os;
}
int main()
{
std::string payload;
{
Ptr<A> p;
std::cout << p << std::endl;
std::ostringstream oss;
boost::archive::xml_oarchive oa(oss);
oa << BOOST_SERIALIZATION_NVP(p);
payload = oss.str();
// std::cout << payload << std::endl;
Ptr<A> p2(A(6));
std::cout << p2 << std::endl;
oa << BOOST_SERIALIZATION_NVP(p2);
payload = oss.str();
// std::cout << payload << std::endl;
}
{
Ptr<A> po;
std::istringstream iss(payload);
boost::archive::xml_iarchive ia(iss);
ia >> BOOST_SERIALIZATION_NVP(po);
std::cout << po << std::endl;
Ptr<A> po2;
ia >> BOOST_SERIALIZATION_NVP(po2);
std::cout << po2 << std::endl;
}
}
expected output:
{nullptr}
A{6}
{nullptr}
A{6}
A: Thanks to Jarod42 comment,
You should serialize a boolean to know if pointer is nullptr or not
(and if not, serialize also its content). for loading, retrieve this
boolean and allocate a default element when needed that you load.
we came with the following save and load functions :
template<class Archive, class T>
void save(Archive & ar, const Ptr<T> &ptr, const unsigned int version)
{
bool is_null = !ptr.m_elem;
ar & boost::serialization::make_nvp("is_null", is_null);
if(!is_null) ar & boost::serialization::make_nvp("data", *ptr.m_elem);
}
template<class Archive, class T>
void load(Archive & ar, Ptr<T> &ptr, const unsigned int version)
{
bool is_null;
ar & boost::serialization::make_nvp("is_null", is_null);
if (!is_null) {
ptr.m_elem = new T;
ar& boost::serialization::make_nvp("data", *ptr.m_elem);
}
}
Live on Coliru
Had an issue in the load function when is_null is false. A storage is indeed needed for ptr in this case.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31809638",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: I want to dynamically query WHERE clause using string builder I want to dynamically build the WHERE clause for my query using string builder.
private void btnquery_Click(object sender, EventArgs e)
{
StringBuilder strQuery = new StringBuilder();
StringBuilder strWhereClass = new StringBuilder();
strQuery.Append("SELECT * FROM [dbo].[poi5] ");
if (namecb.Checked)
{
if (string.IsNullOrEmpty(nametxt.Text))
{ MessageBox.Show("Please enter the name!!!");
nametxt.Focus();
return;
}
else
{
if (strWhereClass.Length == 0)
{ strWhereClass.Append("WHERE [Name_POI] ='" + nametxt.Text + "';");
} else{ trWhereClass.Append(" AND [Name_POI]] ='" + nametxt.Text + "';");
}
}
}
if (versioncb.Checked)
{
if (string.IsNullOrEmpty(versiontxt.Text))
{ MessageBox.Show("Please enter the version!!!");
versiontxt.Focus();
return;
}
else
{
if (strWhereClass.Length == 0)
{
strWhereClass.Append("WHERE [Version] = '" versiontxt.Text + "'");
}
else
{
strWhereClass.Append(" AND [Version] = '" + versiontxt.Text + "'");
}
}
}
con = new SqlConnection(@"Data Source=.\sqlexpress;Initial Catalog=POIFINALLY;Integrated Security=True;");
cmd = new SqlCommand(strQuery.ToString() + strWhereClass.ToString(), con);
con.Open();
da = new SqlDataAdapter(cmd);
da.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
}
A: Write a stored Procedure that takes the filter query dynamically according to cases
Create procedure GetPoi (@Name nvarchar (100),@Version nvarchar (100))
as
begin
declare @Command nvarchar(max)
set @Command = 'select * from tablename where name ='''+@Name+''' and Version='''+@Version+''''
exec sp_executeSql @Command
end
Also you have to make a test to check if the Parameters provided are empty strings and modify your where clause accordingly.
Check Dynamic SQL for more info
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21670046",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
} |
Q: Does github limit the number of personal access tokens per user Using Github Enterprise, I have a service/bot account where I'd like to generate a number of Personal Access tokens and provide to a number of teams.
Is there any limit in how many Personal Access Tokens can be generated per user?
A: As far as I'm aware, there is no limit, but if you want to be sure, you should ask either the GitHub support team or on the GitHub community forums.
GitHub itself has such a bot account and PATs are frequently used there, but do be aware that the UI may be a little (or, depending on how many tokens you issue, very) slow, since it isn't designed for people to have huge numbers of PATs.
You may find it more desirable to use deploy keys if you're accessing a repo, since these have a smaller scope (one repository) and won't have the UI problems mentioned above, but of course that won't work for the API.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/62044629",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to add textFileds in Dropdown Reactjs I want to add textField - autocomplete in Dropdown? Could you help me how to do it?
The source code in here: Source Code in Sanbox
A: Since you are using Material-UI, you can use their autocomplete component with a TextField as input, have a look at the "Combo box" here:
https://material-ui.com/components/autocomplete/#combo-box
| {
"language": "en",
"url": "https://stackoverflow.com/questions/67175353",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Sprint Wireless Toolkit 3.3.2 vs Sun Wireless Toolkit Anyone know the diference between Sprint Wireless Toolkit 3.3.2 and Sun Wireless Toolkit?
A: AFAIK both are same. But I feel some differents between Sprint toolkit and Sun toolkit. These are,
Sprint toolkit having Nokia, Samsung, LG emulators. But Sun java toolkit having their own toolkit.
Sprint support touch emulators. Sun toolkit doesn't have touch emulators.
Zooming emulator screen supports Sprint. Sun toolkit doesn't support.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/4467259",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Javascript displaying text in quotes. How do I remove it? Edit: Turns out the api produces the quotes.
Excuse me, as I have pretty much no knowledge of js/jquery, but I found a code I wanted to use. It uses tumblr's api. http://www.tumblr.com/docs/en/api/v1.
Now, the problem is titles[i] shows text wrapped in quotes. So instead of
<div class="relates">This is the titles i. I want this.</div>,
it shows
<div class="relates">"This is the titles i. I don't want the quotes!"</div>
in the html. I don't want that (for reasons not worth explaining).
Can somebody help me remove the quotes?
Here's the full code.
(function() {
var config = new Object();
var titles = [];
var links = [];
var images = [];
var items = [];
var types = [];
var $j = jQuery.noConflict()
var scripts = document.getElementsByTagName('script');
var this_script = scripts[scripts.length - 1];
var params = this_script.src.replace(/^[^\?]+\??/,'').split('&');
var url_base = ((typeof(config.url) == 'undefined') ? ('http://' + document.domain + '/') : ('http://' + config.url + '/'));
for(var i=0; i<params.length; i++) {
var tmp = params[i].split("=");
config[tmp[0]] = unescape(tmp[1]);
}
if(typeof(config.tags)=='undefined'){ error(0); return; }
if(typeof(config.num)=='undefined'){ config.num=8; }
if(typeof(config.len)=='undefined'){ config.len=60; }
if(typeof(config.title)=='undefined'){ config.title='Related Posts:'; }
if(typeof(config.type)=='undefined'){ config.type=''; }
switch(config.css) {
case ('simple'):
document.write('<link rel="stylesheet" type="text/css" ' +
'href="http://example.com/resource/simple.css" media="screen" />');
break;
case ('complete'):
document.write('<link rel="stylesheet" type="text/css" ' +
'href="http://example.com/resource/complete.css" media="screen" />');
break;
case ('light'):
document.write('<link rel="stylesheet" type="text/css" ' +
'href="http://example.com/resource/light.css" media="screen" />');
break;
case ('dark'):
document.write('<link rel="stylesheet" type="text/css" ' +
'href="http://example.com/resource/dark.css" media="screen" />');
break;}
document.write(
'<div id="tumblrinlink">' +
'<div id="inlink-loading"></div>' +
'<div id="inlink-title"></div>'+
'<ul id="inlink-list"></ul>' +
'' +
'</div>'
);
var tags = config.tags.slice(0,-1).split(',');
$j(document).ready(function() {
function getRelated() {
var req;
for(var i=0; i<tags.length; i++){
req=$j.getJSON(url_base+'api/read/json?callback=?&filter=text&num='+config.num+'&start=0&type='+config.type+'&tagged='+escape(tags[i]), function(data) {
$j(data.posts).each(function(i, post) {
var text='';
if(post.type=='regular') text=post['regular-title']+''+post['regular-body'];
else if(post.type=='link') text+=post['link-text'];
else if(post.type=='quote') text+=post['quote-text'];
else if(post.type=='photo') text+=post['photo-caption'];
else if(post.type=='conversation') text+=post['conversation-title'];
else if(post.type=='video') text+=post['video-caption'];
else if(post.type=='audio') text+=post['audio-caption'];
else if(post.type=='answer') text+=post['question'];
if(text.length>config.len){ text=text.slice(0,config.len); text+='...';}
var image ='';
if(post.type=='photo') image+=post['photo-url-100'];
else if(post.type=='link') image+=['link-text'];
else if(post.type=='quote') image+=['quote-text'];
else if(post.type=='photo') image+=['photo-caption'];
else if(post.type=='conversation') image+=['conversation-title'];
else if(post.type=='video') image+=['video-caption'];
else if(post.type=='audio') image+=['audio-caption'];
else if(post.type=='answer') image+=['question'];
titles.push(text);
links.push(post['url-with-slug']);
images.push(image);
types.push(post['type'])
});
}).complete(getList);
}
}
function getList(){
for(var i=0; i<titles.length; i++){
var regex = new RegExp('('+links[i]+')');
var html = $j("#inlink-list").html();
if(links[i]!=document.location&&!html.match(regex)){
if(config.num--<=0) return;
var item='<li class="inlink-item" id="'+types[i]+'"><a class="inlink-link" href="'+links[i]+'"><img src="'+images[i]+'" alt="'+titles[i]+'" /><div class="relates">'+titles[i]+'</div></a></li>';
$j("#inlink-list").append(item);
}
}
$j("#inlink-title").html('<h2>'+config.title+'</h2>');
$j("#inlink-loading").html('');
}
getRelated();
});
function getError(e){
var msg="error: ";
switch(e){
case 0: msg+='no tags defined'; break;
case 1: msg+='tumblr API problem'; break;
}
$j("#inlink-loading").html(msg);
}})();
A: I am going to assume the quotes are coming from the Tumblr API. In this case, you just need to strip the quotes:
<div class="relates">'+titles[i].substring(1, titles[i].length - 2)+'</div>
substring(1, titles[i].length - 2) will remove the first character (index 0) and the last character (index length - 1) from the string.
Docs
| {
"language": "en",
"url": "https://stackoverflow.com/questions/14132063",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Create bitmap of a DOMElement Objective C I have a Webkit DOMElement, a div for example.
Now I want a renderized NSImage or NSBitmapImageRep of it.
It's like a screenshot of a DOMElement.
A: Public API choices:
-[NSView cacheDisplayInRect:toBitmapImageRep:]
-[NSBitmapImageRep initWithFocusedViewRect:]
Private WebKit method:
-[DOMElement renderedImage]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/4422346",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: SQL help to identify the Missing Data I have the following COMPANY_TABLE table
SOURCE UNIQUE_COMPANY_D RECORD_STATE SUB_COMPANY_ID PARENT PRIMARY_PARENT
ABC 111 Secondary 123 999
XYZ 111 Primary 456
YYY 222 Secondary 895 888 888
TTT 222 Primary 902 888
VVV 333 Primary 101 777 777
RRR 333 Secondary 187 777
IN WHERE UNIQUE_COMPANY_ID = '111' is the issue.
PRIMARY_PARENT IS NOT POPULATED, It should populate based on PARENT. If the PARENT field has Value it should Populate for both rows. if null it has to grab the value from secondary row and populate PRIMARY_PARENT Value. I have like 10 million rows where I need to find the scenarios where Parent is populated and Primary parent is not populated. based on the above criteria. (If the PARENT field has Value it should Populate for both rows. if null it has to grab the value from secondary row and populate PRIMARY_PARENT Value) I want to identify all the error records from 10 million rows.
And I created the SQL below :
SELECT * FROM COMPANY_TABLE WHERE PARENT IS NOT NULL AND PRIMARY_PARENT IS NULL;
But all its showing me single row. I need something which can get me two rows in order and able to differentiate the issue.
A: You have missed one of the conditions. You also want whenever PARENT is NULL the Value of PRIMARY_PARENT be equal to the value of PARENT in the next row. You can take care of it this way:
SELECT * FROM
(SELECT *, LEAD(PARENT) OVER(Order BY (SELECT NULL)) as LeadParent FROM COMPANY_TABLE) T
WHERE PARENT IS NOT NULL AND PRIMARY_PARENT IS NULL
OR ((PARENT IS NULL) AND LeadParent != PRIMARY_PARENT);
A: As Kumar stated, you could try and test to see if the values Parent and Primary_Parent by default are NULL's or blanks.
Did you try:
SELECT * FROM COMPANY_TABLE WHERE PARENT <> '' AND PRIMARY_PARENT <> ''
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40515152",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Put a Variable in List Name Essentially, I want to create and fill a list based on the contents of a variable. The relevant data is being read from a (JSON) text file.
#Check if a game was won, and assign a variable to `outcome`
if game['stats']['win'] == True:
outcome = "victory"
else:
outcome = "defeat"
#put the no. objectives taken in that game in a 'wins' or 'losses' list
objectives_in_(outcome).append(game['stats']['objectives_taken'])
So outside of a useful for-loop, I would want something a result which looks something like this:
print(objectives_in_victory)
7
In case my question remains unclear, I am reading a file that will contain data on whether a match was won, and how many objectives were secured. If the game was won, the number of objectives in that game will be assigned to a 'win list' and visa versa for losses.
I tried using a dictionary which was suggested elsewhere on SO for approaching similar tasks, but matches which have the same outcome and no. objectives are not duplicated making averaging impossibe and causing data to be excluded. It took me a long time to realise this..
A: You could use a dict of lists that looks like this:
objectives_in = {"victory": [], "defeat": []}
You can use it similar to what you have in your example:
objectives_in[outcome].append(game['stats']['objectives_taken'])
# Example stats:
count = len(objectives_in["victory"])
print("Number of victories:", count)
print("Average objectives:", sum(objectives_in["victory"]) / count)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/63973961",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to melt and plot multiple datasets over different ranges on the same set of axis? This is my first time posting here, I hope my question is clear and appropriate. I have a set of data the head of which looks like this:
wl ex421 wl ex309 wl ex284 wl ex347
1 431 0.6168224 321 0.1267943 301 0.06392694 361 0.15220484
2 432 0.6687435 322 0.2416268 302 0.05631659 362 0.08961593
3 433 0.6583593 323 0.4665072 303 0.05327245 363 0.13134187
4 434 0.6832814 324 0.3576555 304 0.00000000 364 0.32432432
5 435 0.6427830 325 0.2194976 305 0.12328767 365 0.50308203
6 436 0.7393562 326 0.1866029 306 0.08675799 366 0.34660977
and so on. The 'wl' columns represent wavelength, and there are four different ranges. The other four columns represent measurements (normalized) taken over the 'wl' ranges. The ranges are of different lengths, too. All of them partially overlap somewhere in the middle of the dataset.
What I need to achieve is a plot showing all four sets of 'ex###' data on the same set of axis and plotted over their respective ranges. The x-axis needs to accommodate all four 'wl' ranges. However, I haven't yet succeeded.
When I had to plot multiple sets of data like this in the past I just melted the data and it always worked. Something like this:
df_melt <- melt(df, id.var = 'wl')
And then I'd plot it like this:
fluor_plt <- ggplot(fluor_ref2_melt, aes(x=wl,y=value,color=variable)) +
geom_point(shape = 1, fill = NA) + geom_path(data = fluor_ref2_melt,size = 1) +
theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank()) +
scale_colour_manual(values = colvec)
However, because I have multiple columns with the name 'wl', which also have different ranges, what happens is that R only takes the first 'wl' column and discards all the other ones. It then basically shifts all the 'ex###' values into that range by using the row index... so I get a plot of the frame below:
wl ex421 ex309 ex284 ex347
1 431 0.6168224 0.1267943 0.06392694 0.15220484
2 432 0.6687435 0.2416268 0.05631659 0.08961593
3 433 0.6583593 0.4665072 0.05327245 0.13134187
4 434 0.6832814 0.3576555 0.00000000 0.32432432
5 435 0.6427830 0.2194976 0.12328767 0.50308203
6 436 0.7393562 0.1866029 0.08675799 0.34660977
Needless to say, this is entirely wrong...
So one way I tried to circumvent the issue is going into Excel and manually moving columns up and down, so that in the dataframe each row corresponds to one 'wl' value, whether there are any measured values associated with it or not. This got rid of the values being 'shifted', but R still discards the 'wl' columns after the first one. Instead of getting an entirely wrong plot, I get a section of the right one. The first set of observations (ex421) is plotted over its entire range; pieces of the other ones are seen where ranges overlap.
I've looked at some similar cases which were asked about here in the past, like this - Reshape data frame from wide to long with re-occuring column names in R.
But I'm new to R and I don't think I could fully understand the proposed solutions. I didn't succeed in reshaping my data in the way I want it to be reshaped (keeping different 'wl' ranges for different sets) and I had no idea which arguments to give to ggplot afterwards. I've tried using data.table, but then I don't know what to give it for value.name and variable.name.
To reiterate, what I want to achieve is what one would get from plotting the four datasets in the spreadsheet by making a single Scatter plot in Excel and adding four different series to it.
Any input would be greatly appreciated!
A: I can think of this solution:
# data:
dt <- structure(list(wl = 431:436,
ex421 = c(0.6168224, 0.6687435, 0.6583593, 0.6832814, 0.642783, 0.7393562),
wl = 321:326,
ex309 = c(0.1267943, 0.2416268, 0.4665072, 0.3576555, 0.2194976, 0.1866029),
wl = 301:306,
ex284 = c(0.06392694, 0.05631659, 0.05327245, 0, 0.12328767, 0.08675799),
wl = 361:366,
ex347 = c(0.15220484, 0.08961593, 0.13134187, 0.32432432, 0.50308203, 0.34660977)),
row.names = c(NA, -6L),
class = c("data.table", "data.frame"))
# get vectors with wl names
wls <- grep("wl", names(dt))
# get vectors with ex_numbers names
exs <- grep("ex", names(dt))
# reformat the data:
newDt <- cbind(stack(dt, select = wls), stack(dt, select = exs))
# Assign reasonable names:
names(newDt) <- c("wlNumber", "wlInd", "exValue", "exNumber")
Now the data is ready to be plotted with any command:
ggplot(newDt, aes(x = wlNumber, y = exValue, color = exNumber))+geom_point()+geom_line()
The main advantage of this approach is that you can have the table spread into many columns. It doesn't matter, as long as their name has "wl" on it ("ex" for the other variables).
A: Here I load a data frame with your data, making sure to allow repeated names with check.names = F, otherwise it would rename the wl columns to be distinct:
df <- read.table(
header = T, check.names = F,
stringsAsFactors = F,
text = " wl ex421 wl ex309 wl ex284 wl ex347
431 0.6168224 321 0.1267943 301 0.06392694 361 0.15220484
432 0.6687435 322 0.2416268 302 0.05631659 362 0.08961593
433 0.6583593 323 0.4665072 303 0.05327245 363 0.13134187
434 0.6832814 324 0.3576555 304 0.00000000 364 0.32432432
435 0.6427830 325 0.2194976 305 0.12328767 365 0.50308203
436 0.7393562 326 0.1866029 306 0.08675799 366 0.34660977")
Then here's a way to reshape, by just stacking subsets of the data. Since there weren't too many column pairs, I thought a semi-manual method would be ok. It preserves the distinct column headers so we can gather those into long form and map to color like in your plot.
library(tidyverse)
df2 <- bind_rows(
df[1:2],
df[3:4],
df[5:6],
df[7:8]
) %>%
gather(variable, value, -wl) %>%
drop_na()
ggplot(df2, aes(x=wl,y=value,color=variable)) +
geom_point(shape = 1, fill = NA) +
geom_path(size = 1) +
theme(panel.grid.major = element_blank(),
panel.grid.minor = element_blank())
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56605354",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Unable to find Artifactory Project in Visual Studio Extensions and Updates I am using Visual Studio 2017. I am trying to add JFrog Artifactory Project to push artifacts to Artifactory.
To add Artifactory project I need to install it from tools--> Extensions and Updates--> search for Artifactory. But the search results is zero.
So how can i install JFrog Artifactory in Visual Studio 2017. It is working fine with Visual studio 2015.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/47923379",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: In Java, how do I create a bitmap to solve "knapsack quandary" I'm in my first programming course and I'm quite stuck right now. Basically, what we are doing is we take 16 values from a text file (on the first line of code) and there is a single value on the second line of code. We read those 16 values into an array, and we set that 2nd line value as our target. I had no problem with that part.
But, where I'm having trouble is creating a bitmap to test every possible subset of the 16 values, that equal the target number.
IE, say we had these numbers:
12 15 20 4 3 10 17 12 24 21 19 33 27 11 25 32
We then correspond each value to a bitmap
0 1 1 0 0 0 0 1 1 1 0 1 0 0 1 0
Then we only accept the values predicated with "1"
15 20 12 24 21 33 25
Then we test that subset to see if it equals the "target" number.
We are only allowed to use one array in the problem, and we aren't allowed to use the math class (haven't gotten to it yet).
I understand the concept, and I know that I need to implement shifting operators and the logical & sign, but I'm truly at a loss. I'm very frustrated, and I just was wondering if anybody could give me any tips.
A: To generate all possible bit patterns inside an int and thus all possible subsets defined by that bit map would simply require you to start your int at 1 and keep incrementing it to the highest possible value an unsigned short int can hold (all 1s). At the end of each inner loop, compare the sum to the target. If it matches, you got a solution subset - print it out. If not, try the next subset.
Can someone help to explain how to go about doing this? I understand the concept but lack the knowledge of how to implement it.
A: OK, so you are allowed one array. Presumably, that array holds the first set of data.
So your approach needs to not have any additional arrays.
The bit-vector is simply a mental model construct in this case. The idea is this: if you try every possible combination (note, NOT permutation), then you are going to find the closest sum to your target. So lets say you have N numbers. That means you have 2^N possible combinations.
The bit-vector approach is to number each combination with 0 to 2^N - 1, and try each one.
Assuming you have less that 32 numbers in the array, you essentially have an outer loop like this:
int numberOfCombinations = (1 << numbers.length - 1) - 1;
for (int i = 0; i < numberOfCombinations; ++i) { ... }
for each value of i, you need to go over each number in numbers, deciding to add or skip based on shifts and bitmasks of i.
A: So the task is to what an algorithm that, given a set A of non-negative numbers and a goal value k, determines whether there is a subset of A such that the sum of its elements is k.
I'd approach this using induction over A, keeping track of which numbers <= k are sums of a subset of the set of elements processed so far. That is:
boolean[] reachable = new boolean[k+1];
reachable[0] = true;
for (int a : A) {
// compute the new reachable
// hint: what's the relationship between subsets of S and S \/ {a} ?
}
return reachable[k];
A bitmap is, mathematically speaking, a function mapping a range of numbers onto {0, 1}. A boolean[] maps array indices to booleans. So one could call a boolean[] a bitmap.
One disadvanatage of using a boolean[] is that you must process each array element individually. Instead, one could use that a long holds 64 bits, and use bitshifting and masking operations to process 64 "array" elements at a time. But that sort of microoptimization is error-prone and rather involved, so not commonly done in code that should be reliable and maintainable.
A: I think you need something like this:
public boolean equalsTarget( int bitmap, int [] numbers, int target ) {
int sum = 0; // this is the variable we're storing the running sum of our numbers
int mask = 1; // this is the bitmask that we're using to query the bitmap
for( int i = 0; i < numbers.length; i++ ) { // for each number in our array
if( bitmap & mask > 0 ) { // test if the ith bit is 1
sum += numbers[ i ]; // and add the ith number to the sum if it is
}
mask <<= 1; // shift the mask bit left by 1
}
return sum == target; //if the sum equals the target, this bitmap is a match
}
The rest of your code is fairly simple, you just feed every possible value of your bitmap (1..65535) into this method and act on the result.
P.s.: Please make sure that you fully understand the solution and not just copy it, otherwise you're just cheating yourself. :)
P.p.s: Using int works in this case, as int is 32 bit wide and we only need 16. Be careful with bitwise operations though if you need all the bits, as all primitive integer types (byte, short, int, long) are signed in Java.
A: There are a couple steps in solving this. First you need to enumerate all the possible bit maps. As others have pointed out you can do this easily by incrementing an integer from 0 to 2^n - 1.
Once you have that, you can iterate over all the possible bit maps you just need a way to take that bit map and "apply" it to an array to generate the sum of the elements at all indexes represented by the map. The following method is an example of how to do that:
private static int bitmapSum(int[] input, int bitmap) {
// a variable for holding the running total
int sum = 0;
// iterate over each element in our array
// adding only the values specified by the bitmap
for (int i = 0; i < input.length; i++) {
int mask = 1 << i;
if ((bitmap & mask) != 0) {
// If the index is part of the bitmap, add it to the total;
sum += input[i];
}
}
return sum;
}
This function will take an integer array and a bit map (represented as an integer) and return the sum of all the elements in the array whose index are present in the mask.
The key to this function is the ability to determine if a given index is in fact in the bit map. That is accomplished by first creating a bit mask for the desired index and then applying that mask to the bit map to test if that value is set.
Basically we want to build an integer where only one bit is set and all the others are zero. We can then bitwise AND that mask with the bit map and test if a particular position is set by comparing the result to 0.
Lets say we have an 8-bit map like the following:
map: 1 0 0 1 1 1 0 1
---------------
indexes: 7 6 5 4 3 2 1 0
To test the value for index 4 we would need a bit mask that looks like the following:
mask: 0 0 0 1 0 0 0 0
---------------
indexes: 7 6 5 4 3 2 1 0
To build the mask we simply start with 1 and shift it by N:
1: 0 0 0 0 0 0 0 1
shift by 1: 0 0 0 0 0 0 1 0
shift by 2: 0 0 0 0 0 1 0 0
shift by 3: 0 0 0 0 1 0 0 0
shift by 4: 0 0 0 1 0 0 0 0
Once we have this we can apply the mask to the map and see if the value is set:
map: 1 0 0 1 1 1 0 1
mask: 0 0 0 1 0 0 0 0
---------------
result of AND: 0 0 0 1 0 0 0 0
Since the result is != 0 we can tell that index 4 is included in the map.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/9167425",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Map String to Object using Jackson with inheritance I have the QueueContent class that it has is a superclass of two others.
I get a String in JSON format that contains the information I need to extract. The super class is:
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public class QueueContent {
private String empresa;
private String empresa_cor;
private String empresa_contato;
private String empresa_url;
private String empresa_telefone;
private String empresa_idioma;
public QueueContent(String empresa, String empresa_cor, String empresa_contato, String empresa_url, String empresa_telefone, String empresa_idioma) {
this.empresa = empresa;
this.empresa_cor = empresa_cor;
this.empresa_contato = empresa_contato;
this.empresa_url = empresa_url;
this.empresa_telefone = empresa_telefone;
this.empresa_idioma = empresa_idioma;
}
public QueueContent() {
}
}
I'm using Lombok to generate Getters / Setters)
This is the child class:
@Data
public class EmailCameraOffline extends QueueContent {
private Timestamp camera_last_online;
private String camera_nome;
private String empresa_url_plataforma;
public EmailCameraOffline(String empresa, String empresa_cor, String empresa_contato, String empresa_url, String empresa_telefone, String empresa_idioma, Timestamp camera_last_online, String camera_nome, String empresa_url_plataforma) {
super(empresa, empresa_cor, empresa_contato, empresa_url, empresa_telefone, empresa_idioma);
this.camera_last_online = camera_last_online;
this.camera_nome = camera_nome;
this.empresa_url_plataforma = empresa_url_plataforma;
}
public EmailCameraOffline() {
}
}
So I've done:
EmailCameraOffline infosEmail = new ObjectMapper().readValue(content, EmailCameraOffline.class);
System.out.println(infosEmail);
And the output is:
EmailCameraOffline (camera_last_online = 2020-03-12 03: 01: 45.0, camera_nome = Pier Cam 1, empresa_url_platform = null)
How do I get my EmailCameraOffline object to have the superclass attributes initialized?
A: Everything should be loaded and initialized just fine, so calling:
System.out.println(infosEmail.getEmpresa());
should give expected value.
Problem
The problem is in the default implementation of toString() method (done via @Data) at EmailCameraOffline class, which does not include inherited fields.
Solution
To fix this you can "override" @Data's toString() implementation to include inherited fields as well using Lombok as:
@Data
@ToString(callSuper = true)
public class EmailCameraOffline extends QueueContent {
...
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60744061",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: SOLR - DataImportHandler - how to map multiple objects inside one list of json objects I am new to SOLR,I am trying to index oracle DB query results using SOLR. I have written config.xml and added indexes in schema.xml as well.
I have multiple queries as sub-entities(with child=true) in my config.xml file. Many of the queries are returning multiple rows. For example I have one entity as
<entity name="example_subentity" child="true" query="SELECT A,B from table_temp">
<field column="A" name="a" />
<field column="B" name="b" />
</entity>
which returns output as
"response":{"numFound":1,"start":0,"docs":[
{
"unique_key":"4493234234",
"_version_":1560479076226957312,
"_childDocuments_":[
{
"a" : "value_a_1",
"b" : "value_b_1",
},
{
"a" : "value_a_2",
"b" : "value_b_2",
}]
}]}
what I am trying to achieve here is, something like
"_childDocuments_":[
{"table_temp_response" :[
{
"a" : "value_a_1",
"b" : "value_b_1",
},
{
"a" : "value_a_2",
"b" : "value_b_2",
}]
}]
Can anyone guide me, how I can get this kind of output using DIH?
Just a update I am looking for a server side solution, I can do this using java or SOLRJ in client side. But I have multiple client which are going to consume SOLR query response.
A: if you use Solrj
JSONArray jArray = new JSONArray();
for (int i = 0; i < docList.size(); i++) {
JSONObject json = new JSONObject(docList.get(i));
jArray.put(json);
}
>
for (int i = 0; i < jArray.length(); i++) {
JSONObject obj = objs.getJSONObject(i);
obj.getString("a"));
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42483064",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: how to detect execution environment? I would like to have a pair ofdb-specmaps with my database configuration for development and production.
But I can't find an easy way to detect the current execution environment. Need something like (defn db-spec [] (if (is-dev?) { dev-spec-here } { prod-spec-here })).
Maybe it can detect the current lein profile. No matter how I ask to google. Can't find how.
A: I'm fond of using environment variables for this (which can be set system wide for example in /etc/profile amongst other places). others prefer to pass a -D definition to the JVM
A: your code is okay, detect it depend your environment, like hostname, IP arrdress, global variable etc.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/13908829",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: why do i get a circular import error on whichever module that comes first but not on the second? I am making a simple inventory program for college assignment. however i keep getting a circular import error on one of the module. i get the error on the module import that comes first and not on the second. but the strange thing is, if i were to switch the import order, the previous erroneous import works and the previously working import returns an error.
Elaboration:
when running as this, import A has circular import error and import B works fine.
import A
import B
But if i run the program as this, import B has circular import error and import A works fine
import B
import A
why is this happening? what is the problem here?
This is the main module.
import purchase
import addition
def choices():
print("Press any of following number for a course of action")
print("1. To Purchase Bikes")
print("2. To Add Bikes in the Stock")
print("3. Exit the program\n")
value = 0
while not value in range(1, 5):
try:
value = int(input("Enter your desired number: "))
except:
print("\n\nPlease enter a valid number between 1-5:\n")
if value > 3 or value < 1:
print("\nInvalid Input!! Please select from the given.\n")
choices()
elif(value == 1):
purchase.purBikes()
elif(value == 2):
addition.addStock()
elif(value == 3):
quit()
choices()
The whole program is available here. i know its a lot to look through but i didn't know what parts to remove to make a minimalized reproduceable example.
https://filebin.net/zgr985zo5wao5c0e
A: You have to rethink the design.
addition.py:
import Main
def addStock():
# The 2 last lines
Main.choices()
return shipCost
A module is a library of reusable components, so they can not depend on some "Main", they must work anyhere, specially on unit tests.
Also, you call addition.addStock() in Main.choices(), so there is a circular call. When does it return shipCost?
A: First off, your welcome function is not defined(I dont see it if it is)
Second, module purchase doesnt exist publicly so it may be the problem
| {
"language": "en",
"url": "https://stackoverflow.com/questions/72219585",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: ggplot/qqplotr returns error on data format I am trying to create a QQ and/or PP plot from the air_time data inside the flights data frame belonging to the nycflights13 package. I am using ggplot with qqplotr.
This is my code:
library(nycflights13)
library(qqplotr)
ggplot(data = flights$air_time, mapping = aes(sample = norm)) +
stat_qq_band() +
stat_qq_line() +
stat_qq_point() +
labs(x = "Theoretical Quantiles", y = "Sample Quantiles")
When I try to run this I get the error:
Error: `data` must be a data frame, or other object coercible by `fortify()`, not a numeric vector
What is causing this error and how do I fix it? I normally call ggplot as follows so I do not know if there could be issues there:
ggplot(flights, air_time, aes(sample = norm))
A: Change the sample argument to reflect the variable inside the data.
Air_time <- flights[, "air_time"] # Or select a random sample to save time
ggplot(data = Air_time, mapping = aes(sample = air_time)) +
stat_qq_band() +
stat_qq_line() +
stat_qq_point()
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60599769",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: "Fragment file is not indexed" in Signac/R I am currently running an snATAC-seq analysis and performed the following command:
chrom_assay <- CreateChromatinAssay(
counts = counts,
sep = c(":", "-"),
genome = 'mm10',
fragments = '../vignette_data/atac_v1_pbmc_10k_fragments.tsv',
min.cells = 10,
min.features = 200
)
Now, my error comes out as
Error in CreateFragmentObject(path = fragments, cells = cells,
validate.fragments = validate.fragments,
:Fragment file is not indexed.
Could someone provide possible solutions to mitigate this?
A: As written in the documentation of the function CreateChromatinAssay, the fragments = file should be a tabix file (ending in .tbi) containing the index with fragments of your data, or a Fragments object in R.
Apparently, first you will need to create the Fragments object in R from your tsv data, using the function CreateFragmentObject(). Take a look at: https://satijalab.org/signac/reference/fragments .
A: Based on the advise from the Signac developer in https://github.com/timoast/signac/issues/7#issuecomment-513934624 , the folder with the fragments file should also contain the fragment index file (.tbi). For example, for the human 10X PBMC vignette data (https://satijalab.org/signac/articles/pbmc_vignette.html): atac_v1_pbmc_10k/atac_v1_pbmc_10k_fragments.tsv.gz and
atac_v1_pbmc_10k/atac_v1_pbmc_10k_fragments.tsv.gz.tbi should be in the same folder. Hope this helps. Thanks.
A: Please see this Github issue to regenerate .tbi file
Briefly, run the following cmds in linux/unix terminal :
*
*gzip -d <fragment.tsv.gz>
*bgzip <fragment.tsv>
*tabix -p bed <fragment.tsv.gz>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/72524686",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: When i press Stop and then Play the sound dont works i have a simple app with 2 buttons. When i press Play, the sound run correctly, but when i press Pause and then play, the sound don´t works.
Why?
Here my code:
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final MediaPlayer mp = MediaPlayer.create(this, R.raw.sound);
Button Play = (Button) findViewById(R.id.button1);
Play.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
mp.start();
}});
final Button button2 = (Button) findViewById(R.id.button2);
button2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mp.stop();
//mp.reset();
}
});
}
}
A: change to this:
button2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (mp != null) {
mp.stop();
mp.release();
}
}
});
A: Don't use stop() for pausing media. Use pause() and check isPlaying() or not before pausing() it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/22319255",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to round up a floating variable in c upto 2/3/4....n digits precision without using and printf(".n%f") float f = 2.8386483,g ;
//Suppose I am having f = 2.8386483..... I want to store k = 2.8.... to n positions where n=a natural //number
//e.g. g= 2.83 to 2 decimal precision/n=2
// g = 2.838 to 3 decimal precision/n=3
A: Without using math.h, or printf(“.n%f”), the other answer will work for you.
But regarding your phrase I want to store k = 2.8.... to n positions. It may be interesting to you that this has less to do with rounding than it has to do with type, and how much memory is required to store each type.
float, double and long double require differing amounts of memory to store the precision (numbers to the right of ".") required by the type, regardless of how you format them for display. That is:
A displayed representation of a float may look like 2.83
while in memory, a float will contain memory sufficient to 7 digits precision 2.8368361 (on 32 bit system)
And for a type double representation of the same number might stored as 2.836836100000001.
Again, the way a number has little to do with how it is stored.
Edit: (Rounding a float to n decimal places)
#include <ansi_c.h>//I did not realized that this header INCLUDEs math.h, oops
int main(void)
{
int p;
float a,c;
printf("Enter the floating point value:-");
scanf("%f",&a);
printf("Enter the precision value:-");
scanf("%d",&p);
if(a>0)
{
c=((int)(a*pow(10,p)+0.5)/(pow(10,p)));
printf("Value Rounding Off:-%f",c);
}
else
{
c=((int)(a*pow(10,p)+0.5)/(pow(10,p)));
printf("Value Rounding Off:-%f",c);
}
getchar();
getchar();
}
From HERE (thanks to H. Gupta)
A: If you want to have n digits, then you can first start with multiplying your number f with 10^n. After that you can turn it into an integer so that the rest of the decimals "disappear" - turn it again into an float and divide by 10^n
However, remember to check for if the number needs to be rounded up or down :)
*
*2 places = 10^2
*2.836836 * 10^2 = 283.6836
*rounding rules: add 0.5 to the number
*283.6836 + 0.5 = 284.1836
*(int) 284.1836 = 284
*284 * 1.0 / 10^2 = 2.84
=>
float f = 10^2 * f + 0.5
int newint = (int) f f = newint * 1.0 / 10^2
A: Scale x and then round. Make sure to deal with negative numbers correctly if rounding to nearest.
Thanks to @David Heffernan C : x to the power n using repeated squaring without recursive function
float pow10f(unsigned exponent) {
float base = 10.0;
float result = 1.0;
while (exponent > 0) {
while ((exponent & 1) == 0) {
exponent /= 2;
base *= base;
}
exponent--;
result *= base;
}
return result;
}
float RoundToNPlaces(float x, unsigned n) {
if (x < 0.0) {
return -RoundToNPlaces(-x, n);
}
float scale = pow10f(n); // fix per @Michael Burr
x *= scale;
uintmax_t u = (uintmax_t) (x + 0.5); // Add 0.5 if rounding to nearest.
x = (float) u;
x /= scale;
return x;
}
Does have a range limit though but likely wider than int.
[Edit] per @Michael Burr comment
(int) (RoundToNPlaces( 2.8386483, 2) * 100) --> 283 rather than the expected 284. What happened though, is correct. Rounded to 2 places the result of 2.8386483 is mathematically 2.84 but is not representable with typical float. The 2 closest float to 2.84 are
2.8399999141693115234375000
2.8400001525878906250000000
and RoundToNPlaces( 2.8386483, 2) resulted in the closer one: 2.8399999141693115234375.
Now performing (int) (2.8399999141693115234375f * 100) --> (int) 283.99999141693115234375f --> 283.
This exhibits the necessary compromise to the OP's original goal, finding 2.8386483f rounded to 2 decimal places does not typically lead to an exact answer. Hence subsequent operations like * 100 and then int conversion lead to unexpected results, not because the best answer was not found in the round to 2 decimal places step, but because the best answer still will not exhibit all the properties of the mathematical exact answer.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/23252453",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Regex return all characters I was using the (.) to match all characters but it return back too with too many matches. How do i make it so it only 1 match?
private MatchCollection RegexMatchingV2(string data, string regex)
{
MatchCollection col = null;
try
{
col = Regex.Matches(data, regex, RegexOptions.IgnoreCase);
}
catch (Exception ex)
{
Response.Write("RegexMatching ERROR:" + ex.Message);
}
return col;
}
protected void Page_Load(object sender, EventArgs e)
{
MatchCollection col= RegexMatchingV2("return all of this data in 1 match", "(.)");
Response.Write(col.Count);//Too much matches
}
A: To make it a single match use (.*)
The single . matches a single character. The additional * means "zero or more".
Edit In response to the comment about two matches (the first match contains the string, and the second is an empty match): The Matches documentation indicates that it gives empty matches special treatment. There is a good example on that page to show the behavior. But the end result is that after the match, it does not do forward movement, so it picks up an empty match. To prevent that, you could use beginning of line and end of line anchors: (^.*$) or use the + to force at least one character to be included: (.+).
A: Since you want to match any number of any characters, change the . to .* to match zero or more, or .+ to match one or more.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/10643275",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: Adding TextView to content_main in Navigation Drawer Template I'm trying to add a TextView to the content_main layout while the setContentView is at activity_main. I am currently using the Navigation Drawer template when you create a new project in Android Studio. Activity_main includes app_bar_main which includes content_main.
Content_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/content_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:orientation="vertical"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="org.test.testy.test"
tools:showIn="@layout/app_bar_main"
android:weightSum="1">
</LinearLayout>
The code I'm trying to use is this:
LayoutInflater inflater;
inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = (View) inflater.inflate(R.layout.content_main, null);
LinearLayout layout = (LinearLayout) view.findViewById(R.id.content_main);
//Card view create
CardView cv = new CardView(layout.getContext());
cv.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
cv.setVisibility(View.VISIBLE);
TextView tv = new TextView(layout.getContext());
tv.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
tv.setText("Test");
tv.setVisibility(View.VISIBLE);
cv.addView(tv);
layout.addView(cv);
Everything below //Card view create was tested in a blank app, which worked perfectly fine. I also tried to put a TextView in the xml of content_main with an id and trying to read the text, which also returned the correct text. If I am able to access the layout and the code for adding to view is fine, then why is it not working?
A: Two things I was doing wrong:
*
*I had to id each of the <include>s with the EXACT name that it was going to and
*I had to go through each includes because I had two:
LinearLayout layout = (LinearLayout) findViewById(R.id.app_bar_main).findViewById(R.id.content_main);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41970933",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: What is the difference between WPF and Silverlight application? What is the difference between WPF and Silverlight application? Are they the same?
A: Silverlight is a subset of WPF. Once it was known as WPF/E (WPF everywhere). In fact, the base framework is similar, but not the same.
See this for further information: Silverlight "WPF/E" first steps: Getting started with simple analog clock, Introduction - What is WPF/E?
A: Silverlight is Microsoft’s latest development platform for building next-generation Web client applications
(WPF) is Microsoft’slatest development platform forbuilding next-generation Windows client applications
Silverlight is generally considered to be a subset of
WPF, and is a XAML
WPF is generally considered to be a subset of .NET Framework
Silverlight Support Cross OS, cross browser, cross device
WPF for Windows client users.
in order to run Silverlight applications at client machines, we need to install Silverlight
software on the client machine once
WPF, on the other hand, does notsupport any plug-in mechanism;instead, we need to install a
completed WPF client application
Silverlight applications are hosted within a webserver and a web page.
WPF applications can be deployed as standalone applications,
A: WPF is based off of the desktop CLR which is the full version of the CLR.
Silverlight is based on a much smaller and more compact CLR which provides a great experience but does not have the full breadth of CLR features. It also has a much smaller version of the BCL.
A:
Silverlight (codenamed WPF/E) is a cross-platform, cross-browser, browser plugin which contains WPF-based technology (including XAML)[17] that provides features such as video, vector graphics, and animations to multiple operating systems including Windows Vista, Windows XP, and Mac OS X, with Microsoft sanctioned 3rd party developers working ports for Linux distributions.[18] Specifically, it is currently provided as an add-on for Mozilla Firefox, Internet Explorer 6 and above, and Apple Safari. Silverlight and WPF only share the XAML presentation layer.
WIKI
A: WPF is essentially the replacement to Winforms in that it is a desktop application platform built on the .Net (3+) platform.
Silverlight represents a subset of WPF that is delivered through a browser plug-in, much like Flash/Flex.
A: Silverlight is a subset of WPF and therefore has fewer features but is more portable. WPF can be ran in both a browser or as a WinForms style application in Windows while Silverlight can only be ran in a browser. WPF is intended to run on Windows systems while Silverlight runs on Windows or Mac, also Linux via Moonlight.
If confused on when to use each, I found a useful blog better explaining this: http://blogs.msdn.com/b/jennifer/archive/2008/05/06/when-should-i-use-wpf-vs-silverlight.aspx
A: wpf is window application and Silverlight is web application
A: A detailed comparison can be found here: http://wpfslguidance.codeplex.com/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/629927",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "26"
} |
Q: Vertically aligning block element to image? I'm looking for a way to vertically align a block element to an image. On my site this image would dynamically change in height and width so I'd need the vertical alignment to adapt for whatever the image size is. For example:
<img src="photo.jpg" alt="test" />
<div id="box">
</div>
img { float: left; }
#box { float: right; width: 200px; height: 150px; background-color: #666; }
So I'd want this div to vertically align itself to the image. How can this be done?
Thanks.
A: The trick is to add a couple layers of wrapper-divs. The first layer is set to white-space: nowrap and max-width:50% which means that the elements inside can't wrap, and are constrained to 50% of the width of the parent.
Then you set the white space back to normal, and make the second layer display:inline-block so that these divs have to play by text alignment rules. Then you set both of them to vertical-align:middle; Just one won't work because vertical align is relative to the baseline of the text, not the containing block element.
So in this way we have constrained ourselves to one line of "text", composed of two div elements both aligned such their middle is at the text baseline, and ensured that their size must be no more than 50% of the parent container.
EDIT: I discovered after little more playing that you need to add some max-width:100% to keep the image from pushing the text out the right hand side.
EDIT 2: I should have mentioned that this requires IE-8 standards mode, added meta-equiv to tell IE-8 to behave itself, but giving a proper doctype or sending an http response header can achieve the same thing google IE8 standards mode for all that stuff.
<html >
<head>
<title>Test</title>
<meta http-equiv="X-UA-Compatible" content="IE=8" />
<style type="text/css">
.wrapper1 {
white-space:nowrap;
max-width:50%;
}
.wrapper2 {
white-space:normal;
display:inline-block;
vertical-align:middle;
max-width:100%;
}
.variable-img {
max-width:100%;
}
</style>
</head>
<body>
<div class="wrapper1">
<div class="wrapper2">
<img class="variable-img" src="test.png">
</div>
<div class="wrapper2">
<div id="box">
Lorem ipsum dolor sit amet, consectetur adipisicing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna
aliqua. Ut enim ad minim veniam, quis nostrud exercitation
ullamco laboris nisi ut aliquip ex ea commodo consequat.
Duis aute irure dolor in reprehenderit in voluptate velit
esse cillum dolore eu fugiat nulla pariatur. Excepteur sint
occaecat cupidatat non proident, sunt in culpa qui officia
deserunt mollit anim id est laborum</div>
</div>
</div>
</body>
</html>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/9072258",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Taking 4-5 second to visible view with big ArrayList data to RecyclerView inside NestedScrollView I have three RecyclerView in NestedScrollView, 2 RecyclerView having approx 100 items and third having approx 400 items. Then it takes 4-5 seconds to render the view after adding data to arraylist and notifiedDataSetChanged(). Every RecyclerView is in vertical. So if there any solution for this please explain
if(!itemsList.isEmpty()) {itemsList.clear();}
itemsList.addAll(itemData);
itemAdapter.notifyDataSetChanged();
A: Recyclerview inside nested scrollview does complete layout at a single load rather than usual recyclerview behaviour, try to remove nested scrollview from layout, use recyclerview with different view types.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56475643",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: python xml elementtree wrap text by number of characters I'm wondering in xml elementtree how to wrap the text?
For instance, I have the following text
4324OO234324O234O32O423423OO23O432O4OO23O4O32O423O423O4O234OO234234O234OO324O234
And I need to make sure that it wraps the text for every 10 characters e.g.
However, I also need to preserve the tabs/whitespace that is happening after each line.
<mydata>
4324OO2343
24O234O32O
423423OO23
O432O4OO2
3O4O32O42
3O423O4O2
34OO234234
O234OO324
O234
</mydata>
Any idea of any easy way to do this in python 2.5.2?
This is not a replicate question, because this is xml elementtree specific... It might be possible to break the chars up into chunks, but then I have to use minidom.parseString and toprettyxml, to get the tabs - but I havent found a way to do it yet –
A: The poster that voted to close this question was not correct and didn't provide help towards a solution. The duplicate thread only provided part of the solution, which is not useful in this case.
In the end I resolved it the following way:
hexerre = re.sub("(.{80})", "\1\n\t\t\t\t\t\t\t", hexer, 0)
By adding the tabs into the regex expression I was able to get the indentation needed.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36245543",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Sencha Extjs 6.2 : Edit object values in cell grid I have a grid and in the last two columns (Chourly and Cdaily), each cell contains an object.
Example of data :
{
data: [{
Date: "2018/01/11 21:00:00",
Ahourly: "1",
Chourly: {
val: 2,
status: "Low",
color: "#ffff00"
}
}, ...
success: true
}
Here is my fiddle, see Chourly and Cdaily columns.
I need to edit data of this object and display the new values.
I tried to use beforeedit end validateedit but for now no success !
Any help ?
Thanks,
mpe
A: First thing to do is to adjust your data model in the store.
Use "mapping" to accommodate all the fields in object field into individual fields,
like that:
var store = Ext.create('Ext.data.JsonStore', {
fields: [
'Date',
'Ahourly',
{name:'ChourlyVal',mapping:'Chourly.val'},
{name:'ChourlyColor',mapping:'Chourly.color'},
{name:'ChourlyStatus',mapping:'Chourly.status'},
{name:'CdailyVal' ,mapping:'Cdaily.val'},
{name:'CdailyColor' ,mapping:'Cdaily.color'},
{name:'CdailyStatus' ,mapping:'Cdaily.status'}
],
proxy: {
type: 'ajax',
url: 'data1.json',
reader: {
type: 'json',
rootProperty: 'data'
}
},
autoLoad: true
});
And than, adjust the column and the renderer to use the mapped fields:
{
text: 'Chourly',
dataIndex: 'ChourlyVal',
flex: 1,
renderer: function (a, meta, record) {
console.log(record);
meta.tdStyle = "background-color:" + record.data.ChourlyColor + ";";
var cellText = a + " " + record.data.ChourlyStatus;
return cellText;
},
editor: 'textfield'
}
I hope that helps
A: Thanks for your reply. I think its the good way.
Then I think I have to use the serialize function to put the object back together with the modified value(s) to send back to the server like this :
fields: ['Date', {
name: 'Chourly',
serialize: function (val, rec) {
return {
'val': rec.get('val'),
'status': rec.get('status'),
'color': rec.get('color')
};
}
}, {
name: 'val',
mapping: 'Chourly.val',
persist: false //Do not write back to server
}, {
name: 'status',
mapping: 'Chourly.status',
persist: false
}, {
name: 'color',
mapping: 'Chourly.color',
persist: false
},
...
]...
Now I have to do that dynamically because I don't know in advance which data the user will consult (Chourly, Dhourly, Ehourly ....). Any idea to modify the model on the load callback ?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/48229785",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Limit root node processing in CPLEX Python I have a very large problem (1m variables, 3m constraints) that I'm trying to solve using CPLEX in Python. Obviously, solving it optimally is out of the question, so I have implemented a time limit so I could get the best solution within that time.
c.timelimit.set(7200)
However, when the time was up, it hadn't even finished processing the root node:
Nodes Cuts/
Node Left Objective IInf Best Integer Best Bound ItCnt Gap
0 0 10.0070 2177 10.0070 65714
0 0 10.0070 1793 Cuts: 29 80275
0 0 10.0070 2427 Cuts: 6928 101277
0 0 10.0070 2061 Cuts: 4737 122524
Implied bound cuts applied: 485
Flow cuts applied: 68
Mixed integer rounding cuts applied: 12019
Zero-half cuts applied: 193
Root node processing (before b&c):
Real time = 7200.47 sec. (2762999.79 ticks)
Parallel b&c, 112 threads:
Real time = 0.00 sec. (0.00 ticks)
Sync time (average) = 0.00 sec.
Wait time (average) = 0.00 sec.
------------
Total (root+branch&cut) = 7200.47 sec. (2762999.79 ticks)
Solution status = 108 :
MIP_time_limit_infeasible
Exception raised during solve
Is there any way to limit the time spent on the root node so it at least starts the b&c method? Would that even be advantageous at all?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/53564585",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: HSQL database user lacks privilege or object not found error I am trying to use hsqldb-2.3.4 to connect from Spring applicastion.
I created data base using the following details
Type : HSQL Database Engine Standalone
Driver: org.hsqldb.jdbcDriver
URL: jdbc:hsqldb:file:mydb
UserName: SA
Password: SA
I created a table named ALBUM under "MYDB" schema
In spring configuration file:
<bean id="jdbcTemplate"
class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">
<constructor-arg ref="dbcpDataSource" />
</bean>
<bean id="dbcpDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.hsqldb.jdbcDriver" />
<property name="url" value="jdbc:hsqldb:file:mydb" />
<property name="username" value="SA" />
<property name="password" value="SA" />
</bean>
And in my spring controller I am doing jdbcTemplate.query("SELECT * FROM MYDB.ALBUM", new AlbumRowMapper());
And It gives me exception:
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.jdbc.BadSqlGrammarException: PreparedStatementCallback; bad SQL grammar [SELECT * FROM MYDB.ALBUM]; nested exception is java.sql.SQLSyntaxErrorException: user lacks privilege or object not found: ALBUM
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:982)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
If I execute same query through SQL editor of hsqldb it executes fine. Can you please help me with this.
A: I had the error user lacks privilege or object not found while trying to create a table in an empty in-memory database.
I used spring.datasource.schema and the problem was that I missed a semicolon in my SQL file after the "CREATE TABLE"-Statement (which was followed by "CREATE INDEX").
A: As said by a previous response there is many possible causes. One of them is that the table isn't created because of syntax incompatibility. If specific DB vendor syntax or specific capability is used, HSQLDB will not recognize it. Then while the creation code is executed you could see that the table is not created for this syntax reason. For exemple if the entity is annoted with @Column(columnDefinition = "TEXT") the creation of the table will fail.
There is a work around which tell to HSQLDB to be in a compatible mode
for pgsl you should append your connection url with that
"spring.datasource.url=jdbc:hsqldb:mem:testdb;sql.syntax_pgs=true"
and for mysql with
"spring.datasource.url=jdbc:hsqldb:mem:testdb;sql.syntax_mys=true"
oracle
"spring.datasource.url=jdbc:hsqldb:mem:testdb;sql.syntax_ora=true"
note there is variant depending on your configuration
it could be hibernate.connection.url= or spring.datasource.url=
for those who don't use the hibernate schema creation but a SQL script you should use this kind of syntax in your script
SET DATABASE SQL SYNTAX ORA TRUE;
It will also fix issues due to vendor specific syntax in SQL request such as array_agg for posgresql
Nota bene : The the problem occurs very early when the code parse the model to create the schema and then is hidden in many lines of logs, then the unitTested code crash with a confusing and obscure exception "user lacks privilege or object not found error" which does not point the real problem at all. So make sure to read all the trace from the beginning and fix all possible issues
A: If you've tried all the other answers on this question, then it is most likely that you are facing a case-sensitivity issue.
HSQLDB is case-sensitive by default. If you don't specify the double quotes around the name of a schema or column or table, then it will by default convert that to uppercase. If your object has been created in uppercase, then you are in luck. If it is in lowercase, then you will have to surround your object name with double quotes.
For example:
CREATE MEMORY TABLE "t1"("product_id" INTEGER NOT NULL)
To select from this table you will have to use the following query
select "product_id" from "t1"
A: user lacks privilege or object not found can have multiple causes, the most obvious being you're accessing a table that does not exist. A less evident reason is that, when you run your code, the connection to a file database URL actually can create a DB. The scenario you're experiencing might be you've set up a DB using HSQL Database Manager, added tables and rows, but it's not this specific instance your Java code is using. You may want to check that you don't have multiple copies of these files: mydb.log, mydb.lck, mydb.properties, etc in your workspace. In the case your Java code did create those files, the location depends on how you run your program. In a Maven project run inside Netbeans for example, the files are stored alongside the pom.xml.
A: I had similar issue with the error 'org.hsqldb.HsqlException: user lacks privilege or object not found: DAYS_BETWEEN' turned out DAYS_BETWEEN is not recognized by hsqldb as a function. use DATEDIFF instead.
DATEDIFF ( <datetime value expr 1>, <datetime value expr 2> )
A: When running a HSWLDB server. for example your java config file has:
hsql.jdbc.url = jdbc:hsqldb:hsql://localhost:9005/YOURDB;sql.enforce_strict_size=true;hsqldb.tx=mvcc
check to make sure that your set a server.dbname.#. for example my server.properties file:
server.database.0=eventsdb
server.dbname.0=eventsdb
server.port=9005
A: I was inserting the data in hsql db using following script
INSERT INTO Greeting (text) VALUES ("Hello World");
I was getting issue related to the Hello World object not found and HSQL database user lacks privilege or object not found error
which I changed into the below script
INSERT INTO Greeting (text) VALUES ('Hello World');
And now it is working fine.
A: Add these two extra properties:
spring.jpa.hibernate.naming.implicit-strategy=
org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyJpaImpl
spring.jpa.hibernate.naming.physical-strategy=
org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
A: I bumped into kind of the same problem recently. We are running a grails application and someone inserted a SQL script into the BootStrap file (that's the entry point for grails). That script was supposed to be run only in the production environment, however because of bad logic it was running in test as well. So the error I got was:
User lacks privilege or object not found:
without any more clarification...
I just had to make sure the script was not run in the test environment and it fixed the problem for me, though it took me 3 hours to figure it out. I know it is very, very specific issue but still if I can save someone a couple of hours of code digging that would be great.
A: I was having the same mistake. In my case I was forgetting to put the apas in the strings.
I was doing String test = "inputTest";
The correct one is String test = "'inputTest'";
The error was occurring when I was trying to put something in the database
connection.createStatement.execute("INSERT INTO tableTest values(" + test +")";
In my case, just put the quotation marks ' to correct the error.
A: In my case the error occured because i did NOT put the TABLE_NAME into double quotes "TABLE_NAME" and had the oracle schema prefix.
Not working:
SELECT * FROM FOOSCHEMA.BAR_TABLE
Working:
SELECT * FROM "BAR_TABLE"
A: had this issue with concatenating variables in insert statement. this worked
// var1, var3, var4 are String variables
// var2 and var5 are Integer variables
result = statement.executeUpdate("INSERT INTO newTable VALUES ('"+var1+"',"+var2+",'"+var3+"','"+var4+"',"+var5 +")");
A: In my case the issue was caused by the absence (I'd commented it out by mistake) of the following line in persistence.xml:
<property name="hibernate.hbm2ddl.auto" value="update"/>
which prevented Hibernate from emitting the DDL to create the required schema elements...
(different Hibernate wrappers will have different mechanisms to specify properties; I'm using JPA here)
A: I had this error while trying to run my application without specifying the "Path" field in Intellij IDEA data source (database) properties. Everything else was configured correctly.
I was able to run scripts in IDEA database console and they executed correctly, but without giving a path to the IDEA, it was unable to identify where to connect, which caused errors.
A: You have to run the Database in server mode and connect.Otherwise it wont connect from external application and give error similar to user lacks privilege.
Also change the url of database in spring configuration file accordingly when running DB in server mode.
Sample command to run DB in server mode
$java -cp lib/hsqldb.jar org.hsqldb.server.Server --database.0 file:data/mydb --dbname.0 Test
Format of URL in configuration file
jdbc:hsqldb:hsql://localhost/Test
A: In my case, one of the columns had the name 'key' with the missing @Column(name = "key") annotation so that in the logs you could see the query that created the table but in fact it was not there. So be careful with column names
A: For what it's worth - I had this same problem. I had a column named 'TYPE', which I renamed to 'XTYPE' and a column named ORDER which I renamed to 'XORDER' and the problem went away.
A: Yet another reason could be a misspelt field name. If your actual table has an id column named albumid and you'd used album_id, then too this could occur.
As another anwer remarked, case differences in field names too need to be taken care of.
A: I faced the same issue and found there was more than one PersistenceUnit (ReadOnly and ReadWrite) , So the tables in HSQLDDB created using a schema from one persistence unit resulted in exception(HSQL database user lacks privilege or object not found error) being thrown when accessed from other persistence unit .It happens when tables are created from one session in JPA and accessed from another session
A: In my case the table MY_TABLE was in the schema SOME_SCHEMA. So calling select/insert etc. directly didn't work. To fix:
*
*add file schema.sql to the resources folder
*in this file add the line CREATE SCHEMA YOUR_SCHEMA_NAME;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/38415734",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "43"
} |
Q: How to handle a GET request in python I have some microservices running in kubernetes, and they need to pass some data among each other, but I can't handle the GET request from the server side.
The docs I found are very focused on how to make the GET request on python, but not how to handle it.
So, this is what I tried:
from flask import Flask
from flask import request
import requests
app = Flask(__name__)
@app.route('/<trace_id>')
def root():
return trace_id
if __name__ == "__main__":
app.run(host='0.0.0.0', port=8080, debug=True)
From the client, I do the request like this:
>>> trace_id = '54b012b2767e7b21321ca649872913c5'
>>> requests.get('http://my-service', params=trace_id)
<Response [404]>
And on my server I get this dumped:
/# python3 app.py
* Serving Flask app "app" (lazy loading)
...
10.52.2.29 - - [29/Nov/2019 18:41:23] "GET /?54b012b2767e7b21321ca649872913c5 HTTP/1.1" 404 -
I would like to know how to handle the request on the server side. Also, it would be nice to get some suggestions of what's the best way of dealing with this.
Note: there is a k8s service in front of the server that gets the
requests on port 80 and forward them to 8080.
A: You need to pass trace_id as input argument
def root(trace_id):
return trace_id
And trace_id is part of the url, not the query part:
requests.get('http://my-service/' + trace_id)
A: We have to look closer at your code.
@app.route('/<trace_id>')
String argument inside brackets is a path part after 'http://my_service/'.
Full path of this API endpoint will be 'http://my_service/value_of_trace_id'.
And this part 'value_of_trace_id' will be stored as 'trace_id' variable and passed to function body so you have to pass it as function (API endpoint) arg.
@app.route('/<trace_id>')
def api_endpoint(trace_id):
return trace_id
So, you have to use:
requests.get('http://my-service/' + trace_id)
I highly recommend read that or that.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/59109784",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: modifying softmax function in tensorflow I started using tensorflow about a week ago, so I'm not sure what API can I use.
Currently I'm using basic mnist number recognition code.
I want to test how recognition precision of this code changes if I modify the softmax function from floating point calculation to fixed point calculation.
At first I tried to modify the library but it was too complicated to do so. So I think I have to read tensors and modify(calculate) it in the form of array and change it to the tensor using tf.Session().eval() function.
Which function should I use?
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
import tensorflow as tf
x = tf.placeholder(tf.float32, [None, 784])
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
y = tf.nn.softmax(tf.matmul(x, W) + b)
#temp = tf.Variable(tf.zeros([784, 10]))
temp = tf.Variable(tf.matmul(x, W) + b)
#temp = tf.add(tf.matmul(x, W),b)
y_ = tf.placeholder(tf.float32, [None, 10])
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]))
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)
#print(temp[500])
for i in range(100):
batch_xs, batch_ys = mnist.train.next_batch(100)
sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})
correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
print(sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels}))
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46020677",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Start Segue After Completion Of Social Sharing I want to let users share some posts from my app with the help of the social framework. But after the post button in the social framework, the segue is not starting. How can I handle this?
var shareToFacebook : SLComposeViewController = SLComposeViewController(forServiceType: SLServiceTypeFacebook)
shareToFacebook.addImage(self.Img.image)
self.presentViewController(shareToFacebook, animated: true, completion: nil)
self.performSegueWithIdentifier("goToStarting", sender: self)
A: You have to present the view controller in this method
var completionHandler: SLComposeViewControllerCompletionHandler!
You can use the above method like this
var shareToFacebook : SLComposeViewController = SLComposeViewController(forServiceType: SLServiceTypeFacebook)
shareToFacebook.addImage(self.Img.image)
shareToFacebook.completionHandler = {
(result:SLComposeViewControllerResult) in
}
self.presentViewController(shareToFacebook, animated: true, completion: nil)
self.performSegueWithIdentifier("goToStarting", sender: self)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/32317586",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to store HTML form value for other pages in PHP and MySQLi? I have created a database in phpMyAdmin with table for topics such as Math, Physics etc. Each topic has a topic_id as primary key in table tb_topic. Each topic can have multiple videos. Admin can add videos to each topic which requires topic_id as foreign key in table tb_video_management to store videos against a topic.
Backend:
There is a button to add videos in form.php
form.php:
<?php
$query = "SELECT topic_id, topic_name,aid FROM tb_topic";
$result = $con->query($query);
while($query_row = mysqli_fetch_assoc($result)) {?>
<tr>
<td><form action='edit.php' method='get'>
<button type='submit' name='edit' id = 'edit' value='<?php echo $query_row['topic_id'];?>' class='btn btn-success'>EDIT</button><br />
</form></td>
</tr>
<?php
} ?>
When this button is clicked, page is navigated to another page "edit.php" which has 2 buttons, one for add new video and second for viewing video gallery.
edit.php:
$id = $_GET['edit'];
echo 'topic id----> ' . $id;
<form action='add_video.php' method='get'>
<button type='submit' name='add' id = 'add' value='<?php echo $id;?>' class='btn btn-success'>ADD NEW VIDEO</button>
</form>
<form action="video.php" method="get">
<button type="submit" name="goback" id="goback" value="submit" class="btn btn-primary">VIEW GALLERY</button>
</form>
The class where videos are added has a form for topic name, details etc.
add_video.php
$id = $_GET['add'];
echo 'topic id----> ' . $id;
<form action="add_video.php" method="post">
Video Title: <input type="text" name="video_name"><br />
Video Detail: <input type="text" name="video_detail"><br />
Video Question: <input type="text" name="video_question"><br />
Video Link: <input type="text" name="video_link"><br />
<input type="submit" name="submit" value = "Submit"><br />
</form>
When "submit" button is clicked, following code executes:
if(isset($_POST['submit'])) {
if(!(empty($_POST['video_name']) || empty($_POST['video_detail']) || empty($_POST['video_question']) || empty($_POST['video_link']))) {
$name = $_POST['video_name'];
$detail = $_POST['video_detail'];
$question = $_POST['video_question'];
$link = $_POST['video_link'];
$insert = "INSERT INTO tb_video_management(topic_id, video_name, video_detail, video_question,video_link) VALUES ('$id','$name','$detail', '$question','$link')";
if(!mysqli_query($con,$insert))
echo "error";
header('location:edit.php');
}
}
The problem I am facing is, when I click submit button, the value in $id is lost (may be because another button (submit) is pressed) and it fails to insert the record as there is no value for "topic_id" anymore. I cannot resolve this issue of keeping foreign key value even after pressing submit button.
So far I have been creating extra table to hold value for topic_id which is definitely not the right approach.
A: To use the $id into another page, you must have to store that in such a way that it will be remain exist after submit.That can be done by using the hidden field.
You may set the value of $id like:
<input type="hidden" name="topic_id" value="<?php echo $id?>">
Once you submit and redirect to add_video.php, you may get the value of $id same as another field video_detail.
On submit look like:
if(isset($_POST['submit'])) {
$topic_id = $_POST['topic_id'];
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56845779",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Data structure and algorithms: Should one use OOP to program algorithms? I have seen people code for example, say a quicksort algorithm without using OOP. I have also seen the identical algorithm in Robert Lafore's data structure and algorithm textbook written under OOP framework.
Is it better to do it using OOP ? What are the advantages or disadvantages?
Suppose I know how to write an algorithm in both ways, should I always do it the OOP way ? Or does it depend on the algorithm itself ? If yes, then what algorithms would using OOP be beneficial ?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/27339508",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Can't get TinyMCE 4.0.6 to work This is driving me crazy....
I'm trying to get TinyMCE v4.0.6 to work, and I'm probably doing something very dumb, since I can't get the editor to display at all.
I could get a v3.5.8 editor to show in a page similar to what follows, but no joy with this:
<!DOCTYPE html>
<html>
<head>
<title>TinyMCE Test</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<script type="text/javascript" src="tinymce/tinymce.min.js"></script>
<script type="text/javascript">
tinymce.init({
selector: "textarea"
});
</script>
</head>
<body>
<form method="post" action="something">
<textarea name="content" cols="100" rows="15">content</textarea>
<input type="submit" value="Save" />
</form>
</body>
</html>
I've verified (using FireBug) that the path to the tinymce JavaScript file is correct, but other than that, I'm completely at a loss.
Thanks for any suggestions..
A: After your comment, I took your HTML and checked it with a CDN copy of tinyMCE and it work fine: http://codepen.io/anon/pen/mIvFg so I can only assume it's an error with your tinymce.min.js file.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/18949318",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Problems with an extra space when redirecting variables into a text file When I run the following lines:
set "Loc=%~dp0"
echo %Loc% > C:\PLACE\LOCFILE.txt
I receive the following in the LOCFILE:
C:\BATCHLOC
^
Note Space
I am trying to use %Loc% like this in a separate batch file:
(
set /p Loc=
)<C:\PLACE\LOCFILE.txt
)
call "%Loc%\FILENAME.bat"
But the space ruins the path, and so then the call command doesn't work. Does anyone know how to fix this, (Stop it from creating the space at the end)?
A: echo %Loc% > C:\PLACE\LOCFILE.txt
↑
This space is written to the file.
Fix:
echo %Loc%> C:\PLACE\LOCFILE.txt
A: This is more robust.
>"C:\PLACE\LOCFILE.txt" echo(%Loc%
The redirection at the starts stops numbers like 3,4,5 in %loc% from breaking your code when redirection is directly at the end (such as shown below).
When using the technique below then constructs like test 2 in %loc% will also fail.
This is because single digit numbers at the end are interpreted as stream designators, so numerals 0 to 9 are all problems when placed directly before a redirection character (> or >>).
do not use this: echo %Loc%> C:\PLACE\LOCFILE.txt
Extra tips:
The echo( protects from other failures in the echo command and the ( character has been tested as the least problematic character when used in this way.
The double quotes around the "drive:\path\filename" also protect against long filename elements such as spaces, as well as the & character.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21898556",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: TextView.setMaxLines not working? In my app I have a screen where I display some text and then a photo. The text is variable in length (sometimes none at all, sometimes a lot), so I wanted to have it set up so the text never takes up more than a few lines (but can be scrolled) leaving enough room for the image below.
My view component for this part is created programatically, and I've adjusted the code to have the following (currently in my text-setting method, but the same thing happens if it's in the initial view-create code)
public void SetDescription(String description)
{
mTxtDescription.setText(Html.fromHtml(description));
mTxtDescription.setClickable(true);
mTxtDescription.setMaxLines(5);
mTxtDescription.setLines(5); //this makes no difference either!
mTxtDescription.setSingleLine(false);
mTxtDescription.setScrollbarFadingEnabled(true);
mTxtDescription.setScrollBarStyle(VERTICAL);
mTxtDescription.setMovementMethod(ScrollingMovementMethod.getInstance());
mTxtDescription.invalidate(); //adding this made no difference...
}
However it doesn't work- long text still fills the whole screen and the image has vanished due to being pushed down to a height of 0. How can I get the text to never be more than 5 lines?
A: Try removing the call to setSingleLine. And use setInputType(InputType.TYPE_TEXT_FLAG_MULTI_LINE). It'd also put this call before the setMaxLines and setLines call to be sure.
Note: setLines overrides the settings of setMaxLines and setMinLines.
The TextView has many issues surrounding the various calls to how it should display multiple, ellipses, etc.
A: The setSingleLine(false) seemes to reset the setMaxLines command. Try to move the setSingleLine command before the setText. That worked for me.
A: The below code is working fine for me
txt = (TextView)findViewById(R.id.textview);
txt.setMaxLines(5);
txt.setMovementMethod(new ScrollingMovementMethod());
txt.setScrollContainer(true);
txt.setText("Example Text");
txt.setTextColor(Color.WHITE);
txt.setScrollbarFadingEnabled(true);
in xml inside textview
android:scrollbars="vertical"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/11408922",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Variable Scopes Within PowerShell Nested Functions I was given this extensive PowerShell script from a major/reputable corporation which was supposed to work flawlessly. Well, it didn't.
The script is composed of numerous nested functions with lots of variables passed to the main parent function and then to all of its children. Children who use and modify all these variables.
Why is it that all these variables do not contain the correct data?
Here's the structure I'm talking about:
f1 {
f2 {
v #prints 0
v = 1
f3
}
f3 {
v #prints 1
v = 2
}
v = 0
f2
v #should print 2 but prints 0
}
A: Note:
This was tested with PowerShell 3.0 and 4.0.
Within nested functions, all child functions have access to all of the parent functions' variables. Any changes to the variables are visible within the local scope of the current function and all the nested child functions called afterwards. When the child function has finished execution, the variables will return to the original values before the child function was called.
In order to apply the variable changes throughout all the nested functions scopes, the variable scope type needs to be changed to AllScope:
Set-Variable -Name varName -Option AllScope
This way, no matter at what level within the nested functions the variable gets modified, the change is persistent even after the child function terminates and the parent will see the new updated value.
Normal behavior of variable scopes within Nested Functions:
function f1 ($f1v1 , $f1v2 )
{
function f2 ()
{
$f2v = 2
$f1v1 = $f2v #local modification visible within this scope and to all its children
f3
"f2 -> f1v2 -- " + $f1v2 #f3's change is not visible here
}
function f3 ()
{
"f3 -> f1v1 -- " + $f1v1 #value reflects the change from f2
$f3v = 3
$f1v2 = $f3v #local assignment will not be visible to f2
"f3 -> f1v2 -- " + $f1v2
}
f2
"f1 -> f1v1 -- " + $f1v1 #the changes from f2 are not visible
"f1 -> f1v2 -- " + $f1v2 #the changes from f3 are not visible
}
f1 1 0
Printout:
f3 -> f1v1 -- 2
f3 -> f1v2 -- 3
f2 -> f1v2 -- 0
f1 -> f1v1 -- 1
f1 -> f1v2 -- 0
Nested Functions with AllScope variables:
function f1($f1v1, $f1v2)
{
Set-Variable -Name f1v1,f1v2 -Option AllScope
function f2()
{
$f2v = 2
$f1v1 = $f2v #modification visible throughout all nested functions
f3
"f2 -> f1v2 -- " + $f1v2 #f3's change is visible here
}
function f3()
{
"f3 -> f1v1 -- " + $f1v1 #value reflects the change from f2
$f3v = 3
$f1v2 = $f3v #assignment visible throughout all nested functions
"f3 -> f1v2 -- " + $f1v2
}
f2
"f1 -> f1v1 -- " + $f1v1 #reflects the changes from f2
"f1 -> f1v2 -- " + $f1v2 #reflects the changes from f3
}
f1 1 0
Printout:
f3 -> f1v1 -- 2
f3 -> f1v2 -- 3
f2 -> f1v2 -- 3
f1 -> f1v1 -- 2
f1 -> f1v2 -- 3
| {
"language": "en",
"url": "https://stackoverflow.com/questions/29831826",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
} |
Q: One to one function in R to change number to text I have quite long list of postal codes with corresponding name of city or town. I just want to write a R program that has postal code as input variable and returns the name of the location (city or town). The list will be finite in length and has about 40 different pairs of postal code and location name. What is the best way to do this?
A: myProg<-function(code) db$city[db$code==code]
A: This is a filtering question. There are a number of ways to filter data in R. Here's what you need to do:
*
*Put your data in a data.frame
*Try filtering it:
*Now make it a function (this is your program)
*Use the function
postal_codes <- data.frame(code = c(78754, 84606), location = c("Austin", "Provo"))
postal_codes[postal_codes$code %in% 78754, ]
postal_finder <- function(mycode) {
postal_codes$location[postal_codes$code %in% mycode]
}
postal_finder(78754)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/65347536",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: ExpressJS app.use("/" router) router.get("/") Breaks I'm not sure how to phrase this, but part of the following code, for lack of an appropriate term, doesn't work. If I try to go to localhost:3000/ it doesn't send back a response. I'm using Express 4.7.4 and the latest node available on the Ubuntu Trusty repository.
app.js
///// Dependencies & config
var express = require('express');
///// Bootstrapping
//// Prepare Express
var server = express();
/// Configure Express
server.set('views', __dirname + '/views');
/// Routers
var infoR = express.Router();
// This doesn't send anything back
infoR.get("/", function(req, res) {
res.render('common/home');
});
// This works perfectly
infoR.get("/something", function(req, res) {
res.render('info/something');
});
// Routes that work
server.use('/admin', require('./routes/admin'));
server.use('/account', require('./routes/account'));
server.use('/', infoR); // This is where the problem starts
///// Start the server
server.listen(3000, function() {
console.log('Server started on port 3000');
});
A: Fixed by updating Express to version 4.9.
Edit: Turns out I've been doing it wrong, as noted in the documentation.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/26372345",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: EXC_BREAKPOINT in Swift I set up a var tagTextField: UITextField in the a set up method. Later when I call a method where I want to do something with this var tagTextField: UITextField, namely:
var pos1 = tagTextField.positionFromPosition(tagTextField.beginningOfDocument, inDirection: UITextLayoutDirection.Right, offset: 0)
I get the following Error:
Thread 1: EXC_BREAKPOINT (code=1, subcode=0x1000e4280)
I tried to just see if the var tagTextField: UITextField == nil, but then I get the same Error. Any suggestions why this is? If you need more code, let me know.
Thanks in advance
edit:
here is the error. no breakpoint
A: You set a breakpoint on Xcode (probably by mistake when trying to access to a specific line).
Breakpoints are represented by blue tabs and allow you to stop the execution of your code to check some variable states for instance. Just click on it again to deactivate it (it will turn light blue).
A: You've set some sort of user-breakpoint.
All user-set breakpoints show up in the Breakpoint Navigator:
If your Xcode doesn't say "No Breakpoints" here, you have breakpoints. Good news is, you can manage all your breakpoints from this tab. You can delete them, or create new ones.
Click the plus sign at the bottom lets you add different sorts of breakpoints here.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/27167664",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: using #define to substitute in a continuous string I am trying to write a Macro for certain read/write functions. The functions are in the form
k_target_socket.write8(address,val);
When I tried #define Wx(add,val) k_target_socket.writex(address,val) I got W8(0x100,0x120); for W8(0x100,0x120); then I replace the macro with #define W(x,add,val) & then got k_target_socket.writex(0x100,0x120); Is there a way to substitute for x in the above two examples?
A: What you need is token pasting. try the following:
#define W(x,ad,val) k_target_socket.write##x(ad,val)
The ## will paste the x with the function name.
More details here
| {
"language": "en",
"url": "https://stackoverflow.com/questions/20541022",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Movable Panel control using C# I'm trying to make my panel control movable using c#, but my main form moves along with the panel control when dragging. Is there a better code for this?
public const int WM_NCLBUTTONDOWN = 0xA1;
public const int HT_CAPTION = 0x2;
[DllImport("user32.dll")]
public static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);
[DllImport("user32.dll")]
public static extern bool ReleaseCaptre();
public static void _MOVE_PANEL(IntPtr Handle, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
ReleaseCaptre();
SendMessage(Handle, WM_NCLBUTTONDOWN, HT_CAPTION, 0);
}
}
private void sub_inv_pcount_edit_MouseMove(object sender, MouseEventArgs e) //panel move
{
_MOVE_PANEL(Handle, e);
}
see sample: see screenshot
A: I'm afraid this is not an approach you can tweak to get the result you want. WM_NCLBUTTONDOWN is essentially how the window manager decides how to handle mouse events on a top-level window. It allows you to make windows that have custom chrome, but it doesn't allow you to do anything about non-top-level windows (such as your panel).
You can get a reasonably nice-working dragging doing the obvious thing - in MouseMove, handle moving the control yourself. It's not going to be as well behaved as moving the entire window, though.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58130649",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Error with primary key in one-to-one relationship using Entity Framework I've created a database according to which the user profile is formed by the following two classes:
public class Usr
{
[Key()]
public int UsrID { get; set; }
public virtual UsrType UsrType { get; set; }
public virtual UsrStatus UsrStatus { get; set; }
[Required]
[MaxLength(100, ErrorMessage = "Email can only contain {0} characters")]
public string UsrEmail { get; set; }
[Required]
[MaxLength(32, ErrorMessage = "Password can only contain {0} characters")]
[MinLength(8, ErrorMessage = "Password must be at least {0} characters")]
public string UsrPassword { get; set; }
}
public class UsrDetails
{
[ForeignKey("UsrID")]
[Required]
public virtual Usr Usr { get; set; }
[Required]
[MaxLength(40, ErrorMessage = "Name can only contain {0} characters")]
public string UsrName { get; set; }
[Required]
[MaxLength(40, ErrorMessage = "Surname can only contain {0} characters")]
public string UsrSurname { get; set; }
[Required]
[MaxLength(20, ErrorMessage = "Country can only contain {0} characters")]
public string UsrCountry { get; set; }
[Required]
[MaxLength(20, ErrorMessage = "City can only contain {0} characters")]
public string UsrCity { get; set; }
[Required]
[MaxLength(40, ErrorMessage = "Street can only contain {0} characters")]
public string UsrStreet { get; set; }
[Required]
public int UsrNum { get; set; }
[Required]
public int UsrPostalCode { get; set; }
}
I want to connect them by having both as primary key the UsrID and I get an error that UsrDetails don't have a primary key because I'm using the foreign key attribute. Any ideas?
A: You need to declare a key property in UserDetails with the same name that you declare in the ForeignKey attribute:
public class UsrDetails
{
[Key]
public int UsrID{ get; set; }
[ForeignKey("UsrID")]
public virtual Usr Usr { get; set; }
}
All your entities must have a PK property. In this case where you are representing a one to one relationship, the PK of the dependent entity also is the FK. You can check this tutorial in case you need more info.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36578154",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: How to make a successful batch commit when some of the docs could've been deleted? Suppose i have a structure like this:
items: {
id1: {
likes: 123
},
id2: {
likes: 456
},
id3: {
sourceId: 'id1',
likes: 123
},
id4: {
sourceId: 'id1',
likes: 123
}
[,...]
}
where any item can either be a source item or an item that references a source item. The purpose of referencing the source item is to keep counters consistent across all items that share the same sourceId.
Therefore, when i change a counter on a source item, i want to batch write that counter's value to all the items that have that item as their sourceId.
My concern
Suppose I read in the docs referencing some sourceId, then i commit the changes in a batch to all of them. What if a very small subset of the docs in the batch were deleted in the small window of time since the documents were read in, or a rare but possible write-rate conflict occurs? Do none of the counters get updated because 1 or 2 documents failed to be updated?
Is it possible to submit a batch that writes the changes to each of its documents independently, such that if one fails, it has no impact on if the others get written?
Or maybe for this scenario it might be better to read in the documents referencing some sourceId and then write the changes to each document in parallel such that write independence is achieved. I don't like this approach since the number of requests would be the size of the batch.
What are your thoughts?
A: Take a careful read of the API docs for BatchWrite. It will answer your questions. Since you're not showing your batch code (are you using set? update?), we have to look at the API docs to assess the failure cases:
create()
This will fail the batch if a document exists at its location.
It sounds like you're probably not using create(), but this is the failure case.
set()
If the document does not exist yet, it will be created.
So, a set will not fail if the documented was deleted before the batch got committed.
update()
If the document doesn't yet exist, the update fails and the entire
batch will be rejected.
So, if you try to update a nonexistent document, the batch will fail.
If you want to decide what to do with each document, depending on its existence and contents, then control the failure cases, use a transaction.
A: If I understand your question, I had a similar scenario and here's how I did it. First, I use generated universal ID's, uid's, for all my item keys/id's. Then, what you do is on the grandchildren, simply write the uid of the parent it is associated with. Each grandchild could be associated with more than one parent.
As you create new items, you have to recursively update the parent with the uid of the item so the parent has record of all its associated child items.
fetchPromise = [];
fetchArray = [];
if(!selectIsEmpty("order-panel-one-series-select") || !selectIsUnselected(orderPanelOneSeriesSelect)){
orderPanelOneTitle.innerHTML = "Select " + orderPanelOneSeriesSelect.value.toString().toUpperCase() + " Option";
}
//on change we need to populate option select based on this value
//now we need to get the particular series doc and fill get array then prmise all to get all options
familyuid = getRecordFromList(doc.getElementById("order-panel-one-family-select"),orderPanelOneFamilySelect.selectedIndex);
seriesuid = getRecordFromList(doc.getElementById("order-panel-one-series-select"),orderPanelOneSeriesSelect.selectedIndex);
optionuid = getRecordFromList(doc.getElementById("order-panel-one-option-select"),orderPanelOneOptionsSelect.selectedIndex);
optionRef = db.collection("products").doc(familyuid).collection("option");
itemRef = db.collection("products").doc(familyuid).collection("item");
targetRef = db.collection("products").doc(familyuid).collection("option").doc(optionuid);
try {
targetRef.get().then(function(snap) {
if (snap.exists) {
for (var key in snap.data()) {
if (snap.data().hasOwnProperty(key)) {
fetchPromise = itemRef.doc(key).get();
fetchArray.push(fetchPromise);
}
}
Promise.all(fetchArray).then(function(values) {
populateSelectFromQueryValues(values,"order-panel-one-item-select");
if(!selectIsEmpty("order-panel-one-item-select")){
enableSelect("order-panel-one-item-select");
}
targetRef.get().then(function(snap){
if(snap.data().name){
var str = snap.data().name.toString();
orderAsideInfo.innerHTML = "Select " + capitalizeFirstLetter(str) + " item.";
}
});
});
}
}).catch(function(error) {
toast("error check console");
console.log("Error getting document:", error);
});
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/49332228",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Quartz CronTrigger expression between two dates Is there a way to write a Quartz CronTrigger expression that runs every day between two dates, for example starts at 11am 5th of Sep 2011 and ends at 11am 10th of June 2012?
A: Use an expression that means every day at 11:00am e.g. "0 0 11 * * ?".
Then set the startTime of the trigger to 5th of Sep 2011 10:59 am, and set the endTime of the trigger to 10th of June 2012 11:01 am.
A: Another solution I found is to specify a route policy (SimpleScheduledRoutePolicy) for the scheduled route and set the RouteStartDate and setRouteStopDate for this policy object.
A: A single cron expression doesn't facilitate running different schedules for the same period type, no matter which period is concerned, your differing schedule being the year period.
However other than your year difference all other periods have the same schedule. So... using these cron expressions:
cron1 = "0 0 23 5/1 SEP-DEC ? 2012"
cron2 = "0 0 23 1/1 JAN-JUN ? 2013"
you can switch the scheduler from using cron1 to cron2 sometime after 11:00.00 PM on 12/31/2012 but before 10:59.99 PM on 1/1/2013, though I wouldn't cut it so close as shown here. If you scheduler is reading its cron expression from the database or a configuration somewhere then just have it read in a new schedule every day at 11:30 PM. If you are storing your cron expressions in a database you could schedule to have a scheduler swap out the cron expression for your particular task using this chron3 below:
cron3 = "0 0 0 1 JAN ? 2013"
Silly me :o) today's date is Mar 13, 2013 so I'm sure this answer is a bit late for you!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7306613",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: C# Console not writing object string I'm trying to get the console to write a string that is part of a object, however the console leaves the string portion blank.
This is how i am getting the information:
Console.WriteLine("Please Enter an Agent Name: ");
agent1 = (Console.ReadLine());
Console.WriteLine("Please Enter " + agent1 + "'s Number of Customers: ");
ID1 = int.Parse(Console.ReadLine());
Then passing the variable agent 1 into a class i created:
Insurance Agent1 = new Insurance(agent1, ID1);
Then im tryting to tell the console to write out the agent's name and customer number:
Console.WriteLine("Agent 1 Name: "+ Agent1.Agent +" , Agent 1 Number of Customers: " + Agent1.Customers +".");
However, the console writes the customer number, which is an int, but not the string agent.
Please Enter an Agent Name: Test Please Enter Test's Number of
Customers: 12
Agent 1 Name: , Agent 1 Number of Customers: 12.
Any idea on how to get this to work?
EDIT:
This is the insurance class for reference:
class Insurance
{
private string _Agent; //String for _Agent because it will be a series of letters
private int _Customers; //Int for _Customers because it will be a whole number
public Insurance (string Agent, int Customers)
{
this.Agent = Agent;
this.Customers = Customers;
}
public string Agent
{
get { return _Agent; }
set { _Agent = Agent; }
}
public int Customers
{
get { return _Customers; }
set //Only set _Customers if the value is larger or equal to zero, if less than zero (negative) set to zero
{
if (value >= 0)
{
_Customers = value;
} else if (value < 0) {
_Customers = 0;
}
}
}
}
A: Your "set" accessor is setup incorrectly. It's setting the value of _Agent to Agent, which calls the "get" on the property itself. The "getter" for Agent returns the _Agent field which is null.
Use value instead:
public string Agent
{
get { return _Agent; }
set { _Agent = value; }
}
Also, if I may, here's a few other suggestions on trimming down that class. But take it with a grain of salt, especially if you're just learning.
class Insurance
{
private int customers;
public Insurance(string agent, int customers)
{
Agent = Agent;
Customers = Customers;
}
public string Agent { get; set; }
public int Customers
{
get { return customers; }
set { customers = Math.Max(value, 0); }
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/48740012",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: python Discord Bot how to send messages from one channel to another async def on_message(message):
if message.channel == (720020927668289588):
await Bot.get_channel(703707652710072515).send(f"{message.author.name}: {message}")
await Bot.process_commands(message)
I am trying to have the bot to when someone sends a msg in channel 1 it will send the message to channel 2
I When i type into channel 1 nothing happens and no msg is send to channel 2 and there is no errors in the console
I have got it sorted
A: message.channel returns a channel object, you're trying to get the id. You can replace message.channel with message.channel.id to get the channel id. Then the code will work.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/65864676",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: custom iOS PWA background color instead of splash screen I don't want to show any custom splash screen for every device. Instead I'd like to just change the default ios black background to my custom background color (e.g. #89CFF0) and show it on every device without long list of links <link rel="apple-touch-startup-image" media="screen and (device-width: 810px) and (device-height: 1080px) and (-webkit-device-pixel-ratio: 2) and (orientation: portrait)" href="/assets/splash_screens/10.2_iPad_portrait.png"> ....
How can I get it?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/73484345",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Why is my random number generator becoming an unused assignment when using it to input values for 2d array? I have been making a basic game of battleship and to get the CPU to choose ship locations on a 2d array I am making two random number generators to pick values from 1 to 8 on a separate method. For some reason, the random generators show up as unused and I don't know why. so far this is what I have. If anyone knows what I'm doing wrong please let me know.
//calls method
board3 = CPUship(board3);
//displays result of method
for (int i = 0; i < board3.length; i++) {
for (int j = 0; j < board3.length; j++) {
System.out.print(board3[i][j]);
}
System.out.println("");
}
public static String[][] CPUship(String[][] board3) {
int rowGenerate;
int colGenerate;
boolean valid2 = false;
for (int CPUships = 0; CPUships < 6; CPUships++) {
while (!valid2) {
rowGenerate = (int) (9 * Math.random() + 0);
colGenerate = (int) (9 * Math.random() + 0);
if (!board3[rowGenerate][colGenerate].equalsIgnoreCase("#")) {
board3[rowGenerate][colGenerate] = "#";
valid2 = true;
}
}
valid2 = false;
}
return board3;
}
A: Here should be a complete code
public static String[][] CPUship(String[][]board3){
int rowGenerate;
int colGenerate;
for (int CPUships = 0; CPUships < 6; CPUships++) {
boolean valid2=false;
while (!valid2){ //instead of valid = false "
rowGenerate = (int) ( 9* Math.random() + 0);
colGenerate = (int) ( 9* Math.random() + 0);
if (!board3[rowGenerate][colGenerate].equalsIgnoreCase ("#")){
board3[rowGenerate][colGenerate]="#";
valid2=true;
}
//removed the valid2=false, it does not "reset" automatically
//removed the CPUships++ ... already done by the for loop
}
}
return board3;
}
or use break instead of the valid boolean
public static String[][] CPUship(String[][]board3){
int rowGenerate;
int colGenerate;
for (int CPUships = 0; CPUships < 6; CPUships++) {
while (true){ //instead of valid = false "
rowGenerate = (int) ( 9* Math.random() + 0);
colGenerate = (int) ( 9* Math.random() + 0);
if (!board3[rowGenerate][colGenerate].equalsIgnoreCase ("#")){
board3[rowGenerate][colGenerate]="#";
break;
}
//removed the valid2=false, it does not "reset" automatically
//removed the CPUships++ ... already done by the for loop
}
}
return board3;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/64733000",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Can I use Environment.Username and MYSQL to verify log in? private void btnSubmitt_Click(object sender, RoutedEventArgs e)
{
try
{
i = 0;
MySqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Select * from users where TX_EMPLOYEE='"; (Environment.UserName) & "'";
DataTable dt = new DataTable();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dt);
i = Convert.ToInt32(dt.Rows.Count.ToString());
}
catch
{
MessageBox.Show("Database connection is not available at this time. Please contact your database administrator ");
}
finally
{
con.Close();
}
I would like to authenticate the user with their computer login name and the exact match that is listed in the MYSQL data table. However Environment.Username is not a valid syntax in this SQL statement.
A: This line is very very wrong:
cmd.CommandText = "Select * from users where TX_EMPLOYEE='"; (Environment.UserName) & "'";
It should be this:
cmd.CommandText = "Select * from users where TX_EMPLOYEE='" + Environment.UserName + "'";
Except, it shouldn't be like that because of SQL injection. If I could make Environment.UserName into ' or 1 = 1 or TX_EMPLOYEE = ' then your final query would become this:
Select * from users where TX_EMPLOYEE='' or 1 = 1 or TX_EMPLOYEE = ''
Which clearly isn't what you want - somebody with no credentials being able to access this. You should instead use SQL parameters:
cmd.CommandText = "Select * from users where TX_EMPLOYEE=?userName";
cmd.Parameters.AddWithValue("?userName", Environment.UserName);
On a separate note, I'm confused by this code:
i = Convert.ToInt32(dt.Rows.Count.ToString());
DataTable.Rows.Count is already an int, so you're converting a number to a string to a number. Why?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60962077",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: SQL Sum with non unique date I'm trying to write a SQL query that will sum total production from the following two example tables:
Table: CaseLots
DateProduced kgProduced
October 1, 2013 10000
October 1, 2013 10000
October 2, 2013 10000
Table: Budget
OperatingDate BudgetHours
October 1, 2013 24
October 2, 2013 24
I would like to output a table as follows:
TotalProduction TotalBudgetHours
30000 48
Here is what I have for code so far:
SELECT
Sum(kgProduced) AS TotalProduction, Sum(BudgetHours) AS TotalBudgetHours
FROM
dbo.CaseLots INNER JOIN dbo.Budget ON dbo.CaseLots.DateProduced = dbo.Budget.OperatingDate
WHERE
dbo.Budget.OperatingDate BETWEEN '2013-10-01' AND '2013-10-02'
It seems that the query is double summing the budget hour in instances where more than one case lot is produced in a day. The table I'm getting is as follows:
Total Production BudgetHours
30000 72
How do I fix this?
A: Think about what the INNER JOIN is doing.
For every row in CaseLot, its finding any row in Budget that has a matching date.
If you were to remove your aggregation statements in SQL, and just show the inner join, you would see the following result set:
DateProduced kgProduced OperatingDate BudgetHours
October 1, 2013 10000 October 1, 2013 24
October 1, 2013 10000 October 1, 2013 24
October 2, 2013 10000 October 2, 2013 24
(dammit StackOverflow, why don't you have Markdown for tables :( )
Running your aggregation on top of that it is easy to see how you get the 72 hours in your result.
The correct query needs to aggregate the CaseLots table first, then join onto the Budget table.
SELECT DateProduced, TotalKgProduced, SUM(BudgetHours) AS TotalBudgetHours
FROM
(
SELECT DateProduced, SUM(kgProduced) AS TotalKgProduced
FROM CaseLots
GROUP BY DateProduced
) AS TotalKgProducedByDay
INNER JOIN
Budget
ON TotalKgProducedByDay.DateProduced = Budget.OperatingDate
WHERE DateProduced BETWEEN '1 Oct 2013' AND '2 Oct 2013'
GROUP BY DateProduced
A: The problem is in the INNER JOIN produces a 3 row table since the keys match on all. So there is three '24's with a sum of 72.
To fix this, it would probably be easier to split this into two queries.
SELECT Sum(kgProduced) AS TotalProduction
FROM dbo.CaseLots
WHERE dbo.CaseLots.OperatingDate BETWEEN '2013-10-01' AND '2013-10-02'
LEFT JOIN
SELECT Sum(BudgetHours) AS TotalBudgetHours
FROM dbo.Budget
WHERE dbo.Budget.OperatingDate BETWEEN '2013-10-01' AND '2013-10-02'
A: This could be easily achieved by this:
SELECT
(SELECT SUM(kgProduced) FROM dbo.CaseLots WHERE DateProduced BETWEEN '2013-10-01' AND '2013-10-02') AS TotalProduction,
(SELECT SUM(BudgetHours) FROM dbo.Budget WHERE OperatingDate BETWEEN '2013-10-01' AND '2013-10-02') AS TotalBudgetHours
There's no need for joining the two tables.
A: Try this:
select DateProduced,TotalProduction,TotalBudgetHours from
(select DateProduced,sum(kgProduced) as TotalProduction
from CaseLots group by DateProduced) p
join
(select OperatingDate,sum(BudgetHours) as TotalBudgetHours
from Budget group by OperatingDate) b
on (p.DateProduced=b.OperatingDate)
where p.DateProduced between '2013-10-01' AND '2013-10-02'
A: The other answers are simpler for this particular case. However if you needed to SUM 10 different values on the CaseLots table, you'd need 10 different subqueries. The following is a general, more scaleable solution:
SELECT
SUM(DayKgProduced) AS TotalProduction,
SUM(BudgetHours) AS TotalBudgetHours
FROM (
SELECT
DateProduced,
SUM(kgProduced) AS DayKgProduced,
FROM dbo.CaseLots
WHERE DateProduced BETWEEN '2013-10-01' AND '2013-10-02'
GROUP BY DateProduced
) DailyTotals
INNER JOIN dbo.Budget b ON DailyTotals.DateProduced = b.OperatingDate
First you SUM the production of each CaseLot without having to SUM the BudgetHours. If you used a SELECT * FROM in the query above you'd see:
Date DayKgProduced BudgetHours
2013-10-01 20000 24
2013-10-02 10000 24
But you want the overall total, so we SUM those daily values, correctly producing:
TotalProduction TotalBudgetHours
30000 48
| {
"language": "en",
"url": "https://stackoverflow.com/questions/20182559",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: ngx-translate if a key is missing in one of the json file replace with other json file same key I have a scenario, I have two languages files en.json & es.json I have a key in en.json file which is missed in es.json file, however, I want to replace this missing key with the en.json key how would I achieve this.
I know the way we use MissingTranslationHandler for missing keys, but I do not want to show a default text for missing keys, Although I'm doing this for a missed key from both files, in my scenario its different.
Any help would be greatly appreciated, thanks in advance!
A: Inside your app module constructor, you can tell what is the default language which you're interested in
export class AppModule {
constructor(translate: TranslateService) {
translate.setDefaultLang('en');
translate.use('en');
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/62444282",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Transfer data from aprs server to symfony database I would like to connect symfony to an "aprs-is" server.
My data are received by the "aprs" server and i would like to insert them in the database i have created in the doctrine of symfony. My entities are ready but i can't figure out how to do that.
I can make an up-link on "aprs" server to redirect the data but i don't know how to architect all that link on both side.
Here is the link of aprs-is server archi: http://he.fi/aprsc/
The informations about the aprs uplink:
$ sudo netstat -anp|grep aprsc
tcp 0 0 192.168.5.56:50002 0.0.0.0:* LISTEN 21864/aprsc
tcp 0 0 127.0.0.1:10151 0.0.0.0:* LISTEN 21864/aprsc
tcp 0 0 127.0.0.1:10151 127.0.0.1:46962 ESTABLISHED 21864/aprsc
tcp 0 0 192.168.5.56:50002 192.168.5.54:34070 ESTABLISHED 21864/aprsc
tcp6 0 0 :::50002 :::* LISTEN 21864/aprsc
unix 3 [ ] STREAM CONNECTE 865809 21864/aprsc
unix 3 [ ] STREAM CONNECTE 864810 21864/aprsc
unix 3 [ ] STREAM CONNECTE 864811 21864/aprsc
The information about apache listener
$ sudo netstat -anp|grep apache2
tcp6 0 0 :::10150 :::* LISTEN 21582/apache2
The log connection on aprs:
2018/07/31 14:32:49.091674 aprsc[21864:7f5c008b1700] INFO: HTTP thread ready.
2018/07/31 14:32:49.091682 aprsc[21864:7f5bfd55f700] INFO: Uplink: 1 uplinks configured, 0 are connected, need to pick new
2018/07/31 14:32:49.091688 aprsc[21864:7f5bfd55f700] DEBUG: Uplink: trying Http (127.0.0.1:10150)
2018/07/31 14:32:49.091755 aprsc[21864:7f5bfd55f700] INFO: Uplink Http: Connecting to 127.0.0.1:10150 (127.0.0.1:10150) [link 0, addr 1/1]
2018/07/31 14:32:49.091832 aprsc[21864:7f5bfd55f700] DEBUG: Uplink Http: poll after connect returned 1, revents 4
2018/07/31 14:32:49.091840 aprsc[21864:7f5bfd55f700] DEBUG: Uplink Http: successful connect
2018/07/31 14:32:49.091858 aprsc[21864:7f5bfd55f700] INFO: Uplink Http: 127.0.0.1:10150: Connection established on fd 13 using source address 127.0.0.1:58630
2018/07/31 14:32:49.091865 aprsc[21864:7f5bfd55f700] DEBUG: pass_client_to_worker: client on fd 13 to thread 0 with 0 users
2018/07/31 14:32:49.091870 aprsc[21864:7f5bfd55f700] INFO: status: setting error flag no_uplink ttl 3600
2018/07/31 14:32:49.121688 aprsc[21864:7f5c00890700] DEBUG: collect_new_clients(worker 0): closing all existing peergroup peers
2018/07/31 14:32:49.121776 aprsc[21864:7f5c00890700] DEBUG: collect_new_clients(worker 0): added fd 13 to polling list, xfd 0x7f5c00a02000
2018/07/31 14:32:49.121795 aprsc[21864:7f5c00890700] DEBUG: Worker 0 accepted 1 new clients, 1 new connections, now total 1 clients
2018/07/31 14:32:50.989005 aprsc[21864:7f5c00890700] INFO: 127.0.0.1:10150: Uplink server software: HTTP/1.1 400 Bad Request
2018/07/31 14:32:50.989070 aprsc[21864:7f5c00890700] ERROR: 127.0.0.1:10150: Uplink's welcome message is not recognized: no # in beginning
2018/07/31 14:32:50.989098 aprsc[21864:7f5c00890700] INFO: Uplink TCP 127.0.0.1:10150 (Http) closed after 2 s: Uplink server protocol error, tx/rx 70/483 bytes 0/0 pkts, dropped 0, fd 13, worker 0
2018/07/31 14:32:50.989228 aprsc[21864:7f5c00890700] INFO: 127.0.0.1:10150: Uplink [0] has been closed: Uplink server protocol error
2018/07/31 14:32:50.989255 aprsc[21864:7f5c00890700] DEBUG: found the link to disconnect
2018/07/31 14:32:53.096709 aprsc[21864:7f5bfd55f700] INFO: Uplink: 1 uplinks configured, 0 are connected, need to pick new
2018/07/31 14:32:53.096795 aprsc[21864:7f5bfd55f700] DEBUG: Uplink: trying Http (127.0.0.1:10150)
2018/07/31 14:32:53.096970 aprsc[21864:7f5bfd55f700] INFO: Uplink Http: Connecting to 127.0.0.1:10150 (127.0.0.1:10150) [link 0, addr 1/1]
2018/07/31 14:32:53.097139 aprsc[21864:7f5bfd55f700] DEBUG: Uplink Http: poll after connect returned 1, revents 4
2018/07/31 14:32:53.097177 aprsc[21864:7f5bfd55f700] DEBUG: Uplink Http: successful connect
2018/07/31 14:32:53.097275 aprsc[21864:7f5bfd55f700] INFO: Uplink Http: 127.0.0.1:10150: Connection established on fd 13 using source address 127.0.0.1:58632
2018/07/31 14:32:53.097305 aprsc[21864:7f5bfd55f700] DEBUG: pass_client_to_worker: client on fd 13 to thread 0 with 0 users
2018/07/31 14:32:53.097324 aprsc[21864:7f5bfd55f700] INFO: status: setting error flag no_uplink ttl 3600
2018/07/31 14:32:53.126840 aprsc[21864:7f5c00890700] DEBUG: collect_new_clients(worker 0): added fd 13 to polling list, xfd 0x7f5c00a02030
2018/07/31 14:32:53.126950 aprsc[21864:7f5c00890700] DEBUG: Worker 0 accepted 1 new clients, 1 new connections, now total 1 clients
2018/07/31 14:32:53.663743 aprsc[21864:7f5c008b1700] DEBUG: http status [127.0.0.1] request /status.json
2018/07/31 14:32:53.664754 aprsc[21864:7f5c008b1700] DEBUG: http_compress_gzip: compressed 7656 bytes to 1743 bytes: 22.8 %
2018/07/31 14:32:54.994428 aprsc[21864:7f5c00890700] INFO: 127.0.0.1:10150: Uplink server software: HTTP/1.1 400 Bad Request
$ sudo service aprsc status
● aprsc.service - LSB: start and stop aprsc
Loaded: loaded (/etc/init.d/aprsc; generated; vendor preset: enabled)
Active: active (running) since Tue 2018-07-31 16:32:48 CEST; 20min ago
Docs: man:systemd-sysv-generator(8)
Process: 21831 ExecStop=/etc/init.d/aprsc stop (code=exited, status=0/SUCCESS)
Process: 21844 ExecStart=/etc/init.d/aprsc start (code=exited, status=0/SUCCESS)
Tasks: 8 (limit: 4915)
CGroup: /system.slice/aprsc.service
└─21864 /opt/aprsc/sbin/aprsc -u aprsc -t /opt/aprsc -f test -e debug -o file -r logs -c /etc/aprsc.conf
systemd[1]: Starting LSB: start and stop aprsc...
aprsc[21844]: * Preparing chroot for APRS-IS server: aprsc chroot
aprsc[21844]: ...done.
aprsc[21844]: * Checking configuration 'aprsc'
aprsc[21844]: * Starting APRS-IS server: aprsc
aprsc[21844]: * Starting 'aprsc'
aprsc[21844]: ...done.
systemd[1]: Started LSB: start and stop aprsc.
A: I have progressed a little on that subject:
What's happening is the format sent from apache to aprs-is as response is badly interpreted by aprs. The apache server send a response with a header configured in apache2.conf:
ServerTokens will return HTTP/1.1 with the version of apache after that ( the verbose depending on the option next to Servertoken )
But i can't figure out how change the value "HTTP/1.1" by "#APRS"
I've tried to change it in mod_header.c but the only file i have found is mod_header.so ...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/51608363",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Unfortunately, AndroidFirst has stopped I am a beginner in android application & just started building first "HelloWorld" app. i followed official tutorial and designed emulator. But when i run it, the emulator says "Unfortunately, AndroidFirst has stopped". I looked around on SO but different solutions didn't help. I am a very beginner for Android, hence can't find the bug or something like wrong/error.
following is logCat:
08-29 05:16:58.629: W/dalvikvm(1934): VFY: unable to resolve static field 1864 (ActionBarWindow) in Landroid/support/v7/appcompat/R$styleable;
08-29 05:16:58.629: D/dalvikvm(1934): VFY: replacing opcode 0x62 at 0x0004
08-29 05:16:58.649: D/AndroidRuntime(1934): Shutting down VM
08-29 05:16:58.649: W/dalvikvm(1934): threadid=1: thread exiting with uncaught exception (group=0xb1daece8)
08-29 05:16:58.669: E/AndroidRuntime(1934): FATAL EXCEPTION: main
08-29 05:16:58.669: E/AndroidRuntime(1934): Process: com.example.androidfirst, PID: 1934
08-29 05:16:58.669: E/AndroidRuntime(1934): java.lang.NoClassDefFoundError: android.support.v7.appcompat.R$styleable
08-29 05:16:58.669: E/AndroidRuntime(1934): at android.support.v7.app.ActionBarActivityDelegate.onCreate(ActionBarActivityDelegate.java:106)
08-29 05:16:58.669: E/AndroidRuntime(1934): at android.support.v7.app.ActionBarActivityDelegateICS.onCreate(ActionBarActivityDelegateICS.java:57)
08-29 05:16:58.669: E/AndroidRuntime(1934): at android.support.v7.app.ActionBarActivity.onCreate(ActionBarActivity.java:99)
08-29 05:16:58.669: E/AndroidRuntime(1934): at com.example.androidfirst.MainActivity.onCreate(MainActivity.java:13)
08-29 05:16:58.669: E/AndroidRuntime(1934): at android.app.Activity.performCreate(Activity.java:5242)
08-29 05:16:58.669: E/AndroidRuntime(1934): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
08-29 05:16:58.669: E/AndroidRuntime(1934): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2161)
08-29 05:16:58.669: E/AndroidRuntime(1934): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2258)
08-29 05:16:58.669: E/AndroidRuntime(1934): at android.app.ActivityThread.access$800(ActivityThread.java:138)
08-29 05:16:58.669: E/AndroidRuntime(1934): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1209)
08-29 05:16:58.669: E/AndroidRuntime(1934): at android.os.Handler.dispatchMessage(Handler.java:102)
08-29 05:16:58.669: E/AndroidRuntime(1934): at android.os.Looper.loop(Looper.java:136)
08-29 05:16:58.669: E/AndroidRuntime(1934): at android.app.ActivityThread.main(ActivityThread.java:5026)
08-29 05:16:58.669: E/AndroidRuntime(1934): at java.lang.reflect.Method.invokeNative(Native Method)
08-29 05:16:58.669: E/AndroidRuntime(1934): at java.lang.reflect.Method.invoke(Method.java:515)
08-29 05:16:58.669: E/AndroidRuntime(1934): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:777)
08-29 05:16:58.669: E/AndroidRuntime(1934): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:602)
08-29 05:16:58.669: E/AndroidRuntime(1934): at dalvik.system.NativeStart.main(Native Method)
08-29 05:21:58.843: I/Process(1934): Sending signal. PID: 1934 SIG: 9
MainActivity.java Code:
package com.example.androidfirst;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.androidfirst"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="21" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
I would be very thankful to you people!
A: For that Android Support library is required
See this image:
Then just import the v7 compact library project into your work space and add it as a library to your project
you can find it in sdk\extras\android\support\v7\appcompat where your SDK is present in directory.
After importing, select your project right click ->Properties-> Android->Add->Select app compact
click ok.
A: The problem resolve when i downloaded API-19 & re-created the AVD. On a very first attempt, the AVD shows "Hello World" the default text on emulator.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/25562413",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: reset infinite scroll with ajax content I am using the ajax infinite scroll with a comment system. It works fine until a user posts a new comment - this breaks the infinite scroll, the 'load more items' link is still there but nothing happens when you click it.
I have seen this question: Reset / disable infinite scroll after AJAX call
I have tried to implement the destroy and bind into my success method but the loadmoreitems link is unreponsive. How can I reset the infinite scroll after a user posts a comment with the code below?
ajax:
<script>
$(document).ready(function(){
$('#commentform').on('submit',function(e) {
$.ajax({
url:'ajaxrequest.php',
data:$(this).serialize(),
type:'POST',
dataType: 'HTML',
success:function(data, response){
ias.destroy();
$("#posts").fadeOut(300);
$('#posts').html(data)
$("#posts").fadeIn(500);
$('html, body').animate({ scrollTop: $('#posts').offset().top - 100 }, 'fast');
ias.bind();
jQuery.ias({
container: "#posts",
item: ".post",
pagination: "#pagination",
next: ".next a"
});
},
error:function(data){
$("#error").show().fadeOut(5000);
}
});
e.preventDefault();
return false;
});
});
</script>
A: When you initialize the scroll on load make sure you have stored it in a variable called ias. Something like this
var ias = jQuery.ias({
container: "#posts",
item: ".post",
pagination: "#pagination",
next: ".next a"
});
And in success method call just the ias.destroy(); and ias.bind(); methods as you have done before.
Remove the initialization that is done again in your code i.e
jQuery.ias({
container: "#posts",
item: ".post",
pagination: "#pagination",
next: ".next a"
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/27079154",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: React stop other events on that element I have a volume element that shows the volume bar when the user hovers over it. This all works great in desktop. However to get the same functionality on mobile, the user has clicks on the volume element which also toggles the mute click event.
I am wanting to stop that mute event when the user clicks (i.e taps) on that element on mobile.
I don't want to modify the Mute or VolumeBar classes to fix this because these are generic classes in my library that the developer uses.
https://jsfiddle.net/jwm6k66c/2145/
*
*Actual: The mute click event gets fired and the volume bar opens.
*Expected: The mute click event doesn't gets fired and the volume bar opens.
Open the console -> go into mobile view (CTRL + SHIFT + M on chrome) -> click the volume button and observe the console logs.
What I have tried:
Using volumeControlOnClick to stop propogation when the volume bar's height is 0 (i.e not visible), this does not cancel the onClick though.
What I want:
To cancel the mute click event if the user clicks on the volume icon for the first time in mobile. Instead it should only show the volume bar.
const volumeControlOnClick = (e) => {
const volumeBarContainer =
e.currentTarget.nextElementSibling.querySelector('.jp-volume-bar-container');
/* Stop propogation is for mobiles to stop
triggering mute when showing volume bar */
if (volumeBarContainer.clientHeight === 0) {
e.stopPropagation();
console.log("stop propogation")
}
};
class Volume extends React.Component {
constructor(props) {
super(props);
this.state = {};
}
render() {
return (
<div className="jp-volume-container">
<Mute onTouchStart={volumeControlOnClick}><i className="fa fa-volume-up" /></Mute>
<div className="jp-volume-controls">
<div className="jp-volume-bar-container">
<VolumeBar />
</div>
</div>
</div>
);
}
};
class Mute extends React.Component {
render() {
return (
<button className="jp-mute" onClick={() => console.log("mute toggled")} onTouchStart={this.props.onTouchStart}>
{this.props.children}
</button>
);
}
};
class VolumeBar extends React.Component {
render() {
return (
<div className="jp-volume-bar" onClick={() => console.log("bar moved")}>
{this.props.children}
</div>
);
}
};
React.render(<Volume />, document.getElementById('container'));
A: Here's what I ended up with. It works because onTouchStart is always calld before onClick if it's a touch event and if not's then the custom logic gets called anyway. It also fires before the hover has happened. This preserves the :hover event. e.preventDefault() did not.
let isVolumeBarVisible;
const onTouchStartMute = e => (
isVolumeBarVisible = e.currentTarget.nextElementSibling
.querySelector('.jp-volume-bar-container').clientHeight > 0
);
const onClickMute = () => () => {
if (isVolumeBarVisible !== false) {
// Do custom mute logic
}
isVolumeBarVisible = undefined;
};
<Mute
aria-haspopup onTouchStart={onTouchStartMute}
onClick={onClickMute}
>
<i className="fa">{/* Icon set in css*/}</i>
</Mute>
A: What you can do is use a flag to indicate you were in a touch event before being in your mouse event, as long as you are using bubble phase. So attach a listener to your container element like this:
let isTouch = false;
const handleContainerClick = () => isTouch = false;
const handleMuteClick = () => {
if (isTouch == false) {
console.log("mute toggled");
}
};
const volumeControlOnClick = () => {
isTouch = true;
};
class Volume extends React.Component {
constructor(props) {
super(props);
this.state = {};
}
render() {
return (
<div className="jp-volume-container" onClick={handleContainerClick}>
<Mute onTouchStart={volumeControlOnClick} onClick={handleMuteClick}><i className="fa fa-volume-up" /></Mute>
<div className="jp-volume-controls">
<div className="jp-volume-bar-container">
<VolumeBar />
</div>
</div>
</div>
);
}
};
class Mute extends React.Component {
render() {
return (
<button className="jp-mute" onTouchStart={this.props.onTouchStart} onClick={this.props.onClick}>
{this.props.children}
</button>
);
}
};
class VolumeBar extends React.Component {
render() {
return (
<div className="jp-volume-bar" onClick={() => console.log("bar moved")}>
{this.props.children}
</div>
);
}
};
render(<Volume />, document.getElementById('container'));
If you are not using bubble phase so you can register a timeout of 100ms with the same logic above, where after 100ms you make your flag variable false again. Just add to your touchStart handler:
setTimeout(() => {isTouch = false}, 100);
EDIT: Even though touch events are supposed to be passive by default in Chrome 56, you call preventDefault() from a touchEnd event to prevent the click handler from firing. So, if you can't modify the click handler of your Mute class in any way, but you can add a touchEnd event, than you could do:
const handleTouchEnd = (e) => e.preventDefault();
const volumeControlOnClick = () => console.log("volumeControlOnClick");
class Volume extends React.Component {
constructor(props) {
super(props);
this.state = {};
}
render() {
return (
<div className="jp-volume-container">
<Mute onTouchStart={volumeControlOnClick} onTouchEnd={handleTouchEnd}><i className="fa fa-volume-up" /></Mute>
<div className="jp-volume-controls">
<div className="jp-volume-bar-container">
<VolumeBar />
</div>
</div>
</div>
);
}
};
class Mute extends React.Component {
render() {
return (
<button className="jp-mute" onTouchStart={this.props.onTouchStart} onTouchEnd={this.props.onTouchEnd} onClick={() => console.log("mute toggled")}>
{this.props.children}
</button>
);
}
};
class VolumeBar extends React.Component {
render() {
return (
<div className="jp-volume-bar" onClick={() => console.log("bar moved")}>
{this.props.children}
</div>
);
}
};
render(<Volume />, document.getElementById('container'));
A: Try this
render() {
return (
<div className="jp-volume-container" onClick={handleContainerClick}>
<Mute onTouchStart={volumeControlOnClick} onClick={handleMuteClick}><i className="fa fa-volume-up" /></Mute>
<div className="jp-volume-controls">
<div className="jp-volume-bar-container">
<VolumeBar />
</div>
</div>
</div>
);
}
};
class Mute extends React.Component {
render() {
return (
<button className="jp-mute" onTouchStart={this.props.onTouchStart} onClick={this.props.onClick}>
{this.props.children}
</button>
);
}
};
class VolumeBar extends React.Component {
render() {
return (
<div className="jp-volume-bar" onClick={() => console.log("bar moved")}>
{this.props.children}
</div>
);
}
};
render(<Volume />, document.getElementById('container'));
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42302200",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Remove the Duplicate value item from 2 same format JSON objects in Java I'm looking for a way to remove the duplicate item from two JSON objects that both have the same value.
e.g.
First object:
{
"a":true,
"b":true,
"c":true,
"d":{"i":true,"ii":true,"iii":true}
}
Second object
{
"a":false,
"b":true,
"c":true,
"d":{"i":true,"ii":true,"iii":false}
}
And after removing the duplicate, I'd like to get
First object
{
"a":true,
"d":{"iii":true}
}
Second object
{
"a":false,
"d":{"iii":false}
}
I wonder if there's a tool already provides this function
(If that couldn't detect the duplicates inside the nested value, it's ok.)
A: Found way myself, I convert the json to map and then compare to remove the duplicates. Then convert the reduced map back to json
| {
"language": "en",
"url": "https://stackoverflow.com/questions/70283709",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Use rvest to extract html table I am a new learner for R, I am interested in using rvest to extract html table and submit html forms.
Now, I want to get some useful information from a Chinese Website. The url is:
http://caipiao.163.com/award/cqssc/20160513.html
I am using Windows 10 Professional with RStudio Version 0.99.896, I use Google Chrome as the web browser with XPATH helper addon.
I want to extract the main html table from the Chinese site, it contains 120 groups of information about the lottery winning number. The first one (001) is: 98446 and the last one (120) is: 01798; I want to extract only the numbers (001) to (120) and the winning numbers: 98446 to 01798.
I used XPATH helper and Chrome web development to get the XPATH.
I think the XPATH for the information I want is:
//html/body/article[@class='docBody clearfix']/section[@id='mainArea']/div[@class='lottery-results']/table[@class='awardList']/*[@id="mainArea"]/div[1]/table/tbody/tr[2]/td[1]
But when I run the following code in RStudio, I can not get the result I want.
The following is my code:
> library(rvest)
Loading required package: xml2
> url <- "http://caipiao.163.com/award/cqssc/20160513.html"
> xp <- "//html/body/article[@class='docBody clearfix']/section [@id='mainArea']/div[@class='lottery-results']/table[@class='awardList']/*[@id='mainArea']/div[1]/table/tbody/tr[2]/td[1]"
>
> x <- read_html(url)
> y <- x %>% html_nodes(xpath=xp)
> y
{xml_nodeset (0)}
>
Please take a look at my code and let me know if I made any mistakes. You can simply ignore those unknown Chinese characters, they are not important, I just want to get the numbers.
Thanks!
John
A: It's not necessary to use such a precise target selector since there's only one table element (as the other answerer also pointed out). But you don't need to leave rvest behind:
library(rvest)
URL <- "http://caipiao.163.com/award/cqssc/20160513.html"
pg <- read_html(URL)
tab <- html_table(pg, fill=TRUE)[[1]]
str(tab)
## 'data.frame': 40 obs. of 39 variables:
## $ 期号 : int 1 2 3 4 5 6 7 8 9 10 ...
## $ 开奖号码: chr "9 8 4 4 6" "1 8 3 1 6" "2 9 3 5 6" "1 4 5 8 0" ...
## ....
(SO is interpreting some of the unicode glyphs as spam so I had to remove the other columns).
The second column gets compressed via post-page-load javascript actions, so you'll need to clean that up a bit if that's the one you're going for.
A: I would use the function readHTMLTable from package XML to get the whole table, as in your website there is only one <table> element:
install.packages("XML)
library(XML)
url <- "http://caipiao.163.com/award/cqssc/20160513.html"
lotteryResults <- as.data.frame(readHTMLTable(url))
Then you can just do some cleansing procedures, subsetting and using rbind to get a data.frame with 2 columns and 120 observations.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37240448",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Using AWS Cloudfront, should I use apache gzip module to compress files or Cloudfront itself? I'm trying to get cloudfront straight on my site.
I want to know if I should you apache module to enable gzip on my site or set Cloudfront to compress the cached files?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39597533",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Looking for pure Java 3D library I have a very simple scenario: given are bare 3d points and I need to connect all these points and draw a surface. And for this case I need a very basic and really pure Java library without any dependencies.
Do you know such a library?
A: Do you know (or test) Java 3D API ?
Useful link : Java 3D API or Java net link
There is also another library : jmathplot (to draw diagram or others) --> it's easier than java 3d API.
It's two diferent philosophy. With the first you have to "draw point by point", with the second (jmathplot) you can use predefined elements and mathematical functions.
A: I think Java Surface Plot might be what you're looking for.
http://javasurfaceplot.sourceforge.net/
A: In order to communicate with the hardware just about any Java 3d library is going to have some dependencies.
You might try this:
http://www.mediafire.com/download/8ui3uwduw17bnx9/OpenGL.rar
There is a video tutorial set available for it. Just drawing a surface shouldn't be a problem.
http://www.youtube.com/watch?v=V1EvbHFtjCE
If you really want to get into Java 3D I would just search around for as much info on the various competing libraries and pick one for what you want to do with it.
edit:
The surface library fron other answer looks promising. I also found https://jogamp.org/jogl/www/ the JOGL or The Java API for OpenGL.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/18382300",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: contains function for int in flutter what is the best way to figure out what number the integer contains
for example:
i have a int that is 96 and i want to see if it has 9 return something and if it has not return something else
A: // this will return true if your int contains the pattern
bool intContains(myInt,pattern){
return myInt.toString().contains(pattern.toString());
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/64129058",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: WPF - XAML - Call an animation in a nested style from the parent style I'm trying to modify an ItemsControl to have a watermark to indicate the behavior of content dropped into it.
I'm using a Label inside a VisualBrush to show the word "OR" as the background to the ItemsControl (The control will contain property filters which will be Or'd together). The change in background is triggered by IsMouseOver on the ItemsControl.
The problem is this: I can get my VisualBrush (see xaml) to appear/disappear if I set the opacity directly in the Label but I cannot get the Opacity to animate if I try to use the nested style for the label. I have tried several approaches without success and so any pointers as to my mistake would be gratefully received.
I have included (one commented out) both animations I have tried. I also tried setting the Foreground on the Label with a ColorAnimation without success.
Many thanks
Ian Carson
<ItemsControl x:Name="OrFilterItemsTarget"
ItemsSource="{Binding Assets.OrFilters}"
ItemTemplateSelector="{StaticResource FilterTargetTemplateSelector}"
ItemContainerStyle="{StaticResource DraggableItemStyle}"
BorderThickness="0,0,0,0.5"
BorderBrush="DimGray"
AllowDrop="True"
IsHitTestVisible="True"
Margin="0,2.95,15.934,77"
HorizontalAlignment="Right"
Width="105">
<ItemsControl.Style>
<Style TargetType="{x:Type ItemsControl}">
<Style.Resources>
<Style x:Key="LabelStyle"
TargetType="{x:Type Label}">
<Style.Resources>
<Storyboard x:Key="FadeUp">
<DoubleAnimationUsingKeyFrames BeginTime="00:00:00"
Storyboard.TargetProperty="Opacity"
FillBehavior="HoldEnd">
<SplineDoubleKeyFrame KeyTime="00:00:2"
Value="0.5" />
</DoubleAnimationUsingKeyFrames>
<!--<DoubleAnimation Storyboard.TargetProperty="Opacity"
From="0" To="0.5"
Duration="0:0:2" />-->
</Storyboard>
<Storyboard x:Key="FadeDown">
<DoubleAnimationUsingKeyFrames BeginTime="00:00:00"
Storyboard.TargetProperty="Opacity"
FillBehavior="Stop">
<SplineDoubleKeyFrame KeyTime="00:00:2"
Value="0" />
</DoubleAnimationUsingKeyFrames>
<!--<DoubleAnimation Storyboard.TargetProperty="Opacity"
From="0.5" To="0"
Duration="0:0:2" />-->
</Storyboard>
</Style.Resources>
<Style.Triggers>
<DataTrigger Binding="{Binding Path=IsMouseOver, ElementName=OrFilterItemsTarget}"
Value="True">
<DataTrigger.EnterActions>
<BeginStoryboard Storyboard="{StaticResource FadeUp}" />
</DataTrigger.EnterActions>
</DataTrigger>
<DataTrigger Binding="{Binding Path=IsMouseOver, ElementName=OrFilterItemsTarget}"
Value="False">
<DataTrigger.EnterActions>
<BeginStoryboard Storyboard="{StaticResource FadeDown}" />
</DataTrigger.EnterActions>
</DataTrigger>
</Style.Triggers>
</Style>
<VisualBrush x:Key="FilterContentType"
AlignmentX="Center"
AlignmentY="Center"
Stretch="None">
<VisualBrush.Visual>
<Label Content="OR"
Foreground="DarkGray"
Style="{StaticResource LabelStyle}">
</Label>
</VisualBrush.Visual>
</VisualBrush>
</Style.Resources>
<Style.Triggers>
<Trigger Property="IsMouseOver"
Value="True">
<Setter Property="Background"
Value="{StaticResource FilterContentType}" />
</Trigger>
<Trigger Property="IsMouseOver"
Value="False">
<Setter Property="Background"
Value="Transparent" />
</Trigger>
</Style.Triggers>
</Style>
</ItemsControl.Style>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel Orientation="Horizontal"
Background="Transparent">
<i:Interaction.Behaviors>
<ei:FluidMoveBehavior AppliesTo="Children"
Duration="0:0:0.3">
<ei:FluidMoveBehavior.EaseY>
<BackEase EasingMode="EaseIn"
Amplitude="0.1" />
</ei:FluidMoveBehavior.EaseY>
</ei:FluidMoveBehavior>
</i:Interaction.Behaviors>
</WrapPanel>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
A: In the end I realized I was over-thinking the problem. Nested styles were unnecessary. The solution was to set the background as the VisualBrush (with its content set up as the desired final appearance) inside its own tag within the ItemsControl and then animate the opacity of the VisualBrush using EventTriggers directly on the ItemsControl. Note the various events to manage both mouse and dragging user activity.
Thanks to anyone who was thinking about this problem. The final XAML looks like this and hopefully will be useful to someone.
<ItemsControl x:Name="OrFilterItemsTarget"
ItemsSource="{Binding Assets.OrFilters}"
ItemTemplateSelector="{StaticResource FilterTargetTemplateSelector}"
ItemContainerStyle="{StaticResource DraggableItemStyle}"
BorderThickness="0,0,0,0.5"
BorderBrush="DimGray"
AllowDrop="True"
IsHitTestVisible="True"
Margin="0,2.95,15.934,77"
HorizontalAlignment="Right"
Width="105">
<ItemsControl.Background>
<VisualBrush x:Name="OrFilterContentType"
AlignmentX="Center"
AlignmentY="Center"
Stretch="None"
Opacity="0">
<VisualBrush.Visual>
<Label Content="OR"
Foreground="DarkGray"
Opacity="0.5" />
</VisualBrush.Visual>
</VisualBrush>
</ItemsControl.Background>
<ItemsControl.Triggers>
<EventTrigger RoutedEvent="ItemsControl.MouseEnter">
<EventTrigger.Actions>
<BeginStoryboard>
<Storyboard>
<DoubleAnimation Storyboard.TargetName="OrFilterContentType"
Storyboard.TargetProperty="(Brush.Opacity)"
From="0" To="1"
Duration="0:0:0.7" />
</Storyboard>
</BeginStoryboard>
</EventTrigger.Actions>
</EventTrigger>
<EventTrigger RoutedEvent="ItemsControl.DragEnter">
<EventTrigger.Actions>
<BeginStoryboard>
<Storyboard>
<DoubleAnimation Storyboard.TargetName="OrFilterContentType"
Storyboard.TargetProperty="(Brush.Opacity)"
From="0"
To="1"
Duration="0:0:0.7" />
</Storyboard>
</BeginStoryboard>
</EventTrigger.Actions>
</EventTrigger>
<EventTrigger RoutedEvent="ItemsControl.MouseLeave">
<EventTrigger.Actions>
<BeginStoryboard>
<Storyboard>
<DoubleAnimation Storyboard.TargetName="OrFilterContentType"
Storyboard.TargetProperty="(Brush.Opacity)"
From="1" To="0"
Duration="0:0:0.7" />
</Storyboard>
</BeginStoryboard>
</EventTrigger.Actions>
</EventTrigger>
<EventTrigger RoutedEvent="ItemsControl.DragLeave">
<EventTrigger.Actions>
<BeginStoryboard>
<Storyboard>
<DoubleAnimation Storyboard.TargetName="OrFilterContentType"
Storyboard.TargetProperty="(Brush.Opacity)"
From="1"
To="0"
Duration="0:0:0.7" />
</Storyboard>
</BeginStoryboard>
</EventTrigger.Actions>
</EventTrigger>
<EventTrigger RoutedEvent="ItemsControl.Drop">
<EventTrigger.Actions>
<BeginStoryboard>
<Storyboard>
<DoubleAnimation Storyboard.TargetName="OrFilterContentType"
Storyboard.TargetProperty="(Brush.Opacity)"
From="1"
To="0"
Duration="0:0:0.7" />
</Storyboard>
</BeginStoryboard>
</EventTrigger.Actions>
</EventTrigger>
</ItemsControl.Triggers>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel Orientation="Horizontal"
Background="Transparent">
<i:Interaction.Behaviors>
<ei:FluidMoveBehavior AppliesTo="Children"
Duration="0:0:0.3">
<ei:FluidMoveBehavior.EaseY>
<BackEase EasingMode="EaseIn"
Amplitude="0.1" />
</ei:FluidMoveBehavior.EaseY>
</ei:FluidMoveBehavior>
</i:Interaction.Behaviors>
</WrapPanel>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/38784476",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to change from annual year end to annual mid year in SAS I currently work in SAS and utilise arrays in this way:
Data Test;
input Payment2018-Payment2021;
datalines;
10 10 10 10
20 20 20 20
30 30 30 30
;
run;
In my opinion this automatically assumes a limit, either the start of the year or the end of the year (Correct me if i'm wrong please)
So, if I wanted to say that this is June data and payments are set to increase every 9 months by 50% I'm looking for a way for my code to recognise that my years go from end of June to the next end of june
For example, if I wanted to say
Data Payment_Pct;
set test;
lastpayrise = "31Jul2018";
array payment:
array Pay_Inc(2018:2021) Pay_Inc: ;
Pay_Inc2018 = 0;
Pay_Inc2019 = 2; /*2 because there are two increments in 2019*/
Pay_Inc2020 = 1;
Pay_Inc2021 = 1;
do I = 2018 to 2021;
if i = year(pay_inc) then payrise(i) * 50% * Pay_Inc(i);
end;
run;
It's all well and good for me to manually do this for one entry but for my uni project, I'll need the algorithm to work these out for themselves and I am currently reading into intck but any help would be appreciated!
P.s. It would be great to have an algorithm that creates the following
Pay_Inc2019 Pay_Inc2020 Pay_Inc2021
1 2 1
OR, it would be great to know how the SAS works in setting the array for 2018:2021 , does it assume end of year or can you set it to mid year or?
A: This is a wonderful use case of the intnx() function. intnx() will be your best friend when it comes to aligning dates.
In the traditional calendar, the year starts on 01JAN. In your calendar, the year starts in 01JUN. The difference between these two dates is exactly 6 months. We want to shift our date so that the year starts on 01JUN. This will allow you to take the year part of the date and determine what year you are on in the new calendar.
data want;
format current_cal_year
current_new_year year4.
;
current_cal_year = intnx('year', '01JUN2018'd, 0, 'B');
current_new_year = intnx('year.6', '01JUN2018'd, 1, 'B');
run;
Note that we shifted current_new_year by one year. To illustrate why, let's see what happens if we don't shift it by one year.
data want;
format current_cal_year
current_new_year year4.
;
current_cal_year = intnx('year', '01JUN2018'd, 0, 'B');
current_new_year = intnx('year.6', '01JUN2018'd, 0, 'B');
run;
current_new_year shows 2018, but we really are in 2019. For 5 months out of the year, this value will be correct. From June-December, the year value will be incorrect. By shifting it one year, we will always have the correct year associated with this date value. Look at it with different months of the year and you will see that the year part remains correct throughout time.
data want;
format cal_month date9.
cal_year
new_year year4.
;
do i = 0 to 24;
cal_month = intnx('month', '01JAN2016'd, i, 'B');
cal_year = intnx('year', cal_month, i, 'B');
new_year = intnx('year.6', cal_month, i+1, 'B');
year_not_same = (year(cal_year) NE year(new_year) );
output;
end;
drop i;
run;
A: Regarding input Payment2018-Payment2021; there is no automatic assumption of yearness or calendaring. The numbers 2018 and 2021 are the bounds for a numbered range list
In a numbered range list, you can begin with any number and end with any number as long as you do not violate the rules for user-supplied names and the numbers are consecutive.
The meaning of the numbers 2018 to 2021 is up to the programmer. You state the variables correspond to the June payment in the numbered year.
You would have to iterate a date using 9-month steps and increment a counter based on the year in which the date falls.
Sample code
Dynamically adapts to the variable names that are arrayed.
data _null_;
array payments payment2018-payment2021;
array Pay_Incs pay_inc2018-pay_inc2021; * must be same range numbers as payments;
* obtain variable names of first and last element in the payments array;
lower_varname = vname(payments(1));
upper_varname = vname(payments(dim(payments)));
* determine position of the range name numbers in those variable names;
lower_year_position = prxmatch('/\d+\s*$/', lower_varname);
upper_year_position = prxmatch('/\d+\s*$/', upper_varname);
* extract range name numbers from the variable names;
lower_year = input(substr(lower_varname,lower_year_position),12.);
upper_year = input(substr(upper_varname,upper_year_position),12.);
* prepare iteration of a date over the years that should be the name range numbers;
date = mdy(06,01,lower_year); * june 1 of year corresponding to first variable in array;
format date yymmdd10.;
do _n_ = 1 by 1; * repurpose _n_ for an infinite do loop with interior leave;
* increment by 9-months;
date = intnx('month', date, 9);
year = year(date);
if year > upper_year then leave;
* increment counter for year in which iterating date falls within;
Pay_Incs( year - lower_year + 1 ) + 1;
end;
put Pay_Incs(*)=;
run;
Increment counter notes
There is a lot to unpack in this statement
Pay_Incs( year - lower_year + 1 ) + 1;
*
*+ 1 at the end of the statement increments the addressed array element by 1, and is the syntax for the SUM Statement
variable + expression The sum statement is equivalent to using the SUM function and the RETAIN statement, as shown here:
retain variable 0;
variable=sum(variable,expression);
*year - lower_year + 1 computes the array base-1 index, 1..N, that addresses the corresponding variable in the named range list pay_inc<lower_year>-pay_inc<upper_year>
*Pay_Incs( <computed index> ) selects the variable of the SUM statement
| {
"language": "en",
"url": "https://stackoverflow.com/questions/52205027",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Make for loop continue until a goal is accomplished I need to be able to find 5 sequential bits of EEPROM memory, ideally closest to 2 (as I have bit #1 & 2 associated with other data and want things to be kept organized). I developed this code which works, but the for loop continues after it has found a good set of numbers.
Serial.println("got to assignment number finder");
for (int AssignCheck = 2; AssignCheck < 250; AssignCheck++){
Serial.println("Finding a good assignment number " + String(AssignCheck));
if (EEPROM.read(AssignCheck) == 255){ //Looks for a blank space which can be used to store the new card
if (EEPROM.read(AssignCheck + 1) == 255){
if (EEPROM.read(AssignCheck + 2) == 255){
if (EEPROM.read(AssignCheck + 3) == 255){
if (EEPROM.read(AssignCheck + 4) == 255){
Serial.println("Found assignment numbers " + String(AssignCheck) + " through to " + String(int(AssignCheck) + 4) + ". Scanner value = " + String(Scanner));
int StoreValue = AssignCheck;
}
}
}
}
}
}
I then thought I could put a while loop around it, and have the while loop stop once a variable is set to 0 as opposed to 1, so I wrote this: (notice the introduction of the while loop, the variable and the Scanner = 0 line in the middle).
Serial.println("got to assignment number finder");
int Scanner = 1;
while (Scanner == 1){
for (int AssignCheck = 2; AssignCheck < 250; AssignCheck++){
Serial.println("Finding a good assignment number " + String(AssignCheck) + ". Scanner value = " + String(Scanner));
if (EEPROM.read(AssignCheck) == 255){ //Looks for a blank space which can be used to store the new card
if (EEPROM.read(AssignCheck + 1) == 255){
if (EEPROM.read(AssignCheck + 2) == 255){
if (EEPROM.read(AssignCheck + 3) == 255){
if (EEPROM.read(AssignCheck + 4) == 255){
Scanner = 0;
Serial.println("Found assignment numbers " + String(AssignCheck) + " through to " + String(int(AssignCheck) + 4) + ". Scanner value = " + String(Scanner));
int StoreValue = AssignCheck;
}
}
}
}
}
}
}
It correctly identifies and sets the variable to 0 when I want, but the while loop doesn't seem to have an impact and the loop continues to produce sets of numbers which could work.
As a novice coder myself, I'm not sure what I could try next.
Any advice would be greatly appreciated.
A: In these case you can use the instruction break:
Serial.println("got to assignment number finder");
for (int AssignCheck = 2; AssignCheck < 250; AssignCheck++){
Serial.println("Finding a good assignment number " + String(AssignCheck));
if (EEPROM.read(AssignCheck) == 255){ //Looks for a blank space which can be used to store the new card
if (EEPROM.read(AssignCheck + 1) == 255){
if (EEPROM.read(AssignCheck + 2) == 255){
if (EEPROM.read(AssignCheck + 3) == 255){
if (EEPROM.read(AssignCheck + 4) == 255){
Serial.println("Found assignment numbers " + String(AssignCheck) + " through to " + String(int(AssignCheck) + 4) + ". Scanner value = " + String(Scanner));
int StoreValue = AssignCheck;
break;
}
}
}
}
}
}
As you can read here, it does exactly what you want.
Please note that your second attempt doesn't work because the for loop is inside the while: it completes before the whole for loop and, after, it compare the "scanner" variable of the while loop
You can correct it in this way:
Serial.println("got to assignment number finder");
int Scanner = 1;
for (int AssignCheck = 2; (AssignCheck < 250) && (Scanner == 1); AssignCheck++){
Serial.println("Finding a good assignment number " + String(AssignCheck) + ". Scanner value = " + String(Scanner));
if (EEPROM.read(AssignCheck) == 255){ //Looks for a blank space which can be used to store the new card
if (EEPROM.read(AssignCheck + 1) == 255){
if (EEPROM.read(AssignCheck + 2) == 255){
if (EEPROM.read(AssignCheck + 3) == 255){
if (EEPROM.read(AssignCheck + 4) == 255){
Scanner = 0;
Serial.println("Found assignment numbers " + String(AssignCheck) + " through to " + String(int(AssignCheck) + 4) + ". Scanner value = " + String(Scanner));
int StoreValue = AssignCheck;
}
}
}
}
}
}
A: Reading EEPROM is expensive, please consider this:
Serial.println("got to assignment number finder");
int Scanner = 1;
char rollingBuffer[5];
rollingBuffer[0] = EEPROM.read(2 + 0);
rollingBuffer[1] = EEPROM.read(2 + 1);
rollingBuffer[2] = EEPROM.read(2 + 2);
rollingBuffer[3] = EEPROM.read(2 + 3);
rollingBuffer[4] = EEPROM.read(2 + 4);
pointRoll = 0;
for (int AssignCheck = 7; (AssignCheck < 255); AssignCheck++)
{
if ((rollingBuffer[0] == 255) && (rollingBuffer[1] == 255) && (rollingBuffer[2] == 255) && (rollingBuffer[3] == 255) && (rollingBuffer[4] == 255))
{
Serial.println("Found assignment numbers " + String(AssignCheck-5) + " through to " + String(int(AssignCheck-1)) + ". Scanner value = " + String(Scanner));
int StoreValue = AssignCheck;
break;
}
rollingBuffer[pointRoll] = EEPROM.read(AssignCheck);
pointRoll++;
if (pointRoll > 4) pointRoll = 0;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46725350",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Laravel back() doesn't use _previous Trying to use
return back();
In one of my controllers however it always seems to return back to the home page if I however use
return Redirect::to($request->session->get('_previous')['url']);
It does work so it seems that for some reason the back() function isn't grabbing _previous correctly. Any way to fix this? I've noticed it in other controllers as well.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/43053936",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Confused in Dependency Injection I am new to MVC and dependency injection. Please help me to understand how that should work. I use Ninject. Here is my code:
in Global.asax file:
private void RegisterDependencyResolver()
{
var kernel = new StandardKernel();
kernel.Bind<IDbAccessLayer>().To<DAL>();
// DAL - is a Data Access Layer that comes from separated class library
DependencyResolver.SetResolver(new NinjectDependencyResolver(kernel));
}
protected void Application_Start()
{
RegisterDependencyResolver();
}
IDbAccessLayer implementation is very simple:
public interface IDbAccessLayer
{
DataContext Data { get; }
IEnumerable<User> GetUsers();
}
now in a Controller I need to create a constructor that gets IDbAccessLayer param. And that just works.
Now I don't know how to pass a connection string to DAL. if I try to replace DAL's constructor with something that accepts a parameter, it doesn't work. Throws an exception with message No parameterless constructor defined for this object
A: You could specify constructor parameters:
kernel
.Bind<IDbAccessLayer>()
.To<DAL>()
.WithConstructorArgument("connectionString", "YOUR CONNECTION STRING HERE");
And instead of hardcoding the connection string in your Global.asax you could read it from your web.config using:
ConfigurationManager.ConnectionStrings["CNName"].ConnectionString
and now your DAL class could take the connection string as parameter:
public class DAL: IDbAccessLayer
{
private readonly string _connectionString;
public DAL(string connectionString)
{
_connectionString = connectionString;
}
... implementation of the IDbAccessLayer methods
}
A: Create a parameter-less constructor that calls the one-parameter constructor with a default connection string.
public DAL() : this("default connection string") {
}
public DAL(string connectionString) {
// do something with connection string
}
A: I've not worked with ninject, just a bit with Unity. But all the IOC containers seem to gravitate towards you making your own factory class that takes your stateful parameters (your connection string), which returns your real object. For example, if you had a Person class which requires a "name" and "age" for the constructor, then you must make a factory which would interact with Unity rather like this:
IPerson foo = container.Resolve<IPersonFactory>().Create("George", 25);
This is one of the things I don't like about IOC containers, but it's generally where it goes...
A: Just stupid idea having no knowledge of ninject:
kernel.Bind<IMyConnectionString>().To<MyConnectionString>();
And to your DAL constructor accepting IMyConnectionString
| {
"language": "en",
"url": "https://stackoverflow.com/questions/5222698",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Change App name dynamically based on user input I want to change the name of the app and the form title based on the user input. I know to do those changes in the manifest and styles, but how to make it dynamic. Please suggest me how to do it?. What are the changes to be done.
A: Did you try this?
myActivity.setTitle(userInput); //Where userInput is new title given by user
Hope this helps.
A: You can simply call the setTitle() function from within your Activity. It takes either an int (resource ID) or a CharSequence as a parameter.
or
this.setTitle("New Title Here");
or change in manifest file
A: If you just want to change the string in the Title bar, you can use setTitle as @android_beginner or @Mystic Magic suggested.
If you intend on changing the name of the app as it appears in the Android desktop, I'm afraid that's not possible.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/19354382",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to replace table name in sql query with regex in Java? I want to replace table name in a sql query string. I only want to change table name. How can I do that in java with regex?
I do not want to use any dependencies.
For example,
Input:
select ... from table1 where/etc ....
expected output:
select ... from UPDATED_TABLE_NAME where/etc ....
A: If you mutate the query explicitly you open yourself to SQL injection. What you could do is use a PreparedStatement with a parameterized query to provide the table name safely.
try (PreparedStatement statement = connection.prepareStatement("SELECT * FROM ?")) {
statement.setString(1, "my_table");
try (ResultSet results = statement.executeQuery()) {
}
}
If you're insistent on using regex you can just use the query above and replace ? with the table name. I would not do this in a production environment.
String query = "SELECT * FROM ?";
String queryWithTable = query.replaceAll("?", "my_table");
| {
"language": "en",
"url": "https://stackoverflow.com/questions/61891745",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.