text:
Q: Eclipse Error : open git-upload-pack and not authorized (EGit) I have seen this problem here often but my problem seems to be more complex. I am not able to clone and use marketplace at the same time. I have to switch between Native and Manual Settings.
Here The diffrence between my Proxy Settings:
Manual:

*

*Cloning ist not working

*Internal Internet Browser ist Working

*Marketplace is working

When i add this to the eclipse.ini
-Dorg.eclipse.ecf.provider.filetransfer.excludeContributors=org.eclipse.ecf.provider.filetransfer.httpclient4

It is this exception:
  org.eclipse.jgit.api.errors.TransportException: https://XXX.XXX.XXX/scm/Test/testprof.git: cannot open git-upload-pack
            at org.eclipse.jgit.api.LsRemoteCommand.execute(LsRemoteCommand.java:221)
            at org.eclipse.jgit.api.LsRemoteCommand.call(LsRemoteCommand.java:159)
            at org.eclipse.egit.core.op.ListRemoteOperation.run(ListRemoteOperation.java:100)
            at org.eclipse.egit.ui.internal.clone.SourceBranchPage$8.run(SourceBranchPage.java:341)
            at org.eclipse.jface.operation.ModalContext$ModalContextThread.run(ModalContext.java:119)

and without it:
java.lang.Exception: org.eclipse.jgit.api.errors.TransportException: https://XXX.XX.XX/scm/XXX/XXX.git: not authorized
  at org.eclipse.oomph.setup.git.impl.GitCloneTaskImpl.perform(GitCloneTaskImpl.java:882)
  at org.eclipse.oomph.setup.internal.core.SetupTaskPerformer.doPerformNeededSetupTasks(SetupTaskPerformer.java:3305)
  at org.eclipse.oomph.setup.internal.core.SetupTaskPerformer.access$1(SetupTaskPerformer.java:3248)
  at org.eclipse.oomph.setup.internal.core.SetupTaskPerformer$WorkspaceUtil$1.run(SetupTaskPerformer.java:4469)
  at org.eclipse.core.internal.resources.Workspace.run(Workspace.java:2240)
  at org.eclipse.core.internal.resources.Workspace.run(Workspace.java:2267)

Native:

*

*Cloning is working

*Internal Brwoser is working

*Marketplace is not working

When i add this to the eclipse.ini
-Dorg.eclipse.ecf.provider.filetransfer.excludeContributors=org.eclipse.ecf.provider.filetransfer.httpclient4

this happens:
org.eclipse.core.runtime.CoreException: Cannot install remote marketplace locations: Connection failed

    This is most often caused by a problem with your internet connection. Please check your internet connection and retry.

        at org.eclipse.epp.internal.mpc.ui.commands.MarketplaceWizardCommand.execute(MarketplaceWizardCommand.java:106)

        at org.eclipse.ui.internal.handlers.HandlerProxy.execute(HandlerProxy.java:295)

        at org.eclipse.ui.internal.handlers.E4HandlerProxy.execute(E4HandlerProxy.java:90)

        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)

        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)

        at java.lang.reflect.Method.invoke(Method.java:498)

    and without it:

        Failed to stream using org.eclipse.epp.internal.mpc.core.transport.httpclient.HttpClientTransport@1e8c67f7 - falling back to org.eclipse.epp.internal.mpc.core.util.TransportFactory$1@7592008d: Connection failed
        This is most often caused by a problem with your internet connection. Please check your internet connection and retry.

Some information:
Yes, my credentials are correct.
Yes, my Proxy settings are correct
ssl.verify in git configs is =false
Windows 7
Egit version 4.4.1 (I also tried 4.6)
Cloning outside of Eclipse is working too
Thanks for your help... if i miss some information please ask...

A: The Solution ist to Clear the HTTPS field in the Network Settings and switch back to Manual.
Marketplace works and Cloning.


text:
Q: Rails: How to set different ":message" for each one of the possible errors? I use this validation:
validates_numericality_of :price, :greater_than_or_equal_to => 0, :less_than => 1000000

How could I set a different :message for each one of the following cases ?

*

*price < 0

*price >= 1000000

A: You can use following in model.rb:-
def validate
  if self.price < 0
      errors.add(:price, "custom message")
  elsif self.price > 1000000
      errors.add(:price, "custom message")
  end
end

Thanks....

A: Assuming you're using Rails 3, another option you have is to create a custom validator:
# You can put this in lib/better_numericality_validator.rb
class BetterNumericalityValidator < ActiveModel::EachValidator
    def validate_each(record,attribute,value)
        if value < 0
            record.errors[attribute] << "must be greater than or equal to 0"
        elsif value >= 1000000
            record.errors[attribute] << "must be less than 1000000")
        end
    end
end

Then you can use your custom validator in your model:
# In your model.rb
validates :price, :better_numericality => true

This method is very similar to Anubhaw's answer.  But pulling the logic out into the a custom validator makes it so that you can reuse the validation elsewhere easily, you can easily unit test the validator in isolation, and I personally think that validates :price, :better_numericality => true leaves your model looking cleaner than the alternative.

A: How about:
validates_numericality_of :price, :greater_than_or_equal_to => 0, :message => "Foo"
validates_numericality_of :price, :less_than => 1000000, :message => "Bar"

I've not tested it, but it should work?
Alternatively,  Anubhaw's question is a good fallback.

A: At some point, you should probably ask yourself whether it isn't time to apply some convention over configuration.
In my opinion, an error message such as "Please enter a valid price greater than 0 and less than 1 million" (or similar) is a perfectly valid solution to the problem. It prevents you from adding unnecessary complexity to your application and allows you to move on to other (presumably more important) features.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to solve $A\tan\theta-B\sin\theta=1$ I was wondering if it is possible to solve
$$A\tan\theta-B\sin\theta=1$$
for $\theta$, where $A>0,B>0$ are real constants.
For sure this can be straightforwardly implemented numerically, but maybe an alternative exists :)...

A: $$\tan x=\frac{2\tan \frac x2}{1-\tan^2 \frac x2}=\frac{2t}{1-t^2}$$
$$\sin x=\frac{2\tan \frac x2}{1+\tan^2 \frac x2}=\frac{2t}{1+t^2}$$

A: Like any other quartic equation, there is a classical way to solve it explicitly in terms of radicals; but this is generally very messy. It is practically much easier, and no less accurate in the final analysis, to solve it by a numerical method such as Newton--Raphson.

A: You can solve it graphical as well:
You can fiddle here.

If you ignore $2\pi$-periodicity you seem to end up with between two and four solutions.


text:
Q: highcharts Nested Grouping right side border missing When I create a nested group chart, right side border not drawn if only one nested group
 example:

jsfiddle.net/gmrpY/7

A: You can set max range in X-axis to eliminate this problem
xAxis :{
    max:0.5,
},


text:
Q: How do I redirect to different pages from a drop down list in php? When users come to my home page I want them to select which page they want to go to.  So, for instance sports, trivia, etc. from a drop down list.  How would I get it to redirect to the specific page that is selected using php?  This should be simple but I haven't found the solution by searching google.

A: <?php
if ($_POST['select']){
   header("Location: ".$_POST['select']);
}
?>
<form type="post" action="">
    <select name="select">
       <option value="http://link1.com">link1</option>
       <option value="http://link2.com">link2</option>
       <option value="http://link3.com">link3</option>
       <option value="http://link4.com">link4</option>
       <option value="http://link5.com">link5</option>
    </slect>
    <input type="submit" />
</form>

A: PHP run serverside and thus can't handle the redirect in the HTML client. However, you can use PHP to dynamicly print your dropdown as needed. Then you add a onSelect function to your dropdown that either does the redirect itself using javascript:window.location="foobar.html" where foobar.html is the page you want to redirect to. Or you make the onSelect fire a javascript function within which you handle the actual redirect and can look at several elements in your page to decide where to redirect the client to.
Good luck!

A: You should think of avoiding drop downs to handle this, and use links instead. However, if you are really into it, here is the solution:
PHP:
if(isset($_POST['redirect'])){
    header('Location: '.$_POST['link']);
    exit;
}

HTML:
<form action="" method="post">
    <select name="link">
       <option value="http://www.site.com/page1">Page 1</option>
       <option value="http://www.site.com/page2">Page 2</option>
       <option value="http://www.site.com/page3">Page 3</option>
    </select>
    <input type="submit" name="redirect" value="GO" />
</form>


text:
Q: PDFBox 2.0: Get color information in TextStripper I'm using PDFBox PDFTextStripper for text extraction. I also need to get color information for each character, ideally in writeString method.
What I found, is this solution for PDFBox 1.8 (actually can be easy converted to 2.0 version), and what else i'm looking for is background color for each character (as in that answer there is only character color).
I added all handlers for Fill operators - CloseFillNonZeroAndStrokePath, CloseFillEvenOddAndStrokePath FillNonZeroAndStrokePath, FillEvenOddAndStrokePath, LegacyFillNonZeroRule, FillNonZeroRule, FillEvenOddRule (like suggested in this topic), and inside those operators get nonStrokingColor:
public final class FillEvenOddRule extends OperatorProcessor {
        @Override
        public void process(Operator operator, List<COSBase> operands) throws IOException {
            linePath.setWindingRule(GeneralPath.WIND_EVEN_ODD);
            deleteCharsInPath();
            linePath.reset();
            PDGraphicsState gs = getGraphicsState();
            PDColor nonStrokingColor = gs.getNonStrokingColor();
            fillColor = nonStrokingColor.toRGB();
        }

        @Override
        public String getName() {
            return "f*";
        }
    }

