text
stringlengths 64
81.1k
| meta
dict |
---|---|
Q:
Finding a custom object in a set and then returning that object
public Table findTable(Container container, String name) {
Iterator<Table> tableFinder = container.getTables().iterator();
while(tableFinder.hasNext()){
if (tableFinder.equals(name)){
return table;
} else {
return null;
}
}
}
So basically this method is supposed to search for a table within the object containerby checking one of its properties tableswhich is a set. It is supposed to find the object through the property name which belongs to Table. Normally, I would just insert a parameter of type table, it'd be easier to find it that way, but the wireframe I was given specifically states that it has to be this way.
I've got hashcode() and equals() as methods for table, I know I need to use them somehow, however I'm not really sure how to do this. The other problem is that I need to return a table and I'm not sure how to do that without an instance of Table so I know that return table is going to give an error. Basically, what I need to know is how to search with name and how to get the table out of the set in order to have a valid return.
A:
With
if (tableFinder.equals(name)){
you are calling equals of the iterator object, this is not what you really want. Instead you want to compare with the Table the iterator is pointing at in each loop. To get that object you need to call the method Iterator#next() on the iterator object.
Table table = tableFinder.next();
if (table.equals(name)){ // assuming that your equals implementation
// compares with the property name of table
| {
"pile_set_name": "StackExchange"
} |
Q:
Stop vis.js physics after nodes load but allow drag-able nodes
I am trying to draw a vis.js network diagram and have vis load and position the nodes. I then want the physics to be disabled so the nodes can be moved by the user. I have tried this but it is not working.
var options = {
nodes: {
borderWidth:4,
size:60,
color: {
border: '#222222',
background: 'grey'
},
font:{color:'black'}
},
edges: {
arrows: {
to: {enabled: false, scaleFactor:1},
middle: {enabled: false, scaleFactor:1},
from: {enabled: false, scaleFactor:1}
},
color: 'black'
},
{ physics: enabled: false; };
Has anyone done this? if so can you provide an example or advice on best way to accomplish this. I have also read the explanation located here, but not being too familiar with java I can't figure the steps out.
Thanks
A:
After some more work and help from the vis.js developer here is the completed code, minus the json data and some options. The trick is to use the "stabilizationIterationsDone" event and disable physics:
// create a network
var container = document.getElementById('mynetwork');
var data = {
nodes: nodes,
edges: edges
};
var options = {
nodes: ...,
edges: ...,
physics: {
forceAtlas2Based: {
gravitationalConstant: -26,
centralGravity: 0.005,
springLength: 230,
springConstant: 0.18,
avoidOverlap: 1.5
},
maxVelocity: 146,
solver: 'forceAtlas2Based',
timestep: 0.35,
stabilization: {
enabled: true,
iterations: 1000,
updateInterval: 25
}
}
};
network = new vis.Network(container, data, options);
network.on("stabilizationIterationsDone", function () {
network.setOptions( { physics: false } );
});
A:
I was able to figure this out and the code now looks like this
// create a network
var container = document.getElementById('mynetwork');
var data = {
nodes: nodes,
edges: edges
};
var options = {
nodes: {
borderWidth:1,
size:45,
color: {
border: '#222222',
background: 'grey'
},
font:{color:'black',
size: 11,
face :'arial',
},
},
edges: {
arrows: {
to: {enabled: false, scaleFactor:1},
middle: {enabled: false, scaleFactor:1},
from: {enabled: false, scaleFactor:1}
},
color: {
color:'#848484',
highlight:'#848484',
hover: '#848484',
},
font: {
color: '#343434',
size: 11, // px
face: 'arial',
background: 'none',
strokeWidth: 5, // px
strokeColor: '#ffffff',
align:'vertical'
},
smooth: {
enabled: false, //setting to true enables curved lines
//type: "dynamic",
//roundness: 0.5
},
}
};
network = new vis.Network(container, data, options);
network.setOptions({
physics: {enabled:false}
});
}
I had to move the network.setOptions() as shown in the new code and it is now working as desired.
A:
I suppose you first want to let the network stabilize and only then disable physics? In that case you can load the Network with physics and stabilization enabled. Once the nodes are stabilized, the stabilized event is fired. Then you can disable the physics via network.setOptions
| {
"pile_set_name": "StackExchange"
} |
Q:
Shading Languages vs Materials in 3D editors
There are many 3d packages which are able to construct materials. Autodesk Maya, 3ds max, Houdini, etc.
There are languages which are able to construct materials as well, like GLSL and Cg.
How does first group correspond to the second? Are there workflows, where they are used simultaneously?
From my experience, constructing materials in 3d packages is way faster than writing code in GLSL. They also have scripting systems for more customization. Do shading languages have their own benefits?
A:
Well, Shading languages like GLSL and HLSL is what all the "material" code ultimately get translated to in the end. Shaders are the actual programs which are run directly on the GPU, and to create them, you use a shading language.
3D packages are generally used to make it easer for you to make realistic looking graphics, and writing shaders by hand is a little cumbersome, as one would require knowledge of shader programming, Lighting mathematics, physics, and so on. What you call materials is just an abstraction provided by the package so that you can design surfaces and graphics in an intuitive, easy and fast way.
It is seen that in most cases, scenes created with 3D packages can be created using a fixed set of commonly used shaders (phong shading, diffuse, specular colors, reflections, simulating roughness and other common things). These are the things 'materials' save you from rewriting.
Though writing shaders directly can be cumbersome, provided you have all the prerequisite knowledge to do so, you can fine-tune and create effects which are otherwise not so much possible with what 3D packages provide with their "material" interface. Shaders give you full control.
| {
"pile_set_name": "StackExchange"
} |
Q:
Почему venv в Linux не видит библиотеки Python?
Писал программу на Windows. Потом перешёл на Linux, запустил виртуальное окружение и все ок, но Python не может найти библиотеки из виртуального окружения. Что делать?
A:
Библиотеки с Виндовс версии не совместимы с Линукс и наоборот. Не все, но ощутимая их часть. Используйте pip freeze для сохранения списка и pip install -r requirements.txt для установки их по списку в другой системе.
| {
"pile_set_name": "StackExchange"
} |
Q:
Método Trim, ¿Cómo eliminar espacios y caracteres especiales entre cadenas de caracteres?
¿Cómo puedo hacer con el método trim que elimine cualquier carácter especial, incluido los espacios en blanco de una cadena de caracteres?.
5N0 839 167 B GRU
5*6 839 461 D
5C/ 854 855 9B9
5C6 8@9 431 5AP
@N0 839 885 H
5@6 845 025 A
Intento aplicar este metodo, pero no me resulta:
System.out.println(text.trim());
A:
El método trim() puede ayudar únicamente a eliminar espacios en los extremos de la cadena.
considero que en este caso es mejor usar el método replace(), reemplazando espacios:
text.replace(" ", "");
de esta forma eliminas los espacios entre los caracteres y no es necesario el método trim() .
Ejemplo:
String text = " 5N0 839 167 B GRU ";
text = text.replace(" ", "");
System.out.println(text);
tendría como salida:
5N0839167BGRU
Eliminar espacios y caracteres especiales.
Lo que requieres en realidad es eliminar además de espacios, caracteres especiales, para esto es recomendable hacer uso de una REGEX:
replaceAll("[^A-Za-z0-9]+", "")
Ejemplo:
String text = " 5C6 8@9 431 5AP ";
text = text.replaceAll("[^A-Za-z0-9]+", "");
System.out.println(text);
tendría como salida:
5C6894315AP
A:
El método trim() lo que hace es eliminar los espacios en blanco al inicio y al final de la palabra, en tu caso podrías usar el método replaceAll(), que recibe un patrón a seguir y por lo que lo reemplazara: ejemplo:
text.replaceAll("[^\\dA-Za-z]", "")
que indica que reemplace todo aquello que no sea numero, letra mayúscula o minúscula por un ""
| {
"pile_set_name": "StackExchange"
} |
Q:
Why is the き in 充電器 器 not 機?
A charger is a machine. Why is it 器 not 機?
A:
機 is for "large" machines; things with "lots" of likely "large" moving parts. What comes to mind are like automated machines of an assembly line (cars, packaging, etc.), printing press, etc. Also, aircraft (飛行機, 航空機).
器 is used for "smaller" things. It is often used to mean [器具]{き・ぐ} - tools, instruments, appliances, etc.
Where the cutoff between "small" and "large" is, and who decides those things, I'm not sure. There may be some counterexamples, but if you stick with the "small" and "large" rule, you'll be right most of the time.
| {
"pile_set_name": "StackExchange"
} |
Q:
Does CLEAR allow you to avoid the full body scanner?
TSA Pre-Check and Global Entry allow passengers to more or less avoid the full-body (millimeter wave) scanners and instead use metal detectors. You also don't have to take off your shoes or take out your laptop.
This is an important benefit to many of us -- even more important than cutting the line. But TSA Pre-Check and Global Entry are only offered to US citizens, permanent residents, and citizens of a restricted subset of countries. The rest of humanity is SOL.
CLEAR seems to offer a solution as you only need a USA driver's license to apply, which means F1 students or H1B workers from any country, for example, are eligible.
But I'm unclear about the benefits of CLEAR. Do you get the same pre-check benefits such as avoiding the full-body scanner if you don't have TSA Pre-Check? If you don’t, is there really that much benefit?
A:
CLEAR lets you go through a shorter line and skip the ID check using biometrics (the long security line is generally the line to the ID check, so skipping it can be a major time-saver). As their site shows, it does not make any difference to the actual TSA screening; you get sent to either PreCheck or normal lines depending on whether or not your ticket qualifies for PreCheck (i.e. you're a member, the airport has PreCheck, the airline participates in PreCheck, and you gave the airline your Known Traveler Number). As for whether it's worth it, that's a matter of personal preference.
The CLEAR Travel Experience
CLEAR speeds you through the long line for ID check, and guides you to the screening line.
Enrolled in PreCheck? We’ll provide you with fast access to PreCheck screening for eligible flights.
| {
"pile_set_name": "StackExchange"
} |
Q:
mysql setup in digital ocean using node express
I just decided to switch from google sql to hosting my own mysql server on the droplet where my app is because google sql is so expensive for a side/start up project.
anyway, my problem is, i don't know how to connect to mysql using my app. I can access the mysql using the terminal, i've also manage to setup it on workbench but i can't get the app to connect to it.
this is my config object
DB_HOST=127.0.0.1
DB_USER=root
DB_PASSWORD=*****
DB_NAME=express_mysql_database00
Questions:
List item are these all i need?
it the db host correct?
i'm using the mysql module, do i need to use a different one to make this work?
A:
From the readme of the mysql npm package, those are the parameters you need (there are a lot more parameters where you most likely the default value is suitable for you):
var connection = mysql.createConnection({
host : 'localhost',
user : 'me',
password : 'secret',
database : 'my_db'
});
it the db host correct?
That depends on how you configured the database. There is a difference between localhost and 127.0.0.1. See: Mysql localhost != 127.0.0.1?
i'm using the mysql module, do i need to use a different one to make this work?
Looks like this is one you can use...
| {
"pile_set_name": "StackExchange"
} |
Q:
Ant design page reloading css rendering delay
I used my react TypeScript project for ant-design, I have some issue when I reload the page, css loading delay, any reason for this?
I imported my main.css to
@import './../node_modules/antd/dist/antd.css';
A:
Actually, based on And Design Doc about getting a start, You could use babel plugin for automatic loading used components like below, it is a recommended way:
// .babelrc or babel-loader option
{
"plugins": [
["import", { "libraryName": "antd", "libraryDirectory": "es", "style": "css" }] // `style: true` for less
]
}
By using this way (from docs):
This allows you to import components from antd without having to manually import the corresponding stylesheet. The antd babel plugin will automatically import stylesheets.
So you can import the component easily and there is no need to load CSS manually, just like below:
import { Button } from 'antd';
But if you don't want to use the above plugin, you can use Ant Desing component by importing its CSS inside each component like below:
import React from 'react';
import Button from 'antd/es/button';
import 'antd/es/button/style/css'; // <<=== this way
import './CustomButton.css';
const CustomButton = () => (
<div className="custom-button">
<Button type="primary">
Button
</Button>
</div>
);
And there is another way, use your own CSS or SCSS or LESS, but import the component CSS at the top of your component CSS system, just like below exactly like docs:
// the custom component
import React from 'react';
import Button from 'antd/es/button';
import './CustomButton.css';
const CustomButton = () => (
<div className="custom-button">
<Button type="primary">
Button
</Button>
</div>
);
// the CustomButton.css file
@import '~antd/es/button/style/css';
.custom-button {
background-color: red; // for example
}
Also, you can use the whole Ant Design CSS instead of using separately each component. I mean this:
import 'antd/dist/antd.css';
Instead of this:
import 'antd/es/button/style/css';
For this way of loading CSS, it is better to import it once at the root of the project or the CSS system.
HINT: I prefer the first, using babel plugin, it is safe, more clear and more readable.
A:
Replace
@import './../node_modules/antd/dist/antd.css';
with
@import '~antd/dist/antd.css';
This is given in the documentation you linked.
| {
"pile_set_name": "StackExchange"
} |
Q:
Restoring database from .sql file is failing
I am trying to use C# to restore a blank database's tables from an sql file I have.
This is the code:
namespace KezberProjectManager
{
public partial class VisitClear : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string sqlConnectionString = "Data Source=JOSH-PC\\SQLEXPRESS;Initial Catalog=KezBlu;Integrated Security=True;MultipleActiveResultSets=True";
FileInfo file = new FileInfo(Path.Combine(
HostingEnvironment.ApplicationPhysicalPath,
@"App_Data\kb.sql"));
string script = file.OpenText().ReadToEnd();
SqlConnection conn = new SqlConnection(sqlConnectionString);
Server server = new Server(new ServerConnection(conn));
server.ConnectionContext.ExecuteNonQuery(script);
}
}
}
Here is the script:
USE [KezBlu]
GO
/****** Object: ForeignKey [Customer_Case] Script Date: 04/24/2013 21:35:08 ******/
ALTER TABLE [dbo].[Cases] DROP CONSTRAINT [Customer_Case]
GO
/****** Object: ForeignKey [Schedule_Case] Script Date: 04/24/2013 21:35:08 ******/
ALTER TABLE [dbo].[Cases] DROP CONSTRAINT [Schedule_Case]
GO
/****** Object: ForeignKey [Status_Case] Script Date: 04/24/2013 21:35:08 ******/
ALTER TABLE [dbo].[Cases] DROP CONSTRAINT [Status_Case]
GO
/****** Object: ForeignKey [Group_Employee] Script Date: 04/24/2013 21:35:08 ******/
ALTER TABLE [dbo].[Employee] DROP CONSTRAINT [Group_Employee]
GO
/****** Object: ForeignKey [Employee_EmployeGroupFilter] Script Date: 04/24/2013 21:35:08 ******/
ALTER TABLE [dbo].[EmployeGroupFilters] DROP CONSTRAINT [Employee_EmployeGroupFilter]
GO
/****** Object: ForeignKey [Group_EmployeGroupFilter] Script Date: 04/24/2013 21:35:08 ******/
ALTER TABLE [dbo].[EmployeGroupFilters] DROP CONSTRAINT [Group_EmployeGroupFilter]
GO
/****** Object: ForeignKey [Employee_LockedDate] Script Date: 04/24/2013 21:35:08 ******/
ALTER TABLE [dbo].[LockedDates] DROP CONSTRAINT [Employee_LockedDate]
GO
/****** Object: ForeignKey [Schedule_Project] Script Date: 04/24/2013 21:35:08 ******/
ALTER TABLE [dbo].[Project] DROP CONSTRAINT [Schedule_Project]
GO
/****** Object: ForeignKey [Employee_Schedule] Script Date: 04/24/2013 21:35:08 ******/
ALTER TABLE [dbo].[Schedule] DROP CONSTRAINT [Employee_Schedule]
GO
/****** Object: ForeignKey [Recurring_Schedule] Script Date: 04/24/2013 21:35:08 ******/
ALTER TABLE [dbo].[Schedule] DROP CONSTRAINT [Recurring_Schedule]
GO
/****** Object: ForeignKey [Project_Task] Script Date: 04/24/2013 21:35:08 ******/
ALTER TABLE [dbo].[Task] DROP CONSTRAINT [Project_Task]
GO
/****** Object: ForeignKey [Schedule_Task] Script Date: 04/24/2013 21:35:08 ******/
ALTER TABLE [dbo].[Task] DROP CONSTRAINT [Schedule_Task]
GO
/****** Object: ForeignKey [Schedule_Task1] Script Date: 04/24/2013 21:35:08 ******/
ALTER TABLE [dbo].[Task] DROP CONSTRAINT [Schedule_Task1]
GO
/****** Object: Table [dbo].[Task] Script Date: 04/24/2013 21:35:08 ******/
ALTER TABLE [dbo].[Task] DROP CONSTRAINT [Project_Task]
GO
ALTER TABLE [dbo].[Task] DROP CONSTRAINT [Schedule_Task]
GO
ALTER TABLE [dbo].[Task] DROP CONSTRAINT [Schedule_Task1]
GO
DROP TABLE [dbo].[Task]
GO
/****** Object: Table [dbo].[Cases] Script Date: 04/24/2013 21:35:08 ******/
ALTER TABLE [dbo].[Cases] DROP CONSTRAINT [Customer_Case]
GO
ALTER TABLE [dbo].[Cases] DROP CONSTRAINT [Schedule_Case]
GO
ALTER TABLE [dbo].[Cases] DROP CONSTRAINT [Status_Case]
GO
DROP TABLE [dbo].[Cases]
GO
/****** Object: Table [dbo].[Project] Script Date: 04/24/2013 21:35:08 ******/
ALTER TABLE [dbo].[Project] DROP CONSTRAINT [Schedule_Project]
GO
DROP TABLE [dbo].[Project]
GO
/****** Object: Table [dbo].[EmployeGroupFilters] Script Date: 04/24/2013 21:35:08 ******/
ALTER TABLE [dbo].[EmployeGroupFilters] DROP CONSTRAINT [Employee_EmployeGroupFilter]
GO
ALTER TABLE [dbo].[EmployeGroupFilters] DROP CONSTRAINT [Group_EmployeGroupFilter]
GO
DROP TABLE [dbo].[EmployeGroupFilters]
GO
/****** Object: Table [dbo].[LockedDates] Script Date: 04/24/2013 21:35:08 ******/
ALTER TABLE [dbo].[LockedDates] DROP CONSTRAINT [Employee_LockedDate]
GO
DROP TABLE [dbo].[LockedDates]
GO
/****** Object: Table [dbo].[Schedule] Script Date: 04/24/2013 21:35:08 ******/
ALTER TABLE [dbo].[Schedule] DROP CONSTRAINT [Employee_Schedule]
GO
ALTER TABLE [dbo].[Schedule] DROP CONSTRAINT [Recurring_Schedule]
GO
DROP TABLE [dbo].[Schedule]
GO
/****** Object: Table [dbo].[Employee] Script Date: 04/24/2013 21:35:08 ******/
ALTER TABLE [dbo].[Employee] DROP CONSTRAINT [Group_Employee]
GO
DROP TABLE [dbo].[Employee]
GO
/****** Object: Table [dbo].[Colors] Script Date: 04/24/2013 21:35:08 ******/
DROP TABLE [dbo].[Colors]
GO
/****** Object: Table [dbo].[Customers] Script Date: 04/24/2013 21:35:08 ******/
DROP TABLE [dbo].[Customers]
GO
/****** Object: Table [dbo].[Group] Script Date: 04/24/2013 21:35:08 ******/
DROP TABLE [dbo].[Group]
GO
/****** Object: Table [dbo].[Recurring] Script Date: 04/24/2013 21:35:08 ******/
DROP TABLE [dbo].[Recurring]
GO
/****** Object: Table [dbo].[Settings] Script Date: 04/24/2013 21:35:08 ******/
DROP TABLE [dbo].[Settings]
GO
/****** Object: Table [dbo].[Statuses] Script Date: 04/24/2013 21:35:08 ******/
DROP TABLE [dbo].[Statuses]
GO
/****** Object: Table [dbo].[Statuses] Script Date: 04/24/2013 21:35:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Statuses](
[StatusID] [int] IDENTITY(1,1) NOT NULL,
[StatusDescription] [varchar](50) NULL,
CONSTRAINT [PK_dbo.Statuses] PRIMARY KEY CLUSTERED
(
[StatusID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object: Table [dbo].[Settings] Script Date: 04/24/2013 21:35:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Settings](
[SettingID] [int] IDENTITY(1,1) NOT NULL,
[SettingKey] [varchar](50) NOT NULL,
[SettingValue] [text] NOT NULL,
CONSTRAINT [PK_dbo.Settings] PRIMARY KEY CLUSTERED
(
[SettingID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object: Table [dbo].[Recurring] Script Date: 04/24/2013 21:35:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Recurring](
[RecurringID] [int] IDENTITY(1,1) NOT NULL,
[Period] [int] NULL,
[DateStart] [datetime] NULL,
[DateLast] [datetime] NULL,
[Advance] [int] NULL,
CONSTRAINT [PK_dbo.Recurring] PRIMARY KEY CLUSTERED
(
[RecurringID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object: Table [dbo].[Group] Script Date: 04/24/2013 21:35:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Group](
[GroupID] [int] IDENTITY(1,1) NOT NULL,
[GroupDescription] [varchar](max) NOT NULL,
[IsReadOnly] [bit] NULL,
CONSTRAINT [PK_dbo.[Group]]] PRIMARY KEY CLUSTERED
(
[GroupID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object: Table [dbo].[Customers] Script Date: 04/24/2013 21:35:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Customers](
[CustomerID] [int] IDENTITY(1,1) NOT NULL,
[CustomerDescription] [varchar](max) NULL,
CONSTRAINT [PK_dbo.Customers] PRIMARY KEY CLUSTERED
(
[CustomerID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object: Table [dbo].[Colors] Script Date: 04/24/2013 21:35:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Colors](
[ColorID] [int] IDENTITY(1,1) NOT NULL,
[ColorValue] [int] NOT NULL,
CONSTRAINT [PK_dbo.Colors] PRIMARY KEY CLUSTERED
(
[ColorID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object: Table [dbo].[Employee] Script Date: 04/24/2013 21:35:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Employee](
[EmployeID] [int] IDENTITY(1,1) NOT NULL,
[EmployeName] [varchar](50) NOT NULL,
[EmployeEmail] [varchar](50) NOT NULL,
[EmployePassword] [char](44) NOT NULL,
[DefaultNumWeek] [smallint] NULL,
[GroupID] [int] NULL,
CONSTRAINT [PK_dbo.Employee] PRIMARY KEY CLUSTERED
(
[EmployeID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object: Table [dbo].[Schedule] Script Date: 04/24/2013 21:35:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Schedule](
[ScheduleID] [int] IDENTITY(1,1) NOT NULL,
[DateFrom] [datetime] NULL,
[Hours] [decimal](10, 2) NULL,
[EmployeID] [int] NULL,
[RecurringID] [int] NULL,
[Priority] [int] NULL,
[DateTo] [datetime] NULL,
[IsLocked] [bit] NOT NULL,
[BumpPriority] [int] NULL,
CONSTRAINT [PK_dbo.Schedule] PRIMARY KEY CLUSTERED
(
[ScheduleID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object: Table [dbo].[LockedDates] Script Date: 04/24/2013 21:35:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[LockedDates](
[LockedDateID] [int] IDENTITY(1,1) NOT NULL,
[Date] [datetime] NOT NULL,
[IsYearly] [bit] NOT NULL,
[EmployeeID] [int] NULL,
CONSTRAINT [PK_dbo.LockedDates] PRIMARY KEY CLUSTERED
(
[LockedDateID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object: Table [dbo].[EmployeGroupFilters] Script Date: 04/24/2013 21:35:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[EmployeGroupFilters](
[EmployeGroupFilterID] [int] IDENTITY(1,1) NOT NULL,
[EmployeID] [int] NOT NULL,
[GroupID] [int] NOT NULL,
CONSTRAINT [PK_dbo.EmployeGroupFilters] PRIMARY KEY CLUSTERED
(
[EmployeGroupFilterID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object: Table [dbo].[Project] Script Date: 04/24/2013 21:35:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Project](
[ProjectID] [int] IDENTITY(1,1) NOT NULL,
[ProjectTitle] [varchar](max) NOT NULL,
[ProjectDescription] [varchar](max) NOT NULL,
[ScheduleID] [int] NULL,
[EstimatedHours] [decimal](10, 2) NULL,
[IsRetired] [bit] NULL,
[Color] [int] NULL,
[PaymoID] [int] NULL,
CONSTRAINT [PK_dbo.Project] PRIMARY KEY CLUSTERED
(
[ProjectID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object: Table [dbo].[Cases] Script Date: 04/24/2013 21:35:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Cases](
[CaseID] [int] IDENTITY(1,1) NOT NULL,
[CaseTitle] [varchar](max) NOT NULL,
[CaseDescription] [varchar](max) NOT NULL,
[CustomerID] [int] NOT NULL,
[ScheduleID] [int] NULL,
[EstimatedHours] [decimal](10, 2) NULL,
[StatusID] [int] NULL,
[Color] [int] NULL,
[CRMID] [varchar](50) NULL,
CONSTRAINT [PK_dbo.Cases] PRIMARY KEY CLUSTERED
(
[CaseID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object: Table [dbo].[Task] Script Date: 04/24/2013 21:35:08 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Task](
[TaskID] [int] IDENTITY(1,1) NOT NULL,
[TaskTitle] [varchar](max) NOT NULL,
[TaskDescription] [varchar](max) NOT NULL,
[ProjectID] [int] NULL,
[ScheduleID] [int] NULL,
[PaymoID] [int] NULL,
[ParentScheduleID] [int] NULL,
[IsUnscheduelable] [bit] NULL,
[EstimatedHours] [decimal](10, 2) NULL,
[PaymoUser] [varchar](max) NULL,
[PaymoOrder] [int] NULL,
[PaymoEstimateHours] [decimal](10, 2) NULL,
CONSTRAINT [PK_dbo.Task] PRIMARY KEY CLUSTERED
(
[TaskID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
/****** Object: ForeignKey [Customer_Case] Script Date: 04/24/2013 21:35:08 ******/
ALTER TABLE [dbo].[Cases] WITH CHECK ADD CONSTRAINT [Customer_Case] FOREIGN KEY([CustomerID])
REFERENCES [dbo].[Customers] ([CustomerID])
GO
ALTER TABLE [dbo].[Cases] CHECK CONSTRAINT [Customer_Case]
GO
/****** Object: ForeignKey [Schedule_Case] Script Date: 04/24/2013 21:35:08 ******/
ALTER TABLE [dbo].[Cases] WITH CHECK ADD CONSTRAINT [Schedule_Case] FOREIGN KEY([ScheduleID])
REFERENCES [dbo].[Schedule] ([ScheduleID])
GO
ALTER TABLE [dbo].[Cases] CHECK CONSTRAINT [Schedule_Case]
GO
/****** Object: ForeignKey [Status_Case] Script Date: 04/24/2013 21:35:08 ******/
ALTER TABLE [dbo].[Cases] WITH CHECK ADD CONSTRAINT [Status_Case] FOREIGN KEY([StatusID])
REFERENCES [dbo].[Statuses] ([StatusID])
GO
ALTER TABLE [dbo].[Cases] CHECK CONSTRAINT [Status_Case]
GO
/****** Object: ForeignKey [Group_Employee] Script Date: 04/24/2013 21:35:08 ******/
ALTER TABLE [dbo].[Employee] WITH CHECK ADD CONSTRAINT [Group_Employee] FOREIGN KEY([GroupID])
REFERENCES [dbo].[Group] ([GroupID])
GO
ALTER TABLE [dbo].[Employee] CHECK CONSTRAINT [Group_Employee]
GO
/****** Object: ForeignKey [Employee_EmployeGroupFilter] Script Date: 04/24/2013 21:35:08 ******/
ALTER TABLE [dbo].[EmployeGroupFilters] WITH CHECK ADD CONSTRAINT [Employee_EmployeGroupFilter] FOREIGN KEY([EmployeID])
REFERENCES [dbo].[Employee] ([EmployeID])
GO
ALTER TABLE [dbo].[EmployeGroupFilters] CHECK CONSTRAINT [Employee_EmployeGroupFilter]
GO
/****** Object: ForeignKey [Group_EmployeGroupFilter] Script Date: 04/24/2013 21:35:08 ******/
ALTER TABLE [dbo].[EmployeGroupFilters] WITH CHECK ADD CONSTRAINT [Group_EmployeGroupFilter] FOREIGN KEY([GroupID])
REFERENCES [dbo].[Group] ([GroupID])
GO
ALTER TABLE [dbo].[EmployeGroupFilters] CHECK CONSTRAINT [Group_EmployeGroupFilter]
GO
/****** Object: ForeignKey [Employee_LockedDate] Script Date: 04/24/2013 21:35:08 ******/
ALTER TABLE [dbo].[LockedDates] WITH CHECK ADD CONSTRAINT [Employee_LockedDate] FOREIGN KEY([EmployeeID])
REFERENCES [dbo].[Employee] ([EmployeID])
GO
ALTER TABLE [dbo].[LockedDates] CHECK CONSTRAINT [Employee_LockedDate]
GO
/****** Object: ForeignKey [Schedule_Project] Script Date: 04/24/2013 21:35:08 ******/
ALTER TABLE [dbo].[Project] WITH CHECK ADD CONSTRAINT [Schedule_Project] FOREIGN KEY([ScheduleID])
REFERENCES [dbo].[Schedule] ([ScheduleID])
GO
ALTER TABLE [dbo].[Project] CHECK CONSTRAINT [Schedule_Project]
GO
/****** Object: ForeignKey [Employee_Schedule] Script Date: 04/24/2013 21:35:08 ******/
ALTER TABLE [dbo].[Schedule] WITH CHECK ADD CONSTRAINT [Employee_Schedule] FOREIGN KEY([EmployeID])
REFERENCES [dbo].[Employee] ([EmployeID])
GO
ALTER TABLE [dbo].[Schedule] CHECK CONSTRAINT [Employee_Schedule]
GO
/****** Object: ForeignKey [Recurring_Schedule] Script Date: 04/24/2013 21:35:08 ******/
ALTER TABLE [dbo].[Schedule] WITH CHECK ADD CONSTRAINT [Recurring_Schedule] FOREIGN KEY([RecurringID])
REFERENCES [dbo].[Recurring] ([RecurringID])
GO
ALTER TABLE [dbo].[Schedule] CHECK CONSTRAINT [Recurring_Schedule]
GO
/****** Object: ForeignKey [Project_Task] Script Date: 04/24/2013 21:35:08 ******/
ALTER TABLE [dbo].[Task] WITH CHECK ADD CONSTRAINT [Project_Task] FOREIGN KEY([ProjectID])
REFERENCES [dbo].[Project] ([ProjectID])
GO
ALTER TABLE [dbo].[Task] CHECK CONSTRAINT [Project_Task]
GO
/****** Object: ForeignKey [Schedule_Task] Script Date: 04/24/2013 21:35:08 ******/
ALTER TABLE [dbo].[Task] WITH CHECK ADD CONSTRAINT [Schedule_Task] FOREIGN KEY([ScheduleID])
REFERENCES [dbo].[Schedule] ([ScheduleID])
GO
ALTER TABLE [dbo].[Task] CHECK CONSTRAINT [Schedule_Task]
GO
/****** Object: ForeignKey [Schedule_Task1] Script Date: 04/24/2013 21:35:08 ******/
ALTER TABLE [dbo].[Task] WITH CHECK ADD CONSTRAINT [Schedule_Task1] FOREIGN KEY([ParentScheduleID])
REFERENCES [dbo].[Schedule] ([ScheduleID])
GO
ALTER TABLE [dbo].[Task] CHECK CONSTRAINT [Schedule_Task1]
GO
I have the drops in there because the database might already be setup in which case I want a fresh copy.
I get:
An exception occurred while executing a Transact-SQL statement or batch.
Is there anything wrong with what I am doing? I got the script from generating it with SQL Server.
I just want it to:
1. Clear any tables, just empty the db.
2. Create the tables and foreign keys.
Thanks
A:
It fails because the GO word is not recognized when you pass the full script as a simple string to ExecuteNonQuery. However, the overload of ExecuteNonQuery that takes a StringCollection object is stated that accepts a script separated by the GO
I will try in this way: (Not tested)
StringCollection col = new StringCollection();
col.Add(script);
server.ConnectionContext.ExecuteNonQuery(col);
if this doesn't work then the only workaround that comes to mind is
string goSplitter = new string[] { "\r\nGO\r\n" };
string[] cmdParts = script.Split(goSplitter, StringSplitOptions.RemoveEmptyEntries);
StringCollection col = new StringCollection();
col.AddRange(cmdParts);
server.ConnectionContext.ExecuteNonQuery(col);
UPDATE
I have tested a small part of your script agains a database of mine with the code you have provided, and contrary to what is my understanding of the documentation about ExecuteNonQuery with a single string, it has worked as expected. So it is possible that you have some syntax error or other problem in the whole script. I suggest to test it inside the Sql Management Studio console
UPDATE 2
Now I was really curious, so I fired up Reflector to investigate the code of ExecuteNonQuery and now the mistery is solved. These are the first decompiled lines of the method that gets a single string.
public int ExecuteNonQuery(string sqlCommand, ExecutionTypes executionType)
{
int num6;
this.CheckDisconnected();
int statementsToReverse = 0;
int num2 = 0;
StringCollection strings = this.GetStatements(sqlCommand, executionType, ref statementsToReverse);
........
So the single string is passed to an internal method called GetStatements that return a StringCollection
| {
"pile_set_name": "StackExchange"
} |
Q:
Do I need to update constraints after I change the position of a UIImageView
I am new to ios and have a UIImageView within my viewController that have constraints on it. I am also using autolayout for this app. Under a certain condition, I allow the user to move the imageView using the Pan Gesture. Do I need to update the constraints for that image after it is moved? Should I update the constraints after it is moved if it isn't necessary? And if yes for either of those, what is the most efficient way to update the constraints?
A:
You should move the imageView by updating its constraints, and not by changing its frame.
An easy way to do this is to position by the image view with two constraints, one that gives it an offset from the top of its superview, and one that gives it an offset from the leading edge of its superview.
Then you can create IBOutlets to these constraints by Control-dragging from the constraints in the Document Outline view to your ViewController, then you just update the constant in the constraints in your Pan Gesture handler.
| {
"pile_set_name": "StackExchange"
} |
Q:
python: how can I double left click to get a point in python
I have a map ,and now I want to double left click to zoom-in the map and left click to get a point.How should I do? I know 'ginput' command but it seems can't work with double-left-click.
latsize=[39,45]
lonsize=[-72.,-66]
plt.figure(figsize=(7,6))
m = Basemap(projection='cyl',llcrnrlat=min(latsize)-0.01,urcrnrlat=max(latsize)+0.01,\
llcrnrlon=min(lonsize)-0.01,urcrnrlon=max(lonsize)+0.01,resolution='h')#,fix_aspect=False)
m.drawparallels(np.arange(int(min(latsize)),int(max(latsize))+1,1),labels=[1,0,0,0])
m.drawmeridians(np.arange(int(min(lonsize)),int(max(lonsize))+1,1),labels=[0,0,0,1])
plt.show()
A:
I'm assuming you're using matplotlib? You have to register an event handler for mouse events. All the information you need can be found here:
Event handling and picking
Look at handling button_press_event or button_release_event. If you follow the link for the MouseEvent class, you'll see it has a boolean double click indicator dblclick.
MouseEvent
Here is a bare-bones example:
import matplotlib.pyplot as plt
def handle_mouse_press( event ):
if event.dblclick:
print "Can haz dblclikz???"
fig = plt.figure()
fig.add_subplot(111)
fig.canvas.mpl_connect('button_press_event', handle_mouse_press)
plt.show()
| {
"pile_set_name": "StackExchange"
} |
Q:
C++ extract .reg file to registry
Can anyone tell me please how to extract the data from a .reg file into the registry?
I've tried:
system("regedit /s product.reg");
It doesn't work, I have also looked at various other questions on here but have had no joy and I have also trouble understanding them.
Can anyone shed any light or send me a link that has a good example please?
Thanks
A:
The following things applies to Windows Vista / Windows 7 and later version.
You won't be able to successfully execute regedit.exe unless your application is not running with Administrator privilege.
If you're using Visual Studio 2005/2008/2010, go to the property window of your project, expand the 'Linker' options, and select 'Manifest File'. Change UAC Execution Level to 'requireAministrator'. Save your project and rebuild your project.
| {
"pile_set_name": "StackExchange"
} |
Q:
MVC in PHP without the "magic"
Let's say I have a PHP Model-View-Controller framework that maps an address like http://example.com/admin/posts/edit/5 to an action that looks like
Posts_Controller::editAction($id)
in file /admin/controllers/posts.php
Now, many existing PHP frameworks that I've looked at would accomplish this by something similar to
$module = Router::getModule(); // "admin"
$controller = Router::getController(); // "posts"
$action = Router::getAction(); // "edit"
$params = Router::getParams(); // array(5)
$controller_file = "/".$module."/controllers/".$controller.".php";
$controller_classname = ucfirst($controller)."_Controller";
$method = $action."Action";
require_once $controller_file;
$controller_obj = new $controller_classname();
call_user_func_array(array($controller_obj,$method),$params);
To me, this smells bad and seems too "magical": I don't believe that you should be able to dynamically create classes based off of a string, then call methods on it specified as strings.
I have also seen alternatives that use reflection to call actions, which also smells bad.
Now imagine I have a larger, modular CMS built off of a similar MVC framework that has a table in the DB for each "page" type: blog, static, photo-album, etc... I imagine that the implementation for this is similar to my previous example.
Am I the only one who thinks this is bad? If not, shouldn't there be a design pattern that would cover this situation?
To Clarify:
Is there some good way to map a query containing information about module, controller, action, and parameters into
A file to include
A class to instantiate
A method to call'
That uses as little "magic" (string-to-class or -to-method or reflection) as possible?
Even better: how would this be done in C# or Java, without reflection? I can allow for concatenating strings to arrive at a file location.
A:
This would be handled by some sort of factory pattern, PHP just makes some nice syntactic sugar to avoid all the implementation around the factory pattern. I don't think this is magic at all, it's just leveraging the language.
A:
There are, in fact, two questions here.
Is PHP as a language used properly here.
Is the logic of this code too "magical"
I can give my view on it as a PHP developer and software engineer involved in development of web applications mostly based on some MVC framework
1) Every language comes with its own syntax that provides more or less expressiveness. I agree that all the power of one language should not be used on every line of code for the sake of readability and simplicity. But in this case, where core of the MVC is designed and implemented I see no reason not to use them especially on the places where end user (application developer in this sense) doesn't see this magic if it is well encapsulated.
I presume this is a simplified and stripped off snippet you posted since there should be some other considerations regarding its design, but creating new instance based on a string name, and calling a function the same way is regular approach in PHP world.
2) I agree that this code is logic wise somewhat magical, especially because it probably provides the promise of generality to the developer. There are different approaches regarding this, that in most times reduce generality of the solution and provide some means of direct definition of the mapping through command map or similar approach (DB for example as you said). This way magic is under the hands of the developer. This, in general, is not suitable for rapid development since there is a lot of manual work in setting the mappings that are by router magic in your case automagically resolved.
Hope it helps a bit.
Cheers,
Ivan
| {
"pile_set_name": "StackExchange"
} |
Q:
How to create a global bidimensional array whose size is only defined at runtime in c (or how to pass arguments to drawing functions in opengl)?
I want to create a bidimensional array that represents the positions of a board game. I've defined that each position is of type 'struct position' which is a enum that can be 'empty', 'piece1' or 'piece2'. The problem is that the user decides which size the table is, that is, how many positions the bidimensional array will have. Since I'm calling graphic functions of opengl which can't take arguments (or is there a way for them to do that?), is it possible to define the size of the bidimensional array at runtime?
A:
No, you can't define the size of an array at run-time in C. But one-dimensional arrays have the same semantics as pointers, so you can "emulate" a multi-dimensional by using pointers instead. Something like this should do the trick:
int w = 16, h = 16;
int *array = malloc(sizeof(int) * w * h);
int x = 4, y = 2;
array[y * w + x] = 1;
| {
"pile_set_name": "StackExchange"
} |
Q:
Users cannot logout because session is not deleted
I am using the core users component. Users after logging in are not able to logout, the logout button simple refreshes the page.
Joomla is not deleting entries from the _session table when a user logs out.
I have disabled extra registration plugins and also changed the session handler and ssl configuration without success. I've been clearing, optimizing and repairing session table.
Any one have ever heard or experienced this problem and can get me a clue?
A:
Just some thoughts:
This could be caused by adding some custom login/logout - Module and then deactivate it without changing the module on frontend back to joomla standard login/logout-Module. If the logout-Button doesnt log the user out, first check if it´s an issue with the logout-module or logout-menuitem. It´s probably not assigned to any Module/Komponent.
Try to add a new (eg hidden) menu-item "user manager"->"Login Form". It should have this link: index.php?option=com_users&view=login (Standard Joomla component). And try to login/logout through that page.
Try to add a new Module: "Module Manager-> Module Login" (Standard Joomla Module). And test with that.
Disable cache in "System->Konfiguration->System->Cache->OFF" while testing and clear cache.
Make sure that all the necessary User-Extensions are published: Eg. "Extensions->Manage->Filter: Select Folder Users->User - Joomla!" Can be deactivated
| {
"pile_set_name": "StackExchange"
} |
Q:
FinderにGitステータスを表示する方法
AtomやIDEだと、ファイルのGit状況をツリービューで表示してくれて便利です。同様の機能をFinderで提供するものってないのでしょうか? イメージとしては、Dropboxのファイルバッジみたいなのが理想的です。
StackOverflow(英語版)だと、PathFinderが回答に上がっていますが、別アプリケーションではなくFinderでできるのが望ましいです。
A:
アプリの信頼度とかは全く不明ですが、Finder BoostというのでGitのStatusを表示出来るようです。
http://hobbyistsoftware.com/finderBoost
| {
"pile_set_name": "StackExchange"
} |
Q:
Properly Declaring a Multi-Dimensional Array of Type int in Java
I've looked all around stackoverflow, and have found multiple answers to defining a multiple dimensional array in Java. Heck I even looked back some of my older code and found similar examples with doubles, but for some reason when utilizing the code out of those examples as well as my own code, I'm getting errors in both Eclipse and IntelliJ like the following:
The following does not give me the above error:
public class foo
{
private int[][] bar()
{
int[][] test = new int[10][];
test[0] = new int[100];
test[1] = new int[500];
}
}
The following gives me the above error:
public class foo
{
int[][] test = new int[10][];
test[0] = new int[100];
test[1] = new int[500];
}
Syntax error on token ";", { expected after this token (for the first line)
Syntax error on token(s), misplaced construct(s) (for the second line)
I'm using this to solve problem 28 on Project Euler.
A:
I guess you placed your code directly in a class. You need to put it inside a method of a class, like this:
public class Snippet {
public static void main(String[] args) {
int[][] test = new int[10][];
test[0] = new int[100];
test[1] = new int[500];
}
}
Or you could use a static initializer:
public class Snippet {
static int[][] test = new int[10][];
static {
test[0] = new int[100];
test[1] = new int[500];
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
I need to use multiple response.redirect in ASP.NET using C#
I'm writing a school program and I'm trying to move 3 input fields to a new page.
I can get the response.redirect to work on one field but not more.
When I click the button it takes me to the next page and only one field is brought over. Not the 3 that I'm trying to get there.
Can anyone steer my right? Thanks in advance...
Page one:
protected void btnEnterSelection_Click(object sender, EventArgs e)
{
lblBookEntered.Visible = true;
lblBookType.Visible = true;
lblPurchaseType.Visible = true;
lblBookEnteredText.Visible = true;
lblBookTypeText.Visible = true;
lblPurchaseTypeText.Visible = true;
lblBookEntered.Text = "The book you entered is: ";
lblBookEnteredText.Text = txtBoxBookTitle.Text;
lblBookType.Text = "The book type is: ";
lblBookTypeText.Text = drpDownType.Text;
lblPurchaseType.Text = "The purchase type is: ";
lblPurchaseTypeText.Text = drpDownPurchase.Text;
}
protected void btnPurchase_Click(object sender, EventArgs e)
{
Response.Redirect("turtleDoxPurchase.aspx?bookName=" + txtBoxBookTitle.Text);
Response.Redirect("turtleDoxPurchase.aspx?bookType=" + drpDownType.Text);
Response.Redirect("turtleDoxPurchase.aspx?purchaseType=" + drpDownPurchase.Text);
}
Page two:
protected void Page_Load(object sender, EventArgs e)
{
lblBookEntered.Visible = true;
lblBookType.Visible = true;
lblPurchaseType.Visible = true;
lblBookEnteredText.Visible = true;
lblBookTypeText.Visible = true;
lblPurchaseTypeText.Visible = true;
lblBookEntered.Text = "The book you entered is: ";
lblBookEnteredText.Text = Request.QueryString["bookName"];
lblBookType.Text = "The book type is: ";
lblBookTypeText.Text = Request.QueryString["bookType"];
lblPurchaseType.Text = "The purchase type is: ";
lblPurchaseTypeText.Text = Request.QueryString["purchaseType"];
lblCreditCard.Visible = true;
txtBoxCreditCard.Visible = true;
lblCreditCardChoice.Visible = true;
rdoListCreditCard.Visible = true;
btnSubmitPayment.Visible = true;
}
A:
If I understand the problem correctly, you are trying to send three values from Page One to Page Two. In that case, you could build a Query string using the values from txtBoxBookTitle, drpDownType and DrpDownPurchase. The string should be in the follwing format:
string queryString = "?bookName={txtBoxBookTitle}&bookType={drpDownType.Value}&purchaseType={DrpDownPurchase.Value}"
Then you could append the above string to your
Response.Redirect("turtleDoxPurchase.aspx" + queryString);
Hope that helps!
| {
"pile_set_name": "StackExchange"
} |
Q:
Checking Output Errors in C and C++
I wrote this simple program. I know that the printf() function in C returns the total number of characters successfully printed so the following C program works fine because any non-zero value is evaluated as true in C.
#include <stdio.h>
int main(void)
{
if (printf("C"))
return 0;
}
But why does the following C++ program compiles & runs fine? If cout is an object not a function, then why is the program giving the expected output?
#include <iostream>
using namespace std;
int main() {
if (cout << "C++")
// your code goes here
return 0;
}
A:
std::cout << "C++";
is a function call to std::operator<<(std::cout, const char*) which returns a reference to std::cout which is convertible to bool. It will evaluate to true if no error on std::cout occurred.
| {
"pile_set_name": "StackExchange"
} |
Q:
Perl regex issue , last character truncated
Have a strange issue with my regex.
My regex is truncating the last character , in the example below it should return the value 32 but it is instead returning 3.
Note that the value could be up to 10 digits!!!
$word = "thisisit=";
$line = "hello thisisit=32 byefornow ";
if ($line =~ m/$word(.*?)\d /)
{
print $1; #returns 3 instead of 32
}
Thanks.
A:
You can do:
if ($line =~ /$word(\d+)/) # This will capture all numbers after your $word
{
print $1;
}
You can also refine to:
if ($line =~ /$word\s*(\d+)/) # In case you're having like "thisisit= 32 byefornow"
Or, to capture everything and stop after first white space:
if ($line =~ /$word(.+?)\s/)
{
print $1;
}
| {
"pile_set_name": "StackExchange"
} |
Q:
How to export solr result into a text file?
I needs to export doc_id, all fields, socr, rank of one search result to evaluate the results. How can I do this in solr?
A:
Solr provides you with a CSV Response writer, which will help you to export the results of solr in an csv file.
http://localhost:8983/solr/select?q=ipod&fl=id,cat,name,popularity,price,score&wt=csv
All the fields queried would be returned by Solr in proper format.
A:
This has nothing to do with SOLR. When you make a SOLR query over http, then SOLR does the search and returns the results to you in your desired format. The default is XML but lots of people specify wt=json to get results in json format. If you want this result in a text file, then make your search client put it there.
In the browser, File -> Save As.
But most people who want this use curl as the client and use the -o option like this:
curl -o result1.xml 'http://solr.local:8080/solr/stuff/select?indent=on&version=2.2&q=fish&fq=&start=0&rows=10&fl=*%2Cscore&qt=&wt=&explainOther=&hl.fl='
Note the single quotes around the URL due to the use of & characters.
| {
"pile_set_name": "StackExchange"
} |
Q:
ruby simple substitutions
very new to Ruby, I've got the following situation. I have a file with values separated by new lines, they look like this:
18917
18927
18929
...
I want to prepend a folder path to all of them, then grab the first 2 characters and prepend that as well, then the value in the file and then append a '.jpg' at the end so they would end up looking like this:
path/to/foler/18/18917.jpg
So I've code this ruby code:
folder = "/path/to/folder"
lines = File.readlines("values.csv")
images = lines.collect.to_s.gsub("\n", ".jpg,")
images.split(',').collect { |dogtag | puts "bad dog: #{folder}/#{dogtag[0,2]}/#{dogtag}" }
Now, this almost works, the part that is not working is the grabbing of the first 2 characters. I also tried it with the method outside quotes (and without the #{} of course) but it just produces an empty result.
Could someone please point out my folly?
Eventually I want to delete those images but I'm guessing that substituting 'File.delete' for 'puts' above would do the trick?
As usual, thanks in advance for taking the time to look at this.
A:
You don't seem to be understanding what collect does.
I would rewrite your snippet like this:
File.read("values.csv").each do |line|
puts "bad dog: /path/to/folder/#{line[0,2]}/#{line.chomp}.jpg"
end
-- Update for last comment: --
If you don't want to use an if statement to check if a file exists before deleting it, you have two option (AFAIK).
Use rescue:
File.read("values.csv").each do |line|
begin
File.delete "/path/to/folder/#{line[0,2]}/#{line.chomp}.jpg"
rescue Errno::ENOENT
next
end
end
Or extend the File class with a delete_if_exists method. You can just put this at the top of your script:
class File
def self.delete_if_exists(f)
if exists?(f)
delete(f)
end
end
end
With this, you can do:
File.read("values.csv").each do |line|
File.delete_if_exists "/path/to/folder/#{line[0,2]}/#{line.chomp}.jpg"
end
| {
"pile_set_name": "StackExchange"
} |
Q:
Kotlin typed->Any->typed
I'm tying to understand that if in Kotlin there is a way to do this:
interface EnumClassX {
...
}
enum class EnumClassA: EnumClassX {
...
}
enum class EnumClassB: EnumClassX {
...
}
enum class EnumClassC: EnumClassX {
...
}
object Foo {
fun bar(enumClassA: EnumClassA) {
...
}
fun bar(enumClassB: EnumClassB) {
...
}
fun bar(enumClassC: EnumClassC) {
...
}
}
class Middle {
fun callFooBar(enumClass: EnumClassX) {
// What I have to do:
when(enumClass){
is EnumClassA -> {
Foo.bar(enumClass) // Note I don't even have to say "enumClass as EnumClassA" b/c it is already inside an "is" block.
}
is EnumClassB -> {
Foo.bar(enumClass)
}
is EnumClassC -> {
Foo.bar(enumClass)
}
}
// What I want to do:
Foo.bar(enumClass) // IDE says "None of the following functions can be called without the arguments supplied." Compiler can't figure out which flavor of enumClass has been passed in to call the appropriate bar.
}
}
Easily fixed with other simple inspection and switches as in the top example but was hoping there was a way to make it direct traffic accordingly? By that I mean that Middle.callFooBar is always called with one of the three types that have individual bar methods and just wondering if there is a way in Kotlin to make it call the right one without manually inspecting the type of enumClass.
Thanks!
Scott
A:
It's not possible, because you're using a static dispatch.
Statement
// callFooBar may be called with type CustomObjectA, CustomObjectB, or
CustomObjectC
Is actually incorrect. The way compiler sees it, your method may be invoked with instance of any class, not only those three classes.
To use dynamic dispatch, you'll need to resort to old good inheritance. I know, inheritance is not cool nowadays, but your case is exactly what it's for:
interface EnumClassX {
fun bar()
}
class EnumClassA : EnumClassX {
override fun bar() { }
}
class EnumClassB : EnumClassX {
override fun bar() { }
}
class EnumClassC : EnumClassX {
override fun bar() { }
}
Theoretically, your code also should have worked with sealed classes (not enums, those are different):
sealed class EnumClassX {
abstract fun bar()
}
class EnumClassA : EnumClassX() {
override fun bar() { }
}
class EnumClassB : EnumClassX() {
override fun bar() { }
}
class EnumClassC : EnumClassX() {
override fun bar() { }
}
But it doesn't. My guess is that's simply because Kotlin team didn't want to complicate compiler further, but maybe I'm just missing some use case. Feel free to ask about why's that on discuss.kotlinlang.org
| {
"pile_set_name": "StackExchange"
} |
Q:
D-Bus method not found at object path despite the fact that method exist
I implement an app with this com.example.appname.desktop file as follows:
$ cat /usr/local/share/applications/com.example.appname.desktop
[Desktop Entry]
Version=1.0
Terminal=false
Type=Application
Name=appname
Exec=/opt/app/appname %u
DBusActivatable=true
Categories=Network;
MimeType=x-scheme-handler/itmm;
NoDisplay=false
$ cat /usr/share/dbus-1/services/com.example.appname.service
[D-BUS Service]
Name=com.example.appname
Exec=/opt/app/appname
Introspection XML looks like this:
$ qdbus com.example.appname /com/example/appname org.freedesktop.DBus.Introspectable.Introspect
<!DOCTYPE node PUBLIC "-//freedesktop//DTD D-BUS Object Introspection 1.0//EN"
"http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd">
<node>
<interface name="org.freedesktop.Application">
<method name="ActivateAction">
<arg name="action_name" type="s" direction="in"/>
<arg name="parameter" type="av" direction="in"/>
<arg name="platform_data" type="a{sv}" direction="in"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.In2" value="QVariantMap"/>
</method>
<method name="Activate">
<arg name="platform_data" type="a{sv}" direction="in"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.In0" value="QVariantMap"/>
</method>
<method name="Open">
<arg name="uris" type="as" direction="in"/>
<arg name="platform_data" type="a{sv}" direction="in"/>
<annotation name="org.qtproject.QtDBus.QtTypeName.In1" value="QVariantMap"/>
</method>
</interface>
<interface name="org.freedesktop.DBus.Properties">
<method name="Get">
<arg name="interface_name" type="s" direction="in"/>
<arg name="property_name" type="s" direction="in"/>
<arg name="value" type="v" direction="out"/>
</method>
----<snipped>-----
But when i try to launch the method it gives me an error:
$ gapplication launch com.example.appname
error sending Activate message to application: GDBus.Error:org.freedesktop.DBus.Error.UnknownMethod: No such method 'Activate' in interface 'org.freedesktop.Application' at object path '/com/example/appname' (signature 'a{sv}')
Is "annotation name=.." XML tag (see introspection XML) the reason this method is not found?
Browsing to itmm://192.168.1.1/query?version=1.0 via browser launches the application with command line parameter, but it is not launched via D-Bus service and thats what my requirement is. Is there a way to debug this via firefox or google chrome browsers?
A:
I use QT's D-Bus binding to implement D-Bus service. My issue were
My class that implemented D-Bus interface was not inheriting QDBusAbstractAdaptor .
Methods to be exported were not marked as public slots
My original class looked like this below:
class DBusService : public Application
{
QOBJECT
Q_CLASSINFO("D-Bus Interface", "org.freedesktop.Application")
public:
void Activate(QMap<QString, QVariant> platform_data)
{
Q_UNUSED(platform_data);
}
void Open(QStringList uris, QMap<QString, QVariant> platform_data)
{
Q_UNUSED(platform_data);
if( ! uris.size() ) {
return;
}
QUrl url(uris[0]);
//use url
}
}
Following one works:
class DBusService : public QDBusAbstractAdaptor //<----- Inherit from this class
{
QOBJECT
Q_CLASSINFO("D-Bus Interface", "org.freedesktop.Application")
public slots: // <------ mark public slots
void Activate(QMap<QString, QVariant> platform_data)
{
Q_UNUSED(platform_data);
}
void Open(QStringList uris, QMap<QString, QVariant> platform_data)
{
Q_UNUSED(platform_data);
if( ! uris.size() ) {
return;
}
QUrl url(uris[0]);
qApp->MyCustomMethod(url);
}
}
D-Bus debugging tools
These tools helped me debugging D-Bus issues.
dbus-monitor - sniffs traffic on the bus
gapplication - lets you debug DBusActivatable services.
| {
"pile_set_name": "StackExchange"
} |
Q:
FIXED: File wont upload, thinking its to do with buffering?
Ive been building a rather large image manipulation website using php / imagick, and for a long time ive had a function working that would upload posted files to the server. It has now decided (6 hours before due) that it doesn't want to accept any more uploads.
I'm thinking it has got something to do with output buffering or file caching of some description at the server side (I really dont know much about these). I've checked that the input types and formats are all the same as what they have been normally, and yet no dice.
Furthermore, I even went back and tried to create a very basic upload page just to test that, and even it doesn't work. Code below is for the basic upload page, i dont think theres anything wrong with it.
HTML:
<form action="" method="POST" enctype="multipart/form-data" >
<div class="">
<input type="text" name="title" /><br />
<input type="text" name="album" /><br />
<textarea cols="40" name="description" ></textarea><br />
</div>
<img class='' src='images/assets/upload/browse.png' /><br />
<input class='' type="file" name="image" value="" />
<input class ="" type="submit" name="upload" value="" />
PHP
<?php
//include 'includes/beginpage.php';
//include 'methods/usermethods.php';
if(isset($_POST['submit'])){
// Example of accessing data for a newly uploaded file
$fileName = $_FILES["file"]["name"];
$fileTmpLoc = $_FILES["file"]["tmp_name"];
// Path and file name
$pathAndName = "Users/".$fileName;
// Run the move_uploaded_file() function here
$moveResult = move_uploaded_file($fileTmpLoc, $pathAndName);
// Evaluate the value returned from the function if needed
if ($moveResult == true) {
echo "File has been moved from " . $fileTmpLoc . " to" . $pathAndName;
} else {
echo "ERROR: File not moved correctly";
}
}
?>
I'd greatly appreciate any help anyone can give me.
Cheers,
Sean
EDIT:
Turns out somehow it has to do with access permissions when creating folders on linux. Ill look into it later, but have just got a temp measure in place for now - create the folders manually.
Thankyou to Michael W for such quick response, helping me find those server logs helped me find the problem
A:
Upon checking the error logs on my server I saw a few lines that referred to an Imagick error. After about 5 minutes on Google the general idea seemed to be that Imagick was restricted from accessing a resource. In my case, the resource didn't actually exist.
I needed to fix some code elsewhere regarding the creating of a directory in the root location on the server for those site files, using the whole 'umask' workaround. I tested and got the site to work correctly with the mkdir() method, tried again and it all worked perfectly. Thanks again to Mike W for the hint on the server logs, I wouldn't have even thought to check there!
| {
"pile_set_name": "StackExchange"
} |
Q:
Fastest execution time for querying on Big size table
i need advice how to get fastest result for querying on big size table.
I am using SQL Server 2012, my condition is like this:
I have 5 tables contains transaction record, each table has 35 millions of records.
All tables has 14 columns, the columns i need to search is GroupName, CustomerName, and NoRegistration. And I have a view that contains 5 of all these tables.
The GroupName, CustomerName, and NoRegistration records is not unique each tables.
My application have a function to search to these column.
The query is like this:
Search by Group Name:
SELECT DISTINCT(GroupName) FROM TransactionRecords_view WHERE GroupName LIKE ''+@GroupName+'%'
Search by Name:
SELECT DISTINCT(CustomerName) AS 'CustomerName' FROM TransactionRecords_view WHERE CustomerName LIKE ''+@Name+'%'
Search by NoRegistration:
SELECT DISTINCT(NoRegistration) FROM TransactionRecords_view WHERE LOWER(NoRegistration) LIKE LOWER(@NoRegistration)+'%'
My question is how can i achieve fastest execution time for searching?
With my condition right now, every time i search, it took 3 to 5 minutes.
My idea is to make a new tables contains the distinct of GroupName, CustomerName, and NoRegistration from all 5 tables.
Is my idea is make execution time is faster? or any other idea?
Thank you
EDIT:
This is query for view "TransactionRecords_view"
CREATE VIEW TransactionRecords_view
AS
SELECT * FROM TransactionRecords_1507
UNION ALL
SELECT * FROM TransactionRecords_1506
UNION ALL
SELECT * FROM TransactionRecords_1505
UNION ALL
SELECT * FROM TransactionRecords_1504
UNION ALL
SELECT * FROM TransactionRecords_1503
A:
You must show sql of TransactionRecords_view. Do you have indexes? What is the collation of NoRegistration column? Paste the Actual Execution Plan for each query.
A:
Ok, so you don't need to make those new tables. If you create Non-Clustered indexes based upon these fields it will (in effect) do what you're after. The index will only store data on the columns that you indicate, not the whole table. Be aware, however, that indexes are excellent to aid in SELECT statements but will negatively affect any write statements (INSERT, UPDATE etc).
Next you want to run the queries with the actual execution plan switched on. This will show you how the optimizer has decided to run each query (in the back end). Are there any particular issues here, are any of the steps taking up a lot of the overall operator cost? There are plenty of great instructional videos about execution plans on youtube, check them out if you haven't looked at exe plans before.
| {
"pile_set_name": "StackExchange"
} |
Q:
ReactJS components for PDF export, Excel export and print
I´m building some ReactJS Table and Report components tha basically will contain <table> data, some graphics (d3) and some textual data. I need to provide 3 buttons:
Export to PDF
Export to Excel
Print
Are there any trustable packages available for the tasks above using ReactJS ? What is the approach to handle these requirements ?
A:
I would use a combination of the following JavaScript libraries:
React Csv is my favourite JavaScript library for working with csv. It excels at dynamic generation.
PDF Make is my favourite JavaScript library for generating PDFs.
Note: I would attach the files to this post, but there is currently no facility for this in StackOverflow.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to register aliased class as global class
/Core/Api.php
<?php namespace Core;
class Api
{
//
}
start.php
<?php
include 'vendor/autoload.php'
index.php
<?php
include 'start.php';
use Core\Api as Api;
new Api // it's work
start.php
<?php
include 'vendor/autoload.php'
use Core\Api as Api;
index.php
<?php
include 'start.php';
new Api; // Fatal error: Class 'Api' not found
There are many tool class will be used in many places, how to alias it as once in some file and let other file can use the aliased name directly?
A:
use works inside current namespace (for a whole file in most cases) only.
You could create empty class to inheritance target class.
<?php
class Api extends \Core\Api
{}
| {
"pile_set_name": "StackExchange"
} |
Q:
Explanation of a line of Objective C code
for (ItemEntity *itemEntity in changedItemEntities) {
[[NetworkWrapper sharedInstance] uploadItemEntity:itemEntity userId:[itemEntity.userId unsignedIntegerValue] title:itemEntity.title completion:^(BOOL success, NSUInteger photoId, NSUInteger timeStamp) {
if (success) {
itemEntity.itemId = [NSNumber numberWithUnsignedInteger:photoId];
itemEntity.isUploaded = YES;
[self.context processPendingChanges];
NSError *error;
[self.context save:&error];
}
}];
}
What do these lines of code do in simple programming terms?
A:
One of Objective-C's strengths is its verbose syntax, making the code very readable.
for (ItemEntity *itemEntity in changedItemEntities) {
This will perform the operation in braces ({}) for each ItemEntity object in changedItemEntities. Inside the braces, each object can be referred to as itemEntity.
[NetworkWrapper sharedInstance]
This gets a reference to the shared instance of a class called NetworkWrapper
uploadItemEntity:itemEntity userId:[itemEntity.userId unsignedIntegerValue] title:itemEntity.title completion:
This tells the shared instance to upload each entity, with a user ID and title derived from the entity object itself. There is a completion block, which is run once the operation is done, and looks like this:
^(BOOL success, NSUInteger photoId, NSUInteger timeStamp) {
if (success) {
itemEntity.itemId = [NSNumber numberWithUnsignedInteger:photoId];
itemEntity.isUploaded = YES;
[self.context processPendingChanges];
NSError *error;
[self.context save:&error];
}
This will run for each completed upload. That code will have a success flag (a boolean value), a photo ID (an integer) and a timestamp (also an integer). In your example the values are used to update the itemEntity object and then the context lines cause the Core Data store of the app to save its data to disk.
So basically you've got a bunch of things, you're performing an upload operation for each one, and when each upload is done, you're running another block of code.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to use selenium along with scrapy to automate the process?
I came to know at one point you need to use webtoolkits like selenium to automate the scraping.
How I will be able to click the next button on google play store in order to scrape the reviews for my college purpose only !!
import scrapy
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.selector import Selector
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from urlparse import urljoin
from selenium import webdriver
import time
class Product(scrapy.Item):
title = scrapy.Field()
class FooSpider(CrawlSpider):
name = 'foo'
start_urls = ["https://play.google.com/store/apps/details?id=com.gaana&hl=en"]
def __init__(self, *args, **kwargs):
super(FooSpider, self).__init__(*args, **kwargs)
self.download_delay = 0.25
self.browser = webdriver.Chrome(executable_path="C:\chrm\chromedriver.exe")
self.browser.implicitly_wait(60) #
def parse(self,response):
self.browser.get(response.url)
sites = response.xpath('//div[@class="single-review"]/div[@class="review-header"]')
items = []
for i in range(0,200):
time.sleep(20)
button = self.browser.find_element_by_xpath("/html/body/div[4]/div[6]/div[1]/div[2]/div[2]/div[1]/div[2]/button[1]/div[2]/div/div")
button.click()
self.browser.implicitly_wait(30)
for site in sites:
item = Product()
item['title'] = site.xpath('.//div[@class="review-info"]/span[@class="author-name"]/a/text()').extract()
yield item
I have updated my code and it is only giving me repeative 40 items again and again.whats wrong with my for loop?
It seems that the source code which is being updated is not passed to the xpath thats why it is returning with same 40 items
A:
I'd do something like that:
from scrapy import CrawlSpider
from selenium import webdriver
import time
class FooSpider(CrawlSpider):
name = 'foo'
allow_domains = 'foo.com'
start_urls = ['foo.com']
def __init__(self, *args, **kwargs):
super(FooSpider, self).__init__(*args, **kwargs)
self.download_delay = 0.25
self.browser = webdriver.Firefox()
self.browser.implicitly_wait(60)
def parse_foo(self.response):
self.browser.get(response.url) # load response to the browser
button = self.browser.find_element_by_xpath("path") # find
# the element to click to
button.click() # click
time.sleep(1) # wait until the page is fully loaded
source = self.browser.page_source # get source of the loaded page
sel = Selector(text=source) # create a Selector object
data = sel.xpath('path/to/the/data') # select data
...
It's better not to wait for a fixed amount of time, though. So instead of time.sleep(1), you can use one of the approaches described here http://www.obeythetestinggoat.com/how-to-get-selenium-to-wait-for-page-load-after-a-click.html.
| {
"pile_set_name": "StackExchange"
} |
Q:
Reservation.last.card => NoMethodError: undefined method `card' for # Did you mean? card_id
I'm sure it something really stupid, but I cannot seem to find the issue.
I'm trying to call Reservation.last.card, but get the error
Reservation Load (0.3ms) SELECT "reservations".* FROM "reservations" ORDER BY "reservations"."id" DESC LIMIT $1 [["LIMIT", 1]]
NoMethodError: undefined method `card' for #<Reservation:0x090d440e130>
Did you mean? card_id
migration + schema
class AddCardToReservations < ActiveRecord::Migration[5.2]
def change
add_reference :reservations, :card, foreign_key: true
end
end
create_table "reservations", force: :cascade do |t|
t.bigint "park_id"
t.bigint "card_id"
t.index ["card_id"], name: "index_reservations_on_card_id"
t.index ["park_id"], name: "index_reservations_on_park_id"
end
models
class Reservation < ApplicationRecord
has_one :card
belongs_to :park
end
class Card < ApplicationRecord
belongs_to :park
has_many :reservations
end
A:
the line in the Reservation class...
has_one :card
Implies that the card object has a reservation_id which isn't the case, the foreign key is card_id in the reservation object, so what you want is...
belongs_to :card
| {
"pile_set_name": "StackExchange"
} |
Q:
FullCalendar mes e ano corrente
Boa noite a todos, estou precisando saber se existe uma forma de pegar o mes e o ano corrente do FullCalendar, quando clicamos em avançar ou retroceder.
Não consegui descobrir qual é o evento que dispara quando clica nos botões de avançar e retroceder de datas.
A idéia e ter essas datas para fazer a pesquisa numa base de dados e trazer os eventos do mês que esta sendo exposto na tela do Fullcalendar, por exemplo outubro 2017.
Existiria uma outra forma de passar esses dados para a pesquisa na base de dados? Estou usando uma array com json para o setFullCalendarEvents = function(){}
A:
Bom dia a todos!
Quero compartilhar uma solução que acabei achando.
Eu estou usando um template que tem o fullcalendar, então pesquisando na documentação achei a seguinte solução:
Criei 3 botões: avançar, retroceder, HOJE .
A função que resgata a data apresentada é:
var moment = $('#full-calendar').fullCalendar('getDate');
var dt = moment.format()
Temos as seguintes funções que fazem o papel de avançar, retroceder e hoje:
$('#full-calendar').fullCalendar('prev');
$('#full-calendar').fullCalendar('today');
$('#full-calendar').fullCalendar('next');
Fazem o calendario avançar, retroceder e ficar no dia de HOJE
Coloquei essas funções nos respectivos botões:
$(".prev_data").click(function(){
$('#full-calendar').fullCalendar('prev');
var moment = $('#full-calendar').fullCalendar('getDate');
alert(moment.format());
});
Pronto, consegui resgatar a mês/ano que esta sendo exibido, quando avançamos ou retrocedemos os meses no calendario.
Abraço a todos
| {
"pile_set_name": "StackExchange"
} |
Q:
Сменить URL
привет...
Как динамически формировать URL средствами PHP(без js!!)?
Хочу на подобии способа
function hashq(){
$range='';
for($i=0;$i<6;$i++){
$range.= range('a', 'z')[rand(0,20)];
}
return substr(crypt($range),12,10);
}
echo '<a href="omg.php?hashmy='.hashq().'">Link<a>';
Только при прямом переходе на omg.php чтобы добавилась
http://localhost/omg.php?hashmy=dt.ghPgxJ1 при чем рандомная....
Знаю вариант только через
header('Location:')
Других нету?
A:
я че-то не вижу в вопросе ничего про POST. ответом вам будет - получили POST - положите его в сессию и отметьте там-же что вы сделали редирект и надо этот POST достать при первом-же удобном случае. можно даже так (просто пример поясняющий идею)
session_start();
$_POST=count($_POST)?$_POST:get_lastpost();
if (rand(1,10)==5) { set_lastpost(); header('Location:'); }
if ($_POST) print_r($_POST);
function get_lastpost() {
if (isset($_SESSION['LastPost']) {
$lastPost=$_SESSION['LastPost'];
unset($_SESSION['LastPost']);
return $lastPost;
}
return false; //хотя конечно это плохо, просто для примера
}
function set_lastpost() {
$_SESSION['LastPost']=$_POST;
}
я вас по итогу немного обманул вы можете ещё так сделать:
header("HTTP/1.1 307 Temporary Redirect");
header("Location: newurl.php");
но если дело происходит на одном сервере, то лучше в сессию записывать.
https://tools.ietf.org/html/draft-ietf-httpbis-p2-semantics-21#page-56
| {
"pile_set_name": "StackExchange"
} |
Q:
using Lagrange's Theorem and cylic geoups
Suppose |G| = 21. If G has exactly one subgroup of order 3 and exactly one subgroup of order 7, prove that G is cyclic.
So far, I only know that by using LaGrange's theorem, the order of every element in G must factor 21. So my options are 1, 3, 7, or 21.
Does it have anything to do with the fact that 3 and 7 are primes or am I reaching a bit too far?
Also, do I have to assume (in the proof) that the subgroups have those specific orders?
A:
To show that $G$ is cyclic is equivalent to showing that $G$ has an element of order $21$.
Let $H$ be the unique subgroup of order $3$.
Then if any element $x\in G$ has order $3$, then $\langle x\rangle$, the group generated by $x$ is a subgroup of order $3$. So $\langle x \rangle = H$. In particular, there can only be $2$ elements of $G$ of order $3$, which are exactly the non-identity elements of $H$.
In a similar way, how many elements of order $7$ are there?
And how many elements do we have left? What can their orders be?
| {
"pile_set_name": "StackExchange"
} |
Q:
Cooling for a small server room
I have a server room about 12 feet square with an unfinished ceiling (exposed ducts and wiring). It houses a few servers (about ten, 1U and 2U) and some networking gear (four 1U switches, three routers, three modems, two cable boxes).
With the door closed, it runs around 80 degrees Fahrenheit with half the servers turned on. When I turned on all the servers it reached 86 before I chickened out and propped the door open.
The room is adjacent to air-conditioned office space, but does not itself have dedicated air conditioning. The ventilation for this room seems to be limited to one duct coming in at ceiling level, with a powered fan to draw air in, and one duct at ceiling level to allow air to flow out (it seems like it may just go into the drop ceiling cavity in the adjacent room).
The adjacent office space stays fairly cool, but I'd prefer not to leave the door propped open all the time.
There is both 110v and 208v service in the room, and plenty of power available. But there are no windows, and no floor drains (in a pinch we might be able to run a condensation hose through a small hole we'd drill in the wall to a nearby sink area, but only if absolutely necessary).
I've considered portable A/C units, but I'm not sure on sizing and a lot less sure how we would run the exhaust hose(s). I suppose we could point one at the existing room exhaust duct (air return), but substantially modifying the duct is probably a no-no.
I've also considered installing a fan box in the door of the room, but I'm concerned that this will only drop the temperature a little. Even right now, with all the equipment on, the room is at 83 degrees with the door open. And the main building A/C turns off daily at 6 PM to conserve energy, so the adjacent room temperature rises at night.
How would you cool this room? Let's say the goal is to bring the temperature with everything running from a steady state of around 90 degrees down to 75 (equivalently, to offset the heat produced by ten 1U servers).
A:
I would use a portable air conditioning unit that consumed it's own condensation and kept the room at 50% relative humidity. Some people argue that dew point is a better metric, but I haven't looked into it deeply enough and am willing to be corrected. Some A/C units will push their condensation through a hose that snakes through the A/C unit's exhaust hose and thus gets evaporated into the hot, dry output air and into the plenum and exhaust system. You could also get an A/C unit that has condensation tanks and just remember to empty them every day. Annoying, yes. But sometimes an admins gotta do what an admins gotta do.
Either way, you must have exhaust. You can run a duct hose from the A/C's output into the plenum space or near the outtake. That might not be sufficient though. IMO, A/C output is your biggest problem here. Might be nice in winter, you can barter with different departments on which cubicle space the exhaust hose will run to each week. :)
Plenty of companies make portable cooling units made for permanent usage in server rooms. Some companies include:
Atlas
Topaz
Movin Cool (I think Atlas bought Movin' Cool, or the other way around, or something else. There seems to be some relationship between the two companies that I haven't determined yet)
I blogged about portable A/C units a little while back on my old blog here: http://thenonapeptide.blogspot.com/2009/12/list-of-portable-cooling-units.html
A:
You really don't want to be stuffing about with this sort of thing or relying on guesswork. Just for starters I suggest you get that ceiling finished off and fitted with an exhaust fan or two.
For scaling the A/C I suggest talking to the A/C people, who know a lot more about this stuff than we do. Tell them the load you're currently running, after adding a bit more than than the maximum you can reasonably expect it to ever be. Don't forget to mention that it needs be be running 24/7. I actually prefer to have multiple units, each of which can handle the normal load, even if it's straining to do so. That way you can more easily deal with a failed unit.
In simple terms, the electricity your gear consumes exits as heat. Work out, or measure if you have the gear, how much you're using. If in doubt get an electrician to measure it for you. It's a small investment that can save you a lot of money later.
A:
I've used one of the portable units in the past, and during peak temperatures, we were able to keep things about 20 degrees cooler. We'd also put some insulation on top of the drop ceilings, which seemed to help quite a bit. On a side note, you're lucky for the lack of windows - this "server room" had an entire wall of windows, which we went to great lengths to block off, as it was a huge source of additional heat.
| {
"pile_set_name": "StackExchange"
} |
Q:
Disconnecting a drive during a secure erase
If I issue the secure erase command to a hard drive can I disconnect the drive as long as it remains powered? I am thinking that since the erase is controlled by the HDD's internal controller it does not need to communicate with the PC.
A:
Doing so is outside the specification for most drive interfaces, so there's no reliable prediction on what will happen. The drive controller would be free, for example, to abort the secure erase command when it detects the control lines being disconnected, expecting a hot swap scenario with the power going away shortly afterwards.
| {
"pile_set_name": "StackExchange"
} |
Q:
Function as argument in python
I need to pass some function as argument in another function. So, I want to add current time to class attribute every second, for example
import time
class Measurement():
values = []
def add_value(self, value):
print "added value"
self.values.append(value)
def smart_delay(input_function,args):
start_time = time.time()
while 5 > (time.time() - start_time):
print "Calling function"
input_function(args)
time.sleep(1)
measurement = Measurement()
smart_delay(measurement.add_value,time.time())
Ok, but after checking contents of measurement.values, I get
[1425980407.173, 1425980407.173, 1425980407.173, 1425980407.173] - so values are the same!!!
What happened? And how to get proper values?
Updated:
Actually, this question is about the way to allow to call some function, passed as the argument to another function. What do you think about this:
import time
class Measurement():
values = []
def add_value(self, value):
print "added value"
self.values.append(value)
def smart_delay(input_function):
start_time = time.time()
while 5 > (time.time() - start_time):
print "Calling function"
input_function()
time.sleep(1)
measurement = Measurement()
smart_delay(lambda: measurement.add_value(time.time()))
A:
Your call to time.time() is executed before the call to smart_delay(...), so smart_delay(measurement.addvalue, time.time()) will first get the return value from time.time() and pass that forward to smart_delay.
You need to pass the time.time function itself, and call it inside of the smart_delay method, instead of passing its return value:
import time
class Measurement():
values = []
def add_value(self, value):
print "added value"
self.values.append(value)
def smart_delay(output_f, input_f):
start_time = time.time()
while 5 > (time.time() - start_time):
print "Calling function"
output_f(input_f())
time.sleep(1)
measurement = Measurement()
smart_delay(measurement.add_value, time.time)
Notice, that this is not the best way to do what you're doing, but it works.
Here's how I'd do it:
import time
# Why do you need a measurement class which only acts as a list anyways?
my_measurements = []
def repeat(duration, function, args=(), kwargs={}, interval=1):
"""Repeat a function call for the given duration."""
start_time = time.time()
while duration > time.time() - start_time:
function(*args, **kwargs)
time.sleep(interval)
def add_time_measurement(measurements):
measurements.append(time.time())
repeat(5, add_time_measurement, (my_measurements,))
And if you want some prints, you can just add them in the add_time_measurement function.
| {
"pile_set_name": "StackExchange"
} |
Q:
What is VPS provisioning?
I'm starting to get my feet wet in the VPS world, so I have some newbie questions for you gurus.
The first is this (as title): what is VPS provisioning?
When you do it and what it's useful for?
Thanks!
A:
It's the manual, semi-automated or fully-automated creation of the storage, networking, VM creation/cloning, OS configuration and user communication of a fully fledged virtual server to order. It's often initiated either directly by a web store front-end or some form of post-purchase operations-led interface.
Basically it's the means to go from a single "build me a VPS" click to handing it over to the user fully ready with as little time and cost incurred as possible.
These systems are often just scripted chains of events utilising APIs from storage and networking vendors with large chunks of API interaction with the hypervisor of choice. Some systems such as VMWare's Orchestrator can be both scripted and also GUI driven.
A:
Provisioning is the process of creating a new virtual server and installing an operating system on it. It's done... whenever you need a new virtual server.
| {
"pile_set_name": "StackExchange"
} |
Q:
iPhone - NSDictionary sorting based on values
Possible Duplicate:
NSDictionary keys sorted by value numerically?
I'm maintaining the scores of my game in a dictionary. Key will be the name of the user and value will be the score. When displaying the scores in table view, I want to sort the dictionary depending on values so that first item will be top score and last item will be least score.
How can this be done?
A:
try this one
NSSortDescriptor *descriptor =
[[NSSortDescriptor alloc] initWithKey:@"Score" ascending:YES];
[items sortUsingDescriptors:[NSArray arrayWithObjects:descriptor,nil]];
[descriptor release];
| {
"pile_set_name": "StackExchange"
} |
Q:
Network Interface does not contain a definition for ""
I recently created this code for a WPF application that I was doing. The project where I'm reusing the code is a Windows 8 application. The code itself is the same so I don't really see what could be the issue. The only difference between them is of course the application and the .NET Framework being used. In the WPF application I was targeting .NET 3.0 and for the Windows 8 application I'm using .NET 4.5.
As you can tell this is an extension method:
public static bool isTunnel(this NetworkInterface adapter)
{
return adapter.NetworkInterfaceType == NetworkInterfaceType.Tunnel;
}
The error it gives for that method is:
Error 3 'System.Net.NetworkInformation.NetworkInterface' does not contain a definition for 'NetworkInterfaceType' and no extension method 'NetworkInterfaceType' accepting a first argument of type 'System.Net.NetworkInformation.NetworkInterface' could be found (are you missing a using directive or an assembly reference?)
Error 4 The name 'NetworkInterfaceType' does not exist in the current context
In my model class I'm having a similar issue. On this line:
foreach (NetworkInterface adapter in NetworkInterface.GetAllNetworkInterfaces())
it causes an error saying that the GetAllNetworkInterfaces() does not exist in NetworkInterface. Here's the exact error:
Error 15 'System.Net.NetworkInformation.NetworkInterface' does not contain a definition for 'GetAllNetworkInterfaces'
Is there something that I don't know about reusing code from WPF application in Windows 8 applications?
Update: Using the ianainterfacetype I was able to fix half of my extension methods because I was able to tell if they were Ethernet, Wireless, or Tunnel. I'm still searching for a way to tell if they were created by VirtualBox or VMware.
For those who want to know about the ianainterfacetype you can find info here.
A:
GetAllNetworkInterfaces is not available to Windows Store (metro) apps. The MSDN Documentation indicates that only the GetIsNetworkAvailable method is available to Windows Store apps. The green briefcase indicates whether or not it is available to Windows Store apps.
I am not aware of any API that is available to Windows Store apps that can give you the information you are looking for.
| {
"pile_set_name": "StackExchange"
} |
Q:
how to pass a member function as a function pointer?
I want add a logger function to a worker class,
how to pass a member function as a function pointer?
use mem_fun?
here is the code sample:
class Work{
public:
void (*logger) (const string &s);
void do_sth(){if (logger) logger("on log")};
};
classs P{
public:
void log(const string &s)(cout << s);
};
int main(){
Work w;
P p;
w.logger = &p.log;
w.do_sth();
}
edit:
I don't want to use void (P::*xxx)() because it stick to class P...
I know C++ hide sth, the real log function is: void log(P &p, const string &s),
and the real project is like this:
I create a CDialog, and there is a log function, it copy the log string to a CEdit.
So I need pass this log function to a Worker class, this class do some serial port job,
I need log and show the data send and recived...
A:
You can accomplish this using std::function and std::bind:
#include <functional>
#include <iostream>
#include <string>
class Work {
public:
std::function<void(const std::string&)> logger;
void do_sth() { logger("on log"); }
};
class P {
public:
void log(const std::string& s) { std::cout << s; }
};
int main() {
Work w;
P p;
w.logger = std::bind(&P::log, p, std::placeholders::_1);
w.do_sth();
}
Note that function and bind may not be in your implementation's standard library yet; you can also get them from the Boost libraries.
| {
"pile_set_name": "StackExchange"
} |
Q:
Why $\int_{0}^{\pi/2}\tan(x/2) dx= \ln 2$
I don't know why
$$\int_0^{\pi/2}\tan\frac{x}2\ dx= \ln 2.$$
How can i solve this to get that answer?
A:
If we set $x=2\arctan t$ we have:
$$ \int_{0}^{\pi/2}\tan\left(\frac{x}{2}\right)\,dx = \int_{0}^{1}\frac{2t}{1+t^2}\,dt = \left.\log(1+t^2)\right|_{0}^{1}=\color{red}{\log 2}$$
as wanted.
A:
$$\int_0^{\frac{\pi}{2}}\tan\left(\frac{x}{2}\right) dx$$
Using $u$-substitution, we have
$$u=\frac{x}{2}\Rightarrow 2\ du=dx$$
So now
$$2\int_0^{\frac{\pi}{4}}\tan u\ du$$
$$=-2\ln\left|\cos \frac{\pi}{4}\right|+2\ln\left|\cos 0\right|$$
$$=-2\ln\frac{1}{\sqrt2}+2\ln 1$$
$$=-2\ln 1+2\ln \sqrt2+2\ln 1$$
$$=2\ln \sqrt2$$
$$=\ln 2$$
| {
"pile_set_name": "StackExchange"
} |
Q:
How to have expect timeout when trying to login to an ssh session it has spawned?
I am writing an bash script that uses expect to login to a bunch of Cisco ASAs (they don't support certificate login, hence using expect), makes a change to the configuration and then logs out.
I'd like the script to move onto the next ASA if it is unable to login.
Here is the script:
#!/bin/bash
# Scriptname: set-mtu
for asa in $(cat asa-list-temp)
do
/usr/bin/expect << EndExpect
spawn ssh admin_15@$asa
expect "assword:"
send "pa$$w0rd\r"
expect ">"
send "do something\r"
expect ">"
send "exit\r"
EndExpect
done
I think I can set a timeout on expect "assword:" but I can't figure out how to get it to close the spawned ssh session and then move onto the next ASA in the for list.
A:
First of all I would use an expect script for this and lose the bash scripting.
Then for the expect part:
You can do this by using a switch that also matches for timeout (page 12 of exploring expect). In that way you can explicitly have some action when expect timeouts.
Otherwise by setting the timeout it will just continue with the next command in line.
set timeout 60
expect {
"assword:" {
}
timeout {
exit 1 # to exit the expect part of the script
}
}
I've created something similar where I used an overall expect script to run an expect script in parallel.
multiple.exp
#!/bin/sh
# the next line restarts using tclsh \
exec expect "$0" "$@"
# multiple.exp --
#
# This file implements the running of multiple expect scripts in parallel.
# It has some settings that can be found in multiple.config
#
# Copyright (c) 2008
#
# Author: Sander van Knippenberg
#####
# Setting the variables
##
source [file dirname $argv0]/.multiple.config
# To determine how long the script runs
set timingInfo("MultipleProcesses") [clock seconds]
# ---------------------------------------------------------------------
######
# Procedure to open a file with a certain filename and retrieve the contents as a string
#
# Input: filename
# Output/Returns: content of the file
##
proc openFile {fileName} {
if {[file exists $fileName] } {
set input [open $fileName r]
} else {
puts stderr "fileToList cannot open $fileName"
exit 1
}
set contents [read $input]
close $input
return $contents
}
######
# Procedure to write text to a file with the given filename
#
# Input: string, filename
##
proc toFile {text filename} {
# Open the filename for writing
set fileId [open $filename "w"]
# Send the text to the file.
# Failure to add '-nonewline' will reslt in an extra newline at the end of the file.
puts -nonewline $fileId $text
# Close the file, ensuring the data is written out before continueing with processing
close $fileId
}
# ---------------------------------------------------------------------
# Check for the right argument
if {$argc > 0 } {
set hostfile [lindex $argv 0]
} else {
puts stderr "$argv0 --- usage: $argv0 <hosts file>"
exit 1
}
# Create the commands that can be spawned in parallel
set commands {}
# Open the file with devices
set hosts [split [openFile $hostfile] "\n"]
foreach host $hosts {
if { [string length $host] > 1 } {
lappend commands "$commandDir/$commandName $host" # Here you can enter your own command!
}
}
# Run the processes in parallel
set idlist {}
set runningcount 0
set pattern "This will never match I guess"
# Startup the first round of processes until maxSpawn is reached,
# or the commands list is empty.
while { [llength $idlist] < $maxSpawn && [llength $commands] > 0} {
set command [lindex $commands 0]
eval spawn $command
lappend idlist $spawn_id
set commands [lreplace $commands 0 0]
incr runningcount
set commandInfo($spawn_id) $command
set timingInfo($spawn_id) [clock seconds]
send_user " $commandInfo($spawn_id) - started\n"
}
# Finally start running the processes
while {$runningcount > 0} {
expect {
-i $idlist $pattern {
}
eof {
set endedID $expect_out(spawn_id)
set donepos [lsearch $idlist $endedID]
set idlist [lreplace $idlist $donepos $donepos]
incr runningcount -1
set elapsedTime [clock format [expr [clock seconds] - $timingInfo($endedID)] -format "%M:%S (MM:SS)"]
send_user " $commandInfo($endedID) - finished in: $elapsedTime\n"
# If there are more commands to execute then do it!
if {[llength $commands] > 0} {
set command [lindex $commands 0]
eval spawn $command
lappend idlist $spawn_id
set commands [lreplace $commands 0 0]
incr runningcount
set commandInfo($spawn_id) $command
set timingInfo($spawn_id) [clock seconds]
}
}
timeout {
break
}
}
}
set elapsed_time [clock format [expr [clock seconds] - $timingInfo("MultipleProcesses")] -format "%M:%S (MM:SS)"]
send_user "$argv0 $argc - finished in: $elapsedTime\n"
multiple.config
# The dir from where the commands are executed.
set commandDir "/home/username/scripts/expect/";
set commandName "somecommand.exp";
# The maximum number of simultanious spawned processes.
set maxSpawn 40;
# The maximum timeout in seconds before any of the processes should be finished in minutes
set timeout 20800;
| {
"pile_set_name": "StackExchange"
} |
Q:
Gradle ExoPlayer and GSON
My Gradle file looks like:
android {
compileSdkVersion 23
buildToolsVersion "23.0.2"
defaultConfig {
minSdkVersion 15
targetSdkVersion 23
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile 'com.google.code.gson:gson:2.4'
compile 'com.squareup.okhttp3:okhttp:3.2.0'
compile 'com.android.support:appcompat-v7:23.2.1'
compile 'com.google.android.exoplayer:exoplayer:r1.5.8'
}
Gradle sync works, but executing the task assembleDebug fails with the following messages:
* Exception is:
org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':exampleApp:transformClassesWithDexForDebug'.
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:69)
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:46)
at org.gradle.api.internal.tasks.execution.PostExecutionAnalysisTaskExecuter.execute(PostExecutionAnalysisTaskExecuter.java:35)
at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:64)
at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:58)
at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:52)
at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:52)
at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:53)
at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43)
at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:203)
at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:185)
at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.processTask(AbstractTaskPlanExecutor.java:62)
at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.run(AbstractTaskPlanExecutor.java:50)
at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor.process(DefaultTaskPlanExecutor.java:25)
at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter.execute(DefaultTaskGraphExecuter.java:110)
at org.gradle.execution.SelectedTaskExecutionAction.execute(SelectedTaskExecutionAction.java:37)
at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:37)
at org.gradle.execution.DefaultBuildExecuter.access$000(DefaultBuildExecuter.java:23)
at org.gradle.execution.DefaultBuildExecuter$1.proceed(DefaultBuildExecuter.java:43)
at org.gradle.execution.DryRunBuildExecutionAction.execute(DryRunBuildExecutionAction.java:32)
at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:37)
at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:30)
at org.gradle.initialization.DefaultGradleLauncher$4.run(DefaultGradleLauncher.java:154)
at org.gradle.internal.Factories$1.create(Factories.java:22)
at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:90)
at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:52)
at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:151)
at org.gradle.initialization.DefaultGradleLauncher.access$200(DefaultGradleLauncher.java:32)
at org.gradle.initialization.DefaultGradleLauncher$1.create(DefaultGradleLauncher.java:99)
at org.gradle.initialization.DefaultGradleLauncher$1.create(DefaultGradleLauncher.java:93)
at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:90)
at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:62)
at org.gradle.initialization.DefaultGradleLauncher.doBuild(DefaultGradleLauncher.java:93)
at org.gradle.initialization.DefaultGradleLauncher.run(DefaultGradleLauncher.java:82)
at org.gradle.launcher.exec.InProcessBuildActionExecuter$DefaultBuildController.run(InProcessBuildActionExecuter.java:94)
at org.gradle.tooling.internal.provider.runner.BuildModelActionRunner.run(BuildModelActionRunner.java:46)
at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
at org.gradle.tooling.internal.provider.runner.SubscribableBuildActionRunner.run(SubscribableBuildActionRunner.java:58)
at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:43)
at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:28)
at org.gradle.launcher.exec.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:77)
at org.gradle.launcher.exec.ContinuousBuildActionExecuter.execute(ContinuousBuildActionExecuter.java:47)
at org.gradle.launcher.daemon.server.exec.ExecuteBuild.doBuild(ExecuteBuild.java:52)
at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
at org.gradle.launcher.daemon.server.exec.WatchForDisconnection.execute(WatchForDisconnection.java:37)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
at org.gradle.launcher.daemon.server.exec.ResetDeprecationLogger.execute(ResetDeprecationLogger.java:26)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
at org.gradle.launcher.daemon.server.exec.RequestStopIfSingleUsedDaemon.execute(RequestStopIfSingleUsedDaemon.java:34)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:74)
at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:72)
at org.gradle.util.Swapper.swap(Swapper.java:38)
at org.gradle.launcher.daemon.server.exec.ForwardClientInput.execute(ForwardClientInput.java:72)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
at org.gradle.launcher.daemon.server.health.DaemonHealthTracker.execute(DaemonHealthTracker.java:47)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
at org.gradle.launcher.daemon.server.exec.LogToClient.doBuild(LogToClient.java:66)
at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
at org.gradle.launcher.daemon.server.exec.EstablishBuildEnvironment.doBuild(EstablishBuildEnvironment.java:71)
at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
at org.gradle.launcher.daemon.server.health.HintGCAfterBuild.execute(HintGCAfterBuild.java:41)
at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
at org.gradle.launcher.daemon.server.exec.StartBuildOrRespondWithBusy$1.run(StartBuildOrRespondWithBusy.java:50)
at org.gradle.launcher.daemon.server.DaemonStateCoordinator$1.run(DaemonStateCoordinator.java:246)
at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:54)
at org.gradle.internal.concurrent.StoppableExecutorImpl$1.run(StoppableExecutorImpl.java:40)
Caused by: java.lang.RuntimeException: com.android.build.api.transform.TransformException: com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command 'C:\Program Files\Java\jdk1.7.0_79\bin\java.exe'' finished with non-zero exit value 2
at com.android.builder.profile.Recorder$Block.handleException(Recorder.java:54)
at com.android.builder.profile.ThreadRecorder$1.record(ThreadRecorder.java:57)
at com.android.builder.profile.ThreadRecorder$1.record(ThreadRecorder.java:47)
at com.android.build.gradle.internal.pipeline.TransformTask.transform(TransformTask.java:147)
at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:75)
at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$IncrementalTaskAction.doExecute(AnnotationProcessingTaskFactory.java:244)
at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$StandardTaskAction.execute(AnnotationProcessingTaskFactory.java:220)
at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$IncrementalTaskAction.execute(AnnotationProcessingTaskFactory.java:231)
at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$StandardTaskAction.execute(AnnotationProcessingTaskFactory.java:209)
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:80)
at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:61)
... 70 more
Caused by: com.android.build.api.transform.TransformException: com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command 'C:\Program Files\Java\jdk1.7.0_79\bin\java.exe'' finished with non-zero exit value 2
at com.android.build.gradle.internal.transforms.DexTransform.transform(DexTransform.java:406)
at com.android.build.gradle.internal.pipeline.TransformTask$2.call(TransformTask.java:151)
at com.android.build.gradle.internal.pipeline.TransformTask$2.call(TransformTask.java:148)
at com.android.builder.profile.ThreadRecorder$1.record(ThreadRecorder.java:55)
... 79 more
Caused by: com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command 'C:\Program Files\Java\jdk1.7.0_79\bin\java.exe'' finished with non-zero exit value 2
at com.android.build.gradle.internal.process.GradleProcessResult.assertNormalExitValue(GradleProcessResult.java:42)
at com.android.builder.core.AndroidBuilder.convertByteCode(AndroidBuilder.java:1344)
at com.android.build.gradle.internal.transforms.DexTransform.transform(DexTransform.java:391)
... 82 more
Caused by: org.gradle.process.internal.ExecException: Process 'command 'C:\Program Files\Java\jdk1.7.0_79\bin\java.exe'' finished with non-zero exit value 2
at org.gradle.process.internal.DefaultExecHandle$ExecResultImpl.assertNormalExitValue(DefaultExecHandle.java:367)
at com.android.build.gradle.internal.process.GradleProcessResult.assertNormalExitValue(GradleProcessResult.java:40)
... 84 more
When I remove gson from the gradle file, the execution of the task can be finished. Has someone an idea what I can do? The execution runs round about 3 minutes...
A:
Try adding multiDexEnabled true to your app build.gradle file.
defaultConfig {
multiDexEnabled true
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Git - replace local branch with remote branch
I know this question has been asked but I can't seem to completely replace my local branch with my remote branch. I had installed a 3rd party plugin in my local branch and am having trouble removing the installation; thus, I want to "start over" with the remote version of the branch. The branch is called "dev" locally and "origin/dev" remotely. I've tried three ways of replacing my local branch with the remote version:
1. git reset HEAD --hard
2. git reset --hard origin/dev
3. git checkout dev
git fetch
git reset --hard origin/dev
But reviewing the local code after the executing the above git commands, I can still see leftover files and folders from the plugin.
Using git status, I get "Your branch is up-to-date with 'origin/dev'. Nothing to commit, working directory clean".
Using git status --ignored, I get too many files to list... basically everything in my .gitignore file I believe.
I only want the code that exists in the remote dev branch and nothing else.
Can somebody help?
Update:
Turns out that the error that I was getting was due to a bunch of files in the directory, root/var/cache/*. My .gitignore file contains the following entries:
/var/*
!/var/package
var/session/*
Trying the possible ways to restore the local dev branch from remote (listed in the question above as well as the proposed solutions below), the root/var/cache directory remained present; I had to manually delete it before my application started functioning again. Looking at the github, the remote dev branch did not contain 'root/var/cache. Can anybody tell me whyroot/var/cache` was not responding to the git commands for replacing the local branch with the remote version?
A:
From another branch (say master), reset your dev branch:
git branch -f dev origin/dev
Then, checkout dev and clean up your extra files:
git checkout dev
git clean -d -f
A:
Try git clean -fx. That will remove all untracked files, even if they're mentioned in .gitignore.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is there a simple workflow to generate a database schema from classes with hibernate mappings?
Id like to define my objects then use hibernate to generate my ddl from this. But it seems like the only real workflow with hibernate is to generate a datbase schema and then reverse engineer it. Am I wanting to do something that makes no sense?
A:
Yes there is a property hibernate.hbm2ddl.auto. The documentation says:
Automatically validates or exports schema DDL to the database when the SessionFactory is created. With create-drop, the database schema will be dropped when the SessionFactory is closed explicitly.
e.g. validate | update | create | create-drop
There are multiple ways to define this property, depending on how you configure your SessionFactory. The hibernate way is to simply add:
<property name="hibernate.hbm2ddl.auto">update</property>
| {
"pile_set_name": "StackExchange"
} |
Q:
JavaFX class design
I used Swing for years and now I am moving to JavaFX. Despite many similarities, I'm confused about some topics, such as how to develop larger applications which involve many scenes/stages effectively. In Swing the most used approach was inheritance, e.g by subclassing JPanel class or other Swing components. From what I saw until now, it seems that in JavaFX this is not the common pratice. Although it is possible to subclass Stage and Scene classes, it seems it's not recomended.
But I also noticed that, especially in cases of a complex GUI, I end up with my main class (the one containing the start method) becoming an enormous cluster of hundred of lines of code. Such a code seems pretty hard to debug and mantain, but probably I am using a wrong approach. While in Swing this could be avoided in some ways, for example by subclassing some components and reusing them, is there any similar design technique that may help me to break up my JavaFX app in more classes?
A:
I would take a look at this tutorial by Oracle which walks you through building a multi-screen javafx application.
The code for this tutorial can be found here Acaicedo GitHub
It follows MVC (Model View Controller) where FXML files are views, associated with unique controllers written in java. This framework adds an extra controller that allows navigation between screens (ie. shifting the show content to a different controller and view).
| {
"pile_set_name": "StackExchange"
} |
Q:
Identifying the time lag between cause and effect
What approaches exist to observe the time lag between two variables?
I need to analyze the relationship between blood pressure and some other factor, such as exercise. The data set I am drawing from has around 1800 individuals, with an average of 100 entries a piece. It is generally known that there is a strong relationship between exercise level and blood pressure. However, if a person increases their steps to 8000+ a day, how long will it take for their blood pressure to drop? I am new to this type of analysis, and this is a challenge I have been thinking about for weeks.
I don't know if anyone wants to comment on possible approaches to this challenge or any issues surrounding it.
Some issues I have been dealing with:
Is it better to treat this as a times series analysis or longitudinal data analysis?
My understanding is that time series usually focuses on one variable with no missing data and is observed at consistent intervals, where as longitudinal is over a longer period and has inconsistent time intervals, dropouts, and missing data.
The data I have seems to fit the longitudinal description more, but it also seems like time series could be used if I averaged the values by week so there would be no missing entries. I'm not sure about the pros and cons of each approach.
Should I be fitting a causal model, or would some other method like regression be more helpful?
I've been looking at various possible causal models, for example Marginal Structural Models (MSM) or Structural Nested Models (SNM), but there seem to be very little information on their application. I did find one R package that applied inverse probability weights and then used Cox proportional hazards regression model on a survival object (MSM), but that seemed to be focus on weighting for confounding and right censoring. Its result was a correlation coefficient, which I don't think helps me.
So I'm not sure if fitting a causal model is what I want, because that seems to be more focused on the making intellectually satisfying assumptions about relationships within the data and then determining the degree of causality, rather than providing information about time lag.
If anyone knows about MSM, SNM, their use in R, or how they might relate to this problem, that would be awesome to hear.
What about survival analysis or SEM?
I haven't explored these options very in-depth yet but they sound potentially relevant.
I've kind of stalled, so any hints about what direction I might want to go would be really appreciated.
Thanks in advance.
A:
When comparing two time series for lead/lag relationships we estimate the cross-correlation function. A statistically significantly high value of this at a particular lag may be indicative of a relationship like the one you are looking for.
| {
"pile_set_name": "StackExchange"
} |
Q:
Cleaning a data.frame in a semi-reshape/semi-aggregate fashion
First time posting something here, forgive any missteps in my question.
In my example below I've got a data.frame where the unique identifier is the tripID with the name of the vessel, the species code, and a catch metric.
> testFrame1 <- data.frame('tripID' = c(1,1,2,2,3,4,5),
'name' = c('SS Anne','SS Anne', 'HMS Endurance', 'HMS Endurance','Salty Hippo', 'Seagallop', 'Borealis'),
'SPP' = c(101,201,101,201,102,102,103),
'kept' = c(12, 22, 14, 24, 16, 18, 10))
> testFrame1
tripID name SPP kept
1 1 SS Anne 101 12
2 1 SS Anne 201 22
3 2 HMS Endurance 101 14
4 2 HMS Endurance 201 24
5 3 Salty Hippo 102 16
6 4 Seagallop 102 18
7 5 Borealis 103 10
I need a way to basically condense the data.frame so that all there is only one row per tripID as shown below.
> testFrame1
tripID name SPP kept SPP.1 kept.1
1 1 SS Anne 101 12 201 22
2 2 HMS Endurance 101 14 201 24
3 3 Salty Hippo 102 16 NA NA
4 4 Seagallop 102 18 NA NA
5 5 Borealis 103 10 NA NA
I've looked into tidyr and reshape but neither of those are can deliver quite what I'm asking for. Is there anything out there that does this quasi-reshaping?
A:
Here are two alternatives using base::reshape and data.table::dcast:
1) base R
reshape(transform(testFrame1,
timevar = ave(tripID, tripID, FUN = seq_along)),
idvar = cbind("tripID", "name"),
timevar = "timevar",
direction = "wide")
# tripID name SPP.1 kept.1 SPP.2 kept.2
#1 1 SS Anne 101 12 201 22
#3 2 HMS Endurance 101 14 201 24
#5 3 Salty Hippo 102 16 NA NA
#6 4 Seagallop 102 18 NA NA
#7 5 Borealis 103 10 NA NA
2) data.table
library(data.table)
setDT(testFrame1)
dcast(testFrame1, tripID + name ~ rowid(tripID), value.var = c("SPP", "kept"))
# tripID name SPP_1 SPP_2 kept_1 kept_2
#1: 1 SS Anne 101 201 12 22
#2: 2 HMS Endurance 101 201 14 24
#3: 3 Salty Hippo 102 NA 16 NA
#4: 4 Seagallop 102 NA 18 NA
#5: 5 Borealis 103 NA 10 NA
| {
"pile_set_name": "StackExchange"
} |
Q:
Pointer Cursor not showing
I'm using ReactJS for this. I have a custom upload image button on my page
.upload-btn-wrapper {
position: relative;
overflow: hidden;
display: inline-block;
cursor: pointer;
}
.upload-btn-wrapper input[type=file] {
font-size: 100px;
position: absolute;
left: 0;
top: 0;
opacity: 0;
}
<div className='upload-btn-wrapper'>
<a onClick={this.changePageImage}>Change Image</a>
<input type='file' name='page_photo' onChange={this.photoChangeHandler} />
</div>
My question is why is the pointer cursor not showing up when I hover over the wrapper? I noticed there is a tiny sweet spot in the bottom left hand corner of the a tag but it's just in the one tiny spot.
I've even tried this
.upload-btn-wrapper a:hover {
position: relative;
overflow: hidden;
display: inline-block;
cursor: pointer;
}
A:
upload-btn-wrapper input[type=file] Is set to position: absolute; And is therefore containing the whole upload-btn-wrapper block. In other words, your anchor is behind the input that is absolute positioned, so you are unable to hover over it.
You can add z-index to the anchor tag to move it up a step, or move the input behind using negative z-index.
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I increment a value using an SQL update statement for each TAG record value
I am executing a SSIS ETL process that loads data into a table and uses a execute SQL statement as the last component of execution to update TAG values based on the value of the Content column. An example is
update [payments].[MTFileValidationData_UAT]
set TAG = 'Header'
where left(content,3) = '{1:' and [TransactionId] = ?
This is actually done for a series of different tags. Once this is done, there is a column called FileSequenceNumber that needs to be updated with a number for each tag so I can eventually compare UAT and Production files against each other for testing purposes.
What I need as well is to update the column FileSequenceNumber to give me a sequential number per each tag for each filename.
Expected result:
RowID | TransactionId | FileName | FileType | Tag | Content | Location | FileSequenceNumber |
------+---------------+----------+----------+-----+---------+----------+--------------------+
1 9052312 ABCFile NULL Header XXX October 1
2 9052312 ABCFile NULL Header ZZZ October 2
3 9052312 ABCFile NULL Header YYY October 3
3 9052312 ABCFile NULL 32B YYY October 1
3 9052312 ABCFile NULL 32B YYY October 2
3 9052312 ABCFile NULL 32B YYY October 3
A:
I believe you're looking to use the fancy windowing functions available with SQL Server 2012+. Specifically, ROW_NUMBER
UPDATE
T
SET
FileSequenceNumber = ROW_NUMBER() OVER (PARTITION BY T.Tag ORDER BY RowID)
FROM
dbo.myTable AS T;
The partition by resets the counter each time the tag changes
The order by specifies how the sequence should be generated within the tag column.
As noted from the comment, window functions can only appear in the select or oder by clause so we have to modify to meet the criteria. DBFiddle for working repro https://dbfiddle.uk/?rdbms=sqlserver_2019&fiddle=d731c14c9e15d70eb3b1d34f7b0f61a8
UPDATE
T
SET
T.FileSequenceNumber = TI.FileSequenceNumber
FROM
dbo.SO_61461648 AS T
INNER JOIN
(
SELECT
FileSequenceNumber = ROW_NUMBER() OVER (PARTITION BY TI.Tag ORDER BY TI.RowID)
, TI.RowID
FROM
dbo.SO_61461648 AS TI
) aS TI
ON TI.RowID = T.RowID;
In the event that the supplied data was accurate and there are 4 rows with the same RowID, then you'd need to take a heavy handed approach and dump the table and reload it.
-- Heavy handed approach to dump the table and reload with new value in case RowID is not unique
declare @Intermediary table
(
RowID int NOT NULL
, Tag varchar(30) NOT NULL
);
DELETE T
OUTPUT DELETED.RowID, DELETED.Tag
INTO @intermediary(RowID, Tag)
FROM
dbo.SO_61461648 AS T;
INSERT INTO
dbo.SO_61461648
SELECT
D.*
, ROW_NUMBER() OVER (PARTITION BY D.Tag ORDER BY D.RowID)
FROM @Intermediary AS D;
SELECT * FROM dbo.SO_61461648 AS T order by RowID, FileSequenceNumber;
| {
"pile_set_name": "StackExchange"
} |
Q:
"StringBuffer sb = new StringBuffer()" get a null value in Android
I use the code below which in my http get request,but what I get from return is a null.I don't know why.
public static String getResponseFromGetUrl(String url) throws Exception {
StringBuffer sb = new StringBuffer();
try {
HttpResponse httpResponse = httpclient.execute(httpRequest);
String inputLine = "";
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
InputStreamReader is = new InputStreamReader(httpResponse
.getEntity().getContent());
BufferedReader in = new BufferedReader(is);
while ((inputLine = in.readLine()) != null) {
sb.append(inputLine);
}
in.close();
}
} catch (Exception e) {
e.printStackTrace();
return "net_error";
} finally {
httpclient.getConnectionManager().shutdown();
}
return sb.toString();
}
And what I have use the function is
String json_str = HttpUtils.getResponseFromGetUrl("www.xxx.com/start");
if ((json_str == null)) Log.d("Chen", "lastestTimestap----" + "json_str == null");
And sometimes the Log will be printed.Not always,in fact like 1%.But I don't know why it caused.
A:
This code will not produce a "null". There must be more code you are not showing.
If this is all the code you have I suggest you remove the StringBuffer and replace it with
return "";
More likely you have forgetten to mention some code which is doing something like
Object o = null;
sb.append(o); // appears as "null"
EDIT: Based on your update, I would have to assume you are reading a line like "null"
It is highly unlikely you want to discard the newline between each line. I suggest either you append("\n") as well or just record all the text you get without regard for new lines.
BTW Please don't use StringBuffer as its replacement StringBuilder has been around for almost ten years. There is a common misconception that using StringBuffer helps with multi-threading but more often it results in incorrect code because it is very harder, if not impossible to use StringBuffer correctly in a multi-threaded context
| {
"pile_set_name": "StackExchange"
} |
Q:
dovecot permission issue
I'm getting in my syslog the following warning
27 16:53:54 h2004156 dovecot: imap-login: Login: user=<[email protected]>, method=PLAIN, rip=89.16.141.57, lip=85.214.254.164, mpid=14496, TLS
Jan 27 16:53:54 h2004156 dovecot: imap([email protected]): Error: chdir(/var/vmail/user/test/) failed: Permission denied (euid=5000(vmail) egid=5000(vmail) missing +x perm: /var/vmail, dir owned by 150:8 mode=0770)
previously I have been adding vmail group and user but doesn't seems to work
A:
The message is telling you exactly what the problem is: Dovecot (running under uid&gid 5000) doesn't have execute (search) permission on the /var/vmail directory. It's even telling you what the owner, group, and mode of the problematic directory is! Did you change the permissions of this directory recently? Was the group ID of that directory supposed to be 5000 (instead of 8) or perhaps was the mode supposed to be 0771 (instead of 0770)?
| {
"pile_set_name": "StackExchange"
} |
Q:
Is Goldstein's matrix formalism to Hamiltonian mechanics necessary?
I am trying to see whether the matrix formalism of the Hamiltonian formalism (used in Goldstein's textbook) is truly necessary to solve problem in this framework.
It appears so based on the problem I've run into. From problem 8.15 in Goldstein we have
A dynamical system has the Lagrangian $$ L= \dot{q}_1{}^2 + \frac{\dot{q}_2{}^2}{a+bq_1{}^2} + k_1q_1{}^2 +k_2\dot{q}_1\dot{q}_2$$ where a,b,$k_1$, and $k_2$ are constants. Find the equations of motion in the Hamiltonian formalism.
Using $H=p^i\dot{q}_i-L$ (where $i=\{1,2\}$ and are summed over) I find that the Hamiltonian is
$$ H= \dot{q}_1{}^2 + \frac{\dot{q}_2{}^2}{a+bq_1{}^2} +k_2\dot{q}_1\dot{q}_2 -k_1q_1{}^2 $$
My concern comes in with the equations of motion.
In particular, consider how one would solve $\frac{\partial H}{\partial p_i} = \dot{q}_i$.
Using $p_i = \frac{\partial L}{\partial \dot{q}_i}$ I find
$$ p_1 = 2\dot{q}_1 + k_2 \dot{q}_2, \text{ and}$$
Unless there is some advanced chain rule having to do with taking partials of functions of several variables with respect to other fucntions of several variables, I think I really ought to look into this matrix formalism that Goldstein uses.
However, I'm not so sure about this matrix formalism. I'm quite confident that my Hamiltonian above is correct. How could it not be? Quite basic, no? However, this solution online uses the matrix formalism from Goldstein and they obtain a different Hamiltonian.
Can I have some insights on if my methods are not well-suited?
A:
The Hamiltonian is a function of the $p$'s and $q$'s, not the $\dot q$'s and $q$'s. Your expression is right, with the understanding that $\dot q_i = \dot q_i(p_1,p_2,q_1,q_2)$.
You need to invert the expressions $p_i = \frac{\partial L}{\partial \dot q_i}$ to obtain the $\dot q$'s as functions of the $p$'s and $q$'s and substitute the results into your expression for $H$. This is somewhat messy and aggravating, but it's what you have to do to obtain the explicit form of the Hamiltonian. From there, you can apply the Hamilton equations to get the equations of motion for the system.
As a side note, you never need to write systems of equations in matrix form; it's just that it is often extremely useful and convenient to do so. Whether you solve for the $\dot q$'s in terms of the $p$'s via substitution or matrix inversion is up to you, but given that this would correspond to a 2x2 matrix, you should be able to instantly write down the inverse transformation. In my opinion, that is the easier route, but you're free to do as you like.
| {
"pile_set_name": "StackExchange"
} |
Q:
Trouble With Overload Resolution
Id like to say that there's a ton of C++ Overloading questions already on SO, but after an hour of looking at them and other posts on forums and newsgroups, I'm still stumped.
Background
I've created a namespace, call it A, where a bunch of classes have the same way of implementing the < operator. In order to avoid code duplication, I wrote this:
namespace A{
template<typename T>
bool operator< (const T&, const T&);
}
In a header file called operator_forwards.h along with a few other declarations.
I then made it a friend to the correct classes by adding a line like this:
//example.h
#include "operator_forwards.h"
namespace A{
template<typename T>
class Example{
public:
friend bool operator< <>(const Example<T>&, const Example T&);
private:
T start;
};
}
Finally, I put the definition in a file called operators.h like this:
namespace A{
template<typename T>
bool operator<(const T& lhs, const T& rhs){
using std::operator<;
return lhs.start<rhs.start;
}
}
And included everything in one header file:
//A.h
#include "example.h"
#include "operators.h"
The Problem
The problem is when I call operator< like this:
Example<vector<int>::iterator> ex1(**foo**);
Example<vector<int>::iterator> ex2(**bar**);
ex1<ex2;
It calls A::operator< fine, however it recursively calls itself to do ex1.start<ex2.start rather then looking up the more specialized operator< for vector::iterator. Resulting in the error C2039: start is not a member of vector::iterator.
Does anyone have any advice for making sure that A::operator< calls the correct operator< for ex1.start?
Note: there are about 20 classes that use A::operator< so if I could avoid defining it in each class separately that'd be awesome.
A:
My humble suggestion: don't do that.
You'll have to deal with this problem in more places than the implementation of A::operator<. Any code anywhere in A can potentially get bamboozled by this unexpected template which claims to support operator< for anything, but can only actually perform it on types which have a start member.
In your case, you're putting a friend declaration in every relevant class anywhere. It's barely any more code to simply implement it in those classes. If that offends your code-duplication sensibilities, then consider a shared base class:
template <typename T>
class IterWrapper {
public:
IterWrapper() {}
explicit IterWrapper(T it) : start(it) {}
bool operator< (const IterWrapper<T>& rhs) { return start < rhs.start; }
protected:
T start;
};
| {
"pile_set_name": "StackExchange"
} |
Q:
When is earliest mention of the Church tradition that Jesus was born in a cave?
The birth of Jesus as recounted by Luke says that:
7 And she gave birth to her first-born son and wrapped him in swaddling cloths, and laid him in a manger, because there was no place
for them in the inn. Cf. Luke 2:7.
How did it come to be known in Church Tradition that Jesus was born in a cave, and when is earliest mention of this tradition?
A:
The earliest reference I can find is Justin Martyr (c. 100 – 165 AD) who wrote in Dialog With Trypho:
But when the Child was born in Bethlehem, since Joseph could not find
a lodging in that village, he took up his quarters in a certain cave
near the village; and while they were there Mary brought forth the
Christ and placed Him in a manger. (1)
A:
There is a short prequel to the gospels called the Protevangelium of James, supposedly written about 150 ad., but it is noncanonical and certainly not an eyewitness account. The author claims to have been walking in a field and this vision just came to him. Although I don't believe that it is authentic history, it does mention Mary going into a cave with her midwife, and there is a big flash of light when Jesus is born. Interesting, but nothing more.
| {
"pile_set_name": "StackExchange"
} |
Q:
Python Game Movement
I am working on a simulation for a business problem, but I am trying to build a 2d game to demonstrate the simulated movements.
To do this, I am starting off with an actual python game that I found some code for online.
The goal is to create 100s of simulated movements (up, down, left, right, stop) via random integer. For example, random = 1, then move left.
For some reason I am able to send the first movement, but the second to 100th movements are ignored by the game.
Can someone please give me a hint as to what I'm doing wrong?
I would greatly appreciate someone's expertise.
GitHub Link :: https://github.com/deacons2016/pygame
from __future__ import division
import random
from cocos.actions import AccelDeccel
from cocos.actions import Delay
from cocos.actions import JumpBy
from cocos.actions import Move
from cocos.actions import MoveBy
from cocos.actions import Repeat
from cocos.actions import Reverse
from cocos.actions import RotateBy
from pyglet.window import key
import cocos
import cocos.collision_model as cm
import resources
import time
class Game(cocos.layer.ColorLayer):
is_event_handler = True
def __init__(self):
super(Game, self).__init__(102, 102, 225, 255)
self.collision_manager = cm.CollisionManagerBruteForce()
self.player = cocos.sprite.Sprite(resources.player)
self.player.position = 400, 25
self.player.velocity = 0, 0
self.player.speed = 150
self.add(self.player, z=2)
self.player.cshape = cm.AARectShape(
self.player.position,
self.player.width//2,
self.player.height//2
)
self.collision_manager.add(self.player)
self.boss = cocos.sprite.Sprite(resources.player)
self.boss.position = 400, 600
self.boss.scale = 0.4
self.add(self.boss, z=1)
self.boss.cshape = cm.AARectShape(
self.boss.position,
self.boss.width//2,
self.boss.height//2
)
self.collision_manager.add(self.boss)
self.batch = cocos.batch.BatchNode()
self.enemies = [cocos.sprite.Sprite(resources.player)
for i in range(6)]
positions = ((250, 125), (550, 125), (300, 325), (500, 325),
(150, 475), (650, 475))
for num, enem in enumerate(self.enemies):
enem.position = positions[num]
enem.cshape = cm.AARectShape(
enem.position,
enem.width//2,
enem.height//2
)
self.collision_manager.add(enem)
self.batch.add(enem)
self.add(self.batch, z=1)
self.player.do(Move())
move_basic = MoveBy((120, 0), 1)
self.enemies[0].do(Repeat(move_basic + Reverse(move_basic)))
self.enemies[1].do(Repeat(Reverse(move_basic) + move_basic))
move_complex = (MoveBy((-75, 75), 1) +
Delay(0.5) +
MoveBy((-75, -75), 1) +
Delay(0.5) +
MoveBy((75, -75), 1) +
Delay(0.5) +
MoveBy((75, 75), 1) +
Delay(0.5))
self.enemies[2].do(Repeat(move_complex))
self.enemies[3].do(Repeat(Reverse(move_complex)))
move_jump = AccelDeccel(JumpBy((200, 0), 75, 3, 3))
move_jump_rot = AccelDeccel(RotateBy(360, 3))
self.enemies[4].do(Repeat(move_jump + Reverse(move_jump)))
self.enemies[4].do(Repeat(move_jump_rot + Reverse(move_jump_rot)))
self.enemies[5].do(Repeat(Reverse(move_jump) + move_jump))
self.enemies[5].do(Repeat(Reverse(move_jump_rot) + move_jump_rot))
self.schedule(self.update)
def simulate(self):
x = 100
while x > 0:
rand = random.randint(1,5)
if rand == 1:
self.movePlayer("left")
time.sleep(.05)
print("left")
elif rand == 2:
self.movePlayer("right")
time.sleep(.05)
print("right")
elif rand == 3:
self.movePlayer("up")
time.sleep(.05)
print("up")
elif rand == 4:
self.movePlayer("down")
time.sleep(.05)
print("down")
elif rand == 5:
self.movePlayer("space")
time.sleep(.05)
print("space")
x -= 1
def update(self, dt):
self.player.cshape.center = self.player.position
for enem in self.enemies:
enem.cshape.center = enem.position
collisions = self.collision_manager.objs_colliding(self.player)
if collisions:
if self.boss in collisions:
print("You won!")
cocos.director.director.pop()
def movePlayer(self, symbol):
if symbol == "left":
self.player.velocity = -self.player.speed, 0
elif symbol == "right":
self.player.velocity = self.player.speed, 0
elif symbol == "up":
self.player.velocity = 0, self.player.speed
elif symbol == "down":
self.player.velocity = 0, -self.player.speed
elif symbol == "space":
self.player.velocity = 0, 0
if __name__ == '__main__':
cocos.director.director.init(
width=800,
height=650,
caption="Catch your husband!"
)
game_layer = Game()
game_scene = cocos.scene.Scene(game_layer)
game_layer.simulate()
cocos.director.director.run(game_scene)
print("after")
A:
Like @Blckknght pointed out, drawing the layer Game and running its other scheduled functions (in your case Game.update) starts only after calling cocos.director.director.run(game_scene). That is why you cannot see the velocity updates - they are done by the time drawing begins.
You should remove the call game_layer.simulate() as it doesn't have the desired effect.
Then you could do:
def simulate(self, dt):
if self.x > 0: # set this to 100 in constructor
rand = random.randint(1,5)
if rand == 1:
self.movePlayer("left")
print("left")
elif rand == 2:
self.movePlayer("right")
print("right")
elif rand == 3:
self.movePlayer("up")
print("up")
elif rand == 4:
self.movePlayer("down")
print("down")
elif rand == 5:
self.movePlayer("space")
print("space")
x -= 1
Notice that I removed calls to time.sleep. Not sure if those would cause problems, but it's probably better to call the dedicated schedule_interval (or schedule) function in cocos2d.
In the constructor of Game:
self.schedule_interval(self.simulate, 0.05)
self.schedule_interval(self.update, 0.05)
To schedule Game.simulate you must change the signature of the function to have dt as its second argument, like Game.update has.
| {
"pile_set_name": "StackExchange"
} |
Q:
Nutch Newbie - JSP with html problem
System: Mac OSX
I have set up nutch so that it crawls and indexes my site. It also returns search results. My problem is that I want to customise the Nutch index.jsp and search.jsp pages to fit with my site. Ive read up and on jsp and it says its just a matter of putting in the html tags and then using <% %> to enclose the Java scriplets you want. For some reason nothing changes when i edit the files (index and search)
Here is what the original file displays:
<%@ page
session="false"
import="java.io.*"
import="java.util.*"
%><%
String language =
ResourceBundle.getBundle("org.nutch.jsp.search", request.getLocale())
.getLocale().getLanguage();
String requestURI = HttpUtils.getRequestURL(request).toString();
String base = requestURI.substring(0, requestURI.lastIndexOf('/'));
response.sendRedirect(language + "/");
%>
Here is my edited version with sum gibberish test added to test it:
<html>
<head>
</head>
<body>
gigigyigig
<%@ page
session="false"
import="java.io.*"
import="java.util.*"
%><%
String language =
ResourceBundle.getBundle("org.nutch.jsp.search", request.getLocale())
.getLocale().getLanguage();
String requestURI = HttpUtils.getRequestURL(request).toString();
String base = requestURI.substring(0, requestURI.lastIndexOf('/'));
response.sendRedirect(language + "/");
%>
ghjgjkbkhb
hjgjvjhvj
</body>
</html>
Nothing has changed tho and the nutch homepage/index.jsp still displays the same as original. This is my first encounter with JSP so its just what ive picked up so far. Can anyone tell me why the page isnt displaying the html with gibberish typed??
A:
I have my search totaly modified. However I have my <html>... tags after the second scriptlet ie <% %> not <%@ page.
As for your index.jsp modified it has a redirection response.sendRedirect and therefore it looks normal to me that you see nothing.
Also I presume you took care of loading the jsp pages at the right place under the tomcat/webapps tree, because the standard ant make file doesn't. So I ended up adding some Ant task to patch my test website.
Beware if you are going to change the .jar files you also need to restart Tomcat.
| {
"pile_set_name": "StackExchange"
} |
Q:
Wait() statement with Swing
I have 2 buttons. 1st starts thread, 2nd makes it wait. 1st button works fine, but second doesn't want to stop 1st button thread. What's wrong? How to make it stop?
package SwingExp;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class WhichButton implements ActionListener {
JLabel jLab, testLab = new JLabel();
JFrame jfrm = new JFrame("Button example");
JButton firstButton = new JButton("First"), secondButton = new JButton("Second");
WhichButton() {
jfrm.setLayout(new FlowLayout());
jfrm.setSize(220, 90);
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
firstButton.addActionListener(this);
secondButton.addActionListener(this);
jfrm.add(firstButton);
jfrm.add(secondButton);
jLab = new JLabel("Press button");
jfrm.add(jLab);
jfrm.add(testLab);
jfrm.setVisible(true);
}
class SimpleThread extends Thread {
Thread t;
boolean suspendFlag;
SimpleThread() {
t = new Thread(this, "settingThread");
t.start();
}
public void run() {
for (int i = 0; i <= 10; i++) {
synchronized (this) {
while (suspendFlag) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
}
testLab.setText(Integer.toString(i));
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
}
firstButton.setEnabled(true);
testLab.setText("Completed.");
}
synchronized void setSuspendFlag(boolean suspendFlag) {
this.suspendFlag = suspendFlag;
}
}
public void actionPerformed(ActionEvent e) {
SimpleThread st = new SimpleThread();
if (e.getActionCommand().equals("First")) {
jLab.setText("First");
firstButton.setEnabled(false);
st.setSuspendFlag(false);
} else {
st.setSuspendFlag(true);
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new WhichButton();
}
});
}
}
I was trying to use interrupt() method, but it makes me one more thread or something like that.
A:
you need to notify() the sleeping thread in the setSuspendFlag() method. otherwise, the thread will block forever in the wait() call.
Also, every time your buttons are pressed, you are creating a new SimpleThread instance. you need to make the SimpleThread instance a member variable and only create it once.
| {
"pile_set_name": "StackExchange"
} |
Q:
Is it possible forbid the switching of NSTabView
I hope to forbid the switching of NSTabView. Is it possible?
When click the tab of NSTabView, what event does it trigger?
I can not found any sendaction relates to this.
Welcome any comment.
Thanks
interdev
A:
Implement the NSTabViewDelegate method:
- (BOOL)tabView:(NSTabView *)tabView shouldSelectTabViewItem:(NSTabViewItem *)tabViewItem
| {
"pile_set_name": "StackExchange"
} |
Q:
Had had (Is it a past perfect or past simple)
Look at the sentence that is in Italic. I wonder if had had there is the past-perfect or is it the Past Simple followed by 'had to'? I'm confused.
Helen stepped outside her front door to see what the weather was like.
It was sunny and warm. That was nice, because for the past two weeks
it had been cold and rainy. It had been so cold that she had had to
turn her heater on. She was lucky, because her heater worked and she
could pay her heating bills.
A:
The past perfect is used to talk about actions that happened before something else. The story is told in the past simple. To refer to the past two weeks, we need to change the tense to the past perfect.
She had had to turn is the past perfect form of she has to turn.
It had been so cold that she had needed to turn her heater on.
The cold had forced her to turn her heater on.
| {
"pile_set_name": "StackExchange"
} |
Q:
Insertion of array to file error
I use the following code to insert array of structure to file but it crash:
void SaveInFile(List * pl)
{
int i;
int s = ListSize(pl);
file = fopen("myFile.txt", "w"); //3shan aktb 3la file mn gded
for (i = 0; i <= s; i++) {
file = fopen("myFile.txt", "a");
fprintf(file, "IDOfprocess%s/n", pl->entry[i].ID);
fprintf(file, "IDOfprocess%s/n", pl->entry[i].BurstTime);
}
fclose(file);
}
Any idea how to solve this?
A:
You are opening the file multiple times without closing it.
This will do:
void SaveInFile(List* pl)
{
int i;
int s=ListSize(pl);
file=fopen("myFile.txt","w");//3shan aktb 3la file mn gded
fclose(file);
for( i=0;i<=s;i++){
file=fopen("myFile.txt","a");
fprintf(file,"IDOfprocess%s/n",pl->entry[i].ID);
fprintf(file,"IDOfprocess%s/n",pl->entry[i].BurstTime);
fclose(file);
}
}
If you do not close the file, the content of any unwritten output buffer is not written to the file.
But what you should actually do is open the file one time and perform the append operations:
void SaveInFile(List* pl)
{
int i;
int s=ListSize(pl);
file=fopen("myFile.txt","w");//3shan aktb 3la file mn gded
fclose(file);
file=fopen("myFile.txt","a");
for( i=0;i<=s;i++){
fprintf(file,"IDOfprocess%s/n",pl->entry[i].ID);
fprintf(file,"IDOfprocess%s/n",pl->entry[i].BurstTime);
}
fclose(file);
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Count DOM elements with CasperJS' evaluate failed
I've just got trouble with CasperJS.
I need to count table rows, since there are many tables that contain same information structure (lets say user table)
So I do some casperjs evaluate code like this
var table_rows1 = casper.evaluate(function(it){ return jQuery("#dResult > div:nth-child("+1+") > div > div:nth-child(4) > div:nth-child("+it+") > div:nth-child(1) > span > div").length; }, it);
It is iterator, it will increasing until reach the table element length.
So lets say we have 3 tables, so it will be 1,2,3
For it = 1, there are no problem occured, its print out the correct table[1] rows number.
But for next it, 2,3, it just print 1 for table rows number.
How it could be become so weird like this?
This is my CasperJS snippet:
function getNumber(it){
window.__utils__.echo("it :"+it);
var query = "#dResult > div:nth-child("+1+") > div > div:nth-child(4) > div:nth-child("+it+") > div:nth-child(1) > span > div";
return jQuery(query).length;
}
var table_rows1 = casper.evaluate(getNumber, 1);
var table_rows2 = casper.evaluate(getNumber, 2);
var table_rows3 = casper.evaluate(getNumber, 3);
this.echo("table rows #1 :"+table_rows1);
this.echo("table rows #2 :"+table_rows2);
this.echo("table rows #3 :"+table_rows3);
And this is the html which I need to scrape...
This is for 1 table, there are many html tags like this
<div class="padd-b-rates">
<div id="showRateWSMA0511000015CL096-CL124">
<div class="bd-rate-in">
<div class="rth1"><b>Room Category </b></div>
<div class="rth2"><b>Breakfast</b></div>
<div class="rth3"><b>Total Stay</b></div>
<div class="rth4"><b>Room Status</b></div>
<div class="clear"></div>
</div>
<span id="RateWSMA0511000015CL096-CL124">
<div class="bd-rate-row">
<div class="rtd1"><span class="rmname-rsht-rate">DELUXE (NRF)</span><i></i></div>
<div class="rtd2"><span>Breakfast</span><i></i></div>
<div class="rtd3"><span><a href="javascript:sHC.ShowPrice('WSMA0511000015','WSMA140400017', 'BB','CL096-CL124');">2,174,005.00 IDR</a></span><i></i></div>
<div class="rtd4"><span class="btn-rsht-rate" onclick="sHC.jumpToPaxdetail(this);" hotelcode="WSMA0511000015" suppliercode="CL096-CL124" droomcatg="WSMA140400017-BB" roomstatus="Y" id="bookWSMA0511000015WSMA140400017-BB-CL096-CL124"><img border="0" src="/b2b/images/result-hotels/btnAV-v3.gif"></span></div>
<div class="clear"></div>
</div>
<div class="bd-rate-row">
<div class="rtd1"><span class="rmname-rsht-rate">EXECUTIVE (NRF)</span><i></i></div>
<div class="rtd2"><span>Breakfast</span><i></i></div>
<div class="rtd3"><span><a href="javascript:sHC.ShowPrice('WSMA0511000015','WSMA140400018', 'BB','CL096-CL124');">2,505,557.00 IDR</a></span><i></i></div>
<div class="rtd4"><span class="btn-rsht-rate" onclick="sHC.jumpToPaxdetail(this);" hotelcode="WSMA0511000015" suppliercode="CL096-CL124" droomcatg="WSMA140400018-BB" roomstatus="Y" id="bookWSMA0511000015WSMA140400018-BB-CL096-CL124"><img border="0" src="/b2b/images/result-hotels/btnAV-v3.gif"></span></div>
<div class="clear"></div>
</div>
<div class="bd-rate-row">
<div class="rtd1"><span class="rmname-rsht-rate">DELUXE</span><i></i></div>
<div class="rtd2"><span>Room Only</span><i></i></div>
<div class="rtd3"><span><a href="javascript:sHC.ShowPrice('WSMA0511000015','WSMA05110034', 'RO','CL096-CL124');">2,743,860.00 IDR</a></span><i></i></div>
<div class="rtd4"><span class="btn-rsht-rate" onclick="sHC.jumpToPaxdetail(this);" hotelcode="WSMA0511000015" suppliercode="CL096-CL124" droomcatg="WSMA05110034-RO" roomstatus="Y" id="bookWSMA0511000015WSMA05110034-RO-CL096-CL124"><img border="0" src="/b2b/images/result-hotels/btnAV-v3.gif"></span></div>
<div class="clear"></div>
</div>
<div class="bd-rate-row">
<div class="rtd1"><span class="rmname-rsht-rate">DELUXE</span><i></i></div>
<div class="rtd2"><span>Breakfast</span><i></i></div>
<div class="rtd3"><span><a href="javascript:sHC.ShowPrice('WSMA0511000015','WSMA05110034', 'BB','CL096-CL124');">2,847,470.00 IDR</a></span><i></i></div>
<div class="rtd4"><span class="btn-rsht-rate" onclick="sHC.jumpToPaxdetail(this);" hotelcode="WSMA0511000015" suppliercode="CL096-CL124" droomcatg="WSMA05110034-BB" roomstatus="Y" id="bookWSMA0511000015WSMA05110034-BB-CL096-CL124"><img border="0" src="/b2b/images/result-hotels/btnAV-v3.gif"></span></div>
<div class="clear"></div>
</div>
</span>
</div>
<div class="bd-rate-bottom">
<div class="rsht-cxl" id="CancelPolicyWSMA0511000015CL096-CL124" onclick="sHC.rCancel('WSMA0511000015CL096-CL124','CL096-CL124');" title="Click for view cancellation policy">
<textarea id="PolicyWSMA0511000015CL096-CL124" style="display:none"></textarea>
Cancellation Policy </div>
<div class="rsht-promotion" id="FOCWSMA0511000015CL096-CL124" onmouseover="sHC.popupHotelFOC(this, 'WSMA0511000015CL096-CL124','CL096-CL124');" detail="" style="display:none;">(Special Promotion)</div>
<div class="rsht-message" id="lyHotelMessageWSMA0511000015CL096-CL124"><blink><b><font color="red">Hotel Message</font> : </b></blink> <span id="HotelMessageWSMA0511000015CL096-CL124" style="word-wrap:break-word;">Complimentary WIFI internet access</span></div>
<div class="clear"></div>
</div>
</div>
If there are another table structure like this, the evaluate function just return 1 or even 0...
so whats the problem about this case?
This is what I've got if I did my jQuery dom counting in inspect element chrome browser
jQuery("#dResult > div:nth-child("+1+") > div > div:nth-child(4) > div:nth-child("+1+") > div:nth-child(1) > span > div").length;
8
jQuery("#dResult > div:nth-child("+1+") > div > div:nth-child(4) > div:nth-child("+2+") > div:nth-child(1) > span > div").length;
15
A:
Your selectors look fine. There are multiple things that might have happened...
Waiting
The site is not fully loaded (dynamic site/SPA) which means that you're trying to access those elements too early. You could for example wait for the first elements to appear and then access all of them:
casper.waitFor(function check(){
return this.evaluate(getNumber, 1) > 0;
}, function then(){
var table_rows1 = this.evaluate(getNumber, 1);
var table_rows2 = this.evaluate(getNumber, 2);
...
});
With XPath
PhantomJS has a bug with :nth-child() selectors which only appears for specific constellations. You can try to use XPath expressions for that.
function getNumber(it){
var query = "//*[@id='dResult']/*["+1+"]/div/*[4]/*["+it+"]/*[1]/span/div";
return __utils__.getElementsByXPath(query).length;
}
The reason I use *[x] instead of div[x] is because XPath takes the element name into account when querying according to a position, but CSS selectors do not.
Different mobile page
Sometimes the server delivers a different page according to the user agent string or the viewport. PhantomJS has a default viewport size of 400x300. Maybe the page was dynamically changed by the page JavaScript.
Check the screenshot (casper.capture()) whether the page looks the same way as in Chrome.
Dump the page source with casper.debugHTML() and compare it with the Chrome version.
Generic problems
There may be other problems with the page. Look for errors with the various event handlers. Please register to the resource.error, page.error, remote.message and casper.page.onResourceTimeout events (Example).
| {
"pile_set_name": "StackExchange"
} |
Q:
Macbook randomly shutdown 4k external monitor
I have a Macbook 16inch connecting to Dell 24inch 4k P2415Q with Moshi USB-C to Mini DisplayPort, bought from Apple.
After 1-2 hours the monitor just shut down like there's no signal, macbook still running. I have to turn off and turn on the monitor to reconnect but it keeps happening all day.
I've done these things so far:
Open / Close lid while connecting to the monitor.
Switch between ports.
Reset NVRAM, PRAM, SMC.
Tested with Macbook 13 (2016), same problem
Tested with my gaming desktop, same monitor same cable, working well, no issue.
Has anyone experienced same issue before ?
A:
Turn out the problem is the the monitor. I've bought a new one and it's ok now.
Still don't know why it only happened to Macbooks not windows
| {
"pile_set_name": "StackExchange"
} |
Q:
What is the unit for resonant frequency?
What is the unit for resonant frequency? where \$\omega_0 = \frac{1}{\sqrt{LC}}\$? Is it just \$HF^{-1}\$?
A:
In the simplest way possible:
L is in henries (H) - \$\Omega \cdot s\$.
C is in farads (F) - \$\dfrac{s}{\Omega}\$
Multiply both and you have \$s^2\$. Take the square root, you have \$s\$. Invert it, you have \$\dfrac{1}{s}\$, that is, \$\frac{rad}{s}\$.
If the expression is written as \$\omega_0 = \dfrac{1}{2\pi\sqrt{LC}}\$ the resonant frequency is in hertz.
| {
"pile_set_name": "StackExchange"
} |
Q:
Check if product type is grouped, without loading whole product
I want to check whether a certain product is of type 'grouped' or something else. And, i need to do this without loading the whole product.
Now for other attributes the code below seems to work perfectly well.
$productResource = $this->objectManager->create('Magento\Catalog\Model\ResourceModel\Product\Action');
$uom = $productResource->getAttributeRawValue($productId, 'uom', $storeId);
But somehow this fails:
$type = $productResource->getAttributeRawValue($productId, 'type_id', $storeId);
$type is always empty.
A:
type_id is not an eav attribute.
without gathering the whole model, you can do it through raw SQL query(it is the fastest solution I guess)
SELECT type_id FROM catalog_product_entity WHERE entity_id=Your_Product_Id
| {
"pile_set_name": "StackExchange"
} |
Q:
Connecting Bot Framework with LUIS. Which AppId and AppKey should I use?
I am trying to use a LUIS bot connect with a bot that is registered on azure. However, I am confused about which keys and Ids should I use. I have the follow 'informations':
On Azure:
Bot handle, Microsoft App ID and Microsoft App Password.
On LUIS:
App ID, App Name, Programmatic API Key
When coding, in the "LUIS Class", I have:
[LuisModel("ID", "Key")]
[Serializable]
public class EstadosLuis : LuisDialog<object>
{...
Question 1 - What Id and Key should I use here?
On the web.config I have:
<add key="BotId" value="BotName" />
<add key="MicrosoftAppId" value="AppID" />
<add key="MicrosoftAppPassword" value="APPKey" />
Question 2 - What Id and Key should I use here?
Question 3- When using the Microsoft Bot Framework Channel Emulator, which Bot URl, App Id and App Password should I use (Local testing)
Question 4- When using the Microsoft Bot Framework Channel Emulator, which Bot URl, App Id and App Password should I use (Online testing)
Thank you!
A:
Q1: App Id and App Key that you get from your LUIS application that you created in the LUIS.ai page. Refer to this to understand from where in the page you can get this information.
Q2: Microsoft App Id and Microsoft App Password you got from Bot Framework Portal. Refer to this if you don't know how to get them.
Q3
Bot Url: The localhost:port url where your bot is running + /api/messages. Usually its http://localhost:3978/api/messages or http://localhost:3979/api/messages. It must be http.
You don't need to use the AppId and App Password unless you are using ngrok to debug your bot locally against one of the supported channels (which in that case you will be updating the endpoint url in the Bot Framework Portal to be the ngrok one + /api/messages). These are the Microsoft App Id and Microsoft App Password from the Bot Framework Portal
Q4
Bot Url: The url where you hosted your bot + /api/messages. If it's hosted in Azure, then it will be something like https://thenameofyourwebapp.azurewebsites.net/api/messages. It must be https
App Id and App Password: These are the ones you get from the Bot Framework Portal
Remember that in this scenario you will have to replace the Emulator URL with the ngrok forward for the port 9000 as I explained here.
| {
"pile_set_name": "StackExchange"
} |
Q:
Element Not Obeying Vertical-Align: bottom, why?
Why doesn't the middle element obey the vertical-align rule?
How could i get it to do so?
Example:
<div id="outer">
<!-- why doesn't this obey its inline-block and snap to bottom? -->
<div id="inner">From The Smiths</div>
</div>
CSS:
#outer{
top: 0.452873563218px;
left: 23.8988505747126px;
transform: rotate(0deg);
-webkit-transform: rotate(0deg);
width: 284.88275862069px;
height: 58.8229885057471px;
z-index: 5;
font-size: 8.81226053639847px;
position: absolute;
overflow: hidden;
margin: 0;
padding: 0;
}
#inner{
top: 0px;
left: 0px;
font-family: 'Open Sans';
text-align: center;
vertical-align: bottom;
color: rgb(140, 149, 157);
font-weight: 300;
font-size: 8.81226053639847px;
position: relative;
display: inline-block;
width: 100%;
margin: 0;
height: 10px;
padding: 0;
overflow: hidden;
}
Link to jsbin: http://jsbin.com/mavuhikifi/2/
A:
You could set the outer div to display:table and the inner div to display:table-cell
#outer {
top: 0.452873563218px;
left: 23.8988505747126px;
transform: rotate(0deg);
-webkit-transform: rotate(0deg);
width: 284.88275862069px;
height: 58.8229885057471px;
z-index: 5;
font-size: 8.81226053639847px;
position: absolute;
overflow: hidden;
margin: 0;
padding: 0;
display: table;
}
#inner {
top: 0px;
left: 0px;
font-family:'Open Sans';
text-align: center;
vertical-align: bottom;
color: rgb(140, 149, 157);
font-weight: 300;
font-size: 8.81226053639847px;
position: relative;
display: table-cell;
width: 100%;
margin: 0;
height: 10px;
padding: 0;
overflow: hidden;
}
<div id="outer">
<!-- why doesn't this obey its inline-block and snap to bottom? -->
<div id="inner">From The Smiths</div>
</div>
Or use absolute/relative positioning as in this jsFiddle.
| {
"pile_set_name": "StackExchange"
} |
Q:
java equivalent to printf("%*.*f")
In C, the printf() statement allows the precision lengths to be supplied in the parameter list.
printf("%*.*f", 7, 3, floatValue);
where the asterisks are replaced with first and second values, respectively.
I am looking for an equivalent in Android/Java; String.format() throws an exception.
EDIT: Thanks, @Tenner; it indeed works.
A:
I use
int places = 7;
int decimals = 3;
String.format("%" + places + "." + decimals + "f", floatValue);
A little ugly (and string concatenation makes it not perform well), but it works.
A:
System.out.print(String.format("%.1f",floatValue));
This prints the floatValue with 1 decimal of precision
| {
"pile_set_name": "StackExchange"
} |
Q:
Convert a unicode string to its original format
Possible Duplicate:
Converting a latin string to unicode in python
I have a list with the following format after storing in a file
list_example = [
u"\u00cdndia, Tail\u00e2ndia & Cingapura",
u"Lines through the days 1 (Arabic) \u0633\u0637\u0648\u0631 \u0639\u0628\u0631 \u0627\u0644\u0623\u064a\u0627\u0645 1",
]
But the actual format of the strings in the list is
actual_format = [
"Índia, Tailândia & Cingapura ",
"Lines through the days 1 (Arabic) سطور عبر الأيام 1 | شمس الدين خ "
]
How can I convert the strings in list_example to strings present in the actual_format list?
A:
Your question is a bit unclear to me. In any case, the following guidelines should help you solving your problem.
If you define those strings in a Python source code, then you should
know in which character encoding your editor saves the source code file (e.g. utf-8)
declare that encoding in the first line of your source file, via e.g. # -*- coding: utf-8 -*-
define those strings as unicode objects:
strings = [u"Índia, Tailândia & Cingapura ", u"Lines through the days 1 (Arabic) سطور عبر الأيام 1 | شمس الدين خ "]
(Note: in Python 3, literal strings are unicode objects by default, i.e. you don't need the u. In Python 2, unicode strings are of type unicode, in Python 3, unicode strings are of type string.)
When you then want to save those strings to a file, you should explicitly define the character encoding:
with open('filename', 'w') as f:
s = '\n'.join(strings)
f.write(s.encode('utf-8'))
When you then want to read those strings again from that file, you again have to explicitly define the character encoding in order to decode the file contents properly:
with open('filename') as f:
strings = [l.decode('utf-8') for line in f]
| {
"pile_set_name": "StackExchange"
} |
Q:
React-router - How to use multiple private routes?
My project have 2 different roles and both need login.
So I created 2 login pages and 2 private routes are Auth and Trainee
The problem is even I type an url is not children of Auth route it will go through Auth then it all wrong after that
<BrowserRouter>
<Switch>
<Route
exact
path={LoginForAuthPath}
component={LoginForAuthComponent}
/>
<Route
exact
path={LoginForTraineePath}
component={LoginForTraineeComponent}
/>
<Auth>
<Route
exact
path={SomeAuthPath}
component={SomeAuthComponent}
/>
</Auth>
<Trainee>
<Route
exact
path={SomeTraineePath}
component={SomeTraineeComponent}
/>
</Trainee>
</Switch>
</BrowserRouter>
class Auth extends React.Component {
constructor(props) {
super(props);
this.state = {
loggedIn: isLoggedIn(),
};
}
render() {
return this.state.loggedIn ? (
<Route children={this.props.children} />
) : (
<Redirect to={LoginPath} />
);
}
}
A:
The issue here is that Switch renders the first matching component/Route within its children.
Since Auth is rendered unconditionally and is a valid component, it stops matching after Auth is rendered and never reaches Trainee
You should perhaps change your implementation of Auth and Trainee so that they both use Route as the direct child
class Auth extends React.Component {
constructor(props) {
super(props);
this.state = {
loggedIn: isLoggedIn(),
};
}
render() {
const {component: Component, ...rest } = this.props;
return <Route {...rest} render={(rProps) => this.state.loggedIn? <Component {...rProps}/>: <Redirect to={LoginPath} />} />
}
}
Similarly change the implementation of Trainee and use it like
<BrowserRouter>
<Switch>
<Route
exact
path={LoginForAuthPath}
component={LoginForAuthComponent}
/>
<Route
exact
path={LoginForTraineePath}
component={LoginForTraineeComponent}
/>
<Auth
exact
path={SomeAuthPath}
component={SomeAuthComponent}
/>
<Trainee
exact
path={SomeTraineePath}
component={SomeTraineeComponent}
/>
</Switch>
</BrowserRouter>
| {
"pile_set_name": "StackExchange"
} |
Q:
Trying to get the code to check if there are even brackets
I am currently trying to come up with a code that will scan a string
and check to see if there is an even number of open and closing brackets on each line. If so, it would return true. (Excuse me for the incorrectness in formatting but I could not get the examples to properly take shape unless I identified it as code)
{} // The code would return true
{{}}
{}{}
{{{}{{}}}}
} // The code would return false
{}
}}{
{{{}{}
What I tried so far:
public boolean bracketsMatch(String brackets)
{
int lb = 0;
int rb = 0;
int i = 0;
while (brackets.charAt(i) == '{' || brackets.charAt(i) == '}' || brackets.charAt(i) == '')
{
if (brackets.charAt(i) == '{')
{
lb += 1;
}
if (brackets.charAt(i) == '}')
{
rb += 1;
}
if (brackets.charAt(i) == '')
{
if (lb / rb == 2)
{
// Is it possible to get the code scan the next line to next line?
// need an extra statement here for ^^ before I can place the if statement below
if (bracket.charAt(i + 1) == '')
{
return true;
}
}
else
{
return false;
}
}
i++
}
}
I apologize in advance for any experienced programmers as this would be an inefficient nightmare. I am relatively new to programming in general. I attempted to have the code check for the number of left brackets (lb) and right brackets (rb). Whenever the code came to an empty string, it would divide lb by rb. If the code did not equal 2, the code would return false. I probably have more than a dozen errors in this code, but I was wondering if there was any way to have the code go onto the next line to scan the next set of brackets. Thanks for any help in advance.
EDIT 1:
public boolean bracketsMatch(String brackets)
{
int balance = 0;
for (int i = 0; i < brackets.length(); i++)
{
char value = brackets.charAt(i);
if (value == '{')
{
balance += 1;
}
else if (value == '}')
{
balance -= 1;
}
}
if (balance != 0)
{
return false;
}
else
{
return true;
}
}
A:
This won't compile, as '' is an invalid character literal:
if (brackets.charAt(i + 1) == '')
And your current approach of counting opening and closing brackets,
and checking the value of lb / rb won't yield the right result.
You don't need to count the right brackets. You only need to count the open brackets, and reduce that count as they get closed.
Here's a sketch of an algorithm you can use,
I hope to not spoil the exercise:
For each character in the string
If it's an open bracket, increment the count
If it's a close bracket
If the open count is 0, there's nothing to close, so they are not balanced, we can stop
Decrement the count
After all characters, if the open count is 0, the brackets are balanced
As an additional code review note, this is bad in many ways:
if (brackets.charAt(i) == '{') {
// ...
}
if (brackets.charAt(i) == '}') {
// ...
}
What's bad:
Calling brackets.charAt(i) repeatedly is unnecessary if the result will always be the same. Call it once and save the result in a variable.
The two if conditions are exclusive: if the first is true, the second won't be true, so it's pointless to evaluate it. The second condition should be if else instead of if. And instead of an if-else chain, a switch could be more interesting here.
Instead of calling the string brackets, it would be better to call it something more general. What if the actual input is "{something}"? Then it contains more than just brackets, but the algorithm would work just the same. Calling it brackets is misleading.
| {
"pile_set_name": "StackExchange"
} |
Q:
New badges based on the number of badges earned
There are various ways and conditions to earn badges, but I have a few more ideas for new badges:
For every 100 bronze badges, earn 1 extra silver badge.
For every 100 silver badges, earn 1 extra gold badge.
For every 100 gold badges, earn 1 extra gold badge.
For 5 bronze badges earned within 1 day, earn 1 extra bronze badge.
For 10 bronze badges earned within 1 day, earn 1 extra silver badge.
For 50 bronze badges earned within 1 day, earn 1 extra gold badge.
For 5 silver badges earned within 1 day, earn 1 extra silver badge.
For 10 silver badges earned within 1 day, earn 1 extra gold badge.
For 20 gold badges earned within 1 day, earn 1 extra gold badge.
This is just an idea. It depends on the moderators and the community to accept it or not.
A:
To what effect?
Let the badges speak for themselves. Badges are supposed to do this; what would be the additional effect of adding more badges for earning badges?
If someone has 100 silver badges, they've contributed an incredible amount to the site. If someone has 100 silver badges and one gold badge for earning those silver badges, my impression of them has not changed. Badges for earning badges are not meaningful because they don't say anything new about the user.
(Side note: 100 gold badges is a phenomenal record which has only been achieved by very few people. For those people, for instance, the difference between 100 and 101 badges is meaningless when put in the perspective of their other contributions.)
A:
It is not needed.
If a user can earn 100 bronze badges, then it will not be a big thing for that user to get one silver badge. At that time the user could gain more than 30 silver badges. Badges are given for various reasons in the community, but awarding badges to badge gaining is not a good idea like giving reputations for earning reputations(ie, earning 100 reputation will get 10 rep free). It won't add any value to the user.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to loop through a selected item(languages) using JavaScript/JQuery?
I accepted a list of languages as a HTTP request and I am seeing how I can loop this over to an Azure logic app. But before I do that, I am wondering how to loop through selected languages to be processed to an Azure logic app?
For example, if the user selected Spanish, how would I process 'Spanish' and send that to my Azure logic app?
Here is my HTML file I created with check boxes of all the languages:
Language.html:
<h2>Check Box</h2>
<form>
<input type="checkbox" name="language" value="english"> English<br/>
<input type="checkbox" name="language" value="spanish"> Spanish <br/>
<input type="checkbox" name="language" value="vietnamese"> Vietnamese<br/>
<input type="checkbox" name="language" value="somali"> Somali <br/>
<input type="checkbox" name="language" value="chinese"> Chinese <br/>
<input type="checkbox" name="language" value="amharic"> Amharic <br/>
<input type="checkbox" name="language" value="korean"> Korean <br/>
<input type="checkbox" name="language" value="russian"> Russian <br/>
<input type="checkbox" name="language" value="tagalog"> Tagalog <br/>
<input type="checkbox" name="language" value="arabic"> Arabic <br/>
<input type="checkbox" name="language" value="khmer"> Khmer <br/>
<input type="checkbox" name="language" value="thai"> Thai <br/>
<input type="checkbox" name="language" value="lao"> Lao <br/>
<input type="checkbox" name="language" value="japanese"> Japanese <br/>
<input type="checkbox" name="language" value="deutsch"> Deutsche <br/>
</form>
A:
UPDATE after clarification
document.querySelector("form").addEventListener("submit",function(e) {
e.preventDefault(); // stop submission
const url = new URL("https://api.videoindexer.ai/location/Accounts/accountId/Videos/videoId/Index?language=...&reTranslate=...&includeStreamingUrls=...&accessToken=...");
const language = document.getElementById("language").value;
url.searchParams.set("language",language)
console.log(url); // change to a fetch or similar
})
ul {
list-style-type: none
}
#chosen {
text-transform: capitalize
}
<form>
<select name="language" id="language">
<option value="en-GB">Please select language (Default en-GB</option>
<option value="sr-Cyrl-RS">Serbian (Cyrillic)</option>
<option value="sr-Latn-RS">Serbian (Latin)</option>
<option value="bs-Latn">Bosnian</option>
<option value="zh-Hans">Chinese (Simplified)</option>
<option value="zh-Hant">Chinese (Traditional)</option>
<option value="fil-PH">Filipino</option>
<option value="en-GB">English United Kingdom</option>
<option value="en-FJ">Fijian</option>
<option value="en-AU">English Australia</option>
<option value="en-WS">Samoan</option>
<option value="en-US">English United States</option>
<option value="el-GR">Greek</option>
<option value="es-ES">Spanish</option>
<option value="et-EE">Estonian</option>
<option value="fa-IR">Persian</option>
<option value="fi-FI">Finnish</option>
<option value="fr-FR">French</option>
<option value="fr-HT">Haitian</option>
<option value="af-ZA">Afrikaans</option>
<option value="ar-SY">Arabic Syrian Arab Republic</option>
<option value="ar-EG">Arabic Egypt</option>
<option value="da-DK">Danish</option>
<option value="de-DE">German</option>
<option value="bg-BG">Bulgarian</option>
<option value="bn-BD">Bangla</option>
<option value="mg-MG">Malagasy</option>
<option value="ms-MY">Malay</option>
<option value="mt-MT">Maltese</option>
<option value="ca-ES">Catalan</option>
<option value="cs-CZ">Czech</option>
<option value="nl-NL">Dutch</option>
<option value="nb-NO">Norwegian</option>
<option value="id-ID">Indonesian</option>
<option value="it-IT">Italian</option>
<option value="lt-LT">Lithuanian</option>
<option value="lv-LV">Latvian</option>
<option value="ja-JP">Japanese</option>
<option value="ur-PK">Urdu</option>
<option value="uk-UA">Ukrainian</option>
<option value="hi-IN">Hindi</option>
<option value="he-IL">Hebrew</option>
<option value="hu-HU">Hungarian</option>
<option value="hr-HR">Croatian</option>
<option value="ko-KR">Korean</option>
<option value="vi-VN">Vietnamese</option>
<option value="tr-TR">Turkish</option>
<option value="ta-IN">Tamil</option>
<option value="th-TH">Thai</option>
<option value="to-TO">Tongan</option>
<option value="ru-RU">Russian</option>
<option value="ro-RO">Romanian</option>
<option value="pt-BR">Portuguese</option>
<option value="pl-PL">Polish</option>
<option value="sv-SE">Swedish</option>
<option value="sw-KE">Kiswahili</option>
<option value="sl-SI">Slovenian</option>
<option value="sk-SK">Slovak</option>
</select>
<input type="submit" />
</form>
You can map them using document.querySelectorAll:
document.querySelector("form").addEventListener("click", function(e) {
if (e.target.name && e.target.name === "language")
document.getElementById("chosen").textContent = [...this.querySelectorAll("[name=language]:checked")].map(chk => chk.value).join(", ");
})
ul {
list-style-type: none
}
#chosen {
text-transform: capitalize
}
<h2>Check Box</h2>
<span id="chosen"></span>
<form>
<ul>
<li><label><input type="checkbox" name="language" value="english"> English</label></li>
<li><label><input type="checkbox" name="language" value="spanish"> Spanish</label></li>
<li><label><input type="checkbox" name="language" value="vietnamese"> Vietnamese</label></li>
<li><label><input type="checkbox" name="language" value="somali"> Somali</label></li>
<li><label><input type="checkbox" name="language" value="chinese"> Chinese</label></li>
<li><label><input type="checkbox" name="language" value="amharic"> Amharic</label></li>
<li><label><input type="checkbox" name="language" value="korean"> Korean</label></li>
<li><label><input type="checkbox" name="language" value="russian"> Russian</label></li>
<li><label><input type="checkbox" name="language" value="tagalog"> Tagalog</label></li>
<li><label><input type="checkbox" name="language" value="arabic"> Arabic</label></li>
<li><label><input type="checkbox" name="language" value="khmer"> Khmer</label></li>
<li><label><input type="checkbox" name="language" value="thai"> Thai</label></li>
<li><label><input type="checkbox" name="language" value="lao"> Lao</label></li>
<li><label><input type="checkbox" name="language" value="japanese"> Japanese</label></li>
<li><label><input type="checkbox" name="language" value="deutsch"> Deutsch</label></li>
</ul>
</form>
| {
"pile_set_name": "StackExchange"
} |
Q:
Angular: Get last 3 elements of json object
I have a page that list an item and let users add comments to it.
On that page I would like to display the last 3 comments added. Any tips on how to do get the last 3 comments from JSON objects?
Also when adding a new comment how can I increment the comment number (hardcoded for now)?
See my code: http://plnkr.co/edit/iOBXuQVY40LD8d8QV5ss?p=preview
Thanks
A:
Look at the limitTo Filter. You can specific from the end of a list by using negative.
You could do
message in item.comments|limitTo:-3
Also for your comments, you should haven't them as a object dictionary, rather just use an array like so:
"comments":
[
{
"id": "comment1",
"name":"user1",
"description": "This is comment 1"
},
{
"id": "comment2",
"name":"Jane D.",
"description": "This is comment 2"
},
{
"id": "comment3",
"name":"Jone D.",
"description": "This is comment 3"
},
{
"id": "comment4",
"name":"Test",
"description": "This is comment 4"
},
{
"id": "comment5",
"name":"user",
"description": "This is comment 5"
}
]
If they aren't already in order you may need to add a date field of sort and sort them after you pull them in.
Here is a update plunker to help you out. Note your ng-repeat was also in the wrong place
A:
Expanding on other answers: You should look at adding an ID or date to each comment. For my example solution, I've used "ID".
In my forked plunk, I've added a total, and a 'show more' button for an expandable comment list. The size is controlled by the variable 'limit'.
Also, the variable 'itemID' inside $scope.addMessage() is adding the ID to each comment. This will solve part 2 of your question.
Plunker: http://plnkr.co/edit/bAtXmCls2gk8p5WAHsrM?p=preview
$scope.addMessage (adds item, description has the value of whatever you put in the input box and resets limit back to latest 3)
$scope.addMessage = function(mess) {
var itemID = $scope.items[0].comments.length + 1;
$scope.items[0].comments.push(
{
"id": itemID,
"name":"user" + itemID,
"description": mess
}
);
$scope.totalItems = itemID;
$scope.limit = 3;
}
$scope.showMore (increases limit by 3)
$scope.showMore = function() {
$scope.limit += 3;
}
JSON: I've changed it a little. 'comments' is now an array, and an 'id' is added
"comments":
[
{
"id": 1,
"name":"user1",
"description": "This is comment 1"
},
{
"id": 2,
"name":"Jane D.",
"description": "This is comment 2"
},
...
]
| {
"pile_set_name": "StackExchange"
} |
Q:
Shrink a div to it's horisontal center
I am trying to implement a CSS3 animation on my site where 2 divs would squeeze together another div with a background image. It's pretty hard to explain, so I made a quick video. Please note that the problem I want to solve is present on this video.
What I'd like to do is when animating the height of a div, it wouldn't shrink to it's horisontal center instead of it's top.
Can this be done in any way?
My HTML:
<div id="container">
<div id="top-bar">
<ul id="nav">
<li><a href="index.php">Főoldal</a>
</li>
<li><a href="szolgaltatasok.html">Szolgáltatások</a>
</li>
<li><a href="portfolio.php">Portfólió</a>
</li>
<li><a href="kapcsolat.html" id="kapcsolat">Kapcsolat</a>
</li>
</ul>
</div>
<div id="content">
<div id="card">
<!-- The orange card : irrelevant -->
</div>
<div id="main">
<div id="inner-content"></div>
</div>
</div>
<div id="bottom-bar">
<div id="logo">
<!-- Logo Image -->
</div>
</div>
</div>
Please check the jsFiddle examples for the full code.
jsFiddle code
jsFiddle Full Screen Result
A:
I have created a fiddle here. Every time you click the button it will add/remove the class that has the scaling transform.
CSS:
.box {
width: 300px;
height: 300px;
background: black;
-webkit-transition: all .6s ease-in-out;
transition: all .6s ease-in-out;;
}
.box-change {
-webkit-transform: scale(0,0);
}
JS:
$(function() {
$("#bt").click(function() {
$(".box").toggleClass("box-change");
});
});
HTML:
<div class="box"></div>
<input type="button" value="Let's Do This Thing" id="bt">
You can change CSS to this:
.box-change {
-webkit-transform: scale(1,0);
}
for shrinking to "horizontal center" effect.
| {
"pile_set_name": "StackExchange"
} |
Q:
Update from java 1.7 to latest version
How can i update to the latest version of java if i have already installed on my pc java 1.7.
If i should remove it first, how can i do that?
A:
have a look for an actual repository here
http://www.ubuntuupdates.org/ppa/webupd8_java
| {
"pile_set_name": "StackExchange"
} |
Q:
how to solve under-determined system of inequalities with multiply variables
I am trying to find a way to solve system of linear inequalities such as:
c>0
y+c<0
x+c>0
x+y+c<0
w+c>0
w+y+c>0
w+x+c>0
w+x+y+c<0
I have had no luck in finding a fast computational method to solve them. I have tried using wolfram alpha. It works for some sets but not for others. Moreover I also tried solving such systems using matlab's solve function but with no luck. Any help regarding this matter would be very much appreciated.
A:
In general there are infinite solutions to an under determined system. You could however search for the smallest solution of an adapted problem. In that case you could preceed as follows:
You first vectorize your problem
x = [c y x w].';
M = [1 0 0 0
1 1 0 0
1 1 1 0
1 0 0 1
1 1 0 1
1 0 1 1
1 1 1 1];
y = [ 1 -1 1 -1 1 1 1 -1].';
You can set the values of ylike you want. They only need to suffice the conditions of your inequalities (i.e y(1)>0, y(2)<0,...).
Now you solve the under determined system Mx=y.
The smallest solution of this system can be found by using the pseudo-inverse of M.
x = M.'(M*M.')^(-1)*y;
If you have chosen yaccordingly to your restrictions, the solution of this problem is also a solution of your problem.
If you want the smallest solution to your problem, just give y only an epsilon room (but then you should calculate it analytical).
| {
"pile_set_name": "StackExchange"
} |
Q:
Pattern.matches() against a char array without cast to String in java
Scenario
I need to check a regex pattern against a character array (char[]). I am not allowed to cast the character array to a String, because of security considerations. Java's Pattern.matches() method is designed to take a pattern and a String. Also, the regex pattern is passed to me from another source, and will change (is not constant).
This does not work:
// This pattern comes from another source, that I do not control. It may change.
String pattern = "^(.)\\1+$";
char[] exampleArray = new char[4];
exampleArray[0] = 'b';
exampleArray[1] = 'l';
exampleArray[2] = 'a';
exampleArray[3] = 'h';
// This should return true, for this pattern, but I cannot pass in a char[].
boolean matches = Pattern.matches(pattern, exampleArray);
Thoughts
I attempted to deconstruct the regex pattern and examine the array for each part of the pattern, but the conditional logic required to interpret each part of the pattern thwarted me. For example: Suppose the pattern contains something like "(.){5,10}". Then I only need to check the char[] length. However, if it contains "^B(.){5,10}X", then I need to do something very different. It feels like there are too many possibilities to effectively deconstruct the regex pattern and account for each possibility (which is exactly why I've always just used Pattern.matches()).
Question
What would be the most efficient way of checking a regex pattern against a character array without casting the character array to a String, or creating a String?
A:
Pattern.matches accepts a general CharSequence. You can use for example CharBuffer from java.nio instead of String.
boolean matches = Pattern.matches(pattern, CharBuffer.wrap(exampleArray));
CharBuffer.wrap will not create an extra copy of the password in memory, so of all the options it's the safest.
A:
If someone has access to the machine's memory then the problems can get far beyond the uncovering of passwords.
boolean matches = Pattern.matches(pattern, new String(exampleArray));
| {
"pile_set_name": "StackExchange"
} |
Q:
Adding data files to SBT project
I would like to add a data file or a configuration file along with my application (such as sample.conf). This file should be available to user so that he/she can edit the sample configuration to further customize the application.
How can I add such files to my project such that
This file becomes part of distributable, and
How can I link it in my source documentation, so that its purpose can be doucmented, and
This is file is goes into a special directory (such as conf)
Or is there any such predefined task available.
A:
SBT Native Packager provides support for doing what you want, though you'll have to dig through the docs a bit. The universal packager is probably the best approach for you.
http://www.scala-sbt.org/sbt-native-packager/
| {
"pile_set_name": "StackExchange"
} |
Q:
Simple Array.prototype is giving a TypeError
I have this (very simple) code:
Array.prototype.test = function(x) { alert(x) }
[0].test('Hello, World!')
However, when I execute it, I get this:
TypeError: Cannot call method 'test' of undefined
What is wrong?
A:
I ran into this this odd error, and I finally figured out that the solution is to add semicolons:
Array.prototype.test = function(x) { alert(x) };
[0].test('Hello, World!');
Otherwise, it would be parsed like this:
Array.prototype.test = function(x) { alert(x) }[0].test('Hello, World!')
function(x) { alert(x) }[0] is undefined because function objects don't have a property called 0, so it becomes
Array.prototype.test = undefined.test('Hello, World!')
Then, it tries to call test on undefined, which it of course can't do, so it gives an error.
| {
"pile_set_name": "StackExchange"
} |
Q:
Do not want to cache the static files in Vert.x
I am creating a simple webapp in Vert.x that will run on Docker, but I don't want Vert.x to cache any of static files as it might not have permissions on Docker to write files.
so as per documentation I am using
-Dvertx.disableFileCaching=true
then also it is creating .vertx folder and cached files.
If I use
-Dvertx.disableFileCPResolving=true
it is not creating .vertx folder but I am not able to access static files at all.
Any other settings i am missing?
A:
If your files are inside the JAR and classpath resolving is disabled, then Vert.x will not be able to server them.
You should put your static files in a webroot directory under the JVM working directory.
| {
"pile_set_name": "StackExchange"
} |
Q:
Image doesn't center in IE7?
<div class="logo">
<h1><a href="/"><img src="image.png" alt="Red Rectangle" /></a></h1>
</div>
.logo h1 img{
position: relative;
width: 256px;
left: 50%;
margin-left: -128px;
border: none;
}
With the code above I am centering an image to the middle. But this only works for FireFox, Chrome, because in Internet Explorer 7 it looks like the image is not centered but like 30 pixels to the right from the center.
Screenshot of the not completely centered image (red) in IE7
Does anybody knows how I can make this work properly in IE7?
EDIT: I don't want to use margin: 0 auto; because that makes the area around the image (when it's centered) also clickable as a link. I want only the image be clickable as a link.
A:
Maybe margin: 0 auto; would work better for you? It depends on if you are positioning this on the page or you just want it centered. You can use this if you know the width of the element:
.logo h1 img {
width: 256px;
margin: 0 auto;
border: none;
}
This will center it because the margin on left and right is auto and the width is set.
jsFiddle: http://jsfiddle.net/thFpF/
Edit
You should instead center a parent element with margin: 0 auto; then and put the image and anchor (<a> link) inside it. This way the whole area will not be clickable.
| {
"pile_set_name": "StackExchange"
} |
Q:
Should I remove the HPlip packages from the Ubuntu repositories before installing the latest version with the HP provided .run installer?
I need the latest version of HPLip on my computer to fully support a new printer. I already have HPLip and HPLip GUI installed from the Ubuntu repositories. HP offers a .run based installer to be run in bash. Should I remove the HPLip deb packages before I run the HP installer, or will the HP installer update current version? I am afraid to just try since I may mess up the printer sub system not knowing how to fix it.
A:
I would suggest removing the packages provided by Ubuntu if you're about to replace them with a more recent version from the vendor.
| {
"pile_set_name": "StackExchange"
} |
Q:
How to return the full object once it`s been found?
So starting from an array of objects I need to find if any of them are called Google. If so I need to return the full object. Now It is returning true
const companies = [ { id: 1, username: 'facebook', website: 'www.facebook.com' }, { id: 2, username: 'google', website: 'www.google.com' }, { id: 3, username: 'linkedin', website: 'www.linkedin.com' } ]
const checkCompany = company => company.name === "google";
console.log(companies.some(checkCompany)); // true
A:
some() returns a Boolean.You can use Array.prototype.find() which returns the value of first element in array. If no element in array matches condition then it returns undefined
const companies = [ { id: 1, username: 'facebook', website: 'www.facebook.com' }, { id: 2, username: 'google', website: 'www.google.com' }, { id: 3, username: 'linkedin', website: 'www.linkedin.com' } ]
const res = companies.find(x => x.username === "google");
console.log(res)
| {
"pile_set_name": "StackExchange"
} |
Q:
font awesome icons size jumps in first load of a static page with vue.js
I'm using vue.js and gridsome to make a personal portfolio. how ever I have this problem that in the fist load of page, the icon sizes are too big and suddenly the come back to normal size. These is my webpage:farzinnasiri.com
I'm using cdn for these website so I don't know that can everybody see the issue but in my first load in both chrome and Firefox the arrow button below the View Portfolio was too big.Also these is that parts code:
<section id="view-portfolio">
<a class="portfolio-button button" href="#works" align="middle">
<span> View Portfolio </span>
<font-awesome-icon :icon="['fas', 'angle-down']"/>
</a>
</section>
The css:
.portfolio-button {
position: absolute !important;
color: white;
left: 50%;
text-align: center;
bottom: 10px;
transform: translateX(-50%);
margin: 7px 0px 0px;
padding: 14px 14px 7px;
}
.portfolio-button span {
display: block;
}
.button {
text-transform: uppercase;
font-weight: 300;
}
.portfolio-button:hover{
text-decoration: none;
}
also this is my main.js file:
import DefaultLayout from '~/layouts/Default.vue'
import '~/vendor/bootstrap.min.css'
import { library,dom } from '@fortawesome/fontawesome-svg-core'
import { fab } from '@fortawesome/free-brands-svg-icons'
import { fas} from '@fortawesome/free-solid-svg-icons'
import { FontAwesomeIcon } from '@fortawesome/vue-fontawesome'
library.add(fas)
library.add(fab)
dom.watch()
export default function (Vue, { router, head, isClient }) {
// Set default layout as a global component
Vue.component('font-awesome-icon', FontAwesomeIcon)
Vue.component('Layout', DefaultLayout)
}
I found some similar issues on the web but I since most of them used pure html/css and I'm using vue those didn't help me to find the answer. can any body help?
A:
you have written below style in vue component, can you move it in a css file:
.svg-inline--fa.fa-w-10 {
width: 0.625em;
}
The problem is app.js file has the above css, so it's taking time to load and once the file is loaded in DOM then you are seeing the effect.
| {
"pile_set_name": "StackExchange"
} |
Q:
Grails: How to remove any and all HTML tags from a String
What is a simple, fast and reliable way to remove any and all HTML tags from a text string in Grails?
A:
This first removes any comments (which might contain tags) and then any tags:
text = text.replaceAll(/<!--.*?-->/, '').replaceAll(/<.*?>/, '')
(via http://grails.1312388.n4.nabble.com/Strip-html-tags-tp1316579p1316580.html)
| {
"pile_set_name": "StackExchange"
} |
Q:
Can non-uniform circular motion be called as periodic motion?
In non-uniform circular motion with a constant magnitude of tangential acceleration, though the particle keeps completing the same circle its speed changes continuously and hence the circular motions each time are not identical. So it should not be periodic motion according to me. Am I right?
A:
No, the situation you’ve described in the body of your question is not periodic. If there exists a $T\in \mathbb{R}$ such that the motion of a particle is described by
$$\mathbf{r}(t + T) = \mathbf{r}(t) $$
and
$$ \mathbf{p}(t + T) = \mathbf{p}(t)$$
for all $t$ in the domain of $\mathbf{r}$, then your motion may be considered to be periodic.
More generally, one can consider phase space $\{ (\mathbf{r, p}) \}$ of your system. Periodic motion corresponds to an orbit in phase space parametrized by time.
So while the position will come back on itself, the momentum never will. Hence the trajectory in phase space is not an orbital.
| {
"pile_set_name": "StackExchange"
} |
Q:
Move area of an image to the center using OpenCV
I'm trying to move a region of an image to the center, I succeeded in getting its contour and I know how to place this in the center.
But what I want is to move the pixels that are inside the contour (yellow with black) at the center and not just the contour (which is pink by CV_FILLED).
Image:
Code:
//Then segment the image. save in Mat crop
// ---- Center image -----
// pos : contour interest
RotatedRect rr = fitEllipse(contours[pos]);
vector<Point>&contour = contours[pos];
//http://stackoverflow.com/a/29467236/4595387
//difference between the centre of the image and centre of the contour
Point center = Point( crop.cols/2, crop.rows/2 );
int nX = center.x - rr.center.x;
int nY = center.y - rr.center.y;
for (size_t i=0; i< contour.size(); i++)
{
contour[i].x += nX;
contour[i].y += nY;
}
cout << "x: " << rr.center.x;
cout << "y: " << rr.center.y;
//color = Scalar(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255));
//contour of the image to the center.
cv::drawContours(crop, contours, pos, color, CV_FILLED);
imshow("In",imagen_src);
imshow("Out",crop);
A:
You need basically to play around with copyTo with a mask. The steps are commented in the code. If you need a different background color, just change backgroundColor in the code below.
Code:
#include <opencv2\opencv.hpp>
using namespace cv;
int main()
{
// Read image
Mat3b img = imread("path_to_image");
// Convert to hsv
Mat3b hsv;
cvtColor(img, hsv, COLOR_BGR2HSV);
// Threshold on yellow color (in hsv space)
Mat1b maskOnYellow;
inRange(hsv, Scalar(20, 100, 100), Scalar(40, 255, 255), maskOnYellow);
// Find contours of yellow item
vector<vector<Point>> contours;
findContours(maskOnYellow.clone(), contours, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE);
// Create a mask as a filled contour
Mat1b mask(img.rows, img.cols, uchar(0));
drawContours(mask, contours, 0, Scalar(255), CV_FILLED);
// Get the bounding box of the item
Rect box = boundingRect(contours[0]);
// Get the roi in the input image according to the mask
Mat3b item(img(box));
// Create a black image (same size as the yellow item and same background bolor as result image)
// to copy the result of the segmentation
Vec3b backgroundColor(0,0,0); // black
Mat3b segmentedItem(item.rows, item.cols, backgroundColor);
// Copy only the masked part
item.copyTo(segmentedItem, mask(box));
// Compute the center of the image
Point center(img.cols / 2, img.rows / 2);
// Create a result image
Mat3b res(img.rows, img.cols, backgroundColor);
// Compute the rectangle centered in the image, same size as box
Rect centerBox(center.x - box.width/2, center.y - box.height/2, box.width, box.height);
// Put the segmented item in the center of the result image
segmentedItem.copyTo(res(centerBox));
imshow("Result", res);
waitKey();
return 0;
}
Input:
Result:
| {
"pile_set_name": "StackExchange"
} |
Q:
How would I go about using FXAA in XNA?
This isn't so much a "give me teh codez" as it is a request for the "right" steps to go through.
I want to implement FXAA in XNA, but I'm a relative newb to the graphics side of game dev, so I'm not sure what the most efficient way to do this would be.
My first hunch is to render the scene into a texture, and then render that texture on a rectangle, with the FXAA code in a pixel shader.
However, I would actually be surprised if there was no more efficient way to do it.
A:
You are almost right about it, but XNA has some built-in features to help you with all of that!
Render to Texture
My first hunch is to render the scene into a texture
Almost. You would start by rendering your scene into a RenderTarget2D (which actually inherits from Texture2D so it does qualify as rendering to a texture). Something like:
PresentationParameters pp = graphicsDevice.PresentationParameters;
RenderTarget2D renderTarget = new RenderTarget2D(graphicsDevice, pp.BackBufferWidth, pp.BackBufferHeight, false, pp.BackBufferFormat, pp.DepthStencilFormat, pp.MultiSampleCount, RenderTargetUsage.DiscardContents);
graphicsDevice.SetRenderTarget(renderTarget);
RenderScene();
graphicsDevice.SetRenderTarget(null);
Apply Shader
and then render that texture on a rectangle, with the FXAA code in a
pixel shader.
And for this you can just use the SpriteBatch class which already creates the quad for you. Load your shader into an Effect object and pass it to SpriteBatch.Begin(). Also, since the render target is already a texture, you can just use it directly! Something like:
Effect fxaa = content.Load<Effect>("fxaa");
spriteBatch.Begin(SpriteSortMode.Deferred, null, null, null, null, fxaa);
spriteBatch.Draw(renderTarget, graphicsDevice.Viewport.Bounds, Color.White);
spriteBatch.End();
Making the Shader Work with SpriteBatch
As for writing a pixel shader that works with SpriteBatch, there's really not much to say (would be a different story if you were writing a vertex shader though). Check this sample to get you started. I'll copy one of the examples here:
sampler TextureSampler : register(s0);
float4 main(float4 color : COLOR0, float2 texCoord : TEXCOORD0) : COLOR0
{
// Your pixel shader logic here
}
technique Desaturate
{
pass Pass1
{
PixelShader = compile ps_2_0 main();
}
}
| {
"pile_set_name": "StackExchange"
} |
Q:
Cannot click my floating action button which is above a scroll view
I have a CoordinatorLayout and inside it, two FloatingActionButton and below them a ScrollView.
The problem is that even though I can see my FloatingActionButtons on screen I cannot click them. I suspect that's because all onTouch events are being handled from ScrollView
Here is my layout xml (which is probably pretty bad so any tips are welcome):
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- Note: that 80dp padding is:
main_padding + fab_size + 8dp = 80dp
16dp + 56dp + 8dp = 80dp
and it was the only way I could think to add padding
between my FABs
I tried to use app:layout_anchor but my 2
FABs had no padding between them... -->
<android.support.design.widget.FloatingActionButton
style="@style/RefreshFab"
android:id="@+id/fab_send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_marginBottom="80dp"
android:layout_marginEnd="16dp"
app:fabSize="normal"
app:pressedTranslationZ="12dp"/>
<android.support.design.widget.FloatingActionButton
style="@style/SendFab"
android:id="@+id/fab_refresh"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:layout_gravity="bottom|end"
app:fabSize="normal"
app:elevation="6dp"
app:pressedTranslationZ="12dp"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<!-- Toolbar -->
<include
layout="@layout/view_toolbar" />
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="16dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="16dp">
<!-- Much stuff here, text views, spinners etc.. -->
</LinearLayout>
</ScrollView>
</LinearLayout>
</android.support.design.widget.CoordinatorLayout>
A:
The problem is because each item is laid out in a CoordinatorLayout in the same order it is written in the xml. By that logic, the FloatingActionButtons are each placed on the screen and then the LinearLayout on top of them, so I would expect the click is being overriden by the LinearLayout.
Rearrange your XML to place the FloatingActionButtons last, so that they are 'on top', so to speak, of your layout. Then they will detect your click listeners just fine.
I think the problem will persist since each FloatingActionButton is wrapped inside of a FrameLayout with match_parent dimensions. I do not believe you need these FrameLayouts, but you can simply put the FloatingActionButtons inside of the CoordinatorLayout.
| {
"pile_set_name": "StackExchange"
} |
Q:
How do I get more chocolate bars?
I've ran out of chocolate bars and didn't realize I could enchant my giant spoon and knight's armor. Is there any way to get more reliably?
A:
According to the Candy Box 2 wiki, you can only get 13 chocolate bars total:
You can buy 1 at the shop.
You get 1 for throwing 1630 candies on the ground
You get 3 for answering the squirrel's questions
You find 1 in the cave
You find 3 beneath the tree, after finding the map (rocks) in the cave
You find 4 in the hole
Without resorting to any sort of cheat/glitch, if you've used your 13 chocolate bars then you're out of luck.
However, there is currently a glitch involving the text-save/load feature that allows you to earn more:
Go to Save, click Get Current Game as Text and copy the text
Start the game over (refresh the page), and get enough candies to get the Save feature again
Paste the text into the bottom text box and click Load
You can now re-earn the chocolate associated with the cave. That means you'll find one more chocolate in the cave and, once you find the cave-rocks again, three more beneath the tree.
You can repeat this to gain as many chocolates as you want.
You could also edit your save file.
Follow the steps above to copy your game-state as text, then find the section with the text number gameChocolateBarsCurrent=0. Change the 0 to whatever value you want, then load the game.
Finally, once you beat the game, you can use the computer to give yourself more chocolate.
| {
"pile_set_name": "StackExchange"
} |
Q:
checking if a script is running?
How can I check if a script (e.g. a bash script) is running (in the background) using command line?
A:
You can run:
jobs -l
Which will show you a list of all backgrounded processes and their PIDs.
| {
"pile_set_name": "StackExchange"
} |
Q:
AngularJS - ng-options compound text of option
I have array with object:
[
...
{
id: 1,
name: 'Value',
desc: 'Test'
}
...
]
How i can generate option by ng-options with text Value (Test)?
A:
You could use:
<select
ng-model="selectedOption"
ng-options="o.id as o.name + ' (' + o.desc + ')' for o in options">
</select>
Demo
| {
"pile_set_name": "StackExchange"
} |
Q:
SOLR 3.6 and query-time join
Does solr 3.6 support joining at all? According to http://java.dzone.com/articles/apache-lucene-and-solr-36 it does, but when i try to execute any join following the tutorial at http://wiki.apache.org/solr/Join all i get is an error "Unknown query type 'join'".
Does it need to be enabled somehow or is it simply not working in the 3.6 release?
A:
there is a Solr4.0 mark at http://wiki.apache.org/solr/Join
its not available in 3.6
also see http://www.searchworkings.org/blog/-/blogs/query-time-joining-in-lucene
there is a possibility that it will also be included in Lucene 3.6
i guess it was not included
| {
"pile_set_name": "StackExchange"
} |
Q:
Swift / Objective-C ASN1 encode public key
I need some help regarding some encryption in Swift. I have been searching a lot about RSA encryption.
We have a generated public key from our back-end servers and we need to use that key to encrypt a secret message that will be passed back to our back-end servers again.
I was able to find RSA encryption libs, but I'm afraid we are having issues because our public key is encoded in ASN.1.
Updates:
Below is our actual code. We tried to encrypt the message using an ASN.1 encoded public key from our server. The problem is that, our backend servers require for the encrypted password to be in hex value, although, I am doing that already, however our backend is not able to decrypt the message.
+ (SecKeyRef) setPublicKey: (NSString *) keyAsBase64 {
/* First decode the Base64 string */
NSData * rawFormattedKey = base64_decode(keyAsBase64);
/* Now strip the uncessary ASN encoding guff at the start */
unsigned char * bytes = (unsigned char *)[rawFormattedKey bytes];
size_t bytesLen = [rawFormattedKey length];
/* Strip the initial stuff */
size_t i = 0;
if (bytes[i++] != 0x30)
return FALSE;
/* Skip size bytes */
if (bytes[i] > 0x80)
i += bytes[i] - 0x80 + 1;
else
i++;
if (i >= bytesLen)
return FALSE;
if (bytes[i] != 0x30)
return FALSE;
/* Skip OID */
i += 15;
if (i >= bytesLen - 2)
return FALSE;
if (bytes[i++] != 0x03)
return FALSE;
/* Skip length and null */
if (bytes[i] > 0x80)
i += bytes[i] - 0x80 + 1;
else
i++;
if (i >= bytesLen)
return FALSE;
if (bytes[i++] != 0x00)
return FALSE;
if (i >= bytesLen)
return FALSE;
/* Here we go! */
NSData * extractedKey = [NSData dataWithBytes:&bytes[i] length:bytesLen - i];
/* Load as a key ref */
OSStatus error = noErr;
CFTypeRef persistPeer = NULL;
static const UInt8 publicKeyIdentifier[] = "com.our.key";
NSData * refTag = [[NSData alloc] initWithBytes:publicKeyIdentifier length:sizeof(publicKeyIdentifier)];
NSMutableDictionary * keyAttr = [[NSMutableDictionary alloc] init];
/* First we delete any current keys */
[keyAttr setObject:(__bridge id)kSecClassKey forKey:(__bridge id)kSecClass];
[keyAttr setObject:(__bridge id)kSecAttrKeyTypeRSA forKey:(__bridge id)kSecAttrKeyType];
[keyAttr setObject:refTag forKey:(__bridge id)kSecAttrApplicationTag];
error = SecItemDelete((__bridge CFDictionaryRef) keyAttr);
[keyAttr setObject:extractedKey forKey:(__bridge id)kSecValueData];
[keyAttr setObject:[NSNumber numberWithBool:YES] forKey:(__bridge id)kSecReturnPersistentRef];
error = SecItemAdd((__bridge CFDictionaryRef) keyAttr, (CFTypeRef *)&persistPeer);
CFRelease(persistPeer);
/* Now we extract the real ref */
SecKeyRef publicKeyRef = nil;
[keyAttr removeAllObjects];
[keyAttr setObject:(__bridge id)kSecClassKey forKey:(__bridge id)kSecClass];
[keyAttr setObject:refTag forKey:(__bridge id)kSecAttrApplicationTag];
[keyAttr setObject:(__bridge id)kSecAttrKeyTypeRSA forKey:(__bridge id)kSecAttrKeyType];
[keyAttr setObject:[NSNumber numberWithBool:YES] forKey:(__bridge id)kSecReturnRef];
// Get the persistent key reference.
error = SecItemCopyMatching((__bridge CFDictionaryRef)keyAttr, (CFTypeRef *)&publicKeyRef);
if (publicKeyRef == nil || ( error != noErr && error != errSecDuplicateItem)) {
NSLog(@"Error retrieving public key reference from chain");
return FALSE;
}
return publicKeyRef;
}
+(NSString* )encryptWithPublicKey:(NSString*)key input:(NSString*) input {
const size_t BUFFER_SIZE = 16;
const size_t CIPHER_BUFFER_SIZE = 16;
const uint32_t PKCS1 = kSecPaddingPKCS1;
SecKeyRef publicKey = [self setPublicKey:key];
NSData *crypted = nil;
NSData *rawinput = [input dataUsingEncoding:NSUTF8StringEncoding];
NSString *theInput = [self base64forData:rawinput];
NSData *data = [theInput dataUsingEncoding:NSUTF8StringEncoding];
uint8_t *srcbuf;
srcbuf = (uint8_t *)calloc(BUFFER_SIZE, sizeof(uint8_t));
srcbuf = (uint8_t *)[data bytes];
size_t srclen = (size_t)data.length;
size_t outlen = SecKeyGetBlockSize(publicKey) * sizeof(uint8_t);
void *outbuf = malloc(outlen);
OSStatus status = noErr;
status = SecKeyEncrypt(publicKey,
PKCS1,
srcbuf,
srclen,
outbuf,
&outlen);
if (status != 0) {
//NSLog(@"SecKeyEncrypt fail. Error Code: %ld", status);
}else{
crypted = [NSData dataWithBytes:outbuf length:outlen];
}
NSString *str = [crypted stringWithHexBytes2];
free(outbuf);
CFRelease(publicKey);
return str;
}
This is the category for hex conversion of NSData.
- (NSString*)stringWithHexBytes2 {
static const char hexdigits[] = "0123456789abcdef";
const size_t numBytes = [self length];
const unsigned char* bytes = [self bytes];
char *strbuf = (char *)malloc(numBytes * 2 + 1);
char *hex = strbuf;
NSString *hexBytes = nil;
for (int i = 0; i<numBytes; ++i) {
const unsigned char c = *bytes++;
*hex++ = hexdigits[(c >> 4) & 0xF];
*hex++ = hexdigits[(c ) & 0xF];
}
*hex = 0;
hexBytes = [NSString stringWithUTF8String:strbuf];
free(strbuf);
return hexBytes;
}
A:
The issue wasn't about the encryption. However, due to security reasons and company policies, we need several steps and levels of encryption before backend can successfully decrypt the password.
Thanks so much guys for the effort on helping me out.
By the way, the code above is working perfectly, even though it doesn't include our additional level of encryption.
| {
"pile_set_name": "StackExchange"
} |
Q:
Auto-correction does not work with autocompletetextview?
It seems like there is no way to enable auto-correction with the autocompletetextview and the multiautocompletetextview in Android.
Auto-correction works perfectly with the standard EditText.
As soon as an Autocompletetextview or a Multiautocompletetextview is used, auto-correction ceases to work.
I've already tried a bunch of potential workarounds but none of them is working (i.e. using the various input options in the XML file).
Has anyone been able to successfully enable auto-correction on an Autocompletetextview or a Multiautocompletetextview and still be able to feed a list of suggestion to it as an Adapter? Thanks much!
A:
autocompletetextview will set InputType.TYPE_TEXT_FLAG_AUTO_COMPLETE flag on the input view.
That flag make some IME stop giving auto correct suggestions.
You can extend AutoCompleteTextView and remove the flag like below
public SocialCompleteTextView(Context context) {
super(context);
int removed = this.getInputType() & (this.getInputType() ^ InputType.TYPE_TEXT_FLAG_AUTO_COMPLETE);
this.setInputType(removed);
}
| {
"pile_set_name": "StackExchange"
} |
Q:
how apply Mysql concat in Propel?
I am trying do a remote filtering of a data grid.
The grid has a textfield, where the user enters chars which are sent to the server to refresh the grid.
My problem is that I am using Propel to work with the database and I need concat two MySQL fields to do the comparison. I don't know how do a simple where concat(firstname, ',', lastname) like '%aText%' in Propel.
I've tried:
$usuarios = UsuariosQuery::create()
->where("(concat(usuarios.apellido,' , ',usuarios.nombre)) LIKE '%?%'",$filter)
->orderByApellido('ASC')
->find();
This doesn't work. How can I get this to work?
A:
Try this according to the doc (search for concat):
$usuarios = UsuariosQuery::create()
->where('CONCAT(Usuarios.Apellido, ",", Usuarios.Nombre) LIKE ?', $filter)
->orderByApellido('ASC')
->find();
}}}
| {
"pile_set_name": "StackExchange"
} |
Q:
Performing algebra with newtypes based on integers Haskell
I'm having some trouble with performing simple addition, subtraction -- any kind of algebra really with Haskells newtype.
My definition is (show included so I can print them to console):
newtype Money = Money Integer deriving Show
What I'm trying to do is basically:
Money 15 + Money 5 = Money 20
Money 15 - Money 5 = Money 10
Money 15 / Money 5 = Money 3
And so on, but I'm getting
m = Money 15
n = Money 5
Main>> m-n
ERROR - Cannot infer instance
*** Instance : Num Money
*** Expression : m - n
I can't find a clear and consise explanation as to how the inheritance here works. Any and all help would be greatly appreciated.
A:
Well Haskell can not add up two Moneys, since you never specified how to do that. In order to add up two as, the as should implement the Num typeclass. In fact newtypes are frequently used to specify different type instances, for example Sum and Product are used to define two different monoids.
You thus need to make it an instance of Num, so you have to define an instance like:
instance Num Money where
Money a + Money b = Money (a+b)
Money a - Money b = Money (a-b)
Money a * Money b = Money (a*b)
abs (Money a) = Money (abs a)
signum (Money a) = Money (signum a)
fromInteger = Money
Since (/) :: Fractional a => a -> a -> a is a member of the Fractional typeclass, this will give some problems, since your Money wraps an Integer object.
You can however implement the Integral typeclass such that it supports div. In order to do this, we however need to implement the Real and Enum typeclass. The Real typeclass requires the type to be implement the Ord, and since the Ord typeclass requires the object to be an instance of the Eq typeclass, we thus end up implementing the Eq, Ord, Real and Enum typeclass.
instance Eq Money where
Money x == Money y = x == y
instance Ord Money where
compare (Money x) (Money y) = compare x y
instance Real Money where
toRational (Money x) = toRational x
instance Enum Money where
fromEnum (Money x) = fromEnum x
toEnum = Money . toEnum
instance Integral Money where
toInteger (Money x) = x
quotRem (Money x) (Money y) = (Money q, Money r)
where (q, r) = quotRem x y
GeneralizedNewtypeDeriving
As @Alec says we can use a GHC extension named -XGeneralizedNewtypeDeriving.
The above derivations are quite "boring" here we each time "unwrap" the data constructor(s), perform some actions, and "rewrap" them (well in some cases either unwrapping or rewrapping are not necessary). Especially since a newtype actually does not exists at runtime (this is more a way to let Haskell treat the data differently, but the data constructor will be "optimized away"), it makes not much sense.
If we compile with:
ghc -XGeneralizedNewtypeDeriving file.hs
we can declare the Money type as:
newtype Money = Money Integer deriving (Show, Num, Enum, Eq, Ord, Real, Integral)
and Haskell will perform the above derivations for us. This is, to the best of my knowledge, a GHC feature, and thus other Haskell compilers do not per se (well they can of course have this feature) support this.
A:
You're missing a instance of how your money can add together, the clue was in the error Instance : Num Money.
So for addition in Haskell the Num type what is needed to add two things together as long you are dealing with numbers so let's make an instance of Num on Money:
newtype Money =
Money Integer deriving Show
instance Num Money where
Money a + Money b = Money $ a + b
-- Money 1 + Money 2 == Money 3
Notice that it returns Money, will let you research how you can get the number out of the type :)
| {
"pile_set_name": "StackExchange"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.