text:
Q: AVL tree(c++), program keeps on crashing I am working on an exercise in processing an AVL tree. The debugger shows no errors. I ran the program and it is supposed to output an output text file. However the program crashes every time.
#include <stdio.h>
#include <assert.h>
#include <algorithm>
#include <vector>
using namespace std;

struct node
{
    int key;
    int height;
    node *left, *right;
    node(int k)
    {
        key = k;
        height = 1;
        left = right = 0;
    }
};

void pre_order(node* root)
{
    if(root == 0) return;
    printf("%d", root->key);
    printf(" ");
    pre_order(root->left);
    pre_order(root->right);
}

void in_order(node* root)
{
    in_order(root->left);
    printf("%d", root->key);
    printf(" ");
    in_order(root->right);
}

int height(node* r)
{
    return r ? r->height : 0;
}

void update_height(node* root)
{
    if(root == 0) return;
    int hl = height(root->left), hr = height(root->right);
    root->height = std::max(hl, hr) + 1;
}

node* right_rotate(node* ref_root)
{
    assert(ref_root && ref_root->left);
    node *a = ref_root, *b = ref_root->left;
    a->left = b->right;
    b->right = a;

    update_height(a);
    update_height(b);
    return b;
}

node* left_rotate(node* ref_root)
{
    assert(ref_root && ref_root->right);
    node *c = ref_root, *d = ref_root->right;
    c->right = d->left;
    d->left = c;
    update_height(c);
    update_height(d);
    return d;
}

node* maintain(node* ref_root)
{
    if(ref_root == 0) return ref_root;
    update_height(ref_root);
    node* ret = ref_root;
    if(height(ref_root->left) > height(ref_root->right) + 1)
    {
        node* p = ref_root->left;
        if( height(p->left) < height(p->right) )
            ref_root->left = left_rotate(p);
        ret = right_rotate(ref_root);
    }
    else if(height(ref_root->right) > height(ref_root->left) + 1)
    {
        node* p = ref_root->right;
        if(height(p->right) < height(p->left)){
            ref_root->right = right_rotate(p);
        }
        ret = left_rotate(ref_root);
    }
    return ret;
}

node* insert_key(int key, node* ref_root)
{
    if(ref_root == 0)
    {
        return ref_root = new node(key);
    }
    if(key < ref_root->key){
        node* child = insert_key(key, ref_root->left);
        ref_root->left = child;
        }
    else if(key > ref_root->key){
        node* child = insert_key(key, ref_root->right);
        ref_root->right = child;
    }
    else
        assert(0);

    return maintain(ref_root);
}

vector<node*> minimum(node* T) {
    vector<node*> x;
    node* y = T;
    while (y->left != NULL) {
        x.push_back(y->left);
    }
    return x;
}

node* delete_key(int key, node* ref_root)
{
    if(key < ref_root->key){
        node* child = delete_key(key, ref_root->left);
        ref_root->left = child;
        }
    else if(key > ref_root->key){
        node* child = delete_key(key, ref_root->right);
        ref_root->right = child;
        }
    else
    {
        if(ref_root->left && ref_root->right)
        {
            vector <node*> y = minimum(ref_root->right);
            node* successor = y.back();
            node* sParent = y[y.size()-2];
            ref_root->key = successor->key;
            sParent->left = successor->right;
        }
        else
        {
            if(ref_root->left != NULL){
                ref_root = ref_root->left;
            }
            else if(ref_root->right != NULL){
                ref_root = ref_root->right;
            }
        }
    }

    return maintain(ref_root);
}

int main()
{
    node *root = 0;
    char op[10] = "";
    int k;
    while(true)
    {
        scanf("%s", op);
        if(op[0] == 'E') break;
        switch(op[0])
        {
        case 'A': scanf("%d", &k); root = insert_key(k, root); break; //Insert
        case 'D': scanf("%d", &k); root = delete_key(k, root); break;//Delete
        case 'P': pre_order(root); printf("\n"); break;//preorder
        case 'I': in_order(root); printf("\n"); break;//inorder
        default: assert(0);
        }
    }
    return 0;
}

A: There is no check in the in_order function that root is not NULL.


text: Q: Getting the current progress of fit_generator in keras I am trying to find a way to get the current epochs/steps while training a model in keras. I plan to run it on a separate thread in my program so that I can display something like a progress bar for my UI. I am having trouble with getting the values for it. Is there something like a function that allows me to get the progress of the training in keras other than what is displayed in the console?

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to draw a lot of rectangles on canvas with good performance? I've got to render a cinema hall map with sectors, rows and seats.
Currently I have around 1000 of seats (filled rectangles) to draw and I'm doing this for every seat by calling:
canvas.drawRect(seatRect, seatPaint)

My view must also support scaling, scrolling and fling.
The performance is awful. I tried to improve it by explicitly enabling hardware acceleration but nothing changed, it seems it was enabled by default on my Nexus 4 (Api 22)
Could you please suggest any methods to render huge number of rectangles at high speed ? So movement, scaling animation is smooth.
Custom View class code:
@Override
public void onDraw(Canvas canvas) {
    super.onDraw(canvas);

    canvas.save();
    canvas.scale(mScaleFactor, mScaleFactor); // scaling support
    canvas.translate(mTranslateX, mTranslateY); // scrolling support

    if (mEventMap != null) {
        mEventMap.paint(canvas);
    }

    canvas.restore();
}

EventMap code:
public void paint(Canvas canvas) {
    for (EventPlace place : places) {
        if (place.isSelected())
            placePaint.setColor(0xFF00FF00);
        else if (place.isAvailable())
            placePaint.setColor(place.getColor());
        else
            placePaint.setColor(0xFF000000);

        canvas.drawRect(place.getBounds(), placePaint);
    }
}

None of the methods called in onDraw create any instances.
There are just a LOT of rectangles...

A: The main problem that you have right now is basically the fact that you perform a large amount of drawing cycles (equal to the number of Rects you have) it's better to store all those rects in Path object, in order to reduce number of drawing cycles. Since you have three states of seats I suggest creation of three Paths. I would suggest doing something like this:
private void init() {
    mSelectedPath = new Path();
    mAvailablePath = new Path();
    mUnavalablePath = new Path();

    mAvailablePaint = new Paint();
    mSelectedPaint = new Paint();
    mUnavalablePaint = new Paint();

    mUnavalablePaint.setColor(Color.RED);
    mSelectedPaint.setColor(Color.YELLOW);
    mAvailablePaint.setColor(Color.GREEN);

    for (EventPlace place : mData) {
        if (place.isSelected())
            mSelectedPath.addRect(rectF, Path.Direction.CW);
        else if (place.isAvailable())
            mAvailablePath.addRect(rectF, Path.Direction.CW);
        else
            mUnavalablePath.addRect(rectF, Path.Direction.CW);
    }
}

Then when you want to associate date with this View you should do something like this:
public void setData(List<EventPlace> data) {
    mData = data;
    init();
    invalidate();
}

Actually you can do it however you like, just keep in mind that you have to call init method and then invalidate. And in the onDraw:
@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);

    canvas.save();
    canvas.scale(mScaleFactor, mScaleFactor); // scaling support
    canvas.translate(mTranslateX, mTranslateY); // scrolling support

    canvas.drawPath(mAvailablePath, mAvailablePaint);
    canvas.drawPath(mUnavalablePath, mUnavalablePaint);
    canvas.drawPath(mSelectedPath, mSelectedPaint);

    canvas.restore();
}

Perhaps you would also want to add some logics to exclude those Rects that are not visible at the moment from paths in order to tweak performance.
I tried animating my approach on test set of Rects and it was running smoothly with 200 rects, I didn't try performing a serious benchmark though


text:
Q: How to add a Tab from one class to a JTabbedPane from another class? I've been working with JTabbedPane's for a little while now, but I have a problem with adding a tab to a JTabbedPane that is initiated in a separate class.
Here's my code...:
import javax.swing.*;
public class ProgLoteDeCarrosVentana
{
    public static void main (String [] Yoshi)
    {
         Windows Frame = new Windows();
         Frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         Frame.setSize(1280, 720);
         Frame.setVisible(true);

    }   //  public static void main (String [] Yoshi)
}   //  public class ProgLoteDeCarrosVentana

class Windows extends JFrame
{
    public JTabbedPane()
    {
        JTabbedPane Tabs = new JTabbedPane();
        JPanel Tab1 = new JPanel();

        Tabs.addTab("Information", Tab1);

        getContentPane().add(Tabs);

    }   //  public JTabbedPane
}   //  class Windows extends JFrame

What I'm trying to do is add a tab, created in 'class Windows', to 'Frame', initiated in the main.
Here's an example of what I'm trying to achieve...: Example
If someone can help me out, I'd appreciate it a lot! Thank you for reading.


text:
Q: Is there a way to change the Eclipse plug-in Team Explorer Everywhere login and password? A new developer installed the TEE plug-in into Eclipse.  Because he hadn't yet been granted access, he borrowed my login and username.  Now that he has been granted access, is there a way to go back and change to using his credentials instead of mine?  I couldn't find any way to do it; there doesn't seem to be any option within Eclipse, under Windows->Preferences->Team or anywhere else.
The last resort I can think of is to completely uninstall and reinstall the plug-in, but I'm not even confident that will work in case Eclipse is hanging on to the credentials somehow. And in any case we'd prefer to do it without having to completely reinstall.

A: Unfortunately, TFS workspaces are created per-user.  If the new developer were to sign in as himself, he cannot load the TFS workspace that he originally used (impersonating you), and the TFS plug-in for Eclipse will not be able to connect his Eclipse projects to TFS.  He'll need to set up a new TFS workspace with the appropriate working folder mappings (the same as the one he's using now).
This can be done manually, but it's probably far easier to simply create a new Eclipse workspace and import the projects again.  There's no need to reinstall Eclipse or the Team Explorer Everywhere plug-in in order to accomplish this, but he does need to reconfigure his profiles (the mechanism used to store connection information in Team Explorer Everywhere 2010.)
He should perform the following steps in order to start over (and authenticate as himself):

*

*Have the developer shelve or check-in any pending changes.  His pending changes will be lost when he creates a new TFS workspace.

*Quit all instances of Eclipse.

*Delete the TEE profile configuration and the workspace cache - the profile configuration has profiles with your authentication, and the workspace cache has a list of your workspaces (with the profile information that is used to connect to them).  The profile configuration file is:
%LOCALAPPDATA%\Microsoft\Team Explorer\10.0\Profiles\profiles.xml
The workspace cache file is:
%LOCALAPPDATA%\Microsoft\Team Explorer\10.0\Workspaces\workspaces.xml

*Restart Eclipse, and import the necessary projects from TFS.  At this point, he should be prompted to authenticate, and should be able to do so as himself.
Note: this mechanism is a bit different in TEE 2012 - we've removed profiles for simplicity.  If you want to authenticate as a different user, we will respect the Windows credentials storage mechanism just like Visual Studio and Internet Explorer.  (Available in Control Panel -> Manage Windows Credentials.)


text:
Q: form editing with codeigniter i'm trying to edit my form field with codeigniter. The submitted values first shown the view and then the informations are edited. but when i submit the form the following error occurs
A PHP Error was encountered
Severity: Notice
Message: Undefined offset: 0
Filename: views/tupdate.php
Line Number: 46
in line 46 I have
 <input type="hidden" name="id" value="<?php echo $info[0]->id  ?>">