Then in processTextPosition I tried to get this fillColor and put it to map for each character (assuming content stream work consecutive way - after Fill operator completes, all next coming to processTextPosition characters should have this fillColor. However this is not truth and all characters have wrong color. There is file I'm trying to process, each second row has blue filling, and I would like to get that blue color for each character in such row, and white color for each character in white row. Is it possible with PDFBox?

A: The problem in context with the sample document

Then in processTextPosition I tried to get this fillColor and put it to map for each character (assuming content stream work consecutive way - after Fill operator completes, all next coming to processTextPosition characters should have this fillColor. However this is not truth and all characters have wrong color.

As you found out, your assumption is wrong for the PDF at hand. The strategy in this document is to first draw all background material and then draw all text. Thus, your approach for this document should always return the color of the last bit of background material.
As mentioned in my comment to the second question here you referenced, you have to collect all rectangles (or more generically: paths) filled in parallel to the actual text extraction and check whether the font rendering color(s) (depending on the text rendering mode it may also be the StrokingColor!) of the currently inspected text coincide with that of the currently top filled path at the location of the text.
In a comment you wonder

does this mean this approach will work for all documents?

Does this approach work for all documents
For many it does but not for all.
The following issues immediately come to mind:

*

*Not all color spaces support the toRGB method you use. (I just checked, I'm positively surprised for how many PDFBox does have an implementation.)
In particular in case of pattern colors you have to do a lot of digging into the pattern and its usage in your case to find the actual background color(s).

*There are other ways to paint a background form, too, in particular:

*

*The approach only considers filled paths, but if you use a larger value for the graphics state line width or a stretching transformation matrix, a stroked line can also paint rectangular forms. Thus, for this case you also have to consider stroked paths.

*The background might be a bitmap image. In this case you'll have to analyze the image to get the background color(s)

*Another alternative to consider is a shading fill. This usually will also result in a range of colors in the background.

*Forms drawn over the glyph afterwards instead of covering it may change foreground and background considerably. There e.g. are blend modes that take the hue from the backdrop and the saturation from the foreground...

*Soft masks active when drawing background or foreground may also be of interest.

*...


text:
Q: How can I load a local file using jQuery? (with file://) Is there any way to load data from a data file (eg a JSON .js file) using jQuery?
eg:
$.get("file:///C:/objectData.js", function() { alert('Load was performed.'); });

At the moment, instead of doing a simple HTTP GET, JQuery appears to be trying to do an OPTIONS request on it, which fails on a file:// URI.  I just want to load the data in so that the site can be used in an offline environment (without a web server installed).

A: GET requires an HTTP connection, so without a local web servber it won't work. While you can open and read a file using HTML5, you can't load a JavaScript resource that way.
If the page is loaded locally, you'd usually load the JS using a script tag.

The only way around this may be in this answer: Is it possible to load in a local version of a JavaScript file instead of the server version?
or this (both require making a local pseudo-server) :

A: I hope it is possible. I'd tried it. the Html code and text files resides in the same folder.
Here is jQuery part.
$(document).ready(function()
{
    $("select").change(function()
    {

        file_name = $("select").val();
        $('#span_result').load(file_name);
    });
});

The Html code is
<select class="sel"  name="files">
    <option  value="">Select a file</option>
    <option  value="file.txt">file.txt</option>
    <option  value="file2.txt">file2.txt</option>
    <option  value="jQuery_file.html">jQuery_file.html</option>
    </select>

Contents of the file will be displayed below

Itworked for me in firefox. Sorry if it failed with you.


text:
Q: python read blocks of lines from file i have a script from which i get the output (i also save this output to a file in f1 = 20141202.194812_carStatus/):
---------------------------------------------
TM 05120970.01: Processing...
TM 05120970: Processing...
TM 05120970: current status Open
TM 05120970: Owner_Info.User_ref = crossi14
TM 05120970: Owner_Info.Email = Criss.Rossi@gmail.com
TM 05120970: CarModel = Nissan Micra
----------------------------------------------
TM 05157414.06: Processing...
TM 05157414: Processing...
TM 05157414: current status Open
TM 05157414: Owner_Info.User_ref = yumiao12
TM 05157414: Owner_Info.Email = Yu.Miao@gmail.com
TM 05157414: CarModel = Toyota Avensis
----------------------------------------------

i used: exec_cmd('cat ' + f1 + '| grep -e "CarModel = " -e "Owner_Info.User_ref = "')
but i also need the first line (actually the second) of the block
TM 05157414.06: Processing...

what i try/need to do is, parse and and get the values in a variable for each of this blocks:
TM 05120970.01 -> car_number = 05120970.01

Owner_Info.User_ref = crossi14 -> owner_user = crossi14

CarModel = Nissan Micra -> car_model = Nissan Micra

with this information i will add some default things like:
priority = Unknown

and i will need to have this variables as input for another script called insert_owner_car.pl
 insert_owner_car.pl -id 05120970.01 -o owner_user="crossi14",car_model="Nissan Micra",priority="Unknown"

this is what i manage to do so far, but its not usuable as i cant get the mentioned values
#!/usr/bin/python

import itertools, commands, datetime, os, re, sys, time

inFile = open("/tmp/20141202.194812_carStatus")
outFile = open("result.txt", "w")
keepCurrentSet = False
for line in inFile:
    if line.startswith("----------------------------------------------"):
        keepCurrentSet = False
    if keepCurrentSet:
        parts = line.split(" = ")[1:]
        part=','.join(parts)
        print part
#outFile.write(parts)
    if line.startswith("----------------------------------------------"):
        keepCurrentSet = True
inFile.close()
outFile.close()

i dont know how to get: 05120970.01
and how to have all the variables from one block to be able to use them as input for that other script
PS: i have python 2.5.1

A: You could use the utility function open_chunk to process the file in chunks:
import re
import subprocess

def open_chunk(readfunc, delimiter, chunksize=1024):
    """
    readfunc(chunksize) should return a string.
    """
    remainder = ''
    for chunk in iter(lambda: readfunc(chunksize), ''):
        pieces = re.split(delimiter, remainder + chunk)
        for piece in pieces[:-1]:
            yield piece
        remainder = pieces[-1]
    if remainder:
        yield remainder

f = open(filename, 'r')
for chunk in open_chunk(f.read, delimiter=r'-{45,}'):
    chunk = chunk.strip()
    if chunk:
        lines = chunk.splitlines()
        firstline = lines[0]
        car_number = firstline.split()[1][:-1]
        for line in lines[1:]:
            if 'Owner_Info.User_ref = ' in line:
                owner_user = line.split(" = ")[1]
            elif 'CarModel = ' in line:
                car_model =  line.split(" = ")[1]
        cmd = ['insert_owner_car.pl'
               , '-id'
               , car_number
               , '-o'
               , 'owner_user="%s"' % (owner_user, )
               , 'car_model="%s"' % (car_model, )
               , 'priority="Unknown"']
        print(' '.join(cmd))
        # subprocess.call(cmd)
f.close()

prints
insert_owner_car.pl -id 05120970.01 -o owner_user="crossi14" car_model="Nissan Micra" priority="Unknown"
insert_owner_car.pl -id 05157414.06 -o owner_user="yumiao12" car_model="Toyota Avensis" priority="Unknown"

If your data file is small, then you could slurp the entire file into a string and then use re.split to split it into chunks:
In [37]: import re

In [38]: re.split(r'-{45,}', open('data').read())
Out[38]:
['\n\n',
 '\nTM 05120970.01: Processing...\nTM 05120970: Processing...\nTM 05120970: current status Open\nTM 05120970: Owner_Info.User_ref = crossi14\nTM 05120970: Owner_Info.Email = Criss.Rossi@gmail.com\nTM 05120970: CarModel = Nissan Micra\n',
 '\nTM 05157414.06: Processing...\nTM 05157414: Processing...\nTM 05157414: current status Open\nTM 05157414: Owner_Info.User_ref = yumiao12\nTM 05157414: Owner_Info.Email = Yu.Miao@gmail.com\nTM 05157414: CarModel = Toyota Avensis\n',
 '\n']

This could be used instead of open_chunk, above. The advantage of using open_chunk is that it can be used on very large files, when slurping the entire file into a string and splitting it into a list requires too much memory.

A: You should use re module to extract relevant information : it is standard, easy and robust.
You could also display block information on a block limit and add a catch all at end of file.
The script would be :
import re

rnum = re.compile('\s*TM\s+([^\s:]+):.*')
ruser = re.compile('.*Owner_Info.User_ref\s*=\s*(.*)')
rmodel = re.compile('.*CarModel\s*=\s*(.*)')

def display(out, num, user, model):
    print(num, user, model)
    out.write('insert_owner_car.pl -id %s -o owner_user="%s",car_model="%s",priority="Unknown"\n' % (num, user, model))

inFile = open("/tmp/20141202.194812_carStatus")
outFile = open("result.txt", "w")
firstOfBlock = False
carnum = None
for line in inFile:
    if line.startswith("--------------------------------"):
        firstOfBlock = True
        if carnum is not None:
            display(outFile, carnum, user, model)
            carnum = None
    else:
        if firstOfBlock:
            m = rnum.match(line)
            if m is not None:
                carnum = m.group(1)
                firstOfBlock = False
        else:
            line = line.strip()
            m = ruser.match(line)
            if m is not None:
                user = m.group(1)
            else:
                m = rmodel.match(line)
                if m is not None:
                    model = m.group(1)

if carnum is not None:
    display(outFile, carnum, user, model)
    carnum = None

inFile.close()
outFile.close()

With your current example, output is
05120970.01 crossi14 Nissan Micra
05157414.06 yumiao12 Toyota Avensis

and result.txt is :
insert_owner_car.pl -id 05120970.01 -o owner_user="crossi14",car_model="Nissan Micra",priority="Unknown"
insert_owner_car.pl -id 05157414.06 -o owner_user="yumiao12",car_model="Toyota Avensis",priority="Unknown"


text:
Q: which is the best practice to store location data on android device I had built an Android app which tracks vehicle location (Android device).My app updates the locations and speed to the server @ every t seconds, using mobile data.App also monitors the vehicle speed which is  under the speed limit or not.Definitely my app will not be able to contact server if  the data connectivity is lost. At this point which is the best practice to store the location data in the device.
My plan is to store the datas in an xml file and update it to server later.Since the app wont update each and every locations but only after 19 secs or greater, I think this is the simplest option.please guide me in right path, if im wrong.  And also I dont know how to update the bunch of data from xml to server.
My current location saving strategy is:
Calling a php page(asyncTask) on server by passing location and other relevent datas.
But how will I implement if I have a bunch of datas!

A: You can store your data in any format: SQLite or Text file with XML/JSON/CSV. But personally I would store it in SQLite. The reason is following. You can create two parallel tasks, one of which collects data into SQLite database and the other sends bunches of that data to the server asynchronously when it's possible. SQLite is more convenient to organize this than text files, since you always work with records.
About sending a bunches of data to the server. You can send your data as a JSON inside a BODY of a HTTP POST request. Then on a server you should read this data and save it to the server database in one SQL statement. This is definitely possible, it's called a batch INSERT statement.
This is example of sending JSON data in a BODY of HTTP POST request:
HttpPost httpPost = new HttpPost(urlString);
String bodyJsonString = this.getBodyJsonString();
httpPost.setEntity(new StringEntity(bodyJsonString, HTTP.UTF_8));

@Override
String getBodyJsonString() {
    JSONObject jsonObject = new JSONObject();

    try {
        jsonObject.put("text", this.message);
        jsonObject.put("theme", this.theme);
    } catch (JSONException e) {
        e.printStackTrace();
    }

    String resultString = jsonObject.toString();
    Log.v(Helper.TAG, "resultString = " + resultString);

    return resultString;
}

A: If you will have alot of information, I think you should build a local database.
http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html

A: I think nosql is good way to work with it.
get it on github:
couchbase lite on android


text:
Q: How to change file association without UAC confirmation? When I was working with file association in a .NET application I hadn't had found a way to set it without UAC popping up a confirmation dialog.
Today, when I opened uTorrent and looked up for file association, I've found that you can enable (writing to registry) without any confirmation from the UAC.
How is that possible? uTorrent is not running as an admin.
Edit:
Well, I have just discovered with Process Monitor (Sysinternals) that what uTorrent.exe does is to create a few keys (uTorrent and .torrent) but in HKCU (HKEY_CURRENT_USER), not in HKEY_CLASSES_ROOT.
Anyways I also have those keys in HKEY_CLASSES_ROOT ... maybe the installer created those. Not sure.

A: See this article in MSDN about the global registry being virtualized so that the changes are only effective for your user profile.


text:
Q: How to bind a child list or array to datagrid? I am new to WPF and still trying to grasp the Binding aspect of WPF controls.  Let me first present the code that I am working with & then I'll pose the questions.
CODE
public class ScannedDocument : Csla.BusinessBase<ScannedDocument>
{
   private string _documentId = string.Empty;
   private BarcodeList _barcodeList = null;

   public string DocumentId
   {
      get { return _documentId; }
   }

   public BarcodeList Barcodes
   {
      get { return _barcodeList; }
      set
      {
         if (_barcodeList.Equals(value))
         {
            _barcodeList = value;
            PropertyHasChanged("Barcodes");
         }
      }

   }
}

public class BarcodeList : Csla.BusinessListBase<BarcodeList, Barcode>
{
   public static BarcodeList NewBarcodeList()
   { return new BarcodeList(); }

   private BarcodeList() {}
}

public class Barcode : Csla.BusinessBase<Barcode>
{
   public string Value
   {
      get { return GetBarcodeValue(); }
   }

   public static Barcode NewBarcode()
   { return new Barcode(); }

   private Barcode() {}
}

XAML
<dg:DataGrid GridLinesVisibility="None" AutoGenerateColumns="False" Name="ScannedDocumentsListView">
<dg:DataGrid.Columns>
    <dg:DataGridTextColumn Header="Document Name" IsReadOnly="True" Binding="{Binding Path=DocumentId}"/>
    <dg:DataGridTextColumn Header="Index 1" Width="80" IsReadOnly="True" Binding="{Binding Path=Barcodes[0].Value}" />
    <dg:DataGridTextColumn Header="Index 2" Width="80" IsReadOnly="True" Binding="{Binding Path=Barcodes[1].Value}" />
    <dg:DataGridTextColumn Header="Index 3" Width="80" IsReadOnly="True" Binding="{Binding Path=Barcodes[2].Value}" />
    <dg:DataGridTextColumn Header="Index 4" Width="80" IsReadOnly="True" Binding="{Binding Path=Barcodes[3].Value}" />
    <dg:DataGridTextColumn Header="Index 5" Width="80" IsReadOnly="True" Binding="{Binding Path=Barcodes[4].Value}" />
    <dg:DataGridTextColumn Header="Index 6" Width="80" IsReadOnly="True" Binding="{Binding Path=Barcodes[5].Value}" />
</dg:DataGrid.Columns>

PROBLEM
When I execute this code, I am able to bind the DocumentId successfully to the grid, but the barcode list doesn't seem to be binding correctly.  I have verified that there is data in the list.  What am I doing wrong?

A: The usual pattern to use in these cases is to implement INotifyPropertyChanged for your BarCode objects and expose them to the DataGridControl with a ObservableCollection. The DataGrid would then show one Barcode object per row with each column displaying the public properties of the BarCode.
Changes in either the Barcode or the the collection would then be propagated to the DataGrid and vice-versa (depending on the DataGrid properties).


text:
Q: C1189 #error: /RTCc rejects conformant code I try to compile the following solution:
https://github.com/TimoKunze/EditControls
When I try to compile it using VS 2022, I am getting the following compiler error:
Error   C1189   #error:  /RTCc rejects conformant code, so it is not supported by the C++ Standard Library. Either remove this compiler option, or define _ALLOW_RTCc_IN_STL to acknowledge that you have received this warning.
EditCtls    C:\Program Files\Microsoft Visual Studio\2022\Preview\VC\Tools\MSVC\14.34.31721\include\yvals_core.h    1542
How could I get rid of this compiler error?
Here are my directories:
Include directories:
D:\Projects\Libraries\WTL\Include;$(IncludePath);$(VCInstallDir)atlmfc\include
External Include Directories:
$(VC_IncludePath);$(WindowsSDK_IncludePath);
Library directories:
$(ProgramFiles)\Windows Kits\10\Lib\10.0.10586.0\um\x86;$(LibraryPath);$(VSInstallDir);$(VSInstallDir)lib
Library WinRT directories:
$(WindowsSDK_MetadataPath);
Source directories:
$(VC_SourcePath);
I am pretty new with C++, and I don't know how to "define _ALLOW_RTCc_IN_STL to acknowledge that I have received this warning."
I also don't see that the /RTCs is defined anywhere in the project property page. Where would I find that?


text: Q: Removing ALAssets in one Array from another I have an array containing my camera roll ALAssets.  In addition I have custom album containing ALAssets.  I would like to remove the custom album assets from the camera roll ALAssets array.  Thereby having an array containing the camera roll minus the assets in the custom album.  I'm able to create the arrays containing both the camera roll assets and the custom album assets but I'm unsure how to then remove the unwanted assets.


text:
Q: How to deserialize json to .net type and return it as string I'm trying to send a POST request using Fiddler as so:
POST http://localhost:50196/api/values/json HTTP/1.1
User-Agent: Fiddler
Content-Type: application/json;
Host: localhost:50196
Content-Length: 73

{"ssn":1605789787,"creditScore":598,"loanAmount":10.0,"loanDuration":360}

This is my WebAPI controller, where I deserialize it to a .NET type which is my POCO. Then I get the ssn and generate a rate which I then want to return.
public class ValuesController : ApiController
{
    [ActionName("json")]
    public string Post(string request)
    {
        var json = JsonConvert.DeserializeObject<JsonModel>(request);
        var ss = json.Ssn;

        var random = new Random();
        var interestRate = random.Next(100, 500);
        var rate = interestRate / 100;

        var delta = "{\"ssn\":" + ss + ",\"interestRate\":" + rate + "}";

        return delta;

    }

}

POCO:
public class JsonModel
{
    [JsonProperty("ssn")]
    public string Ssn { get; set; }
    [JsonProperty("creditScore")]
    public int CreditScore { get; set; }
    [JsonProperty("loanAmount")]
    public decimal LoanAmount { get; set; }
    [JsonProperty("loanDuration")]
    public int LoanDuration { get; set; }
}

WebAPI config:
    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services

        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional },
            constraints: new {action = @"[a-zA-Z]+", id = @"\*"}
        );
    }

This is the error I'm getting:

[HttpException]: The controller for path '/api/values/json'
  was not found or does not implement IController. ved
  System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext
  requestContext, Type controllerType) ved
  System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext
  requestContext, String controllerName) ved
  System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase
  httpContext,  IController& controller, IControllerFactory& factory)
  ved System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase
  httpContext,  AsyncCallback callback, Object state) ved
  System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext,
  AsyncCallback callback, Object state) ved
  System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext
  context, AsyncCallback cb, Object extraData) ved
                               System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
  ved System.Web.HttpApplication.ExecuteStep(IExecutionStep step,
  Boolean& completedSynchronously)

