text:
Q: Get access to MemoryFile from Service My idea is when the user closes the application I want to save a custom file format that includes a image that the user previously opened, and some other properties inside that custom file. To store the image and every other property I use Bytes. The file have to be stored when the method onPause() is called, this is the method the Android team suggest to store any data.
Since code run inside method onPause() is executed on the main thread and the method is called when the user is about to close the application. But what if then he decides to go back to the application, and since the file is big and all the code is done on the main thread the UI freezes. I cannot run the code in to a separate thread, because if the user closes the   application and the thread get destroyed before his work is save, it will be lost.
The pixels for the image are stored as ByteArray , and the overall memory for the array is around 3-7 MB
To keep saving the file on separate thread even when the application is already destroyed I use ForegroundService, with message to the user that his work is now being saved. The problem comes when I try to save the ByteArray, since it is a large in size 3-7 MB and there is limitation when using parcelable data.
I have read this question, and there was a suggestion to use Memory File. I manage to access the byte array in the service, but to do that I first created a Bundle and then add Binder to it. The binder have a method that gives access to the memory file. I have two questions, my first question is if that is the correct way to do it? And my second question is if there are better way to transfer large arrays from activity/fragment to a service with some example code if possible?
Here is the code for class SaveProjectService:
class SaveProjectService : Service() {

    abstract class LocalBinder : Binder() {
        abstract fun getMemoryFile(): MemoryFile
    }

    override fun onCreate() {
        super.onCreate()
    }

    override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {

        val bitmapInfo = intent.getBundleExtra("imageBundle")
        if (bitmapInfo != null) {

            val memoryFile = (bitmapInfo.getBinder("imageBinder") as LocalBinder).getMemoryFile()
            val byteArray = memoryFile.inputStream.readBytes()  // here I manage to get the array values
            memoryFile.close()
        }

        thread {
           // here I save the file
        }

        return START_STICKY
    }

    override fun onDestroy() {
        super.onDestroy()
    }

    override fun onBind(intent: Intent): IBinder? {
        return null
    }
}

Here is the code for creating the service in MainActivity
class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }

    override fun onPause() {

        // create intent
        val serviceIntent = Intent(context, SaveProjectService::class.java)

        // create memory file
        val memoryFile = MemoryFile("image", helper.bitmapInfo.last().bitmapByteBufferData.size)
        memoryFile.outputStream.write(helper.bitmapInfo.last().bitmapByteBufferData)

        // create binder object that return the memory file
        val binder = object : SaveProjectService.LocalBinder() {
               override fun getMemoryFile(): MemoryFile {
                     return memoryFile
               }
        }

        // set binder->bundle->service
        val bundle = Bundle()
        bundle.putBinder("imageBinder", binder)
        serviceIntent.putExtra("imageBundle", bundle)
        ContextCompat.startForegroundService(context!!, serviceIntent)

        super.onPause()
    }

}


text:
Q: Observable Collection not updating datagrid upon linq I have a datagrid and textbox in my application. I will provide a number in textbox and upon clicking the button I want the datagrid to get the data from the given number. The datagrid's Itemsource is a ObservableCollection. The problem is datagrid not updating When i click the button.
I'm learning wpf.  I have a datagrid which is a ObservableCollection. The data for the datagrid is populated via the sql query. The Binding to datagrid works fine. I searched online and found that with linq we can search the collection and get the data but the datagrid doesn't reflect any changes.
ModelClasstab.Where(d => d.claimnumber == "123456712");

In the above I have hardcoded the textbox data to check whether the condition works
Window.xaml
<Label Width="69" Height="23.277" HorizontalAlignment="Left" Margin="1,-10,30,0" VerticalAlignment="Top" Content="From Date"/>
<TextBox HorizontalAlignment="Left" Width="113" Height="19.277"  Margin="-200,1,-228.962,0"  x:Name="txtboxComments"/>
<Button  Command="{Binding dataSearch}" Margin="300,-20,30,0" Width="60" Height="23.277"  Content="Search"></Button>
<DataGrid x:Name="datagrid" ItemsSource="{Binding ModelClasstab}" AutoGenerateColumns="True" CanUserAddRows="False" Height="350" Width="365" Margin="5" HorizontalAlignment="Left"/>