My controller :
 function update($id = 0)
 {
   $data['info'] = $this->trainingUpdate_model->getdata_by_id($id);

   $this->load->view('tupdate', $data);
 }

function super()
{
    $id=$this->input->post('id');
    $data['title']=$this->input->post('title');
    $data['training_description']=$this->input->post('training_description');

    if ($this->trainingUpdate_model->update($id, $data)==TRUE)
    {
      $this->load->view('traing_update_success');
    }
    else
    {
      $this->load->view('S_unsuccess');
    }
}

My Model:
 function getdata_by_id($id = 0)
 {
    $this->db->where('id',$id);
    $sql = $this->db->get('training');
    return $sql->result();
 }

 function update($id,$data)
 {
   $this->db->where('id', $id);
   $this->db->update('training', $data);

   if ($this->db->affected_rows() == '1')
   {
     return TRUE;
   }
   return FALSE;
 }

And View:
 <form action="trainingUpdate/super" method="post">

   <input type="hidden" name="id" value="<?php echo $info[0]->id  ?>">
   Title Name:<input type="text" name="id" value="<?php echo htmlspecialchars($info[0]->title) ?>">
   Title Name: <textarea type="text" name="overview" value=""><?php echo $info[0]->training_description; ?></textarea>

   <input type="Submit" value="Update">
</form>

I'm getting why the information in not updating and why am getting that error.
please help. thanks
For some reason the submitted values are not getting into trainingUpdate/super() method, from where the submitted data is passed to the model. the from is going back to the same view page and giving the error. can anyone tell me why it is happening?? thanks again.

A: if you are getting only one row to update record then use only row() method to fetch only record
Model
function getdata_by_id($id = 0)
 {
    $this->db->where('id',$id);
    $sql = $this->db->get('training');
    //return $sql->result();
    return $sql->row();
 }

view
 <input type="hidden" name="id" value="<?php echo $info->id  ?>">


text:
Q: No recocone el caracter | en una Expresión Regular, Typescript Tengo un arreglo de string que contiene cadenas con este formato
const regiser = "C0000002|ENG|P|L0000002|PF|S0007488|(+)-Cyanidanol|0|"

y para poder reconocer que es valida la cadena genere esta Regex:
const reg_1:RegExp = new RegExp('C[0-9]{7}\|[A-Z]{3}\|[A-Z]\|L[0-9]{7}\|[A-Z]{2}\|S[0-9]{7}\|.*?\|[0-9]\|')

Pero al utlizar el método string.match(regrex) solo reconoce hasta la primera barra | devolviendo [ "C0000002" ], ¿Cómo puedo hacer que reconozca la cadena entera?, siendo que utilizo la barra invertida \ para que | la reconozca como un caracter más y no como un caracter de opciones en las regex.

A: Tal vez el problema sea la manera en que ejecutas tu regex, a mí me funciona tu regex tal como está de la siguiente manera:

const regex = /C[0-9]{7}\|[A-Z]{3}\|[A-Z]\|L[0-9]{7}\|[A-Z]{2}\|S[0-9]{7}\|.*?\|[0-9]\|/gm;
const str = `C0000002|ENG|P|L0000002|PF|S0007488|(+)-Cyanidanol|0|`;
let m;

while ((m = regex.exec(str)) !== null) {
  // Para evitar ciclos infinitos con cero matches
  if (m.index === regex.lastIndex) {
    regex.lastIndex++;
  }

  // El resultado se accede con la variable m.
  m.forEach((match, groupIndex) => {
    console.log(`Coincidencia hallada, grupo ${groupIndex}: ${match}`);
  });
}

A: Econtre que el código inicial funciona correctamente, pero para utilizar caracteres especiales de regex como caracteres ASCII se usa doble barra inversa \\|
const regiser = "C0000002|ENG|P|L0000002|PF|S0007488|(+)-Cyanidanol|0|";

function check_regexp(text:string):void {
    const regexp:RegExp = new RegExp('C[0-9]{7}\\|[A-Z]{3}\\|[A-Z]\\|L[0-9]{7}\\|[A-Z]{2}\\|S[0-9]{7}\\|.*?\\|[0-9]\\|','g');

    console.log(text.math(regexp));
}

check_regexp(register);


text:
Q: Saving SXSSF as .xls file I'm using Apache POI library to import a large amount of data to Excel files. I can't use HSSF model, because of it needs too much memory and Java throws memory heap exception. The way I found is SXSSF workbook model, that writes every N rows to the file instead of storing all workbook in the memory. But I can't find the way, how to save it to .xls (Excel 2003 and lower format) instead of .xlsx.
File f = new File("file.xlsx");
f.createNewFile();
SXSSFWorkbook wb = new SXSSFWorkbook(200);
//inputing values here
FileOutputStream fileOut = new FileOutputStream(f);
wb.write(fileOut);
fileOut.close();

A: You can't.
As explained on the POI Components page, HSSF is for working with .xls files (OLE2 based), and XSSF/SXSSF is for working with .xlsx files (.xlsx)
If you want to generate a .xls file, you'll have to use the HSSF UserModel. There is no streaming write support for HSSF, only streaming read.
The .xls file format isn't so well suited to streaming write as .xlsx (more back/forwards references, offsets etc), so there's no streaming write support in HSSF. Just bump up your Java heap size, or switch to SXSSF for .xlsx, or just use something simple like CSV!
.
Update
If you need to test how much memory you ought to be giving to your system for writing with HSSF, or even XSSF, I'd suggest you try using the SSPerformanceTest example, which can be run on the command line. Fire that up with all the jars, and a given heap size, and see if it completes. It takes arguments of the number of rows and columns, and the type of file to create. Using a nightly build and trying for a 40k row / 10 columns, I can get it to complete quickly in a 90mb heap:
$ java -Xmx90m -classpath poi-3.10-beta3-20131219.jar:poi-examples-3.10-beta3-20131219.jar:poi-ooxml-3.10-beta3-20131219.jar \
     org.apache.poi.ss.examples.SSPerformanceTest HSSF 40000 10 1
Elapsed 1 seconds


