text stringlengths 15 59.8k | meta dict |
|---|---|
Q: Save a custom class to Isolated Storage using a Collection I have created a custom class named ImageItem which contains a BitmapImage and string to gather the response of the CaptureImageTask. I would like to save each image and its respective path to an ObservableCollection which is bound to a listbox in my view.
As of now the listbox populates correctly, but I am having trouble storing ObservableCollection<ImageItem> in isolated storage, I believe because of the BitmapImage type.
I am not sure of how to fix my solution so that the BitmapImage will be allowed to be saved to isolated storage along with its respective path within an ObservableCollection.
I believe I have narrowed down the issue to BitmapImage not being a serializable type. I have tried using [DataContract] and '[DataMember]attributes withinImageItem.cs` without success. I have never attempted to save a nonprimitive type.
Following are the code, with some description of each file.
*
*ImageItem.cs
public class ImageItem
{
public BitmapImage ImageUri
{
get;
set;
}
public string ImagePath
{
get;
set;
}
}
*Settings.cs
I am using a Settings class to create the ObservableCollection of custom type.
public static class Settings
{
public static readonly Setting<ObservableCollection<ImageItem>> imageList = new Setting<ObservableCollection<ImageItem>>("imageList", new ObservableCollection<ImageItem>());
}
*Setting.cs
Where Setting is a class that reads and saves data to Isolated Storage
public class Setting<T>
{
string name;
T value;
T defaultValue;
bool hasValue;
public Setting(string name, T defaultValue)
{
this.name = name;
this.defaultValue = defaultValue;
}
public T Value
{
get
{
//Check for the cached value
if (!this.hasValue)
{
//Try to get the value from Isolated Storage
if (!IsolatedStorageSettings.ApplicationSettings.TryGetValue(this.name, out this.value))
{
//It hasn't been set yet
this.value = this.defaultValue;
IsolatedStorageSettings.ApplicationSettings[this.name] = this.value;
}
this.hasValue = true;
}
return this.value;
}
set
{
//Save the value to Isolated Storage
IsolatedStorageSettings.ApplicationSettings[this.name] = value;
this.value = value;
this.hasValue = true;
}
}
public T DefaultValue
{
get { return this.defaultValue; }
}
// Clear cached value
public void ForceRefresh()
{
this.hasValue = false;
}
}
*MainPage.xaml.cs
From here I am simply attempting to save the result of the CameraCaptureTask which is used to populate the ObservableCollection and the listbox
void cameraCaptureTask_Completed(object sender, PhotoResult e)
{
if (e.TaskResult == TaskResult.OK)
{
//values declared earlier
imgChosenPhotoFilePath = null;
bmp = new BitmapImage();
imgChosenPhotoFilePath = e.OriginalFileName;
bmp.SetSource(e.ChosenPhoto);
imgChosenPhoto.Source = bmp;
//Add photo to listbox and observablecollection
AddToImgList(imgChosenPhotoFilePath, bmp);
}
}
private void AddToImgList(string filePath, BitmapImage bitmap)
{
//save the values to the ObservableCollection
Settings.imageList.Value.Add(new ImageItem() { ImagePath = filePath, ImageUri = bitmap });
//populate the listbox in the view named imgList
imgList.ItemsSource = Settings.imageList.Value;
}
A: As you've discovered, you can't serialize the BitmapImage. The simplest alternative would be to save this as a separate file and then save the name of the file in the collection you're serializing.
Obviously, when deserializing, you'll need to read the file from disk and load it back into a BitmapImage.
If you're persisting this data for use across the lifetime of the app it'll probably be easier to just save the images straight to IsolatedStorage and keep the paths in your view model. You can then bind the path to an Image in the ListBoxItemTemplate.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/15561091",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Bing Maps Error - Microsoft is not defined? My code below throws an error message: ReferenceError: Microsoft is not defined. What am I doing wrong?
<head>
<title>Define New OmniZone</title>
<style type='text/css'>body{margin:0;padding:0;overflow:hidden;font-family:'Segoe UI',Helvetica,Arial,Sans-Serif}</style>
<meta http-equiv='Content-Type' content='text/html; charset=utf-8'/>
<script type='text/javascript' src='https://www.bing.com/api/maps/mapcontrol?callback=loadMap&key=[MyMapKey]' async defer></script>
<script type='text/javascript'>
var map;
function loadMap()
{
map = new Microsoft.Maps.Map('#myMap', {
credentials: '[MyMapKey]',
mapTypeId: Microsoft.Maps.MapTypeId.aerial,
zoom: 16
});
}
</script>
</head>
<body onload="loadMap();">
<form runat="server">
| {
"language": "en",
"url": "https://stackoverflow.com/questions/73355411",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Request to send json with token returns token validation error When sending the request as a JSON, I get the error "Can't check the token validity." Previously, I obtained the token, which is stored in a variable. The statusCode: OK {200}.
What I observe with the error that is displayed is that the json cannot be sent because the token is not being validated. However, if I do the tests in Postman with the token and the JSON, the result is correct. I am using the RestSharp/106.15.0.0 library, which is the same one with which I obtained the token.
I have tried adding other lines of code, like
request2.AddBody(MyJson)
request2.AddHeader("Cache-Control", "no-cache")
I have carried out the tests in postman which are satisfactory
The code in VB.NET 2015 that I have developed is the following:
Dim client = New RestClient(Var_URLWS)
Dim request2 = New RestRequest(Method.POST)
request2.AddHeader("Content-Type", "application/json")
request2.AddHeader("Authorization", "Mybearer " & MyToken)
request2.AddJsonBody(MyJson, "application/json")
Dim response2 As RestResponse = client.Execute(request2)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75431882",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Unable to find the Report Data Pane in Visual Studio 2019 I'm unable to find the Report Data Pane in Visual Studio 2019.
I tried installing all relevant extensions and using Ctrl Alt D as per reports I have found on here but this hasn't seemed to do anything.
A: This has now been resolved, re-imaged laptop > re-installed VS2019 with all required extensions
I believe it may have been a corrupt install of VS but this is yet to be confirmed by Microsoft
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57286304",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Blank value in web service for Int64 type I consume a web service that has a numeric element. The Delphi wsdl importer sets it up as Int64.
The web service allows this element to be blank. However, because it is defined as Int64, when I consume the web service in Delphi without setting a value for it, it defaults to 0 because it's an Int64. But I need it to be blank and the web service will not accept a value of 0 (0 is defined as invalid and returns an error by the web service).
How can I pass a blank value if the type is Int64?
A: Empty age (example)
<E06_14></E06_14>
could have a special meaning, for example be "unknown" age.
In this case, the real question is how to make the field nillable on the Delphi side.
From this post of J.M. Babet:
Support for 'nil' has been an ongoing issue. Several built-in types of
Delphi are not nullable. So we opted to use a class for these cases
(not elegant but it works). So with the latest update for Delphi 2007
I have added several TXSxxxx types to help with this. Basically:
TXSBoolean, TXSInteger, TXSLong, etc. TXSString was already there but
it was not registered. Now it is. When importing a WSDL you must
enable the Use 'TXSString for simple nillable types' option to make
the importer switch to TXSxxxx types. On the command line it is the
"-0z+" option.
The DocWiki for the Import WSDL Wizard also shows two options related to nillable elements:
*
*Process nillable and optional elements - Check this option to make the WSDL importer generate relevant information about optional
and nillable properties. This information is used by the SOAP runtime
to allow certain properties be nil.
*Use TXSString for simple nillable types - The WSDL standard allows simple types to be nil, in Delphi or NULL, in C++, while Delphi
and C++ do not allow that. Check this option to make the WSDL importer
overcome this limitation by using instances of wrapper classes.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/12434202",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: install font ClickOnce but non RunAsAdmin in my Project Used Fonts,
for install fonts when ClickOnce.
string strFontsPathFile = Environment.GetEnvironmentVariable("windir")
+ @"\Fonts\" + strFileName;
File.Copy(strFontFilePath, strFontsPathFile, true);
//2)Step 2 : Install font in resource of MS-Windows
if (AddFontResource(strFontsPathFile) == 0)
return false;
//3)Step 3 : Set registry information of new installed font for use
RegistryKey reg = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Fonts", true);
reg.SetValue(strFileName.Split('.')[0] + " (TrueType)", strFileName);
reg.Close();
SendMessage(HWND_BROADCAST, WM_FONTCHANGE, 0, 0);
But Error:
Access to the path '' is denied.
A: If your fonts don't need to be shared across multiple applications, you may try private font deployment instead of installing them in OS. In that case your app don't need to use administrator account.
There is the good solution for private deploment: Embedding/deploying custom font in .NET app
| {
"language": "en",
"url": "https://stackoverflow.com/questions/20114397",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Set background color for UIView I have a problem when setting the background color for a UIView. What I am doing is:
- (void) viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor clearColor];
}
but I am getting a black background color as shown below:
If I change the background to any another color it works. Any ideas about this ?
A: Your view is working as intended. You are setting it to use a clear background color, which means exactly as it is named, clear, and you will see color and possibly other UI elements underneath your view. Think of it as placing clear plastic wrap (the view) on top of colored construction paper (the super view). If you wish to find where the black color is coming from, I would start with your root controller's view.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/15099958",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Boost MPI and serialization - size of serialized object At my university I have to measure the overhead of the serialization of C++ STL types that are sent using MPI.
Measuring the time is easy, but I have a problem if I would want to measure for example how much bytes is needed to send a vector of 1000 chars and array of 1000 chars for example. Looking at the Boost.MPI docs: http://www.boost.org/doc/libs/1_55_0/doc/html/mpi/tutorial.html#mpi.user_data_types
I can see that it uses Boost.Serialization for serialization: http://www.boost.org/doc/libs/1_55_0/libs/serialization/doc/
Boost.Serialization uses archives for during serialization, but I can't see if there is a way I can extract from archive the amount of bytes it takes? I am not very familiar with boost docs so I may be missing something.
A: Here goes:
#include <iostream>
#include <sstream>
#include <boost/archive/binary_oarchive.hpp>
#include <boost/serialization/vector.hpp>
int main()
{
std::ostringstream oss;
boost::archive::binary_oarchive oa(oss);
std::vector<char> v(1000);
// stream
oa << v;
std::cout << "The number of bytes taken for the vector in an archive is " << oss.str().size() << "\n";
}
On my system it prints:
The number of bytes taken for the vector in an archive is 1048
See it Live On Coliru
It's possible that MPI's packed_oarchive does additional compression. I haven't found this in the docs on a quick scan.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/22455816",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Slow serial connection freezes QT GUI thread I'm working on a project where I need to communicate from my system to some RS485 serial devices. The connection itself works and is in a separate thread than the QT GUI thread.
I am trying to use signals/slots to connect the GUI thread to the serial thread which is mostly working but whenever the external device takes a bit to respond my GUI is still locked up until the port is finished and I haven't been able to figure out how to fix it.
I'm starting my serial thread in main.cpp like this:
int main(int argc, char* argv[])
{
QApplication app(argc, argv);
QFile f(":/TS-Controls.qss");
if (f.open(QIODevice::ReadOnly)) {
app.setStyleSheet(f.readAll());
f.close();
}
for (int i = 0; i < argc; ++i) {
if (QString(argv[i]) == QString("-h") ||
QString(argv[i]) == QString("--help") ||
QString(argv[i]) == QString("-help")) {
qDebug() << "Usage:";
qDebug() << " -embedded : show in fullscreen mode";
qDebug() << " -no-embedded : show in desktop mode";
qDebug() << " -white : Set every background to white for screenshots. ";
return 0;
}
}
MainWindow* mainWindow = new MainWindow();
ModbusThread * thread = new ModbusThread("/dev/ttyAM1");
app.connect(thread->m_conn, SIGNAL(transactionComplete(ModbusTransaction)), mainWindow->ref1, SLOT(receiveTransaction(ModbusTransaction)), Qt::DirectConnection);
app.connect(thread->m_conn, SIGNAL(busAvailable(bool)), mainWindow->TxQueue, SLOT(busAvailable(bool)), Qt::DirectConnection);
app.connect(mainWindow->TxQueue, SIGNAL(elementUnloaded(ModbusTransaction)), thread->m_conn, SLOT(loadTransaction(ModbusTransaction)), Qt::DirectConnection);
thread->start();
mainWindow->show();
return app.exec();
}
As you can see, the thread object is of type ModbusThread which is a subclass of QThread. Also you may notice I'm using Qt::DirectConnect. I tried using the default AutoConnect which should be queued since the serial stuff is going on in another thread but it doesn't seem to make a difference either way in terms of this problem. Here is my ModbusThread class:
#include <QThread>
#include <modbusconn.h>
#include <modbustransaction.h>
#ifndef MODBUSTHREAD_H
#define MODBUSTHREAD_H
class ModbusThread : public QThread
{
public:
ModbusThread(char * port);
ModbusConn * m_conn;
};
#endif // MODBUSTHREAD_H
#include "modbusthread.h"
ModbusThread::ModbusThread(char * port) : QThread()
{
this->m_conn = new ModbusConn(this, port);
}
Now you may be wondering what TxQueue is doing (it is an object listed in the signal/slot connections in main.cpp if you missed it). That is a queue class for the ModbusTransaction datatype. The idea is that since I know that the actual modbus connection might be busy at a given time I can use this queue as a holding buffer. Basically a UI widget will load a transaction request in the queue. If the modbus connection is idle, TxQueue will pass it along as a signal to the connection otherwise it will just add it to the queue. The connection signals TxQueue when it is available to process another transaction via the busAvailable signal.
Somehow it seems like TxQueue is unable to accept transactions to be added to the queue until the connection object finishes.
I have done some sleuthing via google and found a page that recommended that you do this in the constructor of your QThread subclass:
QObject::moveToThread(this);
I gave that a shot but when I run my program none of the signals/slots seem to be getting triggered since the program isn't communicating with the device.
Looking at it, perhaps I should get rid of my Qthread subclass, create a plain Qthread then move the connection object to it?
I'm fairly new with C++ and QT so I'm sure that there's something about my approach that is a bit off. I'd appreciate any advice you guys can offer.
A: QThread should be subclassed only to extend threading behavior. I think you should read the following article before trying to use the moveToThread function: http://blog.qt.io/blog/2010/06/17/youre-doing-it-wrong/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/4330407",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Django BinaryField not rendering I have a model in which I have a BinaryField. When I go in the admin area, and try to add new city using the model form, the checkbox for the BinaryField doesn't get rendered.
models.py:
from django.db import models
# Create your models here.
class City(models.Model):
name = models.CharField(max_length=100, null=False, blank=False, unique=True)
enabled = models.BinaryField(default=True)
timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)
updated = models.DateTimeField(auto_now=True, auto_now_add=False)
class Meta:
ordering = ["id"]
verbose_name = 'city'
verbose_name_plural = 'cities'
def __str__(self):
return self.name
admin.py:
from django.contrib import admin
from .models import City
# Register your models here.
class CityAdmin(admin.ModelAdmin):
search_fields = ['name']
class Meta:
model = City
admin.site.register(City, CityAdmin)
HTML:
<div>
<label class="required" for="id_name">Name:</label>
<input class="vTextField" id="id_name" maxlength="100" name="name" type="text">
</div>
As you can see in HTML, the checkbox input element is not there at all. I have checked, the migrations looks just fine, the field exists in the database as well. My virtual environment is setup to use Django 1.7.
Any help will be appreciated.
Thanks
A: You need BooleanField. BinaryField is for binary data. https://docs.djangoproject.com/en/dev/ref/models/fields/#booleanfield
| {
"language": "en",
"url": "https://stackoverflow.com/questions/25854479",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: i am new to sql .Not Getting query result . Runs fine with no error private void button1_Click(object sender, EventArgs e)
{
DataTable DataTab = new DataTable();
DaSql = new SqlDataAdapter("SELECT * FROM Student where Gender = '" + textBox1.Text + "' ", conSql);
DaSql.Fill(DataTab);
DataGridQueryResult.DataSource = DataTab;
}
A: Dont pay too much attention to SQL INJECTION until you get your code running. Get it working, then secure it. Try set a variable to
var sqlText = "SELECT * FROM Student where Gender = '" + textBox1.Text + "' ";
And then hit that in the debugger to check your full query statement. Make sure you have not got any sillies in there like an extra space.
See a full example of filling a data table here
Fix your SQL INJECTION vulnerability using parameters
A: No error with Query seems binding issue with DataGrid.
My case is same, I use SQL, DataTable, DataGrid.
And would you try this?
DataTable DataTab = new DataTable("Student");
DaSql = new SqlDataAdapter("SELECT * FROM Student where Gender = '" + textBox1.Text + "' ", conSql);
DaSql.Fill(DataTab);
DataGridQueryResult.ItemsSource = DataTab.DefaultView;
And need to check DataGrid settings are correct in Window Designer including AutoGeneratingColumns= True.
I always use ItemsSource with good results.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37008697",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-10"
} |
Q: How can we change a linkbutton to a hyperlink with variables? I'm not very familiar with ASPX, not enough to get my head around this.
Our developers have used this code in a gridview control which opens a new tab and sends the user to a "details" page.
<asp:LinkButton Text='<%# Bind("OrderId") %>' CommandArgument='<%# Bind("FormId") %>' ID="lnkOrderId" runat="server" OnClick="lnkOrderId_Click"></asp:LinkButton>
This code produces HTML that looks like this:
<a id="gvGridView_lnkOrderId_2" href="javascript:__doPostBack('gvGridView$ctl04$lnkOrderId','')">20109</a>
To be able to use a Jquery fancybox control, we need the code to produce the code like this:
<a id="gvGridView_lnkOrderId_2" href=”http://domain.com/Details.aspx?OrderId=20109&FormId=0”>20109</a>
I can see we need to use asp:hyperlink, but what I tried with the variable doesn't work.
Is this possible to do?
A: I use a TemplateFieldand direct render the link, here is how:
On the GridView aspx page I use:
<asp:TemplateField >
<ItemTemplate >
<%#LinkToGoto(Container.DataItem)%>
</ItemTemplate>
</asp:TemplateField>
and on code behind I make the link as:
protected string LinkToGoto(object oItem)
{
// read the data from database
var cOrderId = (int)DataBinder.Eval(oItem, "OrderId");
// format and render back the link
return String.Format("<a href=\"http://domain.com/Details.aspx?OrderId={0}\">go to order</a>", OrderId);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/27980733",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Exception : Collection was modified; enumeration operation may not execute on form Close in setup project I created a setup project of window form application built in C# 4.0. I tested the setup in my test PC which have Vs 2010 Ultimate installed in it and its working fine in it.
I later on to test the application I installed it another machine which does not have VS in it. Every time I try to close the form, it ends up with this exception. The exception is occurring in some forms not in all. I have checked the code and and there is no difference in it(this.close()).
While building the setup I am using
.Net Framework 4 Client Profile as Target Framework.
Microsoft.VisualBasic.PowerPacks.Vs is added in setup.
My not using tab strip nor trying to close multiple form.
This is the complete error
Unhandled exception has occurred in your application. If you click continue, the application will ignore this error and attempt to continue. If you click quit, the application will close rimmediately.
See the end of this message for details on invoking
just-in-time (JIT) debugging instead of this dialog box.
************** Exception Text **************
System.InvalidOperationException: Collection was modified; enumeration operation may not execute.
at System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource)
at System.Collections.Generic.List`1.Enumerator.MoveNextRare()
at System.Collections.Generic.List`1.Enumerator.MoveNext()
at Microsoft.VisualBasic.PowerPacks.ShapeCollection.Dispose(Boolean disposing)
at Microsoft.VisualBasic.PowerPacks.ShapeContainer.Dispose(Boolean disposing)
at System.ComponentModel.Component.Dispose()
at System.Windows.Forms.Control.Dispose(Boolean disposing)
at System.ComponentModel.Component.Dispose()
at System.Windows.Forms.Control.Dispose(Boolean disposing)
at System.ComponentModel.Component.Dispose()
at System.Windows.Forms.Control.Dispose(Boolean disposing)
at System.Windows.Forms.Form.Dispose(Boolean disposing)
at ezyBizManager.Masters.frmUsers.Dispose(Boolean disposing)
at System.ComponentModel.Component.Dispose()
at System.Windows.Forms.Form.WmClose(Message& m)
at System.Windows.Forms.Form.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
************** Loaded Assemblies **************
mscorlib
Assembly Version: 4.0.0.0
Win32 Version: 4.0.30319.1 (RTMRel.030319-0100)
CodeBase: file:///C:/Windows/Microsoft.NET/Framework/v4.0.30319/mscorlib.dll
----------------------------------------
ezyBizManager
Assembly Version: 1.0.0.0
Win32 Version: 1.0.0.0
CodeBase: file:///C:/Program%20Files/Microsoft/COE/ezyBizManager.exe
----------------------------------------
System.Windows.Forms
Assembly Version: 4.0.0.0
Win32 Version: 4.0.30319.1 built by: RTMRel
CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/System.Windows.Forms/v4.0_4.0.0.0__b77a5c561934e089/System.Windows.Forms.dll
----------------------------------------
System.Drawing
Assembly Version: 4.0.0.0
Win32 Version: 4.0.30319.1 built by: RTMRel
CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/System.Drawing/v4.0_4.0.0.0__b03f5f7f11d50a3a/System.Drawing.dll
----------------------------------------
System
Assembly Version: 4.0.0.0
Win32 Version: 4.0.30319.1 built by: RTMRel
CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/System/v4.0_4.0.0.0__b77a5c561934e089/System.dll
----------------------------------------
System.Data.Linq
Assembly Version: 4.0.0.0
Win32 Version: 4.0.30319.1
CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/System.Data.Linq/v4.0_4.0.0.0__b77a5c561934e089/System.Data.Linq.dll
----------------------------------------
System.Core
Assembly Version: 4.0.0.0
Win32 Version: 4.0.30319.1 built by: RTMRel
CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/System.Core/v4.0_4.0.0.0__b77a5c561934e089/System.Core.dll
----------------------------------------
System.Configuration
Assembly Version: 4.0.0.0
Win32 Version: 4.0.30319.1 (RTMRel.030319-0100)
CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/System.Configuration/v4.0_4.0.0.0__b03f5f7f11d50a3a/System.Configuration.dll
----------------------------------------
System.Xml
Assembly Version: 4.0.0.0
Win32 Version: 4.0.30319.1 built by: RTMRel
CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/System.Xml/v4.0_4.0.0.0__b77a5c561934e089/System.Xml.dll
----------------------------------------
System.Data
Assembly Version: 4.0.0.0
Win32 Version: 4.0.30319.1 (RTMRel.030319-0100)
CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_32/System.Data/v4.0_4.0.0.0__b77a5c561934e089/System.Data.dll
----------------------------------------
System.Transactions
Assembly Version: 4.0.0.0
Win32 Version: 4.0.30319.1 (RTMRel.030319-0100)
CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_32/System.Transactions/v4.0_4.0.0.0__b77a5c561934e089/System.Transactions.dll
----------------------------------------
System.EnterpriseServices
Assembly Version: 4.0.0.0
Win32 Version: 4.0.30319.1 (RTMRel.030319-0100)
CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_32/System.EnterpriseServices/v4.0_4.0.0.0__b03f5f7f11d50a3a/System.EnterpriseServices.dll
----------------------------------------
System.Xml.Linq
Assembly Version: 4.0.0.0
Win32 Version: 4.0.30319.1 built by: RTMRel
CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/System.Xml.Linq/v4.0_4.0.0.0__b77a5c561934e089/System.Xml.Linq.dll
----------------------------------------
Anonymously Hosted DynamicMethods Assembly
Assembly Version: 0.0.0.0
Win32 Version: 4.0.30319.1 (RTMRel.030319-0100)
CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_32/mscorlib/v4.0_4.0.0.0__b77a5c561934e089/mscorlib.dll
----------------------------------------
Microsoft.VisualBasic.PowerPacks.Vs
Assembly Version: 10.0.0.0
Win32 Version: 10.0.20911.1
CodeBase: file:///C:/Windows/assembly/GAC_MSIL/Microsoft.VisualBasic.PowerPacks.Vs/10.0.0.0__b03f5f7f11d50a3a/Microsoft.VisualBasic.PowerPacks.Vs.dll
----------------------------------------
Microsoft.VisualBasic
Assembly Version: 10.0.0.0
Win32 Version: 10.0.30319.1 built by: RTMRel
CodeBase: file:///C:/Windows/Microsoft.Net/assembly/GAC_MSIL/Microsoft.VisualBasic/v4.0_10.0.0.0__b03f5f7f11d50a3a/Microsoft.VisualBasic.dll
----------------------------------------************** JIT Debugging **************
To enable just-in-time (JIT) debugging, the .config file for this
application or computer (machine.config) must have the
jitDebugging value set in the system.windows.forms section.
The application must also be compiled with debugging
enabled.
For example:
<configuration>
<system.windows.forms jitDebugging="true" />
</configuration>
When JIT debugging is enabled, any unhandled exception
will be sent to the JIT debugger registered on the computer
rather than be handled by this dialog box.
[Edited:]
I am using image to close the form.
private void imgClose_Click(object sender, EventArgs e)
{
this.Close();
}
A: I think it's a bug in the Dispose() method of ShapeCollection. If I look at this method using for example .NET Reflector, with Microsoft.VisualBasic.PowerPacks.Vs, Version=9.0.0.0, it says this:
foreach (Shape shape in this.m_Shapes)
{
shape.Dispose();
}
And if I look at this method using Microsoft.VisualBasic.PowerPacks.Vs, Version=10.0.0.0, it says this:
for (int i = this.m_Shapes.Count - 1; i >= 0; i--)
{
this.m_Shapes[i].Dispose();
}
Clearly, the implementation has evolved between versions. The latter one doesn't rely on an Enumerator object and therefore cannot fail with the error you show.
What's strange though is your stackframe seems to imply you're running off version 10, which shouldn't use the enumerator?? Maybe you need a VS 2010 update? Or you can also check at the Dispose implementation on the Microsoft.VisualBasic.PowerPacks.Vs you're using.
EDIT: after some digging, your application indeed runs on an old version of the VB Powerpacks. Upgrade to VS2010, SP1 or copy the DLL from a good installation. For this specific Dispose bug, you need at least 10.0.30319.1.
A: I had the same pblm with, especially with LineShape, after headache with installing and searching for right PowerPacks package, I replaced it with RichTextBox by adjusting backcolor to balck and the size, it seems weird but it's quite better for me than spending my time with this bug !! (0_o)
A: I had the same problem. I've been so confused as to what was causing the issue and have been stepping through debugging line by line for a day or so. After Google searching and typing in the right description, it turns out the issue is with line shapes on a form - and likely other shapes. See the links here, hope it saves somebody else some time... you have to read down through the comments, by like the above post it's with line shapes.
http://social.msdn.microsoft.com/Forums/en-US/cb89a159-c989-470f-b74f-df3f61b9dedd/systeminvalidoperationexception-when-closing-a-form?forum=vbpowerpacks
http://channel9.msdn.com/forums/TechOff/520076-VB-2010-Error-PowerPacks-Line-Shape-Dispose/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/14788919",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How my file names have been encoded? After a long time, I come to review the contents of my HDD and see a weird file name.
I'm not sure what tool or program has changed it this way, but when I see the content of the file I could find its original name.
Anyway, I'm encountering a type of encoding and I want to find it. It's not complicated. Mostly for those who are familiar with unicode and utf8. Now I map them and you guess what has happened.
In the following, I give a table which maps the characters. In the second column, there's utf8 form and in the first column there's its equivalent character which is converted.
I need to know what happened and how is it converted to convert it back to utf8. that is, what I have is in the first column, and what I need to get is in the second column:
Hide Copy Code
638 2020 646
639 AF 6AF
637 A7 627
637 B1 631
637 B3 633
637 6BE 62A
20 20
638 67E 641
63A 152 6CC
For more description, consider the first row, utf8 form is 46 06 (type bytes) or 0x0646. The file name for this character is converted into two wide-characters, 0x0638 0x2020.
A: I found the solution myself.
In Notepad++:
*
*Select "Encode in ANSI" from Encoding menu.
*Paste the corrupted text.
*Select "Encode in UTF-8" from Encoding menu.
That's it. The correct text will be displayed.
If so, how can I do the same with Perl?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/31077075",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: ng-show not able to check null or empty string Am trying to show the html element based on condition. Like i have to check claim.claimToDealerCurrencyExchangeRate is empty or null. If it is empty or null then, i dont want to display the element (label and span ).
But it is not working as expected. Label & span elements are visible even claim.claimToDealerCurrencyExchangeRate empty.
Please find my code below.
<div id="exchange" ng-if="hasClaimGrouping('customerInvoiceOrRepairDate')"
ng-show="claim.claimToDealerCurrencyExchangeRate == null"
class="form-group row">
<label class="col-lg-3">{{'claim.view.exchangeRateApplied'|translate}}
</label>
<span>{{claim.claimToDealerCurrencyExchangeRate}}</span>
</div>
A: Is there any reason why you are using both ng-if and ng-show? I think one of them should suffice. The ngIf directive removes or recreates a portion of the DOM tree based on an expression. If the expression assigned to ngIf evaluates to a false value then the element is removed from the DOM, otherwise a clone of the element is reinserted into the DOM.
A: Your code has ng-show="claim.claimToDealerCurrencyExchangeRate == null" which means the div will be visible when claim.claimToDealerCurrencyExchangeRate is null. As per your ask, your logic is wrong. Use ng-hide="claim.claimToDealerCurrencyExchangeRate == null" or ng-show="claim.claimToDealerCurrencyExchangeRate != null". But since you are already using ng-if, you should combine all the conditions within it, unless you absolutely want the DOM element to be toggled between visibility and non-visibility multiple times and not have it re-instantiated every time, use a combination of ng-if and ng-show.
Also, understand empty and null are two different things in JavaScript. For example, if value is a variable. Then value = "" is empty but not null. value = "null" is not null but a non-empty string. Set value = null explicitly then it is null. And in all cases value is not undefined. Check what exactly claim.claimToDealerCurrencyExchangeRate is being set and define your logic in ng-show appropriately.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/55144521",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Ansible undefined variable i have role for Route53 (http://docs.ansible.com/ansible/route53_module.html) and task is:
- name: "SET DNS record"
route53:
aws_access_key: "ACCESSKEY"
aws_secret_key: "SECRET"
command: "create"
zone: "{{ dns_zone }}"
hosted_zone_id: "{{ dns_zone_id }}"
record: "{{ item.dns_record }}"
type: "{{ item.dns_type }}"
ttl: "{{ item.dns_ttl }}"
value: "{{ item.dns_value }}"
failover: "{{item.failover}}"
health_check: "{{item.health_check}}"
identifier: "{{item.identifier}}"
with_items:
- "{{ dns_records }}"
Example of DNS records:
dns_records:
- dns_record: "try1.example.com"
dns_type: "A"
dns_ttl: "3600"
dns_value: "1.1.1.1"
failover: "PRIMARY"
health_check: "aeejas728asd"
identifier: "identifier01"
- dns_record: "try2.example.com"
dns_type: "A"
dns_ttl: "3600"
dns_value: "2.2.2.2"
If i run paybook role FAILS because second value have undefined failover, health_check and identifier. How can i set expression for IF else?
My try:
identifier: "{{item.identifier if item.identifier is defined else '!'}}"
is not working. I need IF not defined THEN IGNORE VALUE.
Thanks for help!
A: From the docs:
identifier: "{{item.identifier|default(omit)}}"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40556950",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Get columns values by a primary key, sqlite I was working on this project using flask, and I am trying to create a route where you can see a post's info (every post's an ID insert in a table like a primary key)
I was trying to display the row values by the primary key (id) on an HTML file. I mean something like this:
primary key(id)-> title's value -> description's value
And display them all together by just having the id (that we got by the route variable) that is the primary key.
However, I don't know if this is possible. Does someone have any idea?
this is my .db file
@app.route("/post/<id>")
def post_list(id):
db = get_db()
post_id = db.execute("SELECT * FROM post WHERE id = ?", [id])
result_id = post_id.fetchone()
return "<h1>ID: {}</h1>".format(result_id["id"])
| {
"language": "en",
"url": "https://stackoverflow.com/questions/72307917",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Protobuf generated file doesn't recognize import path I have a proto file product.proto and I want to use it in catalog.proto. I can successfully import product.proto in catalog.proto but auto-generated catalog.pb.go is not able to reconize the path of its dependency i.e. product.pb.go. It states:
could not import catalog/pb/entities (cannot find package "catalog/pb/entities" in any of
/usr/local/go/src/catalog/pb/entities (from $GOROOT)
/Users/trimulabs/go/src/catalog/pb/entities (from $GOPATH))
Directory structure
catalog
┣ main
┃ ┣ client.go
┃ ┗ server.go
┣ pb
┃ ┣ entities
┃ ┃ ┣ product.pb.go
┃ ┃ ┗ product.proto
┃ ┣ catalog.pb.go
┃ ┗ catalog.proto
catalog.proto
syntax = "proto3";
package catalog;
import "catalog/pb/entities/product.proto";
service CatalogService {
rpc PostProduct (PostProductRequest) returns (PostProductResponse) {}
rpc GetProduct (GetProductRequest) returns (GetProductResponse) {}
rpc GetProducts (GetProductsRequest) returns (GetProductsResponse) {}
}
product.proto
message Product {
string id = 1;
string name = 2;
string description = 3;
double price = 4;
}
message PostProductRequest {
string name = 1;
string description = 2;
double price = 3;
}
message PostProductResponse {
Product product = 1;
}
message GetProductRequest {
string id = 1;
}
message GetProductResponse {
Product product = 1;
}
message GetProductsRequest {
uint64 skip = 1;
uint64 take = 2;
repeated string ids = 3;
string query = 4;
}
message GetProductsResponse {
repeated Product products = 1;
}
Can anyone please help?
A: The error you are seeing is caused because your generated protobuf file likely has an incorrect import path.
If you check your product.pb.go file, it likely has a like like:
import "catalog/pb/entities"
This means it is trying to import the go package with that specified path. As you are probably familiar with, a go package must use the absolute path, so this needs to look something like:
import "github.com/<myuser>/<myproject>/catalog/pb/entities"
protoc-gen-go fortunately supports a couple of flags to help you with this.
Step 1. Set go_package in your .proto file to specify the anticipated import path in go.
option go_package = "example.com/foo/bar";
Step 2: use the --go_opt=module=github.com/<myuser>/<project> flag of protoc to strip the module prefix from your generated code. Otherwise you would get something like this as an output (assuming you are using the current directory as your go_out path
catalog/
main/
pb/
github.com/
<myuser>/
<project>/
catalog/
pb/
entities/
I would recommend reviewing the documentation page on the protoc-gen-go go flags:
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66349677",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Defining a Generic Method in a Trait When Using Algebraic Data Type in Scala I have defined an abstract data type, and i wanted to make it fairly general and scalable.
However, scala type system is giving me a nightmare.
sealed trait Tree[+A] {
def evaluateTree(): A = this match {
case Leaf(value) => value
case Branch_A1(op, left) => op(evaluateTree(left))
case Branch_A2(op, left, right) => op(evaluateTree(left),evaluateTree(right))
}
}
case object EmptyTree extends Tree[Nothing]
case class Leaf[A](value: A) extends Tree[A]
case class Branch_A1[A](op: A => A, left: Tree[A]) extends Tree[A]
case class Branch_A2[A](op: (A,A) => A, left: Tree[A], right: Tree[A]) extends Tree[A]
A would be e.g. Double. So in this case i have a tree which has branches that represent functions of one and two arguments (Branch_A1, Branch_A2)
However it does not compile. In op(evaluateTree(left)) it says that "it cannot resolve ... with such reference".
I could take the function away from the class into a more functional pattern but i want to do it following an object design. The only way i can get it into compiling is to do:
sealed trait Tree[+A] {
def evaluateTree(t: Tree[A]): A = this match {
case Leaf(value) => value
case Branch_A1(op, left) => op(evaluateTree(left))
case Branch_A2(op, left, right) => op(evaluateTree(left),evaluateTree(right))
}
}
case object EmptyTree extends Tree[Nothing]
case class Leaf[A](value: A) extends Tree[A]
case class Branch_A1[A](op: A => A, left: Tree[A]) extends Tree[A]
case class Branch_A2[A](op: (A,A) => A, left: Tree[A], right: Tree[A]) extends Tree[A]
which is stupid since i need to pass it the instance of the object.
I need to tell the compiler that this is an Tree[A]. So i have tried:
sealed trait Tree[+A] {
this: Tree[A] =>
def evaluateTree(): A = this match {
case Leaf(value) => value
case Branch_A1(op, left) => op(evaluateTree(left))
case Branch_A2(op, left, right) => op(evaluateTree(left),evaluateTree(right))
}
}
Still the compiler does not let me go, the error is the same actually.
How can i solve this??
A: It looks like your receivers are screwed up. evaluateTree does not take arguments. I'm assuming you want to evaluate the subtree, as in op(evaluateTree(left)) should instead be op(left.evaluateTree())
def evaluateTree(): A = this match {
case Leaf(value) => value
case Branch_A1(op, left) => op(left.evaluateTree())
case Branch_A2(op, left, right) => op(left.evaluateTree(),right.evaluateTree())
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41065907",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Rails Serializer Association I have a Component class that can be either a Section or Question. A Section can have many Component (i.e. Question).
I'm trying to get the serializer to send back the Component(Section) and its associated Component(Question). Right now, based on my code below, I'm getting back the Question and the Section object that it's associated to (see below). How can I get the serializer to return what I'm expecting?
Response (current):
{"data":
[{"id": 1,
"type": "Section",
"content": "ABC",
"section_id": null,
"section": null
},
{"id": 2,
"type": "Question",
"content": "Q1",
"section_id": 1,
"section":
{"id": 1,
"type": "Section",
"content": "ABC",
"section_id": null
}
},
{"id": 3,
"type": "Question",
"content": "Q2",
"section_id": 1,
"section":
{"id": 1,
"type": "Section",
"content": "ABC",
"section_id": null
}
}]
}
Response (expected):
{"data":
[{"id": 1,
"type": "Section",
"content": "ABC",
"section_id": null,
"section":
{"id": 2,
"type": "Question",
"content": "Q1",
"section_id": 1
},
{"id": 3,
"type": "Question",
"content": "Q2",
"section_id": 1
}
}]
}
ComponentSerializer:
class ComponentSerializer < ActiveModel::Serializer
belongs_to :section
attributes :id,
:type,
:content,
:section_id
end
SectionSerializer:
class ComponentSerializer < ActiveModel::Serializer
has_many :components
attributes :id,
:type,
:content,
:section_id
end
component.rb (model):
class Component < ApplicationRecord
# == Associations ==========================
belongs_to :project
belongs_to :section,
class_name: 'Section',
foreign_key: :section_id,
optional: true
end
section.rb (model):
class Section < Component
# == Associations ==========================
has_many :components,
class_name: 'Component',
foreign_key: :component_id,
dependent: :destroy
end
component_controller.rb:
before_action :load_project
before_action :load_scope
def index
components = paginate @scope, per_page: per_page
data = ActiveModelSerializers::SerializableResource.new(
components,
each_serializer: ComponentSerializer
)
render_response(:ok, { data: data })
rescue ActiveRecord::RecordNotFound
render_response(:not_found, { resource: "Project/Lesson" })
end
def load_scope
@scope = @project.components
@scope = @scope.order("position")
end
def load_project
@project = Project.find(params[:project_id])
rescue ActiveRecord::RecordNotFound
render_response(:not_found, { resource: "Project/Lesson" })
end
| {
"language": "en",
"url": "https://stackoverflow.com/questions/51178633",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Python module ecdsa errors while running paramiko I am trying to install paramiko module..it fails with the below error
python ./test.py
Traceback (most recent call last):
File "./test.py", line 30, in <module>
import paramiko
File "/tmp/build-paramiko/paramiko-1.12.0/paramiko/__init__.py", line 64, in <module>
from transport import SecurityOptions, Transport
File "/tmp/build-paramiko/paramiko-1.12.0/paramiko/transport.py", line 45, in <module>
from paramiko.ecdsakey import ECDSAKey
File "/tmp/build-paramiko/paramiko-1.12.0/paramiko/ecdsakey.py", line 24, in <module>
from ecdsa import SigningKey, VerifyingKey, der, curves
ImportError: No module named ecdsa
Any suggestions on how to proceed with the paramiko installation ?
A: Download the package from 'https://github.com/warner/python-ecdsa' and install it using command
python setup.py install
Your problem will be solved.
A: You can use easy_install to install the lost module "ecdsa" ,which like: easy_install ecdsa,
but you have to ready easy_install first!
A: this:
from ecdsa import SigningKey, VerifyingKey, der, curves
ImportError: No module named ecdsa
suggests that the python-ecdsa package is missing, you can install it with
pip install ecdsa
Though in general, you shouldn't need to install paramiko from sources. You can install it with
pip install paramiko
that has the benefit of automatically resolving the dependencies of a package
| {
"language": "en",
"url": "https://stackoverflow.com/questions/20525147",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Select only 1 payment from a table with customers with multiple payments I have a table called "payments" where I store all the payments of my costumers and I need to do a select to calculate the non-payment rate in a given month.
The costumers can have multiples payments in that month, but I should count him only once: 1 if any of the payments is done and 0 if any of the payment was made.
Example:
+----+------------+--------+
| ID | DATEDUE | AMOUNT |
+----+------------+--------+
| 1 | 2016-11-01 | 0 |
| 1 | 2016-11-15 | 20.00 |
| 2 | 2016-11-10 | 0 |
+----+------------+--------+
The result I expect is from the rate of november:
+----+------------+--------+
| ID | DATEDUE | AMOUNT |
+----+------------+--------+
| 1 | 2016-11-15 | 20.00 |
| 2 | 2016-11-10 | 0 |
+----+------------+--------+
So the rate will be 50%.
But if the select is:
SELECT * FROM payment WHERE DATEDUE BETWEEN '2016-11-01' AND '2016-11-30'
It will return me 3 rows and the rate will be 66%, witch is wrong. Ideas?
PS: This is a simpler example of the real table. The real query have a lot of columns, subselects, etc.
A: Try this
SELECT
id
, SUM(AMOUNT) AS AMOUNT
FROM
Payment
GROUP BY
id;
This might help if you want other columns.
WITH cte (
SELECT
id
, ROW_NUMBER() OVER (PARTITION BY ID ORDER BY AMOUNT DESC ) AS RowNum
-- other row
)
SELECT *
FROM
cte
WHERE
RowNum = 1;
A: It sounds like you need to partition your results per customer.
SELECT TOP 1 WITH TIES
ID,
DATEDUE,
AMOUNT
ORDER BY ROW_NUMBER() OVER (PARTITION BY ID ORDER BY AMOUNT DESC)
WHERE DATEDUE BETWEEN '2016-11-01' AND '2016-11-30'
PS: The BETWEEN operator is frowned upon by some people. For clarity it might be better to avoid it:
*
*What do BETWEEN and the devil have in common?
A: To calculate the rate, you can use explicit division:
select 1 - count(distinct case when amount > 0 then id end) / count(*)
from payment
where . . .;
Or, in a way that is perhaps easier to follow:
select avg(flag * 1.0)
from (select id, (case when max(amount) > 0 then 0 else 1 end) as flag
from payment
where . . .
group by id
) i
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41511026",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Apache Camel aggregator in combination with onCompletion I want the onCompletion to occur after all the aggregated exchanges triggered by both completion size followed by timeout are processed. But it occurs right after the completion size is triggered with some of the exchanges waiting to be triggered by the timeout criteria.
A: I have the route configured as
from(fromEndPoint)
.onCompletion()
.doSomething()
.split() // each Line
.streaming()
.parallelProcessing()
.unmarshal().bindy
.aggregate()
.completionSize(100)
.completionTimeout(5000)
.to(toEndpoint)
Assume if the split was done on 405 lines, the first 4 sets of aggregated exchanges go to the to endpoint completing 400 lines(exchanges) . And then, it immediately triggers the onCompletion. But there are still 5 more aggregated exchanges which would be triggered when the completionTimeout criteria is met. It didn't trigger the onCompletion after the 5 exchanges are routed to the to endpoint.
My question here is , either the onCompletion should be triggered for each exchange or once after all.
Note:- My from endpoint here is a File.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/38414576",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: split cell at special character if comma found after first word hi i've got some budget data with names and titles that read "Last, First - Title" and other rows in same column position that read "anything really - ,asd;flkajsd". I'd like to split the column IF first word ends in a "," at the "-" position that follows it.
ive tried this:
C22$ITEM2 <- ifelse(grepl(",", C22$ITEM), C22$ITEM, NA)
test <- str_split_fixed(C22$ITEM2, "-", 2)
C22 <- cbind(C22, test)
but i'm getting other cells with commas elsewhere, need to limit to just "if first word ends in comma"
A: library(tidyverse)
data <- tibble(data = c("Doe, John - Mr", "Anna, Anna - Ms", " ,asd;flkajsd"))
data
data %>%
# first word must ed with a
filter(data %>% str_detect("^[A-z]+a")) %>%
separate(data, into = c("Last", "First", "Title"), sep = "[,-]") %>%
mutate_all(str_trim)
# A tibble: 1 × 3
# Last First Title
# <chr> <chr> <chr>
#1 Anna Anna Ms
A: We may use extract to do this - capture the regex pattern as two groups ((...)) where the first group would return word (\\w+) from the start (^) of the string followed by a ,, zero or more space (\\s*), another word (\\w+), then the - (preceding or succeeding zero or more space and the second capture group with the word (\\w+) before the end ($) of the string
library(tidyr)
library(dplyr)
extract(C22, ITEM, into = c("Name", "Title"),
"^(\\w+,\\s*\\w+)\\s*-\\s*(\\w+)$") %>%
mutate(Name = coalesce(Name, ITEM), .keep = 'unused')
NOTE: The mutate is added in case the regex didn't match and return NA elements, we coalesce with the original column to return the value that corresponds to NA
| {
"language": "en",
"url": "https://stackoverflow.com/questions/71036291",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: BEM: What are modifiers allowed to modify? Let's say I have the following CSS for a generic list component, using BEM and SCSS:
.list {
&__item {
&:not(:last-child) {
margin-right: .3em;
}
}
}
I want to add a modifier that can make the list vertical, like so:
.list--vertical {
display: flex;
flex-direction: column;
}
My problem arises when I think about the margin for list__item elements. For vertical lists, I want my margin on the bottom, not right of each item. If I understood BEM correctly, I cannot modify the style of list__item based on the modifer of list, is that correct?
To be more precise, this is what I want to do:
.list--vertical {
display: flex;
flex-direction: column;
.list__item {
&:not(:last-child) {
margin-bottom: .3em;
margin-right: 0;
}
}
}
What is the accepted way of dealing with this using BEM? Another modifier for list__item that handles the margin? Another block entirely for vertical lists?
A:
What is the accepted way of dealing with this using BEM?
Depends on what version of BEM you're using. I use a variant of the pre-spec concept of BEM, which means that you'll have different answers if you follow bem.info.
Modifiers should be attached to the element they modify. Modifying a block, however, allows the modifier to be inherited by child elements:
<div class="foo foo--example">
<div class="foo__bar foo--example__bar">...</div>
<div>
This gets messy when child elements have modifiers as well:
<div class="foo foo--example">
<div class="
foo__bar
foo--example__bar
foo__bar--another-example
foo--example__bar--another-example">...</div>
<div>
This form of BEM syntax is quite verbose. It's best used on generated code.
I use LESS for CSS preprocessing, so my BEM code often looks like:
.foo {
...
&__bar {
...
}
}
With modifiers it becomes:
.foo {
...
&__bar {
...
}
&--example {
...
&__bar {
...
}
}
}
This enforces that the cascade is in the proper order and that all selectors continue to have exactly one class.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40242985",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Only update messages when there is a connection I built a site display messages, so the msgloader.js updates the messages every 10 seconds from admin. The client displays this site on a screen constantly.
The problem is that sometimes the internet connection is not so good, the display got disconnected and the msgloader.js still updates the messages, in the end the screen freeze (the reason I know is that there is a clock on the site as well, the clock gets time from the local machine, it simply freeze at a time until we refresh the page which is an issue).
I suspect this freeze issue is because there is too much script running and the machine ram has been taken up.
BACK TO THE QUESTION, Is there any way we can set the below code into update messages every 10 seconds when there is an internet connection, otherwise update messages every hour/two when there is no internet connection.
Any help is appreciated. Thanks.
--------------------------------------------------------------------
Update the data for the static sections
--------------------------------------------------------------------
*/
function updateSection(sect)
{
setTimeout('updateSection(' + sect + ')', 10000);
//alert('updateSection: ' + sect);
var ajax = new sack();
ajax.requestFile = 'ajax/getMessages.php?section='+sect;
ajax.method = 'post';
/*ajax.onError = whenError;*/
ajax.onCompletion = whenComplete;
ajax.runAJAX();
/* function whenError()
{
alert('Could not return getMessages values. <br />Please notify the system administrator.');
}*/
function whenComplete()
{
var messages = ajax.response;
var messages1 = messages.split('---');
var num_messages = messages1[0];
//alert('Num Lines: ' + num_messages );
var messages_list = messages1[1];
//alert('MESSAGES: '+messages);
var msg_data_array = messages_list.split('::');
var i=0;
switch(sect)
{
case 1:
for(i=0;i<=num_messages;i++)
{
var j = i + 1;
icon_to_use = 'icon'+j;
// Set icon class
var icon = document.getElementById('icon_' + sect + '_' + j);
icon_to_use.className = 'icon_pointer';
// Set message text
// -------------------------------------------
var msgtext_array = msg_data_array[i].split('##');
// Here's the title
// -------------------------------------------
var msgtext_1a = msgtext_array[1];
// Here's the text
// -------------------------------------------
var msgtext_1 = msgtext_array[2];
// Set the title space
// -------------------------------------------
var msg_1a = document.getElementById('msg_text_' + sect + '_' + j + 'a');
// Set the text space
// -------------------------------------------
var msg_1 = document.getElementById('msg_text_' + sect + '_' + j);
// Write in the title
// -------------------------------------------
msg_1a.innerHTML = msgtext_1a;
msg_1.innerHTML = "<img src='[url_of_image]' /> " + msgtext_1;
// Write in the text
// -------------------------------------------
msg_1.innerHTML = (msgtext_1) ? separator + msgtext_1 : msgtext_1;
//msg_1a.style.borderBottom="2px solid white";
msg_1a.style.borderBottom="2px solid white";
msg_1.style.borderBottom="2px solid white";
} break;
default:
break;
}
// DEBUG
if(debug)
{
debugReport
(
'updateSection():ID: '+msg_id+
'<br />'+'updateSection():TIMEOUT: '+timeout+
'<br />'+'ROTATE: '+rotate
);
}
else
{
debugReset();
}
}
}
/*
A: Try to use this,
var online = navigator.onLine;
and now you can do like this,
if(online){
alert('Connection is good');
}
else{
alert('There is no internet connection');
}
UPDATE:
Try to put the alert here,
if(online){
setTimeout('updateSection(' + sect + ')', 10000);
//alert('updateSection: ' + sect);
var ajax = new sack();
ajax.requestFile = 'ajax/getMessages.php?section=1';
ajax.method = 'post';
/*ajax.onError = whenError;*/
ajax.onCompletion = whenComplete;
ajax.runAJAX();
}
else{
alert('There is no internet connection');
}
A: If I'm understanding you correctly you could do something like this:
every time onerror event happens on an ajax request increment a counter. After a set limit of fails in a row / fails in an amount of time you change the length of the time-out.
var timeoutLength = 10000
setTimeout('updateSection(' + sect + ')', timeoutLength);
changing the timeoutLength once the ajax requests are failing, IE there is not internet connection.
EDIT
var errorCount = 0;
ajax.onError = whenError;
function whenError() {
errorCount++
if(errorCount < 5) {
timeoutLength = 3600000
}
}
function whenComplete() {
errorCount = 0
...
}
This requires 5 errors in a row to assume that the internet is down. You should probably play around with that. But this should show you the general idea.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/11405196",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: I am trying to scrape a website using python request that doesn't change its link when click on load more i tried but looks its json I'm trying to scrape all the add links from a site and have I been successful in doing so. please check the link
https://www.olx.in/hyderabad_g4058526/q-note-9-pro?isSearchCall=true
The site page has a load more button for loading more adds.
[1]: https://ibb.co/DGNsG6j"
The problem is that clicking on load more doesn't change the URL of the page, therefore I'm being able to scrape only the initial links displayed by default Please help me with this.
A: Have you considered using Selenium? It is able to click through websites automatically by locating HTML tags and clicking links. https://selenium-python.readthedocs.io/index.html
A: Look into their private API; Inspect Element, and Network tab. Notice when you click the 'Load More' button your browser makes a request to the following URL:
https://www.olx.in/api/relevance/v2/search?facet_limit=100&lang=en&latitude=17.46497&location=4058526&location_facet_limit=20&longitude=78.43517&page=1&platform=web-desktop&query=note%209%20pro&spellcheck=true
You can modify the query via the URL params. Then, using requests, you can query this information and organize the JSON return:
{
"version": "100.0",
"data": [
{
"id": "1636448838",
"score": 1679.043212890625,
"spell": {
"id": 54,
"key": "GEAS",
"version": "1",
"main": true,
"facet_disabled": false,
"default_sorting": "DEFAULT"
},
"status": {
"status": "active",
"allow_edit": true,
"ban_reason_id": null,
"display": "active",
"translated_display": "Active",
"link": null,
"flags": {
"new": false,
"hot": false
},
"message": null
},
"category_id": "1453",
"favorites": {
"count": 0,
"count_label_next": "1"
},
"images": [
{
"id": "1003855963",
"external_id": "tj7vu6vj98qp-IN",
"width": 524,
"height": 1080,
"url": "https://apollo-singapore.akamaized.net:443/v1/files/tj7vu6vj98qp-IN/image",
"full": {
"width": 1080,
"height": 2225,
"url": "https://apollo-singapore.akamaized.net:443/v1/files/tj7vu6vj98qp-IN/image;s=1080x2225"
},
"big": {
"width": 505,
"height": 1040,
"url": "https://apollo-singapore.akamaized.net:443/v1/files/tj7vu6vj98qp-IN/image;s=505x1040"
},
"medium": {
"width": 120,
"height": 247,
"url": "https://apollo-singapore.akamaized.net:443/v1/files/tj7vu6vj98qp-IN/image;s=120x247"
},
"small": {
"width": 120,
"height": 247,
"url": "https://apollo-singapore.akamaized.net:443/v1/files/tj7vu6vj98qp-IN/image;s=120x247"
}
},
{
"id": "1003855964",
"external_id": "s6z25cvcbz052-IN",
"width": 524,
"height": 1080,
"url": "https://apollo-singapore.akamaized.net:443/v1/files/s6z25cvcbz052-IN/image",
"full": {
"width": 1080,
"height": 2225,
"url": "https://apollo-singapore.akamaized.net:443/v1/files/s6z25cvcbz052-IN/image;s=1080x2225"
},
"big": {
"width": 505,
"height": 1040,
"url": "https://apollo-singapore.akamaized.net:443/v1/files/s6z25cvcbz052-IN/image;s=505x1040"
},
"medium": {
"width": 120,
"height": 247,
"url": "https://apollo-singapore.akamaized.net:443/v1/files/s6z25cvcbz052-IN/image;s=120x247"
},
"small": {
"width": 120,
"height": 247,
"url": "https://apollo-singapore.akamaized.net:443/v1/files/s6z25cvcbz052-IN/image;s=120x247"
}
},
{
"id": "1003855965",
"external_id": "mq6ouyke1k3h3-IN",
"width": 524,
"height": 1080,
"url": "https://apollo-singapore.akamaized.net:443/v1/files/mq6ouyke1k3h3-IN/image",
"full": {
"width": 1080,
"height": 2225,
"url": "https://apollo-singapore.akamaized.net:443/v1/files/mq6ouyke1k3h3-IN/image;s=1080x2225"
},
"big": {
"width": 505,
"height": 1040,
"url": "https://apollo-singapore.akamaized.net:443/v1/files/mq6ouyke1k3h3-IN/image;s=505x1040"
},
"medium": {
"width": 120,
"height": 247,
"url": "https://apollo-singapore.akamaized.net:443/v1/files/mq6ouyke1k3h3-IN/image;s=120x247"
},
"small": {
"width": 120,
"height": 247,
"url": "https://apollo-singapore.akamaized.net:443/v1/files/mq6ouyke1k3h3-IN/image;s=120x247"
}
},
{
"id": "1003855966",
"external_id": "7vfcbj5fb8fh2-IN",
"width": 524,
"height": 1080,
"url": "https://apollo-singapore.akamaized.net:443/v1/files/7vfcbj5fb8fh2-IN/image",
"full": {
"width": 1080,
"height": 2225,
"url": "https://apollo-singapore.akamaized.net:443/v1/files/7vfcbj5fb8fh2-IN/image;s=1080x2225"
},
"big": {
"width": 505,
"height": 1040,
"url": "https://apollo-singapore.akamaized.net:443/v1/files/7vfcbj5fb8fh2-IN/image;s=505x1040"
},
"medium": {
"width": 120,
"height": 247,
"url": "https://apollo-singapore.akamaized.net:443/v1/files/7vfcbj5fb8fh2-IN/image;s=120x247"
},
"small": {
"width": 120,
"height": 247,
"url": "https://apollo-singapore.akamaized.net:443/v1/files/7vfcbj5fb8fh2-IN/image;s=120x247"
}
}
],
"certified_car": false,
"is_kyc_verified_user": false,
"has_phone_param": false,
"locations_resolved": {
"COUNTRY_id": "1000001",
"COUNTRY_name": "India",
"ADMIN_LEVEL_1_id": "2007599",
"ADMIN_LEVEL_1_name": "Telangana",
"ADMIN_LEVEL_3_id": "4058526",
"ADMIN_LEVEL_3_name": "Hyderabad",
"SUBLOCALITY_LEVEL_1_id": "5348837",
"SUBLOCALITY_LEVEL_1_name": "Murad Nagar"
},
"description": "Full condition with box + bill charger",
"created_at": "2021-05-18T10:53:54+05:30",
"inspection_info": null,
"package_id": null,
"title": "Note 9 pro",
"main_info": null,
"user_type": "Regular",
"display_date": "2021-05-18T05:23:54+0000",
"user_id": "508731436",
"price": {
"value": {
"raw": 14500,
"currency": {
"iso_4217": "INR",
"pre": "₹"
},
"display": "₹ 14,500"
},
"key_name": "Price",
"key": "price"
},
"created_at_first": "2021-05-18T10:53:54+05:30",
"locations": [
{
"lat": 17.39,
"lon": 78.448,
"region_id": "2007599",
"district_id": "5348837",
"city_id": "4058526"
}
],
"parameters": [
{
"type": "single",
"key": "make",
"value": "mi-phone",
"key_name": "Brand",
"formatted_value": "Mi",
"value_name": "Mi"
}
],
"monetizationInfo": null
}
],
"metadata": {
"sections": [
{
"id": 10,
"offset": 0,
"criterion": "less_than",
"distance": 10,
"relaxation_type": "bucket"
},
{
"id": 20,
"offset": 39,
"criterion": "less_than",
"distance": 20,
"relaxation_type": "bucket"
}
],
"feed_version": "100.0",
"total_ads": 190,
"total_suggested_ads": 0,
"ads_on_page": 20,
"total_pages": 4,
"suggested_sections": [],
"original_term": "note 9 pro",
"modified_term": "note 9 pro",
"original_label": "Showing results for ${original_term}",
"show_hint": false,
"show_original_items": true,
"show_suggested_items": false,
"filters": [
{
"id": "price",
"values": [],
"display_order": 200,
"description": "Budget",
"range": [
{
"id": "min",
"description": "min",
"min_value": 0,
"max_value": 10000000000
},
{
"id": "max",
"description": "max",
"min_value": 0,
"max_value": 10000000000
}
],
"type": "range-input",
"render_as": "range-input"
}
],
"applied_sorting": {
"key": "desc-creation"
},
"next_page_url": "http://api.olx.in/relevance/v2/search?facet_limit=100&clientId=pwa&location_facet_limit=20&spellcheck=true&latitude=17.46497&query=note%209%20pro&location=4058526&page=2&lang=en&clientVersion=7.10.1&platform=web-desktop&longitude=78.43517",
"applied_filters": [],
"search_query": "note 9 pro",
"modified_filters": {}
},
"empty": false,
"not_empty": true,
"suggested_data": []
}
I deleted all item entries except one above.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/67709555",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Trouble configuring Presto's memory allocation on AWS EMR I am really hoping to use Presto in an ETL pipeline on AWS EMR, but I am having trouble configuring it to fully utilize the cluster's resources. This cluster would exist solely for this one query, and nothing more, then die. Thus, I would like to claim the maximum available memory for each node and the one query by increasing query.max-memory-per-node and query.max-memory. I can do this when I'm configuring the cluster by adding these settings in the "Edit software settings" box of the cluster creation view in the AWS console. But the Presto server doesn't start, reporting in the server.log file an IllegalArgumentException, saying that max-memory-per-node exceeds the useable heap space (which, by default, is far too small for my instance type and use case).
I have tried to use the session setting set session resource_overcommit=true, but that only seems to override query.max-memory, not query.max-memory-per-node, because in the Presto UI, I see that very little of the available memory on each node is being used for the query.
Through Google, I've been led to believe that I need to also increase the JVM heap size by changing the -Xmx and -Xms properties in /etc/presto/conf/jvm.config, but it says here (http://docs.aws.amazon.com/emr/latest/ReleaseGuide/emr-presto.html) that it is not possible to alter the JVM settings in the cluster creation phase.
To change these properties after the EMR cluster is active and the Presto server has been started, do I really have to manually ssh into each node and alter jvm.config and config.properties, and restart the Presto server? While I realize it'd be possible to manually install Presto with a custom configuration on an EMR cluster through a bootstrap script or something, this would really be a deal-breaker.
Is there something I'm missing here? Is there not an easier way to make Presto allocate all of a cluster to one query?
A: As advertised, increasing query.max-memory-per-node, and also by necessity the -Xmx property, indeed cannot be achieved on EMR until after Presto has already started with the default options. To increase these, the jvm.config and config.properties found in /etc/presto/conf/ have to be changed, and the Presto server restarted on each node (core and coordinator).
One can do this with a bootstrap script using commands like
sudo sed -i "s/query.max-memory-per-node=.*GB/query.max-memory-per-node=20GB/g" /etc/presto/conf/config.properties
sudo restart presto-server
and similarly for /etc/presto/jvm.conf. The only caveats are that one needs to include the logic in the bootstrap action to execute only after Presto has been installed, and that the server on the coordinating node needs to be restarted last (and possibly with different settings if the master node's instance type is different than the core nodes).
You might also need to change resources.reserved-system-memory from the default by specifying a value for it in config.properties. By default, this value is .4*(Xmx value), which is how much memory is claimed by Presto for the system pool. In my case, I was able to safely decrease this value and give more memory to each node for executing the query.
A: As a matter of fact, there are configuration classifications available for Presto in EMR. However, please note that these may vary depending on the EMR release version. For a complete list of the available configuration classifications per release version, please visit 1 (make sure to switch between the different tabs according to your desired release version). Specifically regarding to jvm.config properties, you will see in 2 that these are not currently configurable via configuration classifications. That being said, you can always edit the jvm.config file manually per your needs.
Amazon EMR 5.x Release Versions
1
Considerations with Presto on Amazon EMR - Some Presto Deployment Properties not Configurable:
2
| {
"language": "en",
"url": "https://stackoverflow.com/questions/44147318",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Recursive SELECT in Oracle I have two tables:
Table One
NumLig - CodPro - CodDer
901 - BSFX30 - 0140I18
898 - RSFX30 - 18
6 - MFLX - U
Table Two
NumLig - CodCmp - DerCmp - QtdUti - PerCmp
6 - MDFIB0008 - null - 1 - 2
6 - MDQDN0009 - null - 0,24 - 1
898 - MFLX - U - 0,942 - 2
898 - MDCAM0002 - 0,05 - 0
901 - RSFX - 18 - 1 - 2,5
901 - EDEAD0005 - 0,245 - 0
What I need is that I search for BSFX30 - 0140I18 the output to be:
MDFIB0008 - null - 1 - 2
MDQDN0009 - null - 0,24 - 1
MFLX - U - 0,942 - 2
MDCAM0002 - 0,05 - 0
RSFX - 18 - 1 - 2,5
EDEAD0005 - 0,245 - 0
If I do this:
SELECT E622SIM.CodPro, E622SIM.CodDer, E622DER.TipCpc, E622SIM.NumLig, E622DER.CodCmp, E622DER.DerCmp, E622DER.QtdUti, E622DER.PerCmp
FROM E622SIM
JOIN E622DER
ON E622SIM.NumLig = E622DER.NumLig
The output to be all the data, but I need filter by CodPro and CodDer. If I do this:
SELECT E622SIM.CodPro, E622SIM.CodDer, E622DER.TipCpc, E622SIM.NumLig, E622DER.CodCmp, E622DER.DerCmp, E622DER.QtdUti, E622DER.PerCmp
FROM E622SIM
JOIN E622DER
ON E622SIM.NumLig = E622DER.NumLig
the output to be only:
RSFX - 18 - 1 - 2,5
EDEAD0005 - 0,245 - 0
but I need:
MDFIB0008 - null - 1 - 2
MDQDN0009 - null - 0,24 - 1
MFLX - U - 0,942 - 2
MDCAM0002 - 0,05 - 0
RSFX - 18 - 1 - 2,5
EDEAD0005 - 0,245 - 0
This because RSFX is children of BSFX30, and MFLX is children of RSFX
Thanks!
A: I think you need see documentation about Hierarchical Queries
to connect your data use connect by, to get root element - connect_by_root, to filter the elements by root you need use where connect_by_root(E622SIM.CodPro) = 'BSFX30'
I tried to compile your description into scripts
create table E622SIM(NumLig int, CodPro varchar2(100), CodDer varchar2(100));
insert into E622SIM values (901, 'BSFX30', '0140I18');
insert into E622SIM values (898, 'RSFX30', '18');
insert into E622SIM values (6, 'MFLX', 'U');
create table E622DER (NumLig int, CodCmp varchar2(100), DerCmp varchar2(100), QtdUti varchar2(100), PerCmp varchar2(100));
insert into E622DER values(901, 'RSFX30',18,1,'2,5');
insert into E622DER values(901, 'EDEAD0005',0,245,0);
insert into E622DER values(898, 'MFLX','U','0,942',2);
insert into E622DER values(898, 'MDCAM0002',null,'0,05',0);
insert into E622DER values(6, 'MDFIB0008', null, 1, 2);
insert into E622DER values(6, 'MDQDN0009',null,'0,24',1);
and this is the query that looks as what you need
select E622DER.CodCmp
,E622DER.DerCmp
,E622DER.QtdUti
,E622DER.PerCmp
from E622DER
left outer join E622SIM on E622SIM.NumLig = E622DER.NumLig
where connect_by_root(E622SIM.CodPro) in ('BSFX30')
connect by prior E622DER.CodCmp = E622SIM.CodPro
order by level desc, E622DER.CodCmp asc
CODCMP DERCMP QTDUTI PERCMP
1 MDFIB0008 1 2
2 MDQDN0009 0,24 1
3 MDCAM0002 0,05 0
4 MFLX U 0,942 2
5 EDEAD0005 0 245 0
6 RSFX30 18 1 2,5
| {
"language": "en",
"url": "https://stackoverflow.com/questions/33650405",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-6"
} |
Q: Is CDN and Cloud are same? Is the CDN and Cloud computing are same? If both are different, how they differ? I have googled it, when someone asked me this question. But i could not able to get any clear idea on this. So can anyone explain about this, which would be greatly useful to lot of people.
And also please explain where the CDN will be used and where the cloud will be used?
A: The big difference is that cloud computing is a big group of servers in 1 data center building which is usually at one location. On the other hand CDN is also group of servers but distributed around the country so it allows web visitors a better and faster access to the website. For example if you're in A location trying to access a server in B it can be faster to be hitting a server locally in A for the files. The CDN is usually able to support much larger traffic volumes since the speed is calculated based on location the traffic comes from.
CDN work on the principle of delivering content form the nearest located server as per user location.
CDN is short is a way to boost and speed up your website turn around time.
A: CDN is simply a network of servers that replicate your binary files so that they are served from geographically close locations. CDN has been around for a lot longer than cloud computing as you know it today.
Not every cloud provider is a CDN, and not every CDN is a cloud computing provider.
Cloud computing is simply - dividing up a large computing resource (usually processing power) into little chunks which you can use remotely.
CDN is simply - a bunch of "disks" that are spread across the world in different datacenters. You upload your file to one of these disks - and then tell it where your customers are coming from. It will then copy the same file to other disks that are nearer to your customers; giving your visitors a faster experience. This collection of disks is called the content delivery network.
One of the biggest names in CDN is Akamai.
A: Short answer: They are different. Detailed one follows:
*
*CDN short for Content delivery network is more like edge computing. It follows end-to-end principle of networking meaning, as much work can be de-centralized and distributed to nodes near user, do it. Reduce single point of failure. You can read a small article written by me at : http://www.sitepoint.com/content-delivery-networks-cdn-get-to-the-edge/
*Cloud Computing is much more than delivering content near edge. It's elastic computing, storage and network on demand in very broad sense. For computing you need: storage & processing power and that's what is provided by Cloud Computing
| {
"language": "en",
"url": "https://stackoverflow.com/questions/11928903",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "18"
} |
Q: Minify JS Files with Webpack I'm trying to use the webpack to minify all my js, .css, images and fonts files. As I am studying the Webpack, I am trying first with the JS files.
In my js folder I have the files jquery-2.2.3.min.js, bootstrap.min.js, easing.js, move-top.js and SmoothScroll.min.js.
when i try to run npm start it generates the error Error: Conflict: Multiple chunks iss assets to the same filename principal.js (chunks jquery and bootstrap).
Below is my webpack.config.js:
const webpack = require('webpack');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
mode: 'development',
entry: {
jquery: './js/jquery-2.2.3.min.js',
bootstrap: './js/bootstrap.min.js',
easing: './js/easing.js',
move_top: './js/move-top.js',
smooth_scroll: './js/SmoothScroll.min.js',
},
output: {
filename: 'default.js',
path: __dirname + '/public'
},
plugins: [
new MiniCssExtractPlugin({
filename: "style.css"
})
],
module: {
rules:[
{
test: /\.css$/,
use: [
MiniCssExtractPlugin.loader,
'css-loader'
]
},
{
test: /\.(png|svg|jpg|jpeg|gif)$/,
use: [
'file-loader'
]
}
]
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/64472864",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Define a function to update a class integer property I'm having issues defining a function that controls the correct "speed" (accelerate/slow down).
I currently have my code like this:
class Train():
serial_nummer = 2021001
def __init__(self, type, buildyear):
self.type = type
self.buildyear = buildyear
self.serial_nummer = Train.serial_nummer
self.speed = ()
Train.serial_nummer += 1
return
def snelheid(self, speed):
pass
def __str__(self):
return (f"Train type: {self.type} \nBuildyear: {self.buildyear} \nSerial number: {self.serial_nummer} \nCurrent speed: {self.speed}\n\n")
train1 = Train('Alfatrain', '2001')
train1.speed = 100
print (train1)
How can I create a function that controls the correct "speed"?
Now I'm just modifying the speed with train.speed = 100.
A: You don't really need a function when you can use train.speed += amount. You will want to initialize the speed as 0, not an empty tuple, though
Without more clarity, I'm guessing instructions are looking for
def accelerate(self, amount):
self.speed += amount
def decelerate(self, amount):
self.accelerate(-1*amount)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/69452362",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Convert the string to integer or number How can I convert the string in to the number/integer inside the transfor dataweave. I tried the below
%dw 2.0
import * from dw::util::Coercions
output application/json
---
{
"quoteId" : vars.setQuoteOppRecIds.Id,
"productCode" : payload.ServiceTypeCode,
"axSequenceNumber" : vars.counter as :number,
"phaseLevel" : payload.PhaseLevel as :number,
"activeInSOW" : if(payload.PhaseLevelActivateInSOW == "Yes") (toBoolean("true")) else (toBoolean("false")),
"phaseLevelProject" : payload.PhaseLevelProject
}
But I get the error like Invalid input ':', expected } or ',' for the object expression. (line 8, column 41): I tried to string to boolean using the toBoolean function and itseems to be working fine. Can anyone please tell me what is that I am missing with the string to integer/number conversion
A: The syntax for conversion in DW 2 is different. The Code you used is from dw 1. Adding references to type conversions in dw 2 below and fixed your DW script as well.
https://docs.mulesoft.com/dataweave/2.1/dataweave-types
%dw 2.0
import * from dw::util::Coercions
output application/json
---
{
"quoteId" : vars.setQuoteOppRecIds.Id,
"productCode" : payload.ServiceTypeCode,
"axSequenceNumber" : vars.counter as Number,
"phaseLevel" : payload.PhaseLevel as Number,
"activeInSOW" : if(payload.PhaseLevelActivateInSOW == "Yes") (toBoolean("true")) else (toBoolean("false")),
"phaseLevelProject" : payload.PhaseLevelProject
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/71666312",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Requiring array of modules in Webpack I am currently trying to load a variable array of modules with Webpack.
I've found this link: webpack can not require variable ,the request of a dependency is an expression but it doesn't seem to work for me.
In my project I've got a module inside my node_modules folder. The entry point of the module is called index.js.
Here's the basic structure:
| app
+---app.js
| js
+---gen.js
| node_modules
+---sample_module_1
| +---index.js
+-sample-module_2
+---index.js
| webpack.config.js
In future I'd like to add new modules. Therefore I tried following approach:
//app.js
var modules = [
"sample_module_1",
"sample_module_2"
]
for(var i = 0; i < modules.length; i++) {
require(modules[i] + "/index.js");
}
But Webpack doesn't seem to find the module. I've tried adding a resolveLoader to the webpack.config.js file:
//webpack.config.js
var path = require('path');
module.exports = {
entry: './app/app.js',
output: {
filename: 'gen.js',
path: path.resolve(__dirname, 'js')
},
resolveLoader: {
modules: ["node_modules"],
extensions: ['*', '.js']
}
};
Still, Webpack is not able to find the module.
I've also tried the suggestions on https://webpack.github.io/docs/context.html but still no results.
Any suggestions?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/44695541",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Entity Framework Core: What is the fastest way to check if a generic entity is already in the dbset and then add or update it? I load data from a CSV file, I create entities on the fly then I add them to a List<T>.
The following code takes a List<T> and adds the entities to the right DbSet.
public static void AddEntities<T>(List<T> entities, DbContext db) where T :class
{
using (db)
{
var set = db.Set<T>();
foreach(T e in entities)
{
set.Add(e);
}
db.SaveChanges();
}
}
I'd like to change it to add the entity only if it doesn't exist, otherwise it has to update it.
What is the best way to accomplish this with Entity Framework Core?
I believe I should use System.Reflection to:
*
*get at least the ID but it would be better to get all the keys for the dbset
*loop through the keys to find if an entity is already in the DbSet
*if found then update it with the values from the new entity otherwise add it to the set
Something like this:
public static void AddEntities<T>(List<T> entities, DbContext db) where T :class
{
using (db)
{
var set = db.Set<T>();
foreach(T e in entities)
{
var idProperty = e.GetType().GetProperty("ID").GetValue(e,null);
var obj = set.Find(idProperty);
if (obj==null)
{
set.Add(e);
}
else
{
var properties = (typeof(T)).GetProperties();
foreach (var p in properties)
{
var value = e.GetType().GetProperty(p.Name).GetValue(e,null);
obj.GetType().GetProperty(p.Name).SetValue(obj,value);
}
}
}
db.SaveChanges();
}
}
The code runs from 3 to 4 times slower than the simple add.
Is there a faster way? All the code examples I am finding are all for EF6, based on ObjectContext and IObjectContextAdapter and it seems this kind of code do not longer work with EF Core.
A: Instead of reflection, you could use the EF Core public (and some internal) metadata services to get the key values needed for Find method. For setting the modified values you could use EntityEntry.CurrentValues.SetValues method.
Something like this:
using Microsoft.EntityFrameworkCore.Metadata.Internal;
public static void AddEntities<T>(List<T> entities, DbContext db) where T : class
{
using (db)
{
var set = db.Set<T>();
var entityType = db.Model.FindEntityType(typeof(T));
var primaryKey = entityType.FindPrimaryKey();
var keyValues = new object[primaryKey.Properties.Count];
foreach (T e in entities)
{
for (int i = 0; i < keyValues.Length; i++)
keyValues[i] = primaryKey.Properties[i].GetGetter().GetClrValue(e);
var obj = set.Find(keyValues);
if (obj == null)
{
set.Add(e);
}
else
{
db.Entry(obj).CurrentValues.SetValues(e);
}
}
db.SaveChanges();
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42485128",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Regex extracting image links I've got the following Regular Expression to extract links out of an HTML document, using java.util.regex
<a\s.*?href=([^ >]+).*?<img\s.*?src=([^ ]+)(.*?>.*?<\/a>)
and suspect it to match the last link in this markup.
<font size="4">Mail : </font><a href="mailto:c.bantz@pgt-gmbh.com"><u><font size="4" color="#0000ff">s.weber@pgt-gmbh.com</font></u></a><br />
<br />
<font size="4">Internet : </font><a href="http://www.pgt-gmbh.com/"><u><font size="4" color="#0000ff">http://www.pgt-gmbh.com</font></u></a><font size="4"> </font><br />
<br />
<br />
<font size="4"> </font><a class="domino-attachment-link" style="display: inline-block; text-align: center" href="/_dv/_dv/documents_DE.nsf/0/7fadd8be280a2e34c1257dfd00307098/$FILE/Anfrage.pdf" title="Anfrage.pdf"><img src="/_dv/_dv/documents_DE.nsf/0/7fadd8be280a2e34c1257dfd00307098/f_Text/0.5F66?OpenElement&FieldElemFormat=gif" width="32" height="32" alt="Anfrage.pdf" border="0" /> - Anfrage.pdf</a>
But it doesn't match the link but does something like a greedy search, starting with the mailto: and ending with the last link. The same expression works fine with the regex tester within http://regex101.com.
Any hints?
A: The problem would not occur if newlines are at the end of the text lines.
Now I have an explanation: The <a href="mailto is matched by the regular expression <a\s.*?href=([^ >]+). The following .*? will match any character sequence (without line breaks) until it finds <img.... And it does exactly this (in absence of line breaks).
Example (one with and one without newlines):
private static final Pattern P = Pattern.compile("<a\\s.*?href=([^ >]+).*?<img\\s.*?src=([^ ]+)(.*?>.*?<\\/a>)");
private static final String TEXT = "<font size=\"4\">Mail : </font><a href=\"mailto:c.bantz@pgt-gmbh.com\"><u><font size=\"4\" color=\"#0000ff\">s.weber@pgt-gmbh.com</font></u></a><br />"
+ "<br />"
+ "<font size=\"4\">Internet : </font><a href=\"http://www.pgt-gmbh.com/\"><u><font size=\"4\" color=\"#0000ff\">http://www.pgt-gmbh.com</font></u></a><font size=\"4\"> </font><br />"
+ "<br />"
+ "<br />"
+ "<font size=\"4\"> </font><a class=\"domino-attachment-link\" style=\"display: inline-block; text-align: center\" href=\"/_dv/_dv/documents_DE.nsf/0/7fadd8be280a2e34c1257dfd00307098/$FILE/Anfrage.pdf\" title=\"Anfrage.pdf\"><img src=\"/_dv/_dv/documents_DE.nsf/0/7fadd8be280a2e34c1257dfd00307098/f_Text/0.5F66?OpenElement&FieldElemFormat=gif\" width=\"32\" height=\"32\" alt=\"Anfrage.pdf\" border=\"0\" /> - Anfrage.pdf</a>";
private static final String NEWLINE_TEXT = "<font size=\"4\">Mail : </font><a href=\"mailto:c.bantz@pgt-gmbh.com\"><u><font size=\"4\" color=\"#0000ff\">s.weber@pgt-gmbh.com</font></u></a><br />\n"
+ "<br />\n"
+ "<font size=\"4\">Internet : </font><a href=\"http://www.pgt-gmbh.com/\"><u><font size=\"4\" color=\"#0000ff\">http://www.pgt-gmbh.com</font></u></a><font size=\"4\"> </font><br />\n"
+ "<br />\n"
+ "<br />\n"
+ "<font size=\"4\"> </font><a class=\"domino-attachment-link\" style=\"display: inline-block; text-align: center\" href=\"/_dv/_dv/documents_DE.nsf/0/7fadd8be280a2e34c1257dfd00307098/$FILE/Anfrage.pdf\" title=\"Anfrage.pdf\"><img src=\"/_dv/_dv/documents_DE.nsf/0/7fadd8be280a2e34c1257dfd00307098/f_Text/0.5F66?OpenElement&FieldElemFormat=gif\" width=\"32\" height=\"32\" alt=\"Anfrage.pdf\" border=\"0\" /> - Anfrage.pdf</a>";
public static void main(String[] args) {
Matcher m = P.matcher(TEXT);
if (m.find()) {
System.out.println(m.group());
}
m = P.matcher(NEWLINE_TEXT);
if (m.find()) {
System.out.println(m.group());
}
}
Output:
<a href="mailto:c.bantz@pgt-gmbh.com">... without newlines
<a class="domino-attachment-link"... with newlines
A better pattern
<a\s[^>]*?href=([^>]+)><img\s.*?src=([^ ]+)(.*?>.*?<\/a>)
The problem with HTML and regex is that the upper pattern matches only a specific situation, if some markup is between <a...> and <img...> then it would fail. Surely this could be fixed, but the expression gets more and more incomprehensible.
So: If you want to do this extraction issues for more than one link, you should switch to an HTML-Parser (although finding the best is a science of its own).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/28897927",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Can't add component to JPanel in Swing I want to add at runtime a JLabel under the purple pane which contains already some components, say under the progress bar:
Here is the structure of the elements:
And this is my code which is issued when an event occurs (it's getting there i checked with debug) :
jPanel1.add(new JLabel("Stack Overflow"));
jPanel1.revalidate();
jPanel3.revalidate();
I'm not seeing any changes whatsoever and have no clue where to go from here. When i put a
textarea in the purple pane and then call it's setText() method at the same place i try to add the JLabel component it works.
A: You need to learn more about layouts and how they work. I strongly suggest you read the entire layout manager tutorial, since understanding layouts are the solution here, and just using BorderLayout isn't the way to solve it. You'll likely want to nest layouts, perhaps using BorderLayout for the overall GUI, and having a central JPanel use BoxLayout to allow you to stack components on top of each other inside of it. Then perhaps add this JPanel to the main JPanel that uses BorderLayout in the BorderLayout.CENTER position.
A: Just a hunch, but maybe you need to call repaint() in addition to revalidate()
Java Swing revalidate() vs repaint()
| {
"language": "en",
"url": "https://stackoverflow.com/questions/11236220",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: JavaFX close dialog on thread I am trying to close JavaFX custom dialog after some job is done, but It's not closing. I have tried everything what was on web. But still no success.
I am using :
import javafx.scene.control.Dialog;
Code:
dialogProgressBar.progressIndicator().show();
Service<Void> service = new Service<Void>() {
@Override
protected Task<Void> createTask() {
return new Task<Void>() {
@Override
protected Void call() throws Exception {
//Background work
mySqlDatabaseHandler.mySQLConnection();
mySqlDatabaseHandler.executeStatement();
closeConnection();
Platform.runLater(() -> {
//FX Stuff done here
dialogProgressBar.progressIndicator().close();
});
return null;
}
};
}
};
service.start();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/50239346",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: replace XML tags value in shell script Hi I am a xml file like this.
<parameter name="END_DATE">20181031</parameter>
I want to replace this tags value to some other value I tried like this.
dt=$(awk -F '[<>]' '/_DATE/{print $3}' test.xml)
I extracted the tags value.
I have another variable value like this.
newdt=20181108
Now I need to replace this value to the extracted value.
Any help would be appreciated.
A: Though Chepner is right that awk or sed are not exact tools for xml in case you are NOT having xmlstarlet in your system then try following.
echo $newdt
20181108
awk -v dat="$newdt" 'match($0,/>[0-9]+</){$0=substr($0,1,RSTART) dat substr($0,RSTART+RLENGTH-1)} 1' Input_file
A: If sed works for you -
sed -Ei 's/( name="END_DATE")>20181031</\1>20181108</' test.xml
And xml parser is probably a better idea, though.
If you need to embed the variable -
sed -Ei "s/( name=\"END_DATE\")>20181031</\1>$newdt</" test.xml
| {
"language": "en",
"url": "https://stackoverflow.com/questions/53208735",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Is google drive api for c# thread safe? I'm using google drive API in a multi-thread C# application. I would like to know if the Google dot net client library it's thread-safe or not.
Also I would like to know what's more right:
create a singelton service, or a new service every time.
A: If you are asking if the Google .net client Library is thread safe. I am pretty sure that it is. It is noted in at least one place in the documentation that it is thread safe.
Google APIs Client Library for .NET
UserCredential is a thread-safe helper class for using an access token
to access protected resources. An access token typically expires after
1 hour, after which you will get an error if you try to use it.
A: It isn't. I've tried writing some code assuming it was, and my code would sometimes randomly crash at the "request.Execute()"s...
I tried using a mutex and so only one thread was using a singleton service at a time: that reduced the crashes but it didn't eliminate them.
Leaving the mutex in, I changed it to a singleton UserCredential and use a new service for each thread and it hasn't crashed since. (I don't know if I need the mutex anymore or not, but the google api calls aren't critical path for my application, I just needed to get the calls out of the main thread.)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/28578219",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to pass a data in WkWebView URL in swift In my project I have a dictionary. I need to pass it to a WKWebView as a post parameter. When i try to convert String to URL it returns nil value. any advice to me?
This is my Dictionary named CartDict.
{
"address_id" : "4064",
"customer_id" : "3239",
"language_id" : "1",
"products" : [
{
"option" : "",
"product_id" : "1576",
"quantity" : "2"
},
{
"option" : "",
"product_id" : "1573",
"quantity" : "1"
},
{
"option" : "",
"product_id" : "1575",
"quantity" : "1"
}
],
"set_currency" : "EUR"
}
This is my code:
let urlStr = "https://test.com/index.php?route=checkout/checkout_mobile&data=\(cartDict)"
let trimmedUrl = urlStr.trimmingCharacters(in: CharacterSet(charactersIn: "")).replacingOccurrences(of: " ", with: "%20")
let url = URL(string: trimmedUrl)
print(url)
self.webView.load(URLRequest(url: url!))
Thanks in advance.
A: Set httpBody to your data from dictionary
let trimmedUrl = urlStr.trimmingCharacters(in: CharacterSet(charactersIn: "")).replacingOccurrences(of: " ", with: "%20")
let url = URL(string: trimmedUrl)!
let dic:[String:Any] = ["address_id" : "4064", "customer_id" : "3239", "language_id" : "1", "products" : [ [ "option" : "", "product_id" : "1576", "quantity" : "2" ], [ "option" : "", "product_id" : "1573", "quantity" : "1" ], [ "option" : "", "product_id" : "1575", "quantity" : "1" ] ], "set_currency" : "EUR" ]
let data = try? JSONSerialization.data(withJSONObject: dic)
var req = URLRequest(url: url)
req.httpBody = data
self.webView.load(req)
A: Firstly you need to make sure that the url string is valid, try printing it
print(urlStr)
The post parameters are not url params usually, but http body parameters, thus need to be added to the body of the request. You need to know what format the server is expecting. Modern apis use JSON so you'd need to format your dictionary to json (however the dictionary you posted is actually not a swift dictionary, so it looks ok.).
let urlStr = "https://test.com/index.php?route=checkout/checkout_mobile"
let trimmedUrl = urlStr.trimmingCharacters(in: CharacterSet(charactersIn: "")).replacingOccurrences(of: " ", with: "%20")
let url = URL(string: trimmedUrl)
let request = URLRequest(url: url)
request.httpBody = Data(cartDict.utf8)
self.webView.load(request)
A: From the comments
when i convert this String (urlStr) to URLRequest it returns nil
If this is your question or it maybe useful for others in future.
extension URL {
public var queryParameters: [String: Any]? {
guard let components = URLComponents(url: self, resolvingAgainstBaseURL: true), let queryItems = components.queryItems else { return nil }
return queryItems.reduce(into: [String: String]()) { (result, item) in
result[item.name] = item.value
}
}
}
In your WKNavigationDelegate methods on redirection
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
guard let url = navigationAction.request.url else {
decisionHandler(.allow)
return
}
if url.absoluteString.lowercased().range(of: "redirection/url/you/expected/to/intercept") != nil {
var parameters: [String: Any]?
if let requestBody = navigationAction.request.httpBody {
//If your data is JSON
let requestJSON = try? JSONSerialization.jsonObject(with: requestBody, options: [])
if requestJSON = requestJSON as? [String: Any] {
parameters = requestJSON
}else {
//If your data is utf8 encoded string
let queryUrl = URL(string: url.absoluteString + "?" + String(decoding: requestBody, as: UTF8.self))
parameters = queryUrl?.queryParameters
}
}
//Your post payload in parameters
//Handle it the way you want.
}
decisionHandler(.allow)
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/60813521",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Count occurrences of each unique value within a column pandas I have a dataset which looks as follows:
Station
Month
Year
A
Jan
2021
A
Feb
2021
A
Jan
2021
B
Mar
2021
B
Mar
2021
C
Apr
2021
D
Feb
2021
I am looking to write some code which can identify each unique value within a row and tell me how often it occurs.
eg. For the month column the code should tell be Jan occurs twice, Feb occurs twice, Mar occurs twice and Apr occurs once. It would output similar for the Station and Year columns.
My code looks like this at present, but is not working as intended:
import pandas as pd
for col in df["Month"]:
print((df["Month"])[col].unique())
A: Try value_counts
df["Month"].value_counts()
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74171590",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Internal Server Error when submitting a page I am working a portal website. Here I have forget password page. In this forget password page will have a form with email id. When user gives his email and click on submit it will send an email.
But now actual problem is in my localhost it is working fine. But when I uploaded into the server. And when I open the page forget password and gave email id and clicked on submit then it showing internal server error as shown in the following image.
And the code I have written is
<?php
ini_set('display_errors', 1);
include 'header-employer.php';
echo "In forget password page";
?>
<script type="text/javascript">
function valid_details()
{
var con1=/^[a-zA-Z0-9\_\.]+\@[a-zA-Z\.]+\.([a-z]{2,4})$/;
if(document.getElementById('email').value=="")
{
alert("Please Enter Email Id");
document.getElementById('email').focus();
return false;
}
else if(!document.getElementById('email').value.match(con1))
{
alert("Enter Valid Email Id");
document.getElementById('email').focus();
return false;
}
if(document.getElementById('pass').value=="")
{
alert("Please Enter Password");
document.getElementById('pass').focus();
return false;
}
}
</script>
<?php
if(isset($_POST['sub']) && $_POST['sub']=="Submit")
{
echo "entered into forget password";
$email=mysql_real_escape_string(trim($_POST['email']));
echo "email in forget pwd page:".$email;
$email_fetch=$con->getdata("select * from employers where email='{$email}'");
$rows=mysql_num_rows($email_fetch);
print_r($rows);
if($rows==0)
{
echo '<script> alert("Email Id Not Registered With Us.") </script>';
}
else
{
function randomcode()
{
$chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz0123456789";
$i = 0;
$vcode = '' ;
while($i < 7)
{
$num = mt_rand(0,61);
$tmp = substr($chars, $num, 1);
$vcode = $vcode . $tmp;
$i++;
}
return $vcode;
}
$msg=randomcode();
$secure_msg=md5($msg);
echo "update employers set pass='$secure_msg' where email='{$email}'";
$update_pass=$con->setdata("update employers set pass='$secure_msg' where email='{$email}'");
$user_subject='Your New Password';
$user_message='
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta name="viewport" content="width=device-width"/>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>Job Portal</title>
<!-- <link rel="stylesheet" type="text/css" href="stylesheets/email.css"/> -->
</head>
<body bgcolor="#FFFFFF">
<table style="width:100%;" bgcolor="#999999">
<tr>
<td></td>
<td>
<div style="padding:15px;max-width:600px;margin:0 auto;display:block;">
<table style="width:100%;" bgcolor="#999999">
<tr>
<td style="padding:15px;"><img src="http://www.jobwhizz.com/images/logo.jpg"/></td>
</tr>
</table>
</div>
</td>
<td></td>
</tr>
</table>
<table style="width: 100%;">
<tr>
<td></td>
<td style="display:block!important;max-width:600px!important;margin:0 auto!important;clear:both!important;" bgcolor="#FFFFFF">
<div style="padding:15px;max-width:600px;margin:0 auto;display:block;">
<table style="width:100%;">
<tr>
<td>
<h3>Dear User,</h3>
<p>Your password was reset at <a style="color: #2BA6CB;" href=http://www.jobwhizz.com target=_blank>www.jobwhizz.com</a>
</p>
<p style="padding:15px;background-color:#ECF8FF;margin-bottom: 15px;">
New password is '.$msg.'
</p>
<table style="background-color:#ebebeb;font-size:18px;line-height:19px;font-family: Helvetica, Arial, sans-serif; font-weight:normal;" width="100%">
<tr>
<td>
<table align="left" style="width: 200px;float:left;">
<tr>
<td style="padding-left: 10px;">
<h5 class="">Connect with Us:</h5>
<p class=""><a href="#" style="padding: 3px 7px;font-size:12px;margin-bottom:10px;text-decoration:none;color: #FFF;font-weight:bold;display:block;text-align:center;background-color: #3B5998!important;">Facebook</a> <a href="#" style="padding: 3px 7px;font-size:12px;margin-bottom:10px;text-decoration:none;color: #FFF;font-weight:bold;display:block;text-align:center;background-color: #1daced!important;">Twitter</a> <a href="#" style="padding: 3px 7px;font-size:12px;margin-bottom:10px;text-decoration:none;color: #FFF;font-weight:bold;display:block;text-align:center;background-color: #DB4A39!important;">Google+</a></p>
</td>
</tr>
</table>
<table align="right" style="width: 300px;float:right;">
<tr>
<td>
<h5 class="">Contact Info:</h5>
<p>Phone: <strong>408.341.0600</strong><br/>
Email: support@jobwhizz.com</td>
</tr>
</table>
</td>
</tr>
</table>
</td>
</tr>
</table>
</div>
</td>
<td></td>
</tr>
</table>
</body>
</html>
';
echo "sending email";
$mailto_user=mail($email, $user_subject, $user_message, $headers);
//var_dump($mailto_user);
if($mailto_user)
{
echo '<script> alert("A New Password Is Sent To Your Email Id") </script>';
//echo "<script>window.location.href = 'employer-signin.php';</script>";
header('location: employer-signin.php');
}
}
}
?>
<div class="mainwallpaper">
<div class="container">
<div class="col-md-offset-1 col-md-5"><span class="spacer100"></span>
<div class="transparent panel panel-default" >
<div class="transparent panel panel-body">
<p style="align:center;font-weight:700;">Forgot Password ?</p><hr/>
<form class="form-horizontal" method="post" action="" onsubmit="return valid_details();" autocomplete="off">
<div class="form-group">
<div class="col-sm-12">
<label for="inputPassword3" class=" control-label">Your Registered Email Id</label>
<span class="spacer10"></span>
<input type="text" class="form-control" name="email" id="email" placeholder="Registered Email Id">
<span class="spacer10"></span>
<input type="submit" class="btn btn-warning" name="sub" value="Submit">
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<style>.mainwallpaper{background-image: url("http://jobwhizz.com/images/forget.jpg");
width:100%;background-size: cover;height:450px;background-position: 50% -60px;}
.layer{background-color:; width: 100%; height: 100%;}
.transparent{background:rgba(255,255,255,0.3) !important;}
</style>
<?php include 'footer.php'; ?>
Can anyone help me please...............
Thanks in advance...............!
A: Here are few things you can try.
*
*Try adding error_reporting('E_ALL'); on top of the script.
*Check your web server's configuration (htaccess, virtualhost etc).
*(more likely cause) Since, you are using mail() function, it could be causing the error. Check your server's mail configuration. More info: PHP's mail() function causes a 500 Internal Server Error only after a certain point in the code
*Compare your server's configuration with your localhost's configuration.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/35147151",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: JanusGraph + Cassandra (Generic questions) I have a few questions regarding the integration of the two tools. Not technical questions and how to setup( i will have my fun with that later ) but more on the course of the project and the direction, seeing that JanusGraph is still very young.
I am starting a new project and already decided to use Cassandra for storage and using a graph on top sounds very appealing to me.
A couple of things that i would like to know in advance before i take that road.
*
*JanusGraph is very young and it picks up from where Titan left about a year or so ago. There is gap there but the fact that is part of the Linux Foundation and all the big players are going to support it sounds promising. Is it safe to assume at this point that JanusGraph is here to stay? Would it be safe to depend on Janus as a startup project? And follow development of course and be up to date as much as possible.
*Cassandra. Titan/JanusGraph integrates with Cassandra 2.1.9 using the thrift api which will be deprecated eventually in Cassandra 4. I know that work is being done at the moment to make janus work with Cassandra 3 and eventually work with CQL as well. Is it safe to start with existing janus and Cassandra 2.1.9 and deal with the migration later on? Will it be a huge task for a startup to handle?
*Production ready JanusGraph.(This question relates to any kind of software in it's early stages and whether it's safe for a start up to use). As i understand it, it will take some time for JanusGraph to be production ready and catch up with the rest of the tools it integrates with( although work is being done as we speak:)). Again would it be safe to start using Janus at this point and follow development and finally migrate to a production ready version? What is the overall roadmap for JanusGraph?
My concern in general is whether the combination of the tools is a safe choice for a start up. The whole stack is already new to us and we are excited to try and learn but we will hit a migration period pretty quickly. Is it something that you would do/recommend? Is it a suicide?
Please share your thoughts and keep in mind that it doesn't have to be about the stack i am talking about. It could be any startup company dealing with any kind of software in its early stages.
Cheers
A: Full disclosure, I'm a developer for JanusGraph on Compose.
*
*It's as safe as any other OSS software project with a large amount of backers. Everyone could jump on some new toy tomorrow, but I doubt it. Companies are putting money into it and the development community is very active.
*There is a CQL backend for Janus that's compatible with the Thrift data model. Migration to CQL should be simple and pretty painless when 0.2.0 is released.
*I know there are already people using Titan for production applications. With JanusGraph being forked from Titan, I think it's pretty reasonable to start in with JanusGraph from everything I've seen. As far as a roadmap, I'd check out the JanusGraph mailing list (dev/users) and see what's going on and what's being talked about.
A: Disclosure: I am one of the co-founders of the JanusGraph project; I am also seeking out and adding production users to our GitHub repo and website, so I may be slightly biased. :)
Regarding your questions:
*
*Is it safe to use?
The project is young, but it is built on a foundation of Titan, a very popular graph database that's been around since 2012 and has already been running in production. We have contributors from a number of well-known companies, and several companies are building their business-critical applications directly on JanusGraph, e.g.,
*
*GRAKN.AI is building their knowledge graph on JanusGraph
*IBM's Compose.io has built a managed JanusGraph service
*Uber is already running JanusGraph in production (having previously run Titan)
*several other companies run JanusGraph as a core part of their production environment
We are also starting to identify companies who will provide consulting services around JanusGraph in case someone needs production-level support for their own self-managed deployments.
So as you can see, there is significant interest in and support for this project.
*Cassandra upgrade
@pantalohnes answered this question; I won't repeat it here.
*Production readiness
As I linked above (GitHub repo and website), we already have production users of JanusGraph which you can find there. Those are just the companies that are publicly willing to lend their name/logo to the project; I'm sure there are more. Also, Titan has been running in many production environments for several years; JanusGraph is a more up-to-date version of Titan, despite the low version number.
I am also speaking with other companies who are planning to migrate to JanusGraph soon; look for announcements via the @JanusGraph Twitter handle to learn about more production deployments.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/44805949",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: write! macro does not compile in a separate method when taking reference This is my code:
use std::fs::File;
use std::io::Write;
fn main() {
let f = File::create("").unwrap();
// Compiles
write!(&f, "hi").unwrap();
write_hi(&f);
}
fn write_hi(f: &File) {
// Doesn't compile (cannot borrow `f` as mutable, as it is not declared as mutable)
write!(f, "hi").unwrap();
}
When I have this line without the file being a parameter value, it compiles:
write!(&f, "hi").unwrap();
However, when the f is a parameter value, I get a compile error. It works when I make some mutability changes in the declaration of the f variable and method parameter, but isn't that odd?
Why doesn't the write! macro work on a non-mutable reference when it is used as a parameter value, like it does compile when the referencing variable is declared in the same method?
A: The write! macro internally uses write_fmt which takes a &mut self. Your write!(&f, ...) is actually the odd one since the object being written to should be mutable, however you have an immutable File.
How does this work then? Write has an additional implementation for &Files. So you can write to a mutable reference to an immutable file. I'm not positive, but I believe this was added as a deliberate workaround to allow Files to be written to immutably.
It works in the first case because &f creates a temporary, which can be used mutably. The reason why write!(f, ... (with f being &File) doesn't work is because f is a variable that write_fmt wants to modify, so it needs to be mut.
fn write_hi(mut f: &File) {
// ^^^
write!(f, "hi").unwrap();
}
See also:
*
*Why is it possible to implement Read on an immutable reference to File?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/65135562",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Use SnapHelper to Scroll to a Child view in a recyclerview item In my recyclerview onCreateViewholder method I create a dynamic which would have unspecified number of text views inside a linear layout
if (sessionManager.getBookScrolOrientation() == AppConstents.HORIZONTAL) {
LinearLayout linearLayout = new LinearLayout(context);
ViewGroup.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT , ViewGroup.LayoutParams.MATCH_PARENT);
linearLayout.setLayoutParams(layoutParams);
linearLayout.setOrientation(LinearLayout.HORIZONTAL);
Spannable spannable = getVerseSpanableHorizontal(pidreference.get(position) , cidreference.get(position));
Pagination pagination = new Pagination(spannable,
pageWidth,
pageHight,
textPaint,
lineSpacingMultiplier,
lineSpacingExtra,
isTextPaddingIncluded);
List<CharSequence> list = pagination.getPages();
for (CharSequence charSequence : list){
TextView tv = new TextView(linearLayout.getContext());
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(Tools.getScreenWidth() , ViewGroup.LayoutParams.MATCH_PARENT);
tv.setLayoutParams(params);
tv.setText(charSequence);
linearLayout.addView(tv);
}
MainViewHolder viewHolder = new MainViewHolder(linearLayout);
return viewHolder;
}
When i use SnapHelper with this recyclerview it scrolls to the center of linear layout not the next textview. How can i make it scroll to the next textview inside the linearlayout?
A: If I understand correctly, the problem is that SnapHelper snaps the center of the current view to the center of the recycler. As the docs say:
The implementation will snap the center of the target child view to the center of the attached RecyclerView.
If you want the the current view to snap to the start of the recycler use a libraray such as this one. Import it with gradle and activate it like this:
GravitySnapHelper(Gravity.START).attachToRecyclerView(recyclerview);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/48034912",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to specify which app to make changes with heroku? Hello I have multiple heroku apps. Whenever I I run this command heroku buildpacks:set heroku/nodejs it applies it to the wrong heroku app. How can I specify which app to make this change to. It seems like whenever I run any command with heroku it does it to a different app.
A: Most Heroku CLI commands support the -a parameter to specify the application, in this case:
heroku buildpacks:set heroku/nodejs -a <app name>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66414907",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Functional Swift returns error Why does r1 work but r2 throw a compilation error (Cannot invoke '+' with an argument list of type '(NSArray, [Int])')?
func reduce<T1, T2>(input:[T1], initialResult: T2, f:(T2, T1) -> T2) -> T2 {
var result = initialResult
for x in input {
result = f(result, x)
}
return result
}
let array2D = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
let r1 = reduce(array2D, []){result, x in
result + x}
let r2 = reduce(array2D, []){result, x in
return result + x}
A: If you specify the return type, it silences this error, e.g.:
let r3 = reduce(array2D, []){result, x -> [Int] in
return result + x}
If you specify that that initial empty array is an Int array, the error is silenced:
let r4 = reduce(array2D, [Int]()){result, x in
return result + x}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/27741954",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: webkitfullscreenchange event not firing, when the element contains Flash I have an element that contains a video player: that video player can either be Flash or HTML5 based. I want to be able to make that element fullscreen (I know, only works in webkit at the moment) and run some resizing scripts when it happens.
Here is how I do it:
this.getEl('.fullscreen').bind('click', $.proxy(function() {
this.getEl('#tpPlayer')[0].webkitRequestFullScreen();
}, this));
And the event listener:
this.getEl('#tpPlayer').bind('webkitfullscreenchange', function() {
console.log('fullscreen change');
$(this).toggleClass('tpPlayer tpPlayerFullScreen');
});
When #tpPlayer contains a <video> element, everything works fine: the element goes fullscreen, the event fires, the message is logged and the classes are toggled. However, when #tpPlayer contains a Flash <object>, the element goes fullscreen fine, but no event is fired (so the callback does not run either).
Why is this happening and how to avoid this?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/8160747",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Removing Uploaded Files from Google when item Expires We're using the Google CSE (Custom Search Engine) paid service to index content on our website. The site is built of mostly PHP pages that are assembled with include files, but there are some dynamic pages that pull info from a database into a single page template (new releases for example). The issue we have is I can set an expire date on the content in the database so say "id=2" will bring up a "This content is expired" notice. However, if ID 2 had an uploaded PDF attached to it, the PDF file remains in the search index.
I know I could write a cleanup script and have cron run it that looks at the db, finds expired content, checks to see if any uploaded files were attached and either renames or removes them, but there has to be a better solution (I hope).
Please let me know if you have encountered this in the past, and what you suggest.
Thanks,
D.
A: There's unfortunately no way to give you a straight answer at this time: we have no knowledge of how your PDFs are "attached" to your pages or how your DB is structured.
The best solution would be to create a robots.txt file that blocks the URLs for the particular PDF files that you want to remove. Google will drop them from the index on its next pass (usually in about an hour).
http://www.robotstxt.org/
A: What we ended up doing was tying a check script to the upload script that once it completed the current upload, old files were "unlinked" and the DB records were deleted.
For us, this works because it's kind of an "add one/remove one" situation where we want a set number of of items to appear in a rolling order.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/2304959",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: bxslider bx-viewport height is 0 if shown later I have an angular application in which i am using bxslider plugin.
I have created bxslider directive to call the plugin and everything was working fine till i extended the functionality.
This is the code for creating directive
angular.module('sbAdminApp')
.directive('bxSlider', function(){
return{
restrict: "A",
require: "ngModel",
link: function(scope, element, attrs, ctrl){
element.ready(function(){
$($(element[0])).bxSlider({
controls:false,
pager:true,
maxSlides: 1,
minSlides:1
});
})
}
}
})
This is the html
<div class="banner_section" ng-model="bannerSlider" bx-slider>
<div class="slide" ng-repeat="banner in mobileBanner track by $index">
<img ng-src="images/{{banner}}">
</div>
</div>
Controller with values in array
angular.module('sbAdminApp')
.controller('mobileViewCtrl', function($scope){
$scope.mobileBanner = ['banner_small.png', 'banner_small.png', 'banner_small.png'];
})
But actually that slider div is hidden and i am showing it with ng-show on click of anchor because of which the height of bxslider is 0 i need to do slight resize of window to let bxslider get the required height.
I want bxslider should come correct initially when i am showing div.
A: Thanks for all you support mates. I found the answer.
I was using ng-show to manage when i need to show the slider because of which initially the slider was hidden and giving problem.
But now i switched to ng-if which is not just hiding the slider or completely removing it from DOM and insert it when i need so that bxslider is initialised only when shown and working completely fine.
Found the difference here : what is the difference between ng-if and ng-show/ng-hide
A: The problem is that - Slides/images must be visible before slider gets initiate.
In your case possible solutions are -
Either:
*
*You can reload slider after ng-show animation complete
*Slider can be initiate after ng-show animation complete
To reload bx slider doc -
http://bxslider.com/examples/reload-slider
http://bxslider.com/examples/reload-slider-settings
Sample code:
var slider = $('.bxslider').bxSlider({
mode: 'horizontal'
});
//Inside ng-show callback
slider.reloadSlider();
Trigger event when ng-show is complete
Call a function when ng-show is triggered?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/38918259",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: ignore "channel_layout" when working with multichannel audio in ffmpeg I'm working with multichannel audio files (higher-order ambisonics), that typically have at least 16 channels.
Sometimes I'm only interested in a subset of the audiochannels (e.g. the first 25 channels of a file that contains even more channels).
For this I have a script like the following, that takes a multichannel input file, an output file and the number of channels I want to extract:
#!/bin/sh
infile=$1
outfile=$2
channels=$3
channelmap=$(seq -s"|" 0 $((channels-1)))
ffmpeg -y -hide_banner \
-i "${infile}" \
-filter_complex "[0:a]channelmap=${channelmap}" \
-c:a libopus -mapping_family 255 -b:a 160k -sample_fmt s16 -vn -f webm -dash 1 \
"${outfile}"
The actual channel extraction is done via the channelmap filter, that is invoked with something like -filter:complex "[0:a]channelmap=0|1|2|3"
This works great with 1,2,4 or 16 channels.
However, it fails with 9 channels, and 25 and 17 (and generally anything with >>16 channels).
The error I get is:
$ ffmpeg -y -hide_banner -i input.wav -filter_complex "[0:a]channelmap=0|1|2|3|4|5|6|7|8|9|10|11|12|13|14|15|16" -c:a libopus -mapping_family 255 -b:a 160k -sample_fmt s16 -vn -f webm -dash 1 output.webm
Input #0, wav, from 'input.wav':
Duration: 00:00:09.99, bitrate: 17649 kb/s
Stream #0:0: Audio: pcm_s16le ([1][0][0][0] / 0x0001), 44100 Hz, 25 channels, s16, 17640 kb/s
[Parsed_channelmap_0 @ 0x5568874ffbc0] Output channel layout is not set and cannot be guessed from the maps.
[AVFilterGraph @ 0x5568874fff40] Error initializing filter 'channelmap' with args '0|1|2|3|4|5|6|7|8|9|10|11|12|13|14|15|16'
Error initializing complex filters.
Invalid argument
So ffmpeg cannot guess the channel layout for a 17 channel file.
ffmpeg -layouts only lists channel layouts with 1,2,3,4,5,6,7,8 & 16.
However, I really don't care about the channel layout. The entire concept of "channel layout" is centered around the idea, that each audio channel should go to a different speaker.
But my audio channels are not speaker feeds at all.
So I tried providing explicit channel layouts, with something like -filter_complex "[0:a]channelmap=map=0|1|2|3|4|5|6|7|8|9|10|11|12|13|14|15|16:channel_layout=unknown", but this results in an error when parsing the channel layout:
$ ffmpeg -y -hide_banner -i input.wav -filter_complex "[0:a]channelmap=map=0|1|2|3|4|5|6|7|8|9|10|11|12|13|14|15|16:channel_layout=unknown" -c:a libopus -mapping_family 255 -b:a 160k -sample_fmt s16 -vn -f webm -dash 1 output.webm
Input #0, wav, from 'input.wav':
Duration: 00:00:09.99, bitrate: 17649 kb/s
Stream #0:0: Audio: pcm_s16le ([1][0][0][0] / 0x0001), 44100 Hz, 25 channels, s16, 17640 kb/s
[Parsed_channelmap_0 @ 0x55b60492bf80] Error parsing channel layout: 'unknown'.
[AVFilterGraph @ 0x55b604916d00] Error initializing filter 'channelmap' with args 'map=0|1|2|3|4|5|6|7|8|9|10|11|12|13|14|15|16:channel_layout=unknown'
Error initializing complex filters.
Invalid argument
I also tried values like any, all, none, 0x0 and 0xFF with the same result.
I tried using mono (as the channels are kind-of independent), but ffmpeg is trying to be clever and tells me that a mono layout must not have 17 channels.
I know that ffmpeg can handle multi-channel files without a layout.
E.g. converting a 25-channel file without the -filter_complex "..." works without problems, and ffprobe gives me an unknown channel layout.
So: how do I tell ffmpeg to just not care about the channel_layout when creating an output file that only contains a subset of the input channels?
A: Based on Audio Channel Manipulation you could try splitting into n separate streams the amerge them back together:
-filter_complex "\
[0:a]pan=mono|c0=c0[a0];\
[0:a]pan=mono|c0=c1[a1];\
[0:a]pan=mono|c0=c2[a2];\
[0:a]pan=mono|c0=c3[a3];\
[0:a]pan=mono|c0=c4[a4];\
[0:a]pan=mono|c0=c5[a5];\
[0:a]pan=mono|c0=c6[a6];\
[0:a]pan=mono|c0=c7[a7];\
[0:a]pan=mono|c0=c8[a8];\
[0:a]pan=mono|c0=c9[a9];\
[0:a]pan=mono|c0=c10[a10];\
[0:a]pan=mono|c0=c11[a11];\
[0:a]pan=mono|c0=c12[a12];\
[0:a]pan=mono|c0=c13[a13];\
[0:a]pan=mono|c0=c14[a14];\
[0:a]pan=mono|c0=c15[a15];\
[0:a]pan=mono|c0=c16[a16];\
[a0][a1][a2][a3][a4][a5][a6][a7][a8][a9][a10][a11][a12][a13][a14][a15][a16]amerge=inputs=17"
A: Building on the answer from @aergistal, and working with an mxf file with 10 audio streams, I had to modify the filter in order to specify the input to every pan filter. Working with "pan=mono" it only uses one channel identified as c0
-filter_complex "\
[0:a:0]pan=mono|c0=c0[a0];\
[0:a:1]pan=mono|c0=c0[a1];\
[0:a:2]pan=mono|c0=c0[a2];\
[0:a:3]pan=mono|c0=c0[a3];\
[0:a:4]pan=mono|c0=c0[a4];\
[0:a:5]pan=mono|c0=c0[a5];\
[0:a:6]pan=mono|c0=c0[a6];\
[0:a:7]pan=mono|c0=c0[a7];\
[0:a:8]pan=mono|c0=c0[a8];\
[0:a:9]pan=mono|c0=c0[a9];\
[a0][a1][a2][a3][a4][a5][a6][a7][a8][a9]amerge=inputs=10"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/65109784",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: RecyclerView RecyclerViewDataObserver was not registered Im working with RecyclerView, SyncAdapter and greenrobot eventbus
When my SyncAdapter finished syincing i post a message into the message bus:
EventBus.getDefault().post(new EventMessagesRefreshed());
In my target class i do the following:
@Subscribe
public void onEvent(EventMessagesRefreshed event) {
this.init();
}
And in my init() i create the adapter for the recyclerview and set it:
public void init() {
if(this.listRowParent != null) {
this.adapter = new FragmentMessagesListAdapter(this.getActivity(), SingletonMessages.getInstance().getMessages());
this.listRowParent.setAdapter(this.adapter);
}
}
// listRowParent is my RecyclerView!
The fragment which receives the event is inside a of a tab view. So there are multiple tabs and sometimes ofcourse the SyncAdapter posts the EventMessagesRefreshed into the message bus when im not in the correct target tab but since it is registered it tries to call init() and to create the adapter and set it to the RecyclerView. If that happens i get the following error:
Could not dispatch event: class EventMessagesRefreshed to subscribing class class FragmentMessagesList
java.lang.IllegalStateException: Observer android.support.v7.widget.RecyclerView$RecyclerViewDataObserver@2c3421a7 was not registered.
at android.database.Observable.unregisterObserver(Observable.java:69)
at android.support.v7.widget.RecyclerView$Adapter.unregisterAdapterDataObserver(RecyclerView.java:5688)
at android.support.v7.widget.RecyclerView.setAdapterInternal(RecyclerView.java:873)
at android.support.v7.widget.RecyclerView.setAdapter(RecyclerView.java:857)
So i need to init() my adapter and RecyclerView only when the RecyclerViewDataObserver is registered.
How can i do that?
A: You need to register Data observer to listen to data changes from sync adapter.
mRecyclerViewAdapter.registerAdapterDataObserver(myObserver);
RecyclerView.AdapterDataObserver are a result of which notify methods you call. So for instance if you call notifyItemInserted() after you add an item to your adapter then onItemRangeInserted() will get called
A more detailed example
protected void setupRecyclerView() {
mAdapter = new MyAdapter(mItemList);
mAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
@Override
public void onChanged() {
super.onChanged();
checkAdapterIsEmpty();
}
});
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setAdapter(mAdapter);
checkAdapterIsEmpty();
}`
The adapter may publish a variety of events describing specific
changes. Not all adapters may support all change types and some may
fall back to a generic "something changed" event if more specific data
is not available.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/35996703",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Send photo/image to application Does anyone know if it's possible to get your application on this screen?
Or is this ability only able for Apple?
I did some searching but couldn't find anything relevant, I wasn't exactly sure what to even call this screen.
I'm new so I can't post images...but basically on an iPhone 5, open up a picture. Click the icon that has a rectangle with an arrow jumping out of it. The menu that pop's up is the one I'm talking about.
A: Unfortunately, for no good reason, Apple doesn't list any 3rd party apps in the Photos app even for apps that register the fact that they can open such files.
If you want this feature, file an enhancement request using Apple's bug reporting tool.
A: To directly answer your question, no there is no way to get your application on that list.
For some reason Apple handles images with their own activity sheet.
To get images off the camera roll, look into UIImagePickerController
| {
"language": "en",
"url": "https://stackoverflow.com/questions/13829477",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: is there exist some alternative of Enum.GetName(Type, Object) method in Swift? in c# is possible to get enum name of any type with method
Enum.GetName (Type, Object)
is there possible to do the same in Swift?
As example I have some enum that must have Int raw value, but also I need it's own name.
how to do this in Swift 3?
A: To get an enumeration case's name as a String, you can use init(describing:) on String:
enum Foo: Int {
case A
case B
case C
}
let s = String(describing: Foo.A)
print(s) // "A"
You can bake this into the enum:
enum Foo: Int {
case A
case B
case C
var asString: String { return String(describing: self) }
}
let s = Foo.A.asString
print(s) // "A"
A: Pre-requisite: you have an enumeration type with an underlying RawValue; i.e., an enumeration conforming to RawRepresentable.
The C# method Enum.GetName Method (Type, Object) is described as follows:
Enum.GetName Method (Type, Object)
public static string GetName(
Type enumType,
object value
)
Parameters
enumType
*
*Type: System.Type
*An enumeration type.
value
*
*Type: System.Object
*The value of a particular enumerated constant in terms of its underlying type.
Return Value
- Type: System.String
- A string containing the name of the enumerated constant in enumType whose value is value; or null if no such constant is
found.
"Translated" into Swift, this method takes an enum type as first argument, and a value of the underlying type of the enum as its second one; where the latter would (for the pre-requisites of RawRepresentable conformance) translate into a value of the RawValue type of the enum in Swift.
Finally, the return type System.String (with possible null return) would translate to an optional String return type in Swift (String?).
Knitting these observations together, you could implement your similar getName method (for finding String representation of your cases represented as YourEnum.RawValue instances at runtime) by combining the init?(rawValue:) blueprinted in RawRepresentable with the init(describing:) initializer of String:
func getName<T: RawRepresentable>(_ _: T.Type, rawValue: T.RawValue) -> String? {
if let enumCase = T(rawValue: rawValue) {
return String(describing: enumCase)
}
return nil
}
/* example setup */
enum Rank: Int {
case n2 = 2,n3,n4,n5,n6,n7,n8,n9,n10,J,Q,K,A
}
/* example usage */
let someRawValue = 7
if let caseName = getName(Rank.self, rawValue: someRawValue) {
print(caseName) // n7
}
This is contrived and coerced "translation" however, as Swift enum:s are quite different (and more powerful) than those of C#. You would generally have an actual instance instance of the enum (e.g. Rank.n7) rather than one of its RawValue (e.g. 7), in which case you could simply use the init(describing:) initializer of String directly as described in the answer of @AlexanderMomchliov.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40411688",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Integrating existing crystal report C# I externally created a Crystal Report that I now want to integrate into my C# application using Visual Studio. I added a new item(Crystal Report template) to my project and chose the "From an Existing Report" radio button. I then entered the path of where my report exists. The report then shows up, and the data appears when I click on the Main Report Preview button.
The report has a static parameter that I need to populate before displaying the report.
Being new to C# I am unsure how to
*
*Populate the parameter
*Cause the Report to appear
I did search for how to populate the parameter and this is the code I'm using.
CrystalReport1 g3 = new CrystalReport1();
g3.SetParameterValue("SupplierName", SupplierID);
g3.Refresh();
I don't get an error, but my report isn't showing up, so I must be doing something wrong.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/35002318",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: C++ Remove Evenly numbered words from a string having some issues with implementing the logic for one homework problem. The platform I am using currently is Visual Studio 2013 and am a beginner. We are using the terminal (command prompt) built in with the application to get the input and output. We are currently using "CIN" and "COUT". The problem is as follows:
"Write a program that asks the user for a sentence and then strips out every even-numbered word. For example: "All The Presidents Men" would become "All Presidents". Return the modified sentence to main() function using an output parameter and then display both the original and modified sentences".
I've been trying to apply this with logic that puts each word into an array/vector, and removes each word with an index of an even number. I have yet to successfully accomplish this and am seeking some assistance from you experts!
Thank you much.
A: Live Demo
std::string line;
// get input from cin stream
if (std::getline(cin, line)) // check for success
{
std::vector<std::string> words;
std::string word;
// The simplest way to split our line with a ' ' delimiter is using istreamstring + getline
std::istringstream stream;
stream.str(line);
// Split line into words and insert them into our vector "words"
while (std::getline(stream, word, ' '))
words.push_back(word);
if (words.size() % 2 != 0) // if word count is not even, print error.
std::cout << "Word count not even " << words.size() << " for string: " << line;
else
{
//Remove the last word from the vector to make it odd
words.pop_back();
std::cout << "Original: " << line << endl;
std::cout << "New:";
for (std::string& w : words)
cout << " " << w;
}
}
A: You could write something like this
int count = -1;
for (auto it =input.begin();it!=input.end();){
if(*it==' '){
count++;it++;
if (count%2==0){
while (it != input.end()){
if (*it==' ')break;
it=input.erase (it);
}
}else it++;
}else it++;
}`
| {
"language": "en",
"url": "https://stackoverflow.com/questions/35712597",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Generic Repository should use Unit of Work or DbContext directly
*
*When I use Generic Repository with Entity Framework, do I need to use Unit of Work because to my knowledge UOW coordinate between multiple repositories. Or let Generic Repository work directly on the DbContext because UOW is not needed.
*Which is best practice : use generic repository or implement repository class for each entity type.
A: I don't know which generic repository you are refering to, but here is my experience with A generic repository.
In general, a unit of work or repository is not needed with EntityFramework. EntityFramework does it all.
However, in my first EF project I found myself creating a factory class that handed out and saved all entities. The class was doing that without doing the complete work of a unit of work, nor providing a standardized interface like a repository does. The huge class was in need of some structure. So, my personal advice is against one big repository for all entities, this repository will grow and will be increasingly difficult to maintain. If you think of such a class you better use EF as it is.
In the second project I use a UnitOfWork and generic repository. This suits my purposes much better. One unit of work to do the save operation, saving all changes in one save operation and the same interface for all repositories. Two classes of which I only have to change the unit of work to accommodate a new entity. The unit of work also hides the use of the dbContext which to my opinion causes ugly code.
I do not use a fancy unitofwork or generic repository (I found mine at: http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application), just enough to have some guidance in implementation.
I agree with Gert in his immediate reply: it is all about personal preference.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/14179719",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Wait function return value I have the following program in my book which I tried to run:
int i;
void *xpto(void *ptr) {
printf ("xpto: beggining\n");
for (; i<5; i++)
sleep(1);
printf ("xpto: end i=%d\n", i);
exit(i);
}
int main(int argc, const char * argv[]){
int a, b, c;
i = 0;
printf ("before fork\n");
a = fork();
if (a == 0) {
printf ("before calling xpto\n");
xpto(NULL);
exit (EXIT_SUCCESS);
}
else if (a > 0) {
b = wait(&c);
printf ("after wait (%d, %d)\n",
b, WEXITSTATUS(c));
exit (EXIT_SUCCESS);
}}
This is the output:
before fork
before calling xpto
xpto: beggining
xpto: end i=5
after wait (-1, 0)
Program ended with exit code: 0
In the parent process, shouldn't wait(&c) return the child process id, instead of returning -1?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40265530",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Oauth2 and YouTube - what am I doing wrong? I've been working on this unsuccessfully for a long time now. The YouTube developer examples seem straightforward enough, but I always meet the same two errors:
Access is Denied (when running on IIS)
Or
redirect_uri_mismatch (When running in Visual Studio)
This is the code that always fails for me:
using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
{
credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
// This OAuth 2.0 access scope allows an application to upload files to the
// authenticated user's YouTube channel, but doesn't allow other types of access.
new[] { YouTubeService.Scope.YoutubeUpload },
"user",
CancellationToken.None
);
}
I have:
- Updated the clients_secret and used it with the Javascript version, so I'm fairly sure that isn't the issue
- Tried to create a custom FileDataStore to add as another parameter
Here is more detail to the Access Denied error I get when debugging. It appears as soon as I get to the "credential" line.
at Microsoft.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at Microsoft.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccess(Task task)
at Google.Apis.Auth.OAuth2.GoogleWebAuthorizationBroker.d__1.MoveNext() in c:\ApiaryDotnet\default\Src\GoogleApis.Auth.DotNet4\OAuth2\GoogleWebAuthorizationBroker.cs:line 59
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at _Default.d__1.MoveNext() in c:\Users\Michael\documents\visual studio 2015\websites\website1\Default.aspx.cs:line 46
And this is what shows up in the properties for the credential right before it errors out:
ReadTimeout = 'stream.ReadTimeout' threw an exception of type 'System.InvalidOperationException'
WriteTimeout = 'stream.WriteTimeout' threw an exception of type 'System.InvalidOperationException' int {System.InvalidOperationException}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34212748",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to put constraints on HTML form inputs?
I have a form that looks like this.
What I want to do is, I want to make sure that Minimum Age < Maximum Age
and Minimum Skill Level < Maximum Skill Level
What is a way to put constraints on the inputs?
HTML
{% extends "template.html" %}
{% set active_page = "events" %}
{% block content %}
<div class="jumbo">
<h2>EVENTS PAGE</h2>
<br/>
<p>Click <a href="/welcome">here</a> to go to the welcome page</p>
</div>
<form action = "/events_success" method=post>
Event Name:<br>
<input type="text" name="eventname" required="">
<br>
Sports:<br>
<select name="sports">
{% for item in sports_data %}
<option value="{{ item[0] }}">{{ item[0] }}</option>
{% endfor %}
</select>
<br>
Location:<br>
<select name="location">
{% for item in loc_data %}
<option value="{{ item[0] }}">{{ item[0] }}</option>
{% endfor %}
</select>
<br>
Time:<br>
<input type="datetime-local" name="time" required>
<br>
Number of Players:<br>
<input type="text" name="numplayers" required>
<br>
Minimum Age:<br>
<input type="text" name="minage" required>
<br>
Maximum Age:<br>
<input type="text" name="maxage" required>
<br>
Minimum Skill Level:<br>
<input type = "radio" name = "minskill" value = "1" required> 1
<input type = "radio" name = "minskill" value = "2"> 2
<input type = "radio" name = "minskill" value = "3"> 3
<input type = "radio" name = "minskill" value = "4"> 4
<input type = "radio" name = "minskill" value = "5"> 5
<br>
Maximum Skill Level:<br>
<input type = "radio" name = "maxskill" value = "1" required> 1
<input type = "radio" name = "maxskill" value = "2"> 2
<input type = "radio" name = "maxskill" value = "3"> 3
<input type = "radio" name = "maxskill" value = "4"> 4
<input type = "radio" name = "maxskill" value = "5"> 5
<br>
<br>
Creator: {{ session['username'] }}<br>
<input type="submit" value="Send">
</form>
{% endblock %}
A: You can just try some javaScript to prevent the form submission if those fields fails to fulfill that condition. Please check my demo.
**Note: It's just a demo. That's why didn't put any authentication.
window.onload = function() {
let submit = document.querySelector("#submit");
function validateAge(minAge, maxAge) {
let min = parseInt(minAge, 10);
let max = parseInt(maxAge, 10);
return min >= max ? false : true;
}
function validateSkill(minSkill, maxSkill) {
let min = parseInt(minSkill, 10);
let max = parseInt(maxSkill, 10);
return min >= max ? false : true;
}
submit.onclick = function() {
let minAge = document.querySelector("#minage").value;
let maxAge = document.querySelector("#maxage").value;
let radios = document.querySelectorAll('input[type="radio"]:checked');
let minSkill = radios[0].value;
let maxSkill = radios[1].value;
if(validateAge(minAge, maxAge) && validateSkill(minSkill, maxSkill))
return true;
else {
alert("Invalid data");
return false;
}
}
}
<form id="myForm" action = "/events_success" method=post >
Minimum Age:<br>
<input type="text" name="minage" id="minage" required>
<br>
Maximum Age:<br>
<input type="text" name="maxage" id="maxage" required>
<br>
Minimum Skill Level:<br>
<input type = "radio" name = "minskill" value = "1" required> 1
<input type = "radio" name = "minskill" value = "2"> 2
<input type = "radio" name = "minskill" value = "3"> 3
<input type = "radio" name = "minskill" value = "4"> 4
<input type = "radio" name = "minskill" value = "5"> 5
<br>
Maximum Skill Level:<br>
<input type = "radio" name = "maxskill" value = "1" required> 1
<input type = "radio" name = "maxskill" value = "2"> 2
<input type = "radio" name = "maxskill" value = "3"> 3
<input type = "radio" name = "maxskill" value = "4"> 4
<input type = "radio" name = "maxskill" value = "5"> 5
<br>
<br>
<input type="submit" value="Send" id="submit">
</form>
A: You can use some common PHP validation techniques. These are more beneficial as less risky to injection and other exploits.
PHP:
if (empty($_POST["code"])) {
$errcode = "Verify that you're human";
} else {
$code = test_input($_POST["code"]);
if (!$_POST['code'] < $string) {
$errcode = "Make code greater than string";
}
}
HTML:
<p><label for="code">Scrambled code: </label><input type="text" name="code" id="code" /><span class="error"> * <?php echo $errcode;?></span></p>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/49834858",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: CouchDB backup into S3 in json format I am checking ways to back up CouchDB records for all databases. The docs suggest to either use replication to a new CouchDB instance or simply copy the .couch files. But .couch files cannot be read by a text editor and we want to export records to json format and put it to S3.
I found curl can be used to retrieve data in json
curl -X GET http://127.0.0.1:5984/[mydatabase]/_all_docs?include_docs=true > /Users/[username]/Desktop/db.json
Is there a way to
*
*Split it into json files of say 10,000 records each so that if the DB is huge and there's a failure at Y record I can resume it from the batch that includes Y
*Run the _all_docs on all databases that exist instead of running it individually for each database?
If there's an alternative to curl I'd be happy to try use that as well
| {
"language": "en",
"url": "https://stackoverflow.com/questions/72387645",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to Correctly Cancel a TPL Task with Continuation I have a long running operation which I am putting on a background thread using TPL. What I have currently works but I am confused over where I should be handling my AggregateException during a cancellation request.
In a button click event I start my process:
private void button1_Click(object sender, EventArgs e)
{
Utils.ShowWaitCursor();
buttonCancel.Enabled = buttonCancel.Visible = true;
try
{
// Thread cancellation.
cancelSource = new CancellationTokenSource();
token = cancelSource.Token;
// Get the database names.
string strDbA = textBox1.Text;
string strDbB = textBox2.Text;
// Start duplication on seperate thread.
asyncDupSqlProcs =
new Task<bool>(state =>
UtilsDB.DuplicateSqlProcsFrom(token, mainForm.mainConnection, strDbA, strDbB),
"Duplicating SQL Proceedures");
asyncDupSqlProcs.Start();
//TaskScheduler uiThread = TaskScheduler.FromCurrentSynchronizationContext();
asyncDupSqlProcs.ContinueWith(task =>
{
switch (task.Status)
{
// Handle any exceptions to prevent UnobservedTaskException.
case TaskStatus.Faulted:
Utils.ShowDefaultCursor();
break;
case TaskStatus.RanToCompletion:
if (asyncDupSqlProcs.Result)
{
Utils.ShowDefaultCursor();
Utils.InfoMsg(String.Format(
"SQL stored procedures and functions successfully copied from '{0}' to '{1}'.",
strDbA, strDbB));
}
break;
case TaskStatus.Canceled:
Utils.ShowDefaultCursor();
Utils.InfoMsg("Copy cancelled at users request.");
break;
default:
Utils.ShowDefaultCursor();
break;
}
}, TaskScheduler.FromCurrentSynchronizationContext()); // Or uiThread.
return;
}
catch (Exception)
{
// Do stuff...
}
}
In the method DuplicateSqlProcsFrom(CancellationToken _token, SqlConnection masterConn, string _strDatabaseA, string _strDatabaseB, bool _bCopyStoredProcs = true, bool _bCopyFuncs = true) I have
DuplicateSqlProcsFrom(CancellationToken _token, SqlConnection masterConn, string _strDatabaseA, string _strDatabaseB, bool _bCopyStoredProcs = true, bool _bCopyFuncs = true)
{
try
{
for (int i = 0; i < someSmallInt; i++)
{
for (int j = 0; j < someBigInt; j++)
{
// Some cool stuff...
}
if (_token.IsCancellationRequested)
_token.ThrowIfCancellationRequested();
}
}
catch (AggregateException aggEx)
{
if (aggEx.InnerException is OperationCanceledException)
Utils.InfoMsg("Copy operation cancelled at users request.");
return false;
}
catch (OperationCanceledException)
{
Utils.InfoMsg("Copy operation cancelled at users request.");
return false;
}
}
In a button Click event (or using a delegate (buttonCancel.Click += delegate { /Cancel the Task/ }) I cancel theTask` as follows:
private void buttonCancel_Click(object sender, EventArgs e)
{
try
{
cancelSource.Cancel();
asyncDupSqlProcs.Wait();
}
catch (AggregateException aggEx)
{
if (aggEx.InnerException is OperationCanceledException)
Utils.InfoMsg("Copy cancelled at users request.");
}
}
This catches the OperationCanceledException fine in method DuplicateSqlProcsFrom and prints my message, but in the call-back provided by the asyncDupSqlProcs.ContinueWith(task => { ... }); above the task.Status is always RanToCompletion; it should be cancelled!
What is the right way to capture and deal with the Cancel() task in this case. I know how this is done in the simple cases shown in this example from the CodeProject and from the examples on MSDN but I am confused in this case when running a continuation.
How do I capture the cancel task in this case and how to ensure the task.Status is dealt with properly?
A: You're catching the OperationCanceledException in your DuplicateSqlProcsFrom method, which prevents its Task from ever seeing it and accordingly setting its status to Canceled. Because the exception is handled, DuplicateSqlProcsFrom finishes without throwing any exceptions and its corresponding task finishes in the RanToCompletion state.
DuplicateSqlProcsFrom shouldn't be catching either OperationCanceledException or AggregateException, unless it's waiting on subtasks of its own. Any exceptions thrown (including OperationCanceledException) should be left uncaught to propagate to the continuation task. In your continuation's switch statement, you should be checking task.Exception in the Faulted case and handling Canceled in the appropriate case as well.
In your continuation lambda, task.Exception will be an AggregateException, which has some handy methods for determining what the root cause of an error was, and handling it. Check the MSDN docs particularly for the InnerExceptions (note the "S"), GetBaseException, Flatten and Handle members.
EDIT: on getting a TaskStatus of Faulted instead of Canceled.
On the line where you construct your asyncDupSqlProcs task, use a Task constructor which accepts both your DuplicateSqlProcsFrom delegate and the CancellationToken. That associates your token with the task.
When you call ThrowIfCancellationRequested on the token in DuplicateSqlProcsFrom, the OperationCanceledException that is thrown contains a reference to the token that was cancelled. When the Task catches the exception, it compares that reference to the CancellationToken associated with it. If they match, then the task transitions to Canceled. If they don't, the Task infrastructure has been written to assume that this is an unforeseen bug, and the task transitions to Faulted instead.
Task Cancellation in MSDN
A: Sacha Barber has great series of articles about TPL. Try this one, he describe simple task with continuation and canceling
| {
"language": "en",
"url": "https://stackoverflow.com/questions/9682577",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: mysql query slow with joins upon enabling the slow_query_log in mysql. I found that the query below was one of slowest query with 15 secs or more. How can I optimize this query. All tables are Innodb and
server: Server version: 5.6 Thank you
EXPLAIN EXTENDED SELECT
ntv_staffs.fname,
ntv_staffs.id,
ntv_staffs.mname,
ntv_staffs.profile_pic,
ntv_staffs.lname,
ntv_staff_office.cug,
ntv_staff_office.extension,
ntv_staff_office.off_email,
ntv_staff_office.job_title,
ntv_designations.`name` as designation_name,
ntv_branches.`name` as branch_name,
ntv_departments.`name` as department_name,
ntv_departments.id as department_id
FROM
ntv_staffs
INNER JOIN ntv_staff_office ON ntv_staffs.id = ntv_staff_office.pid
INNER JOIN ntv_departments ON ntv_staff_office.department_id = ntv_departments.id
INNER JOIN ntv_branches ON ntv_staff_office.branch_id = ntv_branches.id
INNER JOIN ntv_designations ON ntv_staff_office.designation = ntv_designations.id
where ntv_staffs.id='662';
+----+-------------+------------------+--------+---------------+---------+---------+----------------------------------------------+------+----------+-------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | filtered | Extra |
+----+-------------+------------------+--------+---------------+---------+---------+----------------------------------------------+------+----------+-------------+
| 1 | SIMPLE | ntv_staffs | const | PRIMARY | PRIMARY | 4 | const | 1 | 100.00 | |
| 1 | SIMPLE | ntv_staff_office | ALL | NULL | NULL | NULL | NULL | 247 | 100.00 | Using where |
| 1 | SIMPLE | ntv_branches | eq_ref | PRIMARY | PRIMARY | 4 | abc_portal_new.sks_staff_office.branch_id | 1 | 100.00 | |
| 1 | SIMPLE | ntv_designations | eq_ref | PRIMARY | PRIMARY | 4 | abc_portal_new.sks_staff_office.designation | 1 | 100.00 | Using where |
| 1 | SIMPLE | ntv_departments | eq_ref | PRIMARY | PRIMARY | 4 | abc_portal_new.sks_staff_office.department_id | 1 | 100.00 | |
+----+-------------+------------------+--------+---------------+---------+---------+----------------------------------------------+------+----------+-------------+
A: Try setting a btree-index for ntv_staff_office.pid.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37405208",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can I get the output of a Timed Out command by subprocess.check_output()? I'm trying to run some commands using the python library subprocess. Some of my commands might get stuck in loops and block the python script. Therefore I'm using check_output() with a timeout argument to limit the commands in time. When the command takes too much time, the function raise a TimeoutExpired error. What I want to do is get what the command has been able to run before being killed by the timeout.
I've except the error and tried "except sp.TimeoutExpired as e:". I read on the doc that if I do e.output it should give me what I want. "Output of the child process if this exception is raised by check_output(). Otherwise, None.". However I don't get anything in the output.
Here is what I did:
import subprocess as sp
try:
out = sp.check_output('ls', stderr=sp.STDOUT, universal_newlines=True, timeout=1)
except sp.TimeoutExpired as e:
print ('output: '+ e.output)
else:
return out
Let say the folder I'm working with is huge and so 1 second isn't enough to ls all its files. Therefore the TimeoutExpired error will be raised. However, I'd like to store what the script was able to get at least. Does someone have an idea?
A: Found a solution, posting it here in case someone is interested.
In Python 3, the run method allows to get the output.
Using the parameters as shown in the example, TimeoutExpired returns the output before the timeout in stdout:
import subprocess as sp
for cmd in [['ls'], ['ls', '/does/not/exist'], ['sleep', '5']]:
print('Running', cmd)
try:
out = sp.run(cmd, timeout=3, check=True, stdout=sp.PIPE, stderr=sp.STDOUT)
except sp.CalledProcessError as e:
print(e.stdout.decode() + 'Returned error code ' + str(e.returncode))
except sp.TimeoutExpired as e:
print(e.stdout.decode() + 'Timed out')
else:
print(out.stdout.decode())
Possible output:
Running ['ls']
test.py
Running ['ls', '/does/not/exist']
ls: cannot access '/does/not/exist': No such file or directory
Returned error code 2
Running ['sleep', '5']
Timed out
I hope it helps someone.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56476535",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to set text dynamically to texbox in vba? Dear Fellow StackOverFlow-members,
I try to dynamically create texboxes in a userform and set default text depending on value from a tab.
First the user fill in textboxes like in the photo
When he clicks the button above, it calls the function that create textboxes in the same userform. Exactly as much as the total of values of the textboxes, futhermore for value "0" it counts as 1 textbox to add.
What I want is when it encounters 0 value I want the new texbox created to set defaut text as "null". Like so :
My code :
For i = 0 To UBound(tabValTextBox)
valTemp = tabValTextBox(i)
If valTemp = 0 Then
iTextBoxMasqueA = iTextBoxMasqueA + 1
Set textBoxCableA = UserForm1.Controls.Add("Forms.TextBox.1")
colTextBoxCableA.Add textBoxCableA
With textBoxCableA
.Name = "cable" & iTextBoxCableA
.Top = iTextBoxCableA * textBoxCableA.Height + 50
.Left = 150
.Text = "Nul"
End With
Else
For j = 0 To valTemp - 1
iTextBoxCableA = iTextBoxCableA + 1
Set textBoxCableA = UserForm1.Controls.Add("Forms.TextBox.1")
colTextBoxCableA.Add textBoxCableA
With textBoxCableA
.Name = "cable" & iTextBoxCableA
.Top = iTextBoxCableA * textBoxCableA.Height + 50
.Left = 150
End With
Next j
End If
Next i
tabValTextbox() is a tab containing the values of the left textboxes.
However the result I get looks like this : I don't get as much textboxes as expected.
I don't understand where I'm missing something. I want to learn from this, so if possible, explain me what I'm doing wrong here, or if my approach is lacking insight.
A: Try this:
For i = 0 To UBound(tabValTextBox)
valTemp = tabValTextBox(i)
iTextBoxCableA = iTextBoxCableA + 1
If valTemp = 0 Then
Set textBoxCableA = UserForm1.Controls.Add("Forms.TextBox.1")
colTextBoxCableA.Add textBoxCableA
With textBoxCableA
.Name = "cable" & iTextBoxCableA
.Top = iTextBoxCableA * textBoxCableA.Height + 50
.Left = 150
.Text = "Nul"
End With
Else
For j = 0 To valTemp - 1
Set textBoxCableA = UserForm1.Controls.Add("Forms.TextBox.1")
colTextBoxCableA.Add textBoxCableA
With textBoxCableA
.Name = "cable" & iTextBoxCableA
.Top = iTextBoxCableA * textBoxCableA.Height + 50
.Left = 150
End With
Next j
End If
Next i
I've moved the iTextBoxCableA increment outside of the zero condition, and removed the iTextBoxMasqueA increment entirely as you weren't using it.
I can't test this myself but I think it'll sort the problem of overlapping out.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/54943065",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Azure AD B2C Application won't show up as an option to add role assignment. (Graph API) I'm following this documentation:
https://learn.microsoft.com/en-us/azure/active-directory-b2c/microsoft-graph-get-started?tabs=app-reg-ga
And I found another question answered that I thought fit my case:
https://learn.microsoft.com/en-us/answers/questions/199433/can39t-add-role-assignments-to-azure-b2c-applicati.html
My problem is that the app that I registered will not appear as an option when I try to follow the "Enable user delete and password update" portion of the documentation.
I am also mindful of the notice "Please allow a few minutes to for the permissions to fully propagate." But I've at it for 2 hours now, so I don't think that is the problem.
Here is my App and its API permissions:
And my B2C Tenant:
A: Microsoft has answered this question on this thread as follows:
Hi All · Thank you for reaching out.
There seems to be an issue with the UI. I will report the issue to the product team and get it addressed.
However, as of now, you can follow below steps and use PowerShell to add application to the User Administrator role:
*
*Install latest Azure AD PowerShell Module.
*Run Connect-AzureAD -TenantId Your_B2CTenant.onmicrosoft.com and sign in with Global Administrator account in that tenant.
*Run Get-AzureADDirectoryRole cmd and copy the object id of the User Administrator role.
*Navigate to Azure AD > Enterprise Applications > Search the app and copy the object id of the app.
*Run Add-AzureADDirectoryRoleMember -ObjectId object_ID_copied_in_Step3 -RefObjectId object_ID_copied_in_Step4 cmdlet.
To verify, navigate to Azure AD B2C > Roles and Administrators > User Administrator. You should see the application present under this role
| {
"language": "en",
"url": "https://stackoverflow.com/questions/65728384",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Is such an iOS model possible to implement? I would like to do the following:
*
*Sell a game for $0.99 at launch with no feature restrictions.
*If it's less than successful, make it free, but limit some features to in-app purchase (I would do this via an update to the existing app).
*BUT, I would like users who originally purchased the app (before it was free) to still have all of the features. In other words, I want to find a way to credit the new in-app purchases to those users, so that they don't have to pay twice.
I would like to do this all with the existing app, instead of making two separate versions of the app (paid and free).
EDIT: it is essential that not a single user ever have to pay twice (i.e. that users who previously paid for the app, do not have to purchase the in-app upgrades in the future).
EDIT 2: It seems like this question has already been answered here: From Paid to FREE w/IAP: Preventing double-charging
A: Certainly.
The company I work for has done this in the past.
If you know you might want to do this in the future, in your first version store a flag to NSUserDefaults indicating that the user has had the paid version. Then, on your In-App version check this flag and provide the content immediately.
If you already have a version released, you may have to look for something that you are already storing, e.g. the user has a highscore greater than zero to indicate that the user has already purchased the app. (There will be a small number of users that may have downloaded the app but not opened it and these users may be charged twice).
A: Yeah, it is. Before you Update your app with FREE version, you add all users that have paid for it serial number "PAID"(or something), and everything else is just conditional statements(if-else). Congrats!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/9263064",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Add unique ID to containing div of file input thumbnail image I have thumbnail previews of a users selected images prior to upload. It will also allow a user to re-arrange the order of the images using jQuery UI. I want to track the order of the images by adding a unique ID to each thumbnails containing div, but I am not able to generate a unique ID. See Code below. Ideally I would like the div ID to match the image name, so then after the form post I use it to match to the filename in the IEnumerable<HttpPostedFileBase>. For example, if the uploaded image is called pic1.jpg, the div containing the thumbnail would be <div id = "pic1">. The line in question would seem to be div.id = File.name, but I am unable to generate a unique ID of any kind?
CODE
//jQuery UI sort
$(function () {
$("#upload-thumbnails").sortable();
$("#upload-thumbnails").disableSelection();
});
//Thumbnail preview
jQuery(function ($) {
var filesInput = document.getElementById("ImageUploads");
filesInput.addEventListener("change", function (event) {
var files = event.target.files; //FileList object
var output = document.getElementById("upload-thumbnails");
for (var i = 0; i < files.length; i++) {
var file = files[i];
var picReader = new FileReader();
picReader.addEventListener("load", function (event) {
var picFile = event.target;
var div = document.createElement("div");
div.id = File.name;
div.innerHTML = "<img class='thumbnail' src='" + picFile.result + "'" +
"title='" + picFile.name + "'/><a href='#' class='remove_pict'>Remove</a>";
output.insertBefore(div, null);
div.children[1].addEventListener("click", function (event) {
div.parentNode.removeChild(div);
});
});
//Read the image
picReader.readAsDataURL(file);
}
});
});
A: In most cases while we uploading images we rename them as the time stamp because of the uniqueness. But for searching, dealing with time stamp is much harder, then add a class name of the div as the file name.
...
var div = document.createElement("div");
div.id = Date.now();
div.className += ' ' + File.name;
...
I am sure this will be help full.
Thanks
A: Not sure I get the question :)
Try instead:
$(div).attr('id', 'yourIDHere')
Or you never use your defined var file , could it not be?
div.id = file.name;
You can generate UUIDs via JS see here
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42368059",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Improving JavaScript path finding algorithm I'm working on an HTML/JavaScript flowchart designer similar to Visual Studio flowchart designer. One of the most fascinating features of VS flowchart designer, is its intelligent path creation algorithm, I think there should be a powerful path finding algorithm behind the scenes (something like A* for example).
I've implemented a path finding algorithm (a simple version of A*) in my application which tries to find a path between my source and destination nodes. Although it is generating the expected results, but it is really poor in terms of performance and speed, as it takes a long calculation time (in fact the calculation time increases as the path gets longer).
What are your suggestions for improving the performance? Do you know how Visual Studio is finding the path so quickly?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/34553526",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Javascript Design Pattern Prototype error for web3.js Don't know what I am doing wrong, created a javascript prototype for a web3js application I am working on. When I try calling the function in the prototype it is not seeing the function in it. Throwing "persona.testing() is not a function" when I check the console.log.
Web3 = require('web3');
if(typeof web3 != "undefined")
web3 = new Web3(web3.currentProvider);
else {
web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
}
var initweb3 = function(address,abi) {
this.address = address,
this.abi = abi;
this.contract;
web3.eth.defaultAccount = web3.eth.accounts[0];
this.contract = web3.eth.contract(this.abi);
this.contract = this.contract.at(this.address);
}
var paddress = "0x0",
pabi = "",
maddress = "",
mabi = "";
persona = new initweb3(paddress,pabi);
//minion = new initweb3(maddress,mabi);
persona.prototype = {
testing: function(){
console.log('Yes, I know');
},
testing1: function(){
console.log('No, I don't');
}
};
persona.testing();
A: You could use Object.assign
persona = Object.assign({}, persona, {
testing: function(){
console.log('Yes, I know');
}
});
or
persona.prototype.testing = function(){};
A: You should use prototype when you want to create one or more instances of a function.
in your case initweb3 is a constructor function.
make sure your constructor function starts with uppercase letter.
For example:
function Person(){ /*...*/ }
Person.prototype.sayHi = function() { };
const p = new Person();
p.sayHi();
in your use case persona is already an instance object, if you want to add a new function to it you simply do persona.testing = function() {}
OR
You can also try extending the initweb3 function.
initweb3.prototype.testing = function(){ /* code goes here */}
.
.
.
persona.testing();
Watch this video to learn more about prototypes in JavaScript.
https://www.youtube.com/watch?v=riDVvXZ_Kb4
| {
"language": "en",
"url": "https://stackoverflow.com/questions/43360662",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Page breaks on php tag The following code is written in php file and breaks page
<?php
$myrows1=cpabc_player_plan();
foreach ($myrows1 as $index=>$item1) //start foreach party plan
{
if ($item1 === reset($myrows1))
{}
?>
<?php }?>
while if I use it as
<?php
$myrows1=cpabc_player_plan();
foreach ($myrows1 as $index=>$item1) //start foreach party plan
{
if ($item1 === reset($myrows1))
{}
}?>
then it works fine.
A: You can use foreach(): endforeach Block like this:
<?php foreach ($myrows1 as $index=>$item1): ?>
<h1> some html tags</h1>
<?php
if ($item1 === reset($myrows1))
{}
?>
<h1> some html tags</h1>
<?php endforeach; ?>
for other php statements you can read this page.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37236871",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Make Syntastic close just the error window I've got the (Mac)Vim Syntastic plugin installed via Janus. When I open the :Errors window to view the reason for syntax errors, it shrinks the file with the errors to one line and uses the rest of the real estate for the Errors window.
Is there a way to make it hog less room for errors and more importantly, how do I close just the Errors window? The usual :q closes both the Errors window AND the original file, even if the cursor is in the Errors window. (That's not 100% correct -- it gratefully does not close the file if the file hasn't yet been saved).
A: Syntastic uses the location list (a window-local variant of the quickfix list), so a :lclose will close it, but keep the other buffers.
As per syntastic's help pages, the initial height can be configured:
:let g:syntastic_loc_list_height=5
But I suspect that your intrusive Janus distribution has a hand in that. Vim "distributions" like spf-13 and Janus lure you with a quick install and out of the box settings, but you pay the price with increased complexity (you need to understand both Vim's runtime loading scheme and the arbitrary conventions of the distribution) and inflexibility (the distribution may make some things easier, but other things very difficult). Vim is incredibly customizable, using someone else's customization makes no sense.
A: Syntastic gets confused when you're juggling multiple buffers on one screen so here's a script that will collect information about the situation, then do the right thing:
function JustCloseSyntasticWindow()
"Check which buffer we are in, and if not, return to the main one:
if &ft == "qf"
normal ZZ
endif
"Since different buffers have different command spaces, check if we've
"escaped the other buffer and then tell syntastic to stop.
if &ft != "qf"
SyntasticReset
" --- or ----
SyntasticToggleMode
endif
endfunction
au FileType buffer1_ft nnoremap :yourcmd<CR>:call JustCloseSyntasticWindow()<cr>
au FileType main_win_ft nnoremap :yourcmd<CR>:call JustCloseSyntasticWindow()<cr>
Don't be shy on the duct tape for this job, it's the only thing holding the unit together.
A: The command to close the Syntastic error window is:
:SyntasticReset
A: You can use :lclose to close it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/18962146",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "32"
} |
Q: VSCode, typescript, eslint and prettier -> null check does not work I've tried to setup typescript linting to use prettier and while prettier works, i seem to have lost the basic typescript error checking. How can i get this back?
^ should complain about accessing .value on foo?
My tsconfig.json
{
"compilerOptions": {
"outDir": "./dist/",
"noImplicitAny": true,
"module": "es6",
"target": "es5",
"jsx": "react",
"allowJs": true,
"sourceMap": true,
"moduleResolution": "node",
"baseUrl": "./src",
"allowSyntheticDefaultImports": true,
"paths": {
"~/*": ["./*"]
}
},
}
.eslintrc.json
{
"extends": [
"eslint:recommended",
"plugin:@typescript-eslint/recommended",
"prettier/@typescript-eslint",
"plugin:prettier/recommended"
],
"plugins": ["@typescript-eslint", "prettier"],
"env": {
"browser": true,
"jasmine": true,
"jest": true,
"es6": true
},
"rules": {
"prettier/prettier": [
"error",
{ "singleQuote": true, "semi": false }
],
"@typescript-eslint/no-use-before-define": "off",
"@typescript-eslint/no-explicit-any": "off",
"@typescript-eslint/class-name-casing": ["error", { "allowUnderscorePrefix": true }],
"@typescript-eslint/interface-name-prefix": ["error", { "prefixWithI": "always", "allowUnderscorePrefix": true}],
"@typescript-eslint/no-unused-vars": ["error", { "args": "none"}],
"@typescript-eslint/no-non-null-assertion": "off",
"semi":"off"
},
"parser": "@typescript-eslint/parser"
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58945203",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Music and Sound Effects How to separate on and off(i mean how to mute separate ) function of Music Background and Sound Effect
AudioManager
public Sound[] sounds;
public static AudioManager instance;
void Awake()
{
if (instance == null)
instance = this;
else
{
Destroy(gameObject);
return;
}
DontDestroyOnLoad(gameObject);
foreach (Sound s in sounds)
{
s.source = gameObject.AddComponent<AudioSource>();
s.source.clip = s.clip;
s.source.volume = s.volume;
s.source.loop = s.loop;
s.source.mute = s.mute;
}
}
Sound.cs
public string name;
public AudioClip clip;
[Range(0f, 1f)]
public float volume;
public bool loop;
public bool mute;
[HideInInspector]
public AudioSource source;
This is my Music and Sound Effects
| {
"language": "en",
"url": "https://stackoverflow.com/questions/51905795",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Set variable while foreach loop is working I have foreach loop that copies files.
I want to set label to "Working.." while the foreach loop is copying the files.
I have tried:
label.text = "Ready";
foreach (file in files)
{
File.Copy(firstDest, secondDest);
label.text = "Working..";
}
label.text = "Ready";
But the label never changes even when it's copying the files for a while 2-3 seconds.
Do you know how to solve this? Thanks!
A: You should do your copy operation in another thread.
label.text = "Ready";
var tasks = Task[files.length];
for (var i=0 ; i<files.length; i++) {
tasks[i] = Task.Run(()=>{
File.Copy(firstDest, secondDest);
});
}
label.text = "Working..";
await Task.WhenAll(tasks);
label.text = "Ready";
In case you want to run it all in one task and not each copy in parallel
label.text = "Ready";
var task =Task.Run(()=>{
foreach (file in files){
File.Copy(firstDest, secondDest);
}
});
label.text = "Working..";
await task;
label.text = "Ready";
| {
"language": "en",
"url": "https://stackoverflow.com/questions/57478509",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is there a way in Javascript/Angular to subscribe to a 'request sent' event hook? I'm wondering if there's a way in a Javascript/Angular application to hook into a 'request-sent' event emitted by the browser immediately after it sends off a request. The purpose is that we want to ensure/control the order of the requests that go out, and we were thinking of sending each one out in response to the previous one emitting a 'request sent' event (this way we ensure the most important requests get out first). We want to allow the requests to run asynchronously/simultaneously so we don't have the option of waiting for one request to return before sending the next one. We want to send each request as soon as we know the previous one was successfully sent.
The challenge with this is that the order in which the requests are sent in the code does not match the order we see in the Chrome network tab, so we can't rely on the sequences of events that run in the code to guarantee that the same sequence will be followed when the browser sends the requests.
This is why it would be really convenient if we could hook into a 'request sent' event fired from the browser or something of that sort. That would ensure that all requests can still go out asynchronously while also controlling the order in which they go out.
Thanks for any forthcoming help.
A: If you want to maintain the order of api calls, you can user switchMap operator.
let's say that you have two api calls:
const apiCall1$ = this.http.get("/endpoint1");
const apiCall2$ = this.http.get("/endpoint2");
and you want to wait for apiCall1 to finish before sending apiCall2, you can do it like this:
apiCall1$.pipe(switchMap(() => apiCall2$)).subscribe({
next: (response) => {
//do something...
}
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/69202449",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Getting checkbox values in angularjs and passing them into another controller I am transitioning from jquery to angularjs. I am trying to develop a small app in SPA style. Left side is the menu that controls the content on the right side. Left side menu has its own controller. When the user selects a checkbox and clicks on 'Go', the checkbox value should be passed to the controller that controls the right side content. Here is the link to the app. Below are the issues I have.
1)I am stumped on a simple problem of accessing checked values of a checkbox. How do I access values of checked checkboxes. The checboxes are on left side menu, and I am using ng-model to currently access the values as below
index.html
<div id="searchOne">
<ul>
<li ng-repeat="searchOneCB in main.checkBoxOneData">
<input type="checkbox" name="firstSearch" id="firstSearch_{{searchOneCB.code}}" ng-model="main.selected[searchOneCB.code]" />
{{searchOneCB.description}}
</li>
</ul>
<button class="btn btn-primary" style="width:80px;margin-right: 10px" ng-click="main.submit()">
Go
</button>
</div>
MainCtrl.js to access the checkbox value.
main.submit = function() {
console.log(main.selected);
}
The values are now in the form of an array as below
[BBBB: true, AAAA: true].
Is this the right way to access the values? What is the best way to retrieve only the checked checbox values?
2) Another question is, once I get the list of checked checkboxes values, how can I pass them to the contentCtrl.js that controls the content on right side?
A: You should inject the controller into the controller you want to use. The answer has already been answered here is the link.
How do I inject a controller into another controller in AngularJS
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30334955",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: ASP.Net MVC in shared hosting environment It's a very simple question, but I wasn't able to find exact answer.
Do you need to install anything extra besides .Net Framework 3.5 and IIS7 to run ASP.Net MVC applications?
Hope it will be useful to other people too.
A: If you don't use any third party libraries, then no.
The host has to have the .NET 3.5 SP1 installed.
However you need to be aware of the trust level issues. Most shared hosts run in medium trust mode. Although this will suffice for the MVC itself, it may not for your other code. If you use reflection for example, you will need the full trust enabled.
Basically this simple code may get you into trouble:
object something = 5;
if (something is int)
{
// Do something
}
Check your code and choose the host wisely.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/1486594",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: When using oracle-jdk17 and gson 2.10, there is an issue that private time cannot be converted The following error occurred when using gson for conversion;
Unable to make field private final java.time.LocalDate java.time.LocalDateTime.date accessible: module java.base does not "opens java.time" to unnamed module @7006c658
My JDK version is java 17.0.5 2022-10-18 LTS, the os is ubuntu 22.04, and the gson version is 2.10;
Here is my code
Gson gson = new GsonBuilder().registerTypeAdapter(LocalDate.class, new LocalDateAdapter().nullSafe()).create();
Type mapType = new TypeToken<Map<String, Object>>() {}.getType();
Type listType = new TypeToken<List<Object>>() {}.getType();
Map<String,Object> map = gson.fromJson(geoCode, mapType);
String adCode = null;
if (Objects.nonNull(map) && map.get("infocode").equals("10000")){
List<Object> list = gson.fromJson(gson.toJson(map.get("geocodes")), listType);
Map<String,Object> temp = gson.fromJson(gson.toJson(list.get(0)),mapType);
adCode = String.valueOf(temp.getOrDefault("adcode","110000"));
}
String weatherInfo = getWeatherInfo(adCode);
return gson.fromJson(weatherInfo, Weather.class);
public class LocalDateAdapter extends TypeAdapter<LocalDate> implements JsonSerializer<LocalDate>, JsonDeserializer<LocalDate> {
@Override
public LocalDate deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
String asString = jsonElement.getAsJsonPrimitive().getAsString();
return LocalDate.parse(asString,DateTimeFormatter.ISO_LOCAL_DATE);
}
@Override
public JsonElement serialize(LocalDate localDate, Type type, JsonSerializationContext jsonSerializationContext) {
return new JsonPrimitive(localDate.format(DateTimeFormatter.ISO_LOCAL_DATE));
}
@Override
public void write(JsonWriter jsonWriter, LocalDate localDate) throws IOException {
jsonWriter.value(localDate.toString());
}
@Override
public LocalDate read(JsonReader jsonReader) throws IOException {
return LocalDate.parse(jsonReader.nextString());
}
}
The data structure looks like this
{"date":"2022-11-28","week":"1","dayweather":"多云","nightweather":"晴","daytemp":"14",
"nighttemp":"-5","daywind":"西北","nightwind":"西北","daypower":"4","nightpower":"4"}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74598982",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Trouble with writing text to a .ini file I am working on a small game project in the Unity 3D engine. I am trying to write a class that will allow a settings menu to write the recorded settings to an .ini file. However, I can't seem to get myto write to the file. I think I wrote the class correctly to do it based upon the MSDN article on the subject. Here is my class
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using UnityEngine;
//Used to allow other files to access the script by name
namespace INI
{
public class iniFile {
public string path;
string winDir=System.Environment.GetEnvironmentVariable("windir");
[DllImport("KERNEL32.DLL")]
private static extern long WritePrivateProfileString(string section, string key, string value, string filePath);
[DllImport("KERNEL32.DLL")]
private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);
/// INIFile Constructor.
public iniFile(string INIPath) {
path = INIPath;
}
/// Write Data to the INI File
public void IniWriteValue(string Section, string Key, string Value) {
long success = WritePrivateProfileString(Section, Key, Value, this.path);
Debug.Log (Section);
Debug.Log (Key);
Debug.Log (Value);
Debug.Log (path);
Debug.Log (success);
return;
}
/// Read Data Value From the Ini File
public string IniReadValue(string Section, string Key) {
StringBuilder temp = new StringBuilder(255);
int i = GetPrivateProfileString(Section, Key, "", temp, 255, this.path);
return temp.ToString();
}
}
}
Here is my call for this class:
if (GUI.Button (new Rect (Screen.width * guiGameplayApplyButtonPlaceX, Screen.height * guiGameplayApplyButtonPlaceY, Screen.width * guiGameplayApplyButtonSizeX, Screen.height * guiGameplayApplyButtonSizeY), "Apply")) {
ini.IniWriteValue("Gameplay","Difficulty","Test");
print ("Apply");
}
I created the instance of the class like this:
iniFile ini = new iniFile(@"..\settings\settingsTest.ini");
A: Maybe that's not the exact answer to your question, but what for you want to create file with settings? Wouldn't be much easier, to use Unity3d built-in feature for saving game preferences, which also works cross-platform?
If you want to give it a try, read about PlayerPrefs.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/23786847",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: How to structure/implement multidimensional data / data cube I've been reading into what a data cube is and there are lots of resources saying what it is and why (OLAP/ business intelligence / aggregations on specific columns) you would use one but never how.
Most of the resources seem to be referencing relational data stores but it doesn't seem like you have to use an RDBMS.
But nothing seems to show how you structure the schema and how to query efficiently to avoid the slow run time of aggregating on all of this data. The best I could find was this edx class that is "not currently available": Developing a Multidimensional Data Model.
A: You probably already know that there are 2 different OLAP approaches:
*
*MOLAP that requires data load step to process possible aggregations (previously defined as 'cubes'). Internally MOLAP-based solution pre-calculates measures for possible aggregations, and as result it is able to execute OLAP queries very fast. Most important drawbacks of this approach come from the fact that MOLAP acts as a cache: you need to re-load input data to refresh a cube (this can take a lot of time - say, hours), and full reprocessing is needed if you decide to add new dimensions/measures to your cubes. Also, there is a natural limit of the dataset size + cube configuration.
*ROLAP doesn't try to pre-process input data; instead of that it translates OLAP query to database aggregate query to calculate values on-the-fly. "R" means relational, but approach can be used even with NoSQL databases that support aggregate queries (say, MongoDb). Since there is no any data cache users always get actual data (on contrast with MOLAP), but DB should able to execute aggregate queries rather fast. For relatively small datasets usual OLTP databases could work fine (SQL Server, PostgreSql, MySql etc), but in case of large datasets specialized DB engines (like Amazon Redshift) are used; they support efficient distributed usage scenario and able to processes many TB in seconds.
Nowadays it is a little sense to develop MOLAP solution; this approach was actual >10 years ago when servers were limited by small amount of RAM and SQL database on HDD wasn't able to process GROUP BY queries fast enough - and MOLAP was only way to get really 'online analytical processing'. Currently we have very fast NVMe SSD, and servers could have hundreds gigabytes of RAM and tens of CPU cores, so for relatively small database (up to TB or a bit more) usual OLTP databases could work as ROLAP backend fast enough (execute queries in seconds); in case of really big data MOLAP is almost unusable in any way, and specialized distributed database should be used in any way.
A: The general wisdom is that cubes work best when they are based on a 'dimensional model' AKA a star schema that is often (but not always) implemented in an RDBMS. This would make sense as these models are designed to be fast for querying and aggregating.
Most cubes do the aggregations themselves in advance of the user interacting with them, so from the user perspective the aggregation/query time of the cube itself is more interesting than the structure of the source tables. However, some cube technologies are nothing more than a 'semantic layer' that passes through queries to the underlying database, and these are known as ROLAP. In those cases, the underlying data structure becomes more important.
The data interface presented to the user of the cube should be simple from their perspective, which would often rule out non-dimensional models such as basing a cube directly on an OLTP system's database structure.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/46882953",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: I have hbase metadata in gcs from another environment. I want to create table from this but not sure how? I have a Hbase table extract in google cloud bucket from SIT environment. I want to create a hbase table using that but I am not sure how to do it. I tried creating dummy table and pushing the data inside of it but it didn't worked out. Any help is appreciated. Thank You !
I tried creating hbase table from metadata stored in gcs but somehow the data is not visible in the new table created. I want to use the data to create hbase table so I can continue my development.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75627484",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to navigate to a route without routerLink in angular2 I am working with nebular framework, from the amazing guys at akveo.
One of the components is a context menu that creates a popup menu with it's options read from an array
items = [{ title: 'Profile' }, { title: 'Log out' }];
I want to navigate to a different screen but tutorials talk mostly about routerLink
<p>This is my link <a routerLink="/getMeOut">out</a></p>
But in this case, I can't add a <a> tag because they abstracted the click event and allow you to subscribe like
this.menuService.onItemClick()
.pipe(
filter(({ tag }) => tag === 'my-context-menu'),
map(({ item: { title } }) => title),
)
.subscribe(title => {
console.error(`${title} was clicked!`)
});
And that prints when each button was clicked, but I have to trigger the navigation inside the .subscribe() function.
How to do so?
A: First of all, the outer route has got to exist, in some routing.module
// app-routing.module.ts
const routes: Routes = [
{ path: 'getMeOut', component: OutComponent },
..
]
Four things are needed then
*
*Import Router from @angular/router.
*Create a private router in your constructor private router: Router.
*Call navigateByUrl() with the desired route.
*Identify your context menu with the nbContextMenuTag property.
Then, in the module that holds the context menu, we create the router to handle the navigation like
// awesome.component.ts
import { Router } from '@angular/router'
import { NbMenuService } from '@nebular/theme';
@Component({
selector: 'awesome',
styleUrls: ['./awesome.component.scss'],
templateUrl: './awesome.component.html',
})
ngOnInit() {
this.menuService.onItemClick()
.pipe(
filter(({ tag }) => tag === 'my-context-menu'),
map(({ item: { title } }) => title),
)
.subscribe(title => {
if (title === 'Log out') this.router.navigateByUrl('/getMeOut');
console.error(`${title} was clicked!`)
});
}
constructor(
private menuService: NbMenuService,
private router: Router) {
}
See the simple use of navigateByUrl from @angular/router.
Just add nbContextMenuTag="my-context-menu" to the html template
<nb-action *nbIsGranted="['view', 'user']" >
<nb-user nbContextMenuTag="my-context-menu"></nb-user>
</nb-action>
I hope it's not a dupe. I found this answer but it meant more about nested routers.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/51602809",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to reference friends in Open Graph? I am creating a Facebook-enabled game where the users will be able to publish 'friend passes'; where a player will be able to post (automatically) such as: 'I passed James Brown on MY_GAME'. I am using Open Graph for posting my actions. I've created an action named 'pass' and an object named 'friend'. Here is my properties (where 'friendpass' is a Friend reference):
I am trying to post actions such as 'Michael passed a friend on MY_GAME' and also tag my passed friend[s?]. How can I enable this functionality? Currently, I ve set up a page (actually just meta-tag) renderer and Here is an example rendered page:
<html and other headers...>
<meta property="fb:app_id" content="345390505541783">
<meta property="og:type" content="smileys-game:friendpass">
<meta id="ogurl" property="og:url" content="http://apps.canpoyrazoglu.com/smileys/pass/mehmet/sucuk">
<meta property="og:title" content="Friend passed!">
<meta property="og:image" content="https://s-static.ak.fbcdn.net/images/devsite/attachment_blank.png">
<meta id="friendid" property="smileys-game:friend" content="735475141">
<meta id="ogdesc" property="og:description" content="something comes here.">
<rest of header and page...>
I use the debug tool to get what Facebook sees and there is a link to the action there as a Graph API call. When I click it it returns OAuth error, when I type that URL to the Graph API explorer, I get this:
Graph API sees my 'friend' object as a webpage, which is actually a reference to a Facebook ID (my own ID). How can I make use of that Friend ID useful and make a link to the friend in the post?
Thanks,
Can.
A: When you create your action type, you need to use the profile object type (aka connected object type). Here I created my verb to "high five" a person:
The object type will be configured automatically because profile is a built-in, FB-provided object type. So you don't have to configure the object type, unless there's an advanced setting you need.
Then create an aggregation:
Your og meta tags for the object then need to use the type profile (filepath for this example is /og/profile2.html):
<head prefix="og: http://ogp.me/ns# fb: http://ogp.me/ns/fb# high_fiver: http://ogp.me/ns/fb/high_fiver#">
<meta property="fb:app_id" content="27877347222" />
<meta property="og:url" content="http://www.rottentomatoes.com/celebrity/tom_hanks/" />
<meta property="og:type" content="profile" />
<meta property="og:title" content="Tom Hanks" />
<meta property="og:description" content="Tom Hanks profile on RT" />
<meta property="og:image" content="http://content6.flixster.com/rtactor/40/37/40376_pro.jpg" />
Notice that you can point to any profile, not just a FB profile. Above, I am using Tom Hanks' profile on Rotten Tomatoes, which uses Open Graph and has og:type profile.
And I publish actions like so:
<script type="text/javascript">
function postAction() {
FB.api(
'/me/high_fiver:high_five' + '?profile=http://www.plooza.com/og/profile2.html',
'post',
function(response) {
if (!response || response.error) {
alert('Error occured');
console.log(response.error);
} else {
alert('Post was successful! Action ID: ' + response.id);
}
}
);
}
</script>
Finally, a user of my app will publish the OG story on his/her timeline (in a "timeline unit"):
When you click the link "Tom Hanks" in the story unit, it loads the Rotten Tomatoes profile.
You can try this demo app here: http://plooza.com/og/profile2.html
A: So “friend” is your own object type? How exactly is it defined?
I think for what you’re planning to do here, the built-in object type Profile might suit your needs better – because that already creates a tie to a Facebook profile that is recognizable as such by the Open Graph.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/12043046",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to add label into form builder (not in twig)? I have this code, but it doesn't work:
$builder->add('name','text',array(
'label' => 'Due Date',
));
the problem i have in fosuserbundle, i have overring form
<?php
namespace Acme\UserBundle\Form\Type;
use Symfony\Component\Form\FormBuilder;
use FOS\UserBundle\Form\Type\RegistrationFormType as BaseType;
class RegistrationFormType extends BaseType
{
public function buildForm(FormBuilder $builder, array $options)
{
// add your custom field
$builder->add('name','text',array(
'label' => 'Due Date',
));
parent::buildForm($builder, $options);
}
public function getName()
{
return 'acme_user_registration';
}
}
but not work, not give me any error and set the label "fos_user_registration_form_name"
A: You see label as fos_user_registration_form_name, because FOSUserBundle uses translations files to translate all texts in it.
You have to add your translations to file called like Resources/translations/FOSUserBundle.nb.yml (example for norwegian) or you can modify translations file coming with the bundle (copying it to Acme\UserBundle is a better way).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/9354988",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: PLSQL procedure error I get the below error while executing code
create or replace
function contact_restriction_function(obj_schema varchar2, obj_name varchar2)
return varchar2 is
v_contact_info_visible hr_user_access.contact_info_visible%type;
begin
-- Here you can put any business logic for filtering
select nvl(max(contact_info_visible),'N')
into v_contact_info_visible
from hr_user_access
where user_name = user;
-- SQL filter / policy predicate
return ''''||v_contact_info_visible||''' = ''Y'' ';
end;
/
after show erros command i got this
show errors
Errors for FUNCTION CONTACT_RESTRICTION:
LINE/COL ERROR
-------- -----------------------------------------------------------------
3/1 PLS-00103: Encountered the symbol "?" when expecting one of the
following:
begin function pragma procedure subtype type
current cursor delete
exists prior external language
This is the remaining code:
begin
dbms_rls.add_policy(object_schema => 'HR' ,
object_name => 'EMPLOYEES' ,
policy_name => 'Contact_Restriction_Policy' ,
policy_function => 'contact_restriction_function' ,
sec_relevant_cols=>'EMAIL,PHONE_NUMBER'Contact Info ,
sec_relevant_cols_opt=>dbms_rls.all_rows);
end;
below is the actual code which i am executing before show errors:
create or replace function contact_restriction(obj_schema varchar2, obj_name varchar2)
return varchar2
is
v_contact_info_visible IN user_access.contact_info_visible%type;
begin
select nvl(max(contact_info_visible),'N')
into v_contact_info_visible
from user_access where username = user;
return 'v_contact-info_visible ='|| 'Y';
end;
A: Your original question shows an error message referring to "?", but the code yout posted a as comment would raise a similar error for `"IN"' instead:
2/24 PLS-00103: Encountered the symbol "IN" when expecting one of the following:
That is because you've used IN for a local variable; but IN, OUT and IN OUT are only applicable to stored procedure parameters. You could have declared the function with an explicit IN for example, though it is the default anyway:
create or replace function contact_restriction(obj_schema IN varchar2, ...
So that needs to be removed from the v_contact_info_visible declaration. You've linked to an example you're working from, but you've removed a lot of important quotes from that, which will still cause it to fail when executed as a part of a VPD; because v_contact_info_visible will be out of scope to the caller. And you have a typo, with a hyphen instead of an underscore.
You need something like:
create or replace function contact_restriction(obj_schema varchar2,
obj_name varchar2)
return varchar2 is
v_contact_info_visible user_access.contact_info_visible%type;
begin
select nvl(max(contact_info_visible),'N')
into v_contact_info_visible
from user_access
where username = user;
return ''''||v_contact_info_visible ||''' =''Y''';
end;
/
When called, that will return a string which is either 'N'='Y' or 'Y'='Y'. VPD will include that as a filter in the original query, which will either prevent any rows being returned (in the first case) or have no effect and allow all rows that match any other existing conditions to be returned (in the second case).
A: The syntax of the function header is incorrect. It should be:
create or replace function contact_restriction(obj_schema IN varchar2, obj_name IN varchar2)
return varchar2
is
| {
"language": "en",
"url": "https://stackoverflow.com/questions/22249293",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: MY SQL Partitioning advice We are currently deciding on a partitioning scheme for a table in our MySQL database. We have multiple shards and we route all of a single users records to one shard. We also want to partition the table itself by userid. We are somewhat new to partitioning and would like some feedback as to which type of partition to use and how often we will likely need to maintain the partition.
We did some simple tests using partitioning by key, linear key, hash and linear hash. In our tests it seems like hash is the fastest option for insertion and it also seems to give us the best distribution using randomly generated userids. While reading the documentation, however, we read that linear hash is better if you want to merge or optimize partitions but we noticed it is a lot slower on insertion. We don’t really understand why we would ever need to merge or optimize partitions so we aren’t sure how much of a consideration this should be.
Also… we are planning to use the maximum number of partitions (1000 I think) because we don’t see any negative to this approach and it should give us the best performance by limiting the number of records per partition to the maximum degree. Is there anything we should be considering when deciding on the number of partitions or is ok to simply use 1000 partitions?
Does anybody have any advice on this?
A: So for anybody who may be interested about this topic , here is my experience :
We finally decided not to use MYSQL portioning and instead using database sharding.
The reason for that is: no matter how good you implement the portioning there is still the fact that data needs to indexed and brought into the memory when needed and for our system which is handling up to 500,000 user's emails this can simply become a major hardware issue over the time as people receive mail and will force you to buy more expensive hardware .
Also there is another hidden cost in MYSQL which is the altering tables schema which can simply become impossible if you have a big table and limited resources. After using MSSQL and Oracle in real world scenario I was NOT really impressed by the way MYSQL handles metadata updates and indexing.
So the short answer would be do not use portioning for you database unless you are sure that you won't have major schema changes to your table/indexes and also your table will not grow too big.
Although I have to say if you design a good index for your system(be very careful with primary keys because that is your clustered index in MYSQL and your queries will be much more efficient if you query on primary key index) you may not really need portioning at all (right now on one of our installations we have a table with +450,000,000 records and it is very fast when you use the primary key index to query the data)
Another point is if there is a chronology in your data and you always have a date range to query it is good idea to use partitioning if your database does not grow too big and if you are intending to delete the old data after a while (like a log rotation,...) partitioning may be the best option because you can simply drop the partition instead of writing a delete process.
Hope this will help you making the right decision.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/29852549",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Converting IF statement to VBA with Variables I am trying to convert the following IF statement into text that will be filled into a cell through VBA:
=IF(XLOOKUP(N7,'EDL Filter'!R2:R660,'EDL Filter'!AA2:AA660)="YES","Port Specific",XLOOKUP(N7,'EDL Filter'!R2:R660,'EDL Filter'!AB2:AB660) )
I've tried splitting it up as I have with other Xlookup statements below:
ActiveCell = "=IF(XLookUp(N" & SafetyRow2 & ",'EDL Filter'!R2:R660,'EDL Filter'!AA2:AA660)=""Yes"",""Port Specific"", Xlookup(N" & SafetyRow2 & ",'EDL Filter'!AB2:AB660))"
However, I keep getting Run-time Error '1004': Application-defined or object-defined error.
The variables have been defined and used earlier in my code without issue, but I am still new to VBA so I might be missing something obvious.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75228831",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: MongoDB: Remove JSON from Array in a Document I want to remove json from an array in a document.
My document is this:
{
"_id" : ObjectId("5c2f9a15a372ef8825b18736"),
"class_section" : [
{
"class_id" : "1",
"section_id" : "A"
},
{
"class_id" : "2",
"section_id" : "A"
}
],
"registered_time" : ISODate("2019-01-04T17:38:29.753Z"),
"__v" : 0
}
I need this following after removing "class_id": "2" and "section_id": "A" with both the conditions
{
"_id" : ObjectId("5c2f9a15a372ef8825b18736"),
"class_section" : [
{
"class_id" : "1",
"section_id" : "A"
}
],
"registered_time" : ISODate("2019-01-04T17:38:29.753Z"),
"__v" : 0
}
How can I do this in MongoDB?
A: Try updating the document by using $pull operator
collection.update(
{},
{ $pull: { "class_section": { class_id: '2' } } }
);
Please refer to mongo documentation of $pull operator here
| {
"language": "en",
"url": "https://stackoverflow.com/questions/54144134",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: React Native Voice error on some Android phones In one of the devices (Redmi 8A), I have the output of
Voice.getSpeechRecognitionServices() ==> ["com.xiaomi.mibrain.speech"] and voice recognising is not working.
Voice.start() ==> undefined but
Voice.isAvailable() ==> true
Voice.isRecognizing() ==> true
but none of the following events are triggered,
Voice.onSpeechResults
Voice.onSpeechStart
Voice.onSpeechEnd
Voice.onSpeechError
Voice.onSpeechPartialResults
I tried again after installing Google App and now the device returns ["com.google.android.googlequicksearchbox", "com.xiaomi.mibrain.speech"] for Voice.getSpeechRecognitionServices() but voice is still not working. Permission is granted and I can record and play using @react-native-community/audio-toolkit.
In the logcat:
SpeechRecognizer: bind to recognition service failed
ActivityManager: Unable to start service Intent { act=android.speech.RecognitionService cmp=com.miui.voiceassist/com.xiaomi.mibrain.speech.asr.AsrService } U=0: not found
Have anyone faced the similar issue and solved this? Any suggestions?
The device is running:
*
*Android Version 9
*MIUI 11.0.3
*Redmi 8A
A: Found out that even if you have Google services, some android phones can be configured to use other voice recognising services and it can break the flow as React Native Voice is using Google Services.
You can check which Voice services a particular Android Phone is using as following:
Settings > App Management > Default App > Assistive App and Voice Input > Assistive App
Hope this is helpful for those who might be facing the same issues.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/62596853",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to use Commands to react to a ListBox I'm trying to learn Commanding and have set up a simple wpf project to use a custom command. I have a ListBox and a Button on a Window. When the ListBox has the focus and an Item is selected, I want the Button to be enabled, otherwise it should be disabled.
I define a CustomCommand in a separate CustomCommands class:
Public Shared ReceivedFocus As New RoutedCommand
and in my Window I set it up as follows:
<CommandBinding
Command="{x:Static local:CustomCommands.ReceivedFocus}"
CanExecute="CanActivate"
Executed="ChangeSelection">
</CommandBinding>
and use the command for the ListBox as follows:
<ListBox
x:Name="lstInactive">
<i:Interaction.Triggers>
<i:EventTrigger
EventName="GotFocus">
<i:InvokeCommandAction
Command="{x:Static local:CustomCommands.ReceivedFocus}"
</i:InvokeCommandAction>
</i:EventTrigger>
</i:Interaction.Triggers>
</ListBox>
and, finally, the CanActivate routine is:
Private Sub CanActivate(sender As Object, e As CanExecuteRoutedEventArgs)
If lstInactive.SelectedIndex >= 0 Then
e.CanExecute = True
Else
e.CanExecute = False
End If
End Sub
This is not working. The major problem is that I don't understand how to relate the CanExecute value to the Button. Should I ignore the CanExecute value in the CanActivate routine and instead just set the Enabled property of the Button? If so, what is the value of the CanExecute paramter of the CanExecuteRoutedEventArgs?
A second problem is that the GotFocus event is not firing until I select an item in the ListBox a second time.
Or maybe I don't have a grasp on Commanding at all and this is not the right approach. This small project is not important in itself, it is intended to make sure I understand Commanding after reading numerous articles about it before I start to use Commands in "real" projects. Sadly, at this stage it is clear I don't.
A:
This is not working. The major problem is that I don't understand how to relate the CanExecute value to the Button.
Bind its Command property to the same command:
<Button Content="Button" Command="{x:Static local:CustomCommands.ReceivedFocus}" />
The Button should then be enabled or disabled based on the value that you set the CanExecute property to in your CanActivate event handler.
You probably also want to listen to the SelectionChanged event. This works as expected:
<StackPanel>
<StackPanel.CommandBindings>
<CommandBinding
Command="{x:Static local:CustomCommands.ReceivedFocus}"
CanExecute="CanActivate"
Executed="ChangeSelection">
</CommandBinding>
</StackPanel.CommandBindings>
<ListBox x:Name="lstInactive">
<ListBoxItem>first</ListBoxItem>
<ListBoxItem>second</ListBoxItem>
<ListBoxItem>third</ListBoxItem>
<i:Interaction.Triggers>
<i:EventTrigger EventName="SelectionChanged">
<i:InvokeCommandAction Command="{x:Static local:CustomCommands.ReceivedFocus}">
</i:InvokeCommandAction>
</i:EventTrigger>
</i:Interaction.Triggers>
</ListBox>
<Button Content="Button" Command="{x:Static local:CustomCommands.ReceivedFocus}" />
</StackPanel>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void CanActivate(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = lstInactive.SelectedIndex >= 0;
}
private void ChangeSelection(object sender, ExecutedRoutedEventArgs e)
{
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/47533919",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Problems with tbb in native dll called from multi-threaded .net application? We have a native .dll that does some HPC type calculations using Threading Building Blocks 4.4 to manage parallelism. This .dll is called from a .Net desktop program that is itself multi-threaded. I'm a novice at tbb, and I was wondering if this kind of set-up was inviting some issues. My use of tbb is pretty basic-- I'm just calling parallel_reduce to do one particular calculation. I'm not explicitly setting up the tbb threadpool; I'm relying on the default initialization for that.
When we do system tests we are seeing some intermittent process hangs. We are not seeing these when we test the native dll in isolation, so I expect a minimal example that demonstrates the problem would be difficult to construct. I'm hoping someone more familiar with tbb than I might be able to suggest if there is likely to be an intrinsic problem in this usage scenario.
Everything is running on Windows 10 on x86-64 platform, by the way.
A: The answer to my question appears to be that there is no problem; Threading Building Blocks can work fine in this scenario. Eliminating the parallel_reduce didn't change the behavior, and further investigation shows that the problem was confined to the managed code; didn't have anything to do with TBB at all.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/37058663",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Dynamically creating Expression Blend controls in WPF C# I have created a button in Expression Blend 4. I want to dynamically create instances of this button at run time.
The code for the button is below:
<Button Content="Button" HorizontalAlignment="Left" Height="139" Margin="46,107,0,0" VerticalAlignment="Top" Width="412" Grid.ColumnSpan="2">
<Button.Background>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="Black"/>
<GradientStop Color="White" Offset="1"/>
</LinearGradientBrush>
</Button.Background>
</Button>
In addition to the supplying the code can you put comments in explaining what you are doing so that I can learn the general principle.
I know this is a simple question so I have been reading up places such as: Expression blend & WPF, Is there a way to "extract" WPF controls of Expression Blend?, and http://social.msdn.microsoft.com/forums/en-US/wpf/thread/ffa981b8-9bba-43a2-ab5e-8e59bc10fc0d/ unfortunately none of these have helped.
A: In your WPF application you should have a App.xaml file, in there you can add Styles that are to be used thoughout your UI.
Example:
<Application x:Class="WpfApplication8.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
StartupUri="MainWindow.xaml">
<Application.Resources>
<!--The style for all your buttons, setting the background property to your custom brush-->
<Style TargetType="{x:Type Button}"> <!--Indicate that this style should be applied to Button type-->
<Setter Property="Background">
<Setter.Value>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="Black"/>
<GradientStop Color="White" Offset="1"/>
</LinearGradientBrush>
</Setter.Value>
</Setter>
</Style>
</Application.Resources>
</Application>
Or if you dont want to apply to all buttons, you can give your Style a Key so you can apply to certain Buttons in your UI
<Application x:Class="WpfApplication8.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
StartupUri="MainWindow.xaml">
<Application.Resources>
<!--Add a x:Key value so you can use on certain Buttons not all-->
<Style x:Key="MyCustomStyle" TargetType="{x:Type Button}">
<Setter Property="Background">
<Setter.Value>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="Black"/>
<GradientStop Color="White" Offset="1"/>
</LinearGradientBrush>
</Setter.Value>
</Setter>
</Style>
</Application.Resources>
</Application>
To use this Style on a Button, just add a binding to the Style property of the Button
<Button Style="{StaticResource MyCustomStyle}" />
this will apply the Style just to this Button
Or if you really want to do it in code behind you can just add the Brush you want to the background
Button b = new Button
{
Background = new LinearGradientBrush(Colors.Black, Colors.White, new Point(0.5, 1), new Point(0.5, 0))
};
its very easy to translate xaml to code because xaml uses the exact same property names, like the code brush I posted above:
new LinearGradientBrush(Colors.Black, Colors.White, new Point(0.5, 1), new Point(0.5, 0))
is ....
Brush(firstColor,secondColor,StartPoint EndPoint)
Xaml just accesses properties in the button, they will all have the same names in C#.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/14015617",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Capturing Self in a double block with ARC I recently learned this trick for when I have to reference self within a block.
__weak MyObject *safeSelf = self;
[self doWithCompletionBlock:^{
HMFInventoryBatchItemsController *strongSelf = safeSelf;
if (strongSelf) {
[strongSelf doSomethingElse];
}
}];
But I've been wondering, what if I have a block within a block? Do I need to do the same thing again?
__weak MyObject *safeSelf = self;
[self doWithCompletionBlock:^{
HMFInventoryBatchItemsController *strongSelf = safeSelf;
if (strongSelf) {
__weak MyObject *saferSelf = strongSelf;
[strongSelf doAnotherThingWithCompletionBlock:^{
HMFInventoryBatchItemsController *strongerSelf = saferSelf;
if (strongerSelf) {
[strongerSelf doSomethingElse];
}
}];
}
}];
Or is this fine
__weak MyObject *safeSelf = self;
[self doWithCompletionBlock:^{
HMFInventoryBatchItemsController *strongSelf = safeSelf;
if (strongSelf) {
[strongSelf doAnotherThingWithCompletionBlock:^{
[strongSelf doSomethingElse];
}];
}
}];
A: The good answer is, it depends. It's in general unsafe to do:
__weak MyObject *safeSelf = self;
[self doWithCompletionBlock:^{
[safeSelf doAnotherThingWithCompletionBlock:^{
[safeSelf doSomethingElse];
}];
}];
The reason for that, is that when you call -doAnotherThingWithCompletionBlock if that method thinks it holds a reference on self, which a selector usually assumes, and it dereferences self to access ivars, then you will crash, because you actually don't hold a reference.
So whether you need to take a new weak reference or not depends on the lifetime semantics you need/want.
EDIT:
By the way, clang even has a warning about that issue that you can enable in Xcode with the CLANG_WARN_OBJC_RECEIVER_WEAK setting (CLANG_WARN_OBJC_REPEATED_USE_OF_WEAK is also useful while we're at it)
A: __block MyObject *safeSelf = self;
[self doWithCompletionBlock:^{
[safeSelf doAnotherThingWithCompletionBlock:^{
[safeSelf doSomethingElse];
}];
}];
Hope it will do what it should normally does. Tell the compiler not to retain the __weak MyObject* no matter in which block scope it is. The fact is i didn't tested. Meanwhile I'll be surprised if it will actually retain MyObject *
| {
"language": "en",
"url": "https://stackoverflow.com/questions/20125219",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: C++ and undefined reference to XML_Parser i have the following problem, i need use expat.h library, i include the library normally:
#include <expat.h>
But when i try to create a object
XML_Parser Parser = XML_ParserCreate(NULL);
Eclipse keppler return undefined reference to XML_ParserCreate . I check the library and is included.
I work with ubuntu 13.04 and g++ compiler.
any idea?
A: Probably you didn't link with the library. You should add this -lexpat to the compiler`s command line. For example:
g++ main.cc -lexpat -o exe
A more advanced (and more easy to use, when you get up to speed) option would be to use pkg-config as e.g. $(pkg-config --libs expat).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/18540608",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How can i iterate Arraylist of an object in Kotlin? I have a arrayList of an object , and i cannot iterate my list forward or reward , i don't want to display my message in these case but it does .
private fun handleLivePopUp() { // vous êtes en direct
val id = presenter.programItems?.indexOf(presenter.currentProgram)
// val it = presenter.programItems?.listIterator()
// val previous = if (id == 0) presenter.programItems!!.size - 1 else id?.minus(1)
if (id != null){
if(id == 0){ //si liste == +1 ou liste == -1 on affiche pas
binding.playerController.startOverImg.setImageDrawable(ContextCompat.getDrawable(this,R.drawable.ic_startover))
binding.playerController.startOverToast.visibility = View.GONE
binding.playerController.startOverLiveToast.visibility = View.VISIBLE
// presenter.programItems!!.size - 1
} else if(id == id - 1 || id == id + 1){
binding.playerController.startOverImg.setImageDrawable(ContextCompat.getDrawable(this,R.drawable.ic_startover))
binding.playerController.startOverLiveToast.visibility = View.GONE // apparait visible à chaque swipe
binding.playerController.startOverToast.visibility = View.GONE
}
}
This is the code i'm trying to do
| {
"language": "en",
"url": "https://stackoverflow.com/questions/72986333",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: login using ssh on multiple user accounts using the same id_rsa and id_rsa.pub i have an id_rsa and id_rsa.pub . say i have 5 users on the same machine. i want to use the same id_rsa and id_rsa.pub to ssh between users without password. is it possible ? As i figure it out if user1 wants to do ssh user2@localhost .../home/user2/.ssh must have a file named authorized_keys with the content of id_rsa.pub. and /home/user1/.ssh must have the id_rsa file. so by doing this user1 can do ssh user2@localhost.
But if user2 wants to do ssh user1@localhost then user1 must have the authorized_keys having the contents of id_rsa.pub and user2 must have the id_rsa file
to sum it up user1 has : authorized_key, id_rsa and user2 has the same files.
what happens on my machine is: user1 can do ssh user2@localhost but user2 cannot do user1@localhost.
is there something missing ? is there something i do not understand ? is it possible to ssh between users using the same id_rsa and the same id_rsa.pub ?
A: File permissions on a user's /home/user/.ssh directory must be 700, and the /home/user/.ssh/authorized_keys must be 600. Meanwhile, it is essential that all files in each .ssh directory are owned by the user in whose home directory they reside. To change ownership recursively, you can:
chown -R username:username /home/username/.ssh
If you have multiple users and need to do this for each of them, you can use this loop:
for SSHUSER in user1 user2 user3 user4 user5; do
# Add the authorized_keys file if it doesn't already exist
touch /home/$SSHUSER/.ssh/authorized_keys
# Set its permissions
chmod 600 /home/$SSHUSER/.ssh/authorized_keys
# Set directory permissions
chmod 700 /home/$SSHUSER/.ssh
# Set ownership for everything
chown -R $SSHUSER:$SSHUSER /home/$SSHUSER/.ssh
done;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/6139978",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How should this be done? (returing a collection of values) I am writing a weather API to connect to the NOAA's XML METARS in C# NETMF. Before, this API was written in PHP, where I was able to use an associative array to return the weather parameters. For example, the return of the getWX() function might have been
Array(
"temp_f" => "70.0",
"windchil" => "65.0",
"wind_dir" => "90"
);
I am trying to replicate that same functionality in my CSharp version, but I am not sure how to go about doing it. Since I am using NETMF, I cannot use a hashtable.
Should I use a struct instead?
In case anyone wants to see the code behind the original PHP API, it is here: http://www.chrisseto.com/wordpress/?p=17
I am trying to get the CSharp version to be as similar as possible.
Thanks!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/2971342",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to Apply Masked SVG Patterns using Coord System of ObjectBoundingBox I am writing inline SVG code for a data visualization and I'm trying to apply a <mask> which I filled with a <pattern> to multiple SVG <rect> elements.
I can't find a combination of patternUnits, patternContentUnits, maskUnits and maskContentUnits that makes the mask filling 100% of each rect it gets applied to without stretching the pattern. Is it even possible? The pattern itself is not that complicated and should look like this: correct pattern dimensions applied
Due to performance optimization I wan't the <defs> tag to live in a separate svg at root level of my component.
#my-defs {
position: absolute;
top: -1000px;
left: -1000px;
}
#my-svg {
width: 200px;
height: 3em;
}
#my-svg rect {
width: 100%;
height: 80%;
}
<svg id="my-defs">
<defs>
<pattern id="diagonal-hatch-pattern" patternUnits="userSpaceOnUse" width="4" height="4">
<path d="M-1,1 l2,-2 M0,4 l4,-4 M3,5 l2,-2" stroke="white" strokeWidth="1" />
</pattern>
<mask id="diagonal-hatch-mask" x="0" y="0" width="1" height="1" maskContentUnits="objectBoundingBox">
<rect fill="url(#diagonal-hatch-pattern)" x="0" y="0" width="1" height="1" />
</mask>
</defs>
</svg>
<svg id="my-svg">
<rect fill="steelblue" mask="url(#diagonal-hatch-mask)" />
</svg>
A: I could get it to work by changing maskContentUnits back to its default value of userSpaceOnUse but that doesn't feel right because of the static dimensions i would have to assign to the mask shape. It would be much better if the rect in my mask would scale to each object the mask gets applied to.
So, if anyone has a better solution, I would be very thankful...
#my-defs {
position: absolute;
top: -1000px;
left: -1000px;
}
#my-svg {
width: 200px;
height: 3em;
}
#my-svg rect {
width: 100%;
height: 80%;
}
<svg id="my-defs">
<defs>
<pattern id="diagonal-hatch-pattern" patternUnits="userSpaceOnUse" width="4" height="4">
<path d="M-1,1 l2,-2 M0,4 l4,-4 M3,5 l2,-2" stroke="white" strokeWidth="1" />
</pattern>
<mask id="diagonal-hatch-mask" x="0" y="0" width="1" height="1" maskContentUnits="userSpaceOnUse">
<rect fill="url(#diagonal-hatch-pattern)" x="0" y="0" width="9000" height="9000" />
</mask>
</defs>
</svg>
<svg id="my-svg">
<rect fill="steelblue" mask="url(#diagonal-hatch-mask)" />
</svg>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/58979707",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.