A: I think your controller can accept your POCO type directly, no need to serialize from the string by hand:
public HttpResponseMessage Post(HttpRequestMessage request, [FromBody]JsonModel)

I'm not sure that's the problem, though. When using WebAPI, I'd stay away from the ActionName attribute. I think it's a lot cleaner to have a separate controller for each type with simple Get/Post, etc. methods. So, in your case:
Controller:
public HttpResponseMessage Post(HttpRequestMessage request, [FromBody]JsonModel)
{}

Then you simply post to:
api/values

...and, finally, your route config:
routeTemplate: "api/{controller}/{id}"

A: Firstly, you are completely missing out in ASP.NET MVC model binding capabilities here, instead of accepting a JSON string in the action and then deserializing, just expect the model and let the framework do the binding for you e.g.
public HttpResponseMessage Post(JsonModel model)
{
    ...
}

Secondly, your exception is due to a routing problem. You are trying to post to api/values/json which is the equivalent to api/{controller}/{action}. However, as you can see you don't have an action which maps to that particular route because your only route expects an id parameter (but your action contains a request parameter).
Switching to using the model directly in the view should be enough to fix this issue and should work posting directly to api/values/json.

I thought that { id = RouteParameter.Optional } was optional as in it would accept the ID

That generally would be the case, however, in your route you have a constraint set on the id which says it has to contain some value - this renders your default value obsolete.


text:
Q: ready made forum,chat and PM soutions in java/jsp I want a ready made jsp/java application that contains forums,chat and IM>I want to modify it according to my needs
Can anyone suggest me?

A: For a modern web-based Chat(IM) application take a look at emite. You also need an XMPP server to deploy it, such as ejabberd, OpenFire and Tigase.
For Forum software take a look at the followings:

*

*JavaBB

*Yazd

*And an Internet forum software comparison is here

*With another list of (maybe old) ones here.


text:
Q: How to tell if wavepacket is nonstationary vs. stationary? $$\psi(x,t) = \int_{-\infty}^{\infty} A(k)e^{i(kx-w(k)t)} \mathrm{d}k$$
Also, what properties of this equation will tell me whether or not this wave is going to spread over time?

A: That's a general solution for a wave packet.
1) A(k) is the spatial Fourier transform of the wave packet at t = 0. Just set t=0 inside the integral and you have the inverse Fourier (or Fourier) tRansform of A(k).
2) That means that A(k) is the spatial spectra of the initial wave packet. So the initial packet spatial extent is roughly 1/(range in k where A is nonzero, or practically non negligible).
3) the wave packet little waves moves to the right in x with phase velocity (i.e., the velocity of the little waves inside the packet) of w(k)/k. If w(k)/k is constant but not zero, call it $v_p$, the phase velocity and the velocity of the packet as a whole, called the group velocity, $v_g$, are the same. That is called a non-dispersive packet (sometimes a packet that is traveling in a non-dispersive media), as it travels. Electromagnetic wave packets in vacuum (and no gravity) are non-dispersive.
4) if w(k) = 0, the packet nor the wavelets inside move. It is static.
5) if w(k)/k is not constant, the packet or media are called dispersive. The group velocity is then $v_g = dw/dk$. That's the velocity of the packet as a whole.
6) if w(k) = constant, it is a sinusoidal (or complex exponential) oscillation in time of the initial wave packet, and it does not move to the right. You can see that from the integral you wrote.
So it'll move to the right under cases 3 when no dispersive, and 5. Ie, non-stationary. If w(k) is either 0 or a constant the packet won't move to the right, i.e. it is stationary. For 6 it is stationary as a packet, but oscillates in place.
You can see a math description with some of those cases described and drawn for a couple different initial packets, like a Gaussian shape at
http://users.physics.harvard.edu/~schwartz/15cFiles/Lecture11-WavePackets.pdf. There's too many possibilities for both the initial packet and w(k) to show them all. The function w(k) is called the dispersion relations, and they also explain why. And you can google more on it.