text:
Q: Converting string/*.rtf to PDF I have been trying to convert, both, a string and a .rtf document to a PDF document. So far I had mixed success. I have tried 3 different ways (code below) to turn the text into PDF. All of em compile, run and create a PDF, but in all casses the document ends up corrupted.
The error: Link
(https://www.dropbox.com/s/j7sckgwm10gf5ml/PdfError.jpg?dl=0)

*

*Turning a simple string into a PDF document
String msg = "dfsgfdsgdfgfdf";

byte[] messageBytes = System.Text.ASCIIEncoding.ASCII.GetBytes(msg);

System.IO.FileStream stream = new System.IO.FileStream(@"C:\\file.pdf", System.IO.FileMode.CreateNew);
System.IO.BinaryWriter writer = new BinaryWriter(stream);
writer.Write(messageBytes, 0, messageBytes.Length);
writer.Close();

*Similar to method to method 1.:
//String myString: Contains the rft document loaded from the RTF file
byte[] messageBytes = Encoding.UTF8.GetBytes(myString);
System.IO.File.WriteAllBytes(@"C:\foo.pdf", messageBytes);

*And the more complicated attempt 3:
public void wordToPDF() {

     ApplicationClass wordApplication = new ApplicationClass();
     Document wordDocument = null;
     object paramSourceDocPath = @"C:\rtfdoc.rtf";
     object paramMissing = Type.Missing;

     string paramExportFilePath = @"C:\pdfdoc.pdf";
     WdExportFormat paramExportFormat = WdExportFormat.wdExportFormatXPS;
     bool paramOpenAfterExport = false;
     WdExportOptimizeFor paramExportOptimizeFor =
         WdExportOptimizeFor.wdExportOptimizeForPrint;
     WdExportRange paramExportRange = WdExportRange.wdExportAllDocument;
     int paramStartPage = 0;
     int paramEndPage = 0;
     WdExportItem paramExportItem = WdExportItem.wdExportDocumentContent;
     bool paramIncludeDocProps = true;
     bool paramKeepIRM = true;
     WdExportCreateBookmarks paramCreateBookmarks =
         WdExportCreateBookmarks.wdExportCreateWordBookmarks;
     bool paramDocStructureTags = true;
     bool paramBitmapMissingFonts = true;
     bool paramUseISO19005_1 = false;

     try
     {
         // Open the source document.
         wordDocument = wordApplication.Documents.Open(
             ref paramSourceDocPath, ref paramMissing, ref paramMissing,
             ref paramMissing, ref paramMissing, ref paramMissing,
             ref paramMissing, ref paramMissing, ref paramMissing,
             ref paramMissing, ref paramMissing, ref paramMissing,
             ref paramMissing, ref paramMissing, ref paramMissing,
             ref paramMissing);

         // Export it in the specified format.
         if (wordDocument != null)
             wordDocument.ExportAsFixedFormat(paramExportFilePath,
                 paramExportFormat, paramOpenAfterExport,
                 paramExportOptimizeFor, paramExportRange, paramStartPage,
                 paramEndPage, paramExportItem, paramIncludeDocProps,
                 paramKeepIRM, paramCreateBookmarks, paramDocStructureTags,
                 paramBitmapMissingFonts, paramUseISO19005_1,
                 ref paramMissing);
     }
     catch (Exception e)
     {
         MessageBox.Show(e.Message);
     }
     finally
     {
         // Close and release the Document object.
         if (wordDocument != null)
         {
             wordDocument.Close(ref paramMissing, ref paramMissing,
                 ref paramMissing);
             wordDocument = null;
         }

         // Quit Word and release the ApplicationClass object.
         if (wordApplication != null)
         {
             wordApplication.Quit(ref paramMissing, ref paramMissing,
                 ref paramMissing);
             wordApplication = null;
         }

         GC.Collect();
         GC.WaitForPendingFinalizers();
         GC.Collect();
         GC.WaitForPendingFinalizers();
     }
 }

PS: In cases 2 and 3 I load a RTF document, which contains special (german) characters, in case 1. it is just the simple string you see in the code, yet it all ends up the same way (see image with the error above)
I hope someone can help me or point me into the right direction.

A: for solution 3, try to change paramExportFormat:
object paramExportFormat = Microsoft.Office.Interop.Word.WdExportFormat.wdExportFormatPDF;


text:
Q: Get around a 404 with mechanize I'm creating a Python script that would read a file of URLs, but I know not all of them will work. I'm trying to figure out how to get around this and make it read the next line of the file, instead of raising the error that I have posted below. I know I need some kind of if statement but I can't quite figure it out.
from mechanize import Browser
from BeautifulSoup import BeautifulSoup
import csv

me = open('C:\Python27\myfile.csv')
reader = csv.reader(me)
mech = Browser()

for url in me:
    response =  mech.open(url)
    html = page.read()
    soup = BeautifulSoup(html)
    table = soup.find("table", border=3)

for row in table.findAll('tr')[2:]:
    col = row.findAll('td')
    BusinessName = col[0].string
    Phone = col[1].string
    Address = col[2].string
    City = col[3].string
    State = col[4].string
    Zip = col[5].string
    Restaurantinfo = (BusinessName, Phone, Address, City, State)
    print "|".join(Restaurantinfo)

When I run that block of code it raises this error:

httperror_seek_wrapper: HTTP Error 404: Not Found

Basically what I am asking for is how to make Python ignore that and try the next URL.

A: if you only have url in your file maybe it would be more simple to write one url per line and use some code like this:
from mechanize import Browser
from BeautifulSoup import BeautifulSoup

me = open('C:\Python27\myfile.csv')
mech = Browser()

for url in me.readlines():
    ...

if you want to keep your code, you have to use :
for url in reader:
    ...


text:
Q: REST API: Can't find list with GetByTitle() I'm having problems to get lists throught the REST API.
I'm calling: /_api/web/lists/getbytitle('<list title>')
I'm getting an error (List doesn't exists) with that libraries named with more than 1 word. For example I'm not able to get "Site Assets". My sharepoint is in spanish so the titles when i call /_api/web/lists are in spanish.
I tried:
getbytitle('Activos del sitio') //Spanish Name
getbytitle('Site Assets')

Tried replacing the spaces with %20 and x0020:
getbytitle('Activos%20del%20sitio') //Spanish Name
getbytitle('Site%20Assets')
getbytitle('Activos_x0020_del_x0020_sitio') //Spanish Name
getbytitle('Site_x0020_Assets')

Tried with the RootFolder.Name
getbytitle('SiteAssets')

Tried on javascript using encodeURIComponent() with the list name.
Nothing works. I'm getting mad with it!
Any Help?
Thanks!

A: You can use the List GUID in the REST API. Go to Library Settings and in the URL you will fin the GUID as shown in image below.

Remove the "%7B" from the start and "%7D" from the end and use it in the rest api as shown in example below (replace the GUID with your GUID).
https://spdev.sharepoint.com/sites/SPTeam/spanish/_api/web/lists('85851fae-11b4-4c3f-8578-918b2c320bb5')

A: The following code for your reference.
<script src="https://code.jquery.com/jquery-1.12.4.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
var listTitle="Activos del sitio";
listTitle=encodeURIComponent(listTitle);
$.ajax({
        url:  _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('"+listTitle+"')",
        type: "GET",
        headers: {"Accept": "application/json;odata=verbose" },
        success: function(data){
            alert(data.d.Title);
        },
        error: function () {
            //console.log("Failed to get details");
        }
    });
});
</script>

A: I am facing the same problem. My current hypothesis: There is a Sharepoint installation language, which in my case I assume to be English (don't know how to check). If I set my user language (Office Profile) via the arcane Delve/help settings to German then spClient.web.lists.get() returns the Title field in German. However, using that name in spClient.web.lists.getByTitle('German Title') returns 404.
Setting the Office Profile to English (installation language) I get an English title and that one works with getByTitle().
So to me it looks like you have to use the Title in the language of your Sharepoint installation.


text:
Q: Why isn't php's class loading is not as simpler as java "import"? PHP developers who are using class features in their projects would have to do a lot of circus to load specific class before using them. php __autoload() (would be deprecated in future), spl_autoload_register(), psr-0 & psr-4 standards to autoload them.
The __autoload() or for that matter spl_autoload_register() function (with paths of all classes in it) defined for example in start.php have to be first included in index or whatever the php page is and then do your work with the loaded class object.
In psr-0 & psr-4 we configure composer.json's by setting autoload's psr-0 or psr-4 or classmap path to vendor folder. Do dump-autload, include that single generated autoload.php in your php file and psr-4 convention of "use" "namespace" said to make our life much easier (which is not).
In java, define classes under packages then simply import required class and use it.
My question is, why is php loading of classes is not as simple as java packages & import?
I know that there might be some implementation difficulties if not nearly impossible.
Few thousands of new c code line if not lakhs would definitely not slow the php interpreter to help find class names which are mentioned in import keyword and load that class from the packages as similar to java, instead of these tedious conventions (spl_autoload_register(),psr-0,psr-4) which are suppose to make loading the classes easier.
I have used java in most of my projects. so, I am new to php and the kind of question might be well expected which might appear pretty noob one. Replies are much appreciated. Thanks.

A: Well, it is.
PSRs are (currently) only recommendations for framework implementations. That is, unless you're writing a framework or package, it's not really aimed at you. It just so happens that a number of php developers like to follow the standards anyway (particularly PSRs 1, 2, and 12).
As it happens, the PSR-4 examples all use spl_autoload_register(), which is  a more convenient way to include packages and classes, without the need of include_once. PSR-4 is only a recommendation by a body separate from the php language, and is relatively recent, which is why you can implement spl_autoload_register() in any way you want.
However, include_once is still a valid method to load a class, and if you ask me can often be the best method, and (not being a Java developer) I assume is just as simple as the equivalent in Java.


text:
Q: Turning off the JIT Compiler According to IBM it is possible to turn off the jit compiler using Compiler.disable()  and I have read on stackoverflow that it is not possible (only using command line arguments - How to check if the JIT compiler is off in Java). Which of the approaches is correct?

A: Please notice that WebSphere Real Time is actually an IBM Java Virtual Machine different from the standard Oracle one available for download.
The correct approach depends on which VM you are actually using:
If you are using the standard VM, use command line arguments.
If you do use WebSphere, use Compiler.disable().

A: For an IBM Jvm, it appears you can disable JIT altogether with -Xint
http://publib.boulder.ibm.com/infocenter/javasdk/v6r0/topic/com.ibm.java.doc.diagnostics.60/diag/appendixes/cmdline/commands_jit.html

A: IBM JDKs (including WebSphere Real Time) support the java.lang.Compiler API, including the disable() and enable() calls.  It's not something we generally recommend using, because it obviously interferes with the JIT compiler's heuristics used to identify what code should be compiled, but the facility is there and supported from Java 5 on (which is where the Compiler API was introduced).


text:
Q: I can't use filter when I have objects inside an array and find last id, angular I need your opinion in this situation:
I get from API with this function:
  getRS(
    idProject: string
  ): Observable<ResponseModel<RSModel>> {
    return this.http.get<ResponseModel<RSModel>>(
      ApiUrlsConfig.getRS(
        idProject
      )
    );
  }

this response:
{
  "data": [
    {
      "id": "id1",
      "state": 1,
      "note": null
    },
    {
      "id": "id1",
      "state": 2,
      "note": "Reason 1"
    },
    {
      "id": "id2",
      "state": 2,
      "note": "Reason updated3",
    }
  ],
  "result": null
}

I need to use filter in this response because I should be get the last state for each id. For example, I want to display state 2 in item with id: id1. For this I want to use filter. The problem is because I can't use filter on it, I don't understand why.
I tried to write this code:
   @Input() set jobId(jobId: string) {
  this.optionsService
    .getRS(
      this.idProject
    )
    .pipe()
    .subscribe((res) => {
      let resId = res.filter((aaa)=>{
          if(aaa.id === jobId){
            res.slice(-1)[0].id
          }
        }
      )
    });
}

Not function.
Please can you share with me any idea?
Thank you

A: Try this logic:

*

*Loop backwards throw it.

*Loop backwards over index to the start.

*Splice duplicates.

let response = {
  "data": [
{
  "id": "id1",
  "state": 1,
  "note": null
},
{
  "id": "id1",
  "state": 2,
  "note": "Reason 1"
},
{
  "id": "id2",
  "state": 2,
  "note": "Reason updated3"
}
  ],
  "result": null
}

let data = response.data;

for (let i = data.length - 1; i >= 0; i--) {
  for (let j = i - 1; j >= 0; j--) {
if (data[i].id === data[j].id) {
  data.splice(j, 1);
  j++;
}
  }
};

console.log(data);

A: try this:
if(aaa.id == jobId){
  return res.slice(-1)[0].id
}


text:
Q: Couchbase MuteteInResult always returns Index 0 is invalid error In couchbase java sdk I am trying to change a Boolean field in database.
I am trying to do as following:
public boolean changeDataFetchOrder(String caseId, String taskId, boolean isRandom) {
    var searchId = "case" + ":" + caseId + ":" + taskId;
    Collection collection = bucket.defaultCollection();

    var result = collection.mutateIn(searchId, Collections.singletonList(
            upsert("isDataFetchOrderRandom", isRandom)
    ));

    return result.contentAs(0, Boolean.class);
}

This operation changes the field in database but it does not returns result of operation.
Should I do an extra configuration?
com.couchbase.client.core.error.InvalidArgumentException: Index 0 is invalid
    at com.couchbase.client.core.error.InvalidArgumentException.fromMessage(InvalidArgumentException.java:28) ~[core-io-2.3.0.jar:na]
    at com.couchbase.client.java.kv.MutateInResult.getFieldAtIndex(MutateInResult.java:118) ~[java-client-3.3.0.jar:na]
    at com.couchbase.client.java.kv.MutateInResult.contentAs(MutateInResult.java:91) ~[java-client-3.3.0.jar:na]
    at com.couchbase.client.java.kv.MutateInResult.contentAs(MutateInResult.java:68) ~[java-client-3.3.0.jar:na]
    at com.company.caseuploadapi.service.couchbase.CaseRepositoryImpl.changeDataFetchOrder(CaseRepositoryImpl.java:179) ~[classes/:na]
    at com.company.caseuploadapi.service.cases.defaults.CaseService.setDataFetchOrder(CaseService.java:371) ~[classes/:na]
    at com.company.caseuploadapi.controller.CaseController.setDataFetchOrder(CaseController.java:79) ~[classes/:na]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:64) ~[na:na]
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
"}

A: Thansk to @Graham Pole, it was answered in Couchbase forum. I am quoting:

Yes, most mutateIn operations don't return what they've written. This
is because generally you know what that is - e.g. you have isRandom
here - and it saves bytes on the wire.
The exception are counters: if you increment or decrement a counter,
it does return what was written, since you otherwise wouldn't that
information.

See the discussion here


text:
Q: java insert Blob as ByteArrayOutputStream get ClassCastException I've to save a pdf file represented as a ByteArrayOutputStream into a Blob SQL field of a table, here's my code:
public boolean savePDF(int version, ByteArrayOutputStream baos) throws Exception{
    boolean completed = false;
    ConnectionManager conn = new ConnectionManager();
    try {
        PreparedStatement statement = conn.getConnection().prepareStatement(INSERT_PDF);
        statement.setLong(1, version);
        statement.setBlob(2, (Blob)baos);
        statement.execute();
        conn.commit();
        completed = true;
    } catch (SQLException e) {
        conn.rollbackQuietly();
        e.printStackTrace();
        throw e;
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }finally{
        conn.close();
    }
    return completed;
}

But I get a java.lang.ClassCastException:
java.io.ByteArrayOutputStream cannot be cast to java.sql.Blob

How can I manage that? Thanks

A: There is a setBlob that takes an InputStream, so
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
statement.setBlob(2, bais);

A: You can't cast ByteArrayOutputStream  to Blob. Try creating the Blob instance as below:
  SerialBlob blob = new SerialBlob(baos.toByteArray());

and then
  statement.setBlob(2, blob);


text:
Q: How do authentication servers handle thousands of CPU intensive logins? Apologies if the answer is obvious, I'm just a little curious and couldn't nail down an answer elsewhere.
I'm used to seeing authentication servers use simple SHA-1 or SHA-256 to validate credentials, but best-practise these days is normally to use bcrypt for credential hashing.
The problem is that bcrypt is designed to use significant amounts of CPU and/or memory to limit the efficacy of brute-forcing algorithms. Easy for a single logon, but when hundreds or thousands of logons are involved, do server admins just throw extreme amounts of hardware at the problem, or do they tweak the bcrypt parameters to ensure a reasonable logon time for users?

A: You can't shouldn't be tweaking the bcrypt parameters too low. The parameters should be set so that it takes at least ~250 ms to verify a password.
That means you will be consuming 100% of a CPU core for 250 ms each login.
So:

*

*on a single core, you can only login 4 people a second

*on dual core: 8 people a second

*quad core: 16 people a second

Fortunately once someone logs in, you will hand them back an authentication cookie. If you do it right, and the authentication cookie doesn't expire for 50+ years, you'll never have to verify their password again.


text:
Q: PHP: include file relative to calling file NOT root file? OK say I have a file called fileA.php in the same directory I have another file called fileB.php
so inside fileA there is this require_once('fileB.php') notice I did not specify a file path because both files are in the same directory.
Now if fileA is included into another file that is located somewhere else, it fails to include fileB because the parent file (the file that included fileA) is not in the same directory as fileB.
So how can I make it so that fileA loads fileB no matter where fileA is included into?
Does that make sense?
Thanks!!

A: Assuming both fileA.php and fileB.php are guaranteed to be in the same directory, this should work:
// fileA.php
require_once(dirname(__FILE__) . DIRECTORY_SEPARATOR .'fileB.php')

A: http://php.net/manual/en/function.include.php#78716
You can set the include root to your website root.


text:
Q: Multiselect with Devise and simple_form I have a rails application that uses Devise and simple_form to register and authenticate a user. I wanted to add another table of preferences such that a user can have multiple preferences and a preference can be assigned to multiple users.
I followed this: https://dev.to/neshaz/join-table-in-rails-23b5
and made the respective associations with a join table and I am able to view the checkboxes multiselect on my form. But I am stuck on the part on processing the params in my registration controller page. For context this is what i have:
registration_controller.rb
    def configure_sign_up_params
devise_parameter_sanitizer.permit(:sign_up) do |u|
  u.permit({ account_attributes: [:username], invite_request_attributes: [:text] }, :company, :email, :password, :password_confirmation, :invite_code, :agreement, :website, :confirm_password)
end

end
_registration.html.haml:
- for preference in Preference.all
  = check_box_tag "preference[user_ids][]", preference.id
  = h preference.pref

A: You try this way.
class ApplicationController < ActionController::Base

  before_action :configure_permitted_parameters, if: :devise_controller?

  def configure_permitted_parameters
    devise_parameter_sanitizer.permit(:sign_up, keys: [:name, preference_ids: []])
    devise_parameter_sanitizer.permit(:account_update, keys: [:name, :website, :bio])
  end

end

_registration.html.haml:
- for preference in Preference.all
  = check_box_tag "user[preference_ids][]", preference.id
  = h preference.pref


text:
Q: How to write a spinning odometer in QT? Hi I would like to create a spinning odometer in QT.
The result should be like this one:
https://www.shutterstock.com/video/clip-4962995-stock-footage-the-counter-displays-one-million-in-frame.html?src=search/dzZbICGUPQ7RgK0rooSE7A:1:0/gg
Something like the picker in IOS.
Any suggestions?

A: There are mainly two ways of designing a UI with Qt:

*

*the "older" method is based on Qt Widgets

*the current suggested method is via QML/Quick
Have a look at the QML Threading example, in particular at the Spinner component. Looks much like what you need to achieve.


text:
Q: Gas with hyperledger Fabric? With Ethereum, gas is an anti-denial of service measure. What is the equivalent in Hyperledger Fabric to avoid abuse of chaincode invocation transactions (INVOKE)? Is the NVP expected to check this abuse?

A: From what I understood, there is no need for such a gas system in Hyperledger Fabric.
The blockchain is supposed to work in a "private" mode, meaning that you know the other peers in the network. It would be easy to detect a malicious peer and revoke its access. Also, there is no "mining" process, only consensus rules triggered for each incoming transaction. This results in a lighter block generation process compared to Bitcoin or Ethereum for example.
However, you can still implement your own custom gas system with a chaincode that add some kind of "transaction fee" before validating any Invoke transaction, but I don't think it would be possible to "mine" gas in the current state of the project.


text:
Q: What are firebase.analytics() default logged events for a web app? From this page, we get that Firebase is supposed to auto log some events.
https://support.google.com/firebase/answer/6317485?hl=en
I have a web app, this is not a mobile app. This is already confusing, since 99% of the automatically collected events are for mobile apps.

I would like to just log every page_view event. And my web app is a Single Page App, so do I need to log this event on every URL change on my client code?
Right now, the only thing I'm doing is:
useEffect(() => {
  props.firebase.analytics();
},[props.firebase]);

This code runs only once per user visit on my web app. After App.js first mount.
And the weird thing is that I'm getting page_view events on my Google Analytics Console:

A: the way I do it, is I pass a name on each component/page. Then create a funnel in Google analytics.

I want to know: "How many users are getting from my article pages and
  going to the dashboard"

I have three components in a flow.
Landing Component
useEffect(() => {
  analytics.logEvent('landing_page_view');
});

Login Component
useEffect(() => {
  analytics.logEvent('login_page_view');
});

Dashboard Component
useEffect(() => {
  analytics.logEvent('dashboard_page_view');
});

Then create a funnel that looks like this. (My data is a bit messed up, but you get the point)

Hope this helps :)


text:
Q: QtCreator: Issues not displayed in Issue panel any more I don't know what I did to break my QtCreator but "suddenly" all my compiler issues (warnings/errors) are not displayed in the issues-panel any more but only in the "Compile output" panel (where I can't use them to jump to the erroneous code just by clicking).
In the "Issues" panel only the compile target (e.g. an object file) is being displayed like this:
[path/to/makefile:89: path/to/object/file.cpp.o] Error 1

I'm using Creator together with CMake (with Makefiles) and GCC. The compiler output itself seems not to be the problem (another tool which outputs <file>:<linenr>: <description> shows the same result).
What are the requirements for Creator to correctly parse and display issues printed by the compiler (or any other tool)? How can I investigate what's going on?
I'm using QtCreator 4.6.2 on Fedora 27 (and I tried 4.8.0-beta1 as well with the same result)

A: I don't know the technical reason but for me creating a new build-folder solved the problem.
Possibly a CMake or Qt-Creator update introduced some new elements in the environment in an incompatible way..

A: For what it's worth, I was able to resolve a similar issue by resetting the compilers for each of my build and run configurations under Preferences > Build & Run > Kits in Qt Creator.
These had been set to <No compiler> for some reason, probably related to careless tracking of various CMake files while passing the project back and forth between different architectures.


text:
Q: Pass parameters in RESTAngular I am using angularJS, RESTangular.
I need to pass 3 parameter.
When I an passing 1 parameter like below, I am getting data
subjectAllocationEdit: function (Restangular, $stateParams ) {
                                return Restangular.one('subjectAllocationEdit', $stateParams.classId).get();
                            }

BUT if I am passing 3 parameter like below, I am NOT getting data and even I am not able to parameters passing to my PHP end.
subjectAllocationEdit: function (Restangular, $stateParams ) {
                                return Restangular.one('subjectAllocationEdit', $stateParams.classId, $stateParams.sectionId, $stateParams.Type).get();
                            }

when hitting my api like  /http/../../subjectAllocationEdit/4/9/main    I am getting records
full state code is as below
How I can pass 3 parameters? or what should be the alternate
.state('subjectAllocationEdit', {
                        url: '/class/subjectAllocation/:classId/:sectionId/:Type',
                        templateUrl: 'app/class/html/subjectAllocation.html',
                        controller: 'subjectAllocationEditCtrl as vm',
                        resolve: {
                            subjectAllocation: function (Restangular, $stateParams) {
                                return Restangular.all('subjectAllocation').getList();
                            },
                            subjectAllocationEdit: function (Restangular, $stateParams ) {
                                return Restangular.one('subjectAllocationEdit', $stateParams.classId, $stateParams.sectionId, $stateParams.Type).get();
                            },
                        }
                    })

A: subjectAllocationEdit: function (Restangular, $stateParams) {
                                return Restangular.all('subjectAllocationEdit')
                                    .getList({"classId":$stateParams.classId,"sectionId":$stateParams.sectionId,"Type":$stateParams.Type});
                            },


text:
Q: Scapy Sends Malformed Packets I'm sending out probe requests using scapy. It works perfectly fine on my desktop but when I send it out from scapy, using the exact same code, the packets arrive malformed. I'm watching them in wireshark.
The malformed one has a Logical-Link Control layer and the bits are all just out of order. I don't really know how else to put it. The source and destination mac addresses are both offset by a few bits. The packet is twice as large, I'm just really baffled.
For example
in scapy, my destination address is "aa:bb:cc:dd:ee:ff"
In the packet capture, the destination is "00:00:00:aa:bb:cc"
EDIT:
The packets show up fine on my laptop in wireshark, but in wireshark on my desktop is where there is an issue.
sendp(Dot11(addr1=dest,
            addr2=source,
            addr3=source)/
      Dot11ProbeReq()/
      Dot11Elt(ID="SSID",info='test')/
      Dot11Elt(ID="Rates", info='\x02\x04\x0b\x16\x0c\x12\x18$')/
      Dot11Elt(ID="ESRates", info='0H`l')/
      Dot11Elt(ID="DSset", info='\x06'),
      iface='wlan0', count=3)

EDIT: I believe the issue is because scapy is sending the wrong type/subtype.
The packet should have
Type/subtype: Probe Request (0x04)

but the packet in wireshark displays
Type/subtype: Data (0x20)

A: Monitor mode was not initiated correctly. The packets became malformed when not sent over a monitor interface.

A: try
sendp(RadioTap()/
      Dot11(addr1=dest,
            addr2=source,
            addr3=source)/
      Dot11ProbeReq()/
      Dot11Elt(ID="SSID",info='test')/
      Dot11Elt(ID="Rates", info='\x02\x04\x0b\x16\x0c\x12\x18$')/
      Dot11Elt(ID="ESRates", info='0H`l')/
      Dot11Elt(ID="DSset", info='\x06'),
      iface='wlan0', count=3)


text:
Q: Iterate through IF-MIB::ifDescr? I am using snmpget in order to get the description of a specific switch port.  How could I read each not null value?  I.E. do a "for-each" sort of operation on the set of IF-MIB::ifDescr values?

A: You want to use the snmpwalk command for this, this goes over all items below the one you specify in the MIB tree.
I don't have anything to query, but you could read each line and filter on the text with something sort of like the following in the shell:
while read line; do
   if $(echo $line | grep NULL); then
      echo $line
   fi
done < <(snmpwalk -Os -c public -v 1 zeus system)


text:
Q: Programming non UI Android code So I'm currently in the process of developing a reasonably large app for Android. I'm the only dev on it. I'm trying to be as organized as possible.
My app sends (or will send) requests to an API and it responds in XML. So I had to write parsers for the different request answers, and while doing the first parser (I used the sdks XmlPullParser) I thought it would be good if I didn't have to test that on the phone (build + it launches the app on the phone).
I'm currently using Android studio.
So my question is:
How do I develop bits of my application that don't need the phone (like UI and user input...), but that still need the Android library (XmlPullParser for me) ?
thanks


text:
Q: Last line of input not scanning in Java Scanner Class I am trying to work on some stuff using the Scanner for input, but for some reason, the scanner is failing me.
I have the following code running, nothing complex:
while(scan.hasNextLine())
    {
        System.out.println(scan.nextLine());
    }

Just as a test bed to make sure everything is being input correctly. If I copy my test material, say
5
4
3
2
1

The output omits the last line. I am pretty sure that it is because nextLine will only return a string if there is a string after it, even if it is empty, but I need it to work this way for the way I will eventually input the data to work. Does anyone know how I can fix this? My only guesses were to either use something other that scanner or to somehow append an empty string to the end of the input, but I wasn't sure how to do the second one, and I didn't think a different scanner-like thing would work. Thanks in advance!

A: Your last line MIGHT not have a "enter" char. So it does not treat it as the end of line. Try
> 5
> 4
> 3
> 2
> 1
>

A: I tried this on Eclipse just then. I didn't replicate Daryl Teo's suggestion; just the same input as what you provided in a .txt. Going straight to standard input, as well as pointing the Scanner to an input file got me the result you wanted, that is
5
4
3
2
1

Could you please post some more code, as was requested in the comments? The error you have doesn't appear to be related to your Scanner at the moment, as weird as that sounds.


text:
Q: PostgreSQL query to count/group by day and display days with no data I need to create a PostgreSQL query that returns

*

*a day

*the number of objects found for that day

It's important that every single day appear in the results, even if no objects were found on that day. (This has been discussed before but I haven't been able to get things working in my specific case.)
First, I found a sql query to generate a range of days, with which I can join:
SELECT to_char(date_trunc('day', (current_date - offs)), 'YYYY-MM-DD')
AS date
FROM generate_series(0, 365, 1)
AS offs

Results in:
    date
------------
 2013-03-28
 2013-03-27
 2013-03-26
 2013-03-25
 ...
 2012-03-28
(366 rows)

Now I'm trying to join that to a table named 'sharer_emailshare' which has a 'created' column:
Table 'public.sharer_emailshare'
column    |   type
-------------------
id        | integer
created   | timestamp with time zone
message   | text
to        | character varying(75)

Here's the best GROUP BY query I have so far:
SELECT d.date, count(se.id) FROM (
    select to_char(date_trunc('day', (current_date - offs)), 'YYYY-MM-DD')
    AS date
    FROM generate_series(0, 365, 1)
    AS offs
    ) d
JOIN sharer_emailshare se
ON (d.date=to_char(date_trunc('day', se.created), 'YYYY-MM-DD'))
GROUP BY d.date;

The results:
    date    | count
------------+-------
 2013-03-27 |    11
 2013-03-24 |     2
 2013-02-14 |     2
(3 rows)

Desired results:
    date    | count
------------+-------
 2013-03-28 |     0
 2013-03-27 |    11
 2013-03-26 |     0
 2013-03-25 |     0
 2013-03-24 |     2
 2013-03-23 |     0
 ...
 2012-03-28 |     0
(366 rows)

If I understand correctly this is because I'm using a plain (implied INNER) JOIN, and this is the expected behavior, as discussed in the postgres docs.
I've looked through dozens of StackOverflow solutions, and all the ones with working queries seem specific to MySQL/Oracle/MSSQL and I'm having a hard time translating them to PostgreSQL.
The guy asking this question found his answer, with Postgres, but put it on a pastebin link that expired some time ago.
I've tried to switch to LEFT OUTER JOIN, RIGHT JOIN, RIGHT OUTER JOIN, CROSS JOIN, use a CASE statement to sub in another value if null, COALESCE to provide a default value, etc, but I haven't been able to use them in a way that gets me what I need.
Any assistance is appreciated! And I promise I'll get around to reading that giant PostgreSQL book soon ;)

A: I'll try to provide an answer that includes some explanation. I'll start with the smallest building block and work up.
If you run a query like this:
SELECT series.number FROM generate_series(0, 9) AS series(number)

You get output like this:
 number
--------
      0
      1
      2
      3
      4
      5
      6
      7
      8
      9
(10 rows)

This can be turned into dates like this:
SELECT CURRENT_DATE + sequential_dates.date AS date
  FROM generate_series(0, 9) AS sequential_dates(date)

Which will give output like this:
    date
------------
 2019-09-29
 2019-09-30
 2019-10-01
 2019-10-02
 2019-10-03
 2019-10-04
 2019-10-05
 2019-10-06
 2019-10-07
 2019-10-08
(10 rows)

Then you can do a query like this (for example), joining the original query as a subquery against whatever table you're ultimately interested in:
   SELECT sequential_dates.date,
          COUNT(calendar_items.*) AS calendar_item_count
     FROM (SELECT CURRENT_DATE + sequential_dates.date AS date
             FROM generate_series(0, 9) AS sequential_dates(date)) sequential_dates
LEFT JOIN calendar_items ON calendar_items.starts_at::date = sequential_dates.date
 GROUP BY sequential_dates.date

Which will give output like this:
    date    | calendar_item_count
------------+---------------------
 2019-09-29 |                   1
 2019-09-30 |                   8
 2019-10-01 |                  15
 2019-10-02 |                  11
 2019-10-03 |                   1
 2019-10-04 |                  12
 2019-10-05 |                   0
 2019-10-06 |                   0
 2019-10-07 |                  27
 2019-10-08 |                  24

A: Based on Gordon Linoff's answer I realized another problem was that I had a WHERE clause that I didn't mention in the original question.
Instead of a naked WHERE, I made a subquery:
SELECT d.date, count(se.id) FROM (
    select to_char(date_trunc('day', (current_date - offs)), 'YYYY-MM-DD')
    AS date
    FROM generate_series(0, 365, 1)
    AS offs
    ) d
LEFT OUTER JOIN (
    SELECT * FROM sharer_emailshare
    WHERE showroom_id=5
) se
ON (d.date=to_char(date_trunc('day', se.created), 'YYYY-MM-DD'))
GROUP BY d.date;

A: You just need a left outer join instead of an inner join:
SELECT d.date, count(se.id)
  FROM
    (
    SELECT to_char(date_trunc('day', (current_date - offs)), 'YYYY-MM-DD') AS date
       FROM generate_series(0, 365, 1) AS offs
    ) d
  LEFT OUTER JOIN sharer_emailshare se
    ON d.date = to_char(date_trunc('day', se.created), 'YYYY-MM-DD')
  GROUP BY d.date;

A: Extending Gordon Linoff's helpful answer, I would suggest a couple of improvements such as:

*

*Use ::date instead of date_trunc('day', ...)

*Join on a date type rather than a character type (it's cleaner).

*Use specific date ranges so they're easier to change later. In this case I select a year before the most recent entry in the table - something that couldn't have been done easily with the other query.

*Compute the totals for an arbitrary subquery (using a CTE). You just have to cast the column of interest to the date type and call it date_column.

*Include a column for cumulative total. (Why not?)

Here's my query:
WITH dates_table AS (
    SELECT created::date AS date_column FROM sharer_emailshare WHERE showroom_id=5
)
SELECT series_table.date, COUNT(dates_table.date_column), SUM(COUNT(dates_table.date_column)) OVER (ORDER BY series_table.date) FROM (
    SELECT (last_date - b.offs) AS date
        FROM (
            SELECT GENERATE_SERIES(0, last_date - first_date, 1) AS offs, last_date from (
                 SELECT MAX(date_column) AS last_date, (MAX(date_column) - '1 year'::interval)::date AS first_date FROM dates_table
            ) AS a
        ) AS b
) AS series_table
LEFT OUTER JOIN dates_table
    ON (series_table.date = dates_table.date_column)
GROUP BY series_table.date
ORDER BY series_table.date

I tested the query, and it produces the same results, plus the column for cumulative total.

A: I like Jason Swett SQL however ran into issue where the count on some dates should be a zero rather than a one.
Running the statment select count(*) from public.post_call_info where timestamp::date = '2020-11-23' count = zero, but below equals a one.
Also the + give me a forward schedule so changed to a minus provide 9 days data prior to current date.
SELECT sequential_dates.date,
COUNT(*) AS call_count
FROM (SELECT CURRENT_DATE - sequential_dates.date AS date
        FROM generate_series(0, 9) AS sequential_dates(date)) sequential_dates
LEFT JOIN public.post_call_info ON public.post_call_info.timestamp::date =
    sequential_dates.date
GROUP BY sequential_dates.date
    order by date desc


text:
Q: Javascript Popup Losing Focus in Some Cases This has been absolutely baffling me. The following code works:
<a href="javascript:void(0);" onclick="openPopUp('Edit_Screen.aspx?Image_Id='+ '<%# Eval("Image_Id") %>','Popup',850,800);">
                         <%# Eval("ReferenceNumber") %>
</a>

Which calls this:
function openPopUp(pageURL, title, popupWidth, popupHeight) {
  var targetPop = null;
  var left = (screen.width / 2) - (popupWidth / 2);
  var top = (screen.height / 2) - (popupHeight / 2);
  targetPop = window.open(pageURL, title, 'toolbar=no, status=no, menubar=no, width=' + popupWidth + ', height=' + popupHeight + ', top=' + top + ', left=' + left).focus();

}

This code does not work:
<asp:Button ID="btnNewRecord" runat="server" Text="Enter New Record" CssClass = "button" OnClientClick="LaunchImage()" />

Which calls this:
function LaunchImage()
{
   debugger;
   openPopUp("Insert_Screen.aspx?dataType=images", "Popup", 750, 650);
}

And that calls the same openPopUp function that was shown above. The first a href code example calls the popup and keeps the focus on the popup. The second, which is called from the ASP button, calls the popup, and then gives the focus back to the screen that called it. Does anyone have any idea why? This has been baffling me for awhile now.
Thanks ahead of time!

A: A click on the button causes a postback, while a click on the anchor link does not. You can prevent the postback by returning false in the OnClientClick event of the button:
OnClientClick="LaunchImage(); return false;"

A: <asp:Button ID="btnNewRecord" runat="server" Text="Enter New Record" CssClass = "button" OnClientClick="LaunchImage(); return false;" />

or
<asp:Button ID="btnNewRecord" runat="server" Text="Enter New Record" CssClass = "button" OnClientClick="return LaunchImage();" />

and javascript
function LaunchImage()
{
   debugger;
   openPopUp("Insert_Screen.aspx?dataType=images", "Popup", 750, 650);
   return false;
}


text:
Q: application of Jensen's Inequality with expectation formulas I have in a resarche article "Distributions of Transmit Power and SINR in Device-to-Device Networks" an equation that I can't prouve it (Eq 7). I applied Jensen's inequality, but I can't go further. Following the equation:
$$ E\{\,exp[-s.\sum_{t\epsilon\phi,R_t\gt R_0}\,P_t.H_t.R_t^{-a}]\,\} \ge exp\,\{-πλ (s.E[P_0])^{2/a}.G_a[\frac{R_0²}{(s.E[P_0])^{2/a}}]\,\} $$
When: $G_a(d)= \binom{1/sinc(2/a) \quad ,\,d=0}{\frac{2d}{(a-2)(1+d^{a/2})}.\, _2F_1(1\,;\,1\,;\,2-\frac2a\,;\,\frac{1}{1+d^{a/2}})\quad ,\,d\gt0} $
and: $\,_2F_1(a;b;c;z)\,$ is the hypergeometric function.
E is the expectation value.
"a" is the path loss exponent. $H_t ∼Exp(μ)$. Rt is the distance between mobiles follow homogeneous PPP Φ with (constant) intensity λ. $P_t$ transmit powers.
I know that it's not easy and it's not enough readable, but I hope that There is some one of you who see this equation in other article with its demonstration ?
If I forgot to mention some thing, please ask me to do.
Many thanks in advance.


text:
Q: Angular: Add class after page load I have a fairly simple Angular routing scheme with two routes:
aoo.config(['$routeProvider', function($routeProvider) {
    $routeProvider.
        when('/frame', {
            controller: 'FrameCtrl',
      templateUrl: 'ngPartials/frame.html'
        }).
    when('/bar', {
      controller: 'BarCtrl',
      templateUrl: 'ngPartials/bar.html'
    }).
        otherwise({
      controller: 'BarCtrl'
        });
}]);

I have a simple CSS transition:
.fade { transition: all 0.15s ease-out }

I apply another class that triggers this transition. I want to add this class on page load and remove it when the route changes. The ng-animate directive seems a tad overkill. Is there a simple clean way to accomplish what I'm trying to do?

A: You can use ui-router. It is more powerful angular routing library which allows you to nest ng-views or have multiple ng-views on one page easly.
https://github.com/angular-ui/ui-router
Also it helps in animating view, when your view (state) changes. To do that you will need to use ng-enter, ng-leave directives which are responsible for animating view/sub-view when it is loading or unloading.
There you have some nice tutorials connected with ui-router:
Animating views
https://scotch.io/tutorials/3-simple-tips-for-using-ui-router

A: I'm not sure if I fully understand what you are wanting to do, but I would look into the $routeChangeSuccess event that is emitted when a route changes. You could set up a listener for this event in your app config, and apply some logic on each change.


text:
Q: Internet Explorer 11 won't set cookies on a site For some reason IE11 (only IE11, tested with other IE9 and IE10) won't create a session on a site i've been working on. So this means that a basic functionality such as site login won't work.
On other browsers this is working perfectly.
I researched a bit and found out that IE won't work with domains with underscore.. but my domain doesn't have one so what could be the problem?
Thanks!

A: I know this is old, but hopefully this helps someone in the future.
You cannot have a blank expires=; value in a cookie in IE11.  You just have to leave the expires field out altogether.

A: This may only apply to another-domain cookies, but if someone finds this via Google (like I did) this may help.
IE11 may not set cookies depending on its Privacy settings.
This worked for me:

(Internet Options -> Privacy -> Advanced -> enable all cookie cases there)

A: IE 11 does not like a domain value in the cookie. Leave it empty.
Wrong for IE 11:
Set-Cookie: kohanasession=foobar; expires=Tue, 09-Apr-2016 01:01:01 GMT; path=/; domain=tc.mk; httponly

Correct for IE 11:
Set-Cookie: kohanasession=foobar; expires=Tue, 09-Apr-2016 01:01:01 GMT; path=/; httponly

A: I had this issue because I was running a single-page Vue application. I was setting the cookie in one route, then immediately routing to a different "page". However, it seems like IE won't send cookies until next page load. So instead of using pushState, I had to force the browser to re-load the page.

A: I recently had this problem myself. In my case, the problem was caused by executing the "ClearAuthenticationCache" command upon successful login. The command was executed to remove HTTP authentication, but it turns out that it will remove session cookies as well.
So I would recommend removing the "ClearAuthenticationCache" call if you executing it after a login.
document.execCommand("ClearAuthenticationCache");

For more information, please see the following link: https://blogs.msdn.microsoft.com/ieinternals/2010/04/04/understanding-session-lifetime/

A: I encountered a similar issue with a different setup, I'd like to share what the problem was and how I resolved it. Hoping it would provide ideas to solutions for those who suffer.
The Setup

*

*Authentication service who sets auth cookies sitting on some-domain.com

*React application bundled and ran by Webpack Server on localhost

*Requests go through Webpack proxy to land on some-domain.com. For example

  '/api/': {
    target: 'some-domain.com',
    logLevel: 'debug',
    secure: false,
    changeOrigin: true,
    pathRewrite: {
    '^/api': '/api'
    }
  }

The Problem #1
Because my authentication service sets cookies on some-domain.com, and my React App was running on localhost, it doesn't have that cookie attached to its requests, and my authentication flow failed.
Solution
I had to rewrite the cookie domain, so I added this line to the proxy config on webpack
    cookieDomainRewrite: {
      '.some-domain.com': 'localhost'
    }

it looks like this in webpack.config.js
  devServer: {
    ...
    proxy: {
      '/api/': {
        target: 'some-domain.com',
        logLevel: 'debug',
        secure: false,
        changeOrigin: true,
        pathRewrite: {
          '^/api': '/api'
        },
        cookieDomainRewrite: {
          '.some-domain.com': 'localhost'
        }
      }
    }
    ...
  }

So this was fine on chrome, firefox... but broken in IE 11.
because IE 11 doesn't support the domain localhost for reasons mentioned in previous posts in this thread, when the rewrite happens, cookie is lost.
The final change I had to make was
   cookieDomainRewrite: {
      '.some-domain.com': null
    }

This will make the domain defaults to localhost while keeping it valid for IE 11.
Sum Up
when working with cookies and IE make sure:

*

*your client and server's domain match

*use null for domain value if working with localhost

A: In order for the cookie persistence functionality to work as expected in IE11 I found that I had to use the toGMTString() method (I tried both toGMTString() and toUTCString()) for the expires field when creating the cookie.  Before adding this, the cookie would not persist after the browser was closed.
Example:
var expiryDate = new Date();
expiryDate.setTime(expiryDate.getTime() + (3650 * 24 * 60 * 60 * 1000));
document.cookie = 'name=value' + '; expires=' + expiryDate.toGMTString() + ';path=/';

A: Looking at the cookies your server is sending down the date of expiry seems to be yesterday. Is the date time set correctly on your server?

A: You are setting one of the session cookies twice:

    Set-Cookie: PHPSESSID=3iv5l4tn2ugkbf4vt09lilsi06; path=/
    Set-Cookie: identity=1468380643; expires=Mon, 09-Jan-2017 12:31:46 GMT; path=/; domain=.tc.mk; httponly
    Set-Cookie: kohanasession=u5rrhtaj731h3p9s44jhp0k612; expires=Tue, 09-Feb-2016 12:31:46 GMT; path=/; domain=tc.mk; HttpOnly
    Set-Cookie: kohanasession=u5rrhtaj731h3p9s44jhp0k612; expires=Tue, 09-Feb-2016 12:31:46 GMT; path=/; domain=tc.mk; httponly
Internet explorer doesnt resend this cookie info on successive calls, while eg Chrome will just take one of the 'kohanasession'. Try sending the 'kohanasession' only once.
Also the domain you're setting in the cookie is 'tc.mk', while you have a SEO redirect to www.tc.mk. I think IE will not use the cookie for www in this case. Try configuring it to www.tc.mk

A: As Martin Beeby suggested, please check expiration of your cookie & set date time correctly on your server.
I have checked session for your site & in even chrome it's seems to be expired.

Seems some issue with cookie creation/expiration date & IE behaves different than chrome based browsers. Different cookies have different times than others.

A: I searched high and low but couldn't find a solution for my issue. After debugging i realized that IE (unlike the other browsers) need the PATH part to start with '/'. I had mine line 'subdir/' and had to prepend it to be '/subdir/' to satisfy IE.


text:
Q: JButton cell panel for drawing I have a problem. I have a cell panel in which every cell is a jbutton. It's for drawing. The problem is that I can't draw on this panel without releasing the mouse. It's supposed that I press the left mouse button and just drag the mouse and I release it only when I have finished drawing. But when I press a particular jbutton the focus is caprtured by it and I can't do any actions until I release the mouse. I would be very grateful if someone helped me to solve this problem.
public class Canvas extends JPanel {

  private static final long serialVersionUID = 1L;

  private JButton [][] buttons;
  private boolean [][] bValues;

  public Canvas(int m, int n){

    buttons = new JButton[m][n];
    bValues = new boolean[m][n];

    GridLayout gridLayout = new GridLayout(m,n,0,0);
    setLayout(gridLayout);

    for(int i = 0; i < m; i++){
        for(int j = 0; j < n; j++){

            JButton btn = new JButton();
            btn.setBackground(Color.WHITE);
            btn.setName(i + ":" + j);
            btn.setEnabled(false);

            btn.addMouseListener(new MouseAdapter() {

                @Override
                public void mousePressed(MouseEvent e) {

                    JButton srcButton = (JButton)e.getSource();
                    srcButton.setSelected(false);
                    StringTokenizer strTok = new StringTokenizer(srcButton.getName(), ":");
                    int row = Integer.parseInt(strTok.nextToken());
                    int col = Integer.parseInt(strTok.nextToken());

                    if(e.getButton() == MouseEvent.BUTTON1){
                        srcButton.setBackground(Color.BLACK);
                        bValues[row][col] = true;
                        System.out.println(row + ":" + col);
                    }
                    else if(e.getButton() == MouseEvent.BUTTON3){
                        srcButton.setBackground(Color.WHITE);
                        bValues[row][col] = false;
                        System.out.println(row + ":" + col);
                    }

                }

            });

            add(btn);

            bValues[i][j] = false;
        }
    }

}

}


text:
Q: Infinity Scroll and UITableView Data Reload I'm implementing infinity scroll to load new data in my uitableview that is implemented like Contacts style in Apple embedded App.
My datasource is a IList and then i add new elements on it.
When load new datas to that list if i don't call
this.TableView.ReloadData()

my UITableView doesn't show the new elements added.
That method generates a ugly effect of white screen for a bit, to show next, succesfully, the data added. There are others ways to do that without that effect?
For example using ReloadRows...i can't use that method because i don't understand in which way pass an NSIndexPath[] for rows that aren't loaded yet

A: You can use the insertrowsatindexpath methods - see the apple documentation at http://developer.apple.com/library/ios/ipad/#documentation/userexperience/conceptual/tableview_iphone/ManageInsertDeleteRow/ManageInsertDeleteRow.html - especially the batch operation section


text:
Q: How do I set the path in OSX in a particular order? I need to set the PATH environment variable in OSX in a particular order (i.e. with /usr/local/bin first in line).
The recommended way to set PATH variables seems to be the /etc/paths files and the /etc/paths.d directory which work but automatically rearrange the order of the specified paths.
I could override this in my .profile but I get the suspicion that programs such as Homebrew do not pick up on user defined environment variables

A: Literally just come across this answer on Stackoverflow, it seems that /etc/profile might be the answer? - although this is shell specific ...

A: To make sure programs launched from the GUI see environment variables, you want to set them in ~/.MacOSX/environment.plist, which like all textual OSX plists is an XML file.  I personally use this prefpane to manage it.
Note that the plist is only read when the session starts, so you will need to log out and back in or reboot after setting it.

A: Programs run from the terminal will pickup the $PATH variable in .profile.


text:
Q: Capacitance and Inductance properties of coaxial transmission lines I'm interested to understand what affect the capacitance (between cable core and shielding) and the inductance have on a signal transmitting down a coaxial cable.

A: The equation which answers your questions is that of the characteristic impedance of the transmission line, which arises from both inductance and capacitance: $$Z_0=\sqrt{\frac{R+j\omega L}{G+j\omega C}}$$
For a lossless transmission line this is simply: $$ Z_0 = \sqrt{\frac{L}{C}} $$

You should also check out the Telegrapher's Equations. They are one of the first steps in to transmission lines, a scary and wonderful topic.

A: Since the op asked for simple infos:

*

*high C means that higher frequencies get cut before, i.e. the cable act as a low pass filter, the higher the C the lower the corner frequency.

*high L means pretty much the same thing, higher frequencies are cut before.

That is because the transmission line is modeled as a second order LP filter (series L, parallel C), so the corner pulsation is \$\omega_0=\frac{1}{\sqrt{LC}}\$.
nb
a transmission line is actually modelled with distributed components, so it's not exactly an LP filter


text:
Q: Cause browser to revalidate (but not necessarily refetch) an image In my web app we serve up all images with HTTP cache headers good for 24 hours, and also ETags. But sometimes the Javascript client app has cause to suspect that an image might have been updated. In those cases I would like to force the browser to revalidate the image cache, without actually breaking the cache.
For example, I get a user record (in JSON) which has a recent LastUpdated date on it. There are several possible reasons the LastUpdated date could have changed: the user might've changed their nickname, or joined a new board, or changed their image. So there's a good chance the image did not change, but we need to check.
I'm aware that I could re-request the image with a cache breaker appended to the URL. But that would force the image to reload whether it had changed or not, cause two entries in the browser's cache, and force me to update all my images with the new url. What I really want is to make the browser re-request the same URL, and send proper If-None-Match and/or If-Modified-Since headers in the request so that it will get a 304 if the image hasn't changed.
Is there any way to accomplish that in Javascript?

A: Since the image lives at the server, in a cache, the server is where the query needs to take place.
I would do a check before page load, force the server to renew the particular image in cache if needed. The "HTML" part should always assume all img-tags etc are correct.
Best ways of renewing single files in server cache is a different beast IMO.

A: This is actually rather simple to accomplish.  Make an AJAX request for the image with the Cache-Control header set to max-age=0.
The server must respond with either the updated image (and a new set of cache headers), or with a 304 containing a Cache-Control header like public, max-age=123.
The 304 with a Cache-Control header is very important because it instructs the browser to update the freshness information associated with the resource.
When the request completes, remove the old <img> element from the DOM and reinsert a new one pointing to the same src.
This works because the request Cache-Control header tells the browser to ignore its cache and go to the network.  When the browser gets a response back, it updates its cache – even though you don't actually do anything with the AJAX results.
Now when you remove the old element and insert a new one, the browser grabs the recently updated image directly from its cache.
In Chrome's network inspector, you see two requests: the AJAX request, then the request generated by reinserting the <img> element.  However, if the server has set the Cache-Control headers properly, the second "request" is fulfilled by the browser's cache, and nothing is actually sent over the wire.
function updateImage(el) {
    el = $(el);
    var src = el.attr('src');

    $.ajax({
        url: src,
        headers: {
            'Cache-Control': 'max-age=0'
        },
        success: function() {
            var parent = el.parent();
            el.remove();
            // this assumes that the <img> has no siblings and no attributes/classes/etc...
            parent.append('<img>').attr('src',src);
        }
    });
}


text:
Q: Does the loot from the loot Goliath improve if he levels up before dying?
Possible Duplicate:
How do Goliath enemies work?

The question says it all.   I have tried this a few times but I didn't get any conclusive results.  If I let the loot Goliath destroy all of his 'friends' to level up, does the loot on his back improve once I kill him?

A: The loot from the chest will be the same as a chest found in the level regardless of the goliath's level.
The goliath itself will drop better loot upon dying if it leveled.
Source: leveled loot goliathes a couple times


text:
Q: auto_ptr_ref implementation questions I have looked at different sources with regard to the internal implementation of auto_ptr<> and auto_ptr_ref<>.  I have this question that I couldn't figure out why.
.... When returning a 'auto_ptr' from a function, the compiler finds that there is no suitable ctor to copy construct the returned object. But there is conversion to 'auto_ptr_ref' and ctor taking an 'auto_ptr_ref' constructing an 'auto_ptr'. Thus, the compiler creates an 'auto_ptr_ref' which basically just holds a reference to the original 'auto_ptr' and then constructs an 'auto_ptr' from this object. That's all (well, when returning an object, the compiler goes through this process normally twice because the returned value is copied somewhere but this does not change the process)....
(Reference http://www.josuttis.com/libbook/auto_ptr.html)
In this example,  I emulate the implementation of auto_ptr<> and auto_ptr_ref<> and is able to generate results showing that compiler indeed goes through the process twice
The example has these basic traits:
1) A's copy constructor does NOT take const reference.
2) A has conversion operator B
3) A has constructor A(B);
class B {
};

class A {
public:

A () {
    printf("A default constructor() @ %p\r\n", this);
}

A(B) {
    printf("constructor(B) @ %p\r\n", this);
}
A (A &a) {
    printf("copy constructor(non-const) @ %p\r\n", this);
}

operator B() {
    printf("A convertion constructor(B) @ %p\r\n", this);
    return B();
}
};

A foo()
{
    return A();
}

int main()
{
    A a(foo());
}

So when A a(foo())) is executed
1) foo() generates temporary object X
2) X is converted to type B
3) constructor A(B) is used to construct object a
This is output:
A default constructor() @ 0xbfea340f
A convertion constructor(B) @ 0xbfea340f
constructor(B) @ 0xbfea344f
A convertion constructor(B) @ 0xbfea344f
constructor(B) @ 0xbfea344e

We can see that compiler wen through the conversion-construct steps 2&3 twice.
Why is that?

A: If you are calling a function which returns a class type, basically the following happens:

*

*On the call, the calling function reserves some space for the temporary return value on the stack (it has to be done by the calling function because anything the called function allocates on the stack gets deallocated as soon as the function returns). It passes the address of that space to the called function.

*On executing the return statement, the called function constructs the return value from the argument given to the return statement into the space provided by the calling function. In your case, that argument is the temporary A value.

*After the function returns, the caller uses the temporary value the called function constructed to do whatever the code demands. In your case, you use it to construct a local variable from it.
So you construct a new object of type A from an existing one twice: First, to construct the temporary return value (whose life time persists after the function foo returns, until the end of the declaration) from the explicitly generated temporary in the return statement (whole lifetime ends on the end of the full expression, that is in this case equivalent to on return from foo). And second, to initialize the local variable a from the temporary returned by foo.
Of course, due to no appropriate copy constructor being available, in both cases you go through the B conversions. This works because the return does a direct initialization, and for a you explicitly coded such a direct initialization.

A: Class A is being created 3 times.  Once as a temporary, and copied twice.  Other compilers might return different results, based on their optimization settings.
return A() creates a temporary A, and then copies it to the returned A   This first copy is the first time that you see steps 2 and 3.
Then A a(foo()); copies the return from foo() into the variable in main.  Triggering steps 2 and 3 again.


text:
Q: Protobuf with Multidimensional Array I'm working on saving and loading for a game being developed in c# xna. I have a long list of class arrays that I'm trying to serialize and im coming across a problem with one of them. Ive done the class like the following
 [ProtoContract]
public class CompleteTile
{
    int _id;
    [ProtoMember(1)]
    public int ID
    {
        get { return _id; }
        set { _id = value; }
    }

    bool _Passable;
    [ProtoMember(2)]
    public bool Passable
    {
        get { return _Passable; }
        set { _Passable = value; }
    }

I can successfully serialize it using
using (var stream = File.OpenWrite("" + saveDestination + "level.dat"))
        { Serializer.Serialize(stream, Globals.levelArray); }

But when I try to deserialize I get the following - Type is not expected, and no contract can be inferred: GameName1.CompleteTile[,,]
Deserilization code -
        using (var stream = File.OpenRead("" + loadDestination + "level.dat"))
        { Globals.levelArray = Serializer.Deserialize<CompleteTile[, ,]>(stream); }

I suspect this is due to it being a multidimensional array but I'm not sure, any help is appreciated.

A: As already mentioned, protobuf does not support multidimensional arrays. However, you can circumvent this limitation by transforming the multidimensional array into a 1D array + a dimensional array of integers. To easy the pain, I use a few extensions
public static class Extensions
{

    #region Multidimensional array handling

    public static ProtoArray<T> ToProtoArray<T>(this Array array)
    {
        // Copy dimensions (to be used for reconstruction).
        var dims = new int[array.Rank];
        for (int i = 0; i < array.Rank; i++) dims[i] = array.GetLength(i);
        // Copy the underlying data.
        var data = new T[array.Length];
        var k = 0;
        array.MultiLoop(indices => data[k++] = (T) array.GetValue(indices));

        return new ProtoArray<T> {Dimensions = dims, Data = data};
    }

    public static Array ToArray<T>(this ProtoArray<T> protoArray)
    {
        // Initialize array dynamically.
        var result = Array.CreateInstance(typeof(T), protoArray.Dimensions);
        // Copy the underlying data.
        var k = 0;
        result.MultiLoop(indices => result.SetValue(protoArray.Data[k++], indices));

        return result;
    }

    #endregion

    #region Array extensions

    public static void MultiLoop(this Array array, Action<int[]> action)
    {
        array.RecursiveLoop(0, new int[array.Rank], action);
    }

    private static void RecursiveLoop(this Array array, int level, int[] indices, Action<int[]> action)
    {
        if (level == array.Rank)
        {
            action(indices);
        }
        else
        {
            for (indices[level] = 0; indices[level] < array.GetLength(level); indices[level]++)
            {
                RecursiveLoop(array, level + 1, indices, action);
            }
        }
    }

    #endregion
}

[ProtoContract]
public class ProtoArray<T>
{
    [ProtoMember(1)]
    public int[] Dimensions { get; set; }
    [ProtoMember(2)]
    public T[] Data { get; set; }
}

and persist each multidimensional arrays as a ProtoArray.


text:
Q: model builder expressions code block and definitions I am having difficulty wrapping my brain around the point of the expression vs the code block. What am I suppose to be defining? I copied the example from calculate value in the ArcGIS help website almost verbatim and yet it says my definition is wrong. More specifically it says a syntax error in line 1.

A: In your code block you are defining a function, in your expression you are calling that function.  Your function needs to specify new variable names that are used within the function, and you pass the field names to those variables.  The function variables should have new unique names, not the same values you are passing in your expression.
Code Block:
def fn(zs, zt):
    if zs => 0:
        return zs
    else:
        return zt

Expression:
fn(!Z_score!, !Z_top!)

So here you are passing the value from !Z_score! to your function into a variable called zs, and the value from !Z_top! into zt.  Those values are then used in the function.
And as commented by Michael Stimson, leave the Data Type as blank as Boolean is unlikely to be the correct value.


text:
Q: Adobe Spark cannot detect WebGL I was working with Adobe Spark, and it was doing well. But when I started using it again (after having my PC to sleep), it says this:

WebGL Disabled
Oops! Looks like your browser has WebGL disabled. Please visit our support page or consult your IT organization for more information.

However, when I accessed the GetWebGL website, I could see that spinning cube.
I also checked my browser settings, and saw that Use hardware acceleration when available was already enabled.
My specifications:

*

*Browser - Opera 49.0.2725.64

*Computer Model - Dell Vostro 1500

*Operating System - Windows 7 x86

A: Restart the browser, and it would be detected by Adobe Spark.


text:
Q: FFmpeg merging two audio filters I want to merge two ffmpeg filters (dynaudnorm and loudnorm) in a batch file like this:
ffmpeg -i input.wav -af dynaudnorm=g=7:m=30, -af loudnorm=I=-16:TP=-1:LRA=3 -ar 44.1k out.mp3

but the result is that only the second filter (loudnorm) is executed. Is something wrong with this code or is it impossible to merge two filters?

A: You can concatenate multiple filters in a filterchain:
ffmpeg -i input.wav -af dynaudnorm=g=7:m=30,loudnorm=I=-16:TP=-1:LRA=3 -ar 44.1k out.mp3

Simply add a , between them (see manual):

A filterchain consists of a sequence of connected filters, each one connected to the previous one in the sequence. A filterchain is represented by a list of ","-separated filter descriptions.

You can also combine multiple filterchains into a filtergraph. See the Filtering Guide for more info and some examples.


text:
Q: Dictionary and radio button with c# Hi so im making radio buttons that represent male and female and a separate set of radio buttons that are years: 2008 and 2010.
They are supposed to be used to get information out of dictionary and depending on the selected radio buttons; they get the respective information. Does anyone have any ideas to get the information out of the dictionary?
private Dictionary<Int32, String> GetLifeExpectancyDictionary(string lifeExpectancyTable)
    {
        Dictionary<Int32, String> returnArray = new Dictionary<Int32, String>();
        switch (lifeExpectancyTable)
        {
            case "MaleTable2008":
                returnArray.Add(0, "75.6");
                returnArray.Add(1, "75.1");
                break;
            case "FemaleTable2008":
                returnArray.Add(0, "80.6");
                returnArray.Add(1, "80.1");
                break;
            case "MaleTable2010":
                returnArray.Add(0, "76.2");
                returnArray.Add(1, "75.7");
                break;
            case "FemaleTable2010":
                returnArray.Add(0, "81.0");
                returnArray.Add(1, "80.5");
                break;
        }

        return returnArray;
    }

A: Dictionary is a key-value storage.
In order to get data from Dictionary by a key you should use [key] operator.
So, in your example
var dict = GetLifeExpectancyDictionary("something");
var first = dict[0];

If you want to get all values, you should use the Values property dict.Value.
Also probably you will want to check if a key exists in a dictionary. In order to achieve this use ContainsKey method.

A: Looks like you've got it completely in reverse. Should be something like this
private Dictionary<string, int> _data;
// Initialize
private void InitData()
{
    _data = new Dictionary<string, int>();
    _data.Add("MaleTable2008_0", 75.6m);
    _data.Add("MaleTable2008_1", 75.1m);
    _data.Add("FemaleTable2008_0", 80.6m);
    _data.Add("FemaleTable2008_1", 80.1m);
    _data.Add("MaleTable2010_0", 76.2m);
    _data.Add("MaleTable2010_1", 75.7m);
    _data.Add("FemaleTable2010_0", 81m);
    _data.Add("FemaleTable2010_1", 80.5m);

}

private decimal GetAvgLifespan(string group)
{
    if (_data.ContainsKey(group))
        return _data[group];

    return 0m;
}


text:
Q: Angular custom filter is not displayed I've been dealing with this for the last day trying to figure out what I've been doing wrong.  I'm trying to pass a value into a filter and return a string from a hash that's been built from a return from a factory.  I can get it to work in a similar function that doesn't call the factory, but whenever I return from the factory I'm unable to display the string, even though the appropriate string is show in the console. Am I missing something really easy here?
Controller here:
var app = angular.module('app', []);
app.controller('ctrl', ['$scope', function($scope) {
  $scope.stuff = 1;
}])

Factory here:
app.factory('factory', ['$q', function($q) {
  var list = [
    {set1: 1,set2: 'name1'},
    {set1: 2,set2: 'name2'}
    ];
  var list2 = [
    {set1: 1,set2: 'name6'},
    {set1: 2,set2: 'name7'}
    ]
  var service = {
    getList: getList
  }
  return service;

  function getList(id) {
    var deferred = $q.defer();
    if (id === 1) {
      deferred.resolve(list);
    } else if (id === 2) {
      deferred.resolve(list2);
    }
    return deferred.promise;
  }
}])

Filter here:
app.filter('customFilter', ['factory', function(factory) {
  var factoryHash = {};
  return function(input, id) {
    factory.getList(id)
      .then(function(res) {
        angular.forEach(res, function(value) {
          this[value.set1] = value.set2;
        }, factoryHash);
        console.log('factoryHash', factoryHash[input])
        return factoryHash[input];
      })
  }
}])

plnkr is here.
https://plnkr.co/edit/c4hYrRrdbBF9M2o5tVV5

A: You can't use a promise inside a filter because the filter will be executed any way and when your promise ends the function already return a result to the UI.


text:
Q: How to suggest new computer domain name I'm trying to write a program that search our domain by entered name of groups of computers (for example for IT users computer name beginns with DITXX, where XX is number of computer) and suggest new computer name. For example we have computers:

*

*DIT01

*DIT02

*..

*DIT10

*DIT11

*..

*DIT156

I have TextBox where i enter group name, then i get a list of computers containing this name and i'm putting them to List and to Array. But how to get last used name and suggest new (here program should suggest name DIT157 beacuse of last name DIT156)? Should i use natural sort? Or trim name DIT to have only numbers, sort them and then just find last, add 1 and then show trimmed name + this number?
Code fragments:
string name = textBox1.Text;
DirectoryEntry domain = new DirectoryEntry("LDAP://*****.****.**.**");
DirectorySearcher search = new DirectorySearcher(domain);
search.Filter = ("(&(ObjectCategory=computer)(cn=") + name + ("*))");

List<string> temp = new List<string>();

richTextBox1.Text = "";
List<string> ComputerList = new List<string>();

foreach (SearchResult c in search.FindAll())
{
    var tmp = (c.GetDirectoryEntry().Name.ToString());

    richTextBox1.Text = richTextBox1.Text + (tmp.Replace("CN=", "")) + (Environment.NewLine);
    //listView1.Items.Add(tmp.Replace("CN=", ""),2);
    temp.Add (tmp.Replace("CN=", ""));

    ComputerList.Add(tmp.Replace("CN=", ""));
}

ComputerList.Sort((x, y) =>
{
    int ix, iy;
    return int.TryParse(x, out ix) && int.TryParse(y, out iy)
        ? ix.CompareTo(iy) : string.Compare(x, y);
});
string[] Computers = ComputerList.ToArray();
Array.Sort(Computers);

foreach (var item in Computers)
{
    listView1.Items.Add(item);
    Console.WriteLine(item.ToString());
}

A: For random computer name generation I personally would try something other than query/sort, like use Random.  Or perhaps append the result of Path.GetRandomFileName() to your prefix (strip out the '.') and limit the total length to 15.
If you choose to do the query and sort I would strip off the text and sort by the number alone, because your example computer names have different lengths.  Sorting by string would cause DIT11 and DIT110 to be next to each other in the list.  And if you write a sorting algorithm you will end up stripping off the text anyway.


text:
Q: FAILED: #-2147467259 System.Net.Sockets.SocketException (0x80004005): Access denied I am trying to get mono up and running on my MacBook Pro.
After successfully installing Mono I am running through the tests as recommended at Getting Started
Everything was going great until I got to the test that involves running
mono tlstest.exe https://www.nuget.org
to test the https connectivity of the mono installation.
When I do this, I get the following error :
FAILED: #-2147467259
System.Net.Sockets.SocketException (0x80004005): Access denied
  at System.Net.Sockets.Socket.Connect (System.Net.EndPoint remoteEP)
  [0x000b6] in <5afdc70d980c4033b3878286f754d091>:0
  at TlsTest.GetStreamPage (System.String url) [0x00057] in
  <7ad9caa5280c42fa9e47b5cc3d9b1e0e>:0
  at TlsTest.Main (System.String[] args) [0x002aa] in
  <7ad9caa5280c42fa9e47b5cc3d9b1e0e>:0

I don't even know where to begin with troubleshooting.
I have a MacBook Pro running MacOS 10.12.6
Mono Version is as follows:
Mono JIT compiler version 5.0.1.1 (2017-02/5077205 Thu May 18 16:11:37 EDT 2017)
Copyright (C) 2002-2014 Novell, Inc, Xamarin Inc and Contributors. www.mono-project.com
    TLS:           normal
    SIGSEGV:       altstack
    Notification:  kqueue
    Architecture:  x86
    Disabled:      none
    Misc:          softdebug
    LLVM:          yes(3.6.0svn-mono-master/8b1520c)
    GC:            sgen (concurrent by default)

Any help, guidance, or even some suggestions on where to start with troubleshooting this error would be greatly appreciated.


text:
Q: CSS3 transition on a background image I want to do an CSS3 transform: rotate(360deg); in a transition 1s;
on a background image instead of a seperate image(element)..
Is this possible? I have searched the hell out of Google but no succes!
What I am trying to achieve is something like:
#footerLogo {
  background: url('ster.png'),
  -moz-transition: -moz-transform 1s,
  transition: transform 1s,
  -o-transition: -o-transform 1s,
  -webkit-transition: -webkit-transform 1s;
  background-position: #outlinedtotheleft;
}
#footerLogo:hover {
  background: transform: rotate(360deg);
  -o-transform: rotate(360deg);
  -moz-transform: rotate(360deg);
  -webkit-transform: rotate(360deg);
}

I hope this is possible! I know it is easily doable in JS (jQuery) with:
$('#something').hover(function(){morecodehere});

...but I want to know if it is possible with only CSS(3)
HTML:

A: I don't think you can apply a transform to the background image itself (separately from the div.) However, you can rotate the whole div, including using a transition to animate it (here's a working example.)
It might help if you could describe the exact effect you want to achieve?
Code:
#footerlogo {
    width: 200px;
    height: 200px;
    background-image: url(http://lorempixum.com/200/200);
    -webkit-transition: -webkit-transform 1s;
    -moz-transition: -moz-transform 1s;
    transition: transform 1s;
}

#footerlogo:hover {
    -webkit-transform: rotate(360deg);
    -moz-transform: rotate(360deg);
    transform: rotate(360deg);
}

A: Sure you can, try something like this:
HTML

CSS
#planet {
    width:200px;
    height:200px;
    background: transparent url(http://cdn3.iconfinder.com/data/icons/nx11/Internet%20-%20Real.png) no-repeat center center;
}

#planet {
  -webkit-animation-name: rotate;
  -webkit-animation-duration:2s;
  -webkit-animation-iteration-count:infinite;
  -webkit-animation-timing-function:linear;
  -moz-animation-name: rotate;
  -moz-animation-duration:2s;
  -moz-animation-iteration-count:infinite;
  -moz-animation-timing-function:linear;
}

@-webkit-keyframes rotate {
  from {-webkit-transform:rotate(0deg);}
  to {  -webkit-transform:rotate(360deg);}
}

@-moz-keyframes rotate {
  from {-moz-transform:rotate(0deg);}
  to {  -moz-transform:rotate(360deg);}
}

JSFiddle