ViewModel.cs :
   public class ViewModel
  {
    public RelayCommand dataSearch { get; set; }
    public ObservableCollection<tabpageAuditInformationModel> ModelClasstab {get; set;}

    public ViewModel()
  {
    FillList();
    dataSearch = new RelayCommand(o => Search());
  }

 public void Search()
    {
     ModelClasstab.Where(d => d.claimnumber == "123456712");
    }

public void FillList()
    {
        string connectionString = "Data Source=192.168.6.102; Initial Catalog=Operations Productivity Tool;Integrated Security=SSPI;";

        string sql = "SELECT distinct Date_Audited as Date , claimNumber as
 claimnumber,Audit_id,[Start Time],[End Time],[Total Time] as
 [Total_time_taken(Mins)] , [Final Status] as finalstatus " +
" FROM dbo.[opcod Audit Information]" +
            //or date = dateadd(day,-1,cast(getdate() as date))) " +"where userName = 'rengar2' ";

        using (var connection = new SqlConnection(connectionString))
        {
            connection.Open();
            using (var command = new SqlCommand(sql, connection))
            {

                try
                {

                    adapter = new SqlDataAdapter(command);
                    ds = new DataSet();
                    adapter.Fill(ds, "tblCountries");

                    if (ModelClasstab == null)
                        ModelClasstab = new ObservableCollection<tabpageAuditInformationModel>();

                    foreach (DataRow dr in ds.Tables[0].Rows)
                    {
                        var month = Convert.ToDateTime(dr[0]).Month;
                        var year = Convert.ToDateTime(dr[0]).Year;
                        var day = Convert.ToDateTime(dr[0]).Day;

                        ModelClasstab.Add(new tabpageAuditInformationModel
                        {
                            claimnumber = dr[1].ToString(),
                            Date = string.Format("{0}/{1}/{2}", month, day, year),
                            Starttime = dr[3].ToString(),
                            EndTime = dr[4].ToString(),
                            TotalTime = dr[5].ToString()
                        });

                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
            }
        }
    }
     }

Model.Cs
 public class tabpageAuditInformationModel
  {
   public String Date
   { get; set; }

   public String claimnumber
   { get; set; }

   public String Starttime
   { get; set; }

   public String EndTime
   { get; set; }

   public String TotalTime
   { get; set; }

}

Edit : After reading the comments, I assigned the value to  a variable and remove all the items in the collection and add only the selected data into the list. Here i cant able to run two foreach at the same time. The breakpoint is not going into the second forloop at all. I'm not sure about my approach. Let me know if there is any better approach.
         var d1 = ModelClasstab.Where(d => d.claimnumber == "123456712");
                    foreach (var a1 in ModelClasstab.ToList())
                        ModelClasstab.Remove(a1);
                    foreach (var a in d1.ToList())
                        ModelClasstab.Add(new tabpageAuditInformationModel
                        {
                            claimnumber = a.claimnumber,
                            Date = a.Date,
                            Starttime = a.Starttime,
                            EndTime = a.EndTime,
                            TotalTime = a.TotalTime
                        });

                }

A: With Collection.Where clause you don't modify the collection, so you don't see any changes in the DataGrid.
One of the many possibilities is to hold your DB data in some variable and set in Search the ModelClasstab property:
public void Search()
{
    ModelClasstab=new ObservableCollection<tabpageAuditInformationModel>(DbData.Where(d => d.claimnumber == "123456712"));
}

For such a way ModelClasstab don't need to be an ObervableCollection and (!) your ViewModel has to implement INotifyPropertyChanged.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why logs both of console and file? I'm using Java util logging and getting logger object via this code:
public static Logger getLoggerForMemberSaving(Class<?> clazz) {
        Logger logger = Logger.getLogger(clazz.getName());
        try {
            Handler fileHandler = new FileHandler("./oneMemberSaving.log");
            Formatter simpleFormatter = new SimpleFormatter();
            fileHandler.setFormatter(simpleFormatter);
            logger.addHandler(fileHandler);
        } catch (Exception ex) {
            logger.log(Level.SEVERE, "An error occured while getting logger object. Error is:" + ex.getMessage());
        }
        return logger;
    }

And, I'm using the logger object like this:
public void addOneMember(Member member) {
        Logger LOGGER = LoggingUtil.getLoggerForMemberSaving(this.getClass());
        try {
            LOGGER.log(Level.INFO, "One member adding method is running!");
            memberRepository.save(member);
            LOGGER.log(Level.INFO, "Member saving is successfull. Member info is:" + member);
        } catch (Exception ex) {
            LOGGER.log(Level.SEVERE, "An error occured while saving member. Error is:" + ex.getMessage());
        }

    }

When I run addOneMember method, the logs at the IDE console and in the file. But I want to see log messages only in the log file.
How can I do this? How can I prevent logging to the IDE console?


text:
Q: Add image path to .txt file I have created the Python script below which prompt I receive the following error when I run it.
Average=mean(diff)
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.2032.0_x64__qbz5n2kfra8p0\lib\statistics.py", line 315, in mean
    raise StatisticsError('mean requires at least one data point')
statistics.StatisticsError: mean requires at least one data point

However, lines 9, 10 and 17 work fine when I comment out the rest of the script. And, the rest of the script works fine when I comment out lines 9, 10 and 17. What am I doing wrong?
import csv
from statistics import mean
PyBank_file=r"PyBank\Resources\budget_data.csv"

with open(PyBank_file, 'r') as csvfile:
    csvreader=csv.reader(csvfile,delimiter=',')

    for row in csvreader:
        # months=[row[0] for row in csvreader]
        # Total_Months=len(months)
        amounts=[int(row[1]) for row in csvreader]
        Total_Profits_Losses=sum(amounts)
        diff=[amounts[i+1]-amounts[i] for i in range(len(amounts)-1)]
        Average=mean(diff)
        Greatest_Increase=max(diff)
        Greatest_Decrease=min(diff)
        # print(Total_Months)
        print(Total_Profits_Losses)
        print(Average)
        print(Greatest_Increase)
        print(Greatest_Decrease)

A: Remove the outer for row in csvreader:. You can only iterate over csvreader once, the list comprehension for amounts uses it all up, and you have no reason to loop over the rows like that. In fact if you uncomment the comprehension for months you will have to convert the reader to a list beforehand and use that list instead.
with open(PyBank_file, 'r') as csvfile:
  csvreader = csv.reader(csvfile, delimiter=',')
  rows = list(csvreader)

months=[row[0] for row in rows]
amounts = [int(row[1]) for row in rows]


text:
Q: Servlets and html issue I am attempting to learn how to use a querystring. My goal is to modify a servlet and from that be able to pull data from a querystring in my URL. I specifically need to show the "action". My URL querystring is to be entered as
?param1=val1&param2=val2. I attempted to modify my servlets processRequest with the following line:
out.println("
" + request.getParameter("
 Action is"  [value] "
") +
);

Any ideas of where to go from here? I'm getting several errors.

A: You are retrieving invalid values from the request parameters.
More specifically, based on your querystring you should retrieve the parameters param1 and param2, which will contain values val1 and val2 respectively, like so:
String p1 = request.getParameter("param1");
String p2 = request.getParameter("param2");
System.out.println("params: 1:"+p1+" 2:"+p2);


text:
Q: Zip content is cleared after downloading it in php The Problem is that when downloading the zip, its content gets deleted.
I use this code to create the zip and add the files to it:
    $zipName = "full path";
    $zip = new ZipArchive();
    $zip->open($zipName, ZipArchive::CREATE);
    for ($i = 0; $i < $length; $i++) {
        if ($ausgabeArray[$i]["filePath"] != '') {
            $zip->addFromString(basename($ausgabeArray[$i]["filePath"]), file_get_contents($ausgabeArray[$i]["filePath"]));
        }
    }
    $zip->close();
    for ($i = 0; $i < $length; $i++) {
        unlink($ausgabeArray[$i]["filePath"]);
    }

And I use this code to download the zip:
        header("Content-disposition: attachment; filename=" . $name);
        header("Content-type: application/".$endung);
        readfile($path);
        unlink($path);
        //name = basename from the path of the zip
        //path = full path to the zip
        //endung = zip

This worked fine on the old server, but after changing it, it stopped working. I stopped the code once before readfile($path); and viewed the zip in the folder and downloaded it from there, everything worked fine this way, but this is of course no option for anybody who has no permission for the server directories.
We use this server:

*

*Ubuntu 20.04.2 LTS

*Apache/2.4.41 (Ubuntu)

*7.3.29 FPM-Application

I'm not sure if the problem has anything to do with the server change or just my code, but I didn't change a thing, and now it is not working any more, so I think it is possible.
I hope someone had this problem before and can help me. Thanks!


text:
Q: Fastest way to go through a long list of arrays I have a data set from electrophysiological recordings in a hdf5 file in the form of what is really close to numpy arrays from my understanding and what I am trying to do is access it in the most efficient and fast way.
Let me explain: The dataset is a list of arrays (2D-array?); each array contains x number of channels (recording sites), usually around 32-64.
The problem is the following: There are millions of arrays and it's taking forever to loop through every individual array. Moreover, I have to loop through each channel in each array in order retrieve the values.
Here is my code:
import h5py

f_kwd = h5py.File("experiment1_100.raw.kwd", "r") # reads hdf5 file
dset_data = f_kwd['recordings/0/data']
print (len(dset_data)) # prints 31646700
print (dset_data[0]) # prints the following

[    94   1377    208    202    246    387   1532   1003    460    665
810    638    223    363    990     78   -139    191     63    630
763     60    682   1025    472   1113   -137    360   1216    297
-71    -35   -477   -498   -541   -557  27776   2281 -11370  32767
-28849 -30243]

list_value = []
for t_stamp in (dset_data):
    for value in t_stamp:
        if value > 400:
            list_value.append(value)

Is there a way to make this a lot more efficient and quick?
Do I have to use numpy and if so, how can I make this happen? I feel like I am doing something wrong here.
EDIT :
Here are some additional info about the  first array in dataset for the following attributes:

.shape -> (42,)
  .itemsize -> 2
  .dtype -> int16
  .size -> 42
  .ndim -> 1

EDIT2 :
..and the dataset itself:

.shape -> (31646700, 42)
  .dtype -> int16
  .size -> 1329161400

A: If my guess that t_stamp is a 1d array of varying length, you could collect all elements >400 with:
list_value = []
for t_stamp in (dset_data):
    list_value.append(t_stamp[t_stamp>400])
    # list_value.extend()

Use append if you want to collect the values in sublists. Use extend if you want one flat list.
It still iterates on the 'rows' of dset_data, but selection from each row will be much faster.
If all rows are 42 long, then dset_data.value will be a 2d numpy array:
dset_data[dset_data>400]

will be a flat array of the selected values

A: this may help. first change nd arry to 1d arry; second sorted it; third find index of number. In this case, you do need iterate all the items.
import numpy as np

newData = dset_data.ravel()
newData.sort()
index = np.searchsorted(data,400)
res = newData[:index ]


text:
Q: pandoc 2.1 YAML metadata and table-of-contents in docx I'm wondering if there is ant way to have the title page, author details, and , that is set in the document YAML metadata block. Ideally, I would want the title page and author details on the first page, the  on the second page, with a level 2 header i.e., ## Abstract, and the table-of-contents preceding the main body of the document.
A similar questions has been asked on this forum previously, but this didn't really resolve my issues (or at least I could see a way to apply it to my question).
I am converting from .md to .docx with a custom .docx template. I am using pandoc 2.1, Scriver 3, with the Scrivomatic+Pandocomatic workflow.
Many thanks in advance.


text:
Q: Reverse for 'edit_post' with arguments '('',)' not found. 1 pattern(s) tried: ['edit_post/(?P\\d+)/$'] enter image description herethe blog_post.html is working properly until the "edit post" link is passed , generating the error above , on the other hand it works if i removed the "blog_id" argument from the url pattern and "blog.id" from the "edit post" link ,but accordingly another error occurs when i click the "edit post" link and open the edit_post.html page it demands the missing (edit_post) argument , if i re-pass the argument again then the url patterns are not matching.
from django.conf.urls import url

from . import views

app_name = 'blogs'

urlpatterns = [
    #index
    url(r'^$',views.index,name='index'),

    #make page for blogposts
    url(r'^blogposts/$',views.blogposts,name='blog_post'),

    #page for making a new post
    url(r'^new_post/$',views.make_post,name='add_post'),

    #page for editing post
    url(r'^edit_post//(?P<blog_id>\d+)$', views.edit_post, name = 'edit_post'),
]

the view page
    from django.shortcuts import render
from django.urls import reverse
from django.http import HttpResponseRedirect
from .models import BlogPost
from .forms import BlogPostForm
def edit_post(request,blog_id):
    post = BlogPost.objects.get(id=blog_id)

    if request.method != 'POST':
        form = BlogPostForm(instance = post)
    else:
        form = BlogPostForm(instance = post, data =request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse('blogs:blog_post'))
    context = {'post':post,'form':form}
    return render(request,'blogy/edit_post.html',context)

the page of the posts
 {% extends "blogy/base.html" %}

{% block content %}

The Posts:

    {% for blog in blogs %}

{{ blog.date_added|date:'M d, Y H:i' }}

{{ blog.text|linebreaks }}

                edit post

        {% empty %}

no posts !

    {% endfor %}

Add a new Post
{% endblock content %}

the page where the edit post link goes
    {% extends "blogy/base.html" %}

{% block content %}

Edit Post:

<form action = "{% url 'blogs:edit_post' blog.id %}" method = 'post'>
    {% csrf_token %}
    {{ form.as_p }}
    <button name='submit'>Save Changes</button>
</form>
{% endblock content %}

A: The issue is that your url is waiting you to pass blog_id variable, but you pass nothing.
Here add blog.id
edit post

A: ok i realized the problem , it should have been (post.id) to be passed not (blog.id) because the name of the variable in the view function was rendered to the html page from the dictionary "context" with the name "post" not "blog"


text:
Q: Python: Problem with raw_input reading a number unfortunately raw_input is not doing what I need it to do. What I am trying to do is get totPrimes = whatever I type in at the prompt. If i replace while count < totPrimes with while count < 50 this script works. If I type 50 into the prompt, this script doesnt work, I'm afraid raw_input isn't the function im looking to use? Here is a snippet of my code:
testNum = 3
div = 2
count = 1
totPrimes = raw_input("Please enter the primes: ")

while count < totPrimes :
    while div <= testNum :

A: Do
totPrimes = int(totPrimes)
while count < totPrimes:
    # code

raw_input gives you a string you must convert to an integer or float before making any numeric comparison.

A: You need to cast totPrimes into an int like this:
integer = int(totPrimes)

A: You just need to convert your raw input in a integer. For your code just change your code as:
testNum = 3
div = 2
count = 1
totPrimes = raw_input("Please enter the primes: ")
totPrimes=int(totPrimes)
while count < totPrimes :
    while div <= testNum :

A: The raw_input function always returns a 'string' type raw_input docs, so we must in this case convert the totPrimes 'string' type to an 'int' or 'float' type like this:
totPrimes = raw_input("Please enter the primes: ")
totPrimes = float(totPrimes)

You can combine them like this:
totPrimes = float(raw_input("Please enter the primes: "))

In order to compare things in python count < totPrimes, the comparison needs to make sense (numbers to numbers, strings to strings) or the program will crash and the while count < totPrimes : while loop won't run.
You can use try/except to protect your program. managing exceptions
For people taking the course "Programming for Everybody" you can take in hours and rate this way. the if/else statement you should try to figure out.

A: You have to change every number to "hrs" or "rate".
For example: 40*10.50+(h-40)*10.50*1.5 is wrong, 40*r+(h-40)*r*1.5 is right.

A: Use input then.
Raw input returns string.
input returns int.


text:
Q: How to show notification in the background in a particular future day using AlarmManager I'm showing a DatePicker to make the user select date in the future, and I want to notify the user one day before the selected date. For example, if the user selects the date [Apr 26, 2020] I want to notify the user in [Apr 25, 2020] even if the app is not running. However, in my case, the notification appears just when the app is running, but when the app is not running notification doesn't work.
This is my MainActivity
class MainActivity : AppCompatActivity() {
    private lateinit var dateFormat: SimpleDateFormat
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        dateFormat = SimpleDateFormat("MMM dd, yyyy", Locale.US)

        edit_text_date.setOnClickListener {
            showDatePicker()
        }
        notify_switch.setOnCheckedChangeListener { buttonView, isChecked ->
            if (isChecked) {
                val deadlineDate = dateFormat.parse(edit_text_date.text.toString())!!
                val c = Calendar.getInstance()
                c.time = deadlineDate
                c.add(Calendar.DATE, -1)
                val pastDay = dateFormat.format(c.time)
                val calender = Calendar.getInstance()
                val currentDate = dateFormat.format(calender.time)
                if (currentDate == pastDay) {
                    val alarmManager = getSystemService(Context.ALARM_SERVICE) as AlarmManager
                    val intent = Intent(this, AlarmReceiver::class.java)
                    val pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0)
                    alarmManager.set(
                        AlarmManager.RTC_WAKEUP,
                        c.timeInMillis,
                        pendingIntent
                    )
                }
            }
        }
    }

    private fun showDatePicker() {
        val c = Calendar.getInstance()
        DatePickerDialog(this,DatePickerDialog.OnDateSetListener { view, year, month, dayOfMonth ->
                val daySelected = Calendar.getInstance()
                daySelected.apply {
                    set(Calendar.YEAR, year)
                    set(Calendar.MONTH, month)
                    set(Calendar.DAY_OF_MONTH, dayOfMonth)
                }
                edit_text_date.setText(dateFormat.format(daySelected.time))
            },
            c.get(Calendar.YEAR),
            c.get(Calendar.MONTH),
            c.get(Calendar.DAY_OF_MONTH)
        ).show()
    }
}

This is AlarmReceiver class
class AlarmReceiver : BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent?) {
        showNotification(context,"title","notification message")

    }
    private fun showNotification(context: Context,title:String,body:String){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
            val notificationChannel = NotificationChannel("CHANNEL_ID","My Channel",NotificationManager.IMPORTANCE_HIGH)
            val notificationManager = context.getSystemService(NotificationManager::class.java)!!
            notificationManager.createNotificationChannel(notificationChannel)
        }
        val notificationManagerCompat = NotificationManagerCompat.from(context)
        val notification = NotificationCompat.Builder(context,"CHANNEL_ID")
            .setSmallIcon(R.drawable.ic_launcher_background)
            .setContentTitle(title)
            .setContentText(body)
            .setPriority(NotificationCompat.PRIORITY_HIGH)
            .build()
        notificationManagerCompat.notify(0,notification)
    }
}