text:
Q: AS2: How do you remove onEnterFrame? For the life of me, I can't get this event to stop. I originally wrote this code in AS3, but when my project manager gave me the specs, they wanted it in AS2. Not really a big deal, most of the code just needed some tweaks.
However, in this one part, I play a small part of a movieclip backward (as an exit animation, opposite of its intro animation). In AS3, it went smoothly like this:
function playExit() {
     this.gotoAndStop(MovieClip(root).exitLabel);
     this.addEventListener(Event.ENTER_FRAME, playBackwards);
}
function playBackwards(e:Event) {
     this.prevFrame();
     if(this.currentFrame == 1) {
          this.removeEventListener(Event.ENTER_FRAME, playBackwards);
          finishExit();
     }
}

Now I'm trying to convert it to AS2. It seems like it should work like this:
function playExit() {
     this.gotoAndStop(_root.exitLabel);
     this.onEnterFrame = function() {
          playBackwards();
     }
}
function playBackwards() {
     trace('Backwaaaaaaaaards, woooo!!');
     this.prevFrame();
     if(this.currentFrame == 1) {
          delete this.onEnterFrame;
          trace('Backwards Completed.');
          finishExit();
     }
}

However, it seems like my little happy backwards trace statement is still running (thus not being deleted) even after my "Backwards Completed." shows up in the output. So when the animation loops, it doesn't even show up at all because it's still trying to run backwards. There's no compiling errors, and I'm not getting any other errors. Am I missing something?
The publish settings are set for Flash Player 8, AS2.
Please and thank you.
Edit: I event tried it like this because I thought it may have been a scope issue, but it only made it worse because it didn't even play backwards (movieclip stayed on the stage).
function playExit() {
     this.gotoAndStop(_root.exitLabel);
     this.onEnterFrame = function() {
          trace('Backwaaaaaaaaards, woooo!!');
          this.prevFrame();
          if(this.currentFrame == 1) {
               delete this.onEnterFrame;
               trace('Backwards Completed.');
               finishExit();
          }
     }
}

