id
stringlengths 5
11
| text
stringlengths 0
146k
| title
stringclasses 1
value |
|---|---|---|
doc_300
|
Say I created an Angular component, something like this:
<app-my-test></app-my-test>
How can I allow the user to set options on and off by just typing the option into the component, something like this:
<app-my-test booleanCheck></app-my-test>
Then in my .ts file, I would like booleanCheck to be true if they added it, and false if they didn't add it. Below is a blitz to play around with. The goal is to get the console.log to log true if booleanCheck was added, and false if it was not added.
https://stackblitz.com/edit/angular-xr3p84?file=src%2Fapp%2Fapp.module.ts
I do NOT want this as an answer please:
<app-my-test booleanCheck="true"></app-my-test>
<app-my-test [booleanCheck]="true"></app-my-test>
A: You can leverage the setter of @Input which will be called if the input is available.
import { Component, OnInit, Input } from '@angular/core';
@Component({
selector: 'my-test',
templateUrl: './app.test.html',
styleUrls: ['./app.test.css']
})
export class TestComponent implements OnInit {
private _booleanCheck = false;
@Input()
set booleanCheck(param) { // this is setter for booleanCheck input.
this._booleanCheck = true;
}
ngOnInit() {
console.log('ngOnInit');
console.log(this._booleanCheck);
}
}
Working copy is here - https://stackblitz.com/edit/angular-9ubmg7
A: You'll have to create a directive that will set the property for you in the host component (Note that the property may no longer be an @Input):
StackBlitz demo
@Component({
selector: 'my-test',
templateUrl: './app.test.html',
styleUrls: [ './app.test.css' ]
})
export class TestComponent implements OnInit {
public booleanCheck: boolean;
ngOnInit() {
console.log('ngOnInit');
console.log(this.booleanCheck);
}
}
@Directive({
selector: '[booleanCheck]'
})
export class BooleanCheck {
constructor(@Host() @Self() @Optional() host: TestComponent) {
host.booleanCheck = true;
}
}
(For an even simpler solution, look here)
A: Since you are passing the attribute to the custom component, it is not possible to add it like how you want. You are passing the input to the custom component and it should be like
<app-my-test [booleanCheck]="true"></app-my-test>
In your component it can be taken like
@Input() booleanCheck;
And if its true / false, you can enable / disable the logs.
Hope I answered your question.
A: One solution might be to check if the variable booleanCheck is undefined or not. This will console.log(this.booleanCheck) an empty string:
<app-my-test booleanCheck></app-my-test>
This will console.log(this.booleanCheck) undefined
<app-my-test></app-my-test>
So you can maybe use that to assign false if undefined and true if it is an empty string
| |
doc_301
|
var txtColor = $(".menu-item").css("background-color");
Where $(".menu-item").css("background-color"); represents pink color. But txtColor is taking as "transparent".
I'm seeing this issue only in IE-8.
Can anyone help me in fixing this issue.
Thanks in advance.
A: Question, is your CSS set up like this?
background: pink;
If so, try using $('.menu-item').css("background"); instead.
Old versions of IE will not properly cascade group definitions (like background) to the other settings. In modern browsers, defining background as "pink" will also set the background-color to "pink".
| |
doc_302
|
I've coded comms software before but this network thing is a whole new kettle of fish.
The config is as follows and it is not correct - my fixed lan connections are not connecting with this:
config interface 'loopback'
option ifname 'lo'
option proto 'static'
option ipaddr '127.0.0.1'
option netmask '255.0.0.0'
config globals 'globals'
option ula_prefix 'fdee:bdcf:b059::/48'
config interface 'lan'
option type 'bridge'
option ifname 'eth0.1'
option proto 'static'
option ipaddr '192.168.1.1'
option netmask '255.255.255.0'
option ip6assign '60'
option dns '192.168.1.1'
config interface 'wan'
option ifname 'eth1.2'
option ipv6 '0'
option proto 'pppoe'
option keepalive '3 5'
option username 'USERNAME'
option password 'PASSWORD'
option mtu '1480'
config interface 'wan6'
option ifname 'eth1.2'
option proto 'dhcpv6'
config switch
option name 'switch0'
option reset '1'
option enable_vlan '1'
option blinkrate '2'
config switch_vlan
option device 'switch0'
option vlan '1'
option ports '0 1 2 3'
config switch_vlan
option device 'switch0'
option vlan '2'
option ports '5t'
config switch_port
option device 'switch0'
option port '1'
option led '6'
config switch_port
option device 'switch0'
option port '2'
option led '9'
config switch_port
option device 'switch0'
option port '5'
option led '2'
The original config had one "config switch vlan" section which included all ports '0 1 2 3 5t'
I'm not 100% sure but believe the 'config interface lan' had ifname - 'eth0' defined, no plan. The 'config interface wan' was set to eth1 (again not 100% sure, might have been eth0 as well.
I thought I would have to separate the LAN and WAN by going them each their own vlan but as it is now, the hardwired connections don't work.
I tried changing the lan interface to 'eth0.2' and then the fixed ports work. But I think there might be contention somehow as the wifi dropped out at some stage.
Would any network guru be able to help?
Thanks
Ron
A: I have it working, what was missing is the CPU port on vlan '1' - this meant any fixed connections weren't working but WIFI connected hosts were.
The fix:
config switch_vlan
option device 'switch0'
option vlan '1'
option ports '0 1 2 3 5t'
And despite me answering my own question, I still don't consider myself a network guru.
Regards
Ron
| |
doc_303
|
layer.cornerRadius Number 10
layer.masksToBounds Boolean true
A: If you're not opposed to using images you could create a circle image of the size you need it to be. Then, assuming it's a UIButton, you can add it as a backgroundImage.
Storyboards
Xcode Screenshot
Swift 3
let circle = UIImage(named: "circle")
button.setBackgroundImage(circle, for: UIControlState.normal)
A: I don't know why your attempt to use user-defined runtime attributes is not working; it's a legitimate technique, and I've used it.
That said, here's another approach: use a UIButton subclass. Define your subclass to set these values in its initializer (here, init(coder:) is what you'll need to implement). Then, in the storyboard, use the Identity inspector to make these buttons instances of this subclass.
This is actually a better approach than yours, because it encapsulates in one place what all the buttons have in common. Having to define the same attributes for four buttons separately was always a Bad Smell!
| |
doc_304
|
For example, let say I have a website named abc.com and before opening my website customer have xyz.com and cfd.com already open in his browser in separate tabs. Now if that person opens my website abc.com then by some means I can fetch details about what other websites are open in person's browser, in this case xyz.com & cfd.com.
I am interested to know, does browser's offer some way? Or is it feasible to achieve by some means through Javascript?
A: No. This is impossible. It would be a terrible privacy invasion otherwise. Browsers have gone to some lengths to prevent this sort of information from leaking.
| |
doc_305
|
bin_path = dirname(sys.executable)
print(os.environ['PATH'])
if 'PATH' in os.environ:
os.environ['PATH'] += ':' + bin_path
else:
os.environ['PATH'] = bin_path
print(bin_path)
print(os.environ['PATH'])
the outputs are :
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games
/home/xiaozh/anaconda3/envs/tensorflow-gpu36/bin
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/home/xiaozh/anaconda3/envs/tensorflow-gpu36/bin
then i want to add "/home/xiaozh/anaconda3/envs/tensorflow-gpu36/bin" as a PATH to Linux system, so that I don't have to write the code above in the later work,but the problem happened ,i do it using:
export PATH=$PATH:/home/xiaozh/anaconda3/envs/tensorflow-gpu36/bin
in Linux ,and check the "PATH" by :
export
and i can see the new PATH variable as following:
declare -x PATH="/home/xiaozh/anaconda3/envs/tensorflow-gpu36/bin:
but the outputs after running the first part codes in Pycharm are same as:
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games
/home/xiaozh/anaconda3/envs/tensorflow-gpu36/bin
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/home/xiaozh/anaconda3/envs/tensorflow-gpu36/bin
then i code in Linux use same codes,the outputs are different,Show me my new PATH in the variable,Given that I will code in Pycharm later, I would like to ask what the problem is.
Is there a solution?
| |
doc_306
|
I've found this so QUESTION : Windows Phone 8.1 Background Task - Can't Debug and won't fire, downloaded and re-implemented the solution (http://1drv.ms/1qCPLMY), and with a little help, that worked out fine.
I've made this simple task :
using Windows.ApplicationModel.Background;
namespace FlexCheck.Tasks
{
public sealed class BackgroundTask : IBackgroundTask
{
BackgroundTaskDeferral _deferral = null;
public void Run(IBackgroundTaskInstance taskInstance)
{
_deferral = taskInstance.GetDeferral();
_deferral.Complete();
}
}
}
In order for this to compile I need target to be Windows Phone 8.1. But then I can not reference from my Windows 8 project.
Question : Can I somehow get around this? Or is there an equivalent IBackgroundTask which can be used on Windows phone 8?
A: Background agents in Windows Phone 8 can't react to the events. It only a pieces of code that run on a timer, nothing more. Switching to WP 8.1 is the only one solution. You can try an Audio Background agent as a hack and do some checks of the network state manually in the code, but this is a rule breaker and usually it won't pass the store certification.
| |
doc_307
|
I would like to know how do these text styles work? Is it some kind of a text span? Thanks for the help.
| |
doc_308
|
Server Error in '/' Application.
Value cannot be null or empty.
Parameter name: contentPath
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.ArgumentException: Value cannot be null or empty.
Parameter name: contentPath
Source Error:
[No relevant source lines]
Source File: c:\Users\User\AppData\Local\Temp\Temporary ASP.NET Files\vs\f60d396e\617997\App_Web_hs3arjh1.3.cs Line: 0
Stack Trace:
[ArgumentException: Value cannot be null or empty.
Parameter name: contentPath]
System.Web.Mvc.UrlHelper.GenerateContentUrl(String contentPath, HttpContextBase httpContext) +130
System.Web.Mvc.UrlHelper.Content(String contentPath) +42
ASP._Page_Views_Shared__Layout_cshtml.Execute() in c:\Users\Manuel\AppData\Local\Temp\Temporary ASP.NET Files\vs\f60d396e\617997\App_Web_hs3arjh1.3.cs:0
System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +177
System.Web.Mvc.WebViewPage.ExecutePageHierarchy() +80
System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +113
System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer) +26
System.Web.WebPages.<>c__DisplayClass3.<RenderPageCore>b__2(TextWriter writer) +210
System.Web.WebPages.HelperResult.WriteTo(TextWriter writer) +27
System.Web.WebPages.WebPageExecutingBase.WriteTo(TextWriter writer, HelperResult content) +31
System.Web.WebPages.WebPageBase.Write(HelperResult result) +32
System.Web.WebPages.WebPageBase.RenderSurrounding(String partialViewName, Action`1 body) +101
System.Web.WebPages.WebPageBase.PopContext() +146
System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +120
System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance) +297
System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer) +115
System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) +248
System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) +27
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +58
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +349
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +69
System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +188
System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +124
System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +27
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +58
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +30
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +29
System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +27
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +48
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +58
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +30
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +21
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +32
System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult asyncResult, Controller controller) +26
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +40
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +58
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +30
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +21
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +29
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +24
System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +27
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +48
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +58
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +30
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +21
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +29
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +23
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9742689
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
This is the code to make the logout.
[HttpPost]
public ActionResult Logout()
{
System.Web.Security.FormsAuthentication.SignOut();
Session.Clear();
Session.RemoveAll();
return RedirectToAction("Login", "Login");
}
I tried to make the logout without the session lines but it keeps the session.
| |
doc_309
|
The background:
We run a fairly large (35M hits/month, peak around 170 connections/sec) site which offers free software downloads (stricly legal) and which is written in ASP .NET 2 (VB .Net :( ). We have 2 web servers, sat behind a dedicated hardware load balancer and both servers are fairly chunky machines, Windows Server 2012 Pro 64 bit and IIS 8. We serve extensionless URLs by using a custom 404 page which parses out the requested URL and Server.Transfers appropriately. Because of this particular component, we have to run in classic pipeline mode.
DB wise we use MySQL, and have two replicated DBs, reads are mainly done from the slave. DB access is via a DevArt library and is extensively cached.
The Problem:
We recently (past few months) moved from older servers, running Windows 2003 Server and IIS6. In the process, we also upgraded the Devart Component and MySql (5.1). Since then, we have suffered intermitted scalability issues, which have become significantly worse as we have added more content. We recently increased the number of programs from 2000 to 4000, and this caused response times to increase from <300ms to over 3000ms (measured with NewRelic). This to my mind points to either a bottleneck in the DB (relatively unlikely, given the extensive caching and from DB monitoring) or a badly written query or code problem.
We also regularly see spikes which seem to coincide with cache refreshes which could support the badly written query argument - unfortunately all caching is done for x minutes from retrieval so it can't always be pinpointed accurately.
All our caching uses locks (like this What is the best way to lock cache in asp.net?), so it could be that one specific operation is taking a while and backing up requests behind it.
The problem is... I can't find it!! Can anyone suggest from experience some tools or methods? I've tried to load test, I've profiled the code, I've read through it line by line... NewRelic Pro was doing a good job for us, but the trial expired and for political reasons we haven't purchased a full licence yet. Maybe WinDbg is the way forward?
Looking forward to any insight anyone can add :)
A: It is not a good idea to guess on a solution. Things could get painful or expensive quickly. You really should start with some standard/common triage techniques and make an educated decision.
Standard process for troubleshooting performance problems on a data driven app go like this:
*
*Review DB indexes (unlikely) and tune as needed.
*Check resource utilization: CPU, RAM. If your CPU is maxed-out, then consider adding/upgrading CPU or optimize code or split your tiers. If your RAM is maxed-out, then consider adding RAM or split your tiers. I realize that you just bought new hardware, but you also changed OS and IIS. So, all bets are off. Take the 10 minutes to confirm that you have enough CPU and RAM, so you can confidently eliminate those from the list.
*Check HDD usage: if your queue length goes above 1 very often (more than once per 10 seconds), upgrade disk bandwidth or scale-out your disk (RAID, multiple MDF/LDFs, DB partitioning). Check this on each MySql box.
*Check network bandwidth (very unlikely, but check it anyway)
*Code: a) Consider upgrading to .net 3.5 (or above). It was designed for better scalability and has much better options for caching. b) Use newer/improved caching. c) pick through the code for harsh queries and DB usage. I have had really good experiences with RedGate Ants, but equiv. products work good too.
And then things get more specific to your architecture, code and platform.
There are also some locking mechanisms for the Application variable, but they are rarely the cause of lockups.
You might want to keep an eye on your pool recycle statistics. If you have a memory leak (or connection leak, etc) IIS might seem to freeze when the pool tops-out and restarts.
| |
doc_310
|
Here is a piece of code that does that:
import matplotlib.pyplot as plt
from matplotlib.patches import Arc
fig, ax = plt.subplots(1,1)
r = 2 #Radius
a = 0.2*r #width
b = 0.5*r #height
#center of the ellipse
x = 0.5
y = 0.5
ax.add_patch(Arc((x, y), a, b, angle = 20,
theta1=0, theta2=120,
edgecolor='b', lw=1.1))
#Now look for the ends of the Arc and manually set the limits
ax.plot([x,0.687],[y,0.567], color='r',lw=1.1)
ax.plot([x,0.248],[y,0.711], color='r',lw=1.1)
plt.show()
Which results in
.
Here the red lines were drawn looking carefully at the ends of the arc. However, as Arc does not allow to fill the arc for optimization, I wonder if there is a way to do it automatically for any center and angles.
A:
According to Wikipedia an ellipse in its polar form looks like
Using this you may calculate the end points of the lines.
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Arc
fig, ax = plt.subplots(1,1)
r = 2 #Radius
a = 0.2*r #width
b = 0.5*r #height
#center of the ellipse
x = 0.5; y = 0.5
# angle
alpha = 20
ax.add_patch(Arc((x, y), a, b, angle = alpha,
theta1=0, theta2=120,
edgecolor='b', lw=1.1))
def ellipse(x0,y0,a,b,alpha,phi):
r = a*b/np.sqrt((b*np.cos(phi))**2 + (a*np.sin(phi))**2)
return [x0+r*np.cos(phi+alpha), y0+r*np.sin(phi+alpha)]
x1,y1 = ellipse(x, y, a/2., b/2., np.deg2rad(alpha), np.deg2rad(0))
ax.plot([x,x1],[y,y1], color='r',lw=1.1)
x2,y2 = ellipse(x, y, a/2., b/2., np.deg2rad(alpha), np.deg2rad(120))
ax.plot([x,x2],[y,y2], color='r',lw=1.1)
ax.set_aspect("equal")
plt.show()
| |
doc_311
|
when I use $locatoin.url('/ar/brand/علوم-الحاسب') it works great.
Now the url is :
/ar/brand/علوم-الحاسب
But when I refresh the page via browser reload button the url encoded and become /ar/brand/%25D8%25B9%25D9%2584%25D9%2588%25D9%2585-%25D8%25A7%25D9%2584%25D8%25AD%25D8%25A7%25D8%25B3%25D8%25A8
my questions:
1- Is this browser related issue, server related issue or Angular JS related issue?
2- How can I disable url encoding?
Note: I am using ngRoute module for routing.
Note: I am using Laravel framework as back-end API and the bootstrapping of Angular app is starting from index.blade.php file
Thanks in advance!
| |
doc_312
|
I used masonry for the ecommerce product categories for the responsive feature.
Now, I need to make the second row to float in center.
Q: Whats the best way to implement it?
It would be nice if the responsive feature is maintained in smaller screen sizes.
Here is my jquery code:
jQuery(window).on('load', function(){
var $ = jQuery;
/* Masonry */
var $container = $('.woo-cat ul.products');
// initialize
$container.masonry({
columnWidth:10,
itemSelector: '.product-category',
isAnimated: true,
isFitWidth: true
});
$container.masonry('reloadItems');
});
A: Best way to implement it? Don't use masonry at all - just use CSS. Your lucky because all your images are 300x300. Masonry is usually used to best arrange items into a grid when they are various sizes and traditionally floating arranges them awkwardly.
A simple example of being responsive and centered is here:
http://jsfiddle.net/aF7tP/
* { margin:0; padding:0; }
ul { list-style: none; text-align: center; font-size: 0;}
li { display: inline-block; font-size: 24px; position: relative; padding: 8px;}
img { display: block; margin: 0 auto; }
span { position: absolute; bottom:8px; left:8px; right:8px; padding: 8px; background: rgba(0,0,0,0.4); color: #fff; }
Your exact CSS will be dictated by exactly what you want, but don't miss the takeaway point - don't use Masonry, it's unnecessary (and detrimental) for your specific requirements.
| |
doc_313
|
class Bundle(models.Model):
name = models.CharField(max_length=100)
class Book(models.Model):
name = models.CharField(max_length=20)
isbn = models.CharField(max_length=13)
bundle = models.ForeignKey(Bundle)
we'll identify the bundles by concatenating the ISBN numbers with the delimiter like so:
123456788 & 123456789
To further export a list of available bundles for further processing we need that number.
I'm aware I could use:
for bundle in Bundle.objects.all():
complex_isbn = ' & '.join(bundle.book_set.all().values_list('isbn', flat=True))
But this would just be too slow for the real-world purpose.
Is there a way I could use annotate to accomplish this? If so, how? I'm struggling to find my way through the docs on how to accomplish concatenating multiple foreign key entries.
A: You can make use of the StringAgg aggregate function [Django-doc], which is only available for PostgreSQL. You thus can annotate the Bundles with the complex ISBN:
from django.contrib.postgres.aggregates import StringAgg
Bundle.objects.annotate(
complex_isbn=StringAgg('isbn', delimiter=' & ')
)
The Bundles that arise from this queryset will have an extra attribute .complex_isbn.
| |
doc_314
|
DATAFRAME 1 DATAFRAME 2
---------------- ----------------
letters | Count letters | Count
---------------- ----------------
ABC | 3 ABCDE | 5
DEFG | 4 WXYZAB | 6
AB | 2 AB | 2
YZ | 2 ABCDEFGHIJ | 10
---------------- ----------------
However, the distribution of count is not the same in every dataframe (ignoring the values in the example above). This is skewing performance in a downstream task. What I want to do is take advantage of the size disparity between the dataframes, and sample from the larger dataframes such that their distribution of count approximates to the target (smaller) dataframe. How do I go about this?
Something I had been thinking of is detailed here. Basically, we bin the target distribution (dataframe1['Count']) and use that to create a stratified subset using train_test_split. That seems like it would work, but appears to be a workaround given that I am not intended to create a train/test split in the data (although we could just be arguing over semantics here).
Is there a proper process/name/package that tackles this problem explicitly? I've been trying to understand kernel density estimators as a potential solution to this problem. Would that be an alternative way to approach this problem?
| |
doc_315
|
I have a UserControl (LoginUserControl.ascx) placed on a Default.aspx, which is in my Masterpage(Site.Master)...
Over the UserControl, the User can login...
Now I would like to set a global Variable, which won't change its Value, wherever I navigate...
A Variable like, IsLogged, (true/false).
Because I got problems with Viewstate and when I change an other Site (by Example to MyOtherSite.aspx), IsLogged is then false...
How can I do it?
A: If its depending on each user session. Write the Value in the Session.
Session["IsLogged"] = true;
| |
doc_316
|
val stream = KafkaUtils.createDirectStream(...)
stream.map(x=> Row(...))
.flatMap(r=> ... List[Row] )
.map(r=> (k,r))
.reduceByKey((r1, r2) => r)
.map { case (_, v) => v}
.foreachRDD { (rdd, time) => // write data}
When I look into the DAG the picture is as following
My question - as far as I understand spark should use a combiner for reduceByKey operation, that should significantly reduce the shuffle size. Why DAG doesn't show this, and how can I check that?
Additional question - if shuffle size is 2.5G does it hit disk? What configuration properties/metrics should I look into to check that job configured and run optimally.
For this job the executors run with 10G memory
A: First question: reduceByKey internally calls combineBykey. You will not see a difference on the DAG execution as a result, i.e. tasks the same.
2nd question, please make a new posting. Since you have not, Details for Stage, Shuffle Spill Disk should give you an indication.
| |
doc_317
|
Another surprise that when I try to reference the VB6 DLL from (in Excel) Tools -> Reference, i can reference it and I can access the Class/Functions, but still when I try to execute it, it says the same error about ActiveX.
what else do I need to do in Windows-10 to have it run ?
A: 32 bit programs can only load 32 bit dlls. 64 bit programs can only load 64 bit dlls. This is important. In COM which VB6 and Excel do, you can do non compatible bitness by forcing the wrong bitness dll into dllhost. All calls are marshalled with EXE servers. See https://learn.microsoft.com/en-us/windows/win32/com/registering-the-dll-server-for-surrogate-activation (note goggle sabotages searches for Windows).
| |
doc_318
|
var table = $('.table').DataTable({
"data":{{ data }},
"scrollX": true,
"fixedColumns": {
rightColumns: 1
},
But when I change the amount of entries to show, or the pagination I get a strange display error.
I tried to solve the error like this:
"initComplete": function(settings, json) {
table.fixedColumns().relayout();
and also like this:
$('.table').on( 'draw.dt', function() {
table.clear().draw();
});
A: Try to relayout on interval utilizing the fixedColumns().relayout() API
setTimeout(
function()
{
$.fn.dataTable.tables( { visible: false, api: true } ).columns.adjust().fixedColumns().relayout();
}, 1000);
| |
doc_319
|
However some evil spirits took over my app when I press OK button on the panel.
If I pick less than 10 files the NSOpenPanel doesn't close immediately however when I pick 11 or more it does. Perhaps those spirits are afraid of large amounts of files...
Here is how I Implemented the routine:
NSOpenPanel *panel = [NSOpenPanel openPanel];
[panel setCanChooseFiles:YES];
[panel setCanChooseDirectories:YES];
[panel setAllowsMultipleSelection:YES];
[panel setTitle:@"Open/Add"];
NSInteger clicked = [panel runModal];
if (clicked == NSFileHandlingPanelOKButton)
{
NSArray * urls = [panel URLs];
[panel orderOut:[self window]];
dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void)
{
//My routine here
});
Do you have any ideas ? or perhaps you know a good exorcist?!
Of course I want it to close immediately!
P.S. I also tried to dispatch after some period of time -> same behaviour
| |
doc_320
|
But, when I change the platform to x64 I get a COMException :
Retrieving the COM class factory for component with CLSID {830690FC-BF2F-47A6-AC2D-330BCB402664} failed due to the following error: 80040154 Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG)).
What is the problem here? Is this caused by the x86 development of Skype?
Is there any way to use this dll to a 64 bit solution platform?
A: You need x64 libraries for 64-bit based applications that are consuming them. Skype does not offer an 64 bit compatible library. It is not possible, to host x86 libraries within x64 processes.
For more information refer to this site:
http://community.skype.com/t5/Desktop-API-former-Public-API/64bit-Version-of-Skype4Com-dll/td-p/68234
Also AnyCPU won't work. About x64/x86-problems I suggest reading this article: http://blogs.msdn.com/b/rmbyers/archive/2009/06/09/anycpu-exes-are-usually-more-trouble-then-they-re-worth.aspx
A: As @Aschratt already stated, it is by no mean possible to host 32-bit dll in 64-bit process.
If it is absolutely necessary for you to have your application 64bit, you can run Skype dll in separate 32 process, and communicate with it using (for example) named pipes (netnamedpipebinding). Although, I would avoid such solution if it is possible to leave your process 32bit.
| |
doc_321
|
I got this failure message:
PLATFORM_VERSION_CODENAME=REL
PLATFORM_VERSION=9
TARGET_PRODUCT=omni_beryllium
TARGET_BUILD_VARIANT=userdebug
TARGET_BUILD_TYPE=release
TARGET_ARCH=arm64
TARGET_ARCH_VARIANT=armv8-a
TARGET_CPU_VARIANT=kryo300
TARGET_2ND_ARCH=arm
TARGET_2ND_ARCH_VARIANT=armv8-a
TARGET_2ND_CPU_VARIANT=cortex-a75
HOST_ARCH=x86_64
HOST_2ND_ARCH=x86
HOST_OS=linux
HOST_OS_EXTRA=Linux-4.9.0-8-amd64-x86_64-Debian-GNU/Linux-9-(stretch)
HOST_CROSS_OS=windows
HOST_CROSS_ARCH=x86
HOST_CROSS_2ND_ARCH=x86_64
HOST_BUILD_TYPE=release
BUILD_ID=PQ2A.190205.001
OUT_DIR=/home/benjamin/OMNI/out
============================================
ninja: no work to do.
ninja: no work to do.
wildcard(/home/benjamin/OMNI/out/target/product/beryllium/clean_steps.mk) was changed, regenerating...
wildcard(vendor/xiaomi/whyred/Android.mk) was changed, regenerating...
[24/971] including development/build/Android.mk ...
development/build/build_android_stubs.mk:43: warning: android_stubs_current
development/build/build_android_stubs.mk:43: warning: metalava_android_stubs_current metalava_android_stubs_current
development/build/build_android_stubs.mk:43: warning: android_system_stubs_current
development/build/build_android_stubs.mk:43: warning: android_test_stubs_current
development/build/build_android_stubs.mk:43: warning: metalava_android_system_stubs_current metalava_android_system_stubs_current
development/build/build_android_stubs.mk:43: warning: metalava_android_test_stubs_current metalava_android_test_stubs_current
[539/971] including system/sepolicy/Android.mk ...
system/sepolicy/Android.mk:79: warning: BOARD_SEPOLICY_VERS not specified, assuming current platform version
[971/971] including vendor/xiaomi/tissot/Android.mk ...
build/make/core/base_rules.mk:412: warning: overriding commands for target `/home/benjamin/OMNI/out/target/product/beryllium/root/res/images/charger/battery_fail.png'
build/make/core/base_rules.mk:412: warning: ignoring old commands for target `/home/benjamin/OMNI/out/target/product/beryllium/root/res/images/charger/battery_fail.png'
build/make/core/base_rules.mk:412: warning: overriding commands for target `/home/benjamin/OMNI/out/target/product/beryllium/root/res/images/charger/battery_scale.png'
build/make/core/base_rules.mk:412: warning: ignoring old commands for target `/home/benjamin/OMNI/out/target/product/beryllium/root/res/images/charger/battery_scale.png'
build/make/core/Makefile:28: warning: overriding commands for target `/home/benjamin/OMNI/out/target/product/beryllium/system/etc/mkshrc'
build/make/core/base_rules.mk:412: warning: ignoring old commands for target `/home/benjamin/OMNI/out/target/product/beryllium/system/etc/mkshrc'
ninja: error: '/home/benjamin/OMNI/out/target/common/obj/JAVA_LIBRARIES/WfdCommon_intermediates/classes.jar', needed by '/home/benjamin/OMNI/out/target/common/obj/PACKAGING/boot-jars-package-check_intermediates/stamp', missing and no known rule to make it
14:54:42 ninja failed with: exit status 1
#### failed to build some targets (02:22 (mm:ss)) ####
Can somebody help me, how to fix it?
A: You are missing the Wfd common jars in your tree most probably. Try picking this commit and add relevant Wfd common libs to see whether it works or not
| |
doc_322
|
This works but now I need to productionize this code and really need to make it more resilient to a crash - i.e. i need to restart the service if it fails.
My options as far as I can see them are....
*
*Run the node service on a linux box and then stdout should work when it's running as a daemon
*Somehow make a windows service be able to "see" stdout
*Create a separate node server (running under nssm) that can monitor the service and restart it if it fails
So far, I would like to avoid options one if possible due to additional hosting hosts. I cant find anything that will help with option two, it looks like windows services just don't work like that.
So today I attempted to create a monitor service that could restart the crashed service if it didnt respond to a heartbeat. The problem is I cant seem to work out how to start a completely independent node server from within another instance node. If I were to use child process then it it is still a child process of a service and stdout dosent work.
So, is it possible to create an independent process in node? Are there any other suggestions for dealing with this problem?
A: A child process is still an independent process, but by default, the stdin streams are still attached to the parent, so when the parent process dies, the child does as well. To avoid this from happening, run the child process as detached. Here's an example from the documentation:
var fs = require('fs');
var spawn = require('child_process').spawn;
var out = fs.openSync('./out.log', 'a');
var err = fs.openSync('./out.log', 'a');
var child = spawn('cmd', [], {
detached: true,
stdio: [ 'ignore', out, err ]
});
child.unref();
The child.unref() method is for removing references to the child in its event loop. That way, the parent won't wait for the child to exit in order to exit itself. Also note that when you use the detached option, you still have to disassociate the child's stdin streams with the parent, or it stays attached.
| |
doc_323
|
Main CPP
#include <iostream>
#include "Header.h"
using namespace std;
int main()
{
node access;
access.getData();
access.outData();
system("pause");
return 0;
}
Header File
#include <iostream>
using namespace std;
class node
{
public:
node(); // Had to create my own default constructor because of my copy constructor.
node(const node &n); // This is a copy constructor.
~node();
void getData();
void outData();
private:
int num;
int lCount = 0; // Counts the number of nodes, increments after each user input.
int *ptr; // Where the linked list will be copied into
node *next;
node *first;
node *temp;
node *point;
};
node::node()
{
num = 0;
}
node::node(const node &n)
{
temp = first;
ptr = new node;
for (int i = 0; i < lCount; i++)
{
ptr[i] = temp->num;
temp = temp->next;
}
}
node::~node() // Deletes the linked list.
{
while (first != NULL)
{
node *delP = first; // Creates a pointer delP pointing to the first node.
first = first->next; // "Removes first node from the list and declares new first.
delete delP; // Deletes the node that was just removed.
}
cout << "List deleted" << endl;
}
void node::getData() // Simple function that creates a linked list with user input.
{
int input = 0;
point = new node;
first = point;
temp = point;
while (input != -1)
{
cout << "Enter any integer, -1 to end." << endl;
cin >> input;
if (input == -1)
{
point->next = NULL;
break;
}
else
{
lCount++;
point->num = input;
temp = new node;
point->next = temp;
point = temp;
}
}
}
void node::outData()
{
temp = first;
cout << "Original" << endl;
while (temp->next != NULL)
{
cout << temp->num << endl;
temp = temp->next;
}
cout << "Copied" << endl;
for (int i = 0; i < lCount; i++)
{
cout << ptr[i] << endl;
}
}
This little snippet is what I am having trouble with in particular:
node::node(const node &n)
{
temp = first;
ptr = new node;
for (int i = 0; i < lCount; i++)
{
ptr[i] = temp->num;
temp = temp->next;
}
}
A: I figured it out! I was tinkering with a much simpler copy constructor. I was having trouble understanding syntax, everything was very complicated and it was overwhelming to look at.
#include <iostream>
using namespace std;
class node
{
public:
node(int x); // Normal Construtor
node(const node &cpy); // Copy Constructor
void change(); // Changes data value
void outData();
private:
int data;
};
int main()
{
node var1(123);
var1.outData();
node var2 = var1;
var2.outData();
var2.change();
var1.outData();
var2.outData();
system("pause");
return 0;
}
node::node(int x)
{
data = x;
}
node::node(const node &cpy)
{
data = cpy.data;
}
void node::outData()
{
cout << data << endl;
}
void node::change()
{
int userIn;
cin >> userIn;
data = userIn;
}
Output:
123
123
(input: 4444)
Output:
123
4444
| |
doc_324
|
I can access duckling from browser as well as postman but in rasa logs I get this error:
`rasa4 | 2023-01-05 10:16:01 ERROR`
rasa.nlu.extractors.duckling_entity_extractor - Failed to connect to duckling http server. Make sure the duckling server is running/healthy/not stale and the proper host and port are set in the configuration.
More information on how to run the server can be found on github: https://github.com/facebook/duckling#quickstart Error: HTTPConnectionPool(host='localhost', port=8000): Max retries exceeded with url: /parse (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7fb33c0733a0>: Failed to establish a new connection: [Errno 111] Connection refused'))
this is my config.yml file:
# The config recipe.
# https://rasa.com/docs/rasa/model-configuration/
recipe: default.v1
# Configuration for Rasa NLU.
# https://rasa.com/docs/rasa/nlu/components/
language: en
pipeline:
# # No configuration for the NLU pipeline was provided. The following default pipeline was used to train your model.
# # If you'd like to customize it, uncomment and adjust the pipeline.
# # See https://rasa.com/docs/rasa/tuning-your-model for more information.
- name: WhitespaceTokenizer
- name: RegexFeaturizer
- name: LexicalSyntacticFeaturizer
- name: CountVectorsFeaturizer
- name: CountVectorsFeaturizer
analyzer: char_wb
min_ngram: 1
max_ngram: 4
- name: DIETClassifier
epochs: 100
constrain_similarities: true
- name: EntitySynonymMapper
- name: ResponseSelector
epochs: 100
constrain_similarities: true
- name: FallbackClassifier
threshold: 0.3
ambiguity_threshold: 0.1
- name: "DucklingHTTPExtractor"
# url of the running duckling server
url: "http://0.0.0.0:8000"
# dimensions to extract
dimensions: ["time", "number", "amount-of-money", "distance"]
# Configuration for Rasa Core.
# https://rasa.com/docs/rasa/core/policies/
policies:
# # No configuration for policies was provided. The following default policies were used to train your model.
# # If you'd like to customize them, uncomment and adjust the policies.
# # See https://rasa.com/docs/rasa/policies for more information.
# - name: MemoizationPolicy
# - name: RulePolicy
# - name: UnexpecTEDIntentPolicy
# max_history: 5
# epochs: 100
# - name: TEDPolicy
# max_history: 5
# epochs: 100
# constrain_similarities: true
I have installed docker on linux and followed all steps mentioned in rasa docker installation instructions
| |
doc_325
|
So, my current procedure is:
*
*Reading all the rows from the table and creating a set of tuples, calling it old_data
*Reading all the rows from the csv and creating another set of tuples, calling it new data.
So, old_data - new_data gives me all the objects that have been deleted and updated.
Similarly, new_data - old_data gives me all the objects that have been inserted and also updated.
So, objects with primary key in both the above differences are the ones which will be used for updating.
Rest are deleted and inserted accordingly.
Now, this is not a Django way of doing it. (I'm comparing the two sets of tuples, not the model objects itself)
Can this be done by comparing the model objects somehow.
Update:
I'm creating hash of the object by overriding the __hash__ function. That has given me some lead. Again, can this be further improved?
| |
doc_326
|
But whenever I started server with debugging mode on vscode, It seems cannot resolve my tsconfig's path and throwing error cannot find module 'my absolute module path'. here is my tsconfig.json file and package.json file
tsconfig.json
{
"compilerOptions": {
"outDir": "./dist",
"moduleResolution": "node",
"sourceMap": true,
"module": "commonjs",
"allowJs": true,
"target": "es5",
"noUnusedParameters": false,
"allowUnreachableCode": true,
"allowUnusedLabels": true,
"lib": [
"es2015"
],
"baseUrl": ".",
"paths": {
"@routes": [
"src/routes/*"
],
"@client": [
"../client/*"
]
},
}
}
package.json - scripts
"scripts": {
"test": "jest --watchAll --runInBand",
"coverage": "jest --coverage",
"start": "ts-node -r tsconfig-paths/register src/index.ts",
"server": "./node_modules/nodemon/bin/nodemon.js",
"client": "npm start --prefix ../client",
"dev": "concurrently \"npm run server\" \"npm run client\""
},
note that I attach "tsconfig-paths/register" on npm start script. and here is my debugging mode setting in launch.json
launch.json
{
"name": "TS File",
"type": "node",
"request": "launch",
"args": [
"${workspaceRoot}/server/src/index.ts"
],
"runtimeArgs": [
"--nolazy",
"-r",
"ts-node/register"
],
"cwd": "${workspaceRoot}/server",
"protocol": "inspector",
"internalConsoleOptions": "openOnSessionStart",
"console": "integratedTerminal"
}
How can I set dubugging mode to resolve my tsconfig.json's path. and is there any way to use absolute path with vscode debugger? (I've tried put "tsconfig-paths/register" on "runtimeArgs" but did not work)
A: To get this to work, you need to tell VS Code where the root path is by setting the NODE_PATH environment variable. Since you're outputing the compiled JavaScript code into the dist folder, set the env NODE_PATH variable as follows in launch.json:
{
"version": "0.2.0",
"configurations": [
{
"type": "pwa-node",
"request": "launch",
"name": "Launch Program",
"skipFiles": ["<node_internals>/**"],
"program": "${workspaceFolder}/src/index.ts",
"preLaunchTask": "tsc: build - tsconfig.json",
"outFiles": ["${workspaceFolder}/dist/**/*.js"],
"env": {
"NODE_PATH": "dist/"
}
}
]
}
| |
doc_327
|
- (void) drawImage2
{
UIImage * demoImage = self.imageCopy;
NSData *jpegData = UIImageJPEGRepresentation(demoImage, 0.80);
CGDataProviderRef dp = CGDataProviderCreateWithCFData(( CFDataRef)jpegData);
CGImageRef cgImage = CGImageCreateWithJPEGDataProvider(dp, NULL, true, kCGRenderingIntentDefault);
[[UIImage imageWithCGImage:cgImage] drawInRect:CGRectMake(513, 314, 135, 135)];
}
Any suggestions for how I can do this? I know how to do it using CALayers with a UIImageView, but not sure here since I don't have the view.
A: - (UIImage*)imageWithBorderFromImage:(UIImage*)source;
{
CGSize size = [source size];
UIGraphicsBeginImageContext(size);
CGRect rect = CGRectMake(0, 0, size.width, size.height);
[source drawInRect:rect blendMode:kCGBlendModeNormal alpha:1.0];
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetRGBStrokeColor(context, 1.0, 0.5, 1.0, 1.0);
CGContextStrokeRect(context, rect);
UIImage *testImg = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return testImg;
}
| |
doc_328
|
This is my task – Converting a bunch of custom built LaTeX files to into InDesign. So my current method is: run the .tex files through a PHP script that changes the custom LaTeX codes to more generic TeX codes, then I'm using TeX2Word to convert them to .doc files, and then placing those into InDesign.
What I'm wanting to do with this preg_replace is convert a few of the TeX tags so they won't be touched by TeX2Word, then I'll be able to run a script in InDesign that changes the HTML-like tags to InDesign text frames, footnotes, variables and such.
[/UPDATED]
I have some text with LaTeX markup in it:
$newphrase = "\blockquote{\hspace*{.5em}Lorem ipsum dolor sit amet, consectetur
adipiscing elit. Integer posuere erat a ante venenatis dapibus posuere
velit aliquet. Aenean lacinia bibendum nulla sed consectetur. Aenean
eu leo quam. Pellentesque ornare sem lacinia quam venenatis
vestibulum. Sed posuere consectetur est at lobortis. \note{Integer
posuere erat a ante venenatis dapibus posuere velit aliquet.
\textit{Vivamus} sagittis lacus vel augue laoreet rutrum faucibus
dolor auctor.}}";
What I want to do is remove \blockquote{...} and replace it with <div>...</div>
So I've tried a jillion different versions of this:
$regex = "#(blockquote){(.*)(})#";
$replace = "<div>$2</div>";
$newphrase = preg_replace($regex,$replace,$newphrase);
This is the output
\<div>\hspace*{.5em</div>Lorem ipsum dolor sit amet, consectetur
adipiscing elit. Integer posuere erat a ante venenatis dapibus posuere
velit aliquet. Aenean lacinia bibendum nulla sed consectetur. Aenean
eu leo quam. Pellentesque ornare sem lacinia quam venenatis
vestibulum. Sed posuere consectetur est at lobortis. \note{Integer
posuere erat a ante venenatis dapibus posuere velit aliquet.
\textit{Vivamus} sagittis lacus vel augue laoreet rutrum faucibus
dolor auctor.}}";
The first problem with it is that it replaces everything from \blockquote{ to the first }.
When I want it to ignore the next } if there has been another { after the initial \blockquote{.
The next problem I'm having is with the \ I can't seem to escape it! I've tried \\, /\\/, \\\, /\\\/, [\], [\\]. Nothing works! I'm sure it's because I don't understand how it really IS suposed to work.
So finally, This is what I want to end up with:
<div>\hspace*{.5em}Lorem ipsum dolor sit amet, consectetur
adipiscing elit. Integer posuere erat a ante venenatis dapibus posuere
velit aliquet. Aenean lacinia bibendum nulla sed consectetur. Aenean
eu leo quam. Pellentesque ornare sem lacinia quam venenatis
vestibulum. Sed posuere consectetur est at lobortis. \note{Integer
posuere erat a ante venenatis dapibus posuere velit aliquet.
\textit{Vivamus} sagittis lacus vel augue laoreet rutrum faucibus
dolor auctor.}</div>";
I'm planning to make $regex & $replace into arrays, so I can replace things like \textit{Vivamus} with this <em>Vivamus</em>
Any guidance would be MUCH welcomed and appreciated!
A: If you still want to do the conversion yourself, you can do it using multiple passes thru the string, replacing the inner elements first:
$t = '\blockquote{\hspace*{.5em}Lorem ipsum dolor sit amet, consectetur
adipiscing elit. Integer posuere erat a ante venenatis dapibus posuere
velit aliquet. Aenean lacinia bibendum nulla sed consectetur. Aenean
eu leo quam. Pellentesque ornare sem lacinia quam venenatis
vestibulum. Sed posuere consectetur est at lobortis. \note{Integer
posuere erat a ante venenatis dapibus posuere velit aliquet.
\textit{Vivamus} sagittis lacus vel augue laoreet rutrum faucibus
dolor auctor.}}';
function hspace($m) { return "<br />"; }
function textit($m) { return "<i>" . $m[1] . "</i>"; }
function note($m) { return "<b>" . $m[1] . "</b>"; }
function blockquote($m) { return "<quote>" . $m[1] . "</quote>"; }
while (true) {
$newt = $t;
$newt = preg_replace_callback("/\\\\hspace\\*\\{([^{}]*?)\\}/", "hspace", $newt);
$newt = preg_replace_callback("/\\\\textit\\{([^{}]*?)\\}/", "textit", $newt);
$newt = preg_replace_callback("/\\\\note\\{([^{}]*?)\\}/", "note", $newt);
$newt = preg_replace_callback("/\\\\blockquote{([^{}]*?)\\}/", "blockquote", $newt);
if ($newt == $t) break;
$t = $newt;
}
echo $t;
But of course, this might work for simple examples, but you cannot use this method to correctly parse the whole TeX format. Also it gets very ineffective for longer inputs.
A: As suggested above, you can use a dedicated LaTeX to HTMl converter such as: SimpleTex4ht.
| |
doc_329
|
I'm relative new to ldap and look for a good reference and quickstart. I want to configure OpenLDAP on an debian system for a sogo, exim, dovecot driven mail server.
A: Looks like I would have been heard. Here is an excellent article about this: http://www.rjsystems.nl/en/2100-d6-openldap-provider.php
| |
doc_330
|
My website is an ASP.net site, so any solution must be compatible with that.
A CSS/JS only solution would be ideal.
I do not need any preview, display or execution ability, simple code color coding in a text editor (textarea?) is all that is required. Commenting highlighting and line numbers would be very nice to have too.
Sorry if this is a duplicate, I found several similar questions, but I still have not found an answer.
Thanks!
A: Check out the list of editors on Wikipedia’s comparison of JavaScript-based source code editors.
I think the most popular editors in that list are Ace and CodeMirror.
| |
doc_331
|
Here is tables:
t1 <- data.table(ID = c(1:6), gender = c("m", "m", "m", "m", "f", "f"), w = c(1:3))
t2 <- data.table(gender = c("m", "f", NA), w = c(1, 2, 3), z = c(4, 2, 3))
A: We can use a non-equi join
library(data.table)
setDT(t1)[t2, .SD, on = .(gender, weight <= weight)]
If we are also interested in the 'z' column
setDT(t1)[t2, c(.SD, .(z = z)), on = .(gender, w <= w), nomatch = FALSE]
# ID gender w z
#1: 1 m 1 4
#2: 4 m 1 4
#3: 5 f 2 2
| |
doc_332
|
I have a QPushButton named btnStart on mi ClassA.ui
and in the header file ClassA.h:
private slots:
void on_btnQuit_clicked();
and when I clicked the button btnStart enter on the slot on_btnQuit_clicked(), but I dont connect anything.
classA.h
class classA : public QDialog
{
Q_OBJECT
public:
classA( QWidget *parent = 0 );
~classA();
private:
Ui::classA* m_ui;
private slots:
void on_btnStart_clicked();
};
classA.cpp
#include "ClassA.h"
#include "ui_ClassA.h"
ClassA::ClassA( QWidget *parent ):
QDialog( parent ),
m_ui( new Ui::classA )
{
m_ui->setupUi( this );
}
ClassA::~ClassA()
{
SWT_DENULL( m_ui );
}
void ClassA::on_btnStart_clicked()
{
//here
}
classA.ui
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>classA</class>
<widget class="QDialog" name="classA">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>667</width>
<height>433</height>
</rect>
</property>
<property name="windowTitle">
<string>title</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<layout class="QHBoxLayout" name="horizontalLayout_2">
<item>
<widget class="QPushButton" name="btnStart">
<property name="text">
<string>Start title</string>
</property>
</widget>
</item>
</layout>
</item>
</layout>
</widget>
<layoutdefault spacing="6" margin="11"/>
<resources/>
<connections/>
</ui>
A: Qt has an auto-connect feature that connects the slots named like this: on_UIELEMENTNAME_SIGNALNAME(SIGNAL_PARAMS) with the corresponding signal, see the doc here
| |
doc_333
|
how do I write this function:
if B2=BUY AND L2 is greater than 0 write positive OR if B2=BUY AND L2 is less than 0 write negative OR if B2 = SELL write nothing
A: Quite easy:
=IF(AND(B2="BUY",0<L2),"positive",IF(AND(B2="BUY",L2<0),"negative",IF(B2="SELL","","L2 equals 0 or B2 contains an unexpected value")))
Note that even though your sentence contains 'OR' many times, the formula does not because for this purpose you don't need an 'OR'. What you describe with 'OR' in your sentence is actually an ELSE.
| |
doc_334
|
I initialize the array like this:
Dim riskDict As New Scripting.Dictionary
riskDict.Add "Weight", Array("WP", 0, Array())
And I have a function, 'getTheRisk', which returns an X by 4 array (Its a SOAP request. I do not know how many results will come back, but it will be four values returned for each result.)
I would like to then store that result into the third element of the item in my dictionary, attempted like this:
For i = 0 To riskDict.count - 1
riskDict.Items(i)(2) = getTheRisk(myDate.Value, myPort.Value, riskDict.Items(i)(0))
Next i
This compiles and runs just fine, but after assigning the array, it shows up as empty in the dictionary:
The getTheRisk function returns something like the following:
How do I set the array in the dict to be the results of the SOAP request?
A: I found a workaround. I initialize the items with only two elements, then redim and add the third as I send the SOAP requests and get the results. I initialize as follows:
Dim riskDict As New Scripting.Dictionary
riskDict.Add "Weight", Array("WP", 0)
And for my loop:
For Each key In riskDict
temp = riskDict(key)
ReDim Preserve temp(UBound(temp) + 1)
temp(UBound(temp)) = getTheRisk(myDate.Value, myPort.Value, riskDict(key)(0))
riskDict(key) = temp
Next key
This is less than ideal, since the redim preserve. (And it just doesn't seem very elegant.) However, this dict is only about 8-10 items long, so it should not cause too much of a performance hit.
If you have any better solutions, please feel free to comment or post them.
Thanks all!
| |
doc_335
|
class User < ActiveRecord::Base
attr_accessible :password, :username, :oauth_token, :provider, :uid, :oauth_expires_at, :picture, :email, :name
def self.from_omniauth(auth)
where(auth.slice(:provider, :uid)).first_or_initialize.tap do |user|
user.provider = auth.provider
user.uid = auth.uid
user.name = auth.info.name
user.username = auth.extra.username
user.email = auth.info.email
user.picture = auth.info.image
user.oauth_token = auth.credentials.token
user.oauth_expires_at = Time.at(auth.credentials.expires_at)
user.save!
end
end
end
A: You can use dragonfly or imagery to play with images once you download or use css to display the image in a different size on the page.
A: Solution
You can set in devise.rb the following attribute:
provider :facebook, ENV['APP_ID'], ENV['APP_SECRET'],
scope: 'email,user_birthday,read_stream', image_size: 'large'
The options for image_size are the following, I am quoting the Wiki from Facebook Omniauth. The link is below.
For setting the image to a specific size I would use Css property height, additionally you will need to delete the account and restart the server to get the image-link in the new size format, because the call to the def self.from_omniauth(auth) is only performed when the user creates the account.
Set the size for the returned image url in the auth hash. Valid options include square (50x50), small (50 pixels wide, variable height), normal (100 pixels wide, variable height), or large (about 200 pixels wide, variable height). Additionally, you can request a picture of a specific size by setting this option to a hash with :width and :height as keys. This will return an available profile picture closest to the requested size and requested aspect ratio. If only :width or :height is specified, we will return a picture whose width or height is closest to the requested size, respectively.
https://github.com/mkdynamic/omniauth-facebook
| |
doc_336
|
When I have blog.permalink = ":year-:month-:day-:title" in the config.rb file, the output is mysite.com/2014-01-16-HelloWorld/ and file can not be found. For some reason it ignores blog.prefix = "blog".
When it is like blog.permalink = "{year}-{month}-{day}-{title}", it links to post but the url is mysite.com/blog/%7Byear%7D-%7Bmonth%7D-%7Bday%7D-%7Btitle%7D/.
Here is what's in the blog section of the config.rb:
activate :blog do |blog|
blog.prefix = "blog"
blog.permalink = ":year-:month-day-:title"
blog.layout = "blog/_post"
blog.default_extension = ".markdown"
blog.summary_separator = /SPLIT_SUMMARY_BEFORE_THIS/
end
Is there something I'm doing wrong?
Any help would be appreciated.
Thanks!!
A: Try with blog.permalink = ":year-:month-:day:title.html" (or remove the .html if you are using directory indexes).
| |
doc_337
|
CSS:
.photo_container {
width: 250px;
height: 250px;
overflow: hidden;
border-style: solid;
border-color: green;
float:left;
margin-right:10px;
position: relative;
}
.photo_container a img{
position:absolute;
}
HTML
<!--p>Photo's height>width </p-->
<div class="photo_container">
<a href="#">
<img class="photo" src="https://upload.wikimedia.org/wikipedia/commons/thumb/5/57/ECurtis.jpg/224px-ECurtis.jpg"
style="width:100%; height:auto;">
</img>
</a>
</div>
<!--p>Photo's width>height </p-->
<div class="photo_container">
<a href="#">
<img class="photo" src="https://upload.wikimedia.org/wikipedia/commons/thumb/c/c8/Altja_j%C3%B5gi_Lahemaal.jpg/220px-Altja_j%C3%B5gi_Lahemaal.jpg"
style="width:auto; height:100%;left=-100px">
</img>
</a>
</div>
Javascript:
// fix image size on load
$(".photo").one("load", function() {
fixImage($(this));
}).each(function() {
if(this.complete) $(this).load();
});
// Just to test if everything's working fine
$(".photo").on("click",function(){
var rand = Math.floor(Math.random() * 200) + 80;
$(this).parent().parent().width(rand);
$(this).parent().parent().height(rand);
fixImage($(this));
});
// Brings the photo dead center
function fixImage(obj){
//alert("something changed");
var pw = obj.parent().parent().width();
var ph = obj.parent().parent().height();
var w = obj.width();
var h = obj.height();
console.log(w+" "+pw);
if(h>w){
var top = (h-ph)/2;
obj.css("top",top*-1);
}else{
var left = (w-pw)/2;
obj.css("left",left*-1);
}
}
Working example: http://jsfiddle.net/vL95x81o/4
How can this be done without using jquery but only CSS? If the size of the div never changes, this solution is fine. But I'm looking into responsive designs and seems like the size of the photo_container div might need to change (via CSS) based on the size of the screen.
Here are the photos before being cropped:
A: You could do something like this:
http://jsfiddle.net/vL95x81o/5/
<!--p>Photo's height>width </p-->
<div class="photo_container">
<div class="photo photo--1">
</div>
</div>
<!--p>Photo's width>height </p-->
<div class="photo_container">
<div class="photo photo--2">
</div>
</div>
.photo_container {
width: 250px;
height: 250px;
overflow: hidden;
border-style: solid;
border-color: green;
float:left;
margin-right:10px;
position: relative;
}
.photo {
height: 100%;
width: 100%;
}
.photo--1 {
background: url('https://upload.wikimedia.org/wikipedia/commons/thumb/5/57/ECurtis.jpg/224px-ECurtis.jpg') no-repeat center center;
background-size: cover;
}
.photo--2 {
background: url('https://upload.wikimedia.org/wikipedia/commons/thumb/c/c8/Altja_j%C3%B5gi_Lahemaal.jpg/220px-Altja_j%C3%B5gi_Lahemaal.jpg') no-repeat center center;
background-size: cover;
}
I have changed the imgs to divs with background images and used background position cover with the image being centered.
A: The background solution that others have posted was my initial thought, but if you want to still use images then you could do the following:
CSS:
.photo_container {
width: 250px;
height: 250px;
overflow: hidden;
border-style: solid;
border-color: green;
float:left;
margin-right:10px;
position: relative;
}
.photo_container img {
min-width: 100%;
min-height: 100%;
position: relative;
top: 50%;
left: 50%;
transform: translateY(-50%) translateX(-50%);
}
HTML:
<div class="photo_container">
<a href="#">
<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/5/57/ECurtis.jpg/224px-ECurtis.jpg" />
</a>
</div>
<div class="photo_container">
<a href="#">
<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/c/c8/Altja_j%C3%B5gi_Lahemaal.jpg/220px-Altja_j%C3%B5gi_Lahemaal.jpg" />
</a>
</div>
This will make any image inside to be either 100% high or 100% wide, depending on the shortest attribute, and centralise them horizontally and vertically.
Edit
It's worth noting that transform is not supported in IE8 or Opera Mini - http://caniuse.com/#feat=transforms2d
A: Use background images.
.photo_container {
width: 250px;
height: 250px;
overflow: hidden;
border-style: solid;
border-color: green;
float:left;
margin-right:10px;
position: relative;
}
.photo_container a{
/* Set the background size to cover to scale the image */
background-size: cover;
/* Position the image in the center */
background-position: 50% 50%;
background-repeat: no-repeat;
position:absolute;
width: 100%;
height: 100%;
}
<!--p>Photo's height>width </p-->
<div class="photo_container">
<a href="#" style="background-image: url(https://upload.wikimedia.org/wikipedia/commons/thumb/5/57/ECurtis.jpg/224px-ECurtis.jpg);">
</a>
</div>
<!--p>Photo's width>height </p-->
<div class="photo_container" >
<a href="#" style="background-image: url(https://upload.wikimedia.org/wikipedia/commons/thumb/c/c8/Altja_j%C3%B5gi_Lahemaal.jpg/220px-Altja_j%C3%B5gi_Lahemaal.jpg);">
</a>
</div>
A: I solved this without using background-images or JS. The height comes from the before tag in the container. The 100% of the padding equals 100% of the widht. So the height has always the same width.
http://jsfiddle.net/a1rLeq06/
<!--p>Photo's height>width </p-->
<div class="photo_container">
<a href="#">
<img class="photo" src="https://upload.wikimedia.org/wikipedia/commons/thumb/5/57/ECurtis.jpg/224px-ECurtis.jpg"
style="width:100%; height:auto;">
</img>
</a>
</div>
<!--p>Photo's width>height </p-->
<div class="photo_container">
<a href="#">
<img class="photo" src="https://upload.wikimedia.org/wikipedia/commons/thumb/c/c8/Altja_j%C3%B5gi_Lahemaal.jpg/220px-Altja_j%C3%B5gi_Lahemaal.jpg"
style="width:auto; height:100%;left=-100px">
</img>
</a>
</div>
The css:
.photo_container {
width: 20%;
display: inline-block;
overflow: hidden;
position: relative;
margin: 10px 0;
}
.photo_container:before {
content: '';
display: block;
padding-top: 100%;
}
.photo {
position: absolute;
top: 0;
right: 0;
left: 0;
bottom: 0;
}
| |
doc_338
|
In order to start running the tests I run a bat file.
This bat file produces an error, prints it, and keeps running until it finishes.
When running the bat file using Jenkins, the job hangs at the same point the error suppose to be printed.
How can I tell Jenkins to ignore the error and just keep going?
This is the error from the cmd manuall run, and as you can see it keeps running after the error:
Waiting for comreader to complete
Error executing test harness to detect type and range data
>>>
>>> This might indicate a problem starting the harness execution or
>>> capturing output data from your simulator or hardware target.
>>> If the current configuration can be used successfully with other
>>> environments, then there might be an execution problem related
>>> to the code in this environment.
Determining Basis Paths (LinearAlgebra)
Determining Basis Paths (MathUtils)
| |
doc_339
|
/usr/src/app/node_modules/mongoose/node_modules/mongodb/lib/server.js:265
process.nextTick(function() { throw err; })
^
MongoError: failed to connect to server [127.0.0.1:27017] on first connect
at null.<anonymous> (/usr/src/app/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/topologies/server.js:325:35)
at emitOne (events.js:77:13)
at emit (events.js:169:7)
at null.<anonymous> (/usr/src/app/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/connection/pool.js:270:12)
at g (events.js:260:16)
at emitTwo (events.js:87:13)
at emit (events.js:172:7)
at Socket.<anonymous> (/usr/src/app/node_modules/mongoose/node_modules/mongodb/node_modules/mongodb-core/lib/connection/connection.js:173:49)
at Socket.g (events.js:260:16)
at emitOne (events.js:77:13)
at Socket.emit (events.js:169:7)
at emitErrorNT (net.js:1269:8)
at nextTickCallbackWith2Args (node.js:458:9)
at process._tickCallback (node.js:372:17)
My app.js is listening in on port 8080 and i exposed port 8080 and 27017 on dockerfile. May i know what else should i be doing to resolve the error. I am a beginner on this, pardon me.
A: you only expose 8080 and that's why it couldn't connect to 27017!
instead of -p 8080:8080 use -P to expose 27017 too!
so you're build command would be this:
docker run -P -d ryan/edocker
| |
doc_340
|
A label named lblTtlMaximize is intended to change the size of the userform on click.
This Userform starts with width = 455,25 and height = 1023,75 (set in the properties box)
Following code does only change the position, but not the height neither the width:
Private Sub lblTtlMaximize_Click()
frmVorlage.Height = 1080
frmVorlage.Width = 1920
frmVorlage.Top = 0
frmVorlage.Left = 0
End Sub
*
*Made sure the sub is executed by putting in "Debug.Print frmVorlage.Height" => Shows 1080 but the actual height of the userform is not changed
*If i put the same code in the initialize event it works and the Userform starts with width 1920 and height 1080
*Me.Width and Me.Height does not work either
I am out of ideas how to fix this, since the .Top and .Left properties are changed on click but the .Height and .Width are not...
A: If you use the form correctly, that is to say you let the user work with a new instance of your frmVorlage form, you will want to set the instance properties using the Me keyword.
Sub ShowMyForm()
Dim uf As frmVorlage
Set uf = New frmVorlage
uf.Show
End Sub
Form Code
Private Sub lblTtlMaximize_Click()
Me.Height = 1080
Me.Width = 1920
Me.Top = 0
Me.Left = 0
End Sub
If you set frmVorlage properties, you are actually just setting the form class's properties. You can see that if you show the form class (frmVorlage.Show), rather than an instance of the form, then your OnClick method works as you have it.
| |
doc_341
|
A: No, you can use big parts of it on Linux and Windows as well.
Most of the iOS stuff will only work on macOS, as the tools being used in the background (xcodebuild etc.) are only available on macOS. But for example creating apps in the Apple Developer Console or uploading apps to App Store Connect will work on all operating systems.
(Fastlane is currently working on improving and stabilizing that support for other operating systems, so expect this to get better over time)
A: You can use "parts" of Fastlane on Windows, for example is not possible of doing screenshots and, of course, anything related to iOS.
You'll probably have to do use some Ubuntu subsystem or a docker if you want to work with Windows.
You should have no problem in Linux.
| |
doc_342
|
I'm trying to force a "time" input tag to allow only minutes and seconds to enter.
The desired format would be MM:SS (without Hour and AM/PM).
So far the only way I've found was using the following code. However, Chrome still shows hours (12, grey and non accessible) and AM/PM (also gray, non accessible).
Any ideas? Is it possible to do what I'm trying to?
Thanks in advance!
<input type="time" step='1' min="00:00:01" max="00:10:00" name="duration" class="required">
| |
doc_343
|
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/air-datepicker/2.2.3/css/datepicker.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/air-datepicker/2.2.3/js/datepicker.min.js"></script>
<form>
<input type="text" class="datepicker-here" id="dob" required readonly ></input>
<button type="submit">submit</button>
</form>
A: To not go too much into why is this happening as I do not use that datepicker, why you simply do not create your own required check with JS? I see read-only is working...
document.getElementById("myform").addEventListener("submit", function(event) {
event.preventDefault()
if (document.getElementById("dob").value === "") {
window.alert("Date empty!");
// Create here what you wish, tooltip, alert, css styling, html alert...
} else {
document.getElementById("myform").submit();
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/air-datepicker/2.2.3/css/datepicker.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/air-datepicker/2.2.3/js/datepicker.min.js"></script>
<form id="myform">
<input type="text" class="datepicker-here" id="dob" required readonly>
<button type="submit">submit</button>
</form>
| |
doc_344
|
What I want to know here is that if the first check i.e. mysqli_connect is successful, does it mean that it is same as boolean true? and if the mysqli_connect is unsuccessful, does it mean that it is same as boolean false??
A: The statement is returning an object, not any boolean values. Try to store it in a variable and var_dump to see what it's returning. It Returns an object representing the connection to the MySQL server.
In the case of not successful, the or statement will execute and halt the execute due to die()
A: I think mysqli_connect_error() will help you fixing this problem.
It return a string which describes the error.
https://www.php.net/manual/de/mysqli.connect-error.php
A: Based on the manual mysqli::__construct
Return Values: Returns an object which represents the connection to a MySQL Server.
So it will return a databases connection object when connection happen successfully.
If not then or condition will execute with the message you wrote in it which is :- Error establishing connection
For a better practice always try to find what problem occur while connection, so that you can fix it. So write like below:-
mysqli_connect($mysql_host, $mysql_user, $mysql_password) or die(mysqli_connect_error());
Reference:- mysqli_connect_error()
| |
doc_345
|
A: By embedding do you mean distributing your program without the file?
Then you can convert it to configuration initialization code in your build toolchain. Add a makefile step (or whatever tool you're using) - a script that converts this .cfg file into some C++ code file that initializes a configuration data structure. That way you can just modify the .cfg file, rebuild the project, and have the new values reflected inside.
By the way, on Windows, you may have luck embedding your data in a resource file.
A: Embedded data are often called "resources". C++ provides no native support, but it can be managed in almost all executable file formats. Try searching for resource managers for c++.
A: One common thing you can do is to represent the file data as an array of static bytes:
// In a header file:
extern const char file_data[];
extern const size_t file_data_size;
// In a source file:
const char file_data[] = {0x41, 0x42, ... }; // etc.
const size_t file_data_size = sizeof(file_data);
Then the file data will just be a global array of bytes compiled into your executable that you can reference anywhere. You'll have to either rewrite your file processing code to be able to handle a raw byte array, or use something like fmemopen(3) to open a pseudo-file handle from the data and pass that on to your file handling code.
Of course, to get the data into this form, you'll need to use some sort of preprocessing step to convert the file into a byte array that the compiler can accept. A makefile would be good for this.
A: If it's any Unix look into mapping the file into process memory with mmap(2). Windows has something similar but I never played with it.
| |
doc_346
|
Am I missing something, or is this just not possible now?
Thanks!
| |
doc_347
|
c:\xampp\mysql\bin>mysqladmin -u root password 123123
mysqladmin: connect to server at localhost failed
error:Access denied for user root@localhost (using password : NO)
A: Shouldn't that be:
mysqladmin -u root -p PASSWORD
?
A: The syntax looks wrong to me, just like Roberto said. You could also use this
mysqladmin -u root -h localhost -p
It should then ask you for the password. This way you can be sure that only a wrongly entered PW prevents you from connecting.
A: It should be:
mysqladmin -u root -p
and it will prompt you for a password. If you need to enter the password directly via the command line ( say you need to write a script), you should be able to do that with:
mysqladmin -u root -p123123
| |
doc_348
|
But in Ubuntu I am not able to see my Mapped Drives.
A: I had this problem as well. I couldn't find a satisfactory answer, but in the end, I created a symbolic link to the mapped drive I was trying to use and put it on a drive I could access. It worked fine.
On Unix, the command for a sym link is
ln -s "pathToFolder" "symLinkName"
A: In Unix you don't see the Network directories because you need to use a protocol like Samba to access folder over network.
So if you want to access those folders from FileChooser I suggest you to mount them on your own filesystem, like that you can have access to them from the FileChooser like any regular folder.
This is a tutorial to mount network drives in Ubuntu.
| |
doc_349
|
The change of the information should be a done with a transition (segmentedControl fades out and label fades in).
I tried to add multiple UIViews in the titleView and animate the alpha value, but it's not working.
[self.navigationItem.titleView addSubview:_mainSegmentedControl];
So I tried to change the content during the animation but since the value can't be animated it will be called immediately:
[UIView animateWithDuration:0.2 animations:^{
_filterSegmentedControl.alpha = 0.0f;} completion:^(BOOL finished) {
[UIView animateWithDuration:0.3 animations:^{
self.navigationItem.titleView = _mainSegmentedControl;
_mainSegmentedControl.alpha = 1.0f;
}];
}];
Any suggestions?
| |
doc_350
|
The following classes could not be instantiated:The following classes could not be instantiated:
- com.milan.searchmenu.persistentsearch.SearchBox (Open Class, Show Error Log)
See the Error Log (Window > Show View) for more details.
Tip: Use View.isInEditMode() in your custom views to skip code when shown in Eclipse
java.lang.NullPointerException By running application also run time null pointer exception occurs can any one tell me how to fix this:
This is my activity:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.manual);
ActionBar actionbar;
actionbar = getActionBar();
search = (SearchBox) findViewById(R.id.searchbox);
search.enableVoiceRecognition(this);
for(int x = 0; x < 10; x++){
com.milan.searchmenu.persistentsearch.SearchResult option = new SearchResult("Result " + Integer.toString(x), getResources().getDrawable(R.drawable.ic_history));
search.addSearchable(option);
}
search.setMenuListener(new MenuListener(){
@Override
public void onMenuClick() {
//Hamburger has been clicked
Toast.makeText(Manual.this, "Menu click", Toast.LENGTH_LONG).show();
}
});
search.setSearchListener(new SearchListener() {
@Override
public void onSearchTermChanged() {
// TODO Auto-generated method stub
}
@Override
public void onSearchOpened() {
// TODO Auto-generated method stub
}
@Override
public void onSearchClosed() {
// TODO Auto-generated method stub
}
@Override
public void onSearchCleared() {
// TODO Auto-generated method stub
}
@Override
public void onSearch(String result) {
Toast.makeText(Manual.this, result +" Searched", Toast.LENGTH_LONG).show();
}
});
This is my XML:
<RelativeLayout
android:id="@+id/Relative_layout"
android:layout_width="wrap_content"
android:layout_height="51dp"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:background="#673AB7">
<com.milan.searchmenu.persistentsearch.SearchBox
android:layout_width="wrap_content"
android:id="@+id/searchbox"
android:layout_height="wrap_content">
</com.milan.searchmenu.persistentsearch.SearchBox>
</RelativeLayout>
<android.support.v4.view.ViewPager
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/pager_sliding_tab_strip">
</android.support.v4.view.ViewPager>
<com.milan.tabs.pagerslidingstrip.PagerSlidingTabStrip
android:id="@+id/pager_sliding_tab_strip"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_alignParentLeft="true"
android:layout_below="@+id/Relative_layout"
android:textSize="15dp"
app:pstsShouldExpand="true"
app:pstsDividerColor="#B39DDB"
app:pstsIndicatorHeight="45dp"
android:background="#673AB7"
app:pstsIndicatorColor="#FFFFFF">
</com.milan.tabs.pagerslidingstrip.PagerSlidingTabStrip>
}
A: You need to add the downloaded library as a dependency of your module. In Android Studio do the following
*
*Place the library in your project somewhere.
*Right click on the library and select "Add as Library"
*Choose your main module: usually either called app or mobile.
*Rebuild and it should work
A: From the post what I understood is that you are having this issue while developing the app and not running.
If the issue is that the layout file is not loading in design view, it will be an issue with the SearchBox control you used in layout.
com.milan.searchmenu.persistentsearch.SearchBox
In custom views, while rendering in design view, it cannot work fully. For example if the custom view is accessing something from assets etc, that dependency will be resolved at runtime only and not in design mode, Because of which you got this error.
So for fixing you need to put those kind of codes inside the if block of View.isInEditMode().
| |
doc_351
|
is there a way by which i can achieve this?
edit: it is a data table which i add to a dataset.
edit: wat if the initials of the words, in this case b,m and s, are not in alphabetical order. in that wat am i supposed to do coz i have another application as well where i'll be required to sort a column having value High, normal and low.
A: Example
DataTable dt = ds.Tables[0];
DataView dv = new DataView(dt);
dv.Sort = sortExpression + direction; //sortexpression will be fieldname direction will be ascending descending
GridView1.DataSource = dv;
GridView1.DataBind()
Have a look at this article: Express Yourself with Expression-based Columns
http://msdn.microsoft.com/en-us/library/ms810291.aspx
OF COURSE IT WORKS!
DataSet myDs = new DataSet();
DataTable myDt = new DataTable("Table1");
myDs.Tables.Add(myDt);
myDt.Columns.Add("Size", typeof(string));
myDt.Columns.Add("Ranking", typeof(int), "Iif((Size)='Large', 1, Iif((Size)='Medium', 2, Iif((Size)='Small', 3, 4)))");
DataRow myDr1 = myDs.Tables["Table1"].NewRow();
DataRow myDr2 = myDs.Tables["Table1"].NewRow();
DataRow myDr3 = myDs.Tables["Table1"].NewRow();
DataRow myDr4 = myDs.Tables["Table1"].NewRow();
myDr1["Size"] = "Large";
myDr2["Size"] = "Medium";
myDr3["Size"] = "Small";
myDr4["Size"] = "Large";
myDt.Rows.Add(myDr1);
myDt.Rows.Add(myDr2);
myDt.Rows.Add(myDr3);
myDt.Rows.Add(myDr4);
DataView myDv = new DataView(myDt);
myDv.Sort = "Ranking";
ultraGrid1.DataSource = myDv;
And that is the code that proves it.
A: Map big, medium, small to an enum in the correct order and sort on that.
Any other answer will require more information as asked for in the comments.
A: If this is really as masqueraded T-SQL question, you could either use UNION (as proposed by Lukasz), or you could use a few WHEN ... THEN constructs in your ORDER BY:
SELECT *
FROM SomeTable
ORDER BY WHEN size = 'big' THEN 2 WHEN 'medium' THEN 1 ELSE 0 END
This might also work in ADO.NET, but I have not tested it:
myDataTable.DefaultView.Sort =
"WHEN size = 'big' THEN 2 WHEN 'medium' THEN 1 ELSE 0 END";
EDIT: David points out, that in your specific case (big, medium, small), the alphabetical sort order matches the expected ordering. In this special case, you can simply do:
ORDER BY size
Or in ADO.NET:
myDataTable.DefaultView.Sort = "size";
A: If you want a simple solution (and if these values are unlikely to change), just order by the 'size' column, since the big, medium and small words are in alphabetical order :D
A: Using the built-in sorting algorithm of the DataView (which is where you'd do actual sorting, not in the DataTable itself), this isn't possible, strictly speaking; there is no support for "custom" sorting, which is what you'd need. The sorting capabilities of the DataView are actually surprisingly limited, and (IIRC) it isn't even a stable sort (since it uses Array.Sort, which is documented as unstable).
Your only real option (from a GUI perspective) is to use a data display control that provides custom sorting capability, like the DevExpress XtraGrid.
A: After edits by OP, it has become (somewhat) clear that we are dealing with a DataTable.
One approach to sorting the rows of a DataTable according to a "mapped value", would be to use its Select method to retrieve several arrays (one for each value) of rows:
List<DataRow> rows = new List<DataRow>();
rows.AddRange(oldTable.Select("size = 'Big'"));
rows.AddRange(oldTable.Select("size = 'Medium'"));
rows.AddRange(oldTable.Select("size = 'Small'"));
If needed, the rows can be imported into a fresh DataTable with the same schema:
DataTable newTable = oldTable.Clone();
foreach (DataRow row in rows)
{
newTable.ImportRow(row);
}
This approach is definitely not very efficient, but it's probably about the easiest way to do this.
A: Try a switch statement.
Switch(var)
{ Case "Big":
//Append to TextBox1
//Or add to var1[]
break;
Case "Small":
//Append to TextBox2
//Or add to var2[]
break;
Case "Medium":
//Append to TextBox3
//Or add to var3[]
break;
}
EDIT: Sort into txtbox's or var[]'s, does this go-round make more sense?
| |
doc_352
|
The problem is, I dont know how to do it. Can anybody help me?
It looks like:
val(:,:,1) =
0.5601
val(:,:,2) =
0.4876
val(:,:,3) =
0.8146
val(:,:,4) =
0.6207
But it should be:
1x4 double =
0.5601 0.4876 0.8146 0.6207
A: You can get rid of singleton dimensions using the squeeze function: squeeze(val)'
You can also look at reshape or permute if your problem is a bit more complex
A: If all the other dimensions are singleton, and the result would be just a 1D vector, you can also use the following:
val(:)'
| |
doc_353
|
A: That will mean the events aren't stored, @Mafei.
Although that might feel off, please consider the following.
Axon Framework guides your applications to a solution using CQRS, DDD, and Event Sourcing. Especially the latter is important for the argument's sake.
If your application employs Event Sourcing, that means both your Projections are constructed through events, and your Command Models are used for business validation. Due to this, all your models are constructed based on events. In essence, the events in your Event Store (which might be Axon Server) are the sole source of truth.
If we circle back to your question of, "what happens if the event isn't stored through some error."
Well, if it's not stored, then it simply didn't happen. None of your Projections or Command Models can use an event that isn't there. Hence, the change simply didn't happen.
Note that Axon Server and Framework will correctly propagate such an exception. Hence, you can act accordingly, like performing a retry or backing off if the connection fails persistently.
| |
doc_354
|
Unfortunetly, about 2 weeks ago it suddenly stopped. It would not run again until we upgraded the Azure Guest OS to the newest Version(1.7).
Over the last two weeks we're noticing that session data transferred between pages (eg. http://program-url/cars/edit/3 will be missing the 3, etc...
IN addition, info stored in sessions will randomly dissapear and reappear, with no apparent reason.
Our application is built on Asp.net MVC 1 with Entity Framework 3.5. Our Db stuff is hosted on SQL Azure.
Does anyone know of a reason why this would be happening, or how to fix it?
A: I don't peronsally know a reason, but you should check the Guest VM OS release notes, which provide all the security patches that are included in a release. Chances are one of the patches changed ASP.NET behavior in some way that is impacting you.
MSDN: Azure Guest OS Releases
http://msdn.microsoft.com/en-us/library/ee924680.aspx
MSDN: Azure Guest OS 1.7
http://msdn.microsoft.com/en-us/library/gg248099.aspx
(The rest of this is just a guess, but figured I'd share)
OS Release 1.7 does include MS Bulletin MS10-070 which patched up a security hole in ASP.NET where the error pages could allow threats to access protected information (Vulnerability 2418042).
This particular patch caused us some problems on our non-Azure systems, as it modifies the way machine key encryption is used when ASP.NEt shares information. Depending on your caching, this may be the cause.
| |
doc_355
|
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
j = arduino()
File "C:\Users\Dhruv and Anuj\Documents\Dhruv K. Patel\Python Files\bitSnake_source\bitSnake\glove_input.py", line 9, in __init__
ser = serial.Serial(port, 9600)
File "C:\Python32\lib\site-packages\serial\serialwin32.py", line 38, in __init__
SerialBase.__init__(self, *args, **kwargs)
File "C:\Python32\lib\site-packages\serial\serialutil.py", line 282, in __init__
self.open()
File "C:\Python32\lib\site-packages\serial\serialwin32.py", line 66, in open
raise SerialException("could not open port %r: %r" % (self.portstr, ctypes.WinError()))
serial.serialutil.SerialException: could not open port 'COM1': WindowsError(2, 'The system cannot find the file specified.')
Here's my arduino code:
int speed = 10;
const int thumb = 2;
const int index = 3;
const int middle = 4;
const int ring = 5;
const int pinky = 6;
String out;
void setup(){
pinMode(thumb,INPUT);
pinMode(index,INPUT);
pinMode(middle,INPUT);
pinMode(ring,INPUT);
pinMode(pinky,INPUT);
Serial.begin(9600);
}
void loop(){
boolean repeat = true;
if(repeat == true){
if(digitalRead(thumb) == HIGH){
Serial.write(1);
Serial.println(1);
repeat = false;
}
if(digitalRead(index) == HIGH){
Serial.write(2);
Serial.println(2);
repeat = false;
}
if(digitalRead(middle) == HIGH){
Serial.write(3);
Serial.println(3);
repeat = false;
}
if(digitalRead(ring) == HIGH){
Serial.write(4);
Serial.println(4);
repeat = false;
}
if(digitalRead(pinky) == HIGH){
Serial.write(5);
Serial.println(5);
repeat = false;
}
}
if(repeat == true){
Serial.write(0);
Serial.println(0);
}
delay(10);
}
And my python code:
import serial
from serial import *
port = 0
class arduino:
def __init__(self):
#serial.tools.list_ports()
ser = serial.Serial(port, 9600)
self.port = str(port)
def read(self):
return ser.readline()
def close(self):
ser.close()
Any help would be great, thanks!!
A: Try another COM port. Your arduino obviously isn't on COM1.
A: You can find out which COM's used in the Windows hardware device manager.
In Win7, my USB-to-serial adapter will have COM40/COM41.
| |
doc_356
|
The problem is that withStyles needs to have access to a theme.
This is an attempt at writing the mounting functions.
import React from 'react';
import { mount, shallow } from 'enzyme';
import {
withStyles,
createGenerateClassName,
createMuiTheme,
jssPreset,
MuiThemeProvider,
getMuiTheme
} from 'material-ui/styles';
import PropTypes from 'prop-types';
import globalThem from 'client/theme/base';
const theme = createMuiTheme(globalThem);
const { muiThemeProviderOptions } = (new MuiThemeProvider({ theme }, {})).getChildContext()
export const shallowWithStyles = node => shallow(
node,
{
context: { muiThemeProviderOptions },
}
)
export const mountWithStyles = node => mount(
node,
{
context: { muiThemeProviderOptions },
}
)
| |
doc_357
|
Notice that I’m not specifying any URL when I call io(), since it defaults to trying to connect to the host that serves the page.
I was wondering how did it do that? How can one through JavaScript on the client side retrieve the details of the server that served this very page? I tried searching through Socket.IO, but wasn't able to find the io() function.
Can someone point that code that retrieves these meta-details or show a small snippet that does the same?
A: In browser Javascript, the window.location object has these relevant properties:
window.location.host - The hostname of the current webpage
window.location.port - The port number of the current web page
Other properties are here: https://developer.mozilla.org/en-US/docs/Web/API/Location
So, socket.io can use these two values to connect back to the host that the current web page came from. You see some of this logic in the socket.io client side file here in the source.
| |
doc_358
|
Is there any way to have ExternalApp behave like it normally does? I hope I'm explained myself a bit clear. Thanks for any help in advance!
Kind regards,
Eric
Public Class Form1
Dim WithEvents P As New Process
Dim SW As System.IO.StreamWriter
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
P.EnableRaisingEvents = True
Me.Text = "My title"
AddHandler P.OutputDataReceived, AddressOf DisplayOutput
P.StartInfo.CreateNoWindow() = True
P.StartInfo.UseShellExecute = False
P.StartInfo.RedirectStandardInput = True
P.StartInfo.RedirectStandardOutput = True
P.StartInfo.FileName = "ExternalApp.exe"
P.StartInfo.Arguments = ""
P.Start()
P.SynchronizingObject = Me
P.BeginOutputReadLine()
SW = P.StandardInput
SW.WriteLine()
End Sub
Private Sub DisplayOutput(ByVal sendingProcess As Object, ByVal output As DataReceivedEventArgs)
TextBox1.AppendText(output.Data() & vbCrLf)
End Sub
Private Sub Textbox2_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox2.KeyPress
If e.KeyChar = Chr(Keys.Return) Then
SW.WriteLine(TextBox2.Text)
End If
End Sub
Private Sub myProcess_Exited(ByVal sender As Object, ByVal e As System.EventArgs) Handles P.Exited
Me.Close()
End Sub End Class
| |
doc_359
|
retrieveQuery = "SELECT itemName, itemCategory, itemSubCategory, itemPrice, orders, (orders * itemPrice) as TotalPrice FROM Menu WHERE itemCategory = @selectedCat AND itemSubCategory LIKE '%@selectedSubCat%'";
The 2 fields in the parameterized query are selectedCat and selectedSubCat.
First scenario is when the user selects for only Food and as you can see the DropdownList Value selected is ALL which means to say that the query statement's Where Clause should have only selectedCat = 'Food' and selectedSubCat LIKE '%%' (ALL VALUES OF FIELD 'itemSubCategory' FOUND IN THE SQL TABLE)
Second scenario is when the user selects for only Food and selects the DropdownList Value to be Donut which means to say that the query statement's Where Clause should have only selectedCat = 'Food' and selectedSubCat LIKE '%Donut%'
Upon when the user hits the Export to PDF button, these lines of codes are executed..
I have removed the unnecessary codes
String itemCat = HF_TabListType.Value;
String itemSubCatFood = ddlFood.SelectedValue;
String itemSubCatBeverage = ddlBeverages.SelectedValue;
//Retrieving Data to Populate to Report Table
String strConnString = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
SqlConnection myConn = new SqlConnection(strConnString);
myConn.Open();
SqlDataAdapter da;
DataSet dsPDF = new DataSet();
String retrieveQuery = String.Empty;
using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream())
{
PdfPTable reportTable = new PdfPTable(1);
if (itemCat == "Food" || itemCat == "Beverages")
{
reportTable = new PdfPTable(foodGV.Columns.Count - 1);
}
else if (itemCat == "Combo")
{
reportTable = new PdfPTable(gvCombo1Total.Columns.Count);
}
reportTable.TotalWidth = 1000f;
reportTable.LockedWidth = true;
reportTable.HorizontalAlignment = Element.ALIGN_CENTER;
reportTable.SpacingAfter = 30f;
//For Food and Beverages
String[] headerForFB = { "No.", "Item Name", "Item Category", "Item Sub Category", "Item Price($)", "Orders", "Total($)" };
//Fod Combo
String[] headerForC = { "No.", "Combo", "Total Amount of Orders", "Total Discounts($)", "Total Sales($)" };
if (itemCat == "Food" || itemCat == "Beverages")
{
for (int i = 0; i < headerForFB.Length; i++)
{
PdfPCell hCell = new PdfPCell(new Phrase(headerForFB[i].ToString(), BoldFontForHeader));
hCell.FixedHeight = 25f;
reportTable.AddCell(hCell);
}
}
else if (itemCat == "Combo")
{
for (int i = 0; i < headerForC.Length; i++)
{
PdfPCell hCell = new PdfPCell(new Phrase(headerForC[i].ToString(), BoldFontForHeader));
reportTable.AddCell(hCell);
}
}
retrieveQuery = "SELECT itemName, itemCategory, itemSubCategory, itemPrice, orders, (orders * itemPrice) as TotalPrice FROM Menu WHERE itemCategory = @selectedCat AND itemSubCategory LIKE '%@selectedSubCat%'";
da = new SqlDataAdapter(retrieveQuery.ToString(), myConn);
da.SelectCommand.Parameters.AddWithValue("@selectedCat", itemCat);
//da.SelectCommand.Parameters.AddWithValue("selectedSubCat", "%" + itemSubCatFood + "%");
if (HF_TabListType.Value.ToString() == "Food")
{
if (ddlFood.SelectedIndex != 0)
{
da.SelectCommand.Parameters.AddWithValue("@selectedSubCat", itemSubCatFood);
}
else
{
da.SelectCommand.Parameters.AddWithValue("@selectedSubCat", "%%");
}
}
else if (HF_TabListType.Value.ToString() == "Beverages")
{
if (ddlBeverages.SelectedIndex != 0)
{
da.SelectCommand.Parameters.AddWithValue("@selectedSubCat", itemSubCatBeverage);
}
else
{
da.SelectCommand.Parameters.AddWithValue("@selectedSubCat", "%%");
}
}
da.Fill(dsPDF);
GridView1.DataSource = dsPDF;
GridView1.DataBind();
PdfPCell cell = null;
PdfPCell cellCount = null;
int j = 0;
//Food/Beverages
if (dsPDF != null || dsPDF.Tables.Count != 0 || dsPDF.Tables[0].Rows.Count != 0)
{
foreach (DataRow r in dsPDF.Tables[0].Rows)
{
cellCount = new PdfPCell(new Phrase((j + 1).ToString(), NormalFont));
cellCount.FixedHeight = 15f;
reportTable.AddCell(cellCount);
for (int i = 0; i < dsPDF.Tables[0].Columns.Count; i++)
{
cell = new PdfPCell(new Phrase(r[i].ToString(), NormalFont));
cell.FixedHeight = 15f;
reportTable.AddCell(cell);
}
j++;
}
}
When the PDF is generated the output of the PDF Table gives this..
Using the Second Scenario stated above,
I have tried to amend the codes and in some instances i got 2 rows with cells that are empty. Meaning the Dataset produced has the rows and columns needed to set the number of rows and columns of the PDF Table respectively.
Could there be an issue with the Retrieve Statement? Or because of adding the da.SelectCommand.Parameters line into if else statements?
I have been trying to work this out for days..
Appreciate any help please, thanks!
| |
doc_360
|
Song #1
Song #2
That is the way I play these songs:
AVPlayerItem *item = [[AVPlayerItem alloc] initWithURL:[NSURL URLWithString:@"http://www.iwheelbuy.com/Player/Test/1.mp3"]];
AVPlayer *player = [[AVPlayer alloc] init];
[player replaceCurrentItemWithPlayerItem:item];
[player setRate:1.0f];
I have some KVO observers, one of them observes AVPlayer status and when I try to play one of these songs it gives me an error:
Domain=AVFoundationErrorDomain Code=-11800
UserInfo=0x1cdc3be0 {NSLocalizedDescription=..., NSUnderlyingError=0x1cdc14c0
"The operation couldn’t be completed. (OSStatus error -303.)"
Is there a way to play these songs? Any help is appreciated.
EDIT:
I have succeeded to make these songs play well
__block AVPlayer *currentPlayerBlock = _currentPlayer;
__block NSURL *urlBlock = url;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:urlBlock options:nil];
AVPlayerItem *item = [[AVPlayerItem alloc] initWithAsset:asset];
dispatch_sync(dispatch_get_main_queue(), ^{
[currentPlayerBlock replaceCurrentItemWithPlayerItem:item];
[currentPlayerBlock setRate:1.0f];
});
});
A: __block AVPlayer *currentPlayerBlock = _currentPlayer;
__block NSURL *urlBlock = url;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:urlBlock options:nil];
AVPlayerItem *item = [[AVPlayerItem alloc] initWithAsset:asset];
dispatch_sync(dispatch_get_main_queue(), ^{
[currentPlayerBlock replaceCurrentItemWithPlayerItem:item];
[currentPlayerBlock setRate:1.0f];
});
});
This way it works
| |
doc_361
|
The bot didn't duplicate the outputs the first few times I tried running the commands, but it started multiplying the outputs after I added more number of commands. I also cut and paste a bunch of code lines around, but nothing gave me an error in my text editor (Atom).
Also, how do I easily restart my bot? I'm using Atom, I don't see an obvious way of doing that on it...
Here's the code I used (all that's left is the token in the end):
import discord
from discord.ext import commands
client = commands.Bot(command_prefix = '.')
@client.event
async def on_ready():
print("Hello world")
@client.event
async def on_member_join(member):
print(f'{member} has joined a server')
@client.event
async def on_member_remove(member):
print(f'{member} has left a server')
@client.command()
async def moon(ctx):
await ctx.send('dancer')
@client.command()
async def ping(ctx):
await ctx.send(f'{round(client.latency * 1000)}ms')
@client.command()
async def test(ctx):
await ctx.send('test')
Example
Another example
I appreciate all input from everyone, thanks!!
A: The bot multiplying the output is most likely a bug because I don't see what you did wrong. I think it may be a problem with your IDE - I don't recommend Atom to run Python scripts you should use VScode or PyCharm - or a problem with your Python interpreter.
To easily shut down the bot, I used this command in my bot:
import sys
import discord
from discord.ext import commands
client = commands.Bot(command_prefix = ".")
@client.command()
async def quit(ctx):
sys.exit()
client.run("")
After that just run your program again. But the easiest way is to just manually kill your program.
A: The quickest way that I can think of to restart your bot is to simply manually stop the python code. I use the atom-python-run package in atom to run my python code. I simply press F5 to start the code and it open up the console outside of the atom text editor. Stopping my code from there is as simple as closing that window.
| |
doc_362
|
{% for i in prosize %}
<li><a class="order" id="{{i.option1}}" href="javascript:setSize('{{i.option1}}')">{{i.option1}}</a></li>
" >{{i.option1}}</a></li>
{% endfor %}
I need to change the style for the first element and remains the same for the others like for the first element the background colour will be black and for others it should be any other colour.
A: You could use {% if forloop.first %} to check if this is the first iteration.
A full list of forloop constructs can be found here:
https://docs.djangoproject.com/en/dev/ref/templates/builtins/#for
A: {{ forloop.counter }}
should give you the count of the iteration. If it's one, you should be dealing with your first element.
A: you can add a custom css class for first element
{% for i in prosize %}
<li {% if forloop.first %}class="red"{% endif %}>
<a class="order" id="{{i.option1}}">{{i.option1}}</a>
</li>
{% endfor %}
and css
.red {
background: red;
}
| |
doc_363
|
A: Just read at the corresponding memory addresses (0x378-0x37f for LPT1). But be aware that this will require elevated privileges (root/kernel) depending on your operating system.
Edit: On modern operating systems this will not work at all due to security limitations. You cannot access the port directly from a userspace program, you have to use the corresponding kernel functions.
| |
doc_364
|
temp = Right(Trim(dataSheet.range("A" & i).value), Len(Trim(dataSheet.range("A" & i).value)) - 1)
So I fixed it with this:
If dataSheet.range("A" & i).value <> "" Then
temp = Right(Trim(dataSheet.range("A" & i).value), Len(Trim(dataSheet.range("A" & i).value)) - 1)
Else
Exit For
End If
My question is adding that If statement a valid fix? It seems like something bigger might be going on that's escaping my grasp...Like shouldn't the Right() function just return nothing when the String is NULL?
A: An empty cell is not null.
The problem lies in your formula: if a cell is empty or only contains spaces, Len(Trim(dataSheet.range("A" & i).value)) is 0 and Len(Trim(dataSheet.range("A" & i).value)) - 1 is -1. When you run Right(someString, -1) you get an error.
You should do this (it also takes care of cells that only contain spaces):
If Len(Trim(dataSheet.range("A" & i).value)) > 0 Then
temp = Right(Trim(dataSheet.range("A" & i).value), Len(Trim(dataSheet.range("A" & i).value)) - 1)
Else
...
End If
| |
doc_365
|
But it's been days I'm struggling with this issue: if last NSTextView in chain is empty (say, user just hit Enter and moved cursor back somewhere in previous text view), then the cursor disappears when come back in this empty NSTextView. If I click by mouse, I have to click twice in the empty text view, so the cursor appears. If I move the cursor with arrow keys, then, again, I have to press an arrow key twice.
I've tried update cursor, but nothing happens. This issue is happens if text view is empty and the last one in series. Where should I find the answer? Searched this forum, Apple docs, googled it — nothing.
create first text view
let textContainer = NSTextContainer(containerSize: containerSize)
layoutManager.addTextContainer(textContainer)
let textView = NSTextView(frame: frame, textContainer: textContainer)
someView.addSubview(textView)
create second text view
let anotherTextContainer = NSTextContainer(containerSize: containerSize)
layoutManager.addTextContainer(anotherTextContainer)
let anotherTextView = NSTextView(frame: anotherFrame, textContainer: anotherTextContainer)
someView.addSubview(anotherTextView)
Now run, type something and hit Enter. Now, if you move the cursor up and then back down, it won't show up. You have to press down key again, then the cursor will show up. Same with mouse: you'll have to do left click for two times and only after that the cursor will show up in the second text view.
Here's the example: https://www.dropbox.com/s/47domcy0nuisncc/%D0%A1%D0%BA%D1%80%D0%B8%D0%BD%D1%88%D0%BE%D1%82%202014-06-28%2013.37.58.png
Here's a sample project: https://www.dropbox.com/s/aw01oo0faajr4rn/Test.zip. I made it from scratch, when you hit Enter key, it places a second text view and you can see, that issue occurs even in a new clean projects.
A: It looks like a bug of Apple engineers. Found the same behavior in other apps.
| |
doc_366
|
My robot application depends on a custom python module, which has to be in my workspace. This python module is built by colcon as a python package, not a ROS package. This page explains how to do that with catkin, but this example shows how to adapt it to colcon. So finally my workspace looks like that :
my_workspace/
|--src/
|--my_module/
| |--setup.py
| |--package.xml
| |--subfolders and python scripts...
|--some_ros_pkg1/
|--some_ros_pkg2/
|...
However the command : colcon build <my_workspace> builds all ROS packages but fails to build my python module as a package.
Here's the error I get :
Starting >>> my-module
[54.297s] WARNING:colcon.colcon_ros.task.ament_python.build:Package 'my-module' doesn't explicitly install a marker in the package index (colcon-ros currently does it implicitly but that fallback will be removed in the future)
[54.298s] WARNING:colcon.colcon_ros.task.ament_python.build:Package 'my-module' doesn't explicitly install the 'package.xml' file (colcon-ros currently does it implicitly but that fallback will be removed in the future)
--- stderr: my-module
usage: setup.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...]
or: setup.py --help [cmd1 cmd2 ...]
or: setup.py --help-commands
or: setup.py cmd --help
error: invalid command 'egg_info'
---
Failed <<< my-module [0.56s, exited with code 1]
I found this issue that seems correlated, and thus tried : pip install --upgrade setuptools
...Which fails with the error message :
Collecting setuptools
Using cached https://files.pythonhosted.org/packages/7c/1b/9b68465658cda69f33c31c4dbd511ac5648835680ea8de87ce05c81f95bf/setuptools-50.3.0.zip
Complete output from command python setup.py egg_info:
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "setuptools/__init__.py", line 16, in <module>
import setuptools.version
File "setuptools/version.py", line 1, in <module>
import pkg_resources
File "pkg_resources/__init__.py", line 1365
raise SyntaxError(e) from e
^
SyntaxError: invalid syntax
----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-uwFamt/setuptools/
And with pip3 install --upgrade setuptools, I get :
Defaulting to user installation because normal site-packages is not writeable
Requirement already up-to-date: setuptools in /home/ubuntu/.local/lib/python3.5/site-packages (50.3.0)
I have both Python 3.5.2 an Python 2.7, but I don't know which one is used by colcon.
So I don't know what to try next, and what the real problem is. Any help welcome !
A: I managed to correctly install my package and its dependencies. I develop the method below, in case it may help someone someday !
I have been mainly inspired by this old DeepRacer repository.
The workspace tree in the question is wrong. It should look like this:
my_workspace/
|--src/
|--my_wrapper_package/
| |--setup.py
| |--my_package/
| |--__init__.py
| |--subfolders and python scripts...
|--some_ros_pkg1/
|--some_ros_pkg2/
*
*my_wrapper_package may contain more than one python custom package.
*A good setup.py example is this one.
*You shouldn't put a package.xml next to setup.py : colcon will only look at the dependencies declared in package.xml, and won't collect pip packages.
*It may help sometimes to delete the folders my_wrapper_package generated by colcon in install/ and build/. Doing so you force colcon to rebuild and bundle from scratch.
| |
doc_367
|
Here is what I tried:
import glob, importlib
for file in glob.iglob("*.py"):
importlib.import_module(file)
This returns an error: ModuleNotFoundError: No module named 'agents.py'; 'agents' is not a package
(here agents.py is one of the files in the folder; it is indeed not a package and not intended to be a package - it is just a script).
If I change the last line to:
importlib.import_module(file.replace(".py",""))
then I get no error, but also the scripts do not run.
Another attempt:
import glob, os
for file in glob.iglob("*.py"):
os.system(file)
This does not work on Windows - it tries to open each file in Notepad.
A: You need to specify that you are running the script through the command line. To do this you need to add python3 plus the name of the file that you are running. The following code should work
import os
import glob
for file in glob.iglob("*.py"):
os.system("python3 " + file)
If you are using a version other than python3, just change the argument from python3 to python
A: Maybe you can make use of the subprocess module; this question shows a few options.
Your code could look like this:
import os
import subprocess
base_path = os.getcwd()
print('base_path', base_path)
# TODO: this might need to be 'python3' in some cases
python_executable = 'python'
print('python_executable', python_executable)
py_file_list = []
for dir_path, _, file_name_list in os.walk(base_path):
for file_name in file_name_list:
if file_name.endswith('.csv'):
# add full path, not just file_name
py_file_list.append(
os.path.join(dir_path, file_name))
print('PY files that were found:')
for i, file_path in enumerate(py_file_list):
print(' {:3d} {}'.format(i, file_path))
# call script
subprocess.run([python_executable, file_path])
Does that work for you?
Note that the docs for os.system() even suggest using subprocess instead:
The subprocess module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using this function.
A: If you have control over the content of the scripts, perhaps you might consider using a plugin technique, this would bring the problem more into the Python domain and thus makes it less platform dependent. Take a look at pyPlugin as an example.
This way you could run each "plugin" from within the original process, or using the Python::multiprocessing library you could still seamlessly use sub-processes.
| |
doc_368
|
our trained system have to learn author's style by using machine learning algorithm.
is there any problem of using Naive Bayes algorithm to train our system to extract each author's style. Otherwise, can you please give me a better alternative??
We are trying to get implement it in python.
Can you tell me where to start? Thanks in advance..
A: I would start by looking at scikit-learn: a machine learning library with a lot of implemented algorithms.
For text classification, Naive Bayes does not usually achieve the best results. Look at Support Vector Machines and algorithms based on ideas from them, such as (you can search for these on the scikit website and go from there): SGDClassifier, PassiveAggressiveClassifier and LinearSVC.
Scikit also implements Naive Bayes classifiers, so have a look at those as well.
I wouldn't start by manually deciding what is relevant to an author's style. Look into CountVectorizer (bag of words model) and TfidfVectorizer (tf-idf weighting for the bag of words model), which should build decent features for you to start with.
A: There are many python libraries that could be used to measure different linguistic aspects of your input text and then using this values as features would probably enhance the quality of your model. I'll name a few here that can help you measuring aspects like Subjectivity, Complexity, Informality, Specificity etc:
TextBlob
Domain-Agnostic-Sentence-Specificity-Prediction
Readability
TextStat
Python Semantic Complexity Analyser
Uncertainty
Lexical Diversity
Lexical Richness
I hope that helps!
| |
doc_369
|
A: I wrote a super simple waitForNonExistence(timeout:) extension function on XCUIElement for this which mirrors the existing XCUIElement.waitForExistence(timeout:) function, as follows:
extension XCUIElement {
/**
* Waits the specified amount of time for the element’s `exists` property to become `false`.
*
* - Parameter timeout: The amount of time to wait.
* - Returns: `false` if the timeout expires without the element coming out of existence.
*/
func waitForNonExistence(timeout: TimeInterval) -> Bool {
let timeStart = Date().timeIntervalSince1970
while (Date().timeIntervalSince1970 <= (timeStart + timeout)) {
if !exists { return true }
}
return false
}
}
A: You will have to setup predicate for the condition you want to test:
let doesNotExistPredicate = NSPredicate(format: "exists == FALSE")
Then create an expectation for your predicate and UI element in your test case:
self.expectationForPredicate(doesNotExistPredicate, evaluatedWithObject: element, handler: nil)
Then wait for your expectation (specifying a timeout after which the test will fail if the expectation is not met, here I use 5 seconds):
self.waitForExpectationsWithTimeout(5.0, handler: nil)
A: You can check the element by XCUIElement.exists for 10 second for each second and then assert the element. See the following for ActivityIndicator:
public func waitActivityIndicator() {
var numberTry = 0
var activityIndicatorNotVisible = false
while numberTry < 10 {
if activityIdentifier.exists {
sleep(1)
numberTry += 1
} else {
activityIndicatorNotVisible = true
break
}
}
XCTAssert(activityIndicatorNotVisible, "Activity indicator is still visible")
}
A: @Charles A has the correct answer. Below is the Swift 5 version of the same.
let doesNotExistPredicate = NSPredicate(format: "exists == FALSE")
expectation(for: doesNotExistPredicate, evaluatedWith: element, handler: nil)
waitForExpectations(timeout: 5.0, handler: nil)
| |
doc_370
|
I was trying to add to those AbstractAuthenticationEvent exposed events an additional information about the URL, which requestor tries to connect to. Unfortunately, all my attempts have failed.
My question is if there are the handy way to fill those events with target URL path?
A: As M.Deinum suggested in the comment, providing custom WebAuthenticationDetails and AuthenticationDetailsSource did the thing.
I've had to create desired WebAuthenticationDetails class
public class ExtendedWebAuthenticationDetails extends WebAuthenticationDetails {
private final String requestUrl;
public ExtendedWebAuthenticationDetails(HttpServletRequest request) {
super(request);
this.requestUrl = request.getRequestURI();
}
public String getRequestUrl() {
return requestUrl;
}
}
And use it within custom WebAuthenticationDetailsSource
@Component
public class CustomWebAuthenticationDetailsSource extends WebAuthenticationDetailsSource {
@Override
public WebAuthenticationDetails buildDetails(HttpServletRequest context) {
return new ExtendedWebAuthenticationDetails(context);
}
}
In the end, tell Spring security to use the configured authenticationDetailsSource
@Configuration
@EnableWebSecurity
public class SecurityCommonConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
private WebAuthenticationDetailsSource detailsSource;
...
@Override
protected void configure(HttpSecurity http) throws Exception {
http.httpBasic().authenticationDetailsSource(detailsSource);
}
}
As a result, all AbstractAuthenticationEvent fired events return ExtendedWebAuthenticationDetails with getDetails() method call. This gives an access to the desired request URL.
| |
doc_371
|
CREATE PROCEDURE PROC_AUTOACTIVE
BEGIN ATOMIC
DECLARE v_sql VARCHAR(800);
DECLARE v_customer_id BIGINT;
DECLARE v_cardnum varchar(500);
DECLARE v_cardtype varchar(20);
DECLARE v_status varchar(10);
DECLARE v_lastname varchar(200);
DECLARE v_email varchar(150);
DECLARE v_mobile varchar(30);
DECLARE v_phone varchar(30);
DECLARE v_zipcode varchar(20);
DECLARE v_crm_mobile varchar(30);
DECLARE v_address varchar(500);
DECLARE v_order_count BIGINT;
DECLARE v_order_no varchar(500);
DECLARE not_found CONDITION FOR SQLSTATE '02000';
DECLARE at_end INT DEFAULT 0;
DECLARE c_customers CURSOR FOR s_cardsinfo;
DECLARE CONTINUE HANDLER FOR not_found SET at_end = 1;
SET v_sql = 'select t.customer_id, v.CUSTOMER_ID, v.CARD_TYPE, v.STATUS
from customer_tempcard t,
vip_fields v
where t.tempcard_num=v.CUSTOMER_ID
and t.status=1
and v.STATUS=1
and exists (select id
from orders o
where o.FK_CUSTOMER=t.CUSTOMER_ID
and o.FK_ORDER_STATUS in (3,4,6)) ';
PREPARE s_cardsinfo FROM v_sql;
OPEN c_customers;
--fetch card info
LOOP_CUSTOMER_INFO:
LOOP
FETCH c_customers INTO v_customer_id,v_cardnum,v_cardtype,v_status;
IF at_end <> 0 THEN
SET at_end = 0;
LEAVE LOOP_CUSTOMER_INFO;
END IF;
select c.LOGON_ID, o.DEV_CUSTOMER_NAME,
o.DEV_MOBILE, o.DEV_PHONE, o.DEV_ZIP, o.DEV_ADDRESS, o.ORDER_NO
into v_email, v_lastname,
v_mobile, v_phone, v_zipcode, v_address, v_order_no
from orders o,customer c
where o.FK_CUSTOMER=c.ID
and o.FK_CUSTOMER=v_customer_id
and o.FK_ORDER_STATUS in (3,4,6)
order by o.ID desc
fetch first 1 rows only;
IF v_mobile <> null THEN
SET v_crm_mobile = v_mobile;
ELSE
SET v_crm_mobile = v_phone;
END IF;
update customer_tempcard ct
set ct.STATUS='0',
ct.UPDATE_TIME=current_timestamp
where ct.CUSTOMER_ID=v_customer_id;
update card_store cs
set cs.STATUS='0',
cs.UPDATE_TIME=current_timestamp
where cs.CARD_NUM=v_cardnum;
update vip_fields v
set v.LAST_NAME=v_lastname,
v.EMAIL=v_email, v.MOBILE=v_crm_mobile,
v.CUSTOMER_UPDATE_TIME=current_timestamp,
v.UPDATE_TIME=current_timestamp,
v.OPERATION_TYPE='2',
v.CREATE_SOURCE='2',
v.STATUS='0',
v.ZIP_CODE=v_zipcode,
v.ADDRESS=v_address
where customer_id = v_cardnum;
update customer c
set c.VIP_CARD_NUMBER=v_cardnum,
c.VIP_CARD_NAME=v_lastname,
c.VIP_EMAIL=v_email,
c.VIP_CARD_TYPE=v_cardtype,
c.LEVEL=v_cardtype,
c.VIP_ZIP=v_zipcode,
c.VIP_MOBILE=v_crm_mobile,
c.VIP_ADDRESS=v_address,
c.FK_CUSTOMER_GRADE='1'
where c.id=v_customer_id;
insert into beactiveinfo
values (default,v_cardnum,v_order_no,current_timestamp);
END LOOP;
CLOSE c_customers;
END
A: BULK COLLECT is part of the Oracle compatibility feature in DB2, so, firstly, you cannot use it in the DB2 SQL PL native context, which you are using in your procedure. Secondly, you don't use BULK COLLECT in a cursor. You use SELECT ... BULK COLLECT INTO an_array_variable ... to populate a PL/SQL array. If you intend then to loop over that array, you won't get any performance benefit over the cursor, while incurring the memory overhead for storing the entire result set in the application memory.
| |
doc_372
|
so i built it change the text to arabic and to englich but the layout still staring from left to right
i want to flip it when i change the language and i dont have any keyword to start searching
and i think i will be just flip the stackpanel so can any one help me
<StackPanel Orientation="Horizontal" VerticalAlignment="Stretch" HorizontalAlignment="Stretch">
<TextBlock Grid.Column="0" Text="Name : " HorizontalAlignment="Right" VerticalAlignment="Center" FontSize="14" FontWeight="Bold" Foreground="#31383F"></TextBlock>
<TextBlock Grid.Column="0" Text="Name : " HorizontalAlignment="Right" VerticalAlignment="Center" FontSize="14" FontWeight="Bold" Foreground="#31383F"></TextBlock>
</StackPanel>
A: use
FlowDirection="RightToLeft"
| |
doc_373
|
Next, I present an instance of UIImagePickerController on top of this view controller. The problem is that when I dismiss the image picker, the presenting view controller's frame covers the entire screen instead of just the portion I want it to cover. The frame specified by frameOfPresentedViewInContainerView in my custom UIPresentationController seems to be completely ignored.
Only if present the image picker with a modalPresentationStyle of UIModalPresentationOverCurrentContext my frames remain intact (which makes sense since no views are removed from the view hierarchy in the first place). Unfortunately that's not what I want. I want the image picker to be presented full screen, which - for whatever reason - seems to mess up my layout. Anything that I might be doing wrong or forgetting here? Any suggestions?
A: This is expected because the fullscreen presentation does not restore the original frame computed by frameOfPresentedViewInContainerView.
The recommended way to fix this is to create a wrapper view in which you will insert the presented view controller's view. Here is the relevant code for your custom presentation controller:
- (void)presentationTransitionWillBegin {
// wrapper is a property defined in the custom presentation controller.
self.wrapper = [UIView new];
[self.wrapper addSubview:self.presentedViewController.view];
}
- (CGRect)frameOfPresentedViewInContainerView {
CGRect result = self.containerView.frame;
// In this example we are doing a half-modal presentation
CGFloat height = result.size.height/2;
result.origin.y = height;
result.size.height = height;
return result;
}
- (UIView *)presentedView {
return self.wrapper;
}
- (BOOL)shouldPresentInFullscreen {
return NO;
}
- (void)containerViewWillLayoutSubviews {
self.wrapper.frame = self.containerView.frame;
self.presentedViewController.view.frame = [self frameOfPresentedViewInContainerView];
}
Note that we override presentedView to return the wrapper view instead of the default value – the presented view controller's view. This way, even if the second presentation modifies the wrapper's frame the presented view controller's view will not change.
A: This worked for me, in UIPresentationController:
override func containerViewWillLayoutSubviews() {
super.containerViewWillLayoutSubviews()
presentedViewController.view.frame = frameOfPresentedViewInContainerView
}
A: erudel's solution didn't work for me as is, but adding another view in between wrapperView and presentedViewController.view did the trick (I have no idea why):
- (instancetype)initWithPresentedViewController:(UIViewController *)presentedViewController
presentingViewController:(UIViewController *)presentingViewController {
if (self = [super initWithPresentedViewController:presentedViewController
presentingViewController:presentingViewController]) {
_wrapperView = [[UIView alloc] init];
_wrapperView2 = [[UIView alloc] init]; // <- new view
}
return self;
}
- (CGRect)frameOfPresentedViewInContainerView {
return self.containerView.bounds;
}
- (UIView *)presentedView {
return self.wrapperView;
}
- (BOOL)shouldPresentInFullscreen {
return NO;
}
- (void)containerViewWillLayoutSubviews {
self.wrapperView.frame = self.containerView.frame;
self.wrapperView2.frame = /* your custom frame goes here */;
self.presentedViewController.view.frame = self.wrapperView2.bounds;
}
- (void)presentationTransitionWillBegin {
[self.wrapperView addSubview:self.wrapperView2];
[self.wrapperView2 addSubview:self.presentedViewController.view];
// Set up a dimming view, etc
}
Tested this on iOS 9.3.
A: I tried containerViewWillLayoutSubviews but it wasn't quite working. I wanted to avoid the extra wrapper views if possible. I came up with this strategy of correcting the frame on the view using the presentedView. In addition I was able to remove containerViewWillLayoutSubviews. forceFrame is tuned to our particular use case. presentedFrame is set by our custom animator.
class CustomModalPresentationController: UIPresentationController {
var presentedFrame = CGRect.zero
var forceFrame = false
override func dismissalTransitionWillBegin() {
forceFrame = false
}
override func presentationTransitionDidEnd(_ completed: Bool) {
forceFrame = true
}
override var presentedView: UIView? {
if forceFrame {
presentedViewController.view.frame = presentedFrame
}
return presentedViewController.view
}
override var frameOfPresentedViewInContainerView: CGRect {
return presentedFrame
}
}
A: I tried both wrapper approaches mentioned. One side effect of using this wrapping approach is that device rotation doesn't display well - introducing black boxes around the presented view.
Instead of doing the wrapping trick, try setting the modalPresentationStyle of the presented UIImagePickerController to UIModalPresentationOverFullScreen. This means the views underneath the image picker won't be removed/restored from the view hierarchy during presentation/dismissal.
| |
doc_374
|
# Page
belongs_to :status
I want to run a callback anytime the status_id of a page has changed.
So, if page.status_id goes from 4 to 5, I want to be able to catch that.
How to do so?
A: Rails 5.1+
class Page < ActiveRecord::Base
before_save :do_something, if: :will_save_change_to_status_id?
private
def do_something
# ...
end
end
The commit that changed ActiveRecord::Dirty is here: https://github.com/rails/rails/commit/16ae3db5a5c6a08383b974ae6c96faac5b4a3c81
Here is a blog post on these changes: https://www.fastruby.io/blog/rails/upgrades/active-record-5-1-api-changes
Here is the summary I made for myself on the changes to ActiveRecord::Dirty in Rails 5.1+:
ActiveRecord::Dirty
https://api.rubyonrails.org/classes/ActiveRecord/AttributeMethods/Dirty.html
Before Saving (OPTIONAL CHANGE)
After modifying an object and before saving to the database, or within the before_save filter:
*
*changes should now be changes_to_save
*changed? should now be has_changes_to_save?
*changed should now be changed_attribute_names_to_save
*<attribute>_change should now be <attribute>_change_to_be_saved
*<attribute>_changed? should now be will_save_change_to_<attribute>?
*<attribute>_was should now be <attribute>_in_database
After Saving (BREAKING CHANGE)
After modifying an object and after saving to the database, or within the after_save filter:
*
*saved_changes (replaces previous_changes)
*saved_changes?
*saved_change_to_<attribute>
*saved_change_to_<attribute>?
*<attribute>_before_last_save
Rails <= 5.0
class Page < ActiveRecord::Base
before_save :do_something, if: :status_id_changed?
private
def do_something
# ...
end
end
This utilizes the fact that the before_save callback can conditionally execute based on the return value of a method call. The status_id_changed? method comes from ActiveModel::Dirty, which allows us to check if a specific attribute has changed by simply appending _changed? to the attribute name.
When the do_something method should be called is up to your needs. It could be before_save or after_save or any of the defined ActiveRecord::Callbacks.
A: The attribute_changed? is deprecated in Rails 5.1, now just use will_save_change_to_attribute?.
For more information, see this issue.
A: Try this
after_validation :do_something, if: ->(obj){ obj.status_id.present? and obj.status_id_changed? }
def do_something
# your code
end
Reference - http://apidock.com/rails/ActiveRecord/Dirty
| |
doc_375
|
My XML code is pretty long and messy so I'm just posting the relevant parts. If you need more please tell me:
<Spinner
android:id="@+id/maze_algorithm_spinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/random_textview"
android:layout_marginTop="40dp"
android:layout_alignEnd="@+id/play"
android:entries="@array/maze_generation_array"/>
<TextView
android:id="@+id/maze_algorithm_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/maze_algorithm_spinner"
android:layout_alignStart="@+id/help"
android:padding="2dp"
android:text="@string/maze_algorithm_spinner_text"
android:background="@android:color/holo_green_light"/>
I basically what Choose algorithm textview and its spinner to be centered vertically in between Random Generation textview and Driver textview.
Here is what my app screen currently looks like:
A: If you are using RelativeLayout as parent try this:
<RelativeLayout ...>
<LinearLayout
android:id="@+id/random_generation_layout"... (responsible for randomGeneration)
android:alignParentTop="true" >
<TextView ... />
<etc>
</LinearLayout>
<LinearLayout
android:id="@+id/choose_algo_layout"... (responsible for ChooseAlgorithm)
android:layout_above="@+id/driver_layout"
android:layout_below="@+id/random_generation_layout" >
<TextView ... />
<etc>
</LinearLayout>
<LinearLayout
android:id="@+id/driver_layout"... (responsible for driver)
android:alignParentBottom="true">
<TextView ... />
<etc>
</LinearLayout>
</RelativeLayout>
Hope it wil help you!
A: If you really don't want nesting then you probably want to try adding two transparent View in between, where these two View elements are of the same height. So it will be like
<RandomGeneration />
<View />
<ChooseAlgorithm />
<View />
<Drive />
On the other hand, without using extra Views, with your dimension currently set to wrap_content, you can also assign paddings to <ChooseAlgorithm />, such that your top padding is the same as the bottom padding. The same goes for margin too. You can use either padding or margin, or both.
| |
doc_376
|
import jpapersistsm.enums.Events;
import jpapersistsm.enums.States;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.statemachine.config.EnableStateMachineFactory;
import org.springframework.statemachine.config.StateMachineConfigurerAdapter;
import org.springframework.statemachine.config.StateMachineFactory;
import org.springframework.statemachine.config.builders.StateMachineConfigurationConfigurer;
import org.springframework.statemachine.config.builders.StateMachineStateConfigurer;
import org.springframework.statemachine.config.builders.StateMachineTransitionConfigurer;
import org.springframework.statemachine.data.jpa.JpaPersistingStateMachineInterceptor;
import org.springframework.statemachine.data.jpa.JpaStateMachineRepository;
import org.springframework.statemachine.ensemble.StateMachineEnsemble;
import org.springframework.statemachine.listener.StateMachineListener;
import org.springframework.statemachine.listener.StateMachineListenerAdapter;
import org.springframework.statemachine.persist.StateMachineRuntimePersister;
import org.springframework.statemachine.service.DefaultStateMachineService;
import org.springframework.statemachine.service.StateMachineService;
import org.springframework.statemachine.state.State;
import org.springframework.statemachine.zookeeper.ZookeeperStateMachineEnsemble;
import java.util.EnumSet;
@Slf4j
@Configuration
@EnableStateMachineFactory
public class JpaPersistStateMachineConfiguration extends StateMachineConfigurerAdapter<States, Events> {
@Autowired
public JpaStateMachineRepository jpaStateMachineRepository;
private Logger logger = LoggerFactory.getLogger(JpaPersistStateMachineConfiguration.class);
@Override
public void configure(StateMachineStateConfigurer<States, Events> states) throws Exception{
states
.withStates()
.initial(States.ORDERED)
.end(States.PAYED)
.end(States.CANCELLED)
.states(EnumSet.allOf(States.class));
}
@Override
public void configure(StateMachineTransitionConfigurer<States,Events> transitions) throws Exception {
transitions
.withExternal().source(States.ORDERED).target(States.ASSEMBLED).event(Events.assemble).and()
.withExternal().source(States.ASSEMBLED).target(States.DELIVERED).event(Events.deliver).and()
.withExternal().source(States.DELIVERED).target(States.PAYED).event(Events.payment_received).and()
.withExternal().source(States.ORDERED).target(States.CANCELLED).event(Events.cancel).and()
.withExternal().source(States.ASSEMBLED).target(States.CANCELLED).event(Events.cancel).and()
.withExternal().source(States.DELIVERED).target(States.CANCELLED).event(Events.cancel);
}
@Override
public void configure(StateMachineConfigurationConfigurer<States,Events> config) throws Exception{
config
.withDistributed()
.ensemble(stateMachineEnsemble())
.and()
.withPersistence()
.runtimePersister(stateMachineRuntimePersister())
.and()
.withConfiguration()
.autoStartup(true);
}
@Bean
public StateMachineEnsemble<States, Events> stateMachineEnsemble() throws Exception {
return new ZookeeperStateMachineEnsemble<States, Events>(curatorClient(), "/app");
}
@Bean
public CuratorFramework curatorClient() throws Exception {
CuratorFramework client = CuratorFrameworkFactory
.builder()
.defaultData(new byte[0])
.retryPolicy(new ExponentialBackoffRetry(1000, 3))
.connectString("localhost:2181,localhost:2182,localhost:2183")
.build();
client.start();
return client;
}
@Bean
public StateMachineRuntimePersister<States,Events,String> stateMachineRuntimePersister(){
return new JpaPersistingStateMachineInterceptor<>(jpaStateMachineRepository);
}
@Bean
public StateMachineService<States,Events> stateMachineService (
StateMachineFactory<States,Events> stateMachineFactory,
StateMachineRuntimePersister<States,Events,String> stateMachineRuntimePersister){
return new DefaultStateMachineService<>(stateMachineFactory, stateMachineRuntimePersister);
}
@Bean
public StateMachineListener<States, Events> listener() {
return new StateMachineListenerAdapter<States, Events>() {
@Override
public void stateChanged(State<States, Events> from, State<States, Events> to) {
logger.info("*** listener: in state changed");
if (from == null) logger.info("*** state machine initialised in state {}", to.getId());
else logger.info("*** state changed from {} to {}", from.getId(), to.getId());
}
};
}
}
And my REST Controller class is:
import jpapersistsm.enums.Events;
import jpapersistsm.enums.States;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.statemachine.StateMachine;
import org.springframework.statemachine.listener.StateMachineListener;
import org.springframework.statemachine.service.StateMachineService;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import java.util.Map;
@RestController
@RequestMapping("/jpapersist")
public class RestServiceController {
@Autowired
public StateMachineService<States, Events> stateMachineService;
@Autowired
public StateMachineListener listener;
public StateMachine<States, Events> stateMachine;
public Logger logger = LoggerFactory.getLogger(RestServiceController.class);
@RequestMapping(value="/init", method= RequestMethod.POST)
public void init(@RequestBody Map<String,String> parameters){
logger.info("\n*** inside of state machine controller : INIT ");
try {
stateMachine = getStateMachine(parameters.get("guid"));
} catch (Exception e) {
e.printStackTrace();
}
logger.info("\n*** state machine initialized to state: {}", stateMachine.getState().getId().name());
}
/***
Synchronized method to obtain persisted state machine from database.
*/
public synchronized StateMachine<States,Events> getStateMachine(String machineId) throws Exception {
if (stateMachine == null) {
stateMachine = stateMachineService.acquireStateMachine(machineId);
stateMachine.addStateListener(listener);
stateMachine.start();
} else if (!ObjectUtils.nullSafeEquals(stateMachine.getId(), machineId)) {
stateMachineService.releaseStateMachine(stateMachine.getId());
stateMachine.stop();
stateMachine = stateMachineService.acquireStateMachine(machineId);
stateMachine.addStateListener(listener);
stateMachine.start();
}
return stateMachine;
}
}
When I send a request for initialize a state machine, getting an error like:
Unable to persist stateMachineContext
Caused by: org.hibernate.id.IdentifierGenerationException: ids for this class must be manually assigned before calling save(): org.springframework.statemachine.data.jpa.JpaRepositoryStateMachine
at org.hibernate.id.Assigned.generate(Assigned.java:33) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:119) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
at org.hibernate.event.internal.DefaultPersistEventListener.entityIsTransient(DefaultPersistEventListener.java:192) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:135) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:62) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:800) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:785) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_222]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_222]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_222]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_222]
at org.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler.invoke(ExtendedEntityManagerCreator.java:350) ~[spring-orm-5.1.9.RELEASE.jar:5.1.9.RELEASE]
at com.sun.proxy.$Proxy117.persist(Unknown Source) ~[na:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_222]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_222]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_222]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_222]
at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:309) ~[spring-orm-5.1.9.RELEASE.jar:5.1.9.RELEASE]
at com.sun.proxy.$Proxy117.persist(Unknown Source) ~[na:na]
at org.springframework.data.jpa.repository.support.SimpleJpaRepository.save(SimpleJpaRepository.java:535) ~[spring-data-jpa-2.1.10.RELEASE.jar:2.1.10.RELEASE]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_222]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_222]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_222]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_222]
at org.springframework.data.repository.core.support.RepositoryComposition$RepositoryFragments.invoke(RepositoryComposition.java:359) ~[spring-data-commons-2.1.10.RELEASE.jar:2.1.10.RELEASE]
at org.springframework.data.repository.core.support.RepositoryComposition.invoke(RepositoryComposition.java:200) ~[spring-data-commons-2.1.10.RELEASE.jar:2.1.10.RELEASE]
at org.springframework.data.repository.core.support.RepositoryFactorySupport$ImplementationMethodExecutionInterceptor.invoke(RepositoryFactorySupport.java:644) ~[spring-data-commons-2.1.10.RELEASE.jar:2.1.10.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.1.9.RELEASE.jar:5.1.9.RELEASE]
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:608) ~[spring-data-commons-2.1.10.RELEASE.jar:2.1.10.RELEASE]
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.lambda$invoke$3(RepositoryFactorySupport.java:595) ~[spring-data-commons-2.1.10.RELEASE.jar:2.1.10.RELEASE]
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:595) ~[spring-data-commons-2.1.10.RELEASE.jar:2.1.10.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.1.9.RELEASE.jar:5.1.9.RELEASE]
at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:59) ~[spring-data-commons-2.1.10.RELEASE.jar:2.1.10.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.1.9.RELEASE.jar:5.1.9.RELEASE]
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:295) ~[spring-tx-5.1.9.RELEASE.jar:5.1.9.RELEASE]
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:98) ~[spring-tx-5.1.9.RELEASE.jar:5.1.9.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.1.9.RELEASE.jar:5.1.9.RELEASE]
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:139) ~[spring-tx-5.1.9.RELEASE.jar:5.1.9.RELEASE]
... 111 common frames omitted
The state of the machine seems to changed, but could not persist on db. As I said, the problem is my curator configuration. Because it works fine when I define connectString with single Zookeeper like
.connectString("localhost:2181")
I'm new to Zookeeper and Curator, and open to any help. Thanks in advance.
A: The problem is with this configuration:
.withConfiguration()
.autoStartup(true);
Because it tries to start the machine, before having a machine id.
| |
doc_377
|
public void merge(Integer [] left, Integer[] right, Integer[] a) {
int i = 0; // a[] index (A)
int lIndex = 0; // left[] index (B)
int rIndex = 0; // right[] index (C)
// Begin main merge process
while((lIndex < left.length) && (rIndex < right.length)) {
if(left[lIndex] <= right[rIndex]) {
a[i] = left[lIndex]; // Store it
lIndex++; // Increase index of left[]
}
else {
a[i] = right[rIndex]; // Store it
rIndex++; // Increase index of right[]
}
i++; // Increase index of a[]
}
if(i == lIndex) { // If the left array is sorted
while(rIndex < right.length) { // Copy the contents of rhe right array to a[]
a[i] = right[rIndex];
i++;
rIndex++;
}
}
else { // If the right array is sorted
while(lIndex < left.length) { // Copy the contents of the left array to a[]
a[i] = left[lIndex];
i++;
lIndex++;
}
}
}
The problem is that every time I execute the function, the input array is returned partially sorted. I mean the majority of the elements are at their correct position but there are one or two that are placed wrong and also a couple of others that are duplicates of other elements! As I can't see what's really the problem, can anyone please help me? The implementation is a mini project for a lesson and I can't use int[ ] (let's say) instead of Integer[ ], in order to copy the contents of array A[ ] with the Arrays.copyOf() method. Thanks in advance and please forgive my syntax/spelling mistakes.
Note that the input array is always a power of 2 (2, 4, 8, 16 etc), so every time I divide by 2 to find the index of the middle element, I always get an even number.
A: I think your problem is here:
if(i == lIndex)
The way to check if you've run out of elements in a list is this:
if (lIndex == left.length)
In other words, if you take some elements from the left and some from the right, even if you exhaust the left array first, i will NOT be equal to lIndex when you've exhausted the left array. It will be greater.
A: From what I can tell, the problem is in your merge method, here:
if (i == lIndex) { // If the left array is sorted ...
i is not necessarily equal to lIndex when the left array is sorted. As a result, the final part of the merge is not always executed. The duplicate elements you're seeing are left over from the original array A in the positions that weren't overwritten because of this.
The correct condition is:
if (lIndex == left.length) { // If the left array is sorted ...
| |
doc_378
|
I generate the password using Math.floor(Math.random() * 6) + 1; to generate numbers from 1 to 6, and using that function to convert a number to an image:
var sam = document.createElement("img");
sam.src = "./samwell_tarly.jpeg";
var arya = document.createElement("img");
arya.src = "./arya_stark.jpeg";
var dany = document.createElement("img");
dany.src = "./dany.jpeg";
var jon = document.createElement("img");
jon.src = "./jon.jpeg";
var ned = document.createElement("img");
ned.src = "./ned_stark.jpeg";
var tyrion = document.createElement("img");
tyrion.src = "./tyrion.jpeg";
var ocu1 = document.getElementById("oc1");
var ocu2 = document.getElementById("oc2");
var ocu3 = document.getElementById("oc3");
var ocu4 = document.getElementById("oc4");
function intToGot(x) {
if(x==1){return arya;}
if(x==2){return sam;}
if(x==3){return ned;}
if(x==4){return dany;}
if(x==5){return jon;}
if(x==6){return tyrion;}
}
and then:
const oc1=Math.floor(Math.random() * 6) + 1;
ocu1.appendChild(intToGot(oc1));
const oc2=Math.floor(Math.random() * 6) + 1;
ocu2.appendChild(intToGot(oc2));
const oc3=Math.floor(Math.random() * 6) + 1;
ocu3.appendChild(intToGot(oc3));
const oc4=Math.floor(Math.random() * 6) + 1;
ocu4.appendChild(intToGot(oc4));
Those are my divs:
<div class="maiores" id="oc1"></div>
<div class="maiores" id="oc2"></div>
<div class="maiores" id="oc3"></div>
<div class="maiores" id="oc4"></div>
The problem i am facing is that:
When the numbers generated are all different, all of the 4 random images appear correctly, with no problems at all. But, when there is repetition, for example, if the password should be [sam,sam,dany,jon], only the last one of the repeated images appear, and the others just don't appear. In that case, the first 'sam' wouldn't appear. I can't understand how am I using wrong the appendChild function, and I need help to solve that problem.
A: solution
Explanation
This is because if a node is already a part of a document, then you cannot use that node reference again in another part of a document. If you do then the previous nodes get removed and inserted into new location.
const parent = document.querySelector("#parent");
const parent2 = document.querySelector("#parent2");
function createListChildElement(text) {
const element = document.createElement("li");
element.textContent = text;
return element;
}
const firstListChild = createListChildElement("First");
parent.appendChild(firstListChild);
const secondListChild = createListChildElement("Second");
parent.appendChild(secondListChild);
parent2.appendChild(firstListChild);
<h1>Second List</h1>
<ul id="parent"></ul>
<h1>Second List</h1>
<ul id="parent2"></ul>
Solution
You can create a new node/clone and append it to a new parent. You can do this using cloneNode method node
const parent = document.querySelector('#parent');
const parent2 = document.querySelector('#parent2');
function createListChildElement( text ) {
const element = document.createElement('li');
element.textContent = text;
return element;
}
const firstListChild = createListChildElement("First");
parent.appendChild( firstListChild );
const secondListChild = createListChildElement("Second");
parent.appendChild( secondListChild );
const clonedChild = firstListChild.cloneNode(true);
parent2.appendChild( clonedChild );
<h1>First list</h1>
<ul id="parent"></ul>
<h1>Second list</h1>
<ul id="parent2"></ul>
A: You've only made one image node for each character. It can only go in one place.
Just generate your images on the fly, instead of ahead of time.
function makeGot(fileName) {
const n = document.createElement("img");
n.src = filename;
return n;
}
function intToGot(x) {
if(x==1){return makeGot("arya_stark.jpeg");}
if(x==2){return makeGot("samwell_tarly.jpeg");}
if(x==3){return makeGot("ned_stark.jpeg");}
if(x==4){return makeGot("dany.jpeg");}
if(x==5){return makeGot("jon.jpeg");}
if(x==6){return makeGot("tyrion.jpeg");}
}
| |
doc_379
|
A: FusionAuth is a complete identity provider as well as a service provider. This means that you can store all of your users in FusionAuth and have them authenticate directly.
You can also use FusionAuth to log users in via other IdPs such as Google, Facebook, Twitter, GitHub, Active Directory, etc. This is called federated login and FusionAuth will handle reconciling user accounts.
Within FusionAuth, you can create an number of Applications, which are just resources a user can log into. Using FusionAuth as the identity provider via OAuth, OpenID Connect or SAMLv2, you get single sign-on for free. The UI for FusionAuth's login pages are also themeable, so you can make it look like your brand easily.
Finally, FusionAuth provides a complete authorization system as well. Each Application can define any number of roles. You then create a UserRegistration, which is a User, an Application and zero or more roles the User is granted for that Application.
Feel free to check out our documentation here: https://fusionauth.io/docs/
It provides a bunch of detail on all of these pieces.
| |
doc_380
|
Can anyone help point me in the right direction please?
A: In Configure Services in Startup:
services.AddAzureClients(builder =>
{
// Use the environment credential by default
builder.UseCredential(new DefaultAzureCredential());
builder.AddQueueServiceClient(Configuration.GetSection("StorageConnectionString"))
.ConfigureOptions(c => c.MessageEncoding = Azure.Storage.Queues.QueueMessageEncoding.Base64);
});
The implementation in the class is:
public class AzureQueueService : IQueueService
{
private readonly QueueServiceClient _queueServiceClient;
public AzureQueueService(QueueServiceClient queueServiceClient)
{
this._queueServiceClient = queueServiceClient;
}
public void SendMessageToQueue(MyMessage message)
{
this._queueServiceClient.GetQueueClient("my-queue-name")
.SendMessage(JsonSerializer.Serialize(message, new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase }));
}
}
A: an interface can be created with function/property which will return queue client and then implement the interface to inject in DI, hope below code will help.
public interface IQueueService
{
QueueClient GetQueueClient();
}
public class AzureQueueService : IQueueService
{
string azureStorageAccountConnectionString;
string queueName;
QueueClient queueClientInstance;
public AzureQueueService(IConfiguration configuration)
{
azureStorageAccountConnectionString = configuration[Constants.KEY_AZURE_STORAGE_ACCOUNT_CONNECTION_STRING];
queueName = configuration[Constants.KEY_QUEUE_NAME];
queueClientInstance = new QueueClient(azureStorageAccountConnectionString, queueName);
}
public QueueClient GetQueueClient()
{
return queueClientInstance ;
}
}
Now you can inject AzureQueueService in dependency injection
| |
doc_381
|
@Override
protected void onCreate(Bundle savedInstanceState){
Log.d(TAG, " onCreate(Bundle) - Ini ");
super.onCreate(savedInstanceState);
database = FirebaseDatabase.getInstance();
String videoId = "";
for(VideoEntity video: videosList) {
videoId = video.getId();
DatabaseReference mRef = database.getReference().child("Videos").push();
mRef.setValue(video);
}
this the VideoEntity class:
package com.app.entities;
import android.os.Parcel;
import android.os.Parcelable;
import java.io.Serializable;
public class VideoEntity implements Parcelable{
private String id;
private String title;
private String description;
private String thumbnailURL;
private String category;
public VideoEntity() {
}
public VideoEntity(Parcel in) {
id = in.readString();
title = in.readString();
description = in.readString();
thumbnailURL = in.readString();
category = in.readString();
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getThumbnailURL() {
return thumbnailURL;
}
public void setThumbnailURL(String thumbnail) {
this.thumbnailURL = thumbnail;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getCategory() {return category;}
public void setCategory(String category) { this.category = category;}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(id);
dest.writeString(title);
dest.writeString(description);
dest.writeString(thumbnailURL);
dest.writeString(category);
}
public static final Creator<VideoEntity> CREATOR = new Creator<VideoEntity>() {
@Override
public VideoEntity createFromParcel(Parcel in) {
return new VideoEntity(in);
}
@Override
public VideoEntity[] newArray(int size) {
return new VideoEntity[size];
}
};
}
The problem is that everytime I start this activity the same objects are inserted in the database, so i have duplicate data in the database.
Is there anyway to avoid this ?
A: If your data has a natural key, store it under its natural key. In your case the videos have an id field, which likely is unique already. So instead of storing the videos under a push ID, store them under their existing ID:
DatabaseReference mRef = database.getReference().child("Videos").child(video.getId());
mRef.setValue(video);
That way the next time you run the app, it will just write the same data in the same location again.
| |
doc_382
|
var input1 = new double[] {15, 20, 25};
dynamic test = Py.Import("Py_file_name");
double r1 = test.function_name(input1);
The value returned from function_name() method is converted to double and I can work with it as I want. But with more complicated code, the things go different, lets say, the retun is a numpy.array:
double [] r1 = test.function_name(input1);
Fails with the error Cannot implicitly convert type 'Python.Runtime.PyObject' to 'double []'.
I can get the value to object like this:
object r1 = test.ANN1_fun(input1);
But this do not solve anything, as I still have variable of type object {Python.Runtime.PyObject} and I cannot (I don't know how) use it in my C# project. How to convert this numpy.array to any C# array?
A: It's more like workaround than solution but I will leave it here, in case someone will deal similar problem in future. It seems that Pythonnet handle seamless only basic data types. So you must convert numpy array to something simpler, like list, on the python site, so assuming y1 is numpy array:
y1=y1.flatten('C') #Only if required by dimensions
y1= [arr.tolist() for arr in y1] #Converting to list
return y1
Now you can catch your value in C#
double [] r1 = test.function_name(input1);
And it will be converted correctly to C# array.
| |
doc_383
|
*
*A=3
*A<5 OR B>C
*A=null OR (B=3 AND C=false)
And then build up Mongo query expression. If there is such library it would help me a lot. Meanwhile I started with writing my own parser. I found Ohm.js that looks easy and it has online editor. I was able to get there:
Query {
exp = simpleExp | andExp | orExp
simpleExp = identifierName operator literal
andExp = simpleExp "AND" simpleExp
orExp = simpleExp " OR " simpleExp
identifierName = identifierStart identifierPart*
identifierStart = letter
identifierPart = letter | digit
nullLiteral = "null"
booleanLiteral = ("true" | "false")
decimalLiteral = digit*
stringLiteral = "\"" digit* "\""
literal = stringLiteral | decimalLiteral | booleanLiteral | nullLiteral
operator = "=" | "<" | ">" | ">=" | "<="
}
The online editor accepts trivial expressions (A=3) but it does not matches an AND/OR combined expressions. Where is my mistake? Btw I do not insist on this library, I can accept other parsers as well.
A: Two things are preventing your exp rule from matching the input A=2 AND B=3.
To better understand these, it would be a good idea to read Ohm's documentation, such as it is; specifically, the syntax reference.
First, the exp rule is a "lexical rule", in Ohm's terms, because its name starts with a lower-case letter. There's only a small difference between syntactic and lexical rules, but it's making all the difference here:
The difference between lexical and syntactic rules is that syntactic rules implicitly skip whitespace characters.
Since none of your rules are syntactic, whitespace is not ignored. But it's not recognised either, except by the somewhat odd " OR " token. In particular, the space before the AND cannot be recognised by the grammar so the parse fails at that point.
So a first step is to change simpleExp, andExp and orExp to syntactic rules by renaming them SimpleExp, AndExp and OrExp, respectively. You can then change " OR " to "OR" if you want to.
The second problem is not so simple. To solve it, it would be useful to look at the model used in the Ohm example arithmetic grammar. (Remember that grammars just have to do with the organisation of symbols; what the symbol means is dealt with elsewhere. So a grammar for boolean expressions using operators AND and OR differs from a arithmeric grammar using operators * and + only in how the operators are spelled. The way that the arithmetic language syntax determines that * has precedence over + is exactly the same as the way a boolean grammar would specify that AND has precedence over OR. But that's not the way your grammar is organized.
In particular, you are falling foul of a key aspect of PEG parsers (like Ohm), which is also mentioned in the Ohm documentation. Alternation (the | operator) in the PEG formalism is ordered: (emphasis added)
expr1 | expr2
Matches the expression expr1, and if that does not succeed, matches the expression expr2.
In other words, if expr1 matches, expr2 is never attempted.
With that in mind, consider the rule:
exp = simpleExp | andExp | orExp
Since both andExp and orExp start with a simpleExp, there is no way either of them could be matched. In order for them to match, simpleExp would have to match, and if simpleExp matches, the alternation succeeds immediately without trying other alternatives. (Many PEG parsing systems use / as the name of the alternation operator rather than | used by context-free grammars, in order to avoid confusing the semantics of the two operators. But Ohm chose not to do that.)
In fact, Ohm's example grammar is not really ideal; it suffers from the usual problem with top-down parsing (shared by PEG parsing), which cannot handle left-recursive grammars. As a result, the language described by the example grammar makes multiplication and addition right-associative. For multiplication and addition, this isn't a problem; (a*b)*c is mathematically the same as a*(b*c). But it would make a big difference to division and subtraction, since (a-b)-c is not the same as a-(b-c) (unless c is 0).
PEG grammars (and many top-down parser generators) compensate for this problem by allowing repetition operators in grammar rules. So it's quite possible that a better way of writing both grammars uses repetition:
Exp = AndExp ("OR" AndExp)*
AndExp = SimpleExp ("AND" SimpleExp)*
SimpleExp = identifierName operator literal | "(" Exp ")"
| |
doc_384
|
Errno::ENOENT: No such file or directory - /app/tmp/members_packaged_uncompressed.js
NoMethodError: undefined method `will_paginate' for #
These errors also occur locally when I run our app with Thin in production mode. Seems like there needs to be something configured for Thin to work properly with our code? Webrick does not give these errors for our app.
Any advice?
| |
doc_385
|
The WebService requires to use a .p12 certificate.
Unfortunately, I don't know where or how to set the certificate.
This is my current code:
BasicHttpsBinding binding = new BasicHttpsBinding();
binding.Name = "basic_ssl_cert";
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Certificate;
EndpointAddress address = new EndpointAddress("https://myWebService");
MyWebServiceGeneratedClass service = new MyWebServiceGeneratedClass(binding, address);
The MyWebServiceGeneratedClass does not offer anything, I could use to set the certificate.
Where or how can I set the certificate with the password?
UPDATE
The property ClientCredentials is only available on the generated service class but NOT on the generated interface on top of the service class.
As I was programming against the interface, i didn't see the property...
| |
doc_386
|
To explain the problem through an example, a User might have a collection of Books. A query populates the collection with a single API call to get all the user's "Favorite" books. A later query might simply request a single book, which may or may not have already been retrieved through the favorite books query.
What I'd like to do it maintain a normalized cache of Books, such as in an AtomFamily keyed by bookId, so I don't have two copies of books that are pulled with different queries. However, I run into a problem, which is that I would like to use Suspense for any one of the queries that retrieves one or more Books. And the natural way to do that with Recoil is to use an async Selector. But I don't see it, if there's a way to normalize the data fetched through async selectors.
Is there a pattern I am overlooking, that would allow me to use async selectors representing different queries that are backed by a shared, normalized AtomFamily?
For example, if I have this BAD code, which creates duplicate objects in my state, how might I rework it to maintain a shared cache for the actual Book objects, and still make use of Suspense if a query is still fetching when a component that uses this state renders?
Query 1: get a group of books through a selector:
const favoriteBooksSelector = selector({
key: 'MyFavoriteBooks',
get: async ({ get }) => {
const response = await allMyFavorityBooksDBQuery({
userID: get(currentUserIDState)
});
return response.books;
},
});
Query 2: get a single book, looks something like:
export const singleBookSelector = selectorFamily({
key: 'singleBookSelector',
get: (bookId: string) => async ({ get }) => {
const response = await singleBookDBQuery({
userID: get(currentUserIDState)
});
return response.book;
}
});
A: To utilize a cache, it must be indexed (keyed). For your example case, it is sensible to key a cache by book ID, so a KV cache is a reasonable choice. In JavaScript, a Map is a natural choice for such a cache.
Below, I have composed a fully-functional example of how to implement such a cache as a primary source for some Recoil atomFamily instances. The code is commented, and I can provide more explanation if anything is unclear.
An increasing query count is displayed as proof of the effectiveness of the cache. I have also included a link to the code in the TypeScript Playground for evaluation. If you would like to modify the code, all you need to do is copy it into a new answer (or just copy and paste it into local text editor and save it as an HTML file, and then serve it via a local http server).
TS Playground
<div id="root"></div><script src="https://unpkg.com/[email protected]/umd/react.development.js"></script><script src="https://unpkg.com/[email protected]/umd/react-dom.development.js"></script><script src="https://unpkg.com/[email protected]/umd/recoil.min.js"></script><script src="https://unpkg.com/@babel/[email protected]/babel.min.js"></script><script>Babel.registerPreset('tsx', {presets: [[Babel.availablePresets['typescript'], {allExtensions: true, isTSX: true}]]});</script>
<script type="text/babel" data-type="module" data-presets="tsx,react">
// import ReactDOM from 'react-dom';
// import {default as React, Suspense, useEffect, useState, type ReactElement, type ReactNode} from 'react';
// import {atomFamily, RecoilRoot, useRecoilValue} from 'recoil';
// This Stack Overflow snippet demo uses UMD modules instead of the above import statments
const {Suspense, useEffect, useState} = React;
const {atomFamily, RecoilRoot, useRecoilValue} = Recoil;
type Book = {
author: string;
id: string;
title: string;
};
// Database simulation:
// The simulated database
const db = new Map<string, Book>();
// Scraped from https://www.penguin.co.uk/articles/2018/100-must-read-classic-books.html#100
(JSON.parse(`[{"author":"Jane Austen","title":"Pride and Prejudice","id":"BnuQKALlW6B6sZNU4bdaB"},{"author":"Harper Lee","title":"To Kill a Mockingbird","id":"UM3ms9hlnTbEmx44JknKc"},{"author":"F. Scott Fitzgerald","title":"The Great Gatsby","id":"hBl51iaNCQ8qZw5iec8hD"},{"author":"Gabriel García Márquez","title":"One Hundred Years of Solitude","id":"CC9hIXCdEHR0beJlbMF_y"},{"author":"Truman Capote","title":"In Cold Blood","id":"l0iJfZNmNBfioHDnHARWQ"},{"author":"Jean Rhys","title":"Wide Sargasso Sea","id":"D0UY9kmrV6HbqlIMspVwn"},{"author":"Aldous Huxley","title":"Brave New World","id":"rK2ks0GbZBDQPns-ZDEyW"},{"author":"Dodie Smith","title":"I Capture The Castle","id":"flTB4dqKfg1PWcUI6KtH2"},{"author":"Charlotte Bronte","title":"Jane Eyre","id":"3x-S6EsNUTZ5l_sESamF_"},{"author":"Fyodor Dostoevsky","title":"Crime and Punishment","id":"ntH3G63fMVKUud6rRhDbY"},{"author":"Donna Tartt","title":"The Secret History","id":"ubrxbS1-7NEr_lml6I8Q3"},{"author":"Jack London","title":"The Call of the Wild","id":"friqBlVlEY3eg2cpkgUET"},{"author":"John Wyndham","title":"The Chrysalids","id":"wRMQGG1QYaeVXXP_ghl-x"},{"author":"Jane Austen","title":"Persuasion","id":"YoMqTM9PhAfctMBqSdz6P"},{"author":"Herman Melville","title":"Moby-Dick","id":"Kd0Oggfkf5AQPGBqpw_iE"},{"author":"C.S. Lewis","title":"The Lion, the Witch and the Wardrobe","id":"-jD0Ujt-r54xbKZ_7Jv59"},{"author":"Virginia Woolf","title":"To the Lighthouse","id":"1TJQYcP6_hwm2syHUH8Dv"},{"author":"Elizabeth Bowen","title":"The Death of the Heart","id":"dl1qbyM0cHdmYUHKhTyZk"},{"author":"Thomas Hardy","title":"Tess of the d'Urbervilles","id":"_i6SLfaMpXRuhVqEH5Jhp"},{"author":"Mary Shelley","title":"Frankenstein","id":"ZPL-swiUogF-_gdabf9qv"},{"author":"Mikhail Bulgakov","title":"The Master and Margarita","id":"x0pw07n3o2KljHZM11isw"},{"author":"L. P. Hartley","title":"The Go-Between","id":"l0jHUSb4bY64k-l9Qed5Z"},{"author":"Ken Kesey","title":"One Flew Over the Cuckoo's Nest","id":"SCKsZTWD2QMsNomUie_Vf"},{"author":"George Orwell","title":"Nineteen Eighty-Four","id":"JscV73l2tSdm5W4kZSvZn"},{"author":"Thomas Mann","title":"Buddenbrooks","id":"f0XqwYfsWJ-w9J18b5FCD"},{"author":"John Steinbeck","title":"The Grapes of Wrath","id":"OnXfkmQEAL7sSQ3PgSV9z"},{"author":"Toni Morrison","title":"Beloved","id":"n3_aZgBlQkphqPTvmJGr6"},{"author":"P. G. Wodehouse","title":"The Code of the Woosters","id":"TzD6k5flXf8HMdfgSacMT"},{"author":"Bram Stoker","title":"Dracula","id":"_WPS6E_6uXVKWX0r2Sop6"},{"author":"J. R. R. Tolkien","title":"The Lord of the Rings","id":"bIzyksKmB0plzGwWI6h7l"},{"author":"Mark Twain","title":"The Adventures of Huckleberry Finn","id":"ctQZfUT_tsujBCdYkv4HA"},{"author":"Charles Dickens","title":"Great Expectations","id":"ULj9NAatfo8tCCe39YZTY"},{"author":"Joseph Heller","title":"Catch-22","id":"bOOUBZK7oFVDRrevxApvN"},{"author":"Edith Wharton","title":"The Age of Innocence","id":"ZJ8y0y-BbnaH5A9TulxgN"},{"author":"Chinua Achebe","title":"Things Fall Apart","id":"eahxg8sFYsudKEl9hocJv"},{"author":"George Eliot","title":"Middlemarch","id":"TLNUskf7TspVe3AOEV4nX"},{"author":"Salman Rushdie","title":"Midnight's Children","id":"0_DeHTlQpW4ffy-liu2R-"},{"author":"Homer","title":"The Iliad","id":"D9cyf2yCAwhnASsxGxtTd"},{"author":"William Makepeace Thackeray","title":"Vanity Fair","id":"YmXxLcLMYmuFkp39Q1aAa"},{"author":"Evelyn Waugh","title":"Brideshead Revisited","id":"p3D_ZtFdhT2Eytv7swOAZ"},{"author":"J.D. Salinger","title":"The Catcher in the Rye","id":"3Sf-5_lsdGVeiWJeSZZQI"},{"author":"Lewis Carroll","title":"Alice’s Adventures in Wonderland","id":"TJJ6J8OHF5PRaiHLEcPdq"},{"author":"George Eliot","title":"The Mill on the Floss","id":"F6S5twxijUt7cSvuoSeKH"},{"author":"Anthony Trollope","title":"Barchester Towers","id":"0jYVd6dhiSF1tJYuIU8az"},{"author":"James Baldwin","title":"Another Country","id":"xRjGwu2vOQObLqbFccnw_"},{"author":"Victor Hugo","title":"Les Miserables","id":"GR24l64YVjFagi-SB1Y-H"},{"author":"Roald Dahl","title":"Charlie and the Chocolate Factory","id":"CAoAoALD3T8wxX0Eevabi"},{"author":"S. E. Hinton","title":"The Outsiders","id":"XYhNMkKTKsh9aNGh24fvZ"},{"author":"Alexandre Dumas","title":"The Count of Monte Cristo","id":"Igcm-Wxq2Uf8vKjBr-D7j"},{"author":"James Joyce","title":"Ulysses","id":"GiianKDQPQVTIaFoFhy6H"},{"author":"John Steinbeck","title":"East of Eden","id":"belUus-Sta74zWfjTiuMW"},{"author":"Fyodor Dostoyevsky","title":"The Brothers Karamazov","id":"wp9JOJ0B8lKmxG0siRuR4"},{"author":"Vladimir Nabokov","title":"Lolita","id":"tvnoXyLsd-PtVmiwZLnM8"},{"author":"Frances Hodgson Burnett","title":"The Secret Garden","id":"VZyJI95JMwkj4rJOJbzzn"},{"author":"Evelyn Waugh","title":"Scoop","id":"QYgFDNe1S0x5V_ub-Vc-S"},{"author":"Charles Dickens","title":"A Tale of Two Cities","id":"G0FUeqOiLuNnBNEr4XPD2"},{"author":"George Grossmith and Weedon Grossmith","title":"Diary of a Nobody","id":"PLi0tMjdAZI54P3U02B2N"},{"author":"Leo Tolstoy","title":"Anna Karenina","id":"E0OlPZ9F8Z3rsEmGihW-0"},{"author":"Alessandro Manzoni","title":"The Betrothed","id":"hPHRkfbcMUeJUejXy7spa"},{"author":"Virginia Woolf","title":"Orlando","id":"FSzptVHC-ICRl0tlPhS-O"},{"author":"Ayn Rand","title":"Atlas Shrugged","id":"CdzIlNo9jp5CDAP5BEwLi"},{"author":"H. G. Wells","title":"The Time Machine","id":"dQn4oEs0hqgfuaFR13S-o"},{"author":"Sun-Tzu","title":"The Art of War","id":"LZwoJLEtLv4Dx2QnUBvwM"},{"author":"John Galsworthy","title":"The Forsyte Saga","id":"p9hOPd4gC7PKX9bbp8JVZ"},{"author":"John Steinbeck","title":"Travels with Charley","id":"c3LtQi5_p-XSF2JSfPOjq"},{"author":"Henry Miller","title":"Tropic of Cancer","id":"iFILNdFzltGXugvwpUjSS"},{"author":"D. H. Lawrence","title":"Women in Love","id":"gYf7mAVCM_SX5e3NDwc9y"},{"author":"Paul Scott","title":"Staying On","id":"gZYOkRz4APlcDGNH5onYD"},{"author":"Kenneth Grahame","title":"The Wind in the Willows","id":"epTCvsskVjm3vnomZCPRw"},{"author":"Willa Cather","title":"My Ántonia","id":"wWoBKiKEQ6KpwigH2RtMQ"},{"author":"Emily Brontë","title":"Wuthering Heights","id":"8Feh8HOHmfFZXwhkclUmj"},{"author":"Patrick Süskind","title":"Perfume","id":"JJntMbxqiKvuryEO82VAX"},{"author":"Leo Tolstoy","title":"War and Peace","id":"CPfDnuxwDYeLvzqLPJzXJ"},{"author":"Somerset Maugham","title":"Of Human Bondage","id":"h4IW8mQUmLTJ9uyfVe2qe"},{"author":"Charles Dickens","title":"Bleak House","id":"NPkSH3PieOiq_gE0svlxB"},{"author":"Honoré de Balzac","title":"Lost Illusions","id":"0Ckpg5CMzAYIUbCjWZXPt"},{"author":"Kurt Vonnegut","title":"Breakfast of Champions","id":"Lydqp4eMEkYL3YVkg0krr"},{"author":"Charles Dickens","title":"A Christmas Carol","id":"ApOCi4LPkvoN2R47C1frw"},{"author":"George Eliot","title":"Silas Marner","id":"5CUwpkfRyLjTBBmJHc0Ic"},{"author":"Virginia Woolf","title":"Mrs Dalloway","id":"9Pdh2b7of93bT-Xp1egBB"},{"author":"Louisa May Alcott","title":"Little Women","id":"095_BrLfJD-pI2nOtqJII"},{"author":"Iris Murdoch","title":"The Sea, The Sea","id":"5V4JjZvcqWhiLTdpYjc5r"},{"author":"Mario Puzo","title":"The Godfather","id":"cK1YXvMZ4xRZVFyQDKcG3"},{"author":"Franz Kafka","title":"The Castle","id":"bV5hrXcPzSfPhLPITPlj7"},{"author":"Robert Graves","title":"I, Claudius","id":"2FFaA72V-Pp74A6mZajR7"},{"author":"J.M. Barrie","title":"Peter Pan","id":"6vwOgrhQTp60ISU-KIxoQ"},{"author":"John Kennedy Toole","title":"A Confederacy of Dunces","id":"zZwqEBfR72Ht_Uwa25blx"},{"author":"W. Somerset Maugham","title":"The Razor's Edge","id":"uL-eIpi0xf11BDmpxfxYQ"},{"author":"Flora Thompson","title":"Lark Rise to Candleford","id":"wISh6hRf-rIOXzGV9pReU"},{"author":"Thomas Hardy","title":"The Return of the Native","id":"ouX9cTm5gF36zX95SfOaE"},{"author":"James Joyce","title":"A Portrait of the Artist as a Young Man","id":"dX6B1SNtZH_Kij9ZdQ3cx"},{"author":"Joseph Conrad","title":"Heart of Darkness","id":"uQk4tRerBAtFtZwh-Xyx3"},{"author":"Elizabeth Gaskell","title":"North and South","id":"8bRGCx_5Pk3i4-RNXlley"},{"author":"Margaret Atwood","title":"The Handmaid's Tale","id":"E0tJsPHR6JnnoQ9UKtKHE"},{"author":"Irene Nemirovsky","title":"Suite Francaise","id":"0lq5lUjV7A0SMvUF-ucmv"},{"author":"Alexander Solzhenitsyn","title":"One Day in the Life of Ivan Denisovich","id":"3Qik1V1BoZZDyPphzedzb"},{"author":"Jonathan Coe","title":"What A Carve Up!","id":"UhNcCOU_TzUDbTOvxzUPU"},{"author":"Robert Pirsig","title":"Zen and the Art of Motorcycle Maintenance","id":"Alpfu_s-Ee8L6G1s7-WD2"},{"author":"Fyodor Dostoyevsky","title":"White Nights","id":"Lr3KmI-pOxer7rSsF8MhE"},{"author":"Charles Dickens","title":"Hard Times","id":"OrxuKkQoEgg2cSDQcyyPc"}]`) as Book[])
.forEach(book => db.set(book.id, book));
function delay (ms: number): Promise<void> {
return new Promise(resolve => setTimeout(resolve, ms));
}
function randomInt (min = 0, max = 1): number {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
// Simulated db methods
const booksDb = {
async getOne (id: string): Promise<Book | undefined> {
return (await this.getMany([id]))[0];
},
async getMany (ids: string[]): Promise<(Book | undefined)[]> {
await delay(randomInt(50, 500));
return ids.map(id => {
const book = db.get(id);
// Simulate getting a copy every time
return book ? {...book} : undefined;
});
},
};
// Recoil state:
// Cached results
const booksCache = new Map<string, Book>();
// Just for this demo, maintain a query count
let dbQueryCount = 0;
// Inspired by effector, I prefix recoil-related variables with $ to simplify naming
const $book = atomFamily<Book | undefined, string>({
key: 'book',
default: async (id) => {
// Return from cache, querying db only if unavailable
if (!booksCache.has(id)) {
dbQueryCount += 1;
const book = await booksDb.getOne(id);
if (book) booksCache.set(id, book);
}
return booksCache.get(id);
},
});
const $books = atomFamily<(Book | undefined)[], string[]>({
key: 'books',
default: async (ids) => {
const books: (Book | undefined)[] = [];
const available: [index: number, id: string][] = [];
const unavailable: [index: number, id: string][] = [];
// Split query into collections of available in cache or not
for (const [index, id] of ids.entries()) {
const isAvailable = booksCache.has(id);
(isAvailable ? available : unavailable).push([index, id]);
}
// Get cached results
for (const [index, id] of available) {
books[index] = booksCache.get(id);
}
// Query the remaining with a single network request
dbQueryCount += 1;
const booksFromDb = await booksDb.getMany(unavailable.map(([, id]) => id));
// Update cache and finalize
for (const [index, id] of unavailable) {
const book = booksFromDb[index];
if (book) booksCache.set(id, book);
books[index] = booksCache.get(id);
}
return books;
},
});
// Components:
function BookComponent ({book}: { book: Book | undefined }): ReactElement {
if (!book) return (<div>Book is not availble</div>);
return (
<div>
<em>{book.title}</em> by <span>{book.author}</span>
</div>
);
}
function BookFromId ({id}: { id: string }): ReactElement {
const book = useRecoilValue($book(id));
return <BookComponent {...{book}} />;
}
function BookCollection ({ids}: { ids: string[]; }): ReactElement {
// To see these loaded individually, uncomment the following lines:
// return (<div>{ids.map((id, index) => (
// <BookFromId {...{id, key: `${index}-${id}`}} />
// ))}</div>);
const books = useRecoilValue($books(ids));
return (<div>{books.map((book, index) => (
<BookComponent {...{book, key: `${index}-${book?.id}`}} />
))}</div>);
}
function LoadingDiv ({children}: { children?: ReactNode }): ReactElement {
return (<div>{children}</div>);
}
const collections: [title: string, ids: string[]][] = [
['Titles starting with A', ['ApOCi4LPkvoN2R47C1frw', 'zZwqEBfR72Ht_Uwa25blx', 'dX6B1SNtZH_Kij9ZdQ3cx', 'G0FUeqOiLuNnBNEr4XPD2', 'TJJ6J8OHF5PRaiHLEcPdq', 'E0OlPZ9F8Z3rsEmGihW-0', 'xRjGwu2vOQObLqbFccnw_', 'CdzIlNo9jp5CDAP5BEwLi']],
['Titles starting with B', ['0jYVd6dhiSF1tJYuIU8az', 'n3_aZgBlQkphqPTvmJGr6', 'NPkSH3PieOiq_gE0svlxB', 'rK2ks0GbZBDQPns-ZDEyW', 'Lydqp4eMEkYL3YVkg0krr', 'p3D_ZtFdhT2Eytv7swOAZ', 'f0XqwYfsWJ-w9J18b5FCD']],
['Titles starting with C', ['bOOUBZK7oFVDRrevxApvN', 'CAoAoALD3T8wxX0Eevabi', 'ntH3G63fMVKUud6rRhDbY']],
];
type OrPromise<T> = T | Promise<T>;
function useLazyValue <T>(initialValue: T, producer: () => OrPromise<T>): T {
const [value, setValue] = useState(initialValue);
const updateValue = async () => {
const result = await producer();
if (value !== result) setValue(result);
};
useEffect(() => void updateValue());
return value;
}
function App (): ReactElement {
const [collectionIndex, setCollectionIndex] = useState(0);
const collectionIds = collections[collectionIndex]![1];
const queryCount = useLazyValue(0, () => dbQueryCount);
const booksLoading = <LoadingDiv>The collection is loading...</LoadingDiv>;
return (
<div style={{
display: 'flex',
flexDirection: 'column',
gap: '0.5rem',
fontFamily: 'sans-serif',
}}>
<h1>Recoil book cache</h1>
<div>Query count: {queryCount}</div>
<label>
<div>Select a collection:</div>
<select
onChange={ev => setCollectionIndex(Number(ev.target.value))}
value={collectionIndex}
>{collections.map(([title], index) => (
<option key={`${index}-${title}`} value={index}>{title}</option>
))}</select>
</label>
<Suspense fallback={booksLoading}>
<BookCollection ids={collectionIds} />
</Suspense>
</div>
);
}
function AppRoot (): ReactElement {
return (
<RecoilRoot>
<App />
</RecoilRoot>
);
}
ReactDOM.render(<AppRoot />, document.getElementById('root'));
</script>
| |
doc_387
|
$ node inspect cypress/support/reset-fixture.js teardown
In that file I have a call to a place where there is a debugger; statement.
I type c to continue to that place.
Once I get there, I type repl and in the repl I type require.
I get an error saying that in that place there is no require: ReferenceError: require is not defined.
The terminal session is below:
/m/s/S/L/T/volto-slate-project > node inspect cypress/support/reset-fixture.js teardown
< Debugger listening on ws://127.0.0.1:9229/0b6b3784-8e0c-4c35-8baa-46ea102b4bfa
< For help, see: https://nodejs.org/en/docs/inspector
< Debugger attached.
Break on start in cypress/support/reset-fixture.js:1
> 1 const xmlrpc = require('xmlrpc');
2
3 // const args = process.argv;
debug> c
break in node_modules/xmlrpc/lib/client.js:119
117
118 if (response.statusCode == 404) {
>119 debugger;
120 callback(__enrichError(new Error('Not Found')))
121 }
debug> repl
Press Ctrl + C to leave debug repl
> require
ReferenceError: require is not defined
at eval (eval at <anonymous> (/media/silviu/Samsung_T5/Lucru/Tibi/volto-slate-project/node_modules/xmlrpc/lib/client.js:119:7), <anonymous>:1:1)
at Client.<anonymous> (/media/silviu/Samsung_T5/Lucru/Tibi/volto-slate-project/node_modules/xmlrpc/lib/client.js:119:7)
at Object.onceWrapper (events.js:422:26)
at ClientRequest.emit (events.js:315:20)
at HTTPParser.parserOnIncomingClient [as onIncoming] (_http_client.js:596:27)
at HTTPParser.parserOnHeadersComplete (_http_common.js:119:17)
at Socket.socketOnData (_http_client.js:469:22)
at Socket.emit (events.js:315:20)
at addChunk (_stream_readable.js:295:12)
at readableAddChunk (_stream_readable.js:271:9)
If I do not type c in the above-presented session, require seems to exist and can be used.
How can I use require after that c?
I use this Node version: v12.18.0.
Thank you.
Update
I have posted an answer, but further explanation would help. A more detailed answer that explains how things work behind the scenes would be very nice.
A: If I put this line:
console.dir(require);
before the line:
debugger;
then when the debugger; line is hit, in the repl of the Node debugger the require function is defined well.
| |
doc_388
|
This is the code I am using to send an FCM push notification via AWS Lambda written in Python. The AWS code is deployed on Lambda using the Zappa package:
# SENDING FCM NOTIFICATION
notification_headers = {
'Content-Type': 'application/json',
'Authorization': 'key=' + serverToken,
}
body_en = {
'notification': {
'title': post['src'],
'body': post['title'],
'click_action': 'FLUTTER_NOTIFICATION_CLICK',
'sound': 'default'
},
'to': deviceToken,
'priority': 'high',
'content_available': 'true',
}
response_en = requests.post(
"https://fcm.googleapis.com/fcm/send",
headers = notification_headers,
data = json.dumps(body_en)
)
return response_en
Are there any imports I must do before being able to use FCM in AWS Lambda?
| |
doc_389
|
I referred couple of forum links in StackOverflow but it doesn't help me.
I'm using angular version 1.3.0
HTML
<!DOCTYPE html>
<html ng-app="myModule">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<script src="/js/lib/angular-1.3.0/angular.js"></script>
<script src="/js/lib/controllers/ifRepeatController.js"></script>
</head>
<body>
<div ng-repeat = "data in comments">
<div ng-if="data.type == 'hootsslllll' ">
//differnt template with hoot data
</div>
<div ng-if="data.type == 'story' ">
//differnt template with story data
</div>
<div ng-if="data.type == 'article' ">
//differnt template with article data
</div>
</div>
</body>
</html>
Controller
var myIfRepeat = angular.module('myIfRepeat',[]);
myIfRepeat.controller('IfRepeatController', function ($scope,$http) {
$scope.comments = [
{"_id":"1",
"post_id":"1",
"user_id":"UserId1",
"type":"hoot"},
{"_id":"2",
"post_id":"2",
"user_id":"UserId2",
"type":"story"},
{"_id":"3",
"post_id":"3",
"user_id":"UserId3",
"type":"article"}
];
});
As per the first condition, the first line should not get displayed (Below find the screenshot for more reference), however the line is getting displayed.
the reference link : Using ng-if inside ng-repeat?
Now i added the controller in the div as advised, however i'm facing the same issue
Below i have given the screenshot for reference. Kindly help me how to solve this issue and please let me know in case of further clarifications.
Below provided screenshot on the working model used angular 1.3 version. If we use angular 1.0.2 the nf-if will not work properly (below provided the screenshot)
Screen shot for angular version 1.0.2
A: I'm not having issues with this working. Tweaked your code to fit into a fiddle
<div ng-app ng-controller="IfRepeatController">
<div ng-repeat="data in comments">
<div ng-if="data.type == 'hootsslllll' ">type={{data.type}}//differnt template with hoot data</div>
<div ng-if="data.type == 'story' ">type={{data.type}}//differnt template with story data</div>
<div ng-if="data.type == 'article' ">type={{data.type}}//differnt template with article data</div>
</div>
</div>
function IfRepeatController($scope) {
$scope.comments = [{
"_id": "1",
"post_id": "1",
"user_id": "UserId1",
"type": "hoot"
}, {
"_id": "2",
"post_id": "2",
"user_id": "UserId2",
"type": "story"
}, {
"_id": "3",
"post_id": "3",
"user_id": "UserId3",
"type": "article"
}];
}
Note: reference angular 1.3.0 here: https://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.7/angular.min.js
A: You are missing ng-controller:
<body ng-controller="IfRepeatController">
A: I have a similar issue. I cannot get ng-if to work correctly. The only way to get it to work is to evaluate the ng-if to the not operator (ng-if="!variableValue"). Is this an AngularJS version issue?
A: This in not AngularJs Version issue, If variableValue has boolean it will work fine.
Sample code like this:
$scope.variableValue = true; in Controller
"<"div ng-if="!variableValue" ">"Don't show content"<"/div">"// This DIV doesn't show the content
"<"div ng-if="variableValue" ">"show content"<"/div">" // This DIV will show the content
| |
doc_390
|
$url = $_GET['url'];
print($url);
.htaccess file:
RewriteEngine On
RewriteBase /
RewriteRule ^get/(.*)/?$ /get.php?url=$1 [L]
I can get up to the question mark when I do it this way.
Example: http://example.com/get/http://example.com?id=1&ad=mahmut
I am getting this result: http://example.com
How can i solve this problem? I tried many examples on the site but failed.
A: Trick is to not to use RewriteRule since you will get only URI part before ?.
You should be using a RewriteCond with THE_REQUEST variable for this:
Options -MultiViews
RewriteEngine On
RewriteCond %{QUERY_STRING} !(^|&)url= [NC]
RewriteCond %{THE_REQUEST} \s/+get/(\S*)\s [NC]
RewriteRule ^ get.php?url=%1 [L,QSA]
THE_REQUEST variable represents original request received by Apache from your browser and it doesn't get overwritten after execution of other rewrite directives. Example value of this variable is GET /index.php?id=123 HTTP/1.1
| |
doc_391
|
Now I had two ideas but I would like to know which one would be easier and how to implement them.
*
*Should I do it with a webview that when online shows the table from the website and when offline shows a cached version?
*Or should I somehow do it with a local database?
*Or suggest something that would be even better/easier?
A: the best practice as i do, is to make a local database for this app,
then call a webservice to get information from the server that fills the web page as xml form, finally parse the xml and insert values into your database.
| |
doc_392
| ||
doc_393
|
How to build the Sql table structure for this?
I thought about building two tables, clients and suppliers. The client table has a client per row, which has one column with the name of the client and the other with (an array?) the suppliers they have.
The suppliers table, instead, would be a supplier per row with its name and the 5 questions and the relative answers as columns. The Client table would have the foreign key in the suppliers column, that would communicate with the suppliers table.
The problem is, every client has different entries for the questions column of the suppliers so I don't know how to differentiate the single supplier for each client who will fill the form.
How would your approach be on this?
Thanks in advance
A: Here is a simple ERD of how I would do that:
Explanation
The tables you already have:
*
*The Client table stores data directly about client.
*The Suppliers table stores data directly about the supplier.
Then I've added:
*
*A dedicated Questions table allows you to decouple the questions from the DB schema. You can add/remove questions at will in the future as rows in this table.
Lastly, instead of adding more columns, relationships are given their own tables. Don't be afraid of having more tables.
*
*The ClientSuppliers table records the links between a Client and a Supplier. This will help determine who to send survey questions to about which supplier.
*The ClientSuppliersAnswers table records the response of a specific client to a specific question about a specific question (note the 3 FKs).
A: I will try to explain a little.
But first, if you want to design correctly a data structure you have to learn quite few things :
*
*Normal forms : https://www.geeksforgeeks.org/database-normalization-normal-forms/
*MERISE or UML : (I have preferences for MERISE that is by experience most adapted to the database world, but it is quite difficult to have resources in english on it)
*
*UML : http://tdan.com/uml-as-a-data-modeling-notation-part-1/8457
*Merise : http://y.mieg.free.fr/EFREI-DBMS/07-Design-E-R.pdf
(And this is only for RDBMS, if you need NoSQL structure : you will need to roll-up your sleeves a little more)
As a piece of advice I will give a methodology that I hope quite clear in data modelisation :
*
*First : define all your terms with the structure that follows
| name
| type [alpha; alphanumerical; numerical; boolean; datetime; entity]
| a proper description
| which entity is depending on
*
*Second : define all your relations and cardinalities
For exemple : 1 client = n suppliers / 0 suppliers = n client
*Third : Design your relational model
(* Fourth : Anticipate performances you will need for your warranty period at minimum)
*Fifth : Choose the technology which receive your structure by raise your humidified finger to the sky if you skipped the fourth part.
*Sixth : Design your physical model (what is going to be put on your hardware)
Now, what you are here for
On a postgresql rdbms, this is a possible solution:
create table supplier (id int primary key, suppliers_name varchar(50));
create table client (id int primary key, client_name varchar (50) unique);
create table question (id int primary key, question_definition varchar(500));
create table question_client (id int primary key, id_suppliers int references supplier(id), id_client int references client (id), id_question int references question(id), question_date timestamp, answer varchar (500));
Now : why ?
With the amount of information you gave me I figured that you needed, why not, only one table after all.
QUESTIONS (client_name varchar, supplier_name varchar, answer_to_question_1 varchar, answer_to_question_2 varchar [...])
And keep the question in your middleware instead of your database.
This form is wrong in many ways and I am sure you figure already some of them, but I have seen this so much time, I felt like explain why is it so wrong.
*
*Lesson 1 : no doubled data Keep that in mind : doubled data are a nightmare. And a living one when you need to have a match on only one client client 'Smith' but someone registered it as 'Smiss'... Who knows if it is the same? The guy that had registered the client? Sorry : in not in the company anymore. The client? Yeah : tell to your client that he paid you for a job that you cannot perform. You will be received. (there is few exceptions, but I can't tell everything in one post).
So from this lesson, we define the structure has follows :
*
*QUESTION (question_description varchar)
*CLIENT (name varchar)
*SUPPLIER (name varchar)
But how to link all of that?
*
*Lesson 2 : primary keys. A lot of modelisation will tell to you that you need to use a field that is unique as a primary key. Or a combination of them. For example : you could be tempted to use the CLIENT name as a primary key. Okay. And in the future you will have another client with the same name... Why not? Can you predict the future? Do you think your healthcare number is unique? Okay : are you sure it will be in the future? Everything changes, everyday. My advice : use a one column int primary key, always
*Lesson 3 : apply the normal forms : There is plenty of example why on the web and my post is already a little to long to explain all of them. But trust me and just do it. You'll learn why studying them.
What have we now ?
*
*CLIENT (id int PK, name varchar)
*SUPPLIER (id int PK, name varchar)
*QUESTION (id int PK, question_definition varchar)
Now we can link all of those with the following table :
QUESTION_CLIENT (id int PK, id_client int REF, id_question int REF, id_supplier int REF, answer varchar)
At this I had a datetime attribute to let you the latitude to answer more than one time the question to your client and find when you did.
There is a lot more to say about relationnal databases modelisation but I hope this is a good start for you to answer : 'How would your approach be on this?' by yourself in the future.
Hope this helps ;)
| |
doc_394
|
A simplified code snippet that demonstrates the problem here:
#include "stdafx.h"
#include <functional>
#include <memory>
class FS
{
};
typedef std::shared_ptr<FS> FSPtr;
class FSM
{
public:
FSM() : m_pFs(new FS()) {}
template <typename CALLABLE, typename... ARGS>
typename std::enable_if<std::is_same<bool, std::result_of_t<CALLABLE(ARGS&&...)>>::value, std::result_of_t<CALLABLE(ARGS&&...)>>::type
All(CALLABLE fn, ARGS&&... args) const // line 21
{
std::function<bool()> rFunc = std::bind(fn, m_pFs, args...);
bool bSuccess = rFunc();
return bSuccess;
}
private:
FSPtr m_pFs;
};
class SFF
{
public:
SFF() : m_pFsm(new FSM()) {}
bool VF(FSPtr pFs)
{
return nullptr != pFs;
}
bool Do()
{
return m_pFsm->All(std::bind(&SFF::VF, this, std::placeholders::_1)); // line 41
}
bool TF(FSPtr pFs, int n)
{
return nullptr != pFs && 0 != n;
}
bool Do1(int n)
{
return m_pFsm->All(std::bind(&SFF::TF, this, std::placeholders::_1, std::placeholders::_2), n); // line 49
}
private:
std::shared_ptr<FSM> m_pFsm;
};
int _tmain(int argc, _TCHAR* argv[])
{
SFF oSff;
bool bOk1 = oSff.Do();
bool bOk2 = oSff.Do1(4);
int rc = (bOk1 && bOk2) ? 0 : 1;
return rc;
}
And the errors VS2017 VC compiler output is:
1>------ Build started: Project: ConsoleApplication1, Configuration: Debug Win32 ------
1>ConsoleApplication1.cpp
1>c:\program files (x86)\microsoft visual studio\2017\professional\vc\tools\msvc\14.11.25503\include\utility(486): error C2338: tuple index out of bounds
1>c:\program files (x86)\microsoft visual studio\2017\professional\vc\tools\msvc\14.11.25503\include\functional(887): note: see reference to class template instantiation 'std::tuple_element<0,std::tuple<>>' being compiled
1>c:\program files (x86)\microsoft visual studio\2017\professional\vc\tools\msvc\14.11.25503\include\tuple(793): note: see reference to function template instantiation 'const tuple_element<_Index,_Tuple>::type &&std::get(const std::tuple<_Rest...> &&) noexcept' being compiled
1> with
1> [
1> _Tuple=std::tuple<_Rest...>
1> ]
1>c:\users\s.chan\source\repos\consoleapplication1\consoleapplication1\consoleapplication1.cpp(41): note: see reference to class template instantiation 'std::result_of<std::_Binder<std::_Unforced,bool (__thiscall SFF::* )(FSPtr),SFF *,const std::_Ph<1> &> (void)>' being compiled
1>c:\users\s.chan\source\repos\consoleapplication1\consoleapplication1\consoleapplication1.cpp(21): note: while compiling class template member function 'std::enable_if<std::is_same<bool,result_of<_Ty>::type>::value,result_of<_Ty>::type>::type FSM::All(CALLABLE,ARGS &&...) const'
1> with
1> [
1> _Ty=CALLABLE (ARGS &&...)
1> ]
1>c:\users\s.chan\source\repos\consoleapplication1\consoleapplication1\consoleapplication1.cpp(41): error C2672: 'FSM::All': no matching overloaded function found
1>c:\users\s.chan\source\repos\consoleapplication1\consoleapplication1\consoleapplication1.cpp(41): error C2893: Failed to specialize function template 'std::enable_if<std::is_same<bool,result_of<_Ty>::type>::value,result_of<_Ty>::type>::type FSM::All(CALLABLE,ARGS &&...) const'
1> with
1> [
1> _Ty=CALLABLE (ARGS &&...)
1> ]
1>c:\users\s.chan\source\repos\consoleapplication1\consoleapplication1\consoleapplication1.cpp(41): note: With the following template arguments:
1>c:\users\s.chan\source\repos\consoleapplication1\consoleapplication1\consoleapplication1.cpp(41): note: 'CALLABLE=std::_Binder<std::_Unforced,bool (__thiscall SFF::* )(FSPtr),SFF *,const std::_Ph<1> &>'
1>c:\users\s.chan\source\repos\consoleapplication1\consoleapplication1\consoleapplication1.cpp(41): note: 'ARGS={}'
1>c:\users\s.chan\source\repos\consoleapplication1\consoleapplication1\consoleapplication1.cpp(49): error C2672: 'FSM::All': no matching overloaded function found
1>c:\users\s.chan\source\repos\consoleapplication1\consoleapplication1\consoleapplication1.cpp(49): error C2893: Failed to specialize function template 'std::enable_if<std::is_same<bool,result_of<_Ty>::type>::value,result_of<_Ty>::type>::type FSM::All(CALLABLE,ARGS &&...) const'
1> with
1> [
1> _Ty=CALLABLE (ARGS &&...)
1> ]
1>c:\users\s.chan\source\repos\consoleapplication1\consoleapplication1\consoleapplication1.cpp(49): note: With the following template arguments:
1>c:\users\s.chan\source\repos\consoleapplication1\consoleapplication1\consoleapplication1.cpp(49): note: 'CALLABLE=std::_Binder<std::_Unforced,bool (__thiscall SFF::* )(FSPtr,int),SFF *,const std::_Ph<1> &,const std::_Ph<2> &>'
1>c:\users\s.chan\source\repos\consoleapplication1\consoleapplication1\consoleapplication1.cpp(49): note: 'ARGS={int &}'
1>Done building project "ConsoleApplication1.vcxproj" -- FAILED.
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
Any help is much appreciated.
A: The reason why your code doesn't compile is the following:
bool Do()
{
return m_pFsm->All(std::bind(&SFF::VF, this, std::placeholders::_1));
}
Here you use wrapper function All to call VF function. But:
1) All function is supposed to get the function arguments:
template <typename CALLABLE, typename... ARGS>
typename std::enable_if<std::is_same<bool, std::result_of_t<CALLABLE(ARGS&&...)>>::value, std::result_of_t<CALLABLE(ARGS&&...)>>::type
All(CALLABLE fn, ARGS&&... args) const // line 21
{
std::function<bool()> rFunc = std::bind(fn, m_pFs, args...);
bool bSuccess = rFunc();
return bSuccess;
}
Args here should stand for single argument of FSPtr type, see the signature of SFF::VF.
So the correct code should be:
return m_pFsm->All(std::bind(&SFF::VF, this, std::placeholders::_1), somethingOfFSPtrType);
A: Apparently fn (CALLABLE) in FSM::All() is supposed to be called as fn(m_pFs, args...), not fn(args...)
So your SFINAE is wrong:
*
*std::result_of_t<CALLABLE(ARGS&&...)> is missing the m_pFs argument:
*std::result_of_t<CALLABLE(FSPtr, ARGS&&...)>
If you add FSPtr it should work. But keep in mind that result_of is deprecated. You can achieve the same effect simply with a trailing return type:
template <typename CALLABLE, typename... ARGS>
auto All(CALLABLE fn, ARGS&&... args)
-> std::enable_if_t<std::is_same_v<bool, decltype(fn(std::declval<FSPtr>(), args...))>, bool>
{
Note also that std::bind returns a lambda. Creating an std::function from that will be inefficient. Better to just use the returned type as-is:
auto rFunc = std::bind(fn, m_pFs, args...); // no need to cast to std::function
rFunc();
| |
doc_395
|
TypeError: Cannot read property 'send' of undefined
The code is shown a pastebin
https://hasteb.in/sanunede.js
A: Error Cannot read property 'send' of undefined in message.channel.send(embed) means, that message.channel returns undefined, so message doesn't contain property channel and message must be wrongly parsed to the function meme
Try using console.log(message) right in the beggining of the function if its valid
Could you also show the main code invoking this funciton??
| |
doc_396
|
I do not see any error in the IDE, but when I run it using mvn clean javafx:run it complains -
Exception in thread "JavaFX Application Thread" java.lang.NoClassDefFoundError: com/sun/webkit/dom/DomMapper
....
Caused by: java.lang.ClassNotFoundException: com.sun.webkit.dom.DomMapper
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:641)
...
This is how my pom.xml looks
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId> ... </groupId>
<artifactId> ... </artifactId>
<version> ... </version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
<exec.mainClass> .... </exec.mainClass>
</properties>
<dependencies>
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-fxml</artifactId>
<version>11</version>
</dependency>
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-controls</artifactId>
<version>11</version>
</dependency>
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-graphics</artifactId>
<version>11</version>
</dependency>
<dependency>
<groupId>org.openjfx</groupId>
<artifactId>javafx-web</artifactId>
<version>11</version>
</dependency>
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.14.3</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.openjfx</groupId>
<artifactId>javafx-maven-plugin</artifactId>
<version>0.0.4</version>
<configuration>
<options>
<option>--add-exports</option><option>javafx.web/com.sun.webkit.dom=ALL-UNAMED</option>
<option>--add-opens</option><option>javafx.web/com.sun.webkit.dom=ALL-UNAMED</option>
</options>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<compilerArgs>
<arg>--add-exports</arg><arg>javafx.web/com.sun.webkit.dom=ALL-UNAMED</arg>
</compilerArgs>
</configuration>
</plugin>
</plugins>
</build>
If I use the Maven shade plugin, I am able to bypass this issue.
I think it has got to do with how JPMS security works, but I cannot figure out how to bypass this. I tried add-exports, and add-opens in various combinations, but it did not help me.
What am I doing wrong?
BTW, I want to map the WebKit DOM to the JSoup dom element, as they give a nice API for CSS selectors.
Update
I am adding an additional stack trace of the error
java.lang.reflect.InvocationTargetException
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:464)
at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:363)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at java.base/sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:1051)
Caused by: java.lang.RuntimeException: Exception in Application start method
at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:900)
at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication$2(LauncherImpl.java:195)
at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: java.lang.NoClassDefFoundError: com/sun/webkit/dom/DomMapper
at xyz.jphil.internal_browser.TestApp.start(TestApp.java:86)
at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$9(LauncherImpl.java:846)
at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runAndWait$12(PlatformImpl.java:455)
at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$10(PlatformImpl.java:428)
at java.base/java.security.AccessController.doPrivileged(Native Method)
at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$11(PlatformImpl.java:427)
at javafx.graphics/com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:96)
at javafx.graphics/com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at javafx.graphics/com.sun.glass.ui.win.WinApplication.lambda$runLoop$3(WinApplication.java:174)
... 1 more
Caused by: java.lang.ClassNotFoundException: com.sun.webkit.dom.DomMapper
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:583)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
... 10 more
A: The solution for this problem lies in using using --patch-module. As I have added a class - com.sun.webkit.dom.DomMapper which is completely sealed by JPMS. The reason why I added DomMapper in the com.sun.webkit.dom.DomMapper was to access some package-private functions.
However, I see that can be easily avoided so I am choosing to avoid using those package-private functions. With this --patch-module is not required, which is also not a recommended thing to do as per JPMS documentation. Now the solution is simpler. Adding --add exports is enough (which is already there in the POM) and I am able to get it working.
Finally exporting the entire program as a farjar using maven shade plugin for example, also works. This I am adding just for information.
This answer is based on comments and valuable inputs by Jewelsea and Slaw.
Further notes:
*
*This example shows the public (although internal) functions of the com.sun.webkit.dom are quite good as it is, gist.github.com/jewelsea/6722397
*The problem I created by making a class inside com.sun.webkit.dom is called split-package - read here How split packages are avoided in Java 9
| |
doc_397
|
So hopefully this is a simple question to answer.
When I do a build a new directory is created on the build machine.
That means I have to go to IIS and change the physical path for the website.
I don't want to have to do that, so what should I be doing to stop this?
A: Deploy new builds to a fixed directory on the machine.
A: If you go in to the the source control explorer for the build you have created and located the TFSBuild.proj, check it out and edit it. Then add at the bottom
You have to replace the areas in CAPS below, this is for the debug build, so for Release change the area in the create item from Debug to Release. I used this method that I created at work for our dev and test build servers and it works like a charm.
<Target Name="AfterDropBuild">
<ItemGroup>
<FilesToDelete Include="\\NETWORK LOCATION TO WEB DIRECTORY USED BY IIS\**\*" />
</ItemGroup>
<Delete Files="@(FilesToDelete)" ContinueOnError="true" />
<Message Text="My target for deployment"/>
<CreateItem Include="$(DropLocation)\$(BuildNumber)\Debug\_PublishedWebsites\WEB APPLICATION NAME\**\*.*" >
<Output ItemName="FilesToCopy" TaskParameter="Include" />
</CreateItem>
<Copy
SourceFiles="@(FilesToCopy)"
DestinationFolder="\\NETWORK LOCATION TO WEB DIRECTORY USED BY IIS\%(RecursiveDir)"
SkipUnchangedFiles="false"
ContinueOnError="true"
OverwriteReadOnlyFiles="true"/>
</Target>
| |
doc_398
|
- (NSInteger)thisW:(NSDate *)date
{
NSCalendar *gregorian = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *todaysComponents =
[gregorian components:NSYearCalendarUnit fromDate:[NSDate date]];
NSUInteger todaysWeek = [todaysComponents weekOfYear];
NSDateComponents *otherComponents =
[gregorian components:NSYearCalendarUnit fromDate:date];
NSUInteger datesWeek = [otherComponents weekOfYear];
//NSLog(@"Date %@",date);
if(todaysWeek==datesWeek){
//NSLog(@"Date is in this week");
return 1;
}else if(todaysWeek+1==datesWeek){
//NSLog(@"Date is in next week");
return 2;
} else {
return 0;
}
}
A: You need to pass NSCalendarUnitWeekOfYear when extracting date components:
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *todaysComponents = [gregorian components:NSCalendarUnitWeekOfYear fromDate:[NSDate date]];
NSUInteger todaysWeek = [todaysComponents weekOfYear];
NSDateComponents *otherComponents = [gregorian NSCalendarUnitWeekOfYear fromDate:date];
NSUInteger datesWeek = [otherComponents weekOfYear];
A: Using datecomponents for week calculations will give you problems when the dates are close to year's end, i.e. "The first week of the year is designated to be the week containing the first Thursday of the year.(ISO 8601)"
I find it easier to compare dates with certain granularity, weekly in this case (the following code detects if a date is more than one week in the past, last week, this week, next week or further in the future)
-(EventWeekRange)numberOfWeeksFromTodayToEvent:(NSDate *)eventDate {
NSCalendar *calendar = [NSCalendar currentCalendar];
NSComparisonResult comparison = [calendar compareDate:[NSDate date] toDate:eventDate toUnitGranularity:NSCalendarUnitWeekOfYear];
if (comparison == NSOrderedSame) {
return RangeThisWeek;
} else if (comparison == NSOrderedAscending) { // The event date is in the future
// Advance today's date one week to check if this new date is in the same week as the event
NSDate *todaysNextWeek = [[NSDate date]dateByAddingTimeInterval:60*60*24*7];
if ([calendar compareDate:todaysNextWeek toDate:eventDate toUnitGranularity:NSCalendarUnitWeekOfYear] == NSOrderedSame) {
return RangeNextWeek;
} else {
return RangeLater;
}
} else { // The event date is in the past
// Advance the event's date one week to check if this new date is in the same week as today
NSDate *eventsNextWeek = [eventDate dateByAddingTimeInterval:60*60*24*7];
if ([calendar compareDate:eventsNextWeek toDate:[NSDate date] toUnitGranularity:NSCalendarUnitWeekOfYear] == NSOrderedSame) {
return RangeLastWeek;
} else {
return RangeEarlier;
}
}
}
| |
doc_399
|
More specifically I use LearnDash pluggin and I want to access courses infos but they doesn't provide any API to access it.
Thanks
A: Overall you need to search Google for things having to do with "Wordpress rest api custom post type" and eventually you'll be dealing with registering custom post types and endpoints in your theme's functions.php
Here is the manual: https://developer.wordpress.org/rest-api/extending-the-rest-api
As an example, here is my situation: I'm using WordPress (4.7) and The Events Calendar ("TEC") plugin. I'm querying the WP DB from an Android app using the REST API, however the only data that's available to REST is basic WP post stuff. I need to expose the custom data in the TEC plugin to the REST API. In order to do that, I've included the following into my functions.php in my theme:
functions.php
/* Exposing the custom post type of the plugin to the REST API.
* In this case, for The Tribe Events Calendar plugin, the custom post type is
* "tribe_events". For other plugins it will be different. */
add_action( 'init', 'my_custom_post_type_rest_support', 25 );
function my_custom_post_type_rest_support() {
global $wp_post_types;
//be sure to set this to the name of your post type!
$post_type_name = 'tribe_events';
if( isset( $wp_post_types[ $post_type_name ] ) ) {
$wp_post_types[$post_type_name]->show_in_rest = true;
$wp_post_types[$post_type_name]->rest_base = $post_type_name;
$wp_post_types[$post_type_name]->rest_controller_class = 'WP_REST_Posts_Controller';
}
}
/* Exposing the custom taxonomy of the plugin to the REST API.
* In this case, for The Tribe Events Calendar plugin, the custom
* taxonomy is "tribe_events_cat". For other plugins it will be different.
*/
add_action( 'init', 'my_custom_taxonomy_rest_support', 25 );
function my_custom_taxonomy_rest_support() {
global $wp_taxonomies;
//be sure to set this to the name of your taxonomy!
$taxonomy_name = 'tribe_events_cat';
if ( isset( $wp_taxonomies[ $taxonomy_name ] ) ) {
$wp_taxonomies[ $taxonomy_name ]->show_in_rest = true;
// Optionally customize the rest_base or controller class
$wp_taxonomies[ $taxonomy_name ]->rest_base = $taxonomy_name;
$wp_taxonomies[ $taxonomy_name ]->rest_controller_class = 'WP_REST_Terms_Controller';
}
}
With the above in my functions.php, now I can query just the custom post type and taxonomy with the REST API. Here's a sample query:
http://www.mywebsite.com/wp-json/wp/v2/tribe_events?tribe_events_cat=64
However, I still don't see any of the custom plugin data per-event. All I see are the basic standard WP fields.
So now I have to add more to my functions.php:
/* Add specific endpoints to REST API.
* The TEC plugin has good documentation, and they have a
* list of the variables. With any other plugin, you might
* have to do more detective work. */
add_action( 'rest_api_init', 'slug_register_event_venue' );
function slug_register_event_venue() {
register_rest_field( 'tribe_events',
'_EventVenueID',
array(
'get_callback' => 'slug_get_event_venue',
'schema' => null
)
);
}
function slug_get_event_venue( $object, $field_name, $request ) {
$postId = tribe_get_venue_id( $object[ 'id' ]);
if ( class_exists( 'Tribe__Events__Pro__Geo_Loc' ) ) {
$output[ 'locid' ] = (float) $postId;
$output[ 'lat' ] = (float) get_post_meta( $postId, Tribe__Events__Pro__Geo_Loc::LAT, true );
$output[ 'lng' ] = (float) get_post_meta( $postId, Tribe__Events__Pro__Geo_Loc::LNG, true );
} else {
$output = array(
'locid' => 0,
'lat' => 0,
'lng' => 0,
);
}
return $output;
}
... and a bunch more endpoint definitions of which I'm excluding the code here.
Now when I run the same query from earlier, new data fields are present in the JSON: all of the endpoints I've added.
At this point I want to exclude a ton of things from the REST API output (all the miscellaneous WP stuff) and just return the event fields I'm interested in. To do that I just add a "&fields" parameter to my query, with fields seperated by comma. There's also a per_page and order parameters too.
http://www.mywebsite.com/wp-json/wp/v2/tribe_events?tribe_events_cat=64&per_page=100&order=asc&fields=id,title.rendered,_EventVenueID.lat,_EventVenueID.lng,_EventVenueID.locid,_EventStartDate.startdate,tribe_events_cat
This returns JSON data with only the data I'm interested in.
The TEC plugin maker has stated they'll be introducing official REST API support sometime soon. This means in the future I can probably eliminate all of this code in functions.php, and just utilize whatever interface the plugin maker comes up with... hopefully a nice sexy page inside the plugin settings.
Now that WP (4.7) has more or less a fully featured REST API, the ball is in the court of the plugin makers to build support for it. So this year you should see plugins be updated accordingly.
A: When you are creating the custom post type in WordPress just add one more parameter show_in_rest as true for the support the rest API for Custom post type.
/**
* Register a book post type, with REST API support
*
* Based on example at:
https://codex.wordpress.org/Function_Reference/register_post_type
*/
add_action( 'init', 'my_book_cpt' );
function my_book_cpt() {
$args = array(
'public' => true,
'show_in_rest' => true,
'label' => 'Books'
);
register_post_type( 'book', $args );
}
Please visit here.
Then you can use the custom endpoint by the URL like this:
https://example.com/wp-json/wp/v2/book
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.