I also register the reciever in Manifest

A: To schedule tasks more efficiently, you should use the newly introduced WorkManager class.
It handles all API levels and you don't have to worry about Android Versions that your application will work on.
To call your function at a set desired time,
OneTimeWorkRequest oneTimeWorkRequest = new OneTimeWorkRequest.Builder(WorkerClass.class)
                                                        .setConstraints(constraints)
                                                        .setInitialDelay(delayToPass, TimeUnit.MILLISECONDS)
                                                        .build();
WorkManager.getInstance(getApplicationContext())
    .enqueueUniqueWork(oneTimeWorkRequest);

For more information check out: https://developer.android.com/reference/androidx/work/WorkManager
"WorkerClass" is a class that will handle your desired work inside the
public Result doWork() // method

Make sure you read about it too.


text:
Q: Unable to build SSRS Project I am trying to set up a build pipeline in Azure DevOPS to build a SSRS project. I have a VSBuild task setup like so
- task: VSBuild@1
  inputs:
    solution: '$(solution)'
    msbuildArgs: '/p:OutDir="bin\Debug" /p:OutputPath="bin\Debug" /verbosity:diagnostic'
    configuration: '$(configuration)'

I am getting the following error

C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\MSBuild\Reporting
Services\Microsoft.ReportingServices.MSBuilder.targets(30,5): Error
MSB4018: The "ReportBuilderTask" task failed unexpectedly
System.ArgumentException: The OutputPath property cannot be blank. It
must provide a relative path that is a child folder under the path of
the report server project.    at
Microsoft.ReportingServices.BuildProcess.ReportProjectOptions.GetOutputDirectory()
at
Microsoft.ReportingServices.BuildProcess.ReportProjectOptions.GetOutputFile(String
fileName)    at
Microsoft.ReportingServices.BuildProcess.Builder.BuildReport(ReportReportNode
node, ReportProjectOptions options, IMessageHandler messageHandler,
ICheckPublish checkPublish)    at
Microsoft.ReportingServices.BuildProcess.Builder.BuildItems(ICollection
collection, ReportProjectOptions options, IMessageHandler
messageHandler, ICheckPublish checkPublish)    at
Microsoft.ReportingServices.BuildProcess.ReportBuilderTask.Execute()
at
Microsoft.Build.BackEnd.TaskExecutionHost.Microsoft.Build.BackEnd.ITaskExecutionHost.Execute()

I checked the PropertyGroup for my configuration and I do see OutputPath, I am also supplying it as an MSBuild parameter additionally, but it isn't getting picked up it seems.
What am I missing? I am using the hosted agent.

A: As stated in the error message, the path cannot be full path. The azure devops variables carry full absolute paths. I have changed the OutputPath property to carry the relative path and things seem to work now.


text:
Q: I am not able to parse data from push notification I want to parse data from a firebase push notification and data is coming along with "aps" and I am finding difficulty in parsing. This is the data I am receiving in push. I want to parse "PnType", "Pickup".
[
  AnyHashable("CustomData"):
  {
    "PnType":"PnNewJob",
    "PnResult":
    {
      "JobId":1743,
      "JobRef":"CAS4491055071",
      "Pickup":"Basil And Bean Co, phase-7, Mohali, Punjab, India",
      "DropOff":"Elante Mall, Chandigarh, Chandigarh, India",
      "Cost":9.00,
      "TotalMiles":4.93
    }
  },
  AnyHashable("google.c.a.e"): 1,
  AnyHashable("gcm.message_id"): 0:1555505650971833%277c5a32277c5a32,
  AnyHashable("aps"):
  {
    alert =
    {
        body = "Hellodrive Notification";
        title = "HelloDrive Notification";
    };
    badge = 1;
    "content-available" = 1;
  }
]

I tried parsing it like
let customData = userInfo["CustomData"] as? [AnyHashable: Any]

I am getting nil each time.

A: I tried pushing the notification using NWPusher app.
JSON pushed:
{
  "CustomData": {
    "PnType": "PnNewJob",
    "PnResult": {
      "JobId": 1743,
      "JobRef": "CAS4491055071",
      "Pickup": "Basil And Bean Co, phase-7, Mohali, Punjab, India",
      "DropOff": "Elante Mall, Chandigarh, Chandigarh, India",
      "Cost": 9,
      "TotalMiles": 4.93
    }
  },
  "google.c.a.e": 1,
  "gcm.message_id": "0:1555505650971833%277c5a32277c5a32",
  "aps": {
    "alert": {
      "body": "Hellodrive Notification",
      "title": "HelloDrive Notification"
    },
    "badge": 1,
    "content-available": 1
  }
}

Following received in didReceiveRemoteNotification
[[AnyHashable("aps"): {
    alert =     {
        body = "Hellodrive Notification";
        title = "HelloDrive Notification";
    };
    badge = 1;
    "content-available" = 1;
}, AnyHashable("google.c.a.e"): 1, AnyHashable("CustomData"): {
    PnResult =     {
        Cost = 9;
        DropOff = "Elante Mall, Chandigarh, Chandigarh, India";
        JobId = 1743;
        JobRef = CAS4491055071;
        Pickup = "Basil And Bean Co, phase-7, Mohali, Punjab, India";
        TotalMiles = "4.93";
    };
    PnType = PnNewJob;
}, AnyHashable("gcm.message_id"): 0:1555505650971833%277c5a32277c5a32]]

Now, i retrieved the values from userInfo using below code in didReceiveRemoteNotification method.It perfectly worked.
    if let customData = userInfo["CustomData"] as? [AnyHashable: Any] {

        if let pnType = customData["PnType"] as? String {
            print("PNType: \(pnType)")
        }

        if let pnResult = customData["PnResult"] as? [AnyHashable: Any] {
            if let pickup = pnResult["Pickup"] as? String {
                print("Pickup: \(pickup)")
            }
        }
    }

Output
PNType: PnNewJob
Pickup: Basil And Bean Co, phase-7, Mohali, Punjab, India

A: First of all cast userInfo to more specific [String:Any], then extract the values
if let userInfo = userInfo as? [String:Any],
   let customData = userInfo["CustomData"] as? [String:Any] {
     let pnType = customData["PnType"] as? String
     print(pnType ?? "n/a")
     if let pnResult = customData["PnResult"] as? [String:Any],
        let pickup = pnResult["Pickup"] as? String {
          print(pickup)
     }

}


text:
Q: Why are my variables not updating in a php mysqli for-loop? I am trying to sort a single table (of 10k+ rows) into two separate tables, but seem to be running into a nonsense error that I can't figure out. When i comment out the mysqli insert statements, the variables are printing out correctly and updating as they should. I can see all of the data with the correct keys and values even when looping through all the values in the table.
When I add in the insert statement and place it in a mysqli_query, however, I am suddenly getting tons of mysqli errors saying that there are suddenly duplicate primary keys, but as per the previous tests, there are no duplicates. Other times, it seems to only loop once and then stop (or loop the correct amount of times, but doing nothing each time. I have printed out the mysql statements and was able to see that they were all correct before attempting the query, and yet it still causes issues when actually running. The code in its entirety is included below, but I cannot figure out what the issue is for the life of me.
$sql = "SELECT * FROM originalTable ORDER BY port LIMIT 20";
$result = mysqli_query($conn, $sql);
$num_Rows = mysqli_num_rows($result);
echo $num_Rows."
";

// gets data for each row in the table

for($i=0; $i<$num_Rows; $i++){
    $row = mysqli_fetch_assoc($result);
    $ID = $row["ID"];
    echo $ID."
";
    $IP = $row["IP"];
    echo $IP."
";
    $port = $row["port"];
    echo $port."
";
    $running = $row["running"];
    echo $running."
";
    $afk = $row["afk"];
    echo $afk."
";
    $gamemode = $row["gamemode"];
    echo $gamemode."
";
    $maxplayers = $row["maxplayers"];
    echo $maxplayers."
";
    $spawnprotection = $row["spawnprotection"];
    echo $spawnprotection."
";
    $whitelist = $row["whitelist"];
    echo $whitelist."
";
    $enablequery = $row["enablequery"];
    echo $enablequery."
";
    $enablercon = $row["enablercon"];
    echo $enablercon."
";
    $rconpassword = $row["rconpassword"];
    echo $rconpassword."
";
    $motd = $row["motd"];
    echo $motd."
";
    $announceachieve = $row["announceplayerachievements"];
    $allowflight = $row["allowflight"];
    $spawnanimals = $row["spawnanimals"];
    $spawnmobs = $row["spawnmobs"];
    $forcegamemode = $row["forcegamemode"];
    $hardcore = $row["hardcore"];
    $pvp = $row["pvp"];
    $difficulty = $row["difficulty"];
    $generatorsettings = $row["generatorsettings"];
    $levelname = $row["levelname"];
    $levelseed = $row["levelseed"];
    $leveltype = $row["leveltype"];
    $autosave = $row["autosave"];

    if($IP == $server1){
        $server = "server1table";
        $sql1 = "INSERT INTO server1table (id, ip, port, running, afk, gamemode, maxplayers, spawnprotection,
              whitelist, enablequery, enablercon, rconpassword, motd, announceplayerachievements,
              allowflight, spawnanimals, spawnmobs, forcegamemode, hardcore, pvp, difficulty,
              generatorsettings, levelname, levelseed, leveltype, autosave) VALUES ('$ID', '$IP',
              '$port', '$running', '$afk', '$gamemode', '$maxplayers', '$spawnprotection', '$whitelist',
              '$enablequery', '$enablercon', '$rconpassword', '$motd', '$announceachieve', '$allowflight', '$spawnanimals',
              '$spawnmobs', '$forcegamemode', '$hardcore', '$pvp', '$difficulty', '$generatorsettings', '$levelname',
              '$levelseed', '$leveltype', '$autosave')";
        echo $sql1;
        $result = mysqli_query($conn, $sql1);
        echo "Server 1
";
        if($result){
            echo "Success?";
        }
        else{
            echo "Failure = " . $conn->error;
        }
    } else if ($IP == $Server2){
        $server = "server2table";
        $sql2 = "INSERT INTO server2table (id, ip, port, running, afk, gamemode, maxplayers, spawnprotection,
              whitelist, enablequery, enablercon, rconpassword, motd, announceplayerachievements,
              allowflight, spawnanimals, spawnmobs, forcegamemode, hardcore, pvp, difficulty,
              generatorsettings, levelname, levelseed, leveltype, autosave) VALUES ('$ID', '$IP',
              '$port', '$running', '$afk', '$gamemode', '$maxplayers', '$spawnprotection', '$whitelist',
              '$enablequery', '$enablercon', '$rconpassword', '$motd', '$announceachieve', '$allowflight', '$spawnanimals',
              '$spawnmobs', '$forcegamemode', '$hardcore', '$pvp', '$difficulty', '$generatorsettings', '$levelname',
              '$levelseed', '$leveltype', '$autosave')";
        echo $sql2;
        $result = mysqli_query($conn, $sql2);
        echo "Server 2
";
        if($result){
            echo "Success?";
        }
        else{
            echo "Failure = " . $conn->error;
        }
    }