A: I'm an idiot. This always happens after I post the question.
Turns out that the "Backwards Completed." never pulled up in my Output (I ran ctrl F to find it, and it wasn't there, it was a different trace statement that led me to believe it showed up).
Anyway, I forgot to change
this.currentFrame

to
this._currentFrame

Thanks again, guys.


text:
Q: Using Moles to override to System.Configuration, not as a Unit Test I'm thinking about the building of a centralized service to provide connection strings to properly authenticated applications.
In order keep the service compatible with normal processes, I was thinking that it would be a great thing to override the System.Configuration ConnectionStrings in the app.config or web.config.
I've thought about using Moles to do this, but the only examples that I'm finding are for UnitTests.
What I'd really like to have is a Mole override to the System.Configuration.ConfigurationManager class, so that I could specifically override the ConnectionStringsGet method to look for a custom style of connection string.  If it isn't found, then pass the call on to the original ConfigurationManger code in order to handle normal connection strings.
I have not yet written any code with Moles because I'm scratching my head about how to start this idea.  If anyone has a pointer on how to get started, I'll take it and go dig some more.

A: It appears that Moles doesn't really support trying to override the System.Configuration in this scenario.
I've found a couple of posts that show promising methods for customizing the system.configuration process.
First is a blog post by Andy Pook http://andypook.blogspot.com/2007/07/overriding-configurationmanager.html and second is a CodeProject article that extends the solution given by Andy http://www.codeproject.com/Articles/69364/Override-Configuration-Manager
These articles have been useful to my thinking process.

A: You'd probably be better off creating an interface to get the data from the config file, and a class which will just wrap the static members.  You can then do your custom logic, and fall back to the standard static methods.


text: Q: Convergence of measure topology Let $(\Omega,\mu)$ be a $\sigma$-finite measure space. Let $1\leq p<\infty.$ Suppose $T:L^p(\Omega)\to L^p(\Omega)$ be a bounded positive function, i.e. it takes nonnegative functions to nonnegative functions. Suppose he restriction of $T$ on any $L^p(A)$, where A has finite measure, is continuous in topology of convergence in measure for both domain and codomain ($L^p(A)$ has the $\sigma$ algebra as the restriction of the whole $\sigma$-algebra). Does it imply that $T:L^p(\Omega)\to L^p(\Omega)$ is continuous in the topology of convergence in measure?


text:
Q: Selecting a single input value from an HTML file using only javascript I am trying to do a form validation WITHOUT jquery. I have found this code, but I am not sure how to convert it from Jquery to plain Javascript.
I found this code here

$('.clickme').click(function() {

  alert($(this).prev().val())
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="hidden" name="myvalue" class="form-control input_text" value="aaa" />
<input type="button" class="clickme" value="Get Value" />

<input type="hidden" name="myvalue" class="form-control input_text" value="bbb" />
<input type="button" class="clickme" value="Get Value" />

<input type="hidden" name="myvalue" class="form-control input_text" value="ccc" />
<input type="button" class="clickme" value="Get Value" />

<input type="hidden" name="myvalue" class="form-control input_text" value="ddd" />
<input type="button" class="clickme" value="Get Value" />

<input type="hidden" name="myvalue" class="form-control input_text" value="eee" />
<input type="button" class="clickme" value="Get Value" />

Any help with this would be amazing. I have multiple forms in one HTML file, all with the same input variables, and I need the functions to only run for when that specific input button is clicked.

A: The below JS code should do the job :
document.querySelectorAll('.clickme').forEach(ele => {
  ele.addEventListener('click', () => alert(ele.previousElementSibling.value))
});

Need to loop through all elements with class "click me" and add a click event to them

document.querySelectorAll('.clickme').forEach(ele => {
  ele.addEventListener('click', () => alert(ele.previousElementSibling.value))
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="hidden" name="myvalue" class="form-control input_text" value="aaa" />
<input type="button" class="clickme" value="Get Value" />

<input type="hidden" name="myvalue" class="form-control input_text" value="bbb" />
<input type="button" class="clickme" value="Get Value" />

<input type="hidden" name="myvalue" class="form-control input_text" value="ccc" />
<input type="button" class="clickme" value="Get Value" />

<input type="hidden" name="myvalue" class="form-control input_text" value="ddd" />
<input type="button" class="clickme" value="Get Value" />

<input type="hidden" name="myvalue" class="form-control input_text" value="eee" />
<input type="button" class="clickme" value="Get Value" />


text:
Q: Decoupling capacitors: what size and how many? Lots of chips nowadays require smoothing capacitors between VCC and GND for proper function. Given that my projects run at all sorts of different voltage and current levels, I was wondering if anyone had any rules of thumb for a) how many and b) what size capacitors should be used to ensure that power supply ripple doesn't affect my circuits?

A: If you're using big electrolytics to smooth out a power supply, don't forget to add small ceramic caps in parallel for the high frequencies.  Electrolytic caps actually look like inductors at high frequencies.

*

*http://www.boostbuck.com/BypassingaCapacitor.html

*http://www.amccaps.com/leaded-capacitors/switch-mode-ceramic-capacitors/impedance-vs-frequency.html

*http://enjeti.tamu.edu/conf-papers/electrolytic-cap-pwm-asd.pdf

A: You need to add a couple of more questions -- (c) what dielectric should I use and
(d) where do I place the capacitor in my layout.
The amount and size varies by application. For power supply components
the ESR (effective series resistance) is a critical component. For example the MC33269 LDO datasheet lists an ESR recommendation of 0.2Ohms to 10Ohms. There is a minimum amount
of ESR required for stability.
For most logic ICs and op-amps I use a 0.1uF ceramic capacitor. I place the capacitor
very close to the IC so that there is very short path from the capacitor leads
to the ground. I use extensive ground and power planes to provide low impedance
paths.
For power supply and high current components each application is different.
I follow the manufacturer recommendations and place the capacitors very close
to the IC.
For bulk filtering of power inputs coming into the board I will typically use a
10uF ceramic X7R capacitor. Again this varies with application.
Unless there is an minimum ESR requirement for stability or I need very large
values of capacitance I will use either X7R or X5R dielectrics. Capacitance
varies with voltage and temperature. Currently it is not difficult to get
affordable 10uF ceramic capacitors. You do not need to over specify the voltage
rating on ceramic capacitors. At the rated voltage the capacitance is within
the tolerance range. Unless you increase the voltage above the dielectric breakdown
you are only losing capacitance. Typically the dielectric strength is 2 to 3 times
the rated voltage.
There is a very good application note about grounding and decoupling
by Paul Brokaw called "An IC Amplifier User's Guide to Decoupling,
Grounding,. and Making Things Go Right for a Change".

A: If it's not a very demanding circuit, scatter some 100nF X7R caps around.  If you don't have power planes, keep them close to a pair of device pins, directly across them ideally.
If your circuit is drawing a lot of power, at high frequencies, you need to design your power distribution system (PDS).  Xilinx have a reasonable introduction to this.  There's also lots of discussion on si-list.
Next question is "what are good rules of thumb to decide if my circuit is demanding enough to be beyond rules of thumb for decoupling design?" :)

A: A smoothing capacitor should be placed, as you stated, in the circuit in case of current spikes caused by load changes. When placing a smoothing capacitor, place it as close to the IC pin as you can. A value of 47uf to about 100uf should be sufficient.
Check out:
http://www.learningaboutelectronics.com/Articles/How-to-connect-a-voltage-regulator-in-a-circuit
for some info on clarifying different capacitor usages in circuits.

A: The reservoir or smoothing capacitor value is a product of the maximum current required by the circuit, and the recovery time of the regulator under load... (no regulator reacts instantly)...
In circuit where the current demands are constant, 10uF - 22uF should suffice...
For circuits where current demands fluctuate rapidly, a capacitor value in the hundreds of uF may be required...
In a recent build with a 3.3 volt supply and sudden demand for 250mA, a capacitor value of 470uF was required to maintain stability...

A: I use the following rules of thumb for my digital circuits:
Each pair of power supplies pins should get its X7R ceramic 100nF capacitor. It should be as close as possible to the pins. Best is if the supply line passes by the capacitor first before it goes to the pin, but most of the time this is not necessary.
The capacitors at the ICs have nothing to do with ripple from the PSU.  They are needed for decoupling, that is to satisfy fast changes in power supply current for the respective IC.  The leads from the power supply to the IC are comparatively long and have some inductance, which prevents quick changes of the current.  The power supply voltage at the IC may then get out of range and the IC can spuriously malfunction or in extreme cases become damaged.
Input and output of the voltage regulator should get a capacitor according to its data sheet, in particular with a correct equivalent series resistance (ESR) value.  If you do it wrong the regulator may oscillate, especially for low dropout voltage regulators (LDOs).
For analog circuits X7R may not be the right material, because it has a relatively large piezoelectric effect. That is, mechanical vibrations can cause voltage changes and vice versa. C0G is better in that respect. Though this caveat mostly applies to signal paths.

A: Like I said in comment, you probably mean decoupling capacitors, not smoothing capacitors.
Decoupling capacitors' purpose is not to get rid of your power supply's ripple, but to catch glitches. An IC may need much extra current for a short time, for instance when thousands of transistors switch at the same time. The inductance of the PCB's traces may prevent that the power supply can deliver this that fast. So decoupling capacitors are used as local energy buffers to overcome this.
This means that it's not easy to calculate what value the capacitors should have. The value depends on the inductance of the PCB's traces and the current peaks your IC excerts on the power supply. Most engineers will place 100nF X7R capacitors as close as possible to the IC's power pins. One capacitor per power pin. A good IC pinout will have a ground pin next to each power pin, so you can keep the loop as short as possible.
For low-power ICs 10nF capacitors may be sufficient and may be preferred over the 100nF because of their lower internal inductance. For this reason you also find 10nF parallel to the 100nF. In this case the smaller capacitor should be closest to the pins.

A: Capacitors made of X7R (and even more so Y5V) have huge capacity/voltage dependence. You can check this yourself at the excellent Murata products online characteristics browser (Simsurfing) at ttp://ds.murata.co.jp/software/simsurfing/en-us/
The ceramic capacitor voltage dependence is striking. It is normal for X7R capacitor to have no more then 30% of rated capacity at rated voltage. For example - 10uF Murata capacitor GRM21BR61C106KE15 (0805 package, X5R) rated for 16V will give you only 2.3uF capacity with 12V DC applied at 25C temperature. Y5V is much worse in this respect.
In order to obtain close to 10uF capacity you have to use 25V rated GRM32DR71E106K (1210 case, X7R) which gives 7.5uF under same conditions.
Other then DC voltage (and temperature) dependencies, Real "ceramic chip capacitor" have strong frequency dependence when acting as power decoupling shunts. Murata's site provides |Z|, R and X frequency dependencies graphs for their capacitors, browsing these gives you an insight into actual performance of the part we call "capacitor" at different frequencies.
Real ceramic capacitor can be modeled by an ideal capacitor (C) connected in series with internal resistance (Resr) and inductance (Lesl). There is also R-isolation in parallel with C, but unless you go over capacitor's rated voltage it is unimportant for power decoupling applications.

simulate this circuit – Schematic created using CircuitLab
Thus chip ceramic capacitors will act as capacitors only up to a certain frequency (self resonant for the serial LC contour which real capacitor is in fact), above which they start to act as inductors. This frequency Fres is equal to sqrt(1/LC) and is determined by both the ceramics composition and capacitor geometry - generally smaller packages have higher Fres Also, capacitors have a purely resistive component (Resr) which results mostly from the losses in the ceramic and determines the minimum impedance the capacitor can provide. It is usually in the mili-Ohms range.
In practice for good decoupling I use 3 types of capacitors.
Higher capacity about 10uF in 1210 or 1208 package per integrated circuit, that covers 10KHz to 10MHz with less then 10-15 mili-Ohm shunt for power line noise.
Then per every IC power pin I put two capacitors - one 100nF in 0806 package covering 1MHz to 40MHz with 20 mili-Ohm shunt, and one 1nF in 0603 package, covering 80MHz to 400MHz with 30 mili-ohm shunt. This more or less covers 10KHz to 400MHz range for filtering out power line noise.
For sensitive power circuits (like PLL digital and especially analog power) I put ferrite beads (again, Murata has characteristics browser for those) rated 100 to 300 Ohms at 100Mhz. It's also a good idea to separate grounds between sensitive and regular power circuits. Thus overall outline of IC power plan looks like this, with 10uF C6 per IC package, and 1nF/100nF C4/C5 per each power pin:

simulate this circuit
Speaking about routing and placement - power and ground is routed to capacitors first, only at capacitors we connect to power and ground planes through vias.  1nF capacitors are placed closer to IC pins. Capacitors have to be placed as close to power pins as possible, no further then 1mm trace length from capacitor pad to IC pad.
Vias and even short traces on PCB pose a significant inductance for the frequencies and capacitance we're dealing with. For example, 0.5mm diameter via in 1.5mm thick PCB has 1.1nH inductance from top to bottom layer. For 1nF capacitor that results in Fres equal to only 15MHz. Thus, connecting a capacitor through via makes 1nF capacitor low Resr unusable at frequencies above 15MHz. In fact 1.1nH reactance at 100MHz is as much as 0.7 Ohm.
Trace of 1mm length 0.2mm width, 0.35mm above power plane will have comparable inductance of 0.4nH - which again makes capacitors less efficient, thus trying to limit capacitors trace length to a fraction of a mm and making them as wide as possible makes a lot of sense.


text:
Q: Efficient reloading data / pushing data from server to client I'm looking for the 'way to go' (i.e. the most efficient, most used, general accepted way) when it comes to the reloading of data from a web server to a front end. In the end application, I will have several output fields where data has to be written to, for example like this:

The data streams will be different from each other in the end application. The lines will have to be reloaded with fresh, up to date data from the server.
I have been thinking of using Ajax requests to update like every second, but there has to be an other way to do this. Ajax requests will cause a lot data traffic. Also, when using the Facebook chat, you don't have to wait every second, chats are received almost instantly. Yet I don't see any Ajax polling requests being made when I use the developer tools of Mozilla Firefox. This made me think if there would be a different way to do this.
I've looked into Node.js, but it appears that isn't possible with my host.
I have heard people talking about Ajax Push, is that what I should use? If so, can you give me a basic usage example?
If not, what would then be the way to go when having multiple data streams that have to be reloaded within a second?
Requirements are speed and low data traffic. It therefore wouldn't be an option to continuously poll the server, I think, because that would create an enormous overhead.
I don't think it's of any importance, but I'm using PHP5.3 in the back end and JavaScript with jQuery 1.9.1 in the front end.

A: This question has been asked a number of times, but in a slightly different ways. Here are a few references that are worth a read:

*

*What are Long-Polling, Websockets, Server-Sent Events (SSE) and Comet?

*Using comet with PHP?

*Apache with Comet Support

*Server Scalability - HTML 5 websockets vs Comet

*How to implement event listening in PHP
In summary: if you are looking at building your solution using PHP on Apache then holding open persistent connections (HTTP long-polling or streaming) is going to use up resources very quickly (is highly inefficient). So, you would be better using a hosted solution (*disclaimer - I work for a hosted solution).
HTTP-Long polling and HTTP Streaming are solutions which have been superseded by Server-Sent Events and WebSockets. So, where possible (where the web client provides support) you should use one of these solutions before falling back to an HTTP-based solution. A good realtime web technology will automatically handle this for you.
Since your diagram shows you are subscribing to multiple data streams you should also consider a Publish/Subscribe solution that naturally fits with this. Again, a good realtime web tech solution will provide you with this.
Also see the realtime web technology guide.

A: I think what you are looking for is generally called Comet.  The was this technique is often made to work is as follows:

*

*The client (web browser) makes a request to the server for new data. This is not reloading the page, but rather is done in JavaScript

*The server responds to the request when it has some data for the client. Again, this doesn't impact the UI since it isn't the page itself that's getting reloaded: the loaindg of data is done "in background" so to speak, in JavaScript code.

*On the serve side, the request waits for new data, and returns the new data when available, or returns nothing if a timeout interval (defined on the server) is reached. This timeout is usually set to be lower than the browser HTTP timeout. The reason for this is so that the server can know whether a particular client got a particular piece of data. If the request is allowed to time out on the client side, the original request might be responded to by the server after the client has timed out, and the client will not get the data, even though the server thinks that it did.

The data is indeed usually transferred as JSON, but you can choose whatever encoding you'd like. See here for one example of how to do this. Goosh is another example of this technique, and so is Interactive Python Shell.  The code for all is available.

On the PHP side you will want to create a page that will respond to these "background" JavaScript Comet requests. It could be the same page as the one that user loads, but let's say it is different, for ease of explanation. So the user loads index.php and the JavaScript Comet code calls getNewData.php to retrieve new data.
In your getNewData.php you will want to wait for your event and return the data then. You don't want to use polling for this, but there are PHP libraries that allow one to use various interprocess communication strategies to wait on events, see this question for instance.  The high-level pseudocode for your getNewData.php would look as follows:

*

*parse JSON request

*Enter an efficient wait state (with timeout), waiting for your "new data is available" event

*Did previous step time out?
Yes: send response indicating no data
No: send response with new data


text:
Q: Why does it complain 'images' variable not available? I am running the TF2 tutorial, and copied exactly the code into a .py file and run it in PyCharm, but got this error message:
Testing started at 12:50 AM ...
/home/martin/nlp/my-env/tf/bin/python /home/martin/.local/share/JetBrains/Toolbox/apps/PyCharm-C/ch-0/193.5233.109/plugins/python-ce/helpers/pycharm/_jb_pytest_runner.py --path /home/martin/tf2-tutorial/cnn_mnist.py
Launching pytest with arguments /home/martin/tf2-tutorial/cnn_mnist.py in /home/martin/tf2-tutorial

============================= test session starts ==============================
platform linux -- Python 3.7.1, pytest-5.3.1, py-1.8.0, pluggy-0.13.1 -- /home/martin/nlp/my-env/tf/bin/python
cachedir: .pytest_cache
rootdir: /home/martin/tf2-tutorial
collecting ... collected 1 item

cnn_mnist.py::test2_step ERROR                                           [100%]
test setup failed
file /home/martin/tf2-tutorial/cnn_mnist.py, line 60
  @tf.function
  def test_step(images, labels):
E       fixture 'images' not found
>       available fixtures: cache, capfd, capfdbinary, caplog, capsys, capsysbinary, doctest_namespace, monkeypatch, pytestconfig, record_property, record_testsuite_property, record_xml_attribute, recwarn, tmp_path, tmp_path_factory, tmpdir, tmpdir_factory
>       use 'pytest --fixtures [testpath]' for help on them.

Why does it think it's a pytest program? And why does it issue this error message? The tutorial should work "as is".
The copied code from the tutorial is below (exact copy):
from __future__ import absolute_import, division, print_function, unicode_literals

import tensorflow as tf

from tensorflow.keras.layers import Dense, Flatten, Conv2D
from tensorflow.keras import Model

mnist = tf.keras.datasets.mnist

(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0

# Add a channels dimension
x_train = x_train[..., tf.newaxis]
x_test = x_test[..., tf.newaxis]

train_ds = tf.data.Dataset.from_tensor_slices(
    (x_train, y_train)).shuffle(10000).batch(32)

test_ds = tf.data.Dataset.from_tensor_slices((x_test, y_test)).batch(32)

class MyModel(Model):
  def __init__(self):
    super(MyModel, self).__init__()
    self.conv1 = Conv2D(32, 3, activation='relu')
    self.flatten = Flatten()
    self.d1 = Dense(128, activation='relu')
    self.d2 = Dense(10, activation='softmax')

  def call(self, x):
    x = self.conv1(x)
    x = self.flatten(x)
    x = self.d1(x)
    return self.d2(x)

# Create an instance of the model
model = MyModel()

loss_object = tf.keras.losses.SparseCategoricalCrossentropy()
optimizer = tf.keras.optimizers.Adam()

train_loss = tf.keras.metrics.Mean(name='train_loss')
train_accuracy = tf.keras.metrics.SparseCategoricalAccuracy(name='train_accuracy')

test_loss = tf.keras.metrics.Mean(name='test_loss')
test_accuracy = tf.keras.metrics.SparseCategoricalAccuracy(name='test_accuracy')

@tf.function
def train_step(images, labels):
  with tf.GradientTape() as tape:
    predictions = model(images)
    loss = loss_object(labels, predictions)
  gradients = tape.gradient(loss, model.trainable_variables)
  optimizer.apply_gradients(zip(gradients, model.trainable_variables))

  train_loss(loss)
  train_accuracy(labels, predictions)

@tf.function
def test_step(images, labels):
  predictions = model(images)
  t_loss = loss_object(labels, predictions)

  test_loss(t_loss)
  test_accuracy(labels, predictions)

EPOCHS = 5

for epoch in range(EPOCHS):
  for images, labels in train_ds:
    train_step(images, labels)

  for test_images, test_labels in test_ds:
    test_step(test_images, test_labels)

  template = 'Epoch {}, Loss: {}, Accuracy: {}, Test Loss: {}, Test Accuracy: {}'
  print(template.format(epoch+1,
                        train_loss.result(),
                        train_accuracy.result()*100,
                        test_loss.result(),
                        test_accuracy.result()*100))

  # Reset the metrics for the next epoch
  train_loss.reset_states()
  train_accuracy.reset_states()
  test_loss.reset_states()
  test_accuracy.reset_states()

Could this be due to the PyCharm environment issue? But it has been working all fine?


text:
Q: How to publish android library without R and BuildConfig I made an android library publish it to jcenter for several versions. But when I use it, I found  R and BuildConfig reference from my own library.How to avoid upload R and BuildConfig.
Here is my build.gradle:
version = "2.1.3"
def siteUrl = 'https://github.com/boybeak/DelegateAdapter'
def gitUrl = 'https://github.com/boybeak/DelegateAdapter.git'
group = "com.github.boybeak"
install {
    repositories.mavenInstaller {
        // This generates POM.xml with proper parameters
        pom {
            project {
                packaging 'aar'
                name 'DelegateAdapter'
                url siteUrl
                licenses {
                    license {
                        name 'Apache-2.0'
                        url 'http://www.apache.org/licenses/LICENSE-2.0.txt'
                    }
                }
                developers {
                    developer {
                        id 'boybeak'
                        name 'gaoyunfei'
                        email 'boybeak@qq.com'
                    }
                }
                scm {
                    connection gitUrl
                    developerConnection gitUrl
                    url siteUrl
                }
            }
        }
    }
}

task sourcesJar(type: Jar) {
    from android.sourceSets.main.java.srcDirs
    classifier = 'sources'

    exclude "**/R.class"
    exclude "**/BuildConfig.class"
}

task jar(type: Jar) {
    from 'build/intermediates/classes/release'
    exclude '**/BuildConfig.class'
    exclude '**/R.class'

}

task javadoc(type: Javadoc) {
    source = android.sourceSets.main.java.srcDirs
    classpath += project.files(android.getBootClasspath().join(File.pathSeparator))
    options.encoding "UTF-8"
    options.charSet 'UTF-8'
    failOnError false

    exclude "**/R.java"
    exclude "**/BuildConfig.java"
}

task javadocJar(type: Jar, dependsOn: javadoc) {
    classifier = 'javadoc'
    from javadoc.destinationDir

    exclude "**/R.java"
    exclude "**/BuildConfig.java"
}

artifacts {
    archives jar
    archives javadocJar
    archives sourcesJar
}
Properties properties = new Properties()
properties.load(
    project.rootProject.file('local.properties').newDataInputStream()
)
bintray {

    user = properties.getProperty("bintray.user")
    key = properties.getProperty("bintray.apikey")
    configurations = ['archives']
    pkg {
        repo = "nulldreams"
        name = "adapter"                // project name in jcenter
        websiteUrl = siteUrl
        vcsUrl = gitUrl
        licenses = ["Apache-2.0"]
        publish = true
    }
}

A: Here's how you can avoid BuildConfig generation for your android libraries:
// TODO replace with https://issuetracker.google.com/issues/72050365 once released.
libraryVariants.all(Action {
    generateBuildConfigProvider.configure {
        enabled = false
    }
})

This works for Gradle Kotlin DSL too.
I am not aware of a way to prevent generation of the R class when you don't have any resources though. Please, comment if you find a way for this.


text:
Q: facebook.stackoverflow.com tools show flags on non-Facebook SO questions On the Stack Overflow Facebook minisite tools page, flags are shown without tag restrictions, meaning that flags from the main Stack Overflow site on non-Facebook questions are shown.
screenshot http://phpcode.eu/images/1314216098.png
As Bill notes below, this makes sense for moderators, but it doesn't make sense for 10k and 20k users who only use the Facebook sub-site.

A: Facebook.Stackoverflow needs all the help it can get for closing and flagging the onslaught of bad/dupe/off-topic questions it can get, so these tools should be updated.  It would help to see a focused view on the bad Facebook questions.   It would also benefit any additional future mini-sites that get launched.   This seems like a over sight when this was built and I really hope this gets implemented.  I started a bounty for it to get more attention.


text:
Q: Golang Converting JSON map[key:2073933158088]
I need to grab the key out of this data structure as a string, but I can't seem to figure out how!
Help with this overly simple question very much appreciated.
The value above is encapsulated in the variable named data.
I have tried: data.key, data[key], data["key"], data[0] and none of these seem to be appropriate calls.
To define data I sent up a JSON packet to a queue on IronMQ. I then pulled the message from the queue and manipulated it like this:
payloadIndex := 0

for index, arg := range(os.Args) {
        if arg == "-payload" {
                payloadIndex = index + 1
        }
}

if payloadIndex >= len(os.Args) {
        panic("No payload value.")
}

payload := os.Args[payloadIndex]

var data interface{}

raw, err := ioutil.ReadFile(payload)

if err != nil {
    panic(err.Error())
}

err = json.Unmarshal(raw, &data)

A: Design your data type to match json structure. This is how can you achieve this:
package main

import (
    "fmt"
    "encoding/json"
)

type Data struct {
    Key string `json:"key"`
}

func main() {
    data := new(Data)
    text := `{ "key": "2073933158088" }`
    raw := []byte(text)
    err := json.Unmarshal(raw, data)
    if err != nil {
        panic(err.Error())
    }
    fmt.Println(data.Key)
}

A: Since the number in the json is unquoted, it's not a string, Go will panic if you try to just handle it as a string (playground: http://play.golang.org/p/i-NUwchJc1).
Here's a working alternative:
package main

import (
    "fmt"
    "encoding/json"
    "strconv"
)

type Data struct {
    Key string `json:"key"`
}

func (d *Data) UnmarshalJSON(content []byte) error {
    var m map[string]interface{}
    err := json.Unmarshal(content, &m)
    if err != nil {
        return err
    }
    d.Key = strconv.FormatFloat(m["key"].(float64), 'f', -1, 64)
    return nil
}

func main() {
    data := new(Data)
    text := `{"key":2073933158088}`
    raw := []byte(text)
    err := json.Unmarshal(raw, data)
    if err != nil {
        panic(err.Error())
    }
    fmt.Println(data.Key)
}

You can see the result in the playground: http://play.golang.org/p/5hU3hdV3kK


text:
Q: Use RegisterStartupScript to place HTML at the bottom of the page? I tried using Page.ClientScript.RegisterStartupScript to place HTML or invisible elements at the bottom of my page and this seems to be working fine. Is there anything wrong with this as the RegisterStartupScript was intended for JavaScript only?

A: <asp:ContentPlaceHolder> is the correct control to use to "place HTML or invisible elements at the bottom of my page"

A: The problem you'll most likely encounter with this approach is that when using the UpdatePanel, you should be calling ScriptManager.RegisterStartupScript() instead. This will depend on the structure of your page (eg, are you registing the script from within a UserControl), and what your javascript is doing

A: What you've done is not something to be taken as a best practice, but I believe it should not cause you any problem. What the ScriptManager and the ClientScript do, is just append the specified content to the output HTML that is going to be sent to the browser.
However, you can consider to achieve this by placing place holder control at the bottom of the  page and then append your HTML content to that holder.


text:
Q: C# Reflection: How to get the properties of the derived class from the base class Basically I just want to get the properties of the derived class with [Test]  attribute from the base class.
Here is my sample code:
namespace TestConsole
{
    public class BaseClass
    {
        private System.Int64 _id;

        public BaseClass()
        { }

        [Test]
        public System.Int64 ID
        {
            get { return _id;}
            set { _id = value;}
        }

        public System.Xml.XmlNode ToXML()
        {
            System.Xml.XmlNode xml = null;

            //Process XML here

            return xml;
        }
    }

    public class DerivedClass : BaseClass
    {
        System.String _name;

        public DerivedClass()
        { }

        [Test]
        public System.String Name
        {
            get { return _name; }
            set { _name = value; }
        }
    }

    public class TestConsole
    {
        public static void main()
        {
            DerivedClass derivedClass = new DerivedClass();

            System.Xml.XmlNode xmlNode = derivedClass.ToXML();
        }
    }
}

I want the xmlNode to be something like this:
<root>
  <class name="DerivedClass">
    <Field name="Id">
    <Field name="Name">
  </class>
</root>

Thank you

A: You can call this.GetType().GetProperties() and call GetCustomAttributes() on each PropertyInfo to find properties that have the attribute.
You will need to run the loop recursively to scan the properties of the base type.

A: I do not think that XmlNode is a good class for this purpose.
Firstly, creating an XmlNode requires you to pass an XmlDocument for it, which is not a beatiful solution.
Secondly, attributes and property values can be nicely extracted with LINQ and I think that this might integrate nicely with LINQ to XML (and, specifically, XElement class).
I wrote some code that does it:
using System;
using System.Linq;
using System.Xml.Linq;

[AttributeUsage(AttributeTargets.Property)]
class PropertyAttribute : Attribute { }

class BaseClass
{
    [Property]
    public int Id { get; set; }

    IEnumerable<XElement> PropertyValues {
        get {
            return from prop in GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public)
                   where prop.GetGetMethod () != null
                   let attr = prop.GetCustomAttributes(typeof(PropertyAttribute), false)
                                  .OfType<PropertyAttribute>()
                                  .SingleOrDefault()

                   where attr != null
                   let value = Convert.ToString (prop.GetValue(this, null))

                   select new XElement ("field",
                       new XAttribute ("name", prop.Name),
                       new XAttribute ("value", value ?? "null")
                   );
        }
    }

    public XElement ToXml ()
    {
        return new XElement ("class",
               new XAttribute ("name", GetType ().Name),
               PropertyValues
               );
    }
}

class DerivedClass : BaseClass
{
    [Property]
    public string Name { get; set; }
}

public static class Program
{
    public static void Main()
    {
        var instance = new DerivedClass { Id = 42, Name = "Johnny" };
        Console.WriteLine (instance.ToXml ());
    }
}

This outputs the following XML to the console:
<class name="DerivedClass">
  <field name="Name" value="Johnny" />
  <field name="Id" value="42" />
</class>


text:
Q: Cakephp 2.5.4: Redirection url after form submit I want to submit the form to www.example.com/users/signup but my page is submitting to www.example.com/test/users/signup.
Cakephp is installed in test folder. I have created htaccess inside test folder.
This is my htaccess:
<IfModule mod_rewrite.c>
 RewriteEngine on
 RewriteRule    ^$ test/    [L]
 RewriteRule    (.*) test/$1 [L]
 RewriteRule    ^$ /test/users/signup  [L]
 RewriteRule users/signup /users/signup [L]
</IfModule>

View:
<?php
echo $this->Form->create('User',array('url'=>array('controller'=>'users','action'=>'signup')), array('id' => 'signup',  'role' => 'form','class'=>'form-signin'));

echo $this->Form->input('User.email',array('type'=>'email','required'=>'required','class'=>'form-control','placeholder'=>'Email'));

echo $this->Form->input('User.password',array('type'=>'password','required'=>'required','class'=>'form-control','placeholder'=>'Password'));
?>

<button type="submit" class="btn btn-lg btn-primary btn-block">Sign up</button>
<?php echo $this -> Form -> end(); ?>

I created the routes:
<?php

Router::connect('/users/signup', array('controller' => 'users', 'action' => 'signup'));
?>

If you want to ask any query please feel free to ask.

A: /signup is the route I connected in routes.php - it's a "pretty url" so I don't have the default /{controller}/{action} format. If the site is not in a sub-folder, any form I generate with $this->Form->create() POSTs to /signup. However, when in the sub-folder, I can see the page at /signup but all generated URLs include the sub-folder. I want the site to work as though there is no sub-folder and behave as though it's in the root. Setting Configure::write('App.baseUrl, '/'); did the trick.
Solution is: Configure::write('App.baseUrl, '/');


text:
Q: Whats the difference between if () {} and if () in javascript I've written this code, which is a basic image gallery in jquery
$(document).ready(function() {
 setInterval("rotateImages()",2000)
 })

function rotateImages() {
     var curPhoto = $("#photoshow div.current");
     var nextPhoto = curPhoto.next();
     if (nextPhoto.length == 0) {
         nextPhoto = $("#photoshow div:first");
     }
     curPhoto.removeClass("current").addClass("previous");
     nextPhoto.css({
         opacity: 0.0
     }).addClass("current").animate({
         opacity: 1.0
     }, 1000, function () {
         curPhoto.removeClass("previous")
     });
}

This works, except when I wrap the if statement with {} it doesn't. I just wanted to understand the difference between the two and why it wouldn't work.

A: multiple lines need {}, otherwise the javascript interpreter doens't know it has more things to run.
try this, it has to work:
$(document).ready(function() {
    setInterval("rotateImages()", 2000);
})

function rotateImages() {
    var curPhoto = $("#photoshow div.current")
    var nxtPhoto = curPhoto.next();

    if (nxtPhoto.length == 0) {
        nxtPhoto = $("#photoshow div:first");
        curPhoto.removeClass('current').addClass('previous');
        nxtPhoto.css({
            opacity: 0.0
        }).addClass('current').animate({
            opacity: 1.0
        }, 1000, function() {
            curPhoto.removeClass('previous');
        });
    }
}

P.S. please also use semi-colons (;) to differentiate lines.

A: If an if-statement has only one statement that should be executed conditionally, you can leave away the braces. If more statements must be executed conditionally you have to embrace them as a block of code within braces. My tip: write always a pair of braces, esp. if you are beginning programming!


text:
Q: Having problem understanding the complex fourier series Here is my textbook, and I am wondering where that conjugate of $g(x)$ comes from? Why it isn't the integral of $f(x)g(x)$?
It seems to contradict this theorem, I am not quite sure

A: Why would it be the integral of $f(x)g(x)$? The equation $$\langle f,g\rangle=\int_{-L}^Lf(x)\bar g(x)dx$$ is a definition of the inner product. The reason is because one of the inner product axioms requires that $\langle f,g\rangle=\overline{\langle g,f\rangle}$ (what Wikipedia calls conjugate symmetry), which is not satisfied if we define the inner product to be the integral of $f(x)g(x)$.


text:
Q: When should extension methods be avoided? Before you start pointing me to duplicates just know that I have read nearly all the posts on SO about extension methods. I am just trying to play devil's advocate for a minute to consider the alternative to my working opinion.
Recently I was working on a project and a need came up for a method to be a base of an interface. So I suggested we write an extension method and it was shot down. Saying it added complexity and harder to debug.
I of course argued and got on SO to find all the wonderful posts that show the many reasons why to use extension methods. Not to forget that a lot of the .net framework uses them. We eventually did not use it as I was overruled by the team.
But then it got me thinking, are there times when an extension method could be used but shouldn't be?
I really couldn't think of any but thought I would post here and see if anyone could think of any other reasons why they shouldn't be used.

A: Any time you have a function which is "generally applicable" to an object of a certain type, regardless of its state, an extension method is a good choice.
For example, today I added two new extension methods to our codebase:
public static XElement ToXElement(this XmlElement element) { }

public static XmlElement ToXmlElement(this XElement element) { }

Both of these are, generally speaking, valid on the types they extend regardless of the state of the instance or where we are using it.
If your method does not meet that criteria, it should probably be moved to a helper method closer to the context where the particular case is always true or easily checked.
For example, a developer recently nominated this to be an extension method:
public static bool ParseYesNoBool(this string input) { }

There are two problems here: first, this will appear on all strings in the application, even though the number of strings which might ever be candidates for this case are very small. So we've broken the first rule, in that it is not useful regardless of state. Similarly, but second, the consumer of this functionality is limited to a single parser for one particular connector to an external system. So promoting implementation-specific functionality into the general-use namespace makes no sense. This was downgraded to a helper method in the parser.
As far as readability and debugging, that is just incorrect for a developer of any reasonable skill level.

A: In general if you control the source-code for the assembly and adding the method does not cause any breaking changes to existing code (which would have been the case if for example LINQ had not been implemented via extension methods) it is better to just add a normal method.

A: This discussion of the Framework Design Guildelines section on extension methods contains some good advice. I think the relevant portion for your scenario is:

To provide helper functionality relevant to every implementation of an interface, if said functionality can be written in terms of the core interface.

If your proposed usage did not pass that test then it should have been shot down.

A: I would say you should avoid them when "they do not make the intend of the code more clear".  Of course, whether or not some code (or codeing style) is "more clear" varying widely between people, so that's pretty much useless.  (I had one boss who said we shoudl avoid using interfaces because they made the code "too complex and hard to understand")

A:
Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type.

Any time you break the intent and design for the feature I would recommend reconsidering the use of an extension method.  I see a few situations when you don't want to use an Extension method:
1) Changing the Object Model to allow for an Extension method: The class you want to create an extension on is an abstract class.  This is going to require you either make each inherited class it's own version of the extension or remove abstract from the class.  Either way, you are changing the object model in order to use an extension method.
2) Forgetting the Decorator Pattern:  The number of extension methods you create for a class exceeds three.  I find it is easier to organize/communicate and maintain the domain/object model with decorated objects than with extended objects.  However, the opposite is also true:  If a decorated object has less than four methods, I find a lot of almost "empty" objects in my project.
3) Private functions: Private functions are meant to modify(create, delete, etc..) the object and extension methods are meant to use the type, much like a struct would.  If you find the extension is being assigned to another instance of the type then it probably should not be in an extension.


