id
stringlengths 5
11
| text
stringlengths 0
146k
| title
stringclasses 1
value |
|---|---|---|
doc_4100
|
I am creating users from the interface and I don't want to use camelcases and numbers for the password format.
Can I do this from inside the config/initializers/active_admin.rb?
Thanks!
A: I managed to do it through devise security extension gem :)
https://github.com/phatworx/devise_security_extension
| |
doc_4101
|
TID: [-1234] [] [2018-06-18 05:44:07,794] ERROR {org.wso2.carbon.andes.internal.QpidServiceComponent} - Wait until Qpid server starts on port 5672 {org.wso2.carbon.andes.internal.QpidServiceComponent}
java.net.ConnectException: Connection refused (Connection refused)
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:204)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:589)
at java.net.Socket.connect(Socket.java:538)
at java.net.Socket.<init>(Socket.java:434)
at java.net.Socket.<init>(Socket.java:244)
at org.wso2.carbon.andes.internal.QpidServiceComponent.startAMQPServer(QpidServiceComponent.java:488)
at org.wso2.carbon.andes.internal.QpidServiceComponent.startAndesBroker(QpidServiceComponent.java:439)
at org.wso2.carbon.andes.internal.QpidServiceComponent.activate(QpidServiceComponent.java:165)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.eclipse.equinox.internal.ds.model.ServiceComponent.activate(ServiceComponent.java:260)
at org.eclipse.equinox.internal.ds.model.ServiceComponentProp.activate(ServiceComponentProp.java:146)
at org.eclipse.equinox.internal.ds.model.ServiceComponentProp.build(ServiceComponentProp.java:345)
at org.eclipse.equinox.internal.ds.InstanceProcess.buildComponent(InstanceProcess.java:620)
at org.eclipse.equinox.internal.ds.InstanceProcess.buildComponents(InstanceProcess.java:197)
at org.eclipse.equinox.internal.ds.Resolver.getEligible(Resolver.java:343)
at org.eclipse.equinox.internal.ds.SCRManager.serviceChanged(SCRManager.java:222)
at org.eclipse.osgi.internal.serviceregistry.FilteredServiceListener.serviceChanged(FilteredServiceListener.java:107)
at org.eclipse.osgi.framework.internal.core.BundleContextImpl.dispatchEvent(BundleContextImpl.java:861)
at org.eclipse.osgi.framework.eventmgr.EventManager.dispatchEvent(EventManager.java:230)
Note:-- Firewald service is disabled out here.
A: First, check if any other processes are occupying 5672. (If so kill that process or offset the WSO2 ports by n.) Then, let it try connecting for 20 minutes. If not, check the CPU utilization at the time. Similar issue got resolved by increasing the number of CPU cores.
A: Try turn offing the firewall
sudo ufw disable
| |
doc_4102
|
sumproduct(b5:b20;c5:c20)/sum(c5:c20)
In Power BI. I tried the following:
Waverage = sumx(table,table[column1])/sum(table[column2])
A: The SUMPRODUCT equivalent in PowerBI is SUMX, but just need to tweak your formula a bit:
Waverage =
VAR numerator = SUMX(table,table[column1]*table[column2])
VAR denominator = SUMX(table, table[column2])
RETURN DIVIDE(numerator, denominator)
The SUMX function here loops over each row of the table that you specify and performs calculations based on your expression. Here SUMX keeps summing the multiplication column1 and column2 row-by-row, until it has done so for all rows.
Variables can be used break down the code into smaller steps for understandability. The DIVIDE function is also useful as it automatically deals with instances where the denominator equals zero.
| |
doc_4103
|
A: Never directly modify tables in the data dictionary. Most of those "tables" are complicated views on undocumented objects. There's no telling what will happen if you modify them.
Instead, use the documented procedure DBMS_JOB.CHANGE to modify job properties. Or even better, avoid those old-fashioned jobs and use the newer DBMS_SCHEDULER package to create and manage jobs.
| |
doc_4104
|
I've created 2 applications: a front-end(calls the API and sends custom HTTP headers with it) and a back-end API:
Front-end method which calls API:
[HttpGet]
public async Task<ActionResult> getCall()
{
string url = "http://localhost:54857/";
string customerApi = "2";
using (var client = new HttpClient())
{
//get logged in userID
HttpContext context = System.Web.HttpContext.Current;
string sessionID = context.Session["userID"].ToString();
//Create request and add headers
client.BaseAddress = new Uri(url);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
//Custom header
client.DefaultRequestHeaders.Add("loggedInUser", sessionID);
//Response
HttpResponseMessage response = await client.GetAsync(customerApi);
if (response.IsSuccessStatusCode)
{
string jsondata = await response.Content.ReadAsStringAsync();
return Content(jsondata, "application/json");
}
return Json(1, JsonRequestBehavior.AllowGet);
}
}
Back-end which receives the request:
public class RedirectController : ApiController
{
//Retrieve entire DB
ConcurrentDBEntities dbProducts = new ConcurrentDBEntities();
//Get all data by customerID
[System.Web.Http.AcceptVerbs("GET")]
[System.Web.Http.HttpGet]
[System.Web.Http.Route("{id}")]
public Customer getById(int id = -1)
{
//Headers uitlezen
/*var re = Request;
var headers = re.Headers;
if (headers.Contains("loggedInUser"))
{
string token = headers.GetValues("loggedInUser").First();
}*/
Customer t = dbProducts.Customers
.Where(h => h.customerID == id)
.FirstOrDefault();
return t;
}
}
Routing:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
The code shown above works fine, I'm getting the correct results of my API call but I'm looking for a way to intercept all of the incoming GET request before im returning a response so i can modify and add logic to this controller. While making my GET request i add custom headers, I'm looking for a way to extract these from the incoming GET all before execution occurs.
Hope someone can help!
Thanks in advance
A: ActionFilterAttribute, used as in the following example, I created the attribute and put it on the api base class where all api classes inherit from, OnActionExecuting is entered before reaching the api method. we can check there if the RequestMethod is of "GET" and do whatever you are planning to do there.
public class TestActionFilterAttribute: ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
if (actionContext.Request.Method.Method == "GET")
{
//do stuff for all get requests
}
base.OnActionExecuting(actionContext);
}
}
[TestActionFilter] // this will be for EVERY inheriting api controller
public class BaseApiController : ApiController
{
}
[TestActionFilter] // this will be for EVERY api method
public class PersonController: BaseApiController
{
[HttpGet]
[TestActionFilter] // this will be for just this one method
public HttpResponseMessage GetAll()
{
//normal api stuff
}
}
| |
doc_4105
|
public UserControl1(){
}
but that didn't work as its returning null any suggestions.
var wc = new WebClient();
var users = "API link";
label.Content = users;
A: What if you do all that after the InitializeComponent(); call in your constructor ?
Once the label variable is set, then you can use it.
| |
doc_4106
|
class KeyboardHandler < EM::Connection
include EM::Protocols::LineText2
def initialize(q)
@queue = q
end
def receive_line(data)
@queue.push(data)
end
end
EM.run {
q = EM::Queue.new
callback = Proc.new do |line|
# puts on every keypress not on "\n"
puts line
q.pop(&callback)
end
q.pop(&callback)
EM.open_keyboard(KeyboardHandler, q)
}
A: If you want to receive unbuffered input from the terminal, you should turn off canonical-mode on standard input. (I also turn off echo to make the screen easier to read.) Add this before your code calls #open_keyboard or within your handler initializer:
require 'termios'
# ...
attributes = Termios.tcgetattr($stdin).dup
attributes.lflag &= ~Termios::ECHO # Optional.
attributes.lflag &= ~Termios::ICANON
Termios::tcsetattr($stdin, Termios::TCSANOW, attributes)
For example:
require 'termios'
require 'eventmachine'
module UnbufferedKeyboardHandler
def receive_data(buffer)
puts ">>> #{buffer}"
end
end
EM.run do
attributes = Termios.tcgetattr($stdin).dup
attributes.lflag &= ~Termios::ECHO
attributes.lflag &= ~Termios::ICANON
Termios::tcsetattr($stdin, Termios::TCSANOW, attributes)
EM.open_keyboard(UnbufferedKeyboardHandler)
end
A: Here's an update for Ruby 2.0+. In Ruby 2.0 we have io/console, which makes handling raw keyboard much easier, and it's cross-platform.
Here's a working example that reacts to raw keyboard events using io/console:
require 'io/console'
require 'eventmachine'
module KB
def receive_data(key)
puts "GOT: #{key}\r"
# CTRL-C will not work in raw mode, so we need another way to exit.
EM::stop if key == 'q'
end
end
begin
EM.run {
# Put console in raw mode (no echo, no line buffering).
IO.console.raw!
EM.open_keyboard(KB)
}
ensure
# Ensure cooked, otherwise console will be unusable after exit.
IO.console.cooked!
end
A: I've not used EventMachine before, but this page on the EventMachine wiki seems to indicate that you should not use the LineText2 protocol as it sounds like you don't want buffered lines.
They give this example:
module MyKeyboardHandler
def receive_data(keystrokes)
puts "I received the following data from the keyboard: #{keystrokes}"
end
end
EM.run {
EM.open_keyboard(MyKeyboardHandler)
}
Does that give you what you want?
| |
doc_4107
|
Then the Email gets sent by calling that method. For this, the global configuration values described in Mail API are used.
The thing is that I want some of these values to be different depending on the Pid of the email record being sent. What would be the most sensible way to achieve that? The only way I can think of doing this right now would be to extend and override the aforementioned class and method, and changing the desired $GLOBALS['TYPO3_CONF_VARS']['MAIL'][...] values before the parent::send call. But I'm not sure if this would be the most sensible and optimal way of achieving this. Should I try something else?
Thanks a lot in advance!
A: Your question still leaves a lot of additional questions:
what version of TYPO3 are you using?
what plugin do you use to transform information (User input?) into a mail?
depending on the software you have options to configure the mails additional to the basic configuration from $GLOBALS['TYPO3_CONF_VARS']['MAIL'].
This configuration is stored in /typo3conf/LocalConfiguration.php, which just stores constant data. But you also have typo3conf/AdditionalConfiguration.php where you can use functions to set values dynamically.
Probably the best way would be to configure your plugin with typoscript or fields in the CE to behave different depending on the page you work.
e.g.: if you use ext:form you have finisher you can configure to set parameters for mails, depending on any available information.
| |
doc_4108
|
The command line I used is
C:\Program Files (x86)\Microsoft\ILMerge>ilmerge /t:dll /out:NewFile.dll D:\victor\Excelimport.dll D:\victor\BOL3.dll**
But I got the following error. Can anyone tell me why I got this error: Unresolved assembly reference not allowed
An exception occurred during merging:
Unresolved assembly reference not allowed: Microsoft.Dexterity.Shell.
at System.Compiler.Ir2md.GetAssemblyRefIndex(AssemblyNode assembly)
at System.Compiler.Ir2md.GetTypeRefIndex(TypeNode type)
at System.Compiler.Ir2md.VisitReferencedType(TypeNode type)
at System.Compiler.Ir2md.VisitClass(Class Class)
at System.Compiler.Ir2md.VisitModule(Module module)
at System.Compiler.Ir2md.SetupMetadataWriter(String debugSymbolsLocation)
at System.Compiler.Ir2md.WritePE(Module module, String debugSymbolsLocation, BinaryWriter writer)
at System.Compiler.Writer.WritePE(String location, Boolean writeDebugSymbols, Module module, Boolean delaySign, String keyFileName, String keyName)
at System.Compiler.Writer.WritePE(CompilerParameters compilerParameters, Module module)
at ILMerging.ILMerge.Merge()
at ILMerging.ILMerge.Main(String[] args)
| |
doc_4109
|
Example:
Function to take a df and delete it:
def delete_file(df):
del df
Function to create a df and send it to my delete_file() function:
def create_and_delete_file():
import pandas as pd
# create / import dataframe
x = pd.DataFrame({'name':['jon','mary'],
'age':[12,45]})
# send the dataframe to my delete function
delete_file(x)
# now print it
print(x)
Let's call the functions. As you can see, I can still print dataframe x after I sent it to my delete_file function.
create_and_delete_file()
name age
0 jon 12
1 mary 45
How can I delete it?
edit More info in red text below (i know there are better ways to analyse a df, this is just hypothetical) The dataframe has 4 cities, equally split. Datafarme is 1GB in size.
# dataframe size 1 Gigabyte
def _calculate_city_sales(df):
'''
The dataframe 'df' is 1 GB in size
We will split it into four segments
Each segment is 250Mb in size
So at the end of the operation (Berlin)
has RAM usage not doubled?
'''
NY = df[df['city']=='NY']
sales = NY.sales.sum()
print(f'New York Sales: {sales}') # 1GB + 250Mb of RAM in use
LA = df[df['city']=='LA']
sales = LA.sales.sum()
print(f'Los Angeles Sales: {sales}') # 1GB + 250Mb + 250Mb of RAM in use
HK = df[df['city']=='HK']
sales = HK.sales.sum()
print(f'Hong Kong Sales: {sales}') # 1GB + 250Mb + 250Mb + 250Mb of RAM in use
BL = df[df['city']=='BL']
sales = BL.sales.sum()
print(f'Berlin Sales: {sales}') # <----- Ram Usage now at 2GB?
A: Try making df None.
def delete_file(df):
df = None
Now if you print df it should say "None". I have no idea why del isn't working though. However, you don't need to delete it manually as python does this on its own.
| |
doc_4110
|
Updating the Database
The Managed Bean's method which takes the form parameters and calls the Service method:
public String changeDetails(){
Date date = DateUtil.getDate(birthDate);
Integer id = getAuthUser().getId();
UserDetail newDetails = new UserDetail(id, occupation, date, originCity, residenceCity, description);
EntityTransaction transaction = getTransaction();
userService.updateDetail(newDetails);
transaction.commit();
return null;
}
The Service Method:
public boolean updateDetail(UserDetail newDetails) {
boolean ok = true;
if (newDetails != null) {
UserDetail user = readDetail(newDetails.getId());
user.setOccupation(newDetails.getOccupation());
user.setOriginCity(newDetails.getOriginCity());
user.setResidenceCity(newDetails.getResidenceCity());
user.setBirth(newDetails.getBirth());
user.setDescription(newDetails.getDescription());
}
return ok;
}
Fetching data from DB
@PostConstruct
public void init(){
userService = new UserService();
sessionController.setAuthUser(userService.read(getAuthUser().getId()));
originCity = getAuthUser().getUserDetail().getOriginCity();
residenceCity = getAuthUser().getUserDetail().getResidenceCity();
occupation = getAuthUser().getUserDetail().getOccupation();
birthDate = DateUtil.getStringDate(getAuthUser().getUserDetail().getBirth());
description = getAuthUser().getUserDetail().getDescription();
}
The problem is that the behavior of this code is different. Sometimes I obtain the desired result: once I submit the new details and call the @PostConstruct init () the new details are printed. Some other times the old details are printed even though the DB entry is updated.
Conclusion: Sometimes the JPA brings me different result from what is in the DB. I guess that this results consist of data from the Persistance Context, data which isn't updated. Is there a way in which I can be sure that the JPA always brings the data directly from the DB? Or is there something I'm missing?
A: You mean is there a way to turn the cache off or empty it before an operation ?
emf.getCache().evictAll();
A: If you are using JPA 2 then @Cacheable(false) on your entity definition should make it read from the DB every time.
| |
doc_4111
|
#!/bin/bash
# Script to post data to Top up processor
curl --request POST 'http://127.0.0.1/user//topup/process.php' --data "receipt=$1" --data "username=$9"
So to run it:
./mpesa_topup.sh sms_message
But the SMS server forwards the message with single quotes:
./mpesa_topup.sh 'sms_message'
The script ends up "parsing the entire SMS as 1 positional parameter. Here is a debug of what happens when the sms server runs the script.
root@sms:/var/lib/playsms/sms_command/1# bash -x mpesa_topup.sh 'JJA88QHC22 Confirmed.on 101015 at 9:49 PMKsh25.00 received from 254712345678 SOME BODY.New Account balance is Ksh25.00'
+ curl --request POST http://10.5.1.2/topup/process.php --data 'receipt=JJA88QHC22 Confirmed.on 101015 at 9:49 PMKsh25.00 received from 254722227332 JOTHAM KIIRU.New Account balance is Ksh25.00' --data username=
root@sms:/var/lib/playsms/sms_command/1#
Is there a way to remove/ignore the opening and closing single quotes in the Bash script?
PS : I am not a coder, gotten where I am with help from my friend Google.
A: It seems like you want the first and ninth word out of the single argument you are sent. You can do something like this:
$ set -- 'JJA88QHC22 Confirmed.on 101015 at 9:49 PMKsh25.00 received from 254712345678 SOME BODY.New Account balance is Ksh25.00'
$ echo $1
JJA88QHC22 Confirmed.on 101015 at 9:49 PMKsh25.00 received from 254712345678 SOME BODY.New Account balance is Ksh25.00
$ set -f # a
$ set -- $1 # b
$ set +f # c
$ echo $1
JJA88QHC22
$ echo $9
254712345678
The key is (b) where we omit the double quotes around the variable. This allows the shell to perform word-splitting on the value of the variable.
The shell will also attempt to perform glob-pattern expansion, unless you tell it not to, which I do in (a), and then turn that back on in (c).
A: You can solve this simply by putting your main command inside a function, and calling it again.
Your server is invoking your script with simple quotes, which transform your arguments in one single argument ($1).
If you treat this arg and call your_function() inside the script, you solved!
Here goes the example:
#!/bin/bash
# Script to post data to Top up processor
args=$1
your_function(){
curl --request POST 'http://127.0.0.1/user//topup/process.php' --data "receipt=$1" --data "username=$9"
}
your_function $1
A: Yes but that won't help. In the end, your code passes the whole SMS as a single string to curl because of --data "receipt=$1". If you only remove the quotes, that would become --data "receipt=JJA88QHC22" and the rest (like the amount) would be missing.
Your problem is that the input was multiple lines of text and that got somehow mangled. The solution is to parse the SMS. Since money is involved, you probably don't want any mistakes. That's why I would use a real programming language like Python or Java. But if you want to use BASH, this might work until an attacker starts sending you SMS to steal money:
# Split first parameter into $1...$n
set -- $1
recepient="$1"
# $2: Confirmed.on
# $3: 101015
# $4: at
# $5: 9:49
# $6: PMKsh25.00
amount=$(echo $6 | sed -e s/^(AM|PM)//) # sed removed the AM/PM at the beginning
# $7: received
# $8: from
sender="$7 $8 $9" # 254722227332 JOTHAM KIIRU.
| |
doc_4112
|
values <- matrix(rexp(440, rate=.1), ncol=44)
I would like to compute the below relative variance of these. Essentially i would like to compute this
This should return a (1 x m) matrix. A single computation in the first column would be something like this.
sum((values[10,9] / values[9,9])^2 / length(values[,1]))
I tried to loop this as ,
for (i in 2 : length(values)) {
values_new <- sum((values[i,i-1] / values[i-1,i-1])) ^ 2 / 10
}
I am not sure how to go about with a loop or a vectorized implementation. Appreciate your help.
A: Simply do:
colMeans((values[-1, ] / values[-nrow(values), ]) ^ 2)
Matrix manipulations/operations in R are fully vectorized.
The above code will divide all the values (except the first row) by all the values (except the last row), put everything in power of 2 and then calculate the resulting columns mean (notice that because we get a nrow(values) - 1 rows per column, we can simply calculate the column means).
A: You might want to try a vectorized version per column and use apply to go over all columns. Here is an example:
apply(values, 2, function(x){
z <- x[2:length(x)]
g <- x[1:(length(x)-1)]
return(sum((z/g)^2)/(length(x)-1))
})
explanation:
z is the same as x without the first element
g is the same as x without the last element
z/g[1] is the same as x[2]/x[1] and so on.. In other words for the first column:
sum((values[2:10,1]/values[1:9,1])^2)/(length(values[,1])-1)
apply goes over the matrix, column by column (since the second argument MARGIN was set to 2) and performs a function. The function performed here is anonymous (defined in place).
| |
doc_4113
|
SlackApp.java
@Configuration
public class SlackApp {
@Bean
public AppConfig loadSingleWorkspaceAppConfig() {
return AppConfig.builder()
.singleTeamBotToken(System.getenv("SLACK_BOT_TOKEN"))
.signingSecret(System.getenv("SLACK_SIGNING_SECRET"))
.build();
}
@Bean
public App initSlackApp(AppConfig config) {
App app = new App(config);
if (config.getClientId() != null) {
app.asOAuthApp(true);
}
app.command("/hello", (req, ctx) -> {
return ctx.ack(r -> r.text("Hi!"));
});
return app;
}
}
Inside the database package:
1.StaffRepository.java
@Repository
public interface StaffRepository extends CrudRepository<Staff, Integer>{
}
*StaffController.java
@RestController
public class StaffController {
@Autowired
private StaffService staffService;
@RequestMapping("/staffs")
public List<Staff> getAllStaffs(){
return staffService.getAllStaffs();
}
@RequestMapping("/staffs/{id}")
public Optional<Staff> getStaff(@PathVariable Integer id){
return staffService.getStaff(id);
}
@RequestMapping(method = RequestMethod.POST, value = "/staffs")
public void createStaff(@RequestBody Staff staff){
staffService.createStaff(staff);
}
}
*StaffService.java
@Service
public class StaffService {
@Autowired
private StaffRepository staffRepository;
public List<Staff> getAllStaffs(){
List<Staff> staffs = new ArrayList<>();
staffRepository.findAll().forEach(staffs::add);
return staffs;
}
public Optional<Staff> getStaff(Integer id){
return staffRepository.findById(id);
}
public void createStaff(Staff staff){
staffRepository.save(staff);
}
public void updateStaff(Integer id, Staff staff){
staffRepository.save(staff);
}
public void deleteStaff(Integer id){
staffRepository.deleteById(id);
}
}
*Staff.java
@Entity
@Table(name="staff")
public class Staff {
@Id
Integer id;
String date;
String time;
String name;
String InOrOut;
String whatFor;
String summary;
String company;
Integer hours;
public Staff(){}
public Staff(Integer id, String date, String time, String name, String InOrOut, String whatFor, String summary, String company, int hours){
super();
this.id = id;
this.date = date;
this.time = time;
this.name = name;
this.InOrOut = InOrOut;
this.whatFor = whatFor;
this.summary = summary;
this.company = company;
this.hours = hours;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getTime() {
return time;
}
public void setTime(String timeStamp) {
this.time = timeStamp;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getInOrOut() {
return InOrOut;
}
public void setInOrOut(String inOrOut) {
InOrOut = inOrOut;
}
public String getWhatFor() {
return whatFor;
}
public void setWhatFor(String whatFor) {
this.whatFor = whatFor;
}
public String getSummary() {
return summary;
}
public void setSummary(String summary) {
this.summary = summary;
}
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
public int getHours() {return hours;}
public void setHours(int hours) {this.hours = hours;}
}
Application.java
@SpringBootApplication
@ServletComponentScan
@EntityScan("example.database")
@ComponentScan({"example.database"})
public class Application {
public static void main(String[] args) {
ApplicationContext myapp = new AnnotationConfigApplicationContext(SlackApp.class);
SpringApplication.run(Application.class, args);
}
}
This is my file structrue:
main
+- java
+- example
+- Application.java
+- SlackApp.java
+- ......
|
+- database
| +- Staff.java
| +- StaffController.java
| +- StaffRepository.java
| +- StaffService.java
Here comes the problem:
If I add @ComponentScan({"example.database"}), it will show this error:
Description:
Parameter 0 of constructor in example.SlackAppController required a bean of type 'com.slack.api.bolt.App' that could not be found.
Action:
Consider defining a bean of type 'com.slack.api.bolt.App' in your configuration.
If I remove @ComponentScan({"example.database"}), it will show this:
Description:
Field staffRepository in example.database.StaffService required a bean of type 'example.database.StaffRepository' that could not be found.
The injection point has the following annotations:
- @org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type 'example.database.StaffRepository' in your configuration.
I also tried to move SlackApp.java into the database package, but it didn't work. Can someone help me, please?
| |
doc_4114
|
server {
listen 80;
root /var/www/mywebsite.com/www; # my index is not a wordpress
index index.php index.html index.htm;
charset UTF-8;
server_name mywebsite.com;
location ^/(alias1|alias2)/(.*)$ { # my wordpress web site
# i want 2 alias for the same wordpress
alias /var/www/mywebsite.com/wordpress;
}
location ~ \.php$ {
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass unix:/var/run/php5-fpm.sock;
fastcgi_index index.php;
include fastcgi_params;
}
location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
expires max;
log_not_found off;
}
}
When i call my web site from http://mywebsite.com/alias1
The php returned is from /var/www/mywebsite.com/www/index.php
if i put my root like /var/www/mywebsite.com/wordpress so the php is returned from /var/www/mywebsite.com/wordpress/index.php but the static return 404.
A part of my debug log:
2014/06/15 01:33:16 [debug] 3955#0: *3 using configuration "^/(alias1|alias2)"
2014/06/15 01:33:16 [debug] 3955#0: *3 http cl:-1 max:1048576
2014/06/15 01:33:16 [debug] 3955#0: *3 rewrite phase: 3
2014/06/15 01:33:16 [debug] 3955#0: *3 post rewrite phase: 4
2014/06/15 01:33:16 [debug] 3955#0: *3 generic phase: 5
2014/06/15 01:33:16 [debug] 3955#0: *3 generic phase: 6
2014/06/15 01:33:16 [debug] 3955#0: *3 generic phase: 7
2014/06/15 01:33:16 [debug] 3955#0: *3 access phase: 8
2014/06/15 01:33:16 [debug] 3955#0: *3 access phase: 9
2014/06/15 01:33:16 [debug] 3955#0: *3 access phase: 10
2014/06/15 01:33:16 [debug] 3955#0: *3 post access phase: 11
2014/06/15 01:33:16 [debug] 3955#0: *3 try files phase: 12
2014/06/15 01:33:16 [debug] 3955#0: *3 http script copy: "/var/www/mywebsite.com/public_html"
2014/06/15 01:33:16 [debug] 3955#0: *3 http script var: "/alias1/"
2014/06/15 01:33:16 [debug] 3955#0: *3 trying to use file: "/alias1/" "/var/www/mywebsite.com/public_html/alias1/"
2014/06/15 01:33:16 [debug] 3955#0: *3 http script var: "/alias1/"
2014/06/15 01:33:16 [debug] 3955#0: *3 trying to use dir: "/alias1/" "/var/www/mywebsite.com/public_html/alias1/"
2014/06/15 01:33:16 [debug] 3955#0: *3 http script copy: "/index.php?q="
2014/06/15 01:33:16 [debug] 3955#0: *3 http script var: "/alias1/"
2014/06/15 01:33:16 [debug] 3955#0: *3 http script copy: "&"
2014/06/15 01:33:16 [debug] 3955#0: *3 trying to use file: "/index.php?q=/alias1/&" "/var/www/mywebsite.com/public_html/index.php?q=/alias1/&"
2014/06/15 01:33:16 [debug] 3955#0: *3 internal redirect: "/index.php?q=/alias1/&"
2014/06/15 01:33:16 [debug] 3955#0: *3 rewrite phase: 1
2014/06/15 01:33:16 [debug] 3955#0: *3 test location: ~ "^/(alias1|alias2)"
2014/06/15 01:33:16 [debug] 3955#0: *3 test location: ~ "\.php$"
2014/06/15 01:33:16 [debug] 3955#0: *3 using configuration "\.php$"
2014/06/15 01:33:16 [debug] 3955#0: *3 http cl:-1 max:1048576
2014/06/15 01:33:16 [debug] 3955#0: *3 rewrite phase: 3
2014/06/15 01:33:16 [debug] 3955#0: *3 post rewrite phase: 4
2014/06/15 01:33:16 [debug] 3955#0: *3 generic phase: 5
2014/06/15 01:33:16 [debug] 3955#0: *3 generic phase: 6
2014/06/15 01:33:16 [debug] 3955#0: *3 generic phase: 7
2014/06/15 01:33:16 [debug] 3955#0: *3 access phase: 8
2014/06/15 01:33:16 [debug] 3955#0: *3 access phase: 9
2014/06/15 01:33:16 [debug] 3955#0: *3 access phase: 10
2014/06/15 01:33:16 [debug] 3955#0: *3 post access phase: 11
2014/06/15 01:33:16 [debug] 3955#0: *3 try files phase: 12
2014/06/15 01:33:16 [debug] 3955#0: *3 http script var: "/index.php"
2014/06/15 01:33:16 [debug] 3955#0: *3 trying to use file: "/index.php" "/var/www/mywebsite.com/www/index.php"
2014/06/15 01:33:16 [debug] 3955#0: *3 try file uri: "/index.php"
Like you see, once nginx find the right path but after he
What did I forget to do?
So if anybody have the solution i want a standart php website to target to a path:
/var/www/mywebsite/www
And for the same domain i want an alias who target to a wordpress script path:
/var/www/mywebsite/wordpress
So, I write a new question, more clearly here:
Nginx vhost website + wordpress alias in subfolder
A: You cannot match multiple locations with Nginx, so you need to include your PHP/fastcgi config inside the location block with the alias. If this isn't the only place you want to process PHP files, I would recommend putting that config into a different config file and use include to use it in multiple places.
php.conf
location ~ \.php$ {
# Zero-day exploit defense.
# http://forum.nginx.org/read.php?2,88845,page=3
# Won't work properly (404 error) if the file is not stored on this server, which is entirely possible with php-fpm/php-fcgi.
# Comment the 'try_files' line out if you set up php-fpm/php-fcgi on another machine. And then cross your fingers that you won't get hacked.
try_files $uri =404;
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass unix:/var/run/php5-fpm.sock;
fastcgi_index index.php;
include fastcgi_params;
}
nginx.conf
server {
# ... your server config
location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
expires max;
log_not_found off;
}
location ~* ^/(alias1|alias2)/ {
alias /var/www/mywebsite.com/wordpress;
try_files $uri $uri/ /index.php$is_args$args;
include php.conf;
}
include php.conf; # replaces your original config
}
| |
doc_4115
|
Before running grunt, the <head>…</head> is this:
<head>
<meta charset="utf-8">
<title>…</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, maximum-scale=1, minimum-scale=1, user-scalable=0, initial-scale=1">
<!-- Place favicon.ico and apple-touch-icon.png in the root directory -->
<!-- build:css(.) styles/vendor.css -->
<!-- bower:css -->
<!-- endbower -->
<!-- endbuild -->
<!-- build:css(.tmp) styles/main.css -->
<!-- Gridset CSS -->
<!--[if (!IE) | (gt IE 9)]><!--><link rel="stylesheet" href="./styles/gridset.css" /><!--<![endif]-->
<!--[if IE 9]><link rel="stylesheet" href="./styles/gridset-ie-9.css" /><![endif]-->
<!--[if lte IE 8]><link rel="stylesheet" href="./styles/gridset-ie-lte8.css" /><![endif]-->
<link rel="stylesheet" href="styles/normalize.css">
<link rel="stylesheet" href="styles/main.css">
<!-- endbuild -->
</head>
After running grunt, the ink to the css file is being commented out, which is obviously making the dist version of the site to look awful without any css attatched.
You can see what it looks like after running the grunt command below:
<head> <meta charset="utf-8"> <title></title> <meta name="description" content=""> <meta name="viewport" content="width=device-width,maximum-scale=1,minimum-scale=1,user-scalable=0,initial-scale=1"> <!-- Place favicon.ico and apple-touch-icon.png in the root directory --> <!--[if lte IE 8]>
<link rel="stylesheet" href="styles/main.0b0cc1af.css">
<![endif]-->
As you can see, it comments out the main.css file, then cuts off the rest of the <head>…</head>
Also, I have added my Gruntfile, if that can be any help to anybody:
// Generated on 2015-01-27 using generator-angular 0.10.0
'use strict';
// # Globbing
// for performance reasons we're only matching one level down:
// 'test/spec/{,*/}*.js'
// use this if you want to recursively match all subfolders:
// 'test/spec/**/*.js'
module.exports = function (grunt) {
// Load grunt tasks automatically
require('load-grunt-tasks')(grunt);
// Time how long tasks take. Can help when optimizing build times
require('time-grunt')(grunt);
// Configurable paths for the application
var appConfig = {
app: require('./bower.json').appPath || 'app',
dist: 'dist'
};
// Define the configuration for all the tasks
grunt.initConfig({
// Project settings
yeoman: appConfig,
// Watches files for changes and runs tasks based on the changed files
watch: {
bower: {
files: ['bower.json'],
tasks: ['wiredep']
},
js: {
files: ['<%= yeoman.app %>/scripts/{,*/}*.js'],
tasks: ['newer:jshint:all'],
options: {
livereload: '<%= connect.options.livereload %>'
}
},
jsTest: {
files: ['test/spec/{,*/}*.js'],
tasks: ['newer:jshint:test', 'karma']
},
styles: {
files: ['<%= yeoman.app %>/styles/{,*/}*.css'],
tasks: ['newer:copy:styles', 'autoprefixer']
},
gruntfile: {
files: ['Gruntfile.js']
},
livereload: {
options: {
livereload: '<%= connect.options.livereload %>'
},
files: [
'<%= yeoman.app %>/{,*/}*.html',
'.tmp/styles/{,*/}*.css',
'<%= yeoman.app %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}'
]
}
},
// The actual grunt server settings
connect: {
options: {
port: 9000,
// Change this to '0.0.0.0' to access the server from outside.
hostname: 'localhost',
livereload: 35729
},
livereload: {
options: {
open: true,
middleware: function (connect) {
return [
connect.static('.tmp'),
connect().use(
'/bower_components',
connect.static('./bower_components')
),
connect.static(appConfig.app)
];
}
}
},
test: {
options: {
port: 9001,
middleware: function (connect) {
return [
connect.static('.tmp'),
connect.static('test'),
connect().use(
'/bower_components',
connect.static('./bower_components')
),
connect.static(appConfig.app)
];
}
}
},
dist: {
options: {
open: true,
base: '<%= yeoman.dist %>'
}
}
},
// Make sure code styles are up to par and there are no obvious mistakes
jshint: {
options: {
jshintrc: '.jshintrc',
reporter: require('jshint-stylish')
},
all: {
src: [
'Gruntfile.js',
'<%= yeoman.app %>/scripts/{,*/}*.js'
]
},
test: {
options: {
jshintrc: 'test/.jshintrc'
},
src: ['test/spec/{,*/}*.js']
}
},
// Empties folders to start fresh
clean: {
dist: {
files: [{
dot: true,
src: [
'.tmp',
'<%= yeoman.dist %>/{,*/}*',
'!<%= yeoman.dist %>/.git{,*/}*'
]
}]
},
server: '.tmp'
},
// Add vendor prefixed styles
autoprefixer: {
options: {
browsers: ['last 1 version']
},
dist: {
files: [{
expand: true,
cwd: '.tmp/styles/',
src: '{,*/}*.css',
dest: '.tmp/styles/'
}]
}
},
// Automatically inject Bower components into the app
wiredep: {
app: {
src: ['<%= yeoman.app %>/index.html'],
ignorePath: /\.\.\//
}
},
// Renames files for browser caching purposes
filerev: {
dist: {
src: [
'<%= yeoman.dist %>/scripts/{,*/}*.js',
'<%= yeoman.dist %>/styles/{,*/}*.css',
'<%= yeoman.dist %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}',
'<%= yeoman.dist %>/styles/fonts/*'
]
}
},
// Reads HTML for usemin blocks to enable smart builds that automatically
// concat, minify and revision files. Creates configurations in memory so
// additional tasks can operate on them
useminPrepare: {
html: '<%= yeoman.app %>/index.html',
options: {
dest: '<%= yeoman.dist %>',
flow: {
html: {
steps: {
js: ['concat', 'uglifyjs'],
css: ['cssmin']
},
post: {}
}
}
}
},
// Performs rewrites based on filerev and the useminPrepare configuration
usemin: {
html: ['<%= yeoman.dist %>/{,*/}*.html'],
css: ['<%= yeoman.dist %>/styles/{,*/}*.css'],
options: {
assetsDirs: ['<%= yeoman.dist %>','<%= yeoman.dist %>/images']
}
},
// The following *-min tasks will produce minified files in the dist folder
// By default, your `index.html`'s <!-- Usemin block --> will take care of
// minification. These next options are pre-configured if you do not wish
// to use the Usemin blocks.
// cssmin: {
// dist: {
// files: {
// '<%= yeoman.dist %>/styles/main.css': [
// '.tmp/styles/{,*/}*.css'
// ]
// }
// }
// },
// uglify: {
// dist: {
// files: {
// '<%= yeoman.dist %>/scripts/scripts.js': [
// '<%= yeoman.dist %>/scripts/scripts.js'
// ]
// }
// }
// },
// concat: {
// dist: {}
// },
imagemin: {
dist: {
files: [{
expand: true,
cwd: '<%= yeoman.app %>/images',
src: '{,*/}*.{png,jpg,jpeg,gif}',
dest: '<%= yeoman.dist %>/images'
}]
}
},
svgmin: {
dist: {
files: [{
expand: true,
cwd: '<%= yeoman.app %>/images',
src: '{,*/}*.svg',
dest: '<%= yeoman.dist %>/images'
}]
}
},
htmlmin: {
dist: {
options: {
collapseWhitespace: true,
conservativeCollapse: true,
collapseBooleanAttributes: true,
removeCommentsFromCDATA: true,
removeOptionalTags: true
},
files: [{
expand: true,
cwd: '<%= yeoman.dist %>',
src: ['*.html', 'views/{,*/}*.html'],
dest: '<%= yeoman.dist %>'
}]
}
},
// ng-annotate tries to make the code safe for minification automatically
// by using the Angular long form for dependency injection.
ngAnnotate: {
dist: {
files: [{
expand: true,
cwd: '.tmp/concat/scripts',
src: ['*.js', '!oldieshim.js'],
dest: '.tmp/concat/scripts'
}]
}
},
// Replace Google CDN references
cdnify: {
dist: {
html: ['<%= yeoman.dist %>/*.html']
}
},
// Copies remaining files to places other tasks can use
copy: {
dist: {
files: [{
expand: true,
dot: true,
cwd: '<%= yeoman.app %>',
dest: '<%= yeoman.dist %>',
src: [
'*.{ico,png,txt}',
'.htaccess',
'*.html',
'views/{,*/}*.html',
'images/{,*/}*.{webp}',
'fonts/{,*/}*.*'
]
}, {
expand: true,
cwd: '.tmp/images',
dest: '<%= yeoman.dist %>/images',
src: ['generated/*']
}]
},
styles: {
expand: true,
cwd: '<%= yeoman.app %>/styles',
dest: '.tmp/styles/',
src: '{,*/}*.css'
}
},
// Run some tasks in parallel to speed up the build process
concurrent: {
server: [
'copy:styles'
],
test: [
'copy:styles'
],
dist: [
'copy:styles',
'imagemin',
'svgmin'
]
},
// Test settings
karma: {
unit: {
configFile: 'test/karma.conf.js',
singleRun: true
}
}
});
grunt.registerTask('serve', 'Compile then start a connect Web server', function (target) {
if (target === 'dist') {
return grunt.task.run(['build', 'connect:dist:keepalive']);
}
grunt.task.run([
'clean:server',
'wiredep',
'concurrent:server',
'autoprefixer',
'connect:livereload',
'watch'
]);
});
grunt.registerTask('server', 'DEPRECATED TASK. Use the "serve" task instead', function (target) {
grunt.log.warn('The `server` task has been deprecated. Use `grunt serve` to start a server.');
grunt.task.run(['serve:' + target]);
});
grunt.registerTask('test', [
'clean:server',
'concurrent:test',
'autoprefixer',
'connect:test',
'karma'
]);
grunt.registerTask('build', [
'clean:dist',
'wiredep',
'useminPrepare',
'concurrent:dist',
'autoprefixer',
'concat',
'ngAnnotate',
'copy:dist',
'cdnify',
'cssmin',
'uglify',
'filerev',
'usemin',
'htmlmin'
]);
grunt.registerTask('default', [
'newer:jshint',
'test',
'build'
]);
};
Thanks in advance!
A: The issue seems to be related to the conditional comments. Looks like usemin is not handling them correctly.
You can solve it by reversing the order of things, for example:
<!--[if (!IE) | (gt IE 9)]><!-->
<!-- build:css(.tmp) styles/gridset.css -->
<link rel="stylesheet" href="./styles/gridset.css" />
<!-- endbuild -->
<!--<![endif]-->
<!-- build:css(.tmp) styles/main.css -->
<link rel="stylesheet" href="styles/main.css">
<!-- endbuild -->
| |
doc_4116
|
but for some reason ng-click doesnt work inside the tooltip body content. here is my code.
<a tooltip-html-unsafe="{{htmlTooltip}}" tooltip-trigger="click" tooltip-placement="bottom" >Dashboard</a>
in controller
$scope.htmlTooltip = 'HRIS';
$scope.dosomething() = function() {
console.log("hello World");
};
how can i accomplish this task. Thanks in advance.
A: I think problem is here:
$scope.dosomething() = function() {
console.log("hello World");
};
You need to change it like this (delete brackets):
$scope.dosomething = function() {
console.log("hello World");
};
Also, it's better if you will add href="#" to your a tag, then cursor will be looking like a pointer.
If you need to call you dosomething function every time you click on the Dashboard link - you need to add ng-click="dosomething()" to your a tag.
So finally it will be looking like this:
<a href="#" tooltip-html-unsafe="{{htmlTooltip}}" ng-click="dosomething()" tooltip-trigger="click" tooltip-placement="bottom">Dashboard</a>
and controller:
$scope.htmlTooltip = 'HRIS';
$scope.dosomething = function() {
console.log("hello World");
};
You can see demo, here everything works OK:
Demo: http://plnkr.co/edit/guQiOUUjuj4fGJDwFBKE?p=preview
| |
doc_4117
|
df = pd.crosstab(db['Age Category'], db['Category'])
| Age Category | A | B | C | D |
|--------------|---|----|----|---|
| 21-26 | 2 | 2 | 4 | 1 |
| 26-31 | 7 | 11 | 12 | 5 |
| 31-36 | 3 | 5 | 5 | 2 |
| 36-41 | 2 | 4 | 1 | 7 |
| 41-46 | 0 | 1 | 3 | 2 |
| 46-51 | 0 | 0 | 2 | 3 |
| Above 51 | 0 | 3 | 0 | 6 |
df.dtype give me
Age Category
A int64
B int64
C int64
D int64
dtype: object
But, when i am writing this to MySQL I am not getting first column
The Output of MySQL is shown below:
| A | B | C | D |
|---|----|----|---|
| | | | |
| 2 | 2 | 4 | 1 |
| 7 | 11 | 12 | 5 |
| 3 | 5 | 5 | 2 |
| 2 | 4 | 1 | 7 |
| 0 | 1 | 3 | 2 |
| 0 | 0 | 2 | 3 |
| 0 | 3 | 0 | 6 |
I want to write in MySQL with First column.
I have created connection using
SQLAlchemy and PyMySQL
engine = create_engine('mysql+pymysql://[user]:[passwd]@[host]:[port]/[database]')
and I am writing using pd.to_sql()
df.to_sql(name = 'demo', con = engine, if_exists = 'replace', index = False)
but this is not giving me first column in MySQL.
Thank you for your time and consideration.
| |
doc_4118
|
The problem is that I don't know where should I place my backend request so that the request will done after uploading and setting urls.
Here is my codw what I imported from firebase.
import { ServiceRegistration } from '../../https/index';
import { storage } from '../../firebase';
import { getDownloadURL, ref, uploadBytesResumable } from 'firebase/storage';
const ServiceRegister = () => {
const [coverPicUrl, setCoverPicUrl] = useState(null); // to save single picture url
const [galleriesUrl, setgalleriesUrl] = useState([]);// to save multiple picture url
const [coverPic, setCoverPic] = useState();
const [gallery, setGallery] = useState([]);
const [Error, setError] = useState('');
function handleMultipleImage(e) {
for (let i = 0; i < e.target.files.length; i++) {
const newImage = e.target.files[i];
setGallery((prevState) => [...prevState, newImage]);
}
}
const uploadCoverPicture = () => {
const storageRef = ref(storage, `/images/${Date.now()}-${coverPic.name}`);
const uplaodTask = uploadBytesResumable(storageRef, coverPic);
uplaodTask.on(
"state_changed",
(snapshot) => { },
(error) => setError(error),
() => {
getDownloadURL(uplaodTask.snapshot.ref).then((downloadUrl) => {
setCoverPicUrl(downloadUrl);
})
}
)
}
function uploadGalleryPictures() {
gallery.map((file) => {
const storageRef = ref(storage, `/images/${Date.now()}-${file.name}`);
const uploadTask = uploadBytesResumable(storageRef, file);
uploadTask.on(
"state_changed",
(snapshot) => { },
(error) => setError(error),
() => {
getDownloadURL(uploadTask.snapshot.ref).then((downloadURLs) => {
for (let i = 0; i < galleriesUrl.length; i++) {
const newUrl = downloadURLs;
setgalleriesUrl((prevState) => [...prevState, newUrl]);
}
ServiceRegistration({ coverPicUrl, galleriesUrl }).then(res => {
setloading(false);
}).catch(err => {
setloading(false);
console.log(err);
})
});
}
);
})
}
function handleFirebaseUplaoding() {
uploadCoverPicture();
uploadGalleryPictures();
}
function handleRegistration(e) {
e.preventDefault();
setloading(true);
if (!coverPic) {
setError('Cover photo is required');
setloading(false);
}
else {
handleFirebaseUplaoding();
}
}
return (
<>
<AppForm headerText='Register your service with WedBook' handleSubmit={handleRegistration} errorText={Error}>
<div className='w-full pl-12 mt-4'>
<label htmlFor="coverpic" className='font-semibold'>Upload a cover photo</label><br />
<input type="file" id='coverpic' onChange={(e) => { setCoverPic(e.target.files[0]) }} className="border border-gray-400 w-[80%] rounded-lg px-3 py-0.5 text-base outline-none " required />
</div>
<div className='w-full pl-12 mt-12'>
<label htmlFor="gallery" className='font-semibold'>Upload Gallery Pictures (maximum 30 picture)</label><br />
<input type="file" name='coverPic' onChange={(e) => { handleMultipleImage(e) }} id='gallery' className="border border-gray-400 w-[80%] rounded-lg px-3 py-0.5 text-base outline-none " multiple />
</div>
<div className='w-full mt-12 flex justify-evenly items-center'>
<ButtonOutline btnType='button' text='Go Back' clickEvent={() => { setImageForm(false) }} />
<ButtonOutline btnType='submit' text='Register' />
</div>
</AppForm>
</>
);
}
I want to post request after recieving all urls from firebase . ServiceRegistration is backend request
| |
doc_4119
|
My intention is to cancel previous call if it hasn't finished. Can anybody can help me?
getAddressLatLng : function(text,callback) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
address : text,
region : Utils.getRegion()
},
function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
callback(results);
}
});
},
A: You could make a global request counter, and only perform your callback behavior if it does not increase. e.g.
var requests = 0;
...
getAddressLatLng : function(text,callback) {
var requestNum;
requests++;
requestNum = requests;
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
address : text,
region : Utils.getRegion()
},
function(results, status) {
if(requestNum != requests) return;
if (status == google.maps.GeocoderStatus.OK) {
callback(results);
}
});
},
I would also suggest debouncing/throttling your function so you don't waste bandwidth generating unnecessary requests (underscore has convenient functions for doing this).
| |
doc_4120
|
Unfortunately I'm almost certain my understanding of Angularjs concepts is flawed, so before blundering ahead with some shoe-horned solution, I would like to know what would be the 'angular way' of achieving this.
I have added a custom attribute directive 'eng-completable' to the html template of a component (a popup that displays on a button-click). I could also add a (potentially spurious) ng-model="completed" variable declaration... (the first line below is the relevant one - the others are all working fine)
<div eng-completable ng-model="completed" class="hidden popup {{component.popup.type}}" id="{{component.popup.name}}" data-replaces="{{component.popup.replaces}}">
<div ng-if="component.popup.type=='overlay'">
<div class="float-right button close-button">X</div>
</div>
<p class="heading">{{component.popup.heading}}</p>
<div class="popup-content">
<div ng-if="0" ng-repeat-start="(innerIndex, component) in component.popup.popup_components"></div>
<div ng-if="0" ng-repeat-start="(type, object) in component"></div>
<div ng-attr-id="{{'p' + pageId + '-s' + skey + '-c' + ckey + '-component-' + index + '-innerComponent-' + innerIndex}}" ng-switch="type">
<div ng-switch-when="image" eng-image></div>
<div ng-switch-when="paragraph" eng-paragraph></div>
</div>
<div ng-if="0" ng-repeat-end></div>
<div ng-if="0" ng-repeat-end></div>
</div>
</div>
I have added the corresponding directive to our app.js file:
app.directive('engCompletable', function() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
scope.completed = false;
console.log("completable attribute encountered and triggered: scope.completed = "+scope.completed);
}
}
});
But then what? How do I access the completed variable in a 'global' sense? The fact that the next step doesn't seem obvious suggests to me I've already gone awry.
What's the best way to store and track multiple completion variables (in multiple scopes?) in an angular app?
EDIT
I think I may need to include more specifics to really reveal my problem:
Assuming I'm able to add a 'completable' property to the scope of each eng-completable directive, when a user clicks a button component which triggers a corresponding popup component (through an id reference to just the DOM element), how do I refer to the angular scope of the popup component to alter the 'completable' property?
I understand that even the framing of the question could be flawed but, if it is, I'd like to know what is the 'right' way to do this, in angular.
Thanks.
A: Subscribing to events is a great way to share data between controllers. Here is an example of sharing to another controller that a comment is finished loading, and 'controller1' will keep track of all comments that were loaded.
Example controller that is waiting to see who is loaded:
angular.module('app').controller('controller1', ['$scope', '$rootScope', function controller1($scope, $rootScope) {
var unsubscribe = $rootScope.$on('comment:loaded', commentLoaded);
$scope.$on('$destroy', function removeBindings() {
unsubscribe();
});
var commentIdsLoaded = {};
function commentLoaded(event, comment) {
commentIdsLoaded[comment.id] = true;
}
});
Controller that is notifying comment loaded
angular.module('app').controller('controller2', ['$scope', '$rootScope', function controller2($scope, $rootScope) {
function commentFinishedLoading(comment) {
$rootScope.$emit('comment:loaded', comment);
}
});
This solution allows you to manage comments without storing them in $rootScope and only storing data in the model that needs it. It will also prevent memory leaks from happening of storing data about these if you change pages.
A: Events are probably the most light-weight way for sharing this kind of state between components and is often the way I would start handling this kind of problem.
With more inter-component interaction, events can become cumbersome and error prone. When there are lots of emitters and/or listeners, you need to make sure the right components are handling the right messages. You are also essentially duplicating state in each of the related components, which makes it easy to have out-of-synch issues.
The main alternative is using a shared service to manage shared state, which allows there to be no state duplication. Services are singletons, so you might not think they'd work well for managing multiple unique states, but they can hold maps (or arrays) of states just fine, and be watched for changes.
A shared service approach could look something like:
// Shared service
angular.module('app').service('completables', function(){
// A map of, perhaps { exerciseId : isCompleted }
var _states = {};
// You could put getters and setters on here to be more explicit
return { 'states': _states }
});
// Some high-level controller
angular.module('app').controller('highLevel', ['completables', function(completables){
$scope.completables = completables;
$scope.$watch('completeables.states', function(oldStates, newStates){
// Do something whenever ANY states change
});
});
// Low-level directives
app.directive('engCompletable', ['completables', function(completables){
return {
scope: { exercise: '=' },
link: function(scope, element, attrs) {
// Set initial (shared) state
completeables.state[scope.exercise.id] = false;
// Triggered by user interaction
scope.completeExercise = function(){
completeables.state[scope.exercise.id] = true;
};
// You could also watch for external changes to just this exercise
scope.completables = completeables;
scope.$watch('completables.' + [scope.exercise.id], function(oldState, newState){
// Do something when changed externally
});
}
}
}]);
Shared services incur more watchers, so keep that in mind. But it keeps the state in one place – great for maintaining synch – and it feels a little more robust.
| |
doc_4121
|
Is it even possible? I have a feeling that no. In that case what is the best alternative?
A: It is totally doable. Some ideas:
*
*It seems you do not need to generate code every time you compile your project. You can generate it once and either check-in into source control or publish as a library.
*Depending on whether you have access to the source code of the Java library or not you will need to use either .java parser or .class parser. Reflection may or may not work for you (the main constraint is you need to have the class in the classpath of the current JVM and load it in memory to access it via reflection API).
*For different approaches to Scala code generation with examples see this post.
A: Of course you can. You can generate them before compilation. You will want to introspect the Java classes (maybe using the reflection API) and then generate corresponding Scala source code. You can either generate it once and copy to the repository or create a generator and use it in the building tool, e.g. in SBT.
You can generate the code either by hand (by concatenating the strings) or by a library like TreeHugger
| |
doc_4122
|
This simple If did not work:
If txt1.Text = "" Or txt2.Text = "" Or txt3.Text = "" Then -Something-
However it works if I only put two of them to compare.
Thanks for your answers.
A: The code above should work but check for null or empty string with
String.IsNullOrEmpty is more elegant:
If String.IsNullOrEmpty(txt1.Text) Or _
String.IsNullOrEmpty(txt2.Text) Or _
String.IsNullOrEmpty(txt3.Text) Then
'Do something
End If
PD: If you use several "OR", all the conditionals will be checked.
If you use OrElse, it will check the conditionals in order and when one it's not true
the next conditional statements will not be checked
A: For or it's not confused. The above works fine.
A: Your code works. If you want the rest of the check to be ommitted you can use OrElse
If txt1.Text = "" OrElse txt2.Text = "" OrElse txt3.Text = "" Then
End If
or better
If String.IsNullOrEmpty(txt1.Text) OrElse String.IsNullOrEmpty(txt2.Text) OrElse String.IsNullOrEmpty(txt3.Text) Then
End If
| |
doc_4123
|
<a href="../Temp/Images/def.jpg" download="">Download</div></a>
Which works fine on a chrome browser but does not work in my webview app. I already activated several permissions.
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.DOWNLOAD_WITHOUT_NOTIFICATION" />
But still the link does not react. How can I trigger a download?
EDIT:
Response Headers:
Cache-Control:private
Connection:Close
Content-Disposition:attachment; filename=IMG_20141004_171308.jpg
Content-Length:3039432
Content-Type:image/jpeg
Date:Wed, 15 Oct 2014 12:35:57 GMT
Server:ASP.NET Development Server/10.0.0.0
X-AspNet-Version:4.0.30319
X-AspNetMvc-Version:4.0
A: Try adding download listener -
mWebView.setDownloadListener(new DownloadListener() {
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimetype,
long contentLength) {
Request request = new Request(Uri.parse(url));
request.allowScanningByMediaScanner();
request.setNotificationVisibility(
DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(
Environment.DIRECTORY_DOWNLOADS, //Download folder
"download"); //Name of file
DownloadManager dm = (DownloadManager) getSystemService(
DOWNLOAD_SERVICE);
dm.enqueue(request);
}
});
A: I had same problem. Here is how I solved it. I extended WebViewClient:
import java.io.File;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.DownloadManager;
import android.content.Context;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.webkit.WebView;
import android.webkit.WebViewClient;
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class MyWebViewClient extends WebViewClient {
private Context context;
public MyWebViewClient(Context context) {
this.context = context;
}
@SuppressLint("NewApi")
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if(url.contains(".jpg")){
DownloadManager mdDownloadManager = (DownloadManager) context
.getSystemService(Context.DOWNLOAD_SERVICE);
DownloadManager.Request request = new DownloadManager.Request(
Uri.parse(url));
File destinationFile = new File(
Environment.getExternalStorageDirectory(),
getFileName(url));
request.setDescription("Downloading ...");
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationUri(Uri.fromFile(destinationFile));
mdDownloadManager.enqueue(request);
return true;
}
return super.shouldOverrideUrlLoading(view, url);
}
public String getFileName(String url) {
String filenameWithoutExtension = "";
filenameWithoutExtension = String.valueOf(System.currentTimeMillis()
+ ".jpg");
return filenameWithoutExtension;
}
}
Of course you can modify url filter such as Uppercase etc other extensions...
In Fragment, add the line:
webPreview.setWebViewClient(new MyWebViewClient(getActivity()));
Or in Activity, add the line:
webPreview.setWebViewClient(new MyWebViewClient(this));
Of course modify webPreview to the WebView name you set
Make sure you add to WebView settings:
webSettings.setDomStorageEnabled(true);
if you have set:
webSettings.setBlockNetworkImage (false);
A: The correct working code in API 30 and more.
Make sure to add following permission in manifest.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
webView.setDownloadListener(new DownloadListener() {
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimetype,
long contentLength) {
Log.i("KAMLESH","Download Image Request "+url);
if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)
{
requestForPermissions(permissionsRequired);
return;
}
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.allowScanningByMediaScanner();
request.setNotificationVisibility(
DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "download"); //Name of file
File file = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS), "image_" + System.currentTimeMillis() + ".jpg");
file.getParentFile().mkdirs();
request.setDestinationUri(Uri.fromFile(file));
DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
dm.enqueue(request);
}
});
void requestForPermissions(String permissions[])
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Need Permission");
builder.setMessage("This app needs Storage permission.");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
ActivityCompat.requestPermissions(WebViewActivity.this, permissionsRequired, 1);
}
});
builder.show();
}
| |
doc_4124
|
Would it be possible to show both hex and ASCII in text mode just like a GUI hex editor?
A: The vim editor usually (?) includes the tool xxd.
$ xxd `which xxd` | head -n 10
0000000: 7f45 4c46 0201 0100 0000 0000 0000 0000 .ELF............
0000010: 0200 3e00 0100 0000 400a 4000 0000 0000 ..>.....@.@.....
0000020: 4000 0000 0000 0000 f035 0000 0000 0000 @........5......
0000030: 0000 0000 4000 3800 0800 4000 1b00 1a00 ....@.8...@.....
0000040: 0600 0000 0500 0000 4000 0000 0000 0000 ........@.......
0000050: 4000 4000 0000 0000 4000 4000 0000 0000 @.@.....@.@.....
0000060: c001 0000 0000 0000 c001 0000 0000 0000 ................
0000070: 0800 0000 0000 0000 0300 0000 0400 0000 ................
0000080: 0002 0000 0000 0000 0002 4000 0000 0000 ..........@.....
0000090: 0002 4000 0000 0000 1c00 0000 0000 0000 ..@.............
A: hexdump itself will show both hex and ascii side-by-side:
$ date | hexdump -v -C
00000000 54 68 75 20 4d 61 79 20 20 31 20 31 36 3a 30 30 |Thu May 1 16:00|
00000010 3a 32 35 20 50 44 54 20 32 30 31 34 0a |:25 PDT 2014.|
0000001d
man hexdump explains:
-C Canonical hex+ASCII display. Display the input offset
in hexadecimal, followed by sixteen space-separated,
two column, hexadecimal bytes, followed by the same
sixteen bytes in %_p format enclosed in ``|'' charac‐
ters.
Calling the command hd implies this option.
A: hexdump -C does what you want.
# hexdump -C /etc/passwd
00000000 72 6f 6f 74 3a 78 3a 30 3a 30 3a 72 6f 6f 74 3a |root:x:0:0:root:|
00000010 2f 72 6f 6f 74 3a 2f 62 69 6e 2f 62 61 73 68 0a |/root:/bin/bash.|
00000020 64 61 65 6d 6f 6e 3a 78 3a 31 3a 31 3a 64 61 65 |daemon:x:1:1:dae|
00000030 6d 6f 6e 3a 2f 75 73 72 2f 73 62 69 6e 3a 2f 62 |mon:/usr/sbin:/b|
00000040 69 6e 2f 73 68 0a 62 69 6e 3a 78 3a 32 3a 32 3a |in/sh.bin:x:2:2:|
00000050 62 69 6e 3a 2f 62 69 6e 3a 2f 62 69 6e 2f 73 68 |bin:/bin:/bin/sh|
...
| |
doc_4125
|
And one build step.
Runner type -- Command Line
Step name -- test
Run -- Custom Script
Script:
conda create -n my_env python=3.8 pytest
source activate my_env
pytest my_file.py
The script is working (I can see results in log PASSED [100%])
But in the "Status" I see
TeamCity: Number of tests 0 is less then the provided threshold
How can I say TeamCity to count my tests?
A: Found solution
I have to install special package teamcity-messages
conda create -n my_env python=3.8 pytest teamcity-messages
| |
doc_4126
|
*
*to add servlet support, I have to right click on the project and "add framework support -> web application" (optionally creates web.xml)
*to add support for JPA, "project structure -> facets -> JPA" (optionally creates persistence.xml)
*to add support for spring data, "project structure -> modules -> Spring data JPA". Adding this, forces me to download new spring data libraries, which override the ones downloaded from maven. Although Intellij sees that the libraries already exist, it gives me no option to keep the existing ones
My question is
*
*is there a significant difference between the 3 options, or is it an inconsistency of Intellij?
*is there a way to add support for spring data jpa without overwriting the existing libraries?
| |
doc_4127
|
Angle Sys Cos Cosine Sys Sin Sine Tangent Cotangent Secant Cosecant
0 1.0000 1.0000 0.0000 0.0000 0.0000 inf
15 0.9659 0.0341 0.2588 -0.9659 -0.9659 -inf
30 0.8660 0.1340 0.5000 -0.8660 -0.8660 -inf
45 0.7071 0.2929 0.7071 -0.7071 -0.7071 -inf
60 0.5000 0.5000 0.8660 -0.5000 -0.5000 -inf
75 0.2588 0.7412 0.9659 -0.2588 -0.2588 -inf
90 0.0000 1.0000 1.0000 0.0000 0.0000 -inf
105 -0.2588 1.2588 0.9659 0.2588 0.2588 -inf
120 -0.5000 1.5000 0.8660 0.5000 0.5000 -inf
135 -0.7071 1.7071 0.7071 0.7071 0.7071 -inf
150 -0.8660 1.8660 0.5000 0.8660 0.8660 -inf
165 -0.9659 1.9659 0.2588 0.9659 0.9659 -inf
180 -1.0000 2.0000 0.0000 1.0000 1.0000 -inf
195 -0.9659 1.9659 -0.2588 0.9659 0.9659 -inf
210 -0.8660 1.8660 -0.5000 0.8660 0.8660 -inf
225 -0.7071 1.7071 -0.7071 0.7071 0.7071 -inf
240 -0.5000 1.5000 -0.8660 0.5000 0.5000 -inf
255 -0.2588 1.2588 -0.9659 0.2588 0.2588 -inf
270 -0.0000 1.0000 -1.0000 -0.0000 -0.0000 -inf
285 0.2588 0.7412 -0.9659 -0.2588 -0.2588 -inf
300 0.5000 0.5000 -0.8660 -0.5000 -0.5000 -inf
315 0.7071 0.2929 -0.7071 -0.7071 -0.7071 -inf
330 0.8660 0.1340 -0.5000 -0.8660 -0.8660 -inf
345 0.9659 0.0341 -0.2588 -0.9659 -0.9659 -inf
360 1.0000 -0.0000 -0.0000 -1.0000 -1.0000 0.9501
Process returned 0 (0x0) execution time : 0.044 s
Press any key to continue.
Source code:
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
// Function Prototypes..
// These are the only function you need to write
// See Sample functions below main()
double Factorial(double); // For loop version
double Sine(double); // Taylor Series Sine
double Cosine(double); // Taylor Series Cosine
double Tangent(double); // Tangent(x) = Sine(x)/Cosine(x)
double Cotangent(double); // Cotangent(x) = Cosine(x)/Sine(x)
double Secant(double); // Secant(x) = 1.0/Cosine(x)
double Cosecant(double); // Cosecant(x) = 1.0/Sine(x)
void PrintTrigTable(void); // Print Trignometric Table
// This main function is complete
int main()
{
PrintTrigTable();
return 0;
}
// PrintTrigTable - write this function
void PrintTrigTable()
{
cout << fixed<<setw(6)<<"Angle";
cout <<fixed << setw(9) << "Sys Cos" << setw(9) << "Cosine" << setw(9) << "Sys Sin" << setw(8) << "Sine";
cout << fixed << setw(9) << "Tangent" << setw(12) << "Cotangent" << setw(9) << "Secant" << setw(9) << "Cosecant" <<endl;
for (double x = 0.0; x <= 360.0; x += 15.0)
{
cout << fixed << setw (6) << setprecision(0) << x;
cout << fixed << setw (9) << setprecision(4)<< cos(x*3.1415926/180);
cout << fixed << setw (9) << setprecision(4)<< Cosine(x);
cout << fixed << setw (9) << setprecision(4)<< sin(x*3.1415926/180);
cout << fixed << setw (9) << setprecision(4)<< Sine(x);
cout << fixed << setw (9) << setprecision(4)<< Tangent(x);
cout << fixed << setw (9) << setprecision(4)<< Cotangent(x) <<endl;
//cout << fixed << setw (9) << setprecision(4)<< Secant(x)<<endl;
//cout << fixed << setw (9) << setprecision(4)<< Cosecant(x) <<endl;
}
}
// Factorial - write this function
double Factorail(double angle)
{
double fact = 1;
for (double i =1; i <= angle; i++)
fact *=i;
return(fact);
}
// Sine - write this function
double Sine(double angle)
{
double PI = 3.1415926;
double mysin= 0, mysin2= 9999;
double anglerad = angle*PI/180.0;
double c =1., counter, fact;
while (abs(mysin2-mysin)> .0001)
{
mysin2= mysin;
fact = 1;
for ( double k =1; k <= counter; k++)
fact *=k;
mysin= mysin + pow(-1,c)*(pow(anglerad,counter)/fact);
c = c+1;
counter = counter +2;
}
return(mysin);
}
double Cosine(double angle)
{
double PI = 3.1415926;
double mycos= 1, mycos2= 9999;
double anglerad = angle*PI/180.0;
double c =1, counter, fact;
while (abs(mycos2-mycos)> .0001)
{
mycos2= mycos;
fact = 1;
for ( double k =1; k <= counter; k++)
fact *=k;
mycos= mycos + pow(-1,c)*(pow(anglerad,counter)/fact);
c = c+1;
counter = counter +2;
}
return(mycos);
}
// Tangent - Tangent(x) = Sine(x)/Cosine(x)
double Tangent(double angle)
{
double inf = (Sine(angle)/Cosine(angle));
if (inf > 100)
{
inf =1.0/0.0;
}
else if (inf < -100)
{
inf = -1.0/0.0;
}
return inf;
}
// Cotangent - write this function -
double Cotangent(double angle)
{
double inf = (Cosine(angle)/Sine( angle));
if (inf > 100)
{
inf =1.0/0.0;
}
else if (inf < -100)
{
inf = -1.0/0.0;
}
return inf;
}
// Secant - Secant(x) = 1.0/Cosine(x)
double Secant(double angle)
{
double inf = (1.0/Cosine(angle));
if (inf > 100)
{
inf =1.0/0.0;
}
else if (inf < -100)
{
inf = -1.0/0.0;
}
return inf;
}
// Cosecant - write this function
double Cosecant(double angle)
{
double inf = (1.0/Sine(angle));
if (inf > 100)
{
inf =1.0/0.0;
}
else if (inf < -100)
{
inf = -1.0/0.0;
}
return inf;
}
| |
doc_4128
|
$(document).mouseup(function (e){
if ($("#full_window_dim").is(':visible') && !$("#hodnotenie_hl_okno").is(e.target) && $("#hodnotenie_hl_okno").has(e.target).length === 0){
$("#full_window_dim").fadeOut();
$('html, body').removeClass('stop-scrolling');
}
});
but this code is not working on mobile phones (I have tried with iPhone 5 - Safari)
How can I hide the element when users taps outside of the window on mobile phones ?
A: you can use touchstart for phones since most devices do not understand the mouse events.
here's the code. you can include as many events you want.
function HideModal(){
if ($("#full_window_dim").is(':visible') && !$("#hodnotenie_hl_okno").is(e.target) && $("#hodnotenie_hl_okno").has(e.target).length === 0){
$("#full_window_dim").fadeOut();
$('html, body').removeClass('stop-scrolling');
}
}
$(document).on({
"touchstart": function (event) { HideModal(); },
"mouseup": function (event) { HideModal(); }
});
A: You can define "body{cursor:pointer}" for your mobile css, then Safari Mobile behaviors as a click, not tap. But I'm not sure if it's an optimal way. I just tried it and worked for me.
| |
doc_4129
|
sudo -u $USER $SUDOCMD &>>stdout.log
The sudo command is a realtime process that print out lots of stuff to the console.
After running the script each time, the script does not return to the command prompt. You have to press enter or ctrl + c to get back to the command prompt.
Is there a way to to do it automatically, so that I can get a return value from the script to decide whether the script runs ok or failed.
thanks.
A: What is probably happening here is that your script is printing binary data to the TTY rather than text to standard output/error, and this is hiding your prompt. You can for example try this:
$ PS1='\$ '
$ (printf "first line\nsecond line\r" > $(tty)) &>> output.log
The second command will result in two lines of output, the second one being "mixed in" with your prompt:
first line
$ cond line
As you can see the cursor is on the "c", but if you start typing the rest of the line is overwritten. What has happened here is the following:
*
*You pressed Enter to run the command, so the cursor moved a line down.
*The tty command prints the path to the terminal file, something like "/dev/pts/1". Writing to this file means that the output does not go to standard output (which is usually linked to the terminal) but directly to the terminal.
*The subshell (similar to running the command in a shell script) ensures that the first redirect isn't overridden by the second one. So the printf output goes directly to the terminal, and nothing goes to the output log.
*The terminal now proceeds to print the printf output, which ends in a carriage return. Carriage return moves the cursor to the start of the line you've already written to, so that is where your prompt appears.
By the way:
*
*&>> redirects both standard output and standard error, contrary to your filename.
*Use More Quotes™
*I would recommend reading up on how to put a command in a variable
| |
doc_4130
|
I keep getting error every time.
I am welcome to do a teamviewer session.
Thank you.
ASP.NET code
<asp:Panel ID="pnlInfoSearch" runat="server">
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
SearchText();
});
function SearchText() {
$(".autosuggest").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "View.ascx/GetPartNumber",
data: "{'PartNumber':'" + document.getElementById('txtPartNum').value + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert("Error");
}
});
}
});
}
</script>
<div id="introcopy">
<h2>Product Info Center</h2>
<p>Download technical and quality documents, check inventory and order samples for your parts.</p>
</div>
<div class="demo">
<p>Enter a part number (or portion of a part number) to retrieve information about that product.</p>
<input type="text" id="txtPartNum" value="Enter part #..." style="height: 18px" class="autosuggest" />
</div>
<script type="text/javascript">
// <![CDATA[
var _sDefaultText = 'Enter part #...';
jQuery('#txtPartNum').keypress(function (e) {
if (e.which == 13) {
e.preventDefault();
window.location.href = '<%= new Uri(String.Concat("http://", Page.Request.UserHostName, Page.Request.RawUrl)).AbsolutePath %>?partnum=' + jQuery(this).val();
}
}).focus(function () {
if (jQuery(this).val() === _sDefaultText) {
jQuery(this).val('');
}
}).blur(function () {
if (jQuery(this).val().length == 0) {
jQuery(this).val(_sDefaultText);
}
});
// ]]>
</script>
<br class="clear" />
</asp:Panel>
C# code....
[WebMethod]
public static List<string> GetPartNumber(string PartNumber)
{
List<string> result = new List<string>();
using (SqlConnection conn = new SqlConnection("HIDDEN"))
{
using (SqlCommand cmd = new SqlCommand("select PartNumber from Products.Products where PartNumber LIKE @SearchText+'%'", conn))
{
conn.Open();
cmd.Parameters.AddWithValue("@SearchText", PartNumber);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
result.Add(dr["PartNumber"].ToString());
}
return result;
}
}
}
A: If you think your issue is SQL related, then refactor the SQL related code and write some tests against that method with some know part numbers.
Looking at your code, the URL for your service method stands out. You specify You specified url: "View.ascx/GetPartNumber" but I would assume you either meant something else (maybe View.ashx or View.asmx). Are you able to hit your service method via your browser as a simple GET?
What do you get when you access this URI in your browser? /View.ascx/GetPartNumber?PartNumber=xyz
| |
doc_4131
|
I want user authentication(read only access) to run sql queries over amazon athena. Athena will be used to run read only queries over s3.
Hue will be used for user authentication instead of direct access to Athena.
So I think with the help of Hue, this can be achievable.
But I'm unable to find the clear way to do apache hue integration with Athena.
A: Hue login has nothing to do with Athena's credential management.
*
*Setup users in Athena (however you do that, I don't know. Seems like IAM bucket policies)
*Download Athena's JDBC driver.
*Copy driver into Hue and configure it for the JDBC notebook interface
You will be prompted for login credentials from the JDBC connection
| |
doc_4132
|
*
*Dispose
*Terminate
*Shutdown
The above 3 methods looks similar by name. However I am not sure about their proper meaning.
Basically, in the provided examples such as Weather update server, the dispose functionality is done automatically by C# because of keyword using. However, in my code, I want to dispose the ZContext object manually. See below the code snippet:
public partial class DataPublisherForm : Form
{
private ZContext zmqContext;
private ZSocket sensorDataPublisher;
public DataPublisherForm()
{
mySensor = new Sensor();
mySensor.DataArrived += OnDataArrived;
zmqContext = new ZContext();
sensorDataPublisher = new ZSocket(zmqContext, ZSocketType.PUB);
sensorDataPublisher.SetOption(ZSocketOption.CONFLATE, 1);
sensorDataPublisher.Bind("tcp://*:10000");
}
private void OnDataArrived(object sender, DataArrivedEventArgs e)
{
byte[] sensorData = e.getSenorData();
sensorDataPublisher.Send(new ZFrame(sensorData));
}
private void DataPublisherForm_FormClosing(object sender, FormClosingEventArgs e)
{
zmqContext.Shutdown();
if (sensorDataPublisher != null)
{
sensorDataPublisher.Close();
sensorDataPublisher.Dispose();
}
}
}
Following are my observations:
*
*Dispose: When I use Dispose method, the application hangs (doesn't respond)
*Shutdown: When I use Shutdown method, the application closes smoothly.
Below are my queries:
*
*What is the proper way to dispose ZContext and ZSocket objects?
*What is the difference among Dispose, Terminate and Shutdown methods?
A: Short version:
Well, there are certain magics under the hood of the ZeroMQ zmqContext() instance, which may well turn things into havoc.
.Terminate() method is a mandatory API-call
.Shutdown() method wraps an optional-only API-call, with a must to call the mandatory API-call
.Dispose() method does GC.SuppressFinalize(this); first and calls .Terminate()
Best practices:
Be nice to resources. Better manage them explicitly and with a due care.
Be cautions on closing the things, that worked. Can hang the whole circus by not doing things right.
public partial class DataPublisherForm : Form
{
private ZContext zmqContext; // a Context() class-instance
private ZSocket sensorDataPublisher; // a Socket() class-instance
// -------------------------------------------- // this.VERSION details
private int majorVerNUM,
minorVerNUM,
patchVerNUM;
private string libzmqVerSTR;
// -------------------------------------------- //
public DataPublisherForm() // CONSTRUCTOR:
{
zmqContext = new ZContext();
zmq.zmq_version( this.majorVerNUM, // Ref. a trailer note:
this.minorVerNUM,
this.patchVerNUM
);
this.libzmqVerSTR = string.Format( "libzmq DLL is version {0}",
zmq.LibraryVersion()
);
mySensor = new Sensor();
mySensor.DataArrived += OnDataArrived;
sensorDataPublisher = new ZSocket(zmqContext, ZSocketType.PUB);
sensorDataPublisher.SetOption(ZSocketOption.CONFLATE, 1);
sensorDataPublisher.Bind("tcp://*:10000");
}
private void OnDataArrived(object sender, DataArrivedEventArgs e)
{
byte[] sensorData = e.getSenorData();
sensorDataPublisher.Send(new ZFrame(sensorData));
}
private void DataPublisherForm_FormClosing(object sender, FormClosingEventArgs e)
{
if (sensorDataPublisher != null)
{ sensorDataPublisher.SetOption( ZSocketOption.LINGER, 0 );
sensorDataPublisher.Close();
sensorDataPublisher.Dispose();
}
// -------------------------<NEVER BEFORE SAFE DISMANTLING ALL SOCKETS>---
zmqContext.Shutdown(); // optional API-call
zmqContext.Terminate(); // mandatory API-call
}
// -------------------------------------------- // VERSION CONTROL METHODS
public string getDllVersionSTRING() // a DLL version
{ return this.libzmqVerSTR;
}
public int getVersionMAJOR() // a version() responder
{
return this.majorVerNUM;
}
public int getVersionMINOR() // a version() responder
{
return this.minorVerNUM;
}
public int getVersionPATCH() // a version() responder
{
return this.patchVerNUM;
}
}
A few version-control methods were just sketched in principle, not finalised in detail, the less tested. The rationale for using a similar concept is in the fact that one cannot ensure ( enforce ) a realistic, distributed ecosystem, where only homogeneous API-versions are granted.
Thus in many operational cases, the API-versions need not match and ZeroMQ has ( besides its own version evolution ) different behaviour requirements ( performance-wise, memory-wise, {local|non-local}-processing-wise ) and having methods to locally detect which API-version or DLL-version is actually used / linked against, is worth having them ( debugging report being the Case#1, not to mention other, API-specific decisions taken on-the-fly ).
An ability to ask a class-method to answer these actual version details could literally save one's hair in troubles during a bug-hunt or after a new version release there comes a review of all related engineering changes and tracking new decision points introduced by all the new features / changed modus operandi.
| |
doc_4133
|
$(function(){
var a=1;
$("#btn").on("click",function(){
a++;
var b=1;
function foo(){
alert(a*b);
b++;
}
}
}
In this case, what is the life time of variable 'a' and 'b'. Is new 'b' allocated in every call of click event and previous b deleted by garbage collector?
| |
doc_4134
|
I'm still having trouble understanding how to read, but I also have no idea how to sign. I thought I'd use the pip signxml library but I do not know if that's the way.
My code so far:
import OpenSSL
def load_public_key(pfx_path, pfx_password):
''' Read the public key and return as PEM encoded '''
# print('Opening:', pfx_path)
with open(pfx_path, 'rb') as f:
pfx_data = f.read()
# print('Loading PFX contents:')
pfx = OpenSSL.crypto.load_pkcs12(pfx_data, pfx_password)
public_key = OpenSSL.crypto.dump_publickey(
OpenSSL.crypto.FILETYPE_PEM,
p12.get_certificate().get_pubkey())
print(public_key)
return public_key
teste = load_public_key("certificates/myfile.pfx", 'mypass')
I need to read a script, sign any XML and get a string with that xml.
A: After some research I came to the following result:
from OpenSSL.crypto import *
import os
passwd = 'my_pass'
cd = 'my_folder'
p12 = load_pkcs12(open(cd + 'file.pfx', 'rb').read(), passwd)
pkey = p12.get_privatekey()
open(cd + 'pkey.pem', 'wb').write(dump_privatekey(FILETYPE_PEM, pkey))
cert = p12.get_certificate()
open(cd + 'cert.pem', 'wb').write(dump_certificate(FILETYPE_PEM,
cert))
ca_certs = p12.get_ca_certificates()
ca_file = open(cd + 'ca.pem', 'wb')
for ca in ca_certs:
ca_file.write(dump_certificate(FILETYPE_PEM, ca))
| |
doc_4135
|
This is my attempt:
df = pd.DataFrame([[1,1],[1,1]])
def mult(df_view, a):
df_view *= a
mult(df.loc[1,1], 2)
print(df)
This is the (undesired) output:
0 1
0 1 1
1 1 1
The expected output is:
0 1
0 1 1
1 1 2
Notice that if we do the assignment directly (i.e. w/o the function), it works:
df = pd.DataFrame([[1,1],[1,1]])
df.loc[1,1] *= 2
print(df)
... gives:
0 1
0 1 1
1 1 2
So, apparently I'm messing up something when passing that view through the function call. I have read this blog post from Jeff Knupp and I think I understand how python's name-object binding works. My understand of DataFrames is that when I call df.loc[1,1] it generates a proxy object which points to the original DataFrame w/ the [1,1] window so that further operations (e.g. assignment) goes to only elements inside the window. Now when I pass that df.loc[1,1] through the function call, the function binds the name df_view to the proxy object. So in my theory, any change (i.e. df_view *= a) should be applied to the view and thus the elements in the original DataFrame. From the result, clearly that's not happening and it seems the DataFrame is copied in the process (I'm not sure where) because some values were changed outside the original DataFrame.
A: Just check
>>> type(df.loc[1, 1])
numpy.int64
So evidently this isn't going to work - you're passing in a single immutable int, which has no bind to the outer DataFrame.
Were you to pass in an actual view with simple indexing (mutable construct), it would most likely work.
>>> mult(df.loc[:, 1], 2)
>>> df
0 1
0 1 2
1 1 2
But some other ops will not work.
>>> mult(df.loc[:, :1], 2)
>>> df
0 1
0 1 2
1 1 2
All in all I think this control flow is a bad idea - a better option would be to operate directly on the index as you showed works. Pandas tends to be more friendly (IMHO) when you stick to immutability when possible.
A: The problem in in some case which is sometimes difficult to detect, copy of data are made.
You can get round the difficulty by indexing in the function :
def mult(df,i,j,a):
df.loc[i,j]*=a
mult(df,1,1,2)
mult(df,1,slice(0,2),6)
print(df)
for
0 1
0 1 1
1 6 12
| |
doc_4136
|
1.- The structure of the project
I have a brand new project folder by the name of card-generator-webpack. The structure of that folder is as follows:
__/ card-generator-webpack
|__/ src
| |__/ assets / img
| |__ favicon.jpeg
| |__ app.js
| |__ index.html
| |__ styles.css
|__ README.md
2.- Initializing WebPack
The first two commands which I run are npm init -y and npm install webpack webpack-cli --save-dev. I do so at the root of my project via Terminal. Once I've done it, the structure of my project looks like so:
__/ card-generator-webpack
|__/ (+) node_modules
|__/ src
| |__/ assets / img
| |__ favicon.jpeg
| |__ app.js
| |__ index.html
| |__ styles.css
|__ (+) package-lock.json
|__ (+) package.json
|__ README.md
Notice how new files and folders are depicted with a (+) at the beginning of its corresponding lines. Likewise, the removal of files and folders will be depicted with a (-) at the beginning of their corresponding lines.
3.- Meeting the first issue
Probably in a very naive fashion, I go to the package.json of my project and, under scripts, I add "build": "webpack" for this final result:
{
"name": "card-generator-webpack",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"webpack": "^5.75.0",
"webpack-cli": "^5.0.1"
}
}
But, after running npm run build, I get a quite long error as output on the Terminal. This is it:
ERROR in main
Module not found: Error: Can't resolve './src' in '/Users/AGLAYA/Local Sites/card-generator-webpack'
resolve './src' in '/Users/AGLAYA/Local Sites/card-generator-webpack'
using description file: /Users/AGLAYA/Local Sites/card-generator-webpack/package.json (relative path: .)
Field 'browser' doesn't contain a valid alias configuration
using description file: /Users/AGLAYA/Local Sites/card-generator-webpack/package.json (relative path: ./src)
no extension
Field 'browser' doesn't contain a valid alias configuration
/Users/AGLAYA/Local Sites/card-generator-webpack/src is not a file
.js
Field 'browser' doesn't contain a valid alias configuration
/Users/AGLAYA/Local Sites/card-generator-webpack/src.js doesn't exist
.json
Field 'browser' doesn't contain a valid alias configuration
/Users/AGLAYA/Local Sites/card-generator-webpack/src.json doesn't exist
.wasm
Field 'browser' doesn't contain a valid alias configuration
/Users/AGLAYA/Local Sites/card-generator-webpack/src.wasm doesn't exist
as directory
existing directory /Users/AGLAYA/Local Sites/card-generator-webpack/src
using description file: /Users/AGLAYA/Local Sites/card-generator-webpack/package.json (relative path: ./src)
using path: /Users/AGLAYA/Local Sites/card-generator-webpack/src/index
using description file: /Users/AGLAYA/Local Sites/card-generator-webpack/package.json (relative path: ./src/index)
no extension
Field 'browser' doesn't contain a valid alias configuration
/Users/AGLAYA/Local Sites/card-generator-webpack/src/index doesn't exist
.js
Field 'browser' doesn't contain a valid alias configuration
/Users/AGLAYA/Local Sites/card-generator-webpack/src/index.js doesn't exist
.json
Field 'browser' doesn't contain a valid alias configuration
/Users/AGLAYA/Local Sites/card-generator-webpack/src/index.json doesn't exist
.wasm
Field 'browser' doesn't contain a valid alias configuration
/Users/AGLAYA/Local Sites/card-generator-webpack/src/index.wasm doesn't exist
webpack 5.75.0 compiled with 1 error and 1 warning in 503 ms
Now, the only way that I've found to solve all of that in order to get WebPack to create the famous folder dist has been adding the path ./src/app.js to the "build": "webpack" that I've just added before, so that the line ends up reading like this:
"build": "webpack ./src/app.js"
And, finally, once I run npm run build, I do now get the folder dist, so that I my project's structure is now:
__/ card-generator-webpack
|__/ (+) dist
| |__ (+) main.js
|__/ node_modules
|__/ src
| |__/ assets / img
| |__ favicon.jpeg
| |__ app.js
| |__ index.html
| |__ styles.css
|__ package-lock.json
|__ package.json
|__ README.md
Thus - and to start with - my questions would be:
*
*What is that error yielded on the Terminal exactly saying?
*Why can't that error be solved by changing the "main": "index.js" to "main": "app.js", or to "main": "./src/app.js"?
*Why the only solution that I've found by myself implies adding an entry point to my "build" script?
*Is it logical to add an entry point to my "build"?
Finally, according with WebPack's documentation:
We also need to adjust our package.json file in order to make sure we mark our package as private, as well as removing the main entry. This is to prevent an accidental publish of your code.
So...
*Why does WebPack's documentation read that removing the main entry is necessary?
*What does WebPack's documentation mean with "accidental publish of your code"?
*Why could our code be published by accident and how does "private": true help to prevent this from happening?
*What if I want to willingly publish it? Should I erase or change this "private": true value?
A: For what it may be worth, and according to what I've kept on researching, the solution to the problem lies in the fact that Webpack
take[s] ./src/index.js as the default!
Source (have a look at this screenshot):
Webpack 4 : ERROR in Entry module not found: Error: Can't resolve './src'
So either the .js file that we want to use as the entry point is called index.js, and it's in the ./src/ path or things blow up.
Now, if we want the entry point to be different from the one taken by WebPack by default, we have two possible solutions:
First solution
Tweaking a bit our package.json, right where we define the script that usually gets the name of "build". In this case, what needs to be done is to add an entry point after the "webpack" value. That is, it should end up like this:
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack [entry point]"
},
Or, for example, if we were using the app.js file in the root of our document:
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack ./app.js"
},
Second solution
The second solution is to start by adding the configuration file webpack.config.js to the root of our project. Within, we'll need to add:
module.exports = {
entry: "./app.js",
};
And, for starters, that would solve the enormous error that I showed in the main message of this thread, as well as the first question, which was:
1. What is that error yielded on the Terminal saying?
So what the error is saying - please, correct me if I am wrong - is that there is no index.js file to resolve in the ./src/ path—or, said differently, that ./src/index.js doesn't exist.
I still can't find a concrete explanation for the second question. This is:
2. Why can't that error be solved by changing the "main": "index.js" to "main": "app.js" (or to "main": "./src/app.js") in our package.json?
The respective answers to the third and fourth questions are also already obvious. That is:
3. Why the only solution I've found by myself implies adding an entry point to my "build"?
The answer would be:
Because, indeed, it is one of the possible solutions.
And...
4. Is it logical to add an entry point to my "build"?
Well, I assume that it is logical because, once again, WebPack defaults to ./src/index.js as its entry point.
Now, regarding questions 5 and 6, my doubts remain, in case you are kind enough to find an answer to share.
Thanks!
| |
doc_4137
|
I tried to install and use the library for 3 time but I always had this problem.
No translation key or locale provided. Skipping translation...
I also followed the example that I found in the docs (multi-page) but the translation didn't work.
Could you please help me?
I attach the link of my repo. It's a little project that I just started. You can find the file in translation.js following the path src/lib/translation and the test in the file +about.svelte following the path src/routes/about.
Can somebody help me please?
I really don't want know how I can fix it. I did several research, but I couldn't find anything.
Thank you
| |
doc_4138
|
But when I try to do it, I get Portlet is temporarily unavailable error. I cannot see anything in the Tomcat's server console. Also when I use processAction() I don't get the error. I don't know what is wrong.
JSP:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1" isELIgnored="false"%>
<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
<portlet:actionURL var="signinAction" name="signinAction">
</portlet:actionURL>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login</title>
</head>
<body onload="load()" id="body1">
<form action="<%=signinAction.toString() %>" name="signinForm" method="post" onsubmit="return signin(this)">
<center>
<div class="div-upside-down" id="div-style">
<table width="95%">
<tr>
<td colspan="3"><p class="pp"></p>
</td>
</tr>
<tr>
<td id="td1">
<input type="text" id="email" name="email" placeholder="Email" />
<p id="one"></p>
</td>
<td id="td2">
<input type="password" id="password" name="password" placeholder="Password" />
<p id="one"></p>
</td>
<td id="td3">
<input type= "submit" name= "submit" value="Login"/>
<p id="one"></p>
</td>
</tr>
</table>
</div>
</center>
</form>
</html>
Portlet:
public class HelloWorldPortlet extends GenericPortlet {
ThemeDisplay td;
public void signinAction(ActionRequest actionRequest, ActionResponse actionResponse) throws PortletException, IOException{
long companyId=10154;
String email = actionRequest.getParameter("email");
String password = actionRequest.getParameter("password");
try
{
int authResult = 0;
long userId = 0;
Company company = PortalUtil.getCompany(actionRequest);
Map headerMap = new HashMap();
Map parameterMap = actionRequest.getParameterMap();
authResult = UserLocalServiceUtil.authenticateByEmailAddress(company.getCompanyId(), email, password,headerMap, parameterMap, null);
userId = UserLocalServiceUtil.getUserIdByEmailAddress(company.getCompanyId(), email);
User user = UserLocalServiceUtil.getUserByEmailAddress(companyId, email);
String screenId = user.getScreenName();
td = (ThemeDisplay) actionRequest.getAttribute(WebKeys.THEME_DISPLAY);
MethodKey key = new MethodKey("com.liferay.portlet.login.util.LoginUtil", "login", HttpServletRequest.class, HttpServletResponse.class, String.class, String.class, boolean.class, String.class);
PortalClassInvoker.invoke(false, key, new Object[] { PortalUtil.getHttpServletRequest(actionRequest), PortalUtil.getHttpServletResponse(actionResponse),screenId, password, true, CompanyConstants.AUTH_TYPE_SN});
actionResponse.sendRedirect(td.getPathMain());
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
Please Help.
A: Some issues that you have. The first, your actual question:
It seems your portlet is inheriting from javax.portlet.GenericPortlet. This means that you'll have to add @ProcessAction(name="signinAction") to your method's signature. If you don't want this annotation, you'll need to inherit from Liferay's MVCPortlet, which finds the method by reflection as you seem to expect it
Second issue with the code you present: Your jsp contains page-level HTML, e.g. <html>, <head> and <body>: A portlet must not contain this, as it will be rendered as part of the page and it's the portal's responsibility to add these items to the page (they will be added only once, no matter how many portlets you display)
Third: As a rule of thumbs, a portlet should not have member variables - in fact, having ThemeDisplay as a portlet class member will result in random failures later: There is typically only one portlet object that handles all the requests that the application gets. You must make ThemeDisplay a local variable instead of a member to avoid concurrency issues and random user data leaking into other user's request processing
| |
doc_4139
|
How do I get that file?
This is my app.json
{
"id": "ba7ba688-4dfe-4594-9870-2db44fec7321",
"name": "test",
"publisher": "Default publisher",
"brief": "",
"description": "",
"version": "1.0.0.0",
"privacyStatement": "",
"EULA": "",
"help": "",
"url": "",
"logo": "",
"capabilities": [],
"dependencies": [],
"screenshots": [],
"platform": "11.0.0.0",
"application": "11.0.0.0",
"idRange": {
"from": 50100,
"to": 50149
}
}
and this is my extension code:
pageextension 50100 CustomerListExt extends "Customer List"
{
layout {
addafter(Name) {
field(NameAgain;Name) {
CaptionML = ENU = 'Another name field';
}
}
}
}
A: You need to add the following property in your app.json:
"features": ["TranslationFile"]
| |
doc_4140
|
But when i start scrolling down and going back to the cell with YouTubePlayerSupportFragment the video goes black but i can still hear the audio playing.
Has anyone had the same problem and managed to solve it?
public void onBindViewHolder(ViewHolder holder) {
holder.youTubePlayerFragment.initialize("KEY",
new YouTubePlayer.OnInitializedListener() {
@Override
public void onInitializationSuccess(YouTubePlayer.Provider provider,
YouTubePlayer youTubePlayer, boolean b) {
youTubePlayer.cueVideo("ID");
youTubePlayer.play();
}
@Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
if (provider != null) {
}
}
});
}
A: u have to pause or stop the video when view is not visible to user like this:-
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (!isVisibleToUser) {
youTubePlayer.stop(); // or pause
}
}
A: So I managed to fix this by using onViewDetachedFromWindow and onViewAttachedToWindow functions of the adapter.
In onViewAttachedToWindow I add the YouTubePlayerSupportFragment and initialize the video and in onViewDetachedFromWindow i pause the video and remove the fragment.
This solved ths issue for me.
| |
doc_4141
|
public static List<Staff> ShowAll()
{
using (ModelPersonnelContainer myContainer = new
ModelPersonnelContainer())
{
return myContainer.Staff.ToList();
}
}
... and then in ButtonShowAll event handler in WebForm1:
protected void ButtonShowAll_Click(object sender, EventArgs e)
{
GridViewAll.DataSource = ClassMyBase.ShowAll();
GridViewAll.DataBind();
}
So far so good, BUT if I add filtering to my public static List<Staff> ShowAll():
public static xyz ShowAll()
{
using (ModelPersonnelContainer myContainer = new
ModelPersonnelContainer())
{
selectedRrows=from item in myContainer.Staff
select new
{
Name=item.Name,
Email=item.Email
}
}
}
my method won’t work because the return data type is no more same as previously. Any easy solutions? What could this return data type xyz be?
If I put everything together (no separate class in my project) and have only ButtonShowAll it will work all right, so like this:
protected void ButtonShowAll_Click(object sender, EventArgs e)
{
using (ModelPersonnelContainer myContainer = new
ModelPersonnelContainer())
{
var selectedRows = from item in myContainer.Staff
select new
{
Name=item.Name,
Email=item.Email
};
GridView1.DataSource = selectedRows.ToList();
GridView1.DataBind();
}
A: This part of your code creates an anonymous class:
new
{
Name=item.Name,
Email=item.Email
}
You should name it explicitly, then that class name will be used, and you can type your return type:
new Staff()
{
Name=item.Name,
Email=item.Email
}
Additionally, you might want to use ToList(), or change your return type to IEnumerable<Staff>, since the LINQ query will not return a List<Staff>:
var selectedRows = ...
.ToList();
| |
doc_4142
|
Please, if you can - help me deal with my problem.
I have this structure in my html code(ng-controller is on wrap tag):
<a ng-repeat="subitem in cur_submenu" ng-href="#/{{subitem.href}}/">{{subitem.name}}</a>
In JS I have:
1) RouteProvider
$routeProvider.
when('/:lvl1', {
template:'<div ng-include="htmlUrl">Loading...</div>',
controller: 'MainCtrl'
})
2) Controller
function MainCtrl($scope, $http, $routeParams){
var lvl = window.location.hash.split('/');
if ($scope.submenu) {
//if data was fetch earlier, then set currentMenu
$scope.cur_submenu = $scope.submenu[lvl[1]];
} else {
MainCtrl.prototype.fetchData();
}
MainCtrl.prototype = {
fetchData: function(){
/*
* Get data about navigation
*/
$http({method: 'GET', url: 'data/main.json'}).
success(function(data){
$scope.menu = data.menu;
$scope.submenu = data.submenu;
$scope.cur_submenu = data.submenu[lvl[1]] //current submenu for my location
});
}
}
But it is not updating on my page, when I changed my location on a website(hash-nav)... Please help my. Full version of my site: http://amiu.ru
A: You don't need to add a function to your Controller with prototyping. Functions called in your view are to be declared on the $scope like so:
function MainCtrl($scope, $http, $routeParams){
var lvl = window.location.hash.split('/');
if ($scope.submenu) {
//if data was fetch earlier, then set currentMenu
$scope.cur_submenu = $scope.submenu[lvl[1]];
} else {
$scope.fetchData();
}
$scope.fetchData = function(){
/*
* Get data about navigation
*/
$http({method: 'GET', url: 'data/main.json'}).
success(function(data){
$scope.menu = data.menu;
$scope.submenu = data.submenu;
$scope.cur_submenu = data.submenu[lvl[1]] //current submenu for my location
});
};
}
In all other cases, if you're executing changes on a $scope outside of a $scope function, you'll need to manually call $scope.$apply() to queue a digest and update your view.
| |
doc_4143
|
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class TestClass
{
public static void main(String[] args) throws InterruptedException
{
WebDriver driver=new FirefoxDriver();
Thread.sleep(2000);
driver.get("http://docs.sencha.com/extjs/4.2.1/extjs-build/examples/form/dynamic.html");
Thread.sleep(2000);
WebElement element=driver.findElement(By.xpath(".//input[@name='first']"));
Thread.sleep(2000);
element.sendKeys("");
element.sendKeys(Keys.TAB);
Thread.sleep(2000);
System.out.println("'"+element.getCssValue("border-color")+"'");
}
}
Webdriver version 2.33 (Java binding)
FF 22
A:
How to get border color or other css values look in Computed there are all values that you can get:
getCssValue("border-bottom-color")
returns rgba(209, 219, 223, 1) and need to clear it (this will work for rgba and rgb):
String rgb[] = driver.findElement(By.name("login[email]")).getCssValue("border-bottom-color").replaceAll("(rgba)|(rgb)|(\\()|(\\s)|(\\))","").split(",");
Now our rgb is in array using this method to parse it
String hex = String.format("#%s%s%s", toBrowserHexValue(Integer.parseInt(rgb[0])), toBrowserHexValue(Integer.parseInt(rgb[1])), toBrowserHexValue(Integer.parseInt(rgb[2])));
private static String toBrowserHexValue(int number) {
StringBuilder builder = new StringBuilder(Integer.toHexString(number & 0xff));
while (builder.length() < 2) {
builder.append("0");
}
return builder.toString().toUpperCase();
}
From this rgba(209, 219, 223, 1) we got this #D1DBDF
P.S. Source of parsing int rgb to hex
A: There seems to be an issue with element.getCssValue("border-color") using a Firefox Driver. This is due to Shorthand CSS properties (e.g. margin, background, border) not been supported.
For Firefox you will need to enter
System.out.println("'"+element.getCssValue("border-top-color")+"'");
The code will print out 'rgba(207, 76, 53, 1)'
Using a ChromeDriver to get your value.
Your current code will print out 'rgb(207, 76, 53)'
To set the ChromeDriver you might need to add this line before you declare your driver
System.setProperty("webdriver.chrome.driver", "/path/to/chromedriver.exe");
WebDriver driver=new ChromeDriver();
You can download the ChromeDriver from here http://chromedriver.storage.googleapis.com/index.html
| |
doc_4144
|
Example
can this be done with CSS or java?
A: This can be pretty easily accomplished by creating an absolutely positioned overflow-hidden wrapper, and adding a spin animation to an element inside the wrapper.
.spinner {
position: absolute;
bottom: 0;
left: 50%;
transform: translateX(-50%);
overflow: hidden;
height: calc(50vw / 2);
}
.spinner img {
animation: spin 5s linear infinite;
width: 50vw;
border-radius: 100%;
}
@keyframes spin {
from {transform:rotate(0deg);}
to {transform:rotate(360deg);}
}
<div class="spinner">
<img src="https://picsum.photos/200">
</div>
| |
doc_4145
|
php artisan make:model ModelName
it creates Model file inside app folder. When we specify namespace like
php artisan make:model SomeFolder/ModelName
it creates Model file inside app/SomeFolder/ModelName.
I wanted to create model files outside of app folder. How to achieve this?
A: I don't see the reason, but I managed to make it on my local computer by php artisan make:model ../../mOdel . Probably in production environment you won't be allowed to do this.
A: Yes you can achieve this via below steps:
1) Change psr-4 value for 'App' into composer.json file
2) Run composer dump-autoload command for load composer
3) Run command for manually created model php artisan make:model yourfoldername/model
NOTE: Make sure, whenever you create model using command you need to change namespace.
| |
doc_4146
|
CSS
div#cardwrap {
border:3px purple solid;
float:left;
position: relative;
left:50%;
}
div#centermaster {
text-align:center;
border:1px yellow solid;
float:left;
position: relative;
left:-50%;
}
div.cardtable {
float:left;
padding:35px;
border:1px green solid;
}
HTML
<div id=cardwrap>
<div id=centermaster>
<div class=cardtable>Images</div> (variable number)
...
</div>
</div>
This would work perfectly, except that I can't seem to get the wrapper to shrinkwrap correctly. Before the images load, it looks fine initially - the yellow wrapper is centering the green divs. But as the images load, the green divs wrap to the next line, which I do want. But then, a gap appears on the right so that the yellow div is no longer shrinkwrapping, and thus, not centering, them. How can I maintain the yellow div matching the width of however many green divs can fit on a row?
Another method to equalize div heights while centering them is also welcome.
(Also are there scripts to equalize widths of certain div class, given variable content?) Basically, the end goal is center the green divs into a table-like format, while accommodating for both variable screen sizes and content.
A: Not sure what exactly do you want, but I think, that you need inline-blocks here, like this: http://jsfiddle.net/TSpXZ/
To make them work in IE, add the following in the Conditional Comments:
div.cardtable {
display:inline;
zoom:1;
}
And try to experiment more with inline-blocks — they are awesome!
| |
doc_4147
|
return (interfaceOrientation == UIInterfaceOrientationLandscapeRight || interfaceOrientation == UIInterfaceOrientationLandscapeLeft);
But then also my app tries to load in Portrait mode first and in the procedure the screen looks stretching. Am I missing something? Please suggest. Any help will be appreciated
Thanks,
Christy
A: You say the code above is in -(void)willRotateToOrientation when it should be placed in -(BOOL)shouldRotateToOrientation.
Assuming that is a typo, set the supported orientations in the Info.plist file to LandscapeRight and LandscapeLeft.
A: Just to make sure Christina's fix in the comments to the other answer doesn't go missed:
application.statusBarOrientation = UIInterfaceOrientationLandscapeRight
I added this in the didFinishLaunching app delegate function and it seems to force a view controller refresh which in my case ensured the OpenGL frame buffer was created in the correct dimensions, bizarre that I have to add this though.
| |
doc_4148
|
One problem area that I can for sure identify (though not the source of the slowness) is the field _globals. I do not want to create a new instance of that class each time an operation is called, but this approach is not thread safe at all.
Any insights into how to improve the performance (if it can be done) and any recommendations for making it thread safe would be much appreciated!
public class Globals<TLhs, TRhs>
{
public TLhs Lhs;
public TRhs Rhs;
}
public struct Vector3
{
private static VectorScripts<Vector3> Scripts { get; } = new VectorScripts<Vector3>(new[] {"X", "Y", "Z"});
public float X;
public float Y;
public float Z;
public Vector3(float x, float y, float z)
{
X = x;
Y = y;
Z = z;
}
public static Vector3 operator *(Vector3 lhs, Vector3 rhs) => Scripts.Multiply(lhs, rhs).Result;
}
public class VectorScripts<TVector>
{
private readonly ScriptRunner<TVector> _multiply;
private readonly Globals<TVector, TVector> _globals;
public VectorScripts(IEnumerable<string> components)
{
_multiply = CSharpScript.Create<TVector>(Operation("*", components), globalsType: typeof(Globals<TVector, TVector>)).CreateDelegate();
_globals = new Globals<TVector, TVector>();
}
public async Task<TVector> Multiply(TVector lhs, TVector rhs)
{
_globals.Lhs = lhs;
_globals.Rhs = rhs;
return await _multiply.Invoke(_globals);
}
private static string Operation(string operation, IEnumerable<string> components)
{
return string.Join("\n", components.Select(component => $"Lhs.{component}{operation}=Rhs.{component};"));
}
}
| |
doc_4149
|
Tested old entity in Common Project: Posology entity (fields: unit, nuberperintake)
Entity in new Project: PatientMedication(fields: drugId, patientId)
PatientMedication may have multiple Posologies for a patient in different time.
I could add one field(column) 'PatientMedicationId' into Posology to have this many-to-one
relation. But the thing is that it will change the entity in Common project and make it dependent on the new project.
So I am thinking that maybe I should use many-to-many to have this relation without introduce this dependency.
Is it a good solution? Is there any other idea?
Thanks in advance.
A: use many to many - and include the date range.
this will be the most flexible solution in the long run.
edit:
example_link_table
----------------------
id_1
id_2
begin_date
end_date
this way, you can indicate when that relationship was valid.
| |
doc_4150
|
if (isGPSEnabled) {
if (locatTeste == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if (locationManager != null) {
locatTeste = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
}
}
but sometimes it gives me an out-of-date location... How can i get the up-to-date location?
A: What you are doing at requestLocationUpdate() is asking the system to start the GPS and give you back the location, but keep in mind that this call is asynchronic, meaning you will not get the location at the next line but only when it will be ready. That is the reason you sometimes might get not up to date locations (you might not even get location at all).
You need to choose what method you want to use, the first one - requestLocationUpdate() will register the class you are using to location updates and will get the location in asyncrhonic time when it's ready.
The second method - getLastKnownLocation() will return the last location the system has. that's do work in synchronic way but some times might not be updated.
What I would do is first try the second method, check the quality of the location, if it's not up to date use the first method to receive one.
something like that:
if (isGPSEnabled && locationManager != null) {
Location l = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (checkIfLocationIsUpdated(l)){
useLocation(l);
}
else{
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
}
}
@override
public void onLocationChanged(Location l){
useLocation(l);
}
EDIT:
private boolean checkIfLocationIsUpdated(Location l){
long maxInterval = 60*1000; //1 minute
float maxAccuracy = 30; //30 meter.
if (System.currentTimeMillis - l.getTime() < maxInterval && l.getAccuracy < maxAccuracy){
return true;
}
else{
return false;
}
}
A: This is expected.
You are using the function getLastKnownLocation(...) and the application is returning what it has in memory. As per the documentation this could be out of date.
Instead use requestLocationUpdates(...) and pass in the parameters you what on how frequently or under what circumstances you want your Location to update.
Read about Androids Location Manager completely to understand the functions available to you.
| |
doc_4151
|
A: There is a separate module called Oracle GoldenGate for BigData. It supports many NoSQL replication targets.
One of the supported BigData databases is also Apache Cassandra.
There is a separate manual explaining how to use it.
There is no separate module that allows you to connect Apache Cassandra as the source of your replication. If you need such replication you need to provide some intermediate step. The source of replication for Oracle GoldenGate can only be a database (Oracle, TimesTen, DB2, Informix, MySQL, MS SQL Server, NonStop SQL/MX, SAP/Sybase ASE, Teradata) or a JMS queue.
| |
doc_4152
|
I want to ask if there are any ideas to do this more perfectly and good from UI perspective.
A: As I undrestood right, it would be better to create client-side object which will build your menu. Input parameter for this object is a JSON with your data. If you need to make any modifications with your GUI, you will change only js/css objects without rebuilding all project.
I hope it will also helps you
Getting The List Of All Pages In The Application.
Please, clarify your issue if my answer isn't right.
| |
doc_4153
|
Is there any way to ignore some of the source properties ?
Any help is humbly appreciated. Thanks
A: Use the copyProperties(...) method from BeanUtilsBean instead, its much better designed. Alternatively you can take a look at Dozer.
| |
doc_4154
|
The menubar and tools are missing like in the following image.
I'm on Kubuntu14.04. I tried installing via different methods and version of python. Same for any browsers. No warnings when launching notebook.
Someone have the same problem on windows (here).
If you have any ideas.
Thank you.
A: Fixed removing ipython and major part of Jupyter traces and reinstalling everything from anaconda.
| |
doc_4155
|
May i check how can i clean my data throughly using big query SQL ?
I have an issue whereby i dont seems to be able to clean my data throughly
Im using
WITH d_group AS(
SELECT
list.group_method AS list_method,
list.group_method_detailed AS list_detailed
FROM table_a AS list
),
d_trim AS (
SELECT
LOWER(TRIM(list_method)) AS modified_group_method
LOWER(TRIM(list_detailed)) AS modified_group_method_detailed
LOWER(TRIM(IFNULL(d_group.list_detailed,d_group.list_method)) AS modified_detailed,
FROM d_group
),
d_detailed AS (
SELECT
modified_group_method,
modified_group_method_detailed,
modified_detailed
CASE
WHEN modified_detailed LIKE '%apple' THEN 'fruits'
ELSE 'Others'
END AS fruits_grouping
FROM d_trim
-- WHERE modified_group_method LIKE '%other' #incorrect here
WHERE modified_group_method LIKE 'other'
),
d_method AS (
SELECT
modified_group_method,
modified_group_method_detailed,
modified_detailed,
CASE
WHEN modified_group_method LIKE '%apple' THEN 'fruits'
ELSE 'Others'
END AS fruits_grouping
FROM d_trim
-- WHERE modified_group_method <> '%other' #Incorrect here ..
WHERE modified_group_method <> 'other'
),
all_table AS (
SELECT
d_method.modified_group_method AS group_method ,
d_method.modified_group_method_detailed AS group_method_detailed,
d_method.change_detailed AS modified_detailed,
d_method.payment_mode
FROM d_method
UNION ALL
SELECT
d_detailed.modified_group_method AS group_method ,
d_detailed.modified_group_method_detailed AS group_method_detailed,
d_detailed.change_detailed AS modified_detailed,
d_detailed.payment_mode
FROM d_detailed
)
SELECT
DISTINCT
list_method,
list_method_detailed,
modified_detailed,
fruits_grouping
FROM all_table
ORDER BY
modified_detailed
However there are still "invisible" space which is affecting my CASE WHEN function
My output result is giving me
group_method
group_detailed
modified_detailed
fruits_grouping
other.
apple.
apple.
fruits
other.
apple.
apple.
Others
apple.
apple.
apple.
fruits
First & Last line result is correct but 2nd line is wrong . I do want to reflect fruits instead of others
I tried various way , export the data into google sheet and try using functions like
TRIM with LOWER . But still there seems to be "invisible" spacing which is affecting my CASE WHEN statement
Is there anything that im missing out here ?
| |
doc_4156
|
Any ideas? I would like to only use CSS if it's possible.
Note that when clicked the button, the element 2 goes off or on and the others move's, I want that movement animated.
Here is my code
$('button').click(function(){
element = $('#dos').is(":visible");
if(!element){
$('#dos').show();
}
else{$('#dos').hide();}
})
section{
margin:auto;
display:block;
text-align:center;
}
#uno{
width:200px;
background:rgba(255,229,0,1.00);
height:100px;
display:inline-block;
}
#dos{
width:200px;
background:rgba(0,255,60,1.00);
height:100px;
display:inline-block;
}
#tres{
width:200px;
background:rgba(232,0,255,1.00);
height:100px;
display:inline-block;
}
button{
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<section>
<div id="uno">1</div>
<div id="dos">2</div>
<div id="tres">3</div><br>
<button>Click</button>
</section>
A: If you want it to be done in CSS, then work with .addClass()/.removeClass() instead of .show() and .hide(). Learn about keyframes – it's easy, intuitive and gives full control over CSS animations. It's as easy as:
@keyframes hide-animation {
to {
width: 0%;
visibility: hidden;
}
}
.hidden {
animation: hide-animation .3s linear forwards;
}
You can bind any animation you want to the class you are adding. Here's your JSFiddle with working hide animation.
A: It's hard for me to give an exact answer without knowing what kind of movement you want but I'll take a stab at it.
One general solution is to put the element you are hiding/showing in a container div, and then animate the width or height of the container div. Let me see if I can give you an example for vertical:
HTML:
<div id="uno">1</div>
<div id="dos-container">
<div id="dos">2</div>
</div>
<div id="tres">3</div>
CSS:
#uno{
height:100px;
}
#dos{
height:100px;
}
#dos-container{ /* same height as dos if starting visible, if starting hidden set to 0*/
height:100px;
}
#tres{
height:100px;
}
JS(with jquery):
$('button').click(function(){
element = $('#dos').is(":visible");
if(!element){
//animate container height to match content div height
$('#dos-container').animate({height: "100px")},500); //500 is the speed of the animation
//show content in container
$('#dos').show();
}
else{
//animate container height to 0
$('#dos-container').animate({height: "0px")},500);
//then hide content div
$('#dos').hide();
}
})
| |
doc_4157
|
The sequence of operations is:
*
*Goto desired directory
*Run program on the first input file
*Goto to relative path where the results are generated
*Rename and copy the file (program generates with same name) in a desired directory
*Goto Step 2 and continue the rest of the steps with the next file
I am aware that I can use the import subprocess and use subprocess.call() to run the Windows shell commands. How do I effect all these steps in an efficient way ?
Any tips will be helpful.
Thanks & Regards,
santosh
A: From what you described I imagine something like this should work.
Just change the paths and names.
import os
import shutil
files = [r"C:\Path\To\File1", r"C:\Path\To\File2"]
new_names = ["new_file1", "new_file2"]
def x(file, new_name):
program_path = r"C:\Path\To\Program"
save_path = r"C:\Path\To\Save"
new_path = r"C:\NewPath\To\Folder"
os.system("%s -argument %s" % (program_path, file))
shutil.move(save_path, new_path + '/' + new_name)
y = 0
for file_ in files:
x(file_, new_names[y])
y += 1
Try to provide what you have done so far so you can get a better answer.
| |
doc_4158
|
When I push to my repository, all looks ok , but after execute karma start --single-run, the console of the travis don't stop to execute the karma start task.
How to fix this?
.travis.yml
language: node_js
sudo: false
node_js:
- 0.10
script: karma start -–single-run
before_install:
- export DISPLAY=:99.0
- sh -e /etc/init.d/xvfb start
before_script:
- npm install -g bower
- npm install
- bower install
Travis Console
Updated Question :
Why in the travis process when i use in the console karma start --single-run the option no overwrite the option singleRun: false in the karma.conf.js? In my local environment this works fine.
A: Finally I solved, the problem was in my karma.conf.js
singleRun: true,
I change this option from false to true. Frequently when i develop, use singleRun option in my karma configuration file to false for use auto watch option.
The weird thing it's that in my local machine when i run karma with the option explicity in the command line (karma start --single-run), the option in the karma.conf.js is overwritten, but in travis this it's not posible.
| |
doc_4159
|
A: In htaccess just change this and problem solved
RewriteEngine on
RewriteCond %{HTTP_HOST} ^www.example.com [NC]
RewriteRule ^(.*)$ http://example.com/$1 [L,R=301,NC]
| |
doc_4160
|
A: Based on the usecase specified, you may use Preferences class in HarmonyOS (ohos.data.preferences.Preferences) to save the color integer that was recently selected by the user when there is a configuration change like rotation of the screen or device language change.
*
*Use
preferences.putInt(key, value);
to store the value before the dialog is going to be destroyed.
*Use
preferences.getInt(key, DEFAULT_VALUE);
to retrieve the value when the dialog is recreated after being destroyed due to configuration change.
For more information, please refer the documentation
| |
doc_4161
|
When I upload a file, its default permissions are 600 and I can't view the file unless I manually change it to 774 or 775.
So, I'd like to change the default permissions of all files that I upload to /var/www/ to 754.
I know that chmod -R 754 /var/www makes all files within that directory to 774 but it doesn't change the default permissions of all new files that are uploaded.
My user is 'joe' for demo purpose since I'm learning, so I even tried chown -R joe /var/www but that didn't change the default permissions either.
How do I change it default permissions from 600 to 774? In which file should I write and what?
A: You should use umask. More info here: http://www.cyberciti.biz/tips/understanding-linux-unix-umask-value-usage.html
A: You must change the umask of the user(s) writing to the directory. And BTW do NOT set execute permissions when they are not needed.
A umask is a negative mask of permissions which should be applied. By default, all files would be created with 666 and all directories with 777. With a umask of 002, which seems to be what you want, these become 664 and 775.
Now, how to set the umask depends on the program which actually writes the file, and whether this setting is available in its configuration file.
Another, less known way, would be to set POSIX ACLs to the upload directory: for this, you can use setfacl with the -d option on /var/www (provided your OS, and filesystem, support it both).
A: One of your comments suggests you are uploading the files through proftpd. If this is the case, then your question is really specific to that piece of software. The answer is not to go modifying /etc/profile, as that is going to change the default umask for all users that use Bourne Shell or similar (i.e. Bash). Furthermore, a user must actually log into the shell for /etc/profile to be read, and on a properly configured system, the user your daemon is running as does not actually log in. Check http://www.proftpd.org/docs/howto/Umask.html for information specific to proftpd and umasks.
| |
doc_4162
|
BasicIndexing belongsTo Applicant
Applicant hasMany Request
As such I would like to retreive the BasicIndexing model and contain the Applicant Model and an applicants corresponding request as shown in the code below
$fullCondition = array(
'contain' => array(
'Applicant' => array(
'Request',
'fields'=>array('Applicant.surname','Applicant.first_name','Applicant.id')
)
),
'conditions' => $conditions,
'fields'=>array('BasicIndexing.application_date','BasicIndexing.application_number')
);
$this->loadModel('BasicIndexing');
$searchResult = $this->BasicIndexing->find('all',$fullCondition);
The problem is that the result returned into $searchResult does not contain the Request model at all. It only contains the Applicant model and ignores the Request model. I tried using a model that is not associated with Applicant and i get the warning that the model is not associated to the Applicant model.
Array
(
[0] => Array
(
[BasicIndexing] => Array
(
[application_date] => 2012-04-17
[application_number] => BIA170420124356
)
[Applicant] => Array
(
[surname] => Kermit
[first_name] => Frog
[id] => 4f8d3b63-c2bc-48a1-9fb5-0290c982293d
)
)
)
Is there anything im doing wrong or there is a problem with the cake 1.3.0 release?
Any help would be highly appreciated.
Thanks.
A: I think it's because of your fields array. You either need to add Request.* to the existing fields array or add a fields array to Request
So it should look like one of two examples below:
$fullCondition = array(
'contain' => array(
'Applicant' => array(
'fields'=>array('Applicant.surname','Applicant.first_name','Applicant.id'),
'Request' => array(
'fields' => array('*')
)
)
),
'conditions' => $conditions,
'fields'=>array('BasicIndexing.application_date','BasicIndexing.application_number')
);
$fullCondition = array(
'contain' => array(
'Applicant' => array(
'fields'=>array('Applicant.surname','Applicant.first_name','Applicant.id', 'Request.*'),
'Request'
)
),
'conditions' => $conditions,
'fields'=>array('BasicIndexing.application_date','BasicIndexing.application_number')
);
A: I just had the same problem. Basically, contain is erratic and would return the results of an associated 'belongsTo' relationship, but not the ones of an 'hasMany'. I only needed one level of recursion, and it turns out that '1' is a special thing for recursive declaration (along with -1 and 0). So my only way to get the data I wanted was to use the clunky 'recursive' declaration, but to set it to an unnecessary high '2'.
I know it's an old question, but I just spent a whole day struggling with this, I hope to spare that to some other poor schmuck stuck with that obsolete version of cake out there..
| |
doc_4163
|
Ultimately this means I will be able to build a scoreboard on my site. I am hoping to create two functions in my site, one which will retrieve the scores and one which will post new scores. I believe in order to achieve this I will need to use PHP to retrieve and post data however I am a little unsure where to start.
If anyone could provide me with some pointers I would be grateful as I am not particularly familiar with MySQL databases or PHP. I did find this guide on connecting to MySQL database from 123reg.co.uk however I am struggling.
Thanks,
Simon
A: The tutorial that you mentioned is outdated, relies on mysql_connect that was deprecated in PHP 5.5.0 and removed on PHP 7.0.0. Find a more up to date tutorial that uses mysqli or PDO.
Also you will need to learn some security concerns, I really recommend you to study a bit before doing this, since you can have serious problems if implement a insecure script to do this.
There are great PHP Frameworks that implement all of this in a secure and easy way, try searching for Laravel Framework. Isn't for begginers, but with a little knowlegend of PHP Object-oriented and MySQL (or any SQL supported by Laravel) you can do what you want.
There are also a nice site to learn Laravel, called Laracasts with very nice screen-casts teaching Laravel (for begginers or not).
| |
doc_4164
|
A: You'll definitely need to have server-side code, though you can probably use Cloud Functions for that.
That said, it doesn't look like there's a Plaid Link Android SDK so you may have to send your Android users to a web UI for adding their ACH details.
| |
doc_4165
|
But in my form Im hiding input fields with query depending on a radion button.
My problem is that hidden input fields are required for submitting the form. How can I skip this. I dont want to validate the hidden inputs.
Error: https://www.screencast.com/t/ObpmoXfGE9
A: When you are hiding form inputs based on radio button value, at that time remove the required attribute from those inputs.
In this way the hidden inputs won't get validated.
$("#hidden_input_id").removeAttr("required");
Hope this helps!
From your fiddle I understood that you need to remove required attribute from hidden inputs. suppose if elevator is visible then you need to remove required attributes from category and ground-area inputs.
Just do it in the following way--
$(document).ready(function(){
$("input[name='type']").change(function() {
$("#elevator").toggle(this.value == "ETW");
$("#category :input").removeAttr("required");
$("#ground_area :input").removeAttr("required");
});
$(document).ready(function() {
$("input[name='type']").change(function() {
$("#elevator").toggle(this.value == "ETW");
$("#category :input").removeAttr("required");
$("#ground_area :input").removeAttr("required");
});
$("input[name='type']").change(function() {
$("#category").toggle(this.value == "EFH" || this.value == "ZFH");
});
$("input[name='type']").change(function() {
$("#ground_area").toggle(this.value == "EFH" || this.value == "ZFH");
});
});
<div class="form-group">
<label>Objektadresse</label>
<input type="text" placeholder="Straße" class="form-control" name="street" required>
</div>
<div class="form-group">
<input type="text" placeholder="Hausnummer" class="form-control" name="house_number" required>
</div>
<div class="form-group">
<input type="text" placeholder="PLZ" class="form-control" name="zip" required>
</div>
<div class="form-group">
<input type="text" placeholder="Stadt" class="form-control" name="town" required>
</div>
<div class="form-group" id="type">
<label>Was möchten Sie bewerten?</label>
<div class="radio">
<label>
<input type="radio" id="type1" name="type" value="ETW" required>Eigentumswohnung</label>
</div>
<div class="radio">
<label>
<input type="radio" id="type2" name="type" value="EFH" required>Einfamilienhaus</label>
</div>
<div class="radio">
<label>
<input type="radio" id="type3" name="type" value="ZFH" required>Mehrfamilienhaus</label>
</div>
</div>
<div id="category" class="form-group" style="display:none;">
<label>Um welche Kategorie handelt es sich?</label>
<div class="radio">
<label>
<input type="radio" name="category" value="FREISTEHEND" required>Freistehend</label>
</div>
<div class="radio">
<label>
<input type="radio" name="category" value="DOPPELHAUS" required>Doppelhaushälfte</label>
</div>
<div class="radio">
<label>
<input type="radio" name="category" value="REIHENMITTELHAUS" required>Reihenmittelhaus</label>
</div>
<div class="radio">
<label>
<input type="radio" name="category" value="REIHENENDHAUS" required>Reihenendhaus</label>
</div>
</div>
<div class="form-group">
<label>Wann wurde das Objekt gebaut?</label>
<input type="text" placeholder="Baujahr" class="form-control" name="year" required>
</div>
<div class="form-group">
<label>Wie groß ist die Wohnfläche</label>
<input type="text" placeholder="Wohnfläche" class="form-control" name="living_area" required>
</div>
<div id="ground_area" class="form-group" style="display:none;">
<label>Wie groß ist das Grundstück</label>
<input type="text" placeholder="Grundstücksgröße" class="form-control" name="ground_area" required>
</div>
<div class="form-group" id="elevator" style="display:none;">
<label>Besitz die Wohnung einen Aufzug?</label>
<div class="radio">
<label>
<input id="elevator1" type="radio" name="elevator" value="true" required>Ja</label>
</div>
<div class="radio">
<label>
<input id="elevator2" type="radio" name="elevator" value="false" required>Nein</label>
</div>
</div>
<div class="form-group">
<label>Besitz das Objekt eine Garage?</label>
<div class="radio">
<label>
<input type="radio" name="garages" value="true" required>Ja</label>
</div>
<div class="radio">
<label>
<input type="radio" name="garages" value="false" required>Nein</label>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
UPDATED fiddle
note: wrap everything inside $(document).ready function.
| |
doc_4166
|
Is it possible to call this method from an angular application using a standard http.get and open the returned view in a separate window?
A: Yes. Use target="_blank" for new window
<a href="https://your/requested/mvc/endpoint" target="_blank">go here</a>
And in href use requested endpoint.
| |
doc_4167
|
Example:
public class A extends B implements Serializable {
private String employeeId;
private String employeeName;
}
public class B extends C implements Serializable {
private String address;
private String countryIsoCode;
private Boolean isMapped;
}
public class C implements Serializable {
private String empRefNo;
private ***Boolean exist***;
}
Here class "B" and "C" has "Boolean" type parameter added in the POJO. I have mapped all the String parameters in my mapper class and didn't map "Boolean" parameters. But when I invoke my mapper class to map the request parameters, after mapping, my request has "exist" parameter [Boolean type] also added without doing any mapping. But in some cases, "isMapped" parameter which is also of type "Boolean" is not been added in the request. When I change the data type of the "exist" parameter to "String", it is not getting added to the request after the mapper class invocation.
Mapstruct automatically adds the "Boolean" type parameter in request from class "C" without mapping. Can someone please help me with this, Thanks!
| |
doc_4168
|
A: Here is the best way I have found to accomplish this. You can call a function on another script like so:
script a.scpt
set myScript to load script "b.scpt"
set foo to myScript's theTest()
script b.scpt
on theTest()
return true
end theTest
As you can see you can call functions within b.scpt from a.scpt by calling the function name myScript's theTest().
A: You can put all the handlers and scripts that you want to reference inside a Script Library (for example: my_math_lib.scpt and my_string_lib.scpt). Then, save this file in a Script Libraries folder on your computer.
Depending on how you want to define the availability of this library, you use a different folder:
*
*Place the my_math_lib.scpt and my_string_lib.scpt files inside the /Library/Script Libraries folder to make them available for all users on the computer.
*Place them in the ~/Library/Script Libraries folder to make them available for a specific user only.
You can then use all the handlers in those libraries as follows:
property math_lib : script "my_math_lib"
property string_lib : script "my_string_lib"
math_lib's do_this()
string_lib's do_that()
| |
doc_4169
|
This works for me with this method:
current_user.flats.delete(Flat.find(7))
When I try to do a similar thing on the rails console, it destroys the whole object in the database:
irb(main):018:0> current_user.houses.delete(House.find(10))
SQL (13.4ms) DELETE FROM "cities_houses" WHERE "cities_houses"."city_id" = ? [["city_id", 10]]
SQL (0.8ms) DELETE FROM "houses" WHERE "houses"."id" = ? [["id", 10]]
As you can see, it removes the whole house object from it's own table.
What makes even less sense: It tries to remove an entry on the join table "cities_houses" using the given house_id (10) as parameter for the city_id to remove the element?
I don't get in general why it tries to update this join table. My command had nothing to do with it...
I'm using Rails version: 5.1.1 and Ruby version: 2.4.1 (x86_64-linux)
A: I found a solution to solve the problem!
This doesn't work, when dependent: :destroy is enabled.
current_user.houses.delete(House.find(10))
The solution is pretty obvious: for a has_many/belongs_to-association, you can just update the value user_id of the flat to nil. I knew this way, but what I've tried first didn't worked:
House.find(10).user_id = nil
House.find(10).save
The updated value will be changed and the change is immediately forgotten, if it is not stored in a variable.
This works:
house = House.find(10)
house.user_id = nil
house.save
Another solution, without loading the house model first:
House.where(id: 10).update_all(user_id: nil)
| |
doc_4170
|
#include <QtMultimedia/QAbstractVideoSurface>
#include <QtMultimedia/QVideoFrame>
according to this question, QtMultimediaKit must be installed. However, the location of headers differ, and code that passes looks like:
#include <QtMultimediaKit/QAbstractVideoSurface>
#include <QtMultimediaKit/QVideoFrame>
It is admittedly a minor difference, but it prevents me from interchangeably compiling in Windows and ubuntu. My guess is, i should use some form of macro expression, in lines of:
#ifdef WIN_MACRO
#include <QtMultimedia/QAbstractVideoSurface>
#include <QtMultimedia/QVideoFrame>
#else
#include <QtMultimediaKit/QAbstractVideoSurface>
#include <QtMultimediaKit/QVideoFrame>
#endif
to make the code compile on both systems. If that is correct, what should the macro be? If not - how can the problem be solved?
A: There is a macro in the Qt libraries that should help you. Try:
#ifdef Q_OS_WIN
| |
doc_4171
|
type Mutation{
createUser(username: String!, email: String!, tempPassword: String!): ComplexCallResult
@aws_iam
}
I am using AmazoneWebServicesClient to execute queries. For query which is already defined in the schema, I gave input in the post request body as below
private String queryAllUsers = "{\n" +
" \"query\": \"{listUsers {name}}\",\n" +
" \"variables\": null,\n" +
" \"operationsName\": null\n" +
"}";
Now I want to run mutation similar to above. My input query was
{
"mutation":"{createUser(email: "test@lb.de", tempPassword: "LPwd!", username: "testUser1") { Exception Success}}"
}
In Java code:
private String testCreateUserInputQuery= "{\n" +
" \"mutation\":\"{createUser(email: \\\"test@lb.de\\\", tempPassword: \\\"LPwd!\\\", username: \\\"testUser10\\\") { Exception Success}}\"\n" +
"}";
But this is not working. Any leads please
Edit: I am updating what I have done here:
This is my latest try which is not working.
private String testCreateUserInputQuery= "{\n" +
" \"query\":\"{mutation($username:String!,$email:String!,$tempPassword:String!) {createUser(username:$username,email:$email,tempPassword:$tempPassword) { Exception Success }}}\", \"variables\":{\"input\":{\"username\":\"testUser11\",\"email\":\"test@lb.de\",\"tempPassword\":\"L123!\" } }\n" +
" }";
Tried like this too:
private String testCreateUserInputQuery= "{\n" +
" \"query\":\"{mutation createUser($username:String!,$email:String!,$tempPassword:String!) {createUser(username:$username,email:$email,tempPassword:$tempPassword) { Exception Success }}}\", \"variables\":{\"input\":{\"username\":\"testUser11\",\"email\":\"test@lb.de\",\"tempPassword\":\"L123!\" } }\n" +
" }";
I am getting exception as below
{"errors":[{"message":"Unable to parse GraphQL query.","errorType":"MalformedHttpRequestException"}]} (Service: appsync; Status Code: 400; Error Code: MalformedHttpRequestException; Request ID: af42c6eb-dd5f-401e-9cac-530e9c62df71; Proxy: null)
Not able to find what is the mistake and no clue. I am exhausted with my search.
Not able to use Postman or Insomnia to try this API as it is my organization's work and the API is secured by AWS IAM. I am yet to be given credentials to test this in the Postman or Insomnia. I can test it only through code.
A: private String testCreateUserInputQuery=" {\n" +
" \"query\":\"mutation { createUser(username: \\\"testUser12\\\",email:\\\"test@lb.de\\\",tempPassword:\\\"tempPassword123!\\\") { Exception Success }}\"\n" +
" }";
For query using variables, the following one works for me
private String testCreateUserInputQuery= "{\n" + " \"query\":\"mutation User($uname: String!,$mail:String!,$tempPwd:String!) { createUser(username: $uname,email:$mail,tempPassword:$tempPwd) { Exception Success }}\", \"variables\":{\"uname\":\"testUser20SK\",\"mail\":\"test@lb.de\",\"tempPwd\":\"LPassword123!\"} \n" + " }";
A: I had to struggle unnecessarily to do this operation. Insomnia tool is automatically converting the GraphQL query to JSON query. Copy and paste or write your GraphQL query, keeping the input mode format as GraphQL. After you are done with that, select JSON. Your GraphQL query will be converted automatically to the JSON query format.
Thanks to the help provided in the video: https://youtu.be/AaD03fv6q-o. Just for the people who need help as I got.
| |
doc_4172
|
I learnt that this can be done by making a post request to the asp.net page with the appropriate parameters.
So in curl,
*
*I make a get request / just use file_get_contents to retrieve the initial page.
*From this, I extract the values for __VIEWSTATE and __EVENTVALIDATION.
So far everything seems ok.
Now, I understand that we need to make a post request using cURL with __VIEWSTATE and other parameters required. ( values for the fields present in the asp.net form )
I am unable to construct the CURLOPT_POSTFIELDS correctly.
For instance, I am trying this out,
$postoptions1='__EVENTTARGET='.('ctl00$ContentPlaceHolder1$gRef').'&__EVENTARGUMENT='.('$2');
$postoptions2 = '&__VIEWSTATE='.urlencode($viewState) ;
$otherparams = '&ctl00$ContentPlaceHolder1$ddlName=Abc';
And before using setopt for CURLOPT_POSTFIELDS, I am doing,
urlencode ($postoptions1.$postoptions2.$otherparams)
This does not work. The submit results are not shown, which means, the required parameter __VIEWSTATE was not found in my post request.
If I change the order of the parameters and place __VIEWSTATE as the first parameter, the results page is shown but the other parameter values are not honoured.
I think there is some problem with the way I am encoding the parameters.
Please tell me how to construct the parameters for the post request to a asp.net page.
Thanks.
--Edited--
Here is the complete code:
$resultsPerPage='10';
$url = "www.example.com"; // url changed
$curl_connection = curl_init($url);
function sendCurl($curl_connection,$url,$params,$isPost=false) {
//$post_string = $params;
$post_string = http_build_query($params);
//$post_string = build_query_string($params);
//$post_string = urlencode($params);
echo 'After Encode'.$post_string;
$cookie="/cookie.txt";
//set options
curl_setopt($curl_connection, CURLOPT_CONNECTTIMEOUT, 300);
curl_setopt($curl_connection, CURLOPT_USERAGENT,
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)");
curl_setopt($curl_connection, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl_connection, CURLOPT_HEADER, 0); // don't return headers
curl_setopt($curl_connection, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl_connection, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curl_connection,CURLOPT_REFERER, $url);
if($isPost) {
curl_setopt ($curl_connection, CURLOPT_POST, true);
//set data to be posted
curl_setopt($curl_connection, CURLOPT_POSTFIELDS, $post_string);
curl_setopt($curl_connection,CURLOPT_COOKIEJAR,$cookie);
}
else {
curl_setopt($curl_connection,CURLOPT_COOKIEFILE,$cookie);
}
$response1 = curl_exec($curl_connection);
if($response1 === false)
{
echo 'Curl error: ' . curl_error($curl_connection);
}
else
{
echo 'Operation completed without any errors';
}
return $response1;
} **// First time, get request to asp.net page
$response1 = sendCurl($curl_connection,$url,'',false);
$viewState=getVStateContent($response1);
$eventValidation =getEventValidationContent($response1);
$simpleParams = '&__VIEWSTATE='.$viewState.'&ctl00$ContentPlaceHolder1$ddlManuf=&ctl00$ContentPlaceHolder1$ddlCrossType=&ctl00$ContentPlaceHolder1$ddlPageSize='.$resultsPerPage.'&ctl00$ContentPlaceHolder1$btnSearch=Search&ctl00_ToolkitScriptManager1_HiddenField=&__EVENTTARGET=&__EVENTARGUMENT=';
// Second post - for submitting the search form
$response2= sendCurl($curl_connection,$url,$simpleParams,true);
----**
A: What you want is http_build_query, which will format an array as proper HTTP parameters.
Edit: To clarify what this should probably look like:
$params = array(
'__EVENTTARGET' => 'ctl00$ContentPlaceHolder1$gRef',
'__EVENTARGUMENT' => '$2',
'__VIEWSTATE' => $viewState,
'ctl00$ContentPlaceHolder1$ddlName' => 'Abc'
);
curl_setopt($curlHandler, CURLOPT_POSTFIELDS, http_build_query($params));
Also, what's ctl00$ContentPlaceHolder1$ddlName supposed to be?
A: Don't urlencode() the ampersands (&) linking the parameters together, just the keys & values (the stuff on either side of the ampersands).
| |
doc_4173
|
src/
module1.py
module2.py
test_module1.py
test_module2.py
subpackage1/
__init__.py
moduleA.py
moduleB.py
test_moduleA.py
test_moduleB.py
Where the module*.py files contains the source code and the test_module*.py contains the TestCases for the relevant module.
With the following comands I can run the tests contained in a single file, for example:
$ cd src
$ nosetests test_filesystem.py
..................
----------------------------------------------------------------------
Ran 18 tests in 0.390s
OK
How can I run all tests? I tried with nosetests -m 'test_.*' but it doesn't work.
$cd src
$ nosetests -m 'test_.*'
----------------------------------------------------------------------
Ran 0 tests in 0.000s
OK
Thanks
A: If they all begin with test then just nosetest should work. Nose automatically searches for any files beginning with 'test'.
A: I don't know about nosetests, but you can achieve that with the standard unittest module. You just need to create a test_all.py file under your root directory, then import all your test modules. In your case:
import unittest
import test_module1
import test_module2
import subpackage1
if __name__ == "__main__":
allsuites = unittest.TestSuite([test_module1.suite(), \
test_module2.suite(), \
subpackage1.test_moduleA.suite(), \
subpackage1.test_moduleB.suite()])
each module should provide the following function (example with a module with two unit tests: Class1 and Class2):
def suite():
""" This defines all the tests of a module"""
suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(Class1))
suite.addTest(unittest.makeSuite(Class2))
return suite
if __name__ == '__main__':
unittest.TextTestRunner(verbosity=2).run(suite())
A: This is probably a hotly-contested topic, but I would suggest that you separate your tests out from your modules. Set up something like this...
Use setup.py to install these into the system path (or you may be able to modify environment variables to avoid the need for an "install" step).
foo/
module1.py
module2.py
subpackage1/
__init__.py
moduleA.py
moduleB.py
Now any python script anywhere can access those modules, instead of depending on finding them in the local directory. Put your tests all off to the side like this:
tests/
test_module1.py
test_module2.py
test_subpackage1_moduleA,py
test_subpackage2_moduleB.py
I'm not sure about your nosetests command, but now that your tests are all in the same directory, it becomes much easier to write a wrapper script that simply imports all of the other tests in the same directory. Or if that's not possible, you can at least get away with a simple bash loop that gets your test files one by one:
#!/bin/bash
cd tests/
for TEST_SCRIPT in test_*.py ; do
nosetests -m $TEST_SCRIPT
done
A: Whether you seperate or mix tests and modules is probably a matter of taste, although I would strongly advocate for keeping them apart (setup reasons, code stats etc).
When you're using nosetests, make sure that all directories with tests are real packages:
src/
module1.py
module2.py
subpackage1/
__init__.py
moduleA.py
moduleB.py
tests/
__init__.py
test_module1.py
test_module2.py
subpackage1/
__init__.py
test_moduleA.py
test_moduleB.py
This way, you can just run nosetests in the toplevel directory and all tests will be found. You need to make sure that src/ is on the PYTHONPATH, however, otherwise all the tests will fail due to missing imports.
A: I'll give a Testoob answer.
Running tests in a single file is like Nose:
testoob test_foo.py
To run tests in many files you can create suites with the Testoob collectors (in each subpackage)
# src/subpackage?/__init__.py
def suite():
import testoob
return testoob.collecting.collect_from_files("test_*.py")
and
# src/alltests.py
test_modules = [
'subpackage1.suite',
'subpackage2.suite',
]
def suite():
import unittest
return unittest.TestLoader().loadTestsFromNames(test_modules)
if __name__ == "__main__":
import testoob
testoob.main(defaultTest="suite")
I haven't tried your specific scenario.
| |
doc_4174
|
2021-04-13 15:31:59
2021-04-13 15:29:59
2021-04-12 15:31:59
2021-04-12 15:29:59
2021-04-10 15:31:59
2021-04-10 15:29:59
2021-04-8 15:31:59
2021-04-8 15:29:59
I want to select the last 3 days data available in table
In above example it is 2021-04-10 , 2021-04-12 and 2021-04-13
I tried something like below
SELECT * FROM `table` WHERE DATE(`timer`) >= DATE(NOW()) - INTERVAL 3 DAY
But its returning data from 2021-04-12 , since there is no data available from 2021-04-11.
A: In MariaDB 10.2.32 you can use DENSE_RANK() window function:
SELECT *
FROM (
SELECT *, DENSE_RANK() OVER (ORDER BY DATE(timer) DESC) rnk
FROM tablename
) t
WHERE rnk <= 3
See a simplified demo.
| |
doc_4175
|
The app setup is react + redux + react-router-redux + redux-saga + immutable + auth0-lock.
Beginning at the top, the App component defines the basic page layout, both Builder and Editor components require the user to be logged in, and authenticated() wraps each in a Higher Order Component responsible for handling authentication.
// index.js
import App from './containers/App';
import Builder from './containers/Builder';
import Editor from './containers/Editor';
import Home from './containers/Home';
import Login from './containers/Login';
import AuthContainer from './containers/Auth0/AuthContainer';
...
ReactDOM.render(
<Provider store={reduxStore}>
<Router history={syncedHistory}>
<Route path={'/'} component={App}>
<IndexRoute component={Home} />
<Route path={'login'} component={Login} />
<Route component={AuthContainer}>
<Route path={'builder'} component={Builder} />
<Route path={'editor'} component={Editor} />
</Route>
</Route>
<Redirect from={'*'} to={'/'} />
</Router>
</Provider>,
document.getElementById('app')
);
At the moment, AuthContainer doesn't do much except check the redux store for isLoggedIn. If isLoggedIn is false, the user is not allowed to view the component, and is redirected to /login.
// containers/Auth0/AuthContainer.js
import React from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { redirectToLogin } from './Auth0Actions';
class AuthContainer extends React.Component {
componentWillMount() {
if (!this.props.isLoggedIn) {
this.props.actions.redirectToLogin();
}
}
render() {
if (!this.props.isLoggedIn) {
return null;
}
return this.props.children;
}
}
// mapStateToProps(), mapDispatchToProps()
export default connect(mapStateToProps, mapDispatchToProps)(AuthContainer);
The next piece is Auth0. The Auth0 Lock works in "redirect" mode, which means the user will leave the app to log in, and then be redirected back to the app at /login. As part of the redirect, Auth0 attaches a token as part of the URL, which needs to be parsed when the app loads.
const lock = new Auth0Lock(__AUTH0_CLIENT_ID__, __AUTH0_DOMAIN__, {
auth: {
redirect: true,
redirectUrl: `${window.location.origin}/login`,
responseType: 'token'
}
});
Since Auth0 will redirect to /login, the Login component also needs authentication logic. Similar to AuthContainer, it checks the redux store for isLoggedIn. If isLoggedIn is true, it redirects to the root /. If isLoggedIn is false, it'll attempt to authenticate.
// containers/Login/index.js
import React from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { authenticate, redirectToRoot } from '../Auth0/Auth0Actions';
class Login extends React.Component {
componentDidMount() {
if (!this.props.isLoggedIn) {
this.props.actions.authenticate();
}
else {
this.props.actions.redirectToRoot();
}
}
render() {
return (
<div>Login Page</div>
);
}
}
// mapStateToProps(), mapDispatchToProps()
export default connect(mapStateToProps, mapDispatchToProps)(Login);
With these pieces in place, my integration with Auth0 seems to be working. However, I now have AuthContainer and Login component, and they are very similar. I can't place the Login component as a child to AuthContainer since the login page does not actually require the user to be logged in.
Ideally, all authentication logic lives in one place, but I'm struggling to figure out another way to get it working, especially with the special case of the Auth0 redirect. I can't help but think that there must be a different approach, a better pattern for authentication flow in a react + redux app.
One thing that would be helpful is to better understand how to dispatch an async action on page load, before the app starts initializing. Since Auth0 works with callbacks, I'm forced to delay setting the redux initial state until after Auth0 invokes the registered callback. What is the recommended way to handle async actions on page load?
I've left out some pieces for brevity, like the actions and sagas, but I'll be more than happy to provide those if it'll be helpful.
A: May not be a complete answer, so sorry for that. Few things to address here:
Ideally, all authentication logic lives in one place
I'm not so sure this is ideal, depending on what you mean by "one place". There's noting wrong with having two functions that are similar but are different enough in some aspect that warrants a little repetition. From what I can see your code the logic is indeed slightly different so two components seems perfectly fine.
Instead of componentDidMount, use Route's onEnter prop
Putting your auth logic after component mounting will likely cause a flicker of your authenticated html showing before the auth logic can run. Conceptually, you would like to prevent rendering this component at all until the auth logic has run. Route's onEnter is perfect for this. https://github.com/ReactTraining/react-router/blob/master/docs/API.md#onenternextstate-replace-callback
let authenticate = (nextState, replace) => {
// check store details here, if not logged in, redirect
}
<Route path={'builder'} onEnter={authenticate} component={Builder} />
how to dispatch an async action on page load, before the app starts initializing
This is quite a common question for React Apps / SPAs. I think the best possible user experience is to display something right away, perhaps a loading spinner or something that says "Fetching user details" or whatnot. You can do this in your top level App container or even before your first call to ReactDOM.render
ReactDOM.render(<SplashLoader />, element)
authCall().then(data =>
ReactDOM.render(<App data={data} />, element)
).catch(err =>
ReactDOM.render(<Login />, element)
}
A: I'm doing the same thing in my project and working fine with redux, react-router, just have a look at my code below:
routes:
export default (
<div>
<Route path="/" component={AuthenticatedComponent}>
<Route path="user" component={User} />
<Route path="user/:id" component={UserDetail} />
</Route>
<Route path="/" component={notAuthenticatedComponent}>
<Route path="register" component={RegisterView} />
<Route path="login" component={LoginView} />
</Route>
</div>
);
AuthenticatedComponent:
export class AuthenticatedComponent extends React.Component {
constructor( props ) {
super( props );
}
componentWillMount() {
this.props.checkAuth().then( data => {
if ( data ) {
this.props.loginUserSuccess( data );
} else {
browserHistory.push( '/login' );
}
} );
}
render() {
return (
<div>
{ this.props.isAuthenticated && <div> { this.props.children } </div> }
</div>
);
}
}
notAuthenticatedComponent:
export class notAuthenticatedComponent extends React.Component {
constructor(props){
super(props);
}
componentWillMount(){
this.props.checkAuth().then((data) => {
if(data && (this.props.location.pathname == 'login')){
browserHistory.push('/home');
}
});
}
render(){
return (
<div>
{ this.props.children }
</div>
);
}
}
A: If you are following the Thanh Nguyen's answer use React's "Constructor" instead of "componentWillMount". As its the recommended way according to the docs.
| |
doc_4176
|
*
*The GCP project is setup and the Visibility is set to "My Domain"
*In the Chrome Web Store the project status is "Published" and "GAM: Published"
*In the Chrome Web Store the visibility option is set to Private -> Everyone at [domain]
I've received no errors and it's been 12 hours since publishing and the guide says it should be a few minutes to an hour.
In our domains admin panel I then goto Apps -> + -> Expand the Hamburger -> "[Domain] Apps" where domain-wide add-ons are found but there's no add-on listed.
I'm not sure what to try next. Any help?
A: Based from this thread, it could be a bug in the publishing system of the Apps Marketplace.
In that case you'd need to report it. There is a category for: Public Trackers > G Suite Developers > G Suite Marketplace in the issue tracker. https://issuetracker.google.com
A: Between 3 and 4 days the project finally appeared in the domain app section of the GAM.
I'm assuming this was a bug since I also published a 2nd test project 2 days after the first project which also didn't show up in the domain app section of the GAM but both the 1st and 2nd projects showed up (seemingly at the same time) in the GAM between 3 and 4 days after I published the 1st project.
| |
doc_4177
|
40 $key = file_get_contents(KEY_FILE);
41 $client->setAssertionCredentials(new Google_AssertionCredentials(
42 SERVICE_ACCOUNT_NAME,
43 array('https://www.googleapis.com/auth/devstorage.full_control'),
44 $key)
45 );
46
47 $client->setClientId(CLIENT_ID);
48 $service = new Google_StorageService($client);
49 $buckets = $service->buckets;
50 $bucketObj = new Google_Bucket();
51
52 $time = time();
53 $b_name = "test_bucket_"."$time";
54 $bucketObj->setName($b_name);
55 // $response = $buckets->insert('test_project-0001',$bucketObj);
56 $response = $buckets->listBuckets('test_project-0001');
57 $tokenStr = $client->getAccessToken();
58 print "Token String : $tokenStr\n";
59 $token = '';
60 if(preg_match('/access_token\":\"(.*.)\",/', $tokenStr, $matches)) {
61 print "Tken $matches[1] \n";
62 $token = $matches[1];
63 }
64
65
66 $req = new Google_HttpRequest("https://www.googleapis.com/upload/storage/v1beta2/b/test_project-0001_test_bucket_1/o?uploadType=resumable&name=song");
67 $req->setRequestHeaders(array(
68 'Authorization:' => "$token",
69 'X-Upload-Content-Length:' => '4509237'));
74 $req->setRequestMethod('POST');
75 // $req->setPostBody($e_body);
76
77 var_dump($req);
78 $gRest = new Google_REST();
79 $response = $gRest->execute($req);
80 var_dump($response);
81
82 ?>
This gives me the following output
{
"error": {
"errors": [{
"domain": "global",
"reason": "authError",
"message": "Invalid Credentials",
"locationType": "header",
"location": "Authorization"
}],
"code": 401,
"message": "Invalid Credentials"
}
}
Could anyone give me some pointers on what I'm doing wrong?
A: I figured it out. Turns out I need to send an authenticated request like this:
63 $req->setRequestHeaders(array(
65 'X-Upload-Content-Length:' => '4509237'));
(notice there's no Authentication parameter in the array)
77 $gcIO = new Google_CurlIO();
78 $response = $gcIO->authenticatedRequest($req);
79 $resp_uri = $response->getResponseHeader('location');
And that's that
| |
doc_4178
|
I want to fetch a number of records by the key attribute and fail if any are missing. The key attribute is unique.
keys = %w(apple pear grape)
fruits = Fruit.where(key: keys)
This could return between 0 and 3 records.
I want this to fail unless 3 records are returned.
Is it possible to do this within ActiveRecord or do I need to check the size of the returned collection as such:
fruits = Fruit.where(key: keys).tap { |fruits| raise(...) unless fruits.size == keys.size }
A: The where method is designed to mirror SQL's where clause, so it will not fail if no matching records are found. It'll just return an empty relation.
After you have filtered your records, raise an error if the size of the returned relation is not equal to what you're looking for. You need to do this before looping through any returned records
keys = %w(apple pear grape)
fruits = Fruit.where(key: keys)
raise 'my special error' unless fruits.size == keys.length
# loop here
| |
doc_4179
|
<ImageView
android:id="@+id/img"
android:layout_width="340dip"
android:layout_height="240dip"
android:layout_marginBottom="60dip"/>
I am setting an img.setimageresource(R.drawable.apple);
Now what I need is I have a i value which is incrementing in onclick of a button as soon as i value is incremented, image should be displayed and its is displaying. Again when i value is incremented it should display the same image just below the 1st image and so on...
A: Make another xml having Imageview only. and remove this Imageview from parent xml. Now use inflater to inflate the imageview xml and add this view in parent xml's layout.
EDIT:
First make two layouts, parent and child. Parent layout has only on linearlayout(vertical) and child layout has only one ImageView. Now Use an Inflater like this:
LayoutInflater inflater = (LayoutInflater)getSystemServices(Context.Layout_InflaterService);
Make a view of child layout like this:
View view = inflater.inflate(R.layout.child,null);
Add this view to parent xml's layout.
layout.add(view);
Hope its clear now.
| |
doc_4180
|
['andrew', 'finance', 'tea', 'juice'],
['bob', 'finance', 'coffee', 'water'],
['charlie', 'sales', 'tea', 'water']
];
I want to return an array that looks like:
arr2 = [
['andrew', 'tea'],
['bob', 'coffee'],
['charlie', 'tea']
];
I have variables for the elements I want to map, like this:
var name = 0;
var drink = 2;
How do I correctly map, I was expecting something like this:
let arr2 = arr.map(function(obj) {
return
[
obj[name],
obj[drink]
]
});
A:
var name = 0;
var drink = 2;
const arr = [
['andrew', 'finance', 'tea', 'juice'],
['bob', 'finance', 'coffee', 'water'],
['charlie', 'sales', 'tea', 'water']
];
const arr2 = arr.map(e => [e[name], e[drink]]);
console.log(arr2);
A: Try this:
var name = 0
var drink = 2
arr.map(elem => [elem[name], elem[drink]]) //?
| |
doc_4181
|
It would be a one-shot operation, we don't need something automated.
I know that:
*
*a bucket name may not be available anymore if one day we want to restore it
*there's an indexing overhead of about 40kb per file which makes it a not so cost-efficient solution for small files and better to use an Infrequent access storage class or to zip the content
I gave it a try and created a vault. But I couldn't run the aws glacier command. I get some SSL error which is apparently related to a Python library, wether I run it on my Mac or from some dedicated container.
Also, it seems that it's a pain to use the Glacier API directly (and to keep the right file information), and that it's simpler to use it via a dedicated bucket.
What about that? Is there something to do what I want in AWS? Or any advice to do it in a not too fastidious way? What tool would you recommend?
A: Whoa, so many questions!
There are two ways to use Amazon Glacier:
*
*Create a Lifecycle Policy on an Amazon S3 bucket to archive data to Glacier. The objects will still appear to be in S3, including their security, size, metadata, etc. However, their contents are stored in Glacier. Data stored in Glacier via this method must be restored back to S3 to access the contents.
*Send data directly to Amazon Glacier via the AWS API. Data sent this way must be restored via the API.
Amazon Glacier charges for storage volumes, plus per request. It is less-efficient to store many, small files in Glacier. Instead, it is recommended to create archives (eg zip files) that make fewer, larger files. This can make it harder to retrieve specific files.
If you are going to use Glacier directly, it is much easier to use a utility, such as Cloudberry Backup, however these utilities are designed to backup from a computer to Glacier. They probably won't backup S3 to Glacier.
If data is already in Amazon S3, the simplest option is to create a lifecycle policy. You can then use the S3 management console and standard S3 tools to access and restore the data.
A: Using a S3 archiving bucket did the job.
Here is how I proceeded:
First, I created a S3 bucket called mycompany-archive, with a lifecycle rule that turns the Storage class into Glacier 1 day after the file creation.
Then, (with the aws tool installed on my Mac) I ran the following aws command to obtain the buckets list: aws s3 ls
I then pasted the output into an editor that can do regexp relacements, and I did the following one:
Replace ^\S*\s\S*\s(.*)$ by aws s3 cp --recursive s3://$1 s3://mycompany-archive/$1 && \
It gave me a big command, from which I removed the trailing && \ at the end, and the lines corresponding the buckets I didn't want to copy (mainly mycompany-archive had to be removed from there), and I had what I needed to do the transfers.
That command could be executed directly, but I prefer to run such commands using the screen util, to make sure the process wouldn't stop if I close my session by accident.
To launch it, I ran screen, launched the command, and then pressed CTRL+A then D to detach it. I can then come back to it by running screen -r.
Finally, under MacOS, I ran cafeinate to make sure the computer wouldn't sleep before it's over. To run it, issued ps|grep aws to locate the process id of the command. And then caffeinate -w 31299 (the process id) to ensure my Mac wouldn't allow sleep before the process is done.
It did the job (well, it's still running), I have now a bucket containing a folder for each archived bucket. Next step will be to remove the undesired S3 buckets.
Of course this way of doing could be improved in many ways, mainly by turning everything into a fault-tolerant replayable script. In this case, I have to be pragmatic and thinking about how to improve it would take far more time for almost no gain.
| |
doc_4182
|
However, there is no output of the picture
Version is 5.3.0
!pip install -U Pillow==5.3.0
from PIL import Image
print(PIL.PILLOW_VERSION)
im= Image.new("RGB", (128, 128), "#FF0000")
im.show()
edit: changing "im.show()" to "im" does the trick. It works now
| |
doc_4183
|
The problem is that the message queue id for the second queue somehow gets changed right after the msgrcv call for the first queue.
Please consider the simplified version (for demo purposes) of my server-process below:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#define SERVER_KEY_PATHNAME "/student/m18512/m1851201/mqueue_server_key"
#define USERS_KEY_PATHNAME "/student/m18512/m1851201/labs"
#define PROJECT_ID 'M'
#define PROJECT_ID_U 'U'
#define QUEUE_PERMISSIONS 0660
struct buffer {
int qid_a;
char message_text [200];
char dest_user[30];
};
struct message {
long mtype;
struct buffer buffer;
};
struct buffer_user {
char source_user [30];
long qid_source_user;
};
struct message_user {
long mtype;
struct buffer_user buffer_user;
};
int main (int argc, char **argv)
{
setvbuf(stdout, NULL, _IONBF, 0);
key_t queue_a_key, queue_b_queue;
int qid_a, qid_b;
struct message message;
struct msqid_ds buf;
//Create queue A
if ((queue_a_key = ftok (SERVER_KEY_PATHNAME, PROJECT_ID)) == -1) {
perror ("ftok");
exit (1);
}
if ((qid_a = msgget (queue_a_key, IPC_CREAT | QUEUE_PERMISSIONS)) == -1) {
perror ("msgget");
exit (1);
}
//Create queue B
if ((queue_b_queue = ftok (USERS_KEY_PATHNAME, PROJECT_ID_U)) == -1) {
perror ("ftok");
exit (1);
}
if ((qid_b = msgget (queue_b_queue, IPC_CREAT | QUEUE_PERMISSIONS)) == -1) {
perror ("msgget");
exit (1);
}
while (1) {
printf("Step 1: qid A: %d\n", qid_a);
printf("Step 1: qid B: %d\n", qid_b);
// read an incoming message
if (msgrcv (qid_a, &message, 300, 0, 0) == -1) {
perror ("msgrcv");
exit (1);
}
printf("Step 2: qid A: %d\n", qid_a);
printf("Step 2: qid B: %d\n", qid_b);
}
}
As it can be seen from the output, once the client process sends a message to queue A, the id for the queue B is changed:
Step 1: qid A: 1674706969
Step 1: qid B: 1679229087
Step 2: qid A: 1674706969
Step 2: qid B: 1679229013
The original id for queue B is 1679229087 (step 1), but at the step 2, the id for this queue becomes 1679229013.
Moreover, looking at ipcs, I don't see a queue with the new id 1679229013, but 1679229087 still exists.
Please see below also the simplified code for the client process:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#define SERVER_KEY_PATHNAME "/student/m18512/m1851201/mqueue_server_key"
#define USERS_KEY_PATHNAME "/student/m18512/m1851201/labs"
#define PROJECT_ID 'M'
#define PROJECT_ID_U 'U'
struct buffer {
int qid;
char message_text [200];
char dest_user[30];
};
struct message {
long mtype;
struct buffer buffer;
};
struct buffer_user {
char source_user [30];
long qid_source_user;
};
struct message_user {
long mtype;
struct buffer_user buffer_user;
};
int main (int argc, char **argv)
{
setvbuf(stdout, NULL, _IONBF, 0);
struct message my_message, return_message;
my_message.mtype = 1;
key_t server_queue_key, users_queue_key;
int server_qid, myqid, users_qid;
// create my client queue for receiving messages from server
if ((myqid = msgget (IPC_PRIVATE, 0660)) == -1) {
perror ("msgget: myqid");
exit (1);
}
if ((server_queue_key = ftok (SERVER_KEY_PATHNAME, PROJECT_ID)) == -1) {
perror ("ftok");
exit (1);
}
if ((server_qid = msgget (server_queue_key, 0)) == -1) {
perror ("msgget: server_qid");
exit (1);
}
my_message.buffer.qid = myqid;
printf("Server qid %d, my qid %d\n", server_qid, myqid);
printf ("Please type a message: ");
while (fgets (my_message.buffer.message_text, 198, stdin)) {
// remove newline from string
int length = strlen (my_message.buffer.message_text);
if (my_message.buffer.message_text [length - 1] == '\n')
my_message.buffer.message_text [length - 1] = '\0';
// send message to server
if (msgsnd (server_qid, &my_message, sizeof (my_message) + 1, 0) == -1) {
perror ("client: msgsnd");
exit (1);
}
}
exit (0);
}
EDIT:
It appears that the problem exists when I declare queue ids like this:
int qid_a, qid_b;
However, when I declare them like this:
int qid_a = 0, qid_b = 0
The problem disappears. Why can that be?
| |
doc_4184
|
item
event
sales
1
A
130
1
B
156
1
C
108
2
B
150
2
D
118
...
...
...
In this data frame, event A is first in time, then B, then C and so forth.
I now want an average per item-id combination through time.
This means that for item 1 event A, the average is simply 130. For item 1 and event B, the average should be (130+156)/2 = 143. But for item 2, event B, the average is 150 and for item 2 and event D, the average is (130+118)/2 = 124.
So the outcome should look like this:
item
event
sales
1
A
130
1
B
143
1
C
131.33
2
B
150
2
D
124
...
...
...
Is this possible without a loop? Can we do this with a group by somehow?
Thanks in advance!
A: Use Expanding.mean with Series.reset_index for remove first level of MultiIndex for correct align to new column:
df['new'] = df.groupby('item')['sales'].expanding().mean().reset_index(level=0, drop=True)
print (df)
item event sales new
0 1 A 130 130.000000
1 1 B 156 143.000000
2 1 C 108 131.333333
3 2 B 150 150.000000
4 2 D 118 134.000000
| |
doc_4185
|
{Notes: "test", Ids: [606, 603]}
this.http.post(url, {"Notes": "test", "Ids": [606,603]}, options)
I'm attempting to deserialize this into a .net Dictionary like:
[HttpPost]
public IHttpActionResult Test(Dictionary<string,string> formData)
{
}
(I've tried to add the [FromBody] decorator too).
If I don't include the array, this works fine. But with the array, I get a couple of parse error:
Unexpected character encountered while parsing value: [. Path 'Ids', line 1, position 23.
Invalid JavaScript property identifier character: ]. Path 'Ids', line 1, position 30.
A: The "JSON" you're posting is not valid JSON - you can use a tool like JSONLint to validate your JSON.
The correct JSON syntax for your data is:
{
"Notes": "test",
"Ids": [606, 603]
}
Also - the method takes a Dictionary<string,string> object. Your array is not a string, and the controller will therefore fail while trying to deserialize the array into a string.
My suggestion is to create a model, which the controller method should receive. Like this:
[HttpPost]
public IHttpActionResult Test(YourModel data)
{
}
class YourModel
{
public string Notes {get;set;}
public int[] Ids {get;set;}
}
Using this code, the controller will deserialize your JSON (when you have corrected the JSON syntax problems) into an instance of YourModel.
| |
doc_4186
|
(defn rt []
(let [tns 'my.namespace-test]
(use tns :reload-all)
(cojure.test/test-ns tns)))
And everytime I make a change I rerun the tests:
user=>(rt)
That been working moderately well for me. When I remove a test, I have to restart the REPL and redefine the method which is a little annoying. Also I've heard bad rumblings about using the use function like this. So my questions are:
*
*Is using use this way going to cause me a problem down the line?
*Is there a more idiomatic workflow than what I'm currently doing?
A: I am so far impressed with lein-midje
$ lein midje :autotest
Starts a clojure process watching src and test files, reloads the associated namespaces and runs the tests relevant to the changed file (tracking dependencies). I use it with VimShell to open a split buffer in vim and have both the source and the test file open as well. I write a change to either one and the (relevant) tests are executed in the split pane.
A: most people run
lein test
form a different terminal. Which guarantees that what is in the files is what is tested not what is in your memory. Using reload-all can lead to false passes if you have changed a function name and are still calling the old name somewhere.
*
*calling use like that is not a problem in it's self, it just constrains you to not have any name conflicts if you use more namespaces in your tests. So long as you have one, it's ok.
*using lein lets you specify unit and integration tests and easily run them in groups using the test-selectors feature.
A: I also run tests in my REPL. I like doing this because I have more control over the tests and it's faster due to the JVM already running. However, like you said, it's easy to get in trouble. In order to clean things up, I suggest taking a look at tools.namespace.
In particular, you can use clojure.tools.namespace.repl/refresh to reload files that have changed in your live REPL. There's alsorefresh-all to reload all the files on the classpath.
I add tools.namespace to my :dev profile in my ~/.lein/profiles.clj so that I have it there for every project. Then when you run lein repl, it will be included on the classpath, but it wont leak into your project's proper dependencies.
Another thing I'll do when I'm working on a test is to require it into my REPL and run it manually. A test is just a no-argument function, so you can invoke them as such.
| |
doc_4187
|
@Test
public void testNestedTheorems() {
String source = "\\begin{theorem}" +
"this is the outer theorem" +
"\\begin{theorem}" +
"this is the inner theorem" +
"\\end{theorem}" +
"\\end{theorem}";
LatexTheoremProofExtractor extractor = new LatexTheoremProofExtractor(source);
extractor.parse();
ArrayList<String> theorems = extractor.getTheorems();
assertNotNull(theorems);
assertEquals(2, theorems.size()); // theorems.size() is 1
assertEquals("this is the outer theorem", theorems.get(0));
assertEquals("this is the inner theorem", theorems.get(1));
}
Here's my theorem extractor which is called by LatexTheoremProofExtractor#parse:
private void extractTheorems() {
// If this has been called before, return
if(theorems != null) {
return;
}
theorems = new ArrayList<String>();
final Matcher matcher = THEOREM_REGEX.matcher(source);
// Add trimmed matches while you can find them
while (matcher.find()) {
theorems.add(matcher.group(1).trim());
}
}
and THEOREM_REGEX is defined as follows:
private static final Pattern THEOREM_REGEX = Pattern.compile(Pattern.quote("\\begin{theorem}")
+ "(.+?)" + Pattern.quote("\\end{theorem}"));
Does anyone have recommendations for dealing with the nested tags?
A: If you only want to match doubly nested theorems, you can write down an explicit regular expression for it. I guess it would look something like this.
Pattern.compile(
Pattern.quote("\\begin{theorem}")
+ "("
+ "(.+?)"
+ Pattern.quote("\\begin{theorem}")
+ "(.+?)"
+ Pattern.quote("\\end{theorem}")
+ ")*"
+ Pattern.quote("\\end{theorem}"));
(This code should give you the idea but it is untested an probably does not work like written. This is not the point I want to make.)
You can continue this for triple-nesting and so forth for any fixed number of nesting you want. Needless to say that it will become rather awkward pretty soon.
However, if your goal is to match arbitrary deep nestings then it is simply impossible to do with regular expressions. The problem is that the language you want to match is not regular (but context-free). Context-free languages are strictly more powerful than regular languages and regular expressions can only match regular languages precisely. In general, you will need to construct a push-down automaton if you want to match a context-free language.
Further reading:
*
*Chomsky hierarchy
*What is meant by “Now you have two problems”?
| |
doc_4188
|
The code I had written works great when it comes to a single file, but I cant seem to append into the dataframe for more files.
import re
import docx2txt
import pandas as pd
import glob
df2=pd.DataFrame()
appennded_data=[]
for file in glob.glob("*.docx"):
text = docx2txt.process(file)
a1=text.split()
d2=a1[37]
doc2=re.findall("HB0....",text)
units2=re.findall("00[0-9]...",text)
df2['Units']=units2
df2['Doc']=doc2[0]
df2['Date']=d2
df2
This gives an error
"Length of values does not match length of index"
Expected output-
From docx1: (Which I get)
Units | Doc | Date
001 | HB00001 | 23/4/12
002 | HB00001 | 23/4/12
003 | HB00001 | 23/4/12
004 | HB00001 | 23/4/12
005 | HB00001 | 23/4/12
From docx2:
Units | Doc | Date
010 | HB00002 | 2/6/16
011 | HB00002 | 2/6/16
Final output:
Units | Doc | Date
001 | HB00001 | 23/4/12
002 | HB00001 | 23/4/12
003 | HB00001 | 23/4/12
004 | HB00001 | 23/4/12
005 | HB00001 | 23/4/12
010 | HB00002 | 2/6/16
011 | HB00002 | 2/6/16
Any help would be appreciated
A: The error is because the lengths of the columns are not the same. The moment the second file is processed, it will be trying to set the columns to values that have a different length to the first file. You cannot assign a column with values that are different to the existing columns.
Since you want the final df to have columns ['Units', 'Doc', 'Date'], what you can do is to create a blank df and just append the new results to it. Use ignore_index=True to just append it below without trying to match row indexes.
import re
import docx2txt
import pandas as pd
import glob
final_df = pd.DataFrame()
for file in glob.glob("*.docx"):
text = docx2txt.process(file)
a1 = text.split()
d2 = a1[37]
doc2 = re.findall("HB0....", text)
units2 = re.findall("00[0-9]...", text)
# because columns are different length, create them as separate df and concat them
df2 = pd.DataFrame()
unit_df = pd.DataFrame(units2)
doc_df = pd.DataFrame(doc2[0])
date_df = pd.DataFrame(d2)
# join them by columns. Any blanks will become NaN, but that's because your data has uneven lengths
df2 = pd.concat([df2, unit_df, doc_df, date_df], axis=1)
# at the end of the loop, append it to the final_df
final_df = pd.concat([final_df, df2], ignore_index=True)
print(final_df)
A: My suggestion is to first build a dict with the contents and create the DataFrame in the end:
import re
import docx2txt
import pandas as pd
import glob
columns = ['Units', 'Doc', 'Date']
data = {col: [] for col in columns}
for file in glob.glob("*.docx"):
text = docx2txt.process(file)
a1=text.split()
d2=a1[37]
doc2=re.findall("HB0....",text)
units2=re.findall("00[0-9]...",text)
data['Units'].extend(units2)
data['Doc'].extend(doc2[0])
data['Date'].extend(d2)
df2 = pd.DataFrame(data)
| |
doc_4189
|
tv<- data.frame(
name = c("p1","p2","p3","p1","p2","p3","p1","p2","p3","p1","p2","p3", "p1", "p2", "p3", "p1", "p2", "p3", "p1", "p2", "p3", "p1", "p2", "p3", "p1", "p2", "p3"),
dates = c("2010", "2010", "2010", "2010", "2010", "2010", "2010", "2010", "2010","2011", "2011", "2011", "2011", "2011", "2011", "2011", "2011", "2011", "2015", "2015", "2015", "2015", "2015", "2015", "2015", "2015", "2015" ),
results = c(40, 40, 45, 50, 52, 52, 53, 54, 56, 70, 50, 10, 40, 55, 55, 60, 60, 70, 30, 60, 60, 55, 55, 54, 32, 33, 57),
parameter = c("D", "D", "D", "R", "R", "R", "C", "C", "C", "D", "D", "D", "R", "R", "R", "C", "C", "C","D", "D", "D", "R", "R", "R", "C", "C", "C")
)
ftv <- function(id){
Ttv <- tv %>% filter(name == id)
ggplot(Ttv, aes(dates, results, group = parameter)) +
geom_point() +
geom_line() +
theme(axis.text.x = element_text(size= 6, angle = 90), strip.text = element_text(size = 6))+
facet_wrap(~parameter, scales = "free")+
ggsave(paste0("~/Desktop//", id, "_test.pdf"))
}
for(id in unique(tv$name)){
ftv(id)
}
And I obtain this
I would like to have the same type of file, but each page containing 1 plot, considering that later on I might want to have more than 3 graph in the file.
thank you for you help.
A: Is this what you want?
# create a new variable that combines the two variables for identifying cases
tv$name_parameter<-paste0(tv$name,tv$parameter)
ftv <- function(id){
Ttv <- tv %>% filter(name_parameter == id) # use the new identifier here
ggplot(Ttv, aes(dates, results, group = parameter)) +
geom_point() +
geom_line() +
theme(axis.text.x = element_text(size= 6, angle = 90), strip.text = element_text(size = 6))+
# # remove facet_wrap bc you're using `parameter` to paginate
# facet_wrap(~parameter, scales = "free")+
ggsave(paste0("~/Desktop//", id, "_test.pdf"))
}
for(id in unique(tv$name_parameter)){ # again, the new identifier
ftv(id)
}
A: Try this:
#Function
ftv <- function(id){
Ttv <- tv %>% filter(name == id)
LTtv <- split(Ttv,Ttv$parameter)
Lplot <- lapply(LTtv, function(x)
ggplot(x, aes(dates, results, group = parameter)) +
geom_point() +
geom_line() +
theme(axis.text.x = element_text(size= 6, angle = 90), strip.text = element_text(size = 6))+
facet_wrap(~parameter, scales = "free"))
#Export
pdf(paste0(id,'.pdf'),width = 14)
lapply(Lplot,plot)
dev.off()
}
#Apply
for(id in unique(tv$name)){
ftv(id)
}
| |
doc_4190
|
I am having an .NET application. I published the application using ClickOnce and kept all the published file on Apache server. Then I created an webpage on which an download link is there pointing to .application file. This working fine. :)
Now my scenario is, I am having 5 computer labs each lab will have there respective Webserver(Tomcat) on which an JAVA web application is deployed. What I have to do is I have to publish .NET application 5 times with 5 different server URLs. Like say if my First server is http://lab1srv:8050/Myapp then in publish URL will be http://lab1srv:8050/Myapp/application same for 2..3..4....(This example is just for 5 server what if I have 100+ server?)
I will be surprised if there is something in which I be able to set deployment provider dynamically or any thing else?
A: See the article Deploying ClickOnce Applications For Testing and Production Servers without Resigning.
Starting with the .NET Framework 3.5, you no longer have to specify a deploymentProvider in your deployment manifest in order to deploy a ClickOnce application for both online and offline usage. This supports the scenario where you need to package and sign the deployment yourself, but allow other companies to deploy the application over their networks.
If your .NET version is lower than that, there is always the Mage.exe (or even better, MageUI.exe).
Now I don't really have hands-on experience with Mage, but it is used to recreate and sign manifests. It will be a matter of creating a good batch file. After that you just have to copy the files to the servers (which can be automated as well), and then just double click the batch file.
| |
doc_4191
|
In the Vue applcation, we use Router. Here is the code below.
Vue.use(Router);
export default new Router({
mode: 'history',
base: process.env.BASE_URL,
routes: [
{
path: '/',
redirect: '/heroes',
},
{
path: '/heroes/:id',
name: 'hero-detail',
// props: true,
props: parseProps,
component: () =>
import(/* webpackChunkName: "bundle.heroes" */ './views/hero-detail.vue'),
},
{
path: '*',
component: PageNotFound,
},
],
});
We open the page in the browser, and it loads the main page. In this page, there is a link button, and this.$router.push will be invoked while the button is clicked.
After clicking the link button, the url in the browser address bar is chagned. Usually the browser will send a request to the server when the address is chagned. But the browser never sends a request to the server in Vue. How does Vue prevent it?
A: On vue-router package there a function called guardEvent. It looks like it prevents redirection on different situations.
function guardEvent (e) {
// don't redirect with control keys
if (e.metaKey || e.altKey || e.ctrlKey || e.shiftKey) { return }
// don't redirect when preventDefault called
if (e.defaultPrevented) { return }
// don't redirect on right click
if (e.button !== undefined && e.button !== 0) { return }
// don't redirect if `target="_blank"`
if (e.currentTarget && e.currentTarget.getAttribute) {
var target = e.currentTarget.getAttribute('target');
if (/\b_blank\b/i.test(target)) { return }
}
// this may be a Weex event which doesn't have this method
if (e.preventDefault) {
e.preventDefault();
}
return true
}
| |
doc_4192
|
I found it easy to persist simple data as strings or integers. But what about when i have relations between objects and i need to use foreign keys. In my app i have areas, and sub areas which have an attribute of type Area (Area where they belong) so my Area and Subarea are like these
class Area(
var idArea: String,
@BeanProperty
var name:String,
@BeanProperty
var letter: String,
@BeanProperty
var color: String
)
extends Idable {
def this() = this("","", "","")
}
class SubArea(var idSubArea: String,
@BeanProperty
var name: String,
@BeanProperty
var area:Area
) extends Idable {
def this() = this("","",null )
How do i define the schema, so my SubArea table has an Area id, foreign key to my Area Table??
For the time being my SubArea schema is like these
object SubAreaSchema extends Schema {
val subAreas=table[SubArea]
on(subAreas)(subArea => declare(
subArea.id is (autoIncremented),
subArea.name is (unique)
))
}
A: You can define the relation in your schema with:
val areaToSubAreas = oneToManyRelation(areas, subAreas).via((a,sA) => s.idArea === sa.areaId)
To make that work, you would want to modify your SubArea class load the foreign key's id directly, as below with the areaId:String.
class SubArea(var idSubArea: String,
@BeanProperty
var name: String,
@BeanProperty
var areaId: String)
and then in the method body, if you want to have access to the object, you can use:
def area = areaToSubAreas.right(this)
which will yield an ManyToOne[Area] which you query, or use headOption on to convert to an Option[Area].
Conversely, if you need to reference the subareas on Area, you can use:
def subAreas = areaToSubAreas.left(this)
which will yield an OneToMany[Area] which can be iterated over, or you can also call toList.
| |
doc_4193
|
*
*Is this documented anywhere?
*Are there ways to decrease this delay?
*Is there a way to know the server timestamp corresponding to the data being returned? Or to have any indication about this delay in the data being returned from Firestore?
(say some data is written to the server at 1:00 - the document is created server-side at that time, I query it at 1:01, but due to the delay it returns the data as it was at 0:58 server-side, the timestamp would be 0:58)
Here I am not speaking about anything with high load, my tests were just about writing and then reading 1 small document.
A: Firestore will have some delays, even I have noticed it. It's better to use the Realtime Database as it lives up to the name, the time lag is minimal, less than a second in most cases !
A: If you use Firestore on a native device offline first is enabled by default. That means data is first written to a cache on your device and then synced to the backend. On Web you can enable that to. To listen for those changes when a write is saved to the backend you would need to enable includeMetadataChanges on your realtime listeners:
db.collection("cities").doc("SF")
.onSnapshot({
// Listen for document metadata changes
includeMetadataChanges: true
}, (doc) => {
// ...
});
That way you will get a notice when the data is written to the backend. You can read more about it here.
The delay should be only between different devices. If you listen to the changes on your device where you write the data it will be shown immidiately.
Also something you should take care of. If you have offline enabled you should not await for the writes to finish. Just use them as if they are synchronous (even on web with enabled offline feature). I had that before in my code and it looked like the database was slow. By removing the await the code was running much faster.
| |
doc_4194
|
<form action="<?php echo $this->getUrl('quote/index/save', array('_secure'=>true)); ?>" id="get_a_quote" method="post" name="get_a_quote" enctype="multipart/form-data">
<div id="wizard">
<label for="attachment">Attachment</label>
<input type="file" name="attachment[]" multiple="multiple" />
<input id="submit" type="submit" name="save" value="Get A Quote" />
</div>
</form>
in IndexController my save action code is:
print_r($_FILES); die;// result Array() but sometimes Array(bla bla bla)
My server info is:
post_max_size = 8M
upload_max_filesize = 16М
| |
doc_4195
|
Codesandbox link:
https://codesandbox.io/s/naughty-darkness-rk8lc?file=/src/App.js
nominatePerson.js
import React, { useRef, useEffect, useState } from "react";
import { useParams } from "react-router-dom";
import { useForm } from "react-hook-form";
import Axios from "axios";
import { Link, useHistory } from "react-router-dom";
import Multiselect from "multiselect-react-dropdown";
const options = [
{ id: 1, name: "Ath", email: "ath.best@test1.com", access: null },
{ id: 2, name: "Arnolds", email: "arnold@test1.com", access: null },
{ id: 3, name: "Alter", email: "alloop@test1.com", access: null },
{ id: 4, name: "Brandan", email: "brandan@test1.com", access: null },
{ id: 5, name: "Ron", email: "ron@test1.com", access: null },
{ id: 6, name: "Rads", email: "rad@test1.com", access: null },
{ id: 7, name: "Sam", email: "sam@y.com", access: null }
];
const NominatePerson = () => {
const [option, setOption] = useState([]);
const [selectedOption, setSelectedOption] = useState([]);
const [nomRegister, setNomRegister] = useState([{}]);
const [helperText, setHelperText] = useState("");
const [userEmail, setUserEmail] = useState("");
const {
register,
handleSubmit,
watch,
formState: { errors },
reset
} = useForm();
const maxOptions = 3;
const history = useHistory();
useEffect(() => {
const userEmail = localStorage.getItem("loginEmail");
setUserEmail(userEmail);
});
useEffect(() => {
const fetchData = async () => {
try {
const res = await Axios.get(
"http://localhost:8000/service/nomineeslist"
);
setOption(options);
console.log("Get the list of nominees :" + JSON.stringify(res.data));
} catch (e) {
console.log(e);
}
};
fetchData();
}, []);
const handleTypeSelect = (e, i) => {
const copy = [...selectedOption];
copy.push(e[i]);
setSelectedOption(copy);
};
const sendNomination = () => {
console.log("What the Array holds: " + JSON.stringify(nomRegister));
const fetchData = async (nomRegister) => {
try {
const res = await Axios.post(
"http://localhost:8000/service/nominateperson",
{ userEmail },
nomRegister
);
if (res.data) {
console.log("Print data:" + res.data);
const successMessage = res.data.message;
setHelperText(successMessage);
setNomRegister(reset);
}
} catch (e) {
console.log(e);
setNomRegister(reset);
setHelperText(e.message);
}
};
fetchData();
};
options.forEach((option) => {
option.displayValue = option.name + "\t" + option.email;
});
const handleChange = (e, i) => {
const { name, email, value } = e.target;
// immutating state (best practice)
const updateList = nomRegister.map((item) => {
return { ...item };
});
const select_Email = selectedOption.map((item) => {
return item.email;
});
//change the specific array case depends on the id //email:emailList[i],
updateList[i] = {
...updateList[i],
name: name,
email: select_Email[i],
reason: value
};
setNomRegister(updateList);
};
return (
<div className="App">
<h1>Nominate a person</h1>
<div className="nomineeSelectBox">
<div id="dialog2" className="triangle_down1" />
<div className="arrowdown">
<Multiselect
onSelect={(e) => handleTypeSelect(e, selectedOption.length)}
options={selectedOption.length + 1 === maxOptions ? [] : options}
displayValue="displayValue"
showCheckbox={true}
emptyRecordMsg={"Maximum nominees selected !"}
/>
</div>
</div>
<div className="nominationcount"></div>
<form onSubmit={handleSubmit(sendNomination)}>
<div className="nomineesSelectedList">
<h4>Selected Nominees</h4>
{selectedOption.map((x, i) => (
<div key={i}>
<div className="row eachrecord">
<div className="column">
<label className="nomlabel">
{x?.name} <b>>></b>
</label>
</div>
<input
required
type="textarea"
placeholder="Please provide reason for nomination.."
key={i}
id={i}
name={x?.name}
className="nomineechoosed"
onChange={(e) => handleChange(e, i)}
/>
</div>
</div>
))}
<div className="row">
<div className="buttongroup">
<input id="Submit" type="submit" value="Submit" />
<input id="Cancel" type="button" value="Cancel" />
</div>
</div>
</div>
</form>
<span className="nominationValidationText">{helperText}</span>
</div>
);
};
export default NominatePerson;
A: I did some changes on the options data, sendNomination, handleChange and input of the textarea. Check this out:
import React, { useRef, useEffect, useState } from "react";
import { useParams } from "react-router-dom";
import { useForm } from "react-hook-form";
import Axios from "axios";
import { Link, useHistory } from "react-router-dom";
import Multiselect from "multiselect-react-dropdown";
const options = [
{
id: 1,
name: "Ath",
email: "ath.best@test1.com",
access: null,
reason: ""
},
{
id: 2,
name: "Arnolds",
email: "arnold@test1.com",
access: null,
reason: ""
},
{ id: 3, name: "Alter", email: "alloop@test1.com", access: null, reason: "" },
{
id: 4,
name: "Brandan",
email: "brandan@test1.com",
access: null,
reason: ""
},
{ id: 5, name: "Ron", email: "ron@test1.com", access: null, reason: "" },
{ id: 6, name: "Rads", email: "rad@test1.com", access: null, reason: "" },
{ id: 7, name: "Sam", email: "sam@y.com", access: null, reason: "" }
];
const NominatePerson = () => {
const [option, setOption] = useState([]);
const [selectedOption, setSelectedOption] = useState([]);
const [nomRegister, setNomRegister] = useState([{}]);
const [helperText, setHelperText] = useState("");
const [userEmail, setUserEmail] = useState("");
const {
register,
handleSubmit,
watch,
formState: { errors },
reset
} = useForm();
const maxOptions = 3;
const history = useHistory();
useEffect(() => {
const userEmail = localStorage.getItem("loginEmail");
setUserEmail(userEmail);
});
useEffect(() => {
const fetchData = async () => {
try {
const res = await Axios.get(
"http://localhost:8000/service/nomineeslist"
);
//const data1 = res.data;
setOption(options);
console.log("Get the list of nominees :" + JSON.stringify(res.data));
} catch (e) {
console.log(e);
}
};
fetchData();
}, []);
const handleTypeSelect = (e, i) => {
const copy = [...selectedOption];
copy.push(e[i]);
setSelectedOption(copy);
};
const sendNomination = () => {
console.log("What the Array holds: " + JSON.stringify(nomRegister));
const fetchData = async (nomRegister) => {
try {
const res = await Axios.post(
"http://localhost:8000/service/nominateperson",
{ userEmail },
nomRegister
);
if (res.data) {
console.log("Print data:" + res.data);
const successMessage = res.data.message;
setHelperText(successMessage);
const updateList = selectedOption.map((item) => {
return { ...item, reason: "" };
});
setSelectedOption(updateList);
setNomRegister(updateList);
}
} catch (e) {
console.log(e);
setHelperText(e.message);
const updateList = selectedOption.map((item) => {
return { ...item, reason: "" };
});
setSelectedOption(updateList);
setNomRegister(updateList);
}
};
fetchData();
};
options.forEach((option) => {
option.displayValue = option.name + "\t" + option.email;
});
const handleChange = (e, i) => {
const { name, email, value } = e.target;
// immutating state (best practice)
const updateList = selectedOption.map((item) => {
return { ...item };
});
const select_Email = selectedOption.map((item) => {
return item.email;
});
//change the specific array case depends on the id //email:emailList[i],
updateList[i] = {
...updateList[i],
name: name,
email: select_Email[i],
reason: value
};
setSelectedOption(updateList);
setNomRegister(updateList);
};
return (
<div className="App">
<h1>Nominate a person</h1>
<div className="nomineeSelectBox">
<div id="dialog2" className="triangle_down1" />
<div className="arrowdown">
<Multiselect
onSelect={(e) => handleTypeSelect(e, selectedOption.length)}
options={selectedOption.length + 1 === maxOptions ? [] : options}
displayValue="displayValue"
showCheckbox={true}
emptyRecordMsg={"Maximum nominees selected !"}
/>
</div>
</div>
<div className="nominationcount"></div>
<form onSubmit={handleSubmit(sendNomination)}>
<div className="nomineesSelectedList">
<h4>Selected Nominees</h4>
{selectedOption.map((x, i) => (
<div key={i}>
<div className="row eachrecord">
<div className="column">
<label className="nomlabel">
{x?.name} <b>>></b>
</label>
</div>
<input
required
type="textarea"
placeholder="Please provide reason for nomination.."
key={i}
id={i}
name={x?.name}
value={x?.reason}
className="nomineechoosed"
onChange={(e) => handleChange(e, i)}
/>
</div>
</div>
))}
<div className="row">
<div className="buttongroup">
<input id="Submit" type="submit" value="Submit" />
<input id="Cancel" type="button" value="Cancel" />
</div>
</div>
</div>
</form>
<span className="nominationValidationText">{helperText}</span>
</div>
);
};
export default NominatePerson;
Check Codesandbox
| |
doc_4196
|
dx/dt = (A + C_d(t) * B) * x,
where A and B are constant matrices and C_d is a diagonal coefficient matrix which smoothly varies depending on the current value of the integration variable.
The square matrices A and B are built up from smaller 60*60 upper triangular or zero matrices. The dimension of the full system is around 2500*2500. A and B are sparse with ~10% non-zero elements. The diagonal elements are negative or zero. The main (physical) constraint is that elements of x(t) are not allowed to become negative during integration.
Currently, I employ a ‘naïve’ step solver
x_(i+1) = A * x_i * dt_i + B * (C_d(t_i) * x_i) * dt_i + x_i
or in the CPU/GPU versions
def solve_CPU(nsteps, dt, c_d, x):
for step in xrange(nsteps):
x += (A.dot(x) + B.dot(x * c_d[step])) * dt[step]
def solve_GPU(m, n, nsteps, dt, c_d, cu_curr_x, cu_delta_x, cu_A, cu_B):
for step in xrange(nsteps):
cubl.gemv(trans='T', m=m, n=n, alpha=1.0, A=cu_A,
x=cu_curr_x, beta=0.0, y=cu_delta_x)
cubl.gemv(trans='T', m=m, n=n, alpha=c_d[step], A=cu_B,
x=cu_curr_x, beta=1.0, y=cu_delta_x)
cubl.axpy(alpha=dt[step], x=cu_delta_x, y=cu_curr_x)
and make use of a feature, that the step sizes dt_ithis can be computed a priory in a way that the elements of x are always >=0 during integration. Depending on the amount of approximations and the settings the number of integration steps varies between 25k and 10M.
I have tried several methods to optimize performance on general purpose hardware:
*
*(unknown) When using ODEPACK’s VODE solver, I do not know how to express the x>=0 constraint
*(slowest) Dense BLAS 2 dot-product using Intel MKL
*(medium) Dense BLAS using single precision cuBLAS on NVIDIA GPU
*(fastest) SCIPY sparse module using CSR/CSC formats
The code is written in Python and has access to the above listed libraries via Anaconda, Numba, Accelerate, Numpy etc. SCIPY's sparse BLAS routines are not properly linked to MKL in Anaconda and Python wrappers around cuSPARSE are to my knowledge not available, yet. I would know how to squeeze out a little bit more performance by directly interfacing to cuSPARSE/C-MKL sparse dot product, but that’s it. This exercise has to be solved dozens of times, again and again if models change, so performance is always an issue. I’m not an expert in this matter, so I don’t know much about preconditioners, factorization theorems etc. what brings me to my question:
Is there a more elegant or better way to solve such a linear-algebra task?
| |
doc_4197
| ||
doc_4198
|
This is the code that I have:
removeIng = pH1 + pH2 + pH3;
System.out.print("Enter number corresponding to element you want to remove");
System.out.printf("%s",removeIng);
remove = in.nextInt();
switch(remove)
{
case 1:
removeIng = pH2 + pH3;
case 2:
removeIng = pH1 + pH3;
case 3:
removeIng = pH1 + pH2;
}
I need the code to be dynamic so that the user could possibly remove all the elements if they want. I have an outside loop already created to allow for that possibility. But I'm at a loss as to how to have "removeIng" subtract the user selected element. I can figure out the other part. Any help would be greatly appreciated. I've found ways to subtract strings that are declared as "blah blah" but nothing like this. Hopefully that makes sense.
Thanks.
A: Try String.replace(CharSequence target, CharSequence replacement) (javadoc). There is also a version of this method that uses regular expressions, if you need a more powerful replacement syntax.
A: Based on your sample code, it might be easier to keep track of which bits of the string the user doesn't want, and generate removeIng based on that. Here's some pseudocode. I sacrificed optimization in favor of clarity:
String[] components;
// what used to be called pH1 is accessed by components[0];
boolean[] deletedPieces;
// initially set to all false
// contains true for segments that the user wants to delete, false otherwise
your outer loop here {
// ask the user which piece to delete here
remove = in.nextInt() - 1; // - 1 to account for array indices starting at 0
deletedPieces[remove] = true;
StringBuilder sb = new StringBuilder();
for(int i = 0; i < total number of possible pieces; i++) {
if(deletedPieces[i])
// user wanted this piece deleted; do nothing
else
sb.append(components[i]);
}
removeIng = sb.toString();
}
| |
doc_4199
|
.content-text {
padding: 10px 10px 10px 10px !important;
font-size: 16px;
line-height: 1.3;
}
Each column need to have the above class, but each column need to have different background colors. Example:
.column--left__content {
background-color: #bebab1;
}
So that would say that column--left__content should inherit everything from content-text. How can I do that the best way?
HTML
<table class="row">
<tbody>
<tr>
<th class="small-12 large-1 columns first first--column__color " style="width:1%;">
<table>
<tr>
<th>
<p></p>
</th>
</tr>
</table>
</th>
<!-- Here is how I solved this until now -->
<th class="small-12 large-5 columns first content-text column--left__content">
<table >
<tr>
<th>
<h5><strong>This is headline 1</strong></h5>
<p class="text-left">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
</th>
</tr>
</table>
</th>
</tr>
</tbody>
</table>
At the moment I am calling the content-text and column--left__content in the sam <th>, which does not look so nice.
The best practice for doing this, how would that be? I am thinking that fx column--left__content have to inherit .content-text, but have individually styles also?
EDIT
The
A: One possible way is to use the nth-child selector in CSS.
.wrapper {
color:#fff;
background-color:none;
width:50%;
height:3rem;
line-height:3rem;
font-size:1.5rem;
}
.wrapper p {
padding:0 0 0 1rem;
}
.wrapper p:nth-child(1) {
background: red;
}
.wrapper p:nth-child(2) {
background: green;
}
.wrapper p:nth-child(3) {
background: brown;
}
<div class="wrapper">
<p> col 1</p>
<p> col 2</p>
<p> col 3</p>
</div>
Another possible way is to create your own background-color helper classes in order to use whenever you want to and not only to use for this case.
.wrapper {
color:#fff;
background-color:none;
width:50%;
height:3rem;
line-height:3rem;
font-size:1.5rem;
}
.wrapper p {
padding:0 0 0 1rem;
}
.bg_red {
background: red;
}
.bg_green {
background: green;
}
.bg_brown {
background: brown;
}
<div class="wrapper">
<p class="bg_red"> col 1</p>
<p class="bg_green"> col 2</p>
<p class="bg_brown"> col 3</p>
</div>
There is a 3rd way that has to do with a small jQuery plugin i have made once (i have not updated it though :) since there was no real usage). But the concept is to use simple helper classes for text-color and background-color in your syntax. The rest is done by the plugin. The class that have to just be added in your HTML (nothing in CSS is needed) have the prefix (bgDarken-,bgLighten-,txtDarken-,txtLighten-) and are followed by a number between 1 and 256. Check the results in the snippet.
You can find it here, there are two examples one using Bootstrap (and is posted here in the snippet), and one using Materialize framework.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jLightenDarken Demo with Bootstrap Framework integration.</title>
<meta name="description" content="The HTML5 Herald">
<meta name="author" content="SitePoint">
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<!--[if lt IE 9]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<style type="text/css">
body {
color:#fff;
background-color:#ffffff;
}
div.alert, div.panel {
background-color:#2196f3;
color:#ffffff;
}
</style>
</head>
<body>
<div class="container-fluid">
<div class="row">
<div class="col-xs-8 col-xs-offset-2 col-sm-8 col-sm-offset-2 col-md-8 col-md-offset-2 col-lg-8 col-lg-offset-2">
<div class="panel panel-default bgDarken-4">
<div class="panel-body">
Lorem ipsum
</div>
<div class="panel-footer bgLighten-4 txtDarken-255"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur lectus neque, pretium eget elit sit amet, maximus pretium libero...</div>
</div>
<div class="panel panel-default bgDarken-8">
<div class="panel-body">
Lorem ipsum
</div>
<div class="panel-footer bgLighten-8 txtDarken-255"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur lectus neque, pretium eget elit sit amet, maximus pretium libero...</div>
</div>
<div class="panel panel-default bgDarken-16">
<div class="panel-body">
Lorem ipsum
</div>
<div class="panel-footer bgLighten-16 txtDarken-255"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur lectus neque, pretium eget elit sit amet, maximus pretium libero...</div>
</div>
<div class="panel panel-default bgDarken-24">
<div class="panel-body">
Lorem ipsum
</div>
<div class="panel-footer bgLighten-16 txtDarken-255"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur lectus neque, pretium eget elit sit amet, maximus pretium libero...</div>
</div>
<div class="panel panel-default bgDarken-40">
<div class="panel-body">
Lorem ipsum
</div>
<div class="panel-footer bgLighten-24 txtDarken-255"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur lectus neque, pretium eget elit sit amet, maximus pretium libero...</div>
</div>
<div class="panel panel-default bgDarken-48">
<div class="panel-body">
Lorem ipsum
</div>
<div class="panel-footer bgLighten-24 txtDarken-255"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur lectus neque, pretium eget elit sit amet, maximus pretium libero...</div>
</div>
<div class="panel panel-default bgDarken-64">
<div class="panel-body">
Lorem ipsum
</div>
<div class="panel-footer bgLighten-24 txtDarken-255"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur lectus neque, pretium eget elit sit amet, maximus pretium libero...</div>
</div>
<div class="panel panel-default bgDarken-80">
<div class="panel-body">
Lorem ipsum
</div>
<div class="panel-footer bgLighten-16 txtDarken-255"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur lectus neque, pretium eget elit sit amet, maximus pretium libero...</div>
</div>
<div class="panel panel-default bgDarken-96">
<div class="panel-body">
Lorem ipsum
</div>
<div class="panel-footer bgLighten-24 txtDarken-255"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur lectus neque, pretium eget elit sit amet, maximus pretium libero...</div>
</div>
<div class="panel panel-default bgDarken-124">
<div class="panel-body">
Lorem ipsum
</div>
<div class="panel-footer bgLighten-24 txtDarken-255"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur lectus neque, pretium eget elit sit amet, maximus pretium libero...</div>
</div>
<div class="panel panel-default bgDarken-140">
<div class="panel-body">
Lorem ipsum
</div>
<div class="panel-footer bgLighten-24 txtDarken-255"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur lectus neque, pretium eget elit sit amet, maximus pretium libero...</div>
</div>
<div class="panel panel-default bgDarken-148">
<div class="panel-body">
Lorem ipsum
</div>
<div class="panel-footer bgLighten-24 txtDarken-255"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur lectus neque, pretium eget elit sit amet, maximus pretium libero...</div>
</div>
<div class="panel panel-default bgDarken-156">
<div class="panel-body">
Lorem ipsum
</div>
<div class="panel-footer bgLighten-24 txtDarken-255"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur lectus neque, pretium eget elit sit amet, maximus pretium libero...</div>
</div>
<div class="panel panel-default bgDarken-164">
<div class="panel-body">
Lorem ipsum
</div>
<div class="panel-footer bgLighten-24 txtDarken-255"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur lectus neque, pretium eget elit sit amet, maximus pretium libero...</div>
</div>
<div class="panel panel-default bgDarken-192">
<div class="panel-body">
Lorem ipsum
</div>
<div class="panel-footer bgLighten-24 txtDarken-255"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur lectus neque, pretium eget elit sit amet, maximus pretium libero...</div>
</div>
<div class="panel panel-default bgDarken-224">
<div class="panel-body">
Lorem ipsum
</div>
<div class="panel-footer bgLighten-16 txtDarken-255"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur lectus neque, pretium eget elit sit amet, maximus pretium libero...</div>
</div>
<div class="panel panel-default bgDarken-255">
<div class="panel-body">
Lorem ipsum
</div>
<div class="panel-footer bgLighten-16 txtDarken-255"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur lectus neque, pretium eget elit sit amet, maximus pretium libero...</div>
</div>
</div>
</div>
<br />
<div class="row">
<div class="col-xs-8 col-xs-offset-2 col-sm-8 col-sm-offset-2 col-md-8 col-md-offset-2 col-lg-8 col-lg-offset-2">
<div class="alert alert-info bgLighten-16"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur lectus neque, pretium eget elit sit amet, maximus pretium libero... </div>
<div class="alert alert-info bgLighten-24"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur lectus neque, pretium eget elit sit amet, maximus pretium libero... </div>
<div class="alert alert-info bgLighten-32"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur lectus neque, pretium eget elit sit amet, maximus pretium libero... </div>
<div class="alert alert-info bgLighten-40"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur lectus neque, pretium eget elit sit amet, maximus pretium libero... </div>
<div class="alert alert-info bgLighten-48"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur lectus neque, pretium eget elit sit amet, maximus pretium libero... </div>
<div class="alert alert-info bgLighten-56"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur lectus neque, pretium eget elit sit amet, maximus pretium libero... </div>
<div class="alert alert-info bgLighten-64"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur lectus neque, pretium eget elit sit amet, maximus pretium libero... </div>
<div class="alert alert-info bgLighten-80"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur lectus neque, pretium eget elit sit amet, maximus pretium libero... </div>
<div class="alert alert-info bgLighten-96"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur lectus neque, pretium eget elit sit amet, maximus pretium libero... </div>
<div class="alert alert-info bgLighten-124 txtDarken-124"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur lectus neque, pretium eget elit sit amet, maximus pretium libero... </div>
<div class="alert alert-info bgLighten-156 txtDarken-156"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur lectus neque, pretium eget elit sit amet, maximus pretium libero... </div>
<div class="alert alert-info bgLighten-164 txtDarken-164"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur lectus neque, pretium eget elit sit amet, maximus pretium libero... </div>
<div class="alert alert-info bgLighten-180 txtDarken-180"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur lectus neque, pretium eget elit sit amet, maximus pretium libero... </div>
<div class="alert alert-info bgLighten-192 txtDarken-196"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur lectus neque, pretium eget elit sit amet, maximus pretium libero... </div>
<div class="alert alert-info bgLighten-216 txtDarken-224"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur lectus neque, pretium eget elit sit amet, maximus pretium libero... </div>
<div class="alert alert-info bgLighten-232 txtDarken-248"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur lectus neque, pretium eget elit sit amet, maximus pretium libero... </div>
<div class="alert alert-info bgLighten-256 txtDarken-256"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur lectus neque, pretium eget elit sit amet, maximus pretium libero... </div>
</div>
</div>
</div>
<!-- Latest compiled and minified JavaScript -->
<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<script type="text/javascript">!function(n){function t(n){return null==n||""==n||"rgba(0, 0, 0, 0)"===n||"transparent"===n}function o(n){var i=n.parent(),r=n.css("background-color");return t(r)&&(r=i&&null!=i?o(i):""),r}function r(n){var i=n.parent(),o=n.css("color");return t(o)&&(o=i&&null!=i?r(i):""),o}function s(n){var t=n.split("-"),i=[];return 2==t.length?(i.functionality=t[0],i.amount=parseInt(t[1]),i):void 0}function l(t){var o,l,a,e,h=[],c=[],u=[];for(e=0,j=0;j<t.length;j++){"txtLighten"==t&&(e=1),"txtDarken"==t&&(e=-1),o=n('div[class*="'+t+'"]');var g,f=0,p=[];for(n.each(o,function(){for($klassKolor=r(n(this)),p.push($klassKolor.match(/\d+/g)),h.push($klassKolor),l=n(this).prop("class").split(" "),k=0;k<l.length;k++)-1!=l[k].search(t)&&(a=s(l[k]),c.push(a.amount))}),f=0;f<p.length;f++){for(g=p[f],i=0;i<g.length;i++)g[i]=parseInt(g[i])+c[f]*e,g[i]>=255&&(g[i]=255),g[i]<=0&&(g[i]=0),g[i]=g[i].toString(16),g[i].length<2&&(g[i]="0"+g[i]);u.push("#"+g.join(""))}}n.each(o,function(t){n(this).css("color",u[t])})}function a(t){var r,l,a,e,h=[],c=[],u=[];for(e=0,j=0;j<t.length;j++){"bgLighten"==t&&(e=1),"bgDarken"==t&&(e=-1),r=n('div[class*="'+t+'"]');var g,f=0,p=[];for(n.each(r,function(){for($klassKolor=o(n(this)),p.push($klassKolor.match(/\d+/g)),h.push($klassKolor),l=n(this).prop("class").split(" "),k=0;k<l.length;k++)-1!=l[k].search(t)&&(a=s(l[k]),c.push(a.amount))}),f=0;f<p.length;f++){for(g=p[f],i=0;i<g.length;i++)g[i]=parseInt(g[i])+c[f]*e,g[i]>=255&&(g[i]=255),g[i]<=0&&(g[i]=0),g[i]=g[i].toString(16),g[i].length<2&&(g[i]="0"+g[i]);u.push("#"+g.join(""))}}n.each(r,function(t){n(this).css("background-color",u[t])})}n.fn.jLightenDarken=function(){l("txtLighten"),l("txtDarken"),a("bgLighten"),a("bgDarken")}}(jQuery);
</script>
<script type="text/javascript">
$(document).ready(function() {
$('body').jLightenDarken();
});
</script>
</body>
</html>
Summing up, depending on what you really want each one of those or any other answer presented by other SO users could be the best (or not) solution for YOU.
A: Assuming you HTML is as follow:
<section class="wrapper">
<div class="col1"> col 1</div>
<div class="col2"> col 2</div>
<div class="col3"> col 3</div>
</section>
your CSS could be like this:
.wrapper > div {
padding: 10px 10px 10px 10px !important;
font-size: 16px;
line-height: 1.3;
}
and have a color for each class:
.col1 {
background-color: red;
}
.col2 {
background-color: green;
}
I hope it helps
A: One good Choice would be too use CSS Less . You can use @extend concept of CSS Less.
.contest-test {
.context-text(); /* Copies everything from .context-text down here */
border: 1px solid red;
}
Follow this Link here
A: First: if every single iteration of an element has the same class, you're doing things wrong.
Second: You can easily fix your problem by not assigning a class, but giving the base CSS to the element itself.
For instance something like this:
th {
padding: 10px 10px 10px 10px !important;
font-size: 16px;
line-height: 1.3;
}
And then you just add the background-color classes as you need them.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.