EDIT: The ID in the table above is not the table ID field or primary key. It represents the ID of the player. The port is the primary key of the table
Clarification: In one iteration of this code, it sent everything to server 1 with no issues, but it totally ignored server 2. I have since tested and ensured that the split (if statement) worked as intended, and it prints the correct server name and sets $sql to the intended value (as it prints out). It will only move the first column of the table and then it sets everything else to blank and the ID to 0 and sends a bunch of duplicate primary errors.

A: I don't think you should be inserting the IDs, that might be where you're fighting with possibly the table primary keys and auto_increment. Just remove the id from the insert and it should be fine. Depending upon how you've set up the table structure. Generally you shouldn't need to preserve the IDs, that's just there for uniqueness and indexing housekeeping etc.


text:
Q: Superposition of conductors If a put some charged conductors in an isolated system i could use the superposition principle to calculate the electric field. The difficult thing is to know in which way the charges will redistribute in the conductors' surfaces.
Nevertheless, when we study capacitors ( = two plane conductors placed close to each other) this redistribution seems not happen; so we can apply directly the superposition , knowing the field generated by each conductor.
Why in this case the redistribution doesn't happen ?

A: Usually when you say parallel plate capacitors, you are considering them large enough to neglect any edge effects. Now, suppose you have two parallel plate capacitors placed closed to each other. Initially, you have charge uniformly distributed on them. Now, when they are close to each other, think about a particular charge. For the charge, there is no preferred direction to move in because of the symmetry of the problem. If it moves someplace, that would mean the symmetry is violated. So, by this simple argument, you can see that the charge redistribution won't take place as long as you are neglecting edge effects. However, a more complete analysis will show that the charges at the edge do have a preferred direction,i.e ,towards the center where the electric field is more stronger. Hence, in reality, the redistribution does take place.


text:
Q: Django directs all requests to child application instead of mainapp Here is the tree of my project:
├── db.sqlite3
├── kitchen_analytics
│   ├── settings.py
│   ├── static_html
│   ├── urls.py
│   └── wsgi.py
├── manage.py
├── statistics101
│   ├── admin.py
│   ├── apps.py
│   ├── computation_logic
│   │   └── dish_count.py
│   ├── migrations
│   ├── models_default.py
│   ├── models.py
│   ├── statsrouter.py
│   ├── templates
│   │   └── statistics101
│   │       └── orders_list.html
│   ├── tests.py
│   ├── urls.py
│   └── views.py
└── templates
    └── index.html

I am trying to add simple html index page,
here is my urlpatterns config from kitchen_analytics/urls.py:
urlpatterns = [
    path('', TemplateView.as_view(template_name='index.html')),
    path('admin/', admin.site.urls),
    path('', include(statistics101.urls, namespace='statistics101')),
]

When I go to http://127.0.0.1:8000/ I get template not found error. Django tries to go to statistics101 app and looks for index.html there. How do I fix this?
Also for some reason I have to keep templates for statistics101 app in templates/statistics101 instead of just templates. How do I keep it in templates?
Here is an error:
TemplateDoesNotExist at /
index.html
Request Method: GET
Request URL:    http://127.0.0.1:8000/
Django Version: 2.1.7
Exception Type: TemplateDoesNotExist
Exception Value:
index.html
Exception Location: /home/aydar/PycharmProjects/kitchen_analytics/venv/lib/python3.6/site-packages/django/template/loader.py in select_template, line 47
Python Executable:  /home/aydar/PycharmProjects/kitchen_analytics/venv/bin/python
Python Version: 3.6.8
Python Path:
['/home/aydar/PycharmProjects/kitchen_analytics',
 '/usr/lib/python36.zip',
 '/usr/lib/python3.6',
 '/usr/lib/python3.6/lib-dynload',
 '/home/aydar/PycharmProjects/kitchen_analytics/venv/lib/python3.6/site-packages',
 '/home/aydar/PycharmProjects/kitchen_analytics/venv/lib/python3.6/site-packages/setuptools-39.1.0-py3.6.egg']
Server time:    Tue, 19 Mar 2019 14:24:12 +0000

Here is template loader postmortem:
Using engine django:

django.template.loaders.app_directories.Loader: /home/uname/PycharmProjects/kitchen_analytics/statistics101/templates/index.html (Source does not exist)
django.template.loaders.app_directories.Loader: /home/uname/PycharmProjects/kitchen_analytics/venv/lib/python3.6/site-packages/django/contrib/admin/templates/index.html (Source does not exist)
django.template.loaders.app_directories.Loader: /home/uname/PycharmProjects/kitchen_analytics/venv/lib/python3.6/site-packages/django/contrib/auth/templates/index.html (Source does not exist)

here is the templates setting from settings.py
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

A: Your top-level templates directory isn't present in your templates DIRS setting. You should add it:
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        ...
    }
]


text:
Q: Dictionary throwing an Argument Exception even when protected by ContainsKey In production, this code (C#, .NET 4.5.1) is throwing a ArgumentException stating that
An item with the same key has already been added.
Code:
public MyClass()
{
   this.MyContent = new Dictionary<string, string>();
}

public IDictionary<string, string> MyContent { get; private set; }

public void AddOrUpdateDictionary(string key, string value)
{
    if (this.MyContent.ContainsKey(key))
    {
        this.MyContent[key] = string.Concat(this.MyContent[key], value);
    }
    else
    {
        this.MyContent.Add(key, value);
    }
}

However, I can't recreate the error in a unit test. E.g. This behaves as expected -
[TestMethod]
public void AddOrUpdateDictionary_WhenAddingSecondValue_ValueIsAppended()
{
    const string InputValue1 = "Value1";
    const string InputValue2 = "Value2";
    string expectedValue = string.Concat(InputValue1, InputValue2);

    var obj = new MyClass();
    obj.AddOrUpdateDictionary("Key", InputValue1);
    obj.AddOrUpdateDictionary("Key", InputValue2);

    Assert.AreEqual(expectedValue, obj.MyContent["Key"]);
}

What is causing this? I thought the ContainsKey would've made the code safe.
Is this some weird threading gotcha I've missed? This code is on a model in an MVC site, no instances of it are static.

A: Assuming the problem is thread related and it is allowed to change the type of dictionary, you could use a ConcurrentDictionary. It exposes a method (AddOrUpdate) that can do exactly what's intended: either add the value or refactor the value based on the present value:
    class MyClass
    {
        public MyClass()
        {
            this.content = new ConcurrentDictionary<string, string>();
        }

        ConcurrentDictionary<string, string> content;
        public IDictionary<string, string> MyContent { get { return content; } }

        public void AddOrUpdateDictionary(string key, string value)
        {
            content.AddOrUpdate(key, value, (k, contentValue) => string.Concat(contentValue, value));
        }
    }

A: You may want to use ConcurrentDictionary<T1, T2>

So it would be like:
    public void AddOrUpdateDictionary(string key, string value)
    {
        if (this.MyContent.ContainsKey(key))
        {
            this.MyContent[key] = string.Concat(this.MyContent[key], value);
        }
        else
        {
            this.MyContent.AddOrUpdate(key, value, (x, y) => value);
        }
    }


text:
Q: How do I fix this file_tracker that reads/writes using JSON dictionaries? I am trying to write a script that tracks for changes made in directories/files set to multiple file paths created by an installer. I found Thomas Sileo's DirTools project on git, modified it, but am now running into some issues when writing/reading from JSON:
1) First, I believe that I am writing to JSON incorrectly and am finding that my create_state() function is only writing the last path I need.
2) If I get it working, I am unable to read/parse the file like I was before. I usually get ValueError: Extra data errors
Code below:
import os import json import getpass

files = [] subdirs = []

USER = getpass.getuser()

pathMac = ['/Applications/',
           '/Users/' + USER + '/Documents/' ]

def create_dir_index(path):
    files = []
    subdirs = []

    for root, dirs, filenames in os.walk(path):
        for subdir in dirs:
            subdirs.append(os.path.relpath(os.path.join(root, subdir), path))

        for f in filenames:
            files.append(os.path.relpath(os.path.join(root, f), path))

    return dict(files=files, subdirs=subdirs)

def create_state(): for count in xrange(len(pathMac)):

        dir_state = create_dir_index(pathMac[count])
        out_file = open("Manifest.json", "w")
        json.dump(dir_state, out_file)
    out_file.close()

def compare_states(dir_base, dir_cmp):
    '''
    return a comparison two manifest json files
    '''

    data = {}

    data['deleted'] = list(set(dir_cmp['files']) - set(dir_base['files']))
    data['created'] = list(set(dir_base['files']) - set(dir_cmp['files']))

    data['deleted_dirs'] = list(set(dir_cmp['subdirs']) - set(dir_base['subdirs']))
    data['created_dirs'] = list(set(dir_base['subdirs']) - set(dir_cmp['subdirs']))

    return data

if __name__ == '__main__':

    response = raw_input("Would you like to Compare or Create? ")

    if response == "Create":
        # CREATE MANIFEST json file
        create_state()
        print "Manifest file created."
    elif response == "Compare":
        # create the CURRENT state of all indexes in pathMac and write to json file
        for count in xrange(len(pathMac)):
            dir_state = create_dir_index(pathMac[count])
            out_file = open("CurrentState.json", "w")
            json.dump(dir_state, out_file)
        out_file.close()

        # Open and Load the contents from the file into dictionaries
        manifest = json.load(open("Manifest.json", "r"))
        current = json.load(open("CurrentState.json", "r"))

        print compare_states(current, manifest)


text:
Q: Troubles using fragment with RecyclerView and Retrofit I have this error, actually I don't know about fragments.
CreatView
@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_inicio, container,
                false);
        getActivity().setTitle(R.string.inicio);
        recyclerView = (RecyclerView) rootView.findViewById(R.id.card_recycler_view);
        recyclerView.setHasFixedSize(true);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(layoutManager);
        loadJSON();
        return rootView;
    }

loadJSON void
private void loadJSON(){
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("http://192.168.1.42:3000/")
            .addConverterFactory(GsonConverterFactory.create())
            .build();
    RequestInterface request = retrofit.create(RequestInterface.class);
    Call<JSONResponse> call = request.getJSON();
    call.enqueue(new Callback<JSONResponse>() {
        @Override
        public void onResponse(Call<JSONResponse> call, Response<JSONResponse> response) {
            JSONResponse jsonResponse = response.body();
            data = new ArrayList<>(Arrays.asList(jsonResponse.getCupon()));
            adapter = new CuponAdapter(data);
            recyclerView.setAdapter(adapter);
        }

        @Override
        public void onFailure(Call<JSONResponse> call, Throwable t) {
            Log.d("Error", t.getMessage());
        }
    });
}

Adapter
public class CuponAdapter extends RecyclerView.Adapter<CuponAdapter.ViewHolder> {
private ArrayList<Cupon> cupon;

public CuponAdapter(ArrayList<Cupon> cupon) {
    this.cupon = cupon;
}

@Override
public CuponAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
    View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.card_row, viewGroup, false);
    return new ViewHolder(view);
}