text:
Q: Laravel Snippets (v.1.13.0): Problems with relationships (One-To-Many, ...) Introduction
I'm using this Add-on for Visual Studio Code.
When creating relations with it. My views seem not working. I get an error in the browser (see below).

Laravel Snippets ID: onecentlin.laravel5-snippets Beschreibung:
Laravel snippets for Visual Studio Code  (Support Laravel 5 and above)
Version: 1.13.0 Herausgeber: Winnie Lin Link zum Visual Studio
Marketplace: https://marketplace.visualstudio.com/items?itemName=onecentlin.laravel5-snippets

My Model
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Person extends Model
{
    use HasFactory;
    protected $fillable = [];

    /**
     * Get the phone associated with the Person
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function phone(): HasOne
    {
        return $this->hasOne(Phone::class);
    }
}

Error shown by the browser, when calling the view

TypeError Return value of App\Models\Person::phone() must be an instance of
App\Models\HasOne, instance of
Illuminate\Database\Eloquent\Relations\HasOne returned (View:
C:\Users\MusaSaglam\componenttest\resources\views\test\index.blade.php)

My view
<x-layout>

        <x-nav.admin-nav/>

            <x-nav.admin-nav-top/>

People

            @foreach ($people as $person)

{{ $person->id }}

{{ $person->phone->number }}

            @endforeach

  </x-layout>

But if I remove : HasOne after public function phone() in my model. Everything works fine.
Two questions

*

*Why does the Snippet adds : HasOne. What is the benefit of this?

*Does not make it easier for users like me using the snippet without : HasOne?
I'm a beginner and I could not understand why the tutorials did not work.

A: You can refer to the type declaration https://www.php.net/manual/en/language.types.declarations.php

*

*Why does the Snippet add: HasOne. What is the benefit of this?

*

*It's the return type of method and it's standard so the VS code add-on is giving you the snippet(code) which follows the industry standards.

*Does not make it easier for users like me using the snippet without : HasOne? I'm a beginner and I could not understand why the tutorials did not work.

*

*This snippet will work don't worry about it. Just declare the HasOne before the class initialization like use Illuminate\Database\Eloquent\Relations\HasOne and it should work.

By the way type hinting is optional so a snippet will work if you just remove :HasOne(return type of method). which you already tried.


text:
Q: Android - Initiate Bluetooth Socket - connection timeout I need to connect to a bluetooth device which acts as a server. I know its UUID (at least the device's documentation contains it). However, I get an exception when I try to connect to it. The discovery part takes place successfully.
In the following, I cite the relevant code parts.
Here is the discovery. After I successfully found my device, I try to connect to it.
private val bluetoothAdapter: BluetoothAdapter? = BluetoothAdapter.getDefaultAdapter()
private val bluetoothReceiver = object : BroadcastReceiver() {
  override fun onReceive(context: Context, intent: Intent) {
    val action: String = intent.action
    when (action) {
      BluetoothDevice.ACTION_FOUND -> {
        val foundDevice: BluetoothDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE)
        Log.i("NAME", foundDevice.name)
        if (foundDevice.name.startsWith("RN487")) {
          bluetoothAdapter?.cancelDiscovery()
          device = foundDevice
          val connectThread = ConnectThread(device)
          connectThread.start()
        }
      }
    }
  }
}
private lateinit var device: BluetoothDevice

The ConnectThread class is here:
private inner class ConnectThread(device: BluetoothDevice) : Thread() {

  private val mSocket: BluetoothSocket? by lazy(LazyThreadSafetyMode.NONE) {
    device.createRfcommSocketToServiceRecord(UUID)
  }

  override fun run() {
    bluetoothAdapter?.cancelDiscovery()
    mSocket?.use { socket ->
      socket.connect()
      toast("Connected!")
    }
  }

  fun cancel() {
    try {
      mSocket?.close()
    } catch (e: IOException) {
      Log.e(TAG, "Could not close the client socket", e)
    }
  }
}

The UUID was given as
private val UUID = nameUUIDFromBytes("49535343-...".toByteArray())

Thanks for your time and expertise!

A: As one of my eagle-eyed colleagues pointed out, the bluetooth description begins with the "oldschool" version on the official android developers site. Later, the bluetooth low energy is described, which I need for my project.


text:
Q: Makefile 'missing separator' for ifneq I know there are other issues with similar titles, but they don't seem to hold the solution.
Heres my makefile:
# Compiler Command
CC = mpiCC
CFLAGS = -c -I./header

# collecting object file names
src = $(wildcard source/*.cpp)
src1 = $(src:.cpp=.o)

objects := $(src1:source/%=bin/%)

# Compile object files into binary
all : $(objects)
    $(CC) -o run $(objects)
ifneq($(n),)                         // <- error location , line 15
    mpirun -np $(n) run
endif

# Generate object files by compiling .cpp and .h files
bin/%.o : source/%.cpp
    $(CC) $(CFLAGS) $?
    mv *.o bin

# Clean Recipe
.PHONY : clean
clean :
    rm -rf all $(objects)

The goal of the ifneq is to have the binary run whenever it finishes compiling.
for example, a user runs the command:
make <- builds without running
make n=5 <- builds and runs on 5 processes
Whenever I use either of these, I get the error:
makefile:15: *** missing separator.  Stop.
I've used cat -e -t -v to verify everything is tabbed instead of spaced. according to (https://www.gnu.org/software/make/manual/make.html#Conditional-Example) this conditional should function.

A: @MadScientist solved it. You need to put a space in between ifneq and its argument. For example:
ifneq($(n),0) is invalid.
ifneq ($(n),0) is valid.


text:
Q: on a strange character sum Recently while studying cubic residues modulo a prime $p$ with $p\equiv1\pmod 3$, I met the following character sum:
$$\sum_{0\le x\le p-1}\left(\frac{x}{p}\right)\left(\frac{x+1}{p}\right)\left(\frac{x+\omega}{p}\right)\left(\frac{x+\omega^2}{p}\right)\chi_p(x^3),$$
where $\omega\in\mathbb{Z}$ with $\omega$ mod $p$ a primitive cubic root of unity in $\mathbb{Z}/p\mathbb{Z}$, $\chi_p$ is a generator of the group of all multiplicative characters over $\mathbb{Z}/p\mathbb{Z}$, and $(\frac{\cdot}{p})$ is the Legendre symbol.
Are there any references concerning the character sums of this type? Your comments are welcome.

A: Your sum is expressible as a linear combination of Jacobi sums. More precisely, let us notice that
$$
\left(\frac{x^3}{p}\right)=\left(\frac{x}{p}\right)
$$
for all $x$ and also that $(x+1)(x+\omega)(x+\omega^2)=x^3+1$. So, the sum $S$ in question is equal to
$$
S=\sum_{0\leq x\leq p-1}\left(\frac{x^3}{p}\right)\left(\frac{x^3+1}{p}\right)\chi_p(x^3).
$$
Now, let $\psi$ be one of two non-principal characters modulo $p$ with $\psi^3=\chi_0$. It is easy to see that
$$
\#\{x:x^3\equiv y \pmod p\}=1+\psi(y)+\psi^2(y)
$$
(i.e. it is $1$ when $y=0$, $3$ when $y$ is a nonzero cubic residue and $0$ if it is a cubic non-residue) Arranging the sum according to the value of $x^3$, we obtain
$$
S=\sum_{0\leq y\leq p-1}\left(\frac{y}{p}\right)\left(\frac{y+1}{p}\right)\chi_p(y)(1+\psi(y)+\psi^2(y)).
$$
To transform this into Jacobi sums, let us make a substitution $y=-z$ and notice that $\psi(-1)=1$, $\chi_p(-1)=-1$ and $\left(\frac{-1}{p}\right)=(-1)^{(p-1)/2}:=\varepsilon_p$. We get
$$
S=-\varepsilon_p\sum_z \left(\frac{z}{p}\right)\left(\frac{1-z}{p}\right)\chi_p(z)(1+\psi(z)+\psi^2(z)).
$$
Next, if $\eta_1,\eta_2$ are characters modulo $p$, then the Jacobi sum $J(\eta_1,\eta_2)$ is given by
$$
J(\eta_1,\eta_2)=\sum_z \eta_1(z)\eta_2(1-z).
$$
For instance, we get
$$
S=-\varepsilon_p(J(\chi_1,L_p)+J(\chi_2,L_p)+J(\chi_3,L_p)),
$$
where $L_p$ is the Legendre symbol and $\chi_i=\psi^iL_p \chi_p$. It is also known that if $\eta_1\eta_2$ is non-principal, then
$$
J(\eta_1,\eta_2)=\frac{g(\eta_1)g(\eta_2)}{g(\eta_1\eta_2)},
$$
(here $g$ is the Gauss sum $g(\eta)=\sum_n \eta(n)e^{2\pi i n/p}$)
so in this case we obtain
$$
S=-\varepsilon_p g(L_p)\sum_i \frac{g(\chi_i)}{g(\psi^i\chi_p)}
$$
and as a consequence of the identity $|g(\chi)|=\sqrt p$ for non-principal $\chi$, we  prove Weil-like estimate
$$
|S|\leq 3\sqrt p.
$$


text:
Q: Is it possible to create an instrumental version of an mp3 file in Mathematica? I'm aware that it's possible to use a program like Audacity to do this and that it's most likely easier, but I'd like to know how to make instrumental versions of songs in the mp3 format using Mathematica.
I'm starting with practically no knowledge of sound data and therefore have no starting point other than importing the file.
Is this possible and how might I go about it?


text:
Q: Framework similar to Prism for Knockout js Microsoft made Prism framework for Silverlight and WPF. It looks great with its RegionManager and other stuff.
Is there any similar framework for Knockout?
Thanks.

A: Rob Eisenberg, the developer of Caliburn.Micro (IMO the best MVVM framework available for XAML apps) is developing Durandal which uses Knockout.
An early version of the source is here, and you can read a little bit about the design concept here.


text:
Q: spring hibernate did not get the value of parameter I try to make an API call with the post method via postman to my spring boot application.
Here is the input:
{
  "username": "name",
  "password": "1234",
  "age": 12,
  "salary": 5000,
  "role": 1
}

Here is the code in the controller:
@RequestMapping(value = "/signup", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<?> saveUser(@RequestBody UserDto user) {
        try {
            System.out.println(user.getUsername()); // => name
            System.out.println(user.getPassword()); // => 1234
            System.out.println(user.getSalary()); // => 5000
            System.out.println(user.getRole()); // => 1
            System.out.println(user.getAge()); // => 12
            userService.save(user);
            return ResponseEntity.ok().body("insert done");
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }

Here is my User.java
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column
private String username;
@Column
@JsonIgnore
private String password;
@Column
private long salary;
@Column
private int age;
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "role_id")
private Role role;
// getters and setters

Here is my Role.java
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@Column(name = "role_name", nullable = false)
private String roleName;
// getters and setters

Here is my UserDto.java
private String username;
private String password;
private int age;
private long salary;
private int role;
// getters and setters

Here is my RoleDto.java
private Long id;
private String roleName;
// getters and setters

Problem: it throws error 'Column 'role_id' cannot be null'
Here is in the userServiceImpl:
Below line (BeanUtils) is refer to here.
    @Override
    public User save(UserDto user) throws Exception {
        User newUser = new User();
        BeanUtils.copyProperties(user, newUser, "password");
        newUser.setPassword(bcryptEncoder.encode(user.getPassword()));
        try {
            userDao.save(newUser);
        } catch (Exception e) {
            throw new Exception(e);
            // this throw "Column role_id cannot be null"
        }
        return newUser;
    }

But, if I use below code, the setRole method is not applicable since I define user.getRole() in the DTO as int but define newUser.setRole() in the User entity as Role. But if I change the setRole in User entity as int, then, how I can tell the spring about the ManyToOne relation between User and Role?
@Override
public User save(UserDto user) throws Exception {
    User newUser = new User();
    newUser.setUsername(user.getUsername());
    newUser.setPassword(bcryptEncoder.encode(user.getPassword()));
    newUser.setAge(user.getAge());
    newUser.setSalary(user.getSalary());
    newUser.setRole(user.getRole()); // here is the problem
    try {
        userDao.save(newUser);
    } catch (Exception e) {
        throw new Exception(e);
    }
    return newUser;
}

Note: I think I just want to make the input parameter for role to be just an integer as provided above.

A: Since you are receiving 1 for the role in your request you should do something like:
Role role = new Role();
role.setId(user.getRole());
role.setRoleName("some name");
newUser.setRole(role);

In the first part of the code the problem may be here BeanUtils.copyProperties(user, newUser, "password");, if you try to debug or print newUser after that line you will see that BeanUtils was not able to populate correctly all the fields of your newUser object. And this is because in the destination (newUser) the field role is of type Role, while in the source (user) the type of that field is just int.


text:
Q: google drive sample code is showing jackson2 package does not exist java compile time error I've configured GDrive API from following tutorial to ubuntu cloud hosting.
https://developers.google.com/drive/api/v3/quickstart/java
configurations are in following screenshot.

It's showing " package com.google.api.client.json.jackson2 does not exist" error

though i tried to add that jar file to lib directory but that didn't fix the issue.

with that i've also added following files

please advice, thanks


text:
Q: How to connect react web part to azure sql database? Any advice about how to connect a spfx web part using the react template to an azure sql database.
But can't seem to find a clear example. I'd be looking to bind controls e.g. Combo boxes  to a sql azure sql table
Any help will be greatly appreciated.

A: You need to remember that anything that runs client side is able to be sniffed out by the end user, so any front end code connecting to a database would necessarily expose the connection details back to the end user - the keys to the kingdom, if you will. This is an egregious security risk.
Best practice is to deploy a custom secured web service, and have the web part call that instead.
There's a lot of ways to achieve this, but very common is to use Azure Functions and/or ASP.Net secured with Azure Active Directory: https://docs.microsoft.com/en-us/sharepoint/dev/spfx/web-parts/guidance/connect-to-api-secured-with-aad


text:
Q: Set environment variable in deployment config for container if variable is not empty I am working with an existing Openshift deployment config where I can only change small parts.
The environment variables are set like this in the container config:
env:
- name: DATABASE_NAME
  valueFrom:
    configMapKeyRef:
      key: DATABASE_NAME
      name: ${DATABASE_CONFIG_MAP}

My problem now is that the config map, which is created in some other step, may not contain the variable. Is it possible to make this environment variable optional in the container DC (or even better, not set the environment variable if it is an empty string)?
Currently, the deployment will fail, mentioning that the key is not present in the config map.
I know that I could use envFrom, but this is unfortunately not possible in this specific deployment config.
Thanks!