@Override
public void onBindViewHolder(ViewHolder holder, int i) {
    holder.tv_titulo.setText(cupon.get(i).getTitulo());
    holder.tv_empresa.setText(cupon.get(i).getEmpresa());
    holder.tv_descripcion.setText(cupon.get(i).getDescripcion());
}

@Override
public int getItemCount() {
    return cupon.size();
}

public class ViewHolder extends RecyclerView.ViewHolder {
    private TextView tv_titulo, tv_descripcion, tv_empresa;

    public ViewHolder(View view) {
        super(view);
        tv_titulo = (TextView) view.findViewById(R.id.tv_titulo);
        tv_descripcion = (TextView) view.findViewById(R.id.tv_descripcion);
        tv_empresa = (TextView) view.findViewById(R.id.tv_empresa);
    }
}
}

The Error

12-08 00:00:05.727 1784-1784/com.mighty.cupoferta E/RecyclerView: No
  adapter attached; skipping layout

This code is based on this link .
But he explains how to put in an activity, how can I put in a fragment?

A:   call.enqueue(new Callback<JSONResponse>() {
    @Override
    public void onResponse(Call<JSONResponse> call, Response<JSONResponse> response) {
        JSONResponse jsonResponse = response.body();
        data = new ArrayList<>(Arrays.asList(jsonResponse.getCupon()));
        adapter = new CuponAdapter(data);
        recyclerView.setAdapter(adapter);
    }

Do not depend on network response to set your adapter.
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(adapter);

You can do it right here.
Then after the network response you can add data to the adapter and call notifyDataSetChanged()

A: Well it is because you are setting adapter after delay, try to set an empty adapter to recyclerview before you return rootView, then update adapter on Retrofit callback as in
@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_inicio, container,
                false);
        getActivity().setTitle(R.string.inicio);
        recyclerView = (RecyclerView) rootView.findViewById(R.id.card_recycler_view);
        recyclerView.setHasFixedSize(true);
        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(layoutManager);
        recyvlerView.setAdapter(new CuponAdapter(new ArrayList<Cupon>()));
        loadJSON();
        return rootView;
    }

A: set your adapter in the onCreateView function and use .notifyDataSetChanged() in the loadJSON function to notifiy the adapter about the changes in the data like the code below.
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_inicio, container,
            false);
    getActivity().setTitle(R.string.inicio);
    recyclerView = (RecyclerView) rootView.findViewById(R.id.card_recycler_view);
    recyclerView.setHasFixedSize(true);
    RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
    recyclerView.setLayoutManager(layoutManager);
    recyclerView.setAdapter(adapter);
    loadJSON();
    return rootView;
 }

and in your adapter class write this
private void loadJSON(){
Retrofit retrofit = new Retrofit.Builder()
        .baseUrl("http://192.168.1.42:3000/")
        .addConverterFactory(GsonConverterFactory.create())
        .build();
RequestInterface request = retrofit.create(RequestInterface.class);
Call<JSONResponse> call = request.getJSON();
call.enqueue(new Callback<JSONResponse>() {
    @Override
    public void onResponse(Call<JSONResponse> call, Response<JSONResponse> response) {
        JSONResponse jsonResponse = response.body();
        data = new ArrayList<>(Arrays.asList(jsonResponse.getCupon()));
        adapter = new CuponAdapter(data);
        adapter.notifyDataSetChanged();
    }

    @Override
    public void onFailure(Call<JSONResponse> call, Throwable t) {
        Log.d("Error", t.getMessage());
    }
});
}


text:
Q: Postmessage from a tab to another tab I want to send data from a website to another website if it needs chrome extension or not for example i have opened https://a.com in a tab in chrome and in another tab https://b.com so in here i want send data from https://b.com to https://a.com with javascript
Code example:
https://a.com:
$(window).on('message',(e)=> { console.log(e.data); }),
https://b.com:
$.postMessage("this is a message","https://a.com");
Result in https://a.com: undefined


text:
Q: C# - Can't connect to remote MySQL server My problem is that I can't connect to my website remote MySQL server. I have read all answers in stackoverflow.com, but I can't find right answer. Here's my C# code:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;

namespace ConsoleApplication3
{
class Program
{
    static void Main(string[] args)
    {
        SqlConnection con;

        string connectionString = @"Server=[IP adress];Port=3306;Database=[database];Uid=[user];Pwd=[pass];";
        con = new SqlConnection(connectionString);
        try
        {
            con.Open();
            Console.WriteLine ("Connection Open ! ");
        }
        catch (Exception ex)
        {
            Console.WriteLine("Can not open connection ! ");
            Console.WriteLine(ex.Message); //shows what error actually occurs
        }
        Console.ReadLine();
    }
}
}

Error:
A network-related or instance-specific error occurred while establishing a
connection to SQL Server. The server was not found or was not accessible.
Verify that the instance name is correct and that SQL Server is configured
to allow remote connections. (provider: Named Pipes Provider, error: 40
Could not open a connection to SQL Server)

Any ideas?

A: When connecting to a MySQL-Database I always used the MySQL Connector you can get here: https://dev.mysql.com/downloads/connector/net/6.9.html
You have to import the MySQL namespaces to your project and then you can use the MySQLConnection instead of the SQLConnection that is, as far as I know, only for MSSQL servers.
http://www.codeproject.com/Tips/423233/How-to-Connect-to-MySQL-Using-Csharp

A: try the following
string connectionString = @"Server=[IP adress]:3306;Database=[database];Uid=[user];Pwd=[pass];";

instead of
 string connectionString = @"Server=[IP adress];Port=3306;Database=[database];Uid=[user];Pwd=[pass];";


text:
Q: Adding Multiple Folder Names From Directory To OptionMenu Python I am trying to add multiple folder names to an options menu. The code below adds only one folder name to the list but I want to add all folder names in the directory.
var = StringVar()
os.chdir('C:\\Users\\mhoban')
all_subdirs = [d for d in os.listdir('.') if os.path.isdir(d)]
for dirs in all_subdirs:
    dir = os.path.join('C:\\Users\\mhoban', dirs)
    os.chdir(dir)
    current = os.getcwd()
    new = str(current).split("\\")[3]

opt1 = OptionMenu(app, var, new)
opt1.grid(row=0, column=1, padx=10, pady=10)
opt1.configure(width = 40, bg = "White")

A: You need to build a list of menu options and then unpack it where you're passing new at the moment:
options = []
for dirs in all_subdirs:
    ...  # same
    options.append(str(current).split("\\")[3])

Unpacking options:
opt1 = OptionMenu(app, var, *options)

Note: options will be the same as all_subdirs, so your processing doesn't seem to achieve anything. Just use all_subdirs instead.


text:
Q: Javascript recursive function not working I am trying to write a code to read a nested JSON and print the items. Later I plan to generate a menu from this.
The JSON content is as follows:
{
    "label": "Root of Menu",
    "child": [
            {
            "label": "Menu 1",
            "child": [
                    {
                    "label": "Menu 1.1",
                    "child": [
                            {
                                "label": "Menu 1.1.1"
                            },
                            {
                                "label": "Menu 1.1.2"
                            }
                    ]
                },
                {
                    "label": "Menu 1.2",
                    "child": [
                            {
                                "label": "Menu 1.2.1"
                            },
                            {
                                "label": "Menu 1.2.2"
                            }
                    ]
                },
                {
                    "label": "Menu 1.3",
                    "child": [
                            {
                                "label": "Menu 1.3.1"
                            },
                            {
                                "label": "Menu 1.3.2"
                            }
                    ]
                }
            ]
        },
        {
            "label": "Menu 2",
            "child": [
                    {
                        "label": "Menu 2.1"
                    },
                    {
                        "label": "Menu 2.2"
                    }
            ]
        },
        {
            "label": "Menu 3",
            "child":
                    {
                        "label": "Menu 3.1"
                    }
        }
    ]
}

I am using the following recursive function:
function menuize(m) {
    if (m instanceof Array) {
        for(i = 0; i < m.length; i++) {
            for(p in m[i]) {
                menuize(m[i][p]);
            }
        }
    } else if (m instanceof Object) {
        for(p in m) {
                menuize (m[p]);
        }

    } else {
        console.log('Label: ' + m);
    }

}

The menuize(m) call starts with m being the JSON object evaluated using JSON.parse(XHR.responseText) where XHR is the XMLHttpRequest object used to retrieve the data. I've seen that the data is read completely fine so that is not the problem.
Now, what happens is that the function works somewhat correct, in terms that it works fine till it reaches the innermost child but after that, it does not get back to properly printing the rest of the items one level up and so on.
The output generated will help you to understand what is happening:
t: Root of Menu
t: Menu 1
t: Menu 1.1
t: Menu 1.1.1
t: Menu 1.1.2

I can't understand what exactly is happening and why shouldn't the items like Menu 1.2, Menu 2 (which are relatively in the upper levels) be printed.
Would someone please be kind to provide some insight and help me understand?
Thanks!

A: Your iteration variables need to be declared with var so they'll be local variables. Otherwise, when you recurse, you're overwriting the variables used in the caller.
function menuize(m) {
    var i, p;
    if (m instanceof Array) {
        for(i = 0; i < m.length; i++) {
            for(p in m[i]) {
                menuize(m[i][p]);
            }
        }
    } else if (m instanceof Object) {
        for(p in m) {
                menuize (m[p]);
        }

    } else {
        console.log('Label: ' + m);
    }

}


text:
Q: Send data without submit button (Javascript / jQuery) <!DOCTYPE html>

        <form name="form1" id="form1" action="coillist" method="POST">

                        Coil #	Width	Gauge

                        <input type="text" maxlength="7" size="7" name="coil_id" value="coil_11">
                        <input type="text" size="7" name="width" value="120">
                        <input type="text" size="5" name="gauge" value="130">

                        <input type="text" maxlength="7" size="7" name="coil_id" value="coil_22">
                        <input type="text" size="7" name="width" value="220">
                        <input type="text" size="5" name="gauge" value="330">

                        <input type="text" maxlength="7" size="7" name="coil_id" value="coil_33">
                        <input type="text" size="7" name="width" value="320">
                        <input type="text" size="5" name="gauge" value="330">

        </form>

I have a dynamic row adding table that could add row into the table.
I am showing it in 3 rows, it could be 1 row, or 4 rows, or n rows if a use wants to add data in.
My question is: How can I send data (coil_id) out without click submit button?
In this example, I want to send a coil_id (coil_id = "coil_22" in this case) to the server without using submit button.
This is also something like: detect if user enter a coil in length of 7 char or digit (Ex: coil_22 or 2C12345), then it will submit the "coil_22"   (not coilL_11 or coil_33) to server without click any submit / send button.
I have used JavaScript / jQuery a while, still feel lost sometimes.
Highly appreciate your help.

A: You can make it with a .keyup(), just add a class to each input for example
<input type="text" class="coil_input" maxlength="7" size="7" name="coil_id" value="coil_11">
<input type="text" class="coil_input" maxlength="7" size="7" name="coil_id" value="coil_22">

All the inputs has to have the same class
Remember to add jQuery to your document.

A: here is example of jquery ajax. serialize will create generate query string that will be sent to your url.
var datastring = $("#yourForm").serialize();
$.ajax({
    type: "POST",
    url: "your url",
    data: datastring,
    dataType: "json",
    success: function(data) { alert('all ok');}
 });


text:
Q: Changing network interface names on RedHat I have a DELL server running RedHat EL 6.3 with two 1G network interfaces, and two 10G network interfaces.
Following this note, I have successfully renamed the two 1G network interfaces that used to be called em1 and em2. However, I cannot rename the 10G network interfaces using this method. (Those are called p4p1 and p4p2, and do not start with em.)
How can I rename the network interface name of my 10G network interfaces on RedHat EL 6.3?

A: As the section of the appendix you linked to states, it's strongly recommended to enable or disable the consistent network device naming feature at install time; doing so after installation is messy and not guaranteed to work, as you've discovered.
To do this, install the system passing biosdevname=0 on the boot command line when booting the installation media, and add the same parameter to the grub boot command line.
Since you've just installed the system anyway, this shouldn't be too big of a headache...

A: I know that my answer is really late, but this can help other people searching for this information, so here it goes:
It is better to give these 2 options as kernel parameters:
biosdevname=0 net.ifnames=0

To add this to the boot you can do:
/sbin/grubby --update-kernel=`/sbin/grubby --default-kernel` --args="biosdevname=0 net.ifnames=0 "

Or modify the /etc/default/grub and add biosdevname=0 net.ifnames=0"" to the **GRUB_CMDLINE_LINUX and regenerate grub configuration:
grub2-mkconfig -o /boot/grub2/grub.cfg

Example of the /etc/default/grub entry:
# cat /etc/default/grub
GRUB_TIMEOUT=5
GRUB_DISTRIBUTOR="$(sed 's, release .*$,,g' /etc/system-release)"
GRUB_DEFAULT=saved
GRUB_DISABLE_SUBMENU=true
GRUB_TERMINAL_OUTPUT="console"
GRUB_CMDLINE_LINUX="rd.lvm.lv=rhel_7/swap rd.luks.uuid=luks-cc387312-6da6-469a-8e49-b40cd58ad67a crashkernel=auto  vconsole.keymap=us vconsole.font=latarcyrheb-sun16 rd.lvm.lv=rhel_7/root rhgb quiet net.ifnames=0 biosdevname=0"
GRUB_DISABLE_RECOVERY="true"


text:
Q: Visualforce render as pdf doesn't render arabic content We are trying to render a VF page as pdf using visualforce render as pdf in arabic language.
Except for the english text below none of the other text appear in the pdf especially the one in arabic in p tag below.

There is already another question here raised yesterday but it doesnt contain the VF code so created a new question.
We followed this link in salesforce documentation for VF render as pdf but it doesnt work
<apex:page showHeader="false" applyBodyTag="false"  renderAs="pdf">

これはサンプルページです。

This is a sample page: API version 28.0

     مرحبا

</apex:page>

There is an idea created for it to be enabled in future.
Is there any other solution we can try to get around this? for now the only work around we have is to render the page as Visualforce and use the browser print functionality.
Update:
Based on the suggestion provided in the comments by kurunve i tried it and it seemed to print the Arabic content but not the correct content though
I tested the same page with Visualforce render as PDF and just Visualforce page the results are different
Visualforce render as pdf:

Visualforce Page without render as pdf:

Confused that same content with and without the renderas tag behaves differently. Any insights on why it behaves this way would be appreciated.


text:
Q: Draw a shadow for two childs in container, that have no space between them So childs have some strange shadows, that overlapping each other. Is there any way to draw like one shadow for both of them?
The case, I mean is what if they are not even on the same level of view hierarchy.
Here what I want to achieve:

Here`s xml layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    android:id="@+id/root"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="200dp"
    android:elevation="8dp"
    tools:context=".MainActivity">

    <View
        android:background="@android:color/white"
        android:layout_width="40dp"
        android:elevation="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_height="40dp"/>
    <View
        android:background="@android:color/white"
        android:layout_width="40dp"
        android:layout_marginTop="48dp"
        android:layout_marginStart="8dp"
        android:elevation="8dp"
        android:layout_height="40dp"/>
    <View.../>
    <View.../>
</RelativeLayout>

A: If you want two Child View to have the same shadow, just put them in the same Layoutand add the shadow on the Layout
<LinearLayout
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:elevation="8dp">

   <View
    android:background="@android:color/white"
    android:layout_width="40dp"
    android:layout_marginStart="8dp"
    android:layout_marginTop="8dp"
    android:layout_height="40dp"/>
   <View
    android:background="@android:color/white"
    android:layout_width="40dp"
    android:layout_marginTop="48dp"
    android:layout_marginStart="8dp"
    android:layout_height="40dp"/>

</LinearLayout>

A: <?xml version="1.0" encoding="utf-8"?>
  <RelativeLayout
  android:id="@+id/root"
  xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:tools="http://schemas.android.com/tools"
  android:layout_width="match_parent"
  android:layout_height="200dp"
  android:elevation="8dp"
  tools:context=".MainActivity">

  <View
      android:background="@android:color/white"
      android:layout_width="40dp"
      android:elevation="8dp"
      android:layout_marginStart="8dp"
      android:layout_marginTop="8dp"
      android:layout_height="40dp"/>
  <View
      android:background="@android:color/white"
      android:layout_width="40dp"
      android:layout_marginTop="68dp"
      android:layout_marginStart="8dp"
      android:elevation="8dp"
      android:layout_height="40dp"/>
  <View.../>
  <View.../>
</RelativeLayout>

A: Two thing u can do. you can use Linear layout instead of Relative layout or you can specify position of the view ie,
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    android:id="@+id/root"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="200dp"
    android:elevation="8dp"
    tools:context=".MainActivity">

    <View
        android:background="@android:color/white"
        android:layout_width="40dp"
        android:elevation="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_height="40dp"/>
    <View
        android:background="@android:color/white"
        android:layout_width="40dp"
        android:layout_marginTop="48dp"
        android:layout_marginStart="8dp"
        android:elevation="8dp"
        android:layout_height="40dp"
        android:layout_toRightOf="@id/view1"/>
    <View.../>
    <View.../>
</RelativeLayout>


text:
Q: htaccess - How to cut some text from url I have simple question about htaccess, but i can't solve it. Part of links of my website on google search has a fragment of url and i don't know how this fragment appeared there? here is an examle:
in google seach is:
http://dobry-portal.pl/part1-/Tranformers,main,film,0
real adres is
http://www.dobry-portal.pl/Tranformers,main,film,0
Sometimes adrress on google seach have more than one part between slashes ex. http://dobry-portal.pl/part1-/part2-/part3-/Tranformers,main,film,0
How can i simply cut of that parts in htaccess to redirect to real adres http://www.dobry-portal.pl/Tranformers,main,film,0
I've tried

RewriteRule (.)/part1-/(.) $1/$2 [L]

but this is not work
Thanks for help,
Adam

A: Try this:
RewriteRule ^(.*)(/part[0-9]+-)+(.*)$    $1$3 [L]

You may also try the RewriteCond pattern:
RewriteCond %{REQUEST_URI}   ^(.*)(/part[0-9]+-)+(.*)$ [NC]
RewriteRule ^                %1%3 [L]

For more details see the documentation.

A: This should remove all the "fake subdirectories" between slashes for you:
RewriteRule ^.*/([^/,]*,.*) $1 [L,R=301]

*

*^.*/ greedily matches the path up to the last forward slash

*([^/,]*,.*) captures to Group 1...

*[^/,]* any characters that are not slashes or commas,

*,.* then a comma and he rest of the string

*The $1 back-reference substitutes Group 1 for the url

*[L,R=301] last rule, permanent redirect

I'm sure some tweaks are possible, but this should get you started.


text:
Q: Add third level to php menu in WP? I'm attempting to add a for loop to a php menu that will add a tertiary level to a currently existing WP menu.  Unfortunately, the only editable amount of content is that posted below, so please bear with me on this one.
I'm just wondering, before I attempt to implement this code, if anyone can tell me if it will actually work, of if you assume it'll break everything.
What I've done is to take the same semantic forloop that was written for the secondary (or 'sub_nav') menu items, and repeat it in attempts to dynamically generate third level (or 'tert_nav') menu items.

<?php
    $main_nav_items = wp_get_nav_menu_items(2);
    $sub_nav = array();
    foreach ($main_nav_items as $item) {
        if($item->menu_item_parent !== '0'){
            $parent_id = $item->menu_item_parent;
            $sub_nav[$parent_id][] = array('item' => $item);
        }
    }
    $tert_nav = array();
    foreach ($sub_nav_items as $item) {
        if($item->menu_item_parent !== '0'){
            $parent_id = $item->menu_item_parent;
            $tert_nav[$parent_id][] = array('item' => $item);
        }
    }
?>

    <?php foreach ($sub_nav as $key => $value) { ?>
        <ul class="nav sub-nav" data-parent="<?php print $key; ?>">
            <?php foreach ($value as $item) { ?>
                <?php if(isset($_GET['archive'])): ?>
                    <li class="menu-item-<?php print $item['item']->object_id; ?> <?php print ($item['item']->title == 'Archives') ? 'current-menu-item' : 'menu-item'; ?>"><a href="<?php print $item['item']->url; ?>"><?php print $item['item']->title; ?>
                        <?php foreach ($tert_nav as $key => $value) { ?>
                            <ul class="nav tert-nav" data-parent="<?php print $key; ?>">
                                <?php foreach ($value as $item) { ?>
                                    <?php if(isset($_GET['archive'])): ?>
                                        <li class="menu-item-<?php print $item['item']->object_id; ?> <?php print ($item['item']->title == 'Archives') ? 'current-menu-item' : 'menu-item'; ?>"><a href="<?php print $item['item']->url; ?>"><?php print $item['item']->title; ?>

                                    <?php else: ?>
                                        <li class="menu-item-<?php print $item['item']->object_id; ?> <?php print ($item['item']->object_id == get_the_ID()) ? 'current-menu-item' : 'menu-item'; ?>"><a href="<?php print $item['item']->url; ?>"><?php print $item['item']->title; ?>

                                    <?php endif; ?>
                                <?php } ?>

                        <?php } ?>

                <?php else: ?>
                    <li class="menu-item-<?php print $item['item']->object_id; ?> <?php print ($item['item']->object_id == get_the_ID()) ? 'current-menu-item' : 'menu-item'; ?>"><a href="<?php print $item['item']->url; ?>"><?php print $item['item']->title; ?>
                        <?php foreach ($sub_nav as $key => $value) { ?>
                            <ul class="nav tert-nav" data-parent="<?php print $key; ?>">
                                <?php foreach ($value as $item) { ?>
                                    <?php if(isset($_GET['archive'])): ?>
                                        <li class="menu-item-<?php print $item['item']->object_id; ?> <?php print ($item['item']->title == 'Archives') ? 'current-menu-item' : 'menu-item'; ?>"><a href="<?php print $item['item']->url; ?>"><?php print $item['item']->title; ?>

                                    <?php else: ?>
                                        <li class="menu-item-<?php print $item['item']->object_id; ?> <?php print ($item['item']->object_id == get_the_ID()) ? 'current-menu-item' : 'menu-item'; ?>"><a href="<?php print $item['item']->url; ?>"><?php print $item['item']->title; ?>

                                    <?php endif; ?>
                                <?php } ?>

                        <?php } ?>

                <?php endif; ?>
            <?php } ?>

    <?php } ?>

Any help would be so very greatly appreciated.  Thank you!!


text:
Q: How to disable the try it function in the Azure API management developer portal? On the Azure API management developer portal, there is a "Try it" feature to test api request in your browser.
The try it button:

Is it possible to disable/remove this feature? I don't want developers to be able to post test data inside our production environment.

A: I found a way to hide the try it button. This doesn't completely disable the feature, but makes it hidden for the user.

*

*Go to the Developer portal logged in as an admin.

*Click on the Edit icon on the top right

*Select Template => Operation.

*This should open a markup window. Look for the try it button. It should look like this

    Try it

*Either remove the tag entirely or wrap it in a if/unless. Azure apim uses the DotLiquid language for its templates. I ended up doing this.

{% assign apiNamePrefix = api.name | slice: 0, 4 %}
{% if apiNamePrefix == 'TEST' %}

    Try it

{% endif %}

*Save your changes. Then Publish.


text:
Q: Script to mv the files with file sequence which is lowest Could you help me how to write a shell script
I have the below set of files with
Folder path: abc/xyz
abc122.1001.csv
abc122.1002.csv
abc122.1003.csv

I want to search for the abc122.* files in a folder location and move all the files to another location except the file with the lowest sequence number (1001, 1002...)
ex: abc122.1001.csv is the lowest sequence file, all other files with abc122* have to be moved to another location.
I've tried the command below, but it doesn't work
find /abc/xyz -name 'abc122*' |sort -r | tail -n1 |  mv {} u05/BACKUP/OLD

A: This can be a starting point:
move_all_but_one.sh
#!/bin/bash

shift

if [ $# -gt 0 ]; then
        mv $@ u05/BACKUP/OLD/
fi

Than run it:
./move_all_but_one.sh abc122*

But still not a final solution as it can crash for very long list of files (argument list too long).

A: The syntax {} is for the exec command of find, not for mv nor the shell.
Replacing | mv ... with
| while read f; do mv "$f" u05/BACKUP/OLD; done

should help, no ?
the | sort -r | tail -n 1 could be replaced by | sort | tail -n +2


text:
Q: ASP.Net Core MVC Routing Issue I am working on a project (Developed by using .Net Core), I have set some routes and one of them is not working e.g.
1) routes.MapRoute("HRDetail", "H-R/{TName}/{MId}", new { controller = "ABC", action = "XYZ1" });
2) routes.MapRoute("CL", "{SName}/{CName}/{CId}", new { controller = "ABC", action = "XYZ2" });

I have written the code in the same sequence in Startup class, and my action methods are as follows.
public async Task<IActionResult> XYZ2(string SName, string CName, Int16 CId)
{//for route#2}
public async Task<IActionResult> XYZ1( string TName, Int64 MId)
{//for route#1}

Now I want to hit on XYZ1 by using route#1 and the link (to hit on XYZ1 is being created dynamically) is like this http://localhost:4321/H-R/UK/1234. But the problem is that when i click on this link, it always take me to XYZ2 method.
I didn't set any route on controller or action method level.
Is there any solution plz?

A: It seems, The route are getting confused. There are two ways you can fix this.
1) in your first route specify the regular expression which will say that first parameter will be a fixed string as H-R
2) in you second route specify the regular expression which will say that first parameter will never be H-R
1st
routes.MapRoute("HRDetail", "{ActionName}/{TName}/{MId}", new { controller = "ABC", action = "XYZ1" }, new{ActionName = "$your regularexpression to include only H-R$"});

OR
routes.MapRoute("CL", "{SName}/{CName}/{CId}", new { controller = "ABC", action = "XYZ2" }, new {SName = "$your regularexpression to exclude H-R$" });

PS: you need to put some efforts for regular expression


text:
Q: paintbox doesnt paint from timer method c++ builder borland I am using Borland C++Builder 6.
I have two methods of the form:
void __fastcall FDisplay::PaintBox1Paint(TObject *Sender)
void __fastcall FDisplay::TimerLabelsViewTimer(TObject *Sender)

In the first method I draw the coordinate system.
and in the second method I did:
    PaintBox1->Canvas->MoveTo(693,201);
    PaintBox1->Canvas->LineTo(770,187);

and the line doesn't appear on the coordinate system.
my second question, how can I erase the line and return to the base paint?  Should I do this?
PaintBox1->Invalidate();
PaintBox1->Update();

A: You must do ALL of the drawing inside of the OnPaint event handler.  That includes your line drawing.  Your OnTimer event handler cannot draw directly on the PaintBox, the drawing will be lost the next time the PaintBox is painted for any reason.
What you can do instead is have the OnTimer handler store the desired coordinates for the line drawing and then Invalidate() the PaintBox to signal a repaint.  The OnPaint event can then draw the line at the stored coordinates.  To erase the line, Invalidate() the PaintBox and simply don't draw the line.
For example:
private:
    TPoint lineStartPos;
    TPoint lineEndPos;

...

void __fastcall FDisplay::PaintBox1Paint(TObject *Sender)
{
    //...

    if (!lineStartPos.IsEmpty() && !lineEndPos.IsEmpty())
    {
        PaintBox1->Canvas->MoveTo(lineStartPos.x, lineStartPos.y);
        PaintBox1->Canvas->LineTo(lineEndPos.x, lineEndPos.y);
    }

    //...
}

void __fastcall FDisplay::TimerLabelsViewTimer(TObject *Sender)
{
    //...
    PaintBox1->Invalidate();
}

To draw the line:
lineStartPos = Point(693,201);
lineEndPos = Point(770, 187);
PaintBox1->Invalidate();

To erase the line:
lineStartPos = TPoint();
lineEndPos = TPoint();
PaintBox1->Invalidate();


text:
Q: How can I display all of the information from a single column from MySQL? I am programming a discord bot and am fairly new with MySQL. I've tried to do this myself, but maybe I'm missing something.
I want to display all of the information from a specific column for all rows in a table. It'll do that, however, my method has so far proven to send three separate discord messages, and I would like it only to send one.
I know that i++ will increment, but I didn't think it'd increment into three messages. Not too sure what to do about this, as I'm not an expert.
Many thanks in advance!!
const [check1, check1d, check1e] = await pool.query("SELECT `TeamName` FROM `performancetracker`.`queue`");

var i;

for (i = 0; i < check1.length; [i++]) {
  const result = (`${check1 [i].TeamName}`)

  const embed = new MessageEmbed()
    .setTitle("Test Name")
    .setDescription(`Test Description`)
    .addField('Team Name:', `${result}`, true)
    .setTimestamp()

  message.channel.send(embed);
}

A: The problem is that you're using message.channel.send()on every loop, thus the message will be sent again. You need to use it after the loop is done.
You also need to define the embed before the loop and only use .addField() inside of it.
Like this:
var i;

const embed = new MessageEmbed()
  .setTitle("Test Name")
  .setDescription(`Test Description`)
  .setTimestamp()

for (i = 0; i < check1.length; [i++]) {
  const result = (`${check1 [i].TeamName}`)
  embed.addField('Team Name:', `${result}`, true)
}

message.channel.send({ embeds: [embed] });


text:
Q: Method Not Allowed (POST): / I'm trying to make a simple one-paged shop. I made a ListView of the items and it renders no problem. The shopping cart will be in a modal. I made the buy button, but whenever I press it, it says:
Method Not Allowed (POST): /
Method Not Allowed: /
[22/Dec/2021 11:40:04] "POST / HTTP/1.1" 405 0

Here are my views:
from django.shortcuts import render
from django.views.generic import ListView
from .models import Item
from .forms import AddCartForm

class ItemsListView(ListView):
    model = Item
    template_name = 'main_page.html'

def aBuy(request):
    form = AddCartForm
    if request.method == 'POST':
        print('BUY BUY')
    return render(request, 'main_page.html', {'form':form})

This is the form:
class AddCartForm(ModelForm):
    class Meta:
        model = Item
        fields = ['price', 'quantity']

The form in html:
<div class="col" style="text-align:left">
                          <form name="buy" method="POST">
                              {% csrf_token %}
                              {{ form }}
                            <input type="submit" class="btn btn-info butt" value="Buy">
                          </form>
                      </div>

I cannot continue making the logic for adding it to the future cart because of it. print('BUY BUY') is just for testing.
In the url file it's only the main page with ItemListView.as_view. I tried putting the aBuy function in it and out, same problem remains.

A: You forgot the action attribute in your form:
<form action="/path-to-post-url/" method="post">
  {% csrf_token %}
  {{ form }}
  <input type="submit" value="Submit">
</form>

You can read more about templatings and forms here  Django Forms.


text:
Q: Class 'PhpOffice\PhpWord\TemplateProcessor' not found I have PHPWORD in /libraries/PhpOffice/PhpWord/ directory. I'm trying to use it in completly other part of app (Joomla website) like this:
require_once JPATH_LIBRARIES.'/vendor/autoload.php'; //composer
require_once JPATH_LIBRARIES.'/PhpOffice/PhpWord/PhpWord.php';
$Wzor = new \PhpOffice\PhpWord\TemplateProcessor(JPATH_ROOT.'/images/powiadomienia/SzablonPowiadomienia.docx');

But I get error:

Class 'PhpOffice\PhpWord\TemplateProcessor' not found

I tried many variants and paths, I tried to read online help but always with the same result. Can I ask for for some help and guidance? How can I include such class to my script?

A: Use the /vendor folder, not "libraries" (see why below).
In your project root folder:
composer require phpoffice/phpword

Then:
require_once JPATH_ROOT.'/vendor/autoload.php';
$Wzor = new \PhpOffice\PhpWord\TemplateProcessor(JPATH_ROOT.'/images/powiadomienia/SzablonPowiadomienia.docx');

WARNING:
NEVER run a "composer require" inside the "/libraries" folder as it WILL DELETE the Joomla core on more recent versions. This happens because people were using this folder and to emphatize that it shouldn't be used, the Joomla core team removed the composer.json file from it. Because of this, the Joomla core is wiped out when trying to add libraries on this folder.

Why not use "/libraries"?
From https://docs.joomla.org/J3.x:Using_Composer_with_Joomla:

Can you install any extra libraries via Composer?
Not at the moment in Joomla! 3.4. In the longer term it is the CMS's
  aim that you can download extra packages. To emphasize this, we will
  not yet be releasing the composer.json file within the main Joomla!
  download.

A: From what I found out problem was used framework - Joomla. It has its own method to discover classes. I had to put files into /libraries/src folder and then put this code to use this class:
JLoader::registerNamespace('PhpOffice', JPATH_LIBRARIES . '/src');
$objPHPWord = new \PhpOffice\PhpWord\PhpWord();

A: you need to install phpoffice/phpword with composer
composer require phpoffice/phpword


text:
Q: Lagrange Interpolation Polynomial Code for coefficients Can someone help me with developing a simple MATLAB code that inputs the n datasets $ \lbrace x_i : i=0,...,n \rbrace$ and $ \lbrace f^i : i=0,...,n \rbrace$ and produces the coefficients $ \lbrace c_i : i=0,...,n \rbrace$ of the Lagrange Polynomials?
I have an understanding of how to achieve the polynomial itself, but extracting each coefficients I am new to. Any help would be great :)
Thanks :)

A: You can find coefficients of Lagrange interpolation polynomial relatively easy if you use a matrix form of Lagrange interpolation presented in "Beginner's guide to mapping simplexes affinely", section "Lagrange interpolation" (you may check for concrete example in "Workbook on mapping simplexes affinely", section "Lagrange interpolation"). General formula looks as follows
$$
f(x) = (-1)
\frac{
    \det
    \begin{pmatrix}
        0       & f_0       & f_1       & \cdots & f_n       \\
        x^n     & x_0^n     & x_1^n     & \cdots & x_n^n     \\
        x^{n-1} & x_0^{n-1} & x_1^{n-1} & \cdots & x_n^{n-1} \\
        \cdots  & \cdots    & \cdots    & \cdots & \cdots    \\
        1       & 1         & 1         & \cdots & 1         \\
    \end{pmatrix}
}{
    \det
    \begin{pmatrix}
        x_0^n     & x_1^n     & \cdots & x_n^n     \\
        x_0^{n-1} & x_1^{n-1} & \cdots & x_n^{n-1} \\
        \cdots    & \cdots    & \cdots & \cdots    \\
        1         & 1         & \cdots & 1         \\
    \end{pmatrix}
}.
$$
Using Laplace expansion along the first column you can get expressions for coefficients at $x^i$.
CODE
I'm afraid, I don't know Matlab good enough to provide you with appropriate code, but I worked with Python a little bit, maybe the following can help (sorry for bad codestyle -- I'm mathematician, not programmer)
import numpy as np
# input
x = [0, 2, 4, 5]  # <- x's
y = [2, 5, 7, 7]  # <- y's
# calculating coefficients
M = [[_x**i*(-1)**(i*len(x)) for _x in x] for i in range(len(x))]
C = [np.linalg.det((M+[y]+M)[d:d+len(x)]) for d in range(len(x)+1)]
C = (C / C[0] * (-1)**(len(x)+1) )[1:]
# polynomial lambda-function
poly = lambda _x: sum([C[i] * _x**i for i in range(len(x))])
# output and tests
print("Coefficients:\n", C)
print("TESTING:")
for _x, _y in zip(x, y):
    result = "[OK]" if np.allclose(_y, poly(_x)) else "[ERROR]"
    print(_x, " mapped to: ", poly(_x), " ; expected: ", _y, result)

This code calculates coefficients of the Lagrange interpolation polynomial, prints them, and tests that given x's are mapped into expected y's. You can test this code with Google colab, so you don't have to install anything. Probably, you can translate it to Matlab.

A: function a = coefPolinomLagrange (x, y)
n = length(x);
M = [];
for i=1:n
    M = [M; x.^(i-1)'];
end

denom = M;
det_denom = det(denom);

Mcirc = [M;y';M(1:end-1,:)];

for i=1:n
    numer = Mcirc(i+1:i+n,:);
    a(i) = (-1)^(n-i) * det(numer) / det_denom;
end
a = fliplr(a);
end


text:
Q: Why doesn't `sizeof()` work as expected when the argument is a dereferenced pointer pointing to an array? My problem is when using sizeof(), the result is the pointer size not the array pointed to.
Please, help me.
Here is the code.
The first function creates a 2d matrix and the second displays it while the main function performs a test.
 #include<iostream>
 template<typename T>
    T** Mat(T vals[],size_t m, size_t n){

        T** mat=new T*[m];

        for(size_t i=0;i<m;i++) mat[i]=new T[n];

        for(size_t mi=0;mi<m;mi++){

            for(size_t ni=0;ni<n;ni++){
                mat[mi][ni]=vals[mi*(n-1)+ni];

            }
        }
        return mat;
    }

template<typename T>
void dispMat2d(T** mat){

    for(size_t mi{};mi<sizeof(*mat)/sizeof(mat[0]);mi++){

        std::cout<<"I'm here "<<sizeof(*mat)/*/sizeof(mat[0])*/<<"\n";

            for(size_t ni{};ni<sizeof(*mat[0])/sizeof(mat[0][0]);ni++){
                std::cout<<"o"<<mat[mi][ni]<<"\t";

            }
            std::cout<<std::endl;
    }
}
int main(int c, char* arr[]){

    double v[]={1.0,2,3,4,5,6};

    auto myMat=Mat<double>(v,2,3);

    dispMat2d(myMat);

    return 0;
}

I tried to use std::size() but it doesn't accept the arguments *myMat1 and **myMat1.
Thanks in advance

A: Pointers do not keep the information whether they point to a single object or first element of an array.
Compare
int *p = new int();

and
int *p = new int[10]();

So sizeof( *p ) in the both cases is equivalent to sizeof( int ).
So you have to pass sizes of arrays explicitly.
Pay attention to that the function Mat has a bug.
Instead of
mat[mi][ni]=vals[mi*(n-1)+ni];

there must be
mat[mi][ni]=vals[mi * n + ni];

A: Arrays decay into pointers when passed as arguments to functions, so the size information is lost.
One way to make it work is to take the argument as a reference to an array of a specific size.
Example:
#include<array>
#include<iostream>

// helper
template<typename T, size_t Y, size_t X>
using mat_t = std::array<std::array<T, X>, Y>;

template<typename T, size_t Y, size_t X, size_t N>
auto Mat(const T (&vals)[N]) {
    static_assert(Y*X<=N, "vals[] too small"); // compile time assertion
    mat_t<T, Y, X> mat;

    for(size_t mi=0; mi<Y; ++mi) {
        for(size_t ni=0; ni<X; ++ni) {
            mat[mi][ni] = vals[mi*X+ni];       // bugfix
        }
    }
    return mat;
}

template<typename T, size_t Y, size_t X>
void dispMat2d(const mat_t<T, Y, X>& mat){

    for(size_t mi=0; mi<Y; ++mi){
        for(size_t ni=0; ni<X; ++ni) {
            std::cout << 'o' <<mat[mi][ni] << '\t';
        }
        std::cout << '\n';
    }
}
int main(){
    double v[]={1,2,3,4,5,6};
    auto myMat=Mat<double,2,3>(v);
    dispMat2d(myMat);
}


text:
Q: 10gen mms monitoring service to start after reboot I have setup MMS agent for my mongoD instances on AWS. MMS Agent is on a separate t1.micro instance. It all works fine however, every time I reboot the server I have to run sudo nohup python agent.py > agent.log 2>&1 & to start the service!!
How can I add this to service so with every reboot MMS Agent starts too!

A: If you are running Ubuntu you could use the following Upstart script ( /etc/init/mms_agent.conf ):
#
# description   "mms_agent"
#

start on runlevel [2345]
stop on runlevel [06]

respawn
respawn limit 2 5

env PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
env LOGFILE=/opt/mms_agent/mms_agent.log

respawn
respawn limit 2 5

kill timeout 60

chdir /opt/mms_agent

script

  exec su -c 'python agent.py' mms_agent >> $LOGFILE 2>&1

end script


text:
Q: Trying profile routes on Backend with node js without using passport.js for authentication I am trying to do profile page for user on my project without using passaport.js for authentication.
I created my middleware for auhtentiction which is check-auth.js. I am using insomnia for accessing my profile routes with token. I am getting error from check-auth.js.Is anyone can help me for this issue?
Thanks

*

*This is middleware for authentication  (check-auth.js)

const jwt = require('jsonwebtoken')
const HttpError = require('../models/HttpError')

module.exports = (req, res , next) => {
  if(req.method === 'OPTIONS'){
      return next()
    }
  try {
    const token = req.headers.authorization.split(' ')[1]                       //We took token from headers authorization.( Bearer 'token')
    if(!token){                                                                 // We check token if it is falsy.If it is, We will send error for authentication failed
          throw new Error('Authentication failed')
    }

    const decodeToken = jwt.verify(token,process.env.JWT_SECRET_KEY)            // for verifying token we need token and our secret key.
     console.log(decodeToken.userId)
     console.log(req.isLoggedIn)

     req.userData = {userId:decodedToken.userId}                                // We will use userid to delete and edit  recipes and meals. we need that.
     next()                                                                     // It is authenticated go next middleware

  }
  catch(err){                                                                   // if our token does not match with the token.
    const error = new HttpError('Authentication failed mi', 403)
    return next(error)                                                          // Send error
  }
}

2-This is my user controller for profile page.(users.js)
const profile = async(req, res, next) => {

  let existingUser
  try{
        existingUser = await User.findById(req.userData.userId,'-password').exec()
     }
  catch(err){
       const error = new HttpError('Profile failed, please try again', 500)
       return next(error)
     }
     if(!existingUser){
       const error = new HttpError('User does not exist',422)
     }

    res.status(200).json({user:existingUser.toObject({getters:true})})
}

3-This my routes for user    (user-routes)
const express = require('express')
const {check} = require('express-validator')
const router = express.Router()
const usersController = require('../controllers/users')
const checkAuth = require('../middleware/check-auth')

router.post('/signUp', [
  check('username').not().isEmpty(),
  check('age').not().isEmpty(),
  check('gender').not().isEmpty(),
  check('email').normalizeEmail().isEmail(),
  check('password').isLength({min:6})
],usersController.signUp)
router.post('/login',[
  check('email').normalizeEmail().isEmail(),
  check('password').isLength({min:6})
],usersController.login)
router.use(checkAuth)
router.get('/profile',usersController.profile)
module.exports = router


text:
Q: Excel Listobject Table Insert Rows Causes Cell Formula Error Background:
I've created a Word template that contains a routine that creates an array which holds a Project title in the first dimension and a Goal title in the second dimension.  This array is transposed to a table in Excel to be used in creating a timeline/gantt chart.
Problem:
The transpose places the array information appropriately into an Excel table and expands the size of that table as desired.  Cell B5 is the beginning of the DataBodyRange and the start of where I want to paste the array information.
' paste headings from array into excel
xlWS.Range("B5:C" & UBound(gHeadings, 2)) = xlApp.Transpose(gHeadings)

What does not occur in the proper manner is in subsequent data cells within the table.  Timeline cells have the following formula:
=IF(AND(COLUMNS($H$5:H10)>=$E5,COLUMNS($H$5:H10)<=$F5),IF(COLUMNS($H$5:H10)-$E5<ROUND(($F5-$E5+1)*$G5,0),fillblock,""),"")

When the transpose is finish, the row of cells containing the referenced formula errors on the row of the table that was the original last row of the DataBodyRange.  On that row, row 10, the formula gets changed from what's displayed above to:
=IF(AND(COLUMNS($H$5:H119)>=$E10,COLUMNS($H$5:H119)<=$F10),IF(COLUMNS($H$5:H119)-$E10<ROUND(($F10-$E10+1)*$G10,0),fillblock,""),"")

Any thoughts or understanding of why this happens, and how to prevent it?

A: The overall answer as to why Excel Tables behave in the fashion I've described is not answered.  But, here is my workaround.  The speed hit is negligible.
    ' variable to hold the formula and fix the double-quote ("") issue in vba
        sEmpty = Chr(34) & Chr(34)
        sFormula = "=IF(AND(COLUMNS($H$5:H5)>=$E5,COLUMNS($H$5:H5)<=$F5),IF(COLUMNS($H$5:H5)-$E5<ROUND(($F5-$E5+1)*$G5,0),fillblock," & sEmpty & ")," & sEmpty & ")"

    ' paste cell formula into the new worksheet
        lTblRows = xlLO.DataBodyRange.Rows.Count
        xlWS.Range("H5:AK" & lTblRows + 4).Formula = sFormula

This effectively copies the formula into each cell referenced within the table, copying over the cells that got mis-referenced during the row insert.