text:
Q: make time function with Interpolation of discrete time data and use this function in Solve and Plot I have value of a and b in terms of time for discrete value of time. How can i make a time function with interpolation? after that and generate a[t_]:=Interpolation of some point in terms of time... and b[t_]:=... i need to put x[t] and y[t] from solve to them that if i type x[6.5] and press shift+enter i can give correct value of x[t] in t=6.5s . after determine x[t] and y[t] i want to plot them in function of time. My input is a(t=1):2, a(t=2):4,...b(t=1):7,b(t=2):5,... and my favorite out put is x[t],y[t] when time is in interval of (t=1,t=10)
my sample code that didn't work is:
ClearAll[a, b, x, y]
a[t_] := Interpolation[{1, 2}, {2, 4}, {3, 6}, {4, 7}, {5, 6}, {6, 5}, {7, 3}, {8, 2}, {9, 1}, {10, 0.5}];
b[t_] := Interpolation[{1, 7}, {2, 5}, {3, 3}, {4, 1}, {5, 3}, {6, 4}, {7, 5}, {8, 5}, {9, 3}, {10, 1}];
Solve[a[t]* x[t] + y[t] == 7 && b[t]* x[t] - y[t] == 1, {x[t], y[t]}]
a[6.5]
x[6.5]
Plot[x[t], y[t], {t, 1, 10}]

All of my data is between t=1s and t=10s and i need x[t],y[t] and plot of them in this interval of time.

A: Differentiate and solve this function equation with NDSolve.
Use spline interpolation, because it can be differentiated.
ClearAll[a, b, x, y]
ptsa = {{1, 2}, {2, 4}, {3, 6}, {4, 7}, {5, 6}, {6, 5}, {7, 3}, {8,
2}, {9, 1}, {10, 0.5}};
a = Interpolation[ptsa, InterpolationOrder -> 3, Method -> "Spline"];
ptsb = {{1, 7}, {2, 5}, {3, 3}, {4, 1}, {5, 3}, {6, 4}, {7, 5}, {8,
5}, {9, 3}, {10, 1}};
b = Interpolation[ptsb, InterpolationOrder -> 3, Method -> "Spline"];

Plot[a[t], {t, 1, 10}, Epilog -> Point@ptsa]

Plot[b[t], {t, 1, 10}, Epilog -> Point@ptsb]

Not shown here.
Find starting values.
sol = Solve[
  a[1]*x[1] + y[1] == 7 && b[1]*x[1] - y[1] == 1, {x[1], y[1]}]

(*   {{x[1] -> 0.888889, y[1] -> 5.22222}}   *)

ndsol = NDSolve[
  D[a[t]*x[t] + y[t] == 7 && b[t]*x[t] - y[t] == 1, t] &&
  x[1] == (x[1] /. sol) && y[1] == (y[1] /. sol), {x, y}, {t, 1, 10}]

Plot[Evaluate[{x[t], y[t]} /. ndsol], {t, 1, 10},
   PlotStyle -> {Blue, Red}]

Proof the result
Plot[Evaluate[{a[t]*x[t] + y[t], b[t]*x[t] - y[t]} /. ndsol], {t, 1,
   10}, PlotStyle -> {Blue, Red}]


text:
Q: Can I use a persistent (Oracle) recordset in access project? Obviously you cannot set the recordset property of a form in an Access Project with an Oracle-based recordset, but is there a way to show or select these records in an Access form?

A: *

*Add a DSN entry for the Oracle database in the ODBC control panel

*In Access, create a new Query, define it as Pass-Through, type whatever you want in the query text otherwise you can't save it (SELECT * is ok). This pass-trough query will be used to retrieve data from Oracle and show them in your form, and you will define it's SQL on-the-fly in the VBA code

*In your form code, do this:

' Add this local variable to your form
Private OracleQD As QueryDef

' Do the following in the Load event of your form :
Set OracleQD = CurrentDb.QueryDefs("Your_Previously_Created_Query_name")
OracleQD.Connect = "ODBC;DSN=your_ODBC_entry_name;UID=your_Oracle_User;Pwd=Your_Oracle_Password"
OracleQD.ODBCTimeout = 600  ' Set to anything you want

' Do this everytime you want to retrieve data from Oracle
OracleQD.SQL = "SELECT * FROM whatever_table_you_want"
Set Form_Your_form_name.Recordset = OracleQD.OpenRecordset(dbOpenSnapshot)

A: I solved the problem by creating a table on the back-end server, looping through the oracle-based recordset in VBA and then creating new records in the (sql server) table by using a stored procedure which takes fields from the oracle-based recordset as parameters and inserts these values as a record in the sql server table.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Javascript: function and its argument I've a problem with my function and its arguments... this is the code:
function elab(){

   var up = arguments[0];
   var id = arguments[1];
   len = arguments.length - 3;

   for(var a = 1; a <= 10; a++){

      arg = (arguments[2] + a); // id tag html : [nome][num]
      document.getElementById(arg).style.display = "block";
   }

   for (var i = 3; i < len; i++) {

      alert('test1');
      document.getElementById(arguments[i]).style.display = "none";
      alert('test2');
   }

   change_price(up, id);
}

The script hangs at the second cycle: it prints 'test1' but not 'test2'.
Where is the error?
thx all ;)

A: Note that this advice should be used for all things unsure:
for (var i = 3; i < len; i++) {
    var node = document.getElementById(arguments[i]);

    if (node) {
        node.style.display = "none"; // block
    }
}

In other words, always test if an element can be found if you're not 100% sure. To be even more pedantic:
for (var i = 3; i < len; i++) {
    var node = document.getElementById(arguments[i]);

    if (!node) {
        throw "Element " + arguments[i] + " not found.";
    }
    node.style.display = "none"; // block
}


text:
Q: Select n rows without LIMIT mysql I have a problem. I would like to get only 300 rows from table without touching LIMIT. I need LIMIT for pagination. Is this possible in MySQL?
My current query:
SELECT a.title, a.askprice, a.picture, a.description, a.userid, a.id
    FROM mm_ads AS a WHERE a.category = 227 AND a.status = 1
    ORDER BY id DESC LIMIT 40,20

Edit:
Simple explanation: I need to get from a system last 300 ads but I need to keep pagination, because I don't want to have 300 rows listed in one page..

A: SELECT *
FROM (
   SELECT a.title, a.askprice, a.picture, a.description, a.userid, a.id
   FROM mm_ads AS a
   WHERE a.category = 227 AND a.status = 1
   ORDER BY id DESC
   LIMIT 300
) t
LIMIT 40,20

If the purpose is to speed up the query, then you can create a composite index:
ALTER TABLE `mm_ads`
    ADD INDEX `mm_ads_index` (`category` ASC, `status` ASC, `id` DESC);

A: Use SQL_CALC_FOUND_ROWS after your SELECT:
SELECT SQL_CALC_FOUND_ROWS *

EDIT:
And in php, run this row to get the amount of rows:
list($int_rows) = mysql_fetch_row(mysql_query("SELECT FOUND_ROWS()"));

This will go through all the rows, get the total amount, but not fetch all the rows.
EDIT2:
May have misunderstod your question, however this is a common solution for pagination.

A: Simple solution is
Fits count only amount of result you need and use it in your pagination
then use limit in your query to load data on each page
SELECT a.title, a.askprice, a.picture, a.description, a.userid, a.id
    FROM mm_ads AS a WHERE a.category = 227 AND a.status = 1
    ORDER BY id DESC LIMIT 40,20
it dosen't matter how large your data base is it only gives you the 20 results (although it search for full database)

A: One more thing that you can do is just fetch all the 300 rows from database and save it in an array and then paginate the array indexes


text:
Q: How do I make a link stay a color when on the current page? I'm not sure if this is done with javascript or css but if there is anyone out there who can be of any help....please, I sincerely appreciate it! Thanks in advance

A: You do this by applying CSS to the different a tag states.  This resource should be helpful:
http://www.echoecho.com/csslinks.htm


text:
Q: Wifi connected but no internet on Ubuntu 18.04 I have a Dell laptop with Ubuntu 18.04. Despite being connected to the wifi, there is no internet. If I try to ping a server, I get no answer.
I googled extensively for a solution, without finding anything that works for me. I know that similar questions have been asked several times already, but nothing worked.
Important notes:

*

*My laptop works just fine with other WiFis

*This WiFi works just fine with other devices

*I have never had this problem before

*Turning off and back on WiFi on my laptop doesn't work

*Forgetting network doesn't work

*Restarting my laptop doesn't work

*Restarting modem doesn't work

Update:
I still have this problem, it appears randomly.
If i run nmcli when connected to the WiFi I get this:
nmcli
wlp3s0: connected to CenturyLink2002
        "Intel Centrino Wireless-N 1000 [Condor Peak] (Centrino Wireless-N 1000 BGN)"
        wifi (iwlwifi), 74:E5:0B:B0:9E:B6, hw, mtu 1500
        ip4 default
        inet4 192.168.0.46/24
        route4 0.0.0.0/0
        route4 192.168.0.0/24
        route4 169.254.0.0/16
        inet6 fe80::695c:c596:311c:929f/64
        route6 ff00::/8
        route6 fe80::/64
        route6 fe80::/64

enp10s0: unavailable
        "Realtek RTL8111/8168/8411 PCI Express Gigabit Ethernet Controller"
        ethernet (r8169), 84:8F:69:C7:AD:32, hw, mtu 1500

lo: unmanaged
        "lo"
        loopback (unknown), 00:00:00:00:00:00, sw, mtu 65536

DNS configuration:
        servers: 192.168.0.1 205.171.3.25
        domains: Home
        interface: wlp3s0

Use "nmcli device show" to get complete information about known devices and
"nmcli connection show" to get an overview on active connection profiles.

Consult nmcli(1) and nmcli-examples(5) manual pages for complete usage details.


text:
Q: How to fix rotated image from iOS camera in Codename One? I have written a code to open gallery and choose image file in CodenameOne. On iOS it also allows to capture image. When I capture a photo on iOS, the photo is rotated by 90°. When I pick photo from gallery it is not rotated. How to fix that 90° rotation? Here is my code for opening gallery:
Display.getInstance().openGallery((evt) -> {
        if (evt != null && evt.getSource() != null) {
            String filePath = (String) evt.getSource();
            Image img = null;
            try {
                img = Image.createImage(filePath);
            } catch (IOException e) {
            }
            if (img != null) {
                img = img.scaledLargerRatio(IMAGE_WIDTH_FOR_UPLOAD, IMAGE_HEIGHT_FOR_UPLOAD);
                ImageHelper.saveToFileSystem("image" + ".jpg", img, null, null);
                base64Img = (String) ImageHelper.loadBase64FromFileSystem("image" + ".jpg");
                browser.execute("document.getElementById(\"" + QR_PHOTO_UPLOAD_IMG_ID + "\").setAttribute('src', '" + BASE64_PREFIX + base64Img + "');"
                        + " document.getElementById(\"" + QR_PHOTO_UPLOAD_INPUT_ID + "\").setAttribute('base64', '" + BASE64_PREFIX + base64Img + "');"
                        + "");
            }
        }
        photoGalleryOpened = false;
    }, Display.GALLERY_IMAGE);

Here is code for Image saving to file system:
public static boolean saveToFileSystem(String path, Image capturedImage, String format, Float quality) {
    if (format == null) {
        format = ImageIO.FORMAT_JPEG;
    }
    if (quality == null) {
        quality = 1f;
    }
    OutputStream os = null;
    try {
        String pathToBeStored = path.startsWith(APPHOMEPATH)?  path : (APPHOMEPATH + path);
        os = FileSystemStorage.getInstance().openOutputStream(pathToBeStored);
        ImageIO.getImageIO().save(capturedImage, os, format, quality);
        os.close();
    } catch (Exception e) {
        Log.e(e);
        try {
            if (os != null) {
                os.close();
            }
        } catch (IOException ex) {
            Log.e(ex);
        }
        return false;
    } finally {
        try {
            if (os != null) {
                os.close();
            }
        } catch (IOException ex) {
            Log.p(ex.getMessage());
        }
    }

    return true;
}

Here is code for getting base64 string from image file:
public static Object loadBase64FromFileSystem(String path) {
        String ret = "";
        try {
            Image image = loadFromFileSystem(path);
            if (image == null) {
                throw new IOException("File not found (" + APPHOMEPATH + path + ")");
            }
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.getImageIO().save(image, baos, ImageIO.FORMAT_JPEG, 1);
            byte[] bytes = baos.toByteArray();
            ret = Base64.encodeNoNewline(bytes);
        } catch (Exception ex) {
            Log.e(ex);
        }
        return ret;
    }

public static Image loadFromFileSystem(String path) {
       try {
           File f = new File(APPHOMEPATH + path);
           if(f.exists()){
               Log.p("Image exists: " + f.exists());
               Image img = Image.createImage(f.getPath());
               return img;
           }else{
                Log.p("Image doesn't exist");
               return null;
           }
       } catch (Exception ex) {
           Log.e(ex);
       }
       Log.p("Image doesn't exist");
       return null;
   }

A: Mobile OS's often take a photo with one orientation and then just mark it as rotated in a tag e.g. photos are always landscape but when you take a portrait mode photo it's marked as rotated by 90 degrees.
This works fine as most apps read the tags and implicitly rotate that photo after loading. Some apps don't and the native image reading code doesn't do that on mobile OSs. We need to explicitly parse the tags and do the rotation. We do that for capture logic but we don't do that generically for image loading.
The problem is that rotating the image is very expensive and doing it for every image load would be expensive (but might be what we have to do in this case). Right now the only workaround I can think about is manually parsing the image tags which would be a bit painful.


text:
Q: How to make sub queries with success with multiple parameter I have two tables PA_Ledger and PA_Trans. I just wrote a stored procedure that filters with date, inner join, group by PA_Ledger.Name and sorts by that name.
I have a stored procedure that finds records with join,group by and date filter as like :
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- =============================================
-- Author:      Shalin Gajjar
-- Create date: 27/10/221
-- Description: get all report data
-- =============================================
--exec [dbo].[PA_Report_IndexPagingData] 100,1,'Oct  28 2021 12:00AM','Oct  30 2021 12:00AM','Order By Name Asc',''
ALTER PROCEDURE [dbo].[PA_Report_IndexPagingData]
    --10,1,'Order By Name Asc','',3
    -- Add the parameters for the stored procedure here
    @PageSize int,
    @PageIndex int,
    @startdt1 nvarchar(50),
    @startdt2 nvarchar(50),
    @Sort nvarchar(50),
    @Search nvarchar(max)
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @qry nvarchar(max)
    DECLARE @TotalRecords nvarchar(max)

    SET @TotalRecords=' ( select count(*) from PA_Ledger pl join PA_Trans pt on (pl.LedgerId = pt.Ledgeridcr or pl.LedgerId = pt.Ledgeriddr )
                         where isnull(Isdeleted,0) = 0 and pl.Name like ''%'+@Search+'%''
                          and (pt.TransOn >= '''+convert(nvarchar,CONVERT(DATETIME,@startdt1,110))+''' or convert(date,'''+convert(nvarchar,CONVERT(DATETIME,@startdt1,110))+''') = convert(date,''01/01/1900'') )
                         and (pt.TransOn <='''+convert(nvarchar,CONVERT(DATETIME,@startdt2,110))+''' or convert(date,'''+convert(nvarchar,CONVERT(DATETIME,@startdt2,110))+''') = convert(date,''01/01/1900'') )
                         group by pl.Name)'

    set @qry = ' select  *, '+@TotalRecords+' As TotalRecords,
                        (select row_number() over(order by pl.name) as RowNo,pl.Name,sum(pt.Amount) as Amount
                         from PA_Ledger pl
                         join PA_Trans pt on (pl.LedgerId = pt.Ledgeridcr or pl.LedgerId = pt.Ledgeriddr)
                         and pl.Name like ''%'+@Search+'%'' and
                         isnull(Isdeleted,0) = 0
                         and (pt.TransOn >= '''+convert(nvarchar,CONVERT(DATETIME,@startdt1,110))+''' or convert(date,'''+convert(nvarchar,CONVERT(DATETIME,@startdt1,110))+''') = convert(date,''01/01/1900'') )
                         and (pt.TransOn <='''+convert(nvarchar,CONVERT(DATETIME,@startdt2,110))+''' or convert(date,'''+convert(nvarchar,CONVERT(DATETIME,@startdt2,110))+''') = convert(date,''01/01/1900'') )
                         group by Name
                        ) i where RowNo between  '+Convert(nvarchar(10),( (@pageIndex-1) * @pageSize  ) + 1 )+ ' and '  + Convert(varchar(10),( (@pageIndex-1) * @pageSize  ) + @pageSize) + ' '+ @Sort

    print(@qry)
    exec(@qry+@TotalRecords)

END

When I execute then generate error like :
( select count(*) from PA_Ledger pl join PA_Trans pt on (pl.LedgerId = pt.Ledgeridcr or pl.LedgerId = pt.Ledgeriddr )
                         where isnull(Isdeleted,0) = 0 and pl.Name like '%%'
                          and (pt.TransOn >= 'Oct 28 2021 12:00AM' or convert(date,'Oct 28 2021 12:00AM') = convert(date,'01/01/1900') )
                         and (pt.TransOn <='Oct 30 2021 12:00AM' or convert(date,'Oct 30 2021 12:00AM') = convert(date,'01/01/1900') )
                         group by pl.Name)
 select  *,  ( select count(*) from PA_Ledger pl join PA_Trans pt on (pl.LedgerId = pt.Ledgeridcr or pl.LedgerId = pt.Ledgeriddr )
                         where isnull(Isdeleted,0) = 0 and pl.Name like '%%'
                          and (pt.TransOn >= 'Oct 28 2021 12:00AM' or convert(date,'Oct 28 2021 12:00AM') = convert(date,'01/01/1900') )
                         and (pt.TransOn <='Oct 30 2021 12:00AM' or convert(date,'Oct 30 2021 12:00AM') = convert(date,'01/01/1900') )
                         group by pl.Name) As TotalRecords,

                        (select row_number() over(order by pl.name) as RowNo,pl.Name,sum(pt.Amount) as Amount
                         from PA_Ledger pl
                         join PA_Trans pt on (pl.LedgerId = pt.Ledgeridcr or pl.LedgerId = pt.Ledgeriddr)
                         and pl.Name like '%%' and
                         isnull(Isdeleted,0) = 0
                         and (pt.TransOn >= 'Oct 28 2021 12:00AM' or convert(date,'Oct 28 2021 12:00AM') = convert(date,'01/01/1900') )
                         and (pt.TransOn <='Oct 30 2021 12:00AM' or convert(date,'Oct 30 2021 12:00AM') = convert(date,'01/01/1900') )
                         group by Name
                        ) i where RowNo between  1 and 100 Order By Name Asc

Msg 207, Level 16, State 1, Line 27
Invalid column name 'RowNo'.
Msg 207, Level 16, State 1, Line 27
Invalid column name 'RowNo'.
Msg 263, Level 16, State 1, Line 13
Must specify table to select from.
Msg 116, Level 16, State 1, Line 27
Only one expression can be specified in the select list when the subquery is not introduced with EXISTS.
Msg 207, Level 16, State 1, Line 27
Invalid column name 'Name'.

What is the better solution for this stored procedure? Please help me to get out of this situation.

A: Well, you haven't given us create/insert queries, so we have to go blind. Try changing the first line of your set @qry:
set @qry = ' select  *, '+@TotalRecords+' As TotalRecords,

to this:
set @qry = ' select  *, '+@TotalRecords+' As TotalRecords, i.* from

This will cause your parenthesis (...) i to be a derived table instead of a single value, and we SELECT all its elements , i.*
Also, change @totalrecords to this version with alternate aliases:
set @TotalRecords=' ( select count(*) from PA_Ledger pl2 join PA_Trans pt2 on (pl2.LedgerId = pt2.Ledgeridcr or pl2.LedgerId = pt2.Ledgeriddr )
                         where isnull(Isdeleted,0) = 0 and pl2.Name like ''%'+@Search+'%''
                          and (pt2.TransOn >= '''+convert(nvarchar,CONVERT(DATETIME,@startdt1,110))+''' or convert(date,'''+convert(nvarchar,CONVERT(DATETIME,@startdt1,110))+''') = convert(date,''01/01/1900'') )
                         and (pt2.TransOn <='''+convert(nvarchar,CONVERT(DATETIME,@startdt2,110))+''' or convert(date,'''+convert(nvarchar,CONVERT(DATETIME,@startdt2,110))+''') = convert(date,''01/01/1900'') )
                         group by pl2.Name)'


text:
Q: RSS Feed from Site to Facebook Fanpage I have a WordPress based site and a Facebook fanpage. I want to include my site RSS feed to the page, in the FBML tab. I tried some JSs, but those didn't work. How can I do this? I want my RSS shows up in a Static FBML tab, not in the note.
Thanks in advance.

A: This is actually pretty straightforward to do--what you'll need to do is create a new app for the fanpage and set it to be a Page Tab. From there, you can have it just load a page on your server as an iframe.
Granted, you'll need to set up something like MagpieRSS in order to be read off that page, but it's pretty simple if you're not looking to push wall posts.

A: I'm doing this in PHP:
     $doc = new DOMDocument();
      $doc->load('https://www.mywebsite.com/rss.php');

      foreach ($doc->getElementsByTagName('item') as $node) {
               /*
do things with the item
           */
        }


text:
Q: Java - Clip and Looping Sound I finally got my sound clip to work in my java application.
This is picky, but there's a minor pause between each sound loop. Is there any way to "merge" the two loops slightly so the sound seems continuous?

A: The short answer is, you can do it with two copies of the cue being played back alternately. Probably not what you wanted to hear, because you have to write the code to manage this yourself rather than, say, rely on a parameter that could be passed to the built-in looping functionality.
The implementation I came up with and am currently using has as its core algorithm, this:
while loop periodically calls a runnable that plays the cue (or its twin, determined by a boolean switch) on its own thread, and has a sleep increment set just a bit below the length of the duration of the WAV file.
It helps to have the cue itself start and end in silence, but ramp quickly at the overlap point, as one might do a splice with Sound Editing software. If the cue doesn't start/end in silence, there is a chance of having clicks when the sound starts or stops.

A: See Clip.setLoopPoints(startFrame,endFrame).


text:
Q: Is my thinking about OOP persistence-separation right? I am reading about OOP and trying to apply it to Rails (inspired by Uncle Bob's Ruby conf talk), and I was wondering, is it right to access the repository from a "logic" model in the way I do below:
class Product
  ...
  def pick_a_random_product
    repository.pick_a_random_product
  end
  ...
end

Does this qualify as "logic being separated from persistence" ? Is it O.K to be using the repository as extensively as may be needed, inside a "domain"/"logic" model?
repository is meant to be some class that does the real job of fetching something from the database.

A: It works but if pick_a_random_product is use for different class means that
Suppose you have class xyz
Class Xyz
  ...
  def pick_a_random_product
    Product.pick_a_random_product
    # Xyz.pick_a_random_product you can't use this.
  end
  ...
end

you have class Product
class Product
  ...
  def pick_a_random_product
    Xyz.pick_a_random_product
  end
  ...
end


text:
Q: how to make array combination with unique value and limited character? i have a array like this
['1', '2', '3', '4']; I want to make result of the array like this
['123', '124', '132', '134', '142', '143', '213' ,' 214', '231', '234', '241', '243', '312', '314', '321', '324', '341', '342', '412', '413', '421', '423', '431', '423']
this is my code
<?php
ini_set('memory_limit', '-1');

function permute($arg) {
    $array = is_string($arg) ? str_split($arg) : $arg;
    if(1 === count($array))
        return $array;
    $result = array();
    foreach($array as $key => $item)
        foreach(permute(array_diff_key($array, array($key => $item))) as $p)
            $result[] = $item . $p;
    return $result;
}
$array = array('1','2','3','4');
var_dump(permute($array));
 ?>

the result of my code is
['1234', '1243', '1324', '1342', '1423', '1432', '2134', '2314', '2413' ......... ]

i want to limit character of result just 3 character. how to make it?

A: <?php
function combination($chars, $size, $combinations = array()) {

    if (empty($combinations)) {
        $combinations = $chars;
    }

    # we're done if we're at size 1
    if ($size == 1) {
        return $combinations;
    }
    $new_combinations = array();
    foreach ($combinations as $combination) {
        foreach ($chars as $char) {
            $new_combinations[] = $combination . $char;
        }
    }
    return combination($chars, $size - 1, $new_combinations);

}

function permute($array, $numberOfChar)
{
  $output = combination($array, $numberOfChar);
  $result = array_values(array_filter($output,function($str){
    for($i = 0; $i < strlen($str); $i++)
    {
        for($j = $i + 1; $j < strlen($str); $j++)
        {
            if($str[$i] == $str[$j])
            {
                return false;
            }
        }
    }
    return true;
  }));
  return $result;
}

$array = array(1,2,3,4);
print_r(permute($array, 3)); // pass an array an num of permute char


text:
Q: Can't assign an image to a Nullable ImageView How can I set an image to ImageView?
The idea of my app is to show the different type of RecyclerView's view holder according to the data class in a RecyclerView. Data classes look like this:
abstract class Thing(open val title: String, open val body: String, open val pic: ImageView?)

data class Movie(override val title: String, override val body: String): Thing(title, body, pic = null)
data class Book(override val title: String, override val body: String): Thing(title, body, pic = null)
data class Game(override val title: String, override val body: String, override val pic: ImageView?): Thing(title, body, pic)

Also, I have a MainFragment where I am adding the data manually. Here I am trying to give the name and the description of a game, and also to set the particular image to a game_pic ImageView:
class MainFragment: Fragment() {
private val mMoviesBooksGames = listOf(
  Game("Dixit", "Give the perfect clue so most (not all) players guess the right surreal image card.", game_pic.setImageResource(R.drawable.alias) as ImageView)
  }
}

How I declare the GameViewHolder where my game_pic is:
class GameViewHolder(inflater: LayoutInflater, parent: ViewGroup) :
    ThingViewHolder(inflater.inflate(R.layout.game_list_item, parent, false)) {
    private var mGameTitleView: TextView? = null
    private var mGameDescriptionView: TextView? = null
    private var mGamePicImageView: ImageView? = null

    init {
        mGameTitleView = itemView.findViewById(R.id.game_title)
        mGameDescriptionView = itemView.findViewById(R.id.game_description)
        mGamePicImageView = itemView.findViewById(R.id.game_pic)
    }

    override fun bind(dataToBind: Thing) {
        mGameTitleView?.text = ">> Book ${dataToBind.title}"
        mGameDescriptionView?.text = dataToBind.body
        mGamePicImageView = dataToBind.pic
    }
}

An error that I get after using game_pic.setImageResource(R.drawable.alias) as ImageView is:
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.recyclerview, PID: 822
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.recyclerview/com.example.recyclerview.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageResource(int)' on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3555)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3707)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2220)
        at android.os.Handler.dispatchMessage(Handler.java:107)
        at android.os.Looper.loop(Looper.java:237)
        at android.app.ActivityThread.main(ActivityThread.java:8019)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1100)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageResource(int)' on a null object reference
        at com.example.recyclerview.MainFragment.<init>(MainFragment.kt:33)
        at com.example.recyclerview.MainFragment$Companion.newInstance(MainFragment.kt:67)
        at com.example.recyclerview.MainActivity.createFragment(MainActivity.kt:4)
        at com.example.recyclerview.MainActivity.createFragment(MainActivity.kt:3)
        at com.example.recyclerview.SingleFragmentActivity.onCreate(SingleFragmentActivity.kt:25)
        at android.app.Activity.performCreate(Activity.java:7957)
        at android.app.Activity.performCreate(Activity.java:7946)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1307)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3530)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3707)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2220)
        at android.os.Handler.dispatchMessage(Handler.java:107)
        at android.os.Looper.loop(Looper.java:237)
        at android.app.ActivityThread.main(ActivityThread.java:8019)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1100)
I/Process: Sending signal. PID: 822 SIG: 9

A: The error says that your game_pic variable is null.
One workaround I can suggest without seeing your code:
private val mMoviesBooksGames = listOf( Game(
        "Dixit",
        "Give the perfect clue so most (not all) players guess the right surreal image card.",
        ImageView(this).apply { setImageResource(R.drawable.alias) })
)

Construct ImageView and set image resource on non-null instance.
Or you can initialize your game_pic somewhere in, for example, onCreateView method and therefore initialize your mMoviesBooksGames after that.
UPD:

*

*You should not declare your Views as nullable.

*You can set your image resource in another way.

First of all, you initialize your mGamePicImageView in init and then rewrite it in bind. Second, you can instead pass only drawable data to view holder, not a whole new ImageView.
I suggest you to redesign your data class:
data class Game(
    override val title: String,
    override val body: String,
    override val imageDrawable: Drawable)

And then in bind method of viewholder
mGamePicImageView.setImageDrawable(dataToBind.imageDrawable)

And finally
private val mMoviesBooksGames = listOf( Game(
    "Dixit",
    "Give the perfect clue so most (not all) players guess the right surreal image card.",
    ContextCompat.getDrawable(this.activity, android.R.drawable.alias))
    )

Not that first argument of getDrawable is context, so pass your fragment's parent activity there. Second argument is drawable's id, I am not sure if you need prefix android., so you can also try just R.drawable.alias.

A: data class Game(
    override val title: String,
    override val body: String,
    override val image: Int)

modify the data class like this
override fun bind(dataToBind: Thing) {
    mGameTitleView?.text = ">> Book ${dataToBind.title}"
    mGameDescriptionView?.text = dataToBind.body
    mGamePicImageViewsetImageResource(dataToBind.pic)
}

after that write replace the code into your view holder like this
data class Game(
    "Dixit",
    "Give the perfect clue so most (not all) players guess the right surreal image card.",
    R.drawable.your_pic

)
then try to put this value in your Game cons.


text:
Q: $N$ lines on a plane, proof of Area Say we have $n$ number of lines on a plane, none of which are parallel and there is never more than two of them intersecting each other at the same point. Lines divide the plane into $A_n$ different areas. The objective is to prove that $A_n=A_{n-1} + n$ and with induction that $A_n=(n^2+n+2)/2$. I have a minimal idea of how to approach this problem. I tried approximating how many different areas a number of intersecting lines would create but it did not seem to help very much. Any ideas? And what is meant by dividing the plane into areas by these lines?
Now that I think about this, it would seem that $A_n$ just increases by adding $n$ number of lines to the previous area. Does this mean that there is always one extra line that yields a new area?
I may be wrong, but in my opinion, the question in the textbook is either obvious and does not require overthinking or is simply poorly stated? The most important aspect is the proof by induction, however.

A: Start with two lines : easy 4 regions, than add a third how many new ones? and a fourth?  then imagine n lines how many new ones appear with one more ? how many lines will it cross, thats the induction.

A: I got the first 4 regions between the red lines in arabic numbers, the 3 new ones due to the black line have roman numerals.


text:
Q: Objective C - addobserver for UIView adding subviews? Is there an easy way for listening for when a child or subview has been added to a UIView?
I've gone through the addobserver options and haven't found an obvious option anyway. There may be another option that would be affected though when content is added to a view or am I wrong in saying that? i.e. content width or height, positions, etc.?
Edit
This is accomplished easily using the advice of @Alkimake below (TextHolderClass).
I created a custom UIView subclass and set the UIView's class in Interface Builder to be equal to TextHolderClass
Thanks for your help, I know it should have been obvious :)

A: UIView methods may help you:
- (void)willMoveToSuperview:(UIView *)newSuperview

A: UIView has 2 methods to call after subview interactions. Simply create your custom UIView class and implement these methods which is pretty for you. And use your own CustomView
- (void)didAddSubview:(UIView *)subview;
- (void)willRemoveSubview:(UIView *)subview;


text:
Q: asp.net MVC 5 entity framework - DropDownListFor trims space? I have table of products with primary key(data type nvarchar(50)) like
100531         00001
in Model i get products List
public List<string> GetProductsList()
{
        List<string> productsList = new List<string>();
        using (Entities database = new Entities ())
        {
            productsList = (from product
                            in database.Products
                            select product.ID).Take(10).ToList();

        }
        return productsList;
}

in View I display DropDownList with products
@Html.DropDownListFor(model => model.Product, new SelectList(Model.ProductsList), "-- Product --", new { @class = "form-control" } )

But items in DropDownList displays like
100531 00001

ID of product is also foreign key in Orders table. But I can't add new order with product ID
100531 00001
My question is : Can I change something in appliaction to display data like it is in database or I must change something in database?
UPDATE
found solution here How to retain spaces in DropDownList - ASP.net MVC Razor views

A: You can use this Replace(" ", " ") method to preserve whitespaces in dropdownlistfor like following code.
Reference: http://www.dennisonpro.info/preserving-whitespace-in-dropdownlist-items-with-c-mvc-3/
public List<string> GetProductsList()
{
        List<string> productsList = new List<string>();
        using (Entities database = new Entities ())
        {
            productsList = (from product
                            in database.Products
                            select product.ID).Take(10).ToList();

        }
        productsList = productsList.Select(str=>str.Replace(" ", " "));
        return productsList;
}

A: I recommend to use key value pair list when you want to bind something to drop down list. Currently you are returning a list of string which hold product id but instead you should return a key value pair of either product id and product id or product id and product name. So that you can bind dropdown as
@Html.DropDownListFor(model => model.Product,
new SelectList(Model.ProductsList, "Key", "Value"), "-- Product --",
new { @class = "form-control" } )

instead of your current implementation
@Html.DropDownListFor(model => model.Product,
new SelectList(Model.ProductsList), "-- Product --",
new { @class = "form-control" } )

Problem with your current implementation is that you have multiple white space in your product id but html will allow only one white space character unless that is  . But in database you have white space character instead of &nbsp ; so while posting your data you get only 1 white space which doesn't match to your database record. Thus I recommend you to return key value pair of list.


text:
Q: NEO4j, Storing more than `3` models in the catalog is available with a licensed Graph Data Science library I am using NEO4j to do graph embedding. This is the document I follow. When I am running the code in Neo4j.
CALL gds.beta.graphSage.train(
  'noPropertiesGraph',
  {
    modelName: 'myModel',
    featureProperties: ['degree']
  }
)
YIELD trainMillis
RETURN trainMillis

I met this error. How do I solve this?

A: Graph Data Science GDS library has its own separate license for its Enterprise Edition, which is not covered under Neo4j Enterprise Edition. You might wanna drop some of your older models to get this working.
Check this GitHub discussion.


text:
Q: How to call this.close in buildResult method when using Search Delegate (Flutter)? I have a very simple SearchApp that has an AppBar with a search Icon and a text widget. When the search Icon is tapped, showSearch is called and the CustomSearchDelegate is called. How do I make it so that in the buildResults method, this.close is immediately called without returning a widget and the query is passed to the SearchApp stateless widget to be displayed on the Text widget.
Here is the code:
class SearchApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        actions: <Widget>[
          IconButton(
            tooltip: 'Search',
            icon: const Icon(Icons.search),
            //Don't block the main thread
            onPressed: () {
              showSearch(context: context, delegate: CustomSearchDelegate());
            },
          ),
        ],
      ),
      body: Text(query), // The query data should be displayed here
    );
  }
}

class CustomSearchDelegate extends SearchDelegate {
  @override
  List<Widget> buildActions(BuildContext context) {
    return <Widget>[Icon(Icons.close)];
  }

  @override
  Widget buildLeading(BuildContext context) {
    return Icon(Icons.arrow_back_ios);
  }

  @override
  Widget buildResults(BuildContext context) {
    // GO back to SearchApp page immediately with the query result
  }

  @override
  Widget buildSuggestions(BuildContext context) {
    return Column();
  }
}

A: I realized I could edit the source code of the search class, so I copied and pasted the source code and under the Textfield, I simply deleted the showResult method and replaced it with close, so no results page would be shown. As for passing the query to the original page, all I had to do was store the value in an asynchronous variable.

A: If you just want to use close() function without buildResults() you can override showResults()
  @override
  void showResults(BuildContext context) {
    // TODO: implement showResults
    super.showResults(context);
  }

to this:
  @override
  void showResults(BuildContext context) {
    close(context, query);
  }

like this:
class CustomSearchDelegate extends SearchDelegate<String> {
  @override
  List<Widget> buildActions(BuildContext context) {
    return <Widget>[Icon(Icons.close)];
  }

  @override
  Widget buildLeading(BuildContext context) {
    return Icon(Icons.arrow_back_ios);
  }

  @override
  Widget buildResults(BuildContext context) {
    // unused
    return const SizedBox();
  }

  @override
  void showResults(BuildContext context) {
    close(context, query);
  }

  @override
  Widget buildSuggestions(BuildContext context) {
    return Column();
  }
}

call like this to get query result:
onPressed: () async {
  String? result = await showSearch(context: context, delegate: CustomSearchDelegate());
}


text:
Q: scrape a table with rvest in R that has mismatch table heading I'm trying to scrape this table which seems like it would be super simple.
Here's the url of the table: https://fantasy.nfl.com/research/scoringleaders?position=1&sort=pts&statCategory=stats&statSeason=2019&statType=weekStats&statWeek=1
Here's what I coded:
url <- "https://fantasy.nfl.com/research/scoringleaders?position=1&sort=pts&statCategory=stats&statSeason=2019&statType=weekStats&statWeek=1"
x = data.frame(read_html(url) %>%
  html_nodes("table") %>%
  html_table())

This works ok but gives really weird two row headers and when I try to add %>% slice(-1) to take out the top row it says I can't because it's a list. Would really like to figure out how to do this.

A: Here's one solution. An explanation follows.
library(rvest)
library(tidyverse)

read_html(url) %>%
  html_nodes("table") %>%
  html_table(header = T) %>%
  simplify() %>%
  first() %>%
  setNames(paste0(colnames(.), as.character(.[1,]))) %>%
  slice(-1)

Output of glimpse():
Observations: 25
Variables: 16
$ Rank          <chr> "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"…
$ Player        <chr> "Lamar Jackson QB - BAL", "Dak Prescott QB - DAL", "Deshaun W…
$ Opp           <chr> "@MIA", "NYG", "@NO", "@ARI", "@JAX", "@PHI", "PIT", "WAS", "…
$ PassingYds    <chr> "324", "405", "268", "385", "378", "380", "341", "313", "248"…
$ PassingTD     <chr> "5", "4", "3", "3", "3", "3", "3", "3", "3", "3", "2", "2", "…
$ PassingInt    <chr> "-", "-", "1", "-", "-", "-", "-", "-", "-", "1", "1", "1", "…
$ RushingYds    <chr> "6", "12", "40", "22", "2", "-", "-", "5", "24", "6", "13", "…
$ RushingTD     <chr> "-", "-", "1", "-", "-", "-", "-", "-", "-", "-", "-", "-", "…
$ ReceivingRec  <chr> "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "…
$ ReceivingYds  <chr> "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "…
$ ReceivingTD   <chr> "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "…
$ RetTD         <chr> "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "…
$ MiscFumTD     <chr> "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "…
$ Misc2PT       <chr> "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "1", "-", "…
$ FumLost       <chr> "-", "-", "-", "1", "-", "-", "-", "-", "-", "-", "-", "-", "…
$ FantasyPoints <chr> "33.56", "33.40", "30.72", "27.60", "27.32", "27.20", "25.64"…

Explanation
From ?html_table docs:

html_table currently makes a few assumptions:

*

*No cells span multiple rows

*Headers are in the first row

Part of your problem is solved by setting header = TRUE in html_table().
Another part of the problem is that the header cells span two rows, which html_table() does not expect.
Assuming you don't want to lose the information in either header row, you can:

*

*Use simplify and first to pull out the data frame from the list you get from html_table

*Use setNames to merge the two header rows (which are now the data frame columns and the first row)

*Remove the first row (now redundant) with slice


text:
Q: Can a Solr Request Handler modify the query string? I'm trying to improve an existing solr search which uses the StandardRequestHandler.  I'd like to switch to a dismax-based handler, however I'll need to remove the  fieldname from the "fieldname:value" query.
Is it possible to modify the q parameter value as it's passed to a request handler?

A: I haven't looked into this deeply but I think you might want to create your own QueryParser, probably extending the one you're using now. The result you want to achieve does require some coding.
On the other hand, of course it would be better to modify the client side, that way you wouldn't need to hack Solr.


text:
Q: AppExchange: API to search for package by keyword, get latest version etc We are using couple external packages (mainly provided by SF Labs) as helper utils by installing them in every dev/qa/uat sandboxes along with deployment of our main app code.
The process of sandbox setup is automated via CI. But the challenge here is that we are using hardcoded version numbers of those external packages and updating them manually every time when new version becomes available in AppExchange.
The question here: is it possible to integrate somehow with AppExchange (via some sort of api) to query for latest available package version of specific package?
Haven't found anything like that in docs so far.
The only option we've come up for now is to do a web scraping of AppExchange web page by hardcoded  listing id to parse from html body latest version number available. Kind of clumsy approach. There should be something better.
Any help or alternative ideas would be appreciated.


text:
Q: Peculiarity with Scale and Z-Score I was attempting to scale my data in R after doing some research on the function (which it seems to follow (x - mean) / std.dev. This was just what I was looking for, so I scaled my dataframe in R. I'd also want to make sure my assumptions are correct so that I don't have wrong conclusions.

Assumption
R scales each column independently. Therefore, column 1 will have its own mean and standard deviation. Column 2 will have its own.

Assuming I have a dataset of size 100,000 and I scale 3 columns. If I proceed to remove all columns with a Z-Score over 3 and less than -3, I could have up to (100,000 * .003) = 900 rows removed!
However, when I went to truncate my data, my 100,000 rows were left with 94,798. This means 5,202 rows were removed.
Does this mean my assumption about scale was wrong, and that it doesn't scale by column?

Update
So I ran a test and did Z-Score conversion on my own. Still the same amount of columns removed in the end so I believe scale does work. Now I'm just curious why more than .3% of the data is removed when 3 standard deviations out are removed.


text:
Q: Difference between wc -c and ${#}? I've created script, where I encoded string 28 times with base64. Then I wanted to echo count of chars in outputted string.
First I used ${#var} which gave me 34070.
Then I tried on the same string
script.sh | wc -c

which gave me 34071.
#!/bin/bash
var="9M"
for i in {1..28};do
var=$(echo $var | base64)
done
echo ${#var}

What exactly does make those two outputs different?

A: As you can see in this example using the command od showing the bytes, it prints the newline:

$ echo foo | od -c -b
0000000   f   o   o  \n
        146 157 157 012
0000004

So in this case, wc -c as well as wc -m is counting the newline.
Without the newline:
$ echo -n foo | od -c -b
0000000   f   o   o
        146 157 157
0000003

So if you use echo, add the -n option so it doesn't print the newline, or printf:
$ printf "%s" foo | od -c -b
0000000   f   o   o
        146 157 157
0000003

A: The extra character is the newline. You can see it if you do, for example:
echo $var | hd | tail


text:
Q: elasticsearch copy field when indexing I would like to create a one to many relashanship for the purpose of aggregations.
The "join" will be according to a field called "common_id":

*

*When I create the first document belonging to the same group I would like to use it's flakeId (it's _id) as the common_id.

*When adding other document belonging to the same group I would like to explicitly set the common_id to have the same value as the first document I added. This can be done by my app since my application will know the common_id of the first element.

My problem is with the first document:
How can i tell elasticsearch to copy the _id into common_id in a single call to elastic (I know I can do it using update script, or using two calls one for index and one for update... but this requires two requests instead of one).
I would like a simple syntax for this.
thanks


text:
Q: C Abstract Limitation I'm making a network server in C and trying to define packet handlers as generic as possible.
When I receive a completed packet, I want to create a struct and send it to the defined handler.
struct handler {
   char *msg_name;
   void (*handler)(network_client *, void *msg).
}

//global variable containing all handlers
struct handler const handlers[] = {
   {"hello_msg", &helloMessageHandler}
};

struct hello_message_s {
   int foo;
   char *bar;
   float foobar;
}

//called when received hello_cmd and deserialized hello_message_s bytes received by the network
void helloMessageHandler(network_client *c, void *msg) {
   struct hello_message_s *casted = msg;

   casted->foo; //etc..
}

My question is; is there a way to specify the message struct directly instead of void * forcing me to cast later?
i.e change void helloMessageHandler(network_client *c, void *msg) to void helloMessageHandler(network_client *c, struct hello_message_s *msg).
It's not possible since handlers[] can hold handlers with void * only.
struct handler const handlers[] = {
   {"hello_msg", &helloMessageHandler}
};

Any solution?

A: If you have only a finite number of structs describing a packet, you can use union including all the packets instead of void *.
But usage of void * is more common, as far as I know. The downside of using union is that its size will be equal to the largest member of the union.


text:
Q: Hiding the keyboard when application returns from suspension I have an application where the login screen moves the username/password fields up by resizing the main view when the keyboard is shown.
The problem is that if I suspend the app (clicking the home button) while the keyboard is visible and then bring the application back, it will "reset" the view size (as per the NIB), but the keyboard will still be visible, meaning that part of the "form" becomes hidden by the keyboard.
Does anyone have any suggestions for the best way to either hide the keyboard whenever the application returns from a suspended state (I know applicationDidBecomeActive gets called on my app delegate), or make sure that the view remains resized?
Thanks in advance!

A: I think you'll be able to achieve this using NSNotificationCenter
In your view controller, in viewWillAppear call:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appWasResumed) name:UIApplicationWillEnterForegroundNotification object:nil];

and implement a method:
-(void) appWasResumed
{
    [textField1 resignFirstResponder];
    //If you are changing positions of items, you might want to do that here too.
}

and I think the rest should be handled automatically.
If it's not handled automatically try adding this to your AppDelegate on applicationDidBecomeActive or applicationWillEnterForeground:
[[NSNotificationCenter defaultCenter] postNotificationName:UIApplicationWillEnterForegroundNotification object:nil];

I've not used NSNotificationCenter a lot, so some of the syntax may be wrong. Check out the link I provided at the top for confirmation.

A: Subscribe the UIApplicationDidEnterBackgroundNotification notification (via addObserver:selector:name:object: selector of NSNotificationCenter) and call [element resignFirstResponder].
I'm not sure whether it'll go down smoothly since the keyboard always animates when hiding, but at least it'll get the job done.


text:
Q: NoMethodError: undefined method `mail' for main:Object on rails console I am trying to test the working of mailer. Normally on rails I first test my code logic on console level and then once it is successful I put it into the real source code. I am trying to do the same while working on ApplicationMailer. I followed some other solution and first ran the following on rails console to first set up the ActionMailer
ActionMailer::Base.delivery_method = :smtp
ActionMailer::Base.smtp_settings = {
  address: 'smtp.gmail.com',
  port: 587,
  domain: 'gmail.com',
  authentication: 'plain',
  enable_starttls_auto: true,
  user_name: '***********',
  password: '******'
}

and then I ran my code:
y.include? x
  if true
    @receiver = Model.where(category_id: "#{x}").pluck(:email)
    mail(to: @receiver, subject: @subject)
  end

I'm getting the following error:
NoMethodError: undefined method `mail' for main:Object
    from (irb):19

Could somebody please tell me how make this work on rails console?

A: You can test mail using following way
ActionMailer::Base.mail(from: "test@example.co", to: @receiver, subject: @subject, body: "Test").deliver

A: Rails sets up a lot of convenience so that you can e.g. send mails from the controller easily.
In the console, you are not in the context of a controller, therefore you have not set this up already. The same would go for view-helpers.
In order to use the mail-method, you need to tell Ruby where to look for it.
It should be enough to send the mail like this:
ActionMailer::Base.mail(from: "test@example.co", to: @receiver, subject: @subject, body: "Test").deliver

Keep in mind that you can also use different delivery_methods, if you just want to test the mail-generation, but not yet the integration with your SMTP.


text:
Q: Will all TSP algorithms give the same optimum route? I was just wondering if all algorithms for the TSP will give the same optimum routes? I thought that this would be the case but ive implemented branch and bound and A* and they both give very different results to the same input, I was just wondering if this is normal?

A: The route my differ, but the cost of all optimal solution should be the same.
If your A* solution is more expensive, than your heuristic is wrong.
Have a look at wikipedia A* algorithm for proofs that it always finds an optimal solution.

A: No. Provided more than one optimal route exists, different algorithms will not necesarily find the same path. It will depend on the implementation, and I assume it will also depend on how you label the graph, so that different labelings will make the same algorithm find different routes.


text:
Q: Coefficient of $x^{41}$ in $(x^5 + x^6 + x^7 + x^8 + x^9)^5$
What is the coefficient of coefficient of $x^{41}$ in $(x^5 + x^6 + x^7 + x^8 + x^9)^5$?

Using summation of G.P., this is equivalent to finding the coefficient of $x^{41}$ in
$$\left(x^5 \left(\frac{1-x^5}{1-x}\right)\right)^5$$
and thus finding coefficient of $x^{16}$ in $(\frac{1-x^5}{1-x})^5$. How to proceed after this?

A: It's convenient to use the coefficient of operator $[x^k]$ to denote the coefficient of $x^k$ in a series. This way we can write e.g.
\begin{align*}
[x^k](1+x)^n=\binom{n}{k}
\end{align*}

We obtain
  \begin{align*}
[x^{16}]\left(\frac{1-x^5}{1-x}\right)^5
&=[x^{16}](1-x^5)^5\sum_{k=0}^\infty \binom{-5}{k}(-x)^k\tag{1}\\
&=[x^{16}](1-5x^5+10x^{10}-10x^{15})\sum_{k=0}^\infty \binom{k+4}{4}(-x)^k\tag{2}\\
&=\binom{20}{4}-5\binom{15}{4}+10\binom{10}{4}-10\binom{5}{4}\tag{3}\\
&=4845-5\cdot 1365+10\cdot 210-10\cdot 5\\
&=70
\end{align*}

Comment:

*

*In (1) we use the binomial series expansion of $\frac{1}{(1-x)^5}$

*In (2) it is sufficient to expand to binomial up to $x^{15}$ since we only need coefficients of powers of $x^{16}$. We also use the binomial identity
\begin{align*}
\binom{-n}{k}=\binom{n+k-1}{k}(-1)^k
\end{align*}

*In (3) we select the coefficients of the series accordingly

A: In other words, how many ways are there to write
$$ 41 = a + b+c+d+e $$
where $a,b,c,d,e$ are integers between $5$ and $9$, inclusive.
The highest sum we can make is $9\cdot 5=45$, so to get $41$ instead we need to remove $4$ units from among the 5 variables. Fortunately, even removing all $4$ of them from the same variable still leaves $5$, which is a valid value. So what we're counting is the same as

How many ways are there to write $4$ as an (ordered) sum of $5$ non-negative integers?

This is a standard combinatorial problem; by the stars-and-bars formula, the answer is $$\binom{4+5-1}{4} = 70$$

A: Why not to apply the multinomial sum (just to study it a little bit) so we need the coefficient of $x^{16}$ in $(x^4+x^3+x^2+x+1)^5$?
Put $A=x^3+x^2+x+1$ so one has $$(x^4+A)^5=x^{20}+5x^{16}A+10x^{12}A^2+10x^8A^3+5x^4A^4+A^5$$
Hence, after to see in $A,A^2,A^3,A^4$ ($A^5$ does not participate here because its greatest exponent is $15$) the coefficients of $1,x^4,x^8,x^{12}$ respectively, the required coefficient is equal to
$$\color{red}{5\cdot1+10\cdot3+10\cdot3+5\cdot1=70}$$


text:
Q: Can WP7 Silver Light Gesture Listener be added to a StackPanel? I'm working on a small Windows Phone 7 Silver Light app. I simply want a context menu to pop up over an item in a Listbox when the user taps and holds on the respective entry. I've read through several posts and the most common answer given is to use the Silverlight toolkit. I was excited since I already have it set up and use it for a few other things in the app. So I found a tutorial that explains how to set it up on a button. It failed when I tried because I was setting the content for the button twice:
    <Button Width="Auto" MinWidth="460" Height="Auto" HorizontalAlignment="Stretch">
        <Button.Content>
            <toolkit:GestureListener Hold="GestureListener_Hold" />
            <StackPanel ..... >
                .......
            </<StackPanel>
        </Button.Content>
    </Button>

Which tells me "The property 'Content' is et more than once.
So after searching again I found a nice article, http://forums.create.msdn.com/forums/t/85263.aspx, which shows that I can move the statement to look more like:
    <StackPanel Orientation.....>
        <toolkit:GestureListener Hold="GestureListener_Hold" />
        <TextBlock
            Text="{Binding ItemName}" FontSize="{StaticResource PhoneFontSizeLarge}"
            HorizontalAlignment="Stretch" VerticalAlignment="Center" Height="40"/>
    </StackPanel>

Which tells me "A value of type 'GestureListener' cannot be added to a collection or dictionary of type 'UIElementCollection'.
I'd appreciate any help on either method or a brand new one.
Thanks in advance!

A: You need to set the GestureListener as the value of the GestureService.GestureListener attached property:
<Button Width="Auto" MinWidth="460" Height="Auto" HorizontalAlignment="Stretch">
    <Button.Content>
        <StackPanel ..... >
            <toolkit:GestureService.GestureListener>
                <toolkit:GestureListener Hold="GestureListener_Hold" />
            </toolkit:GestureService.GestureListener>
            .......
        </<StackPanel>
    </Button.Content>
</Button>

For what it's worth, the toolkit already includes a ContextMenu helper. See here


text:
Q: Lookup values from one xml to update another xml I have a need to look up many values in one xml which looks like:
<cat catid="some_generic_text_followed_by_something_specific1" pid="x1">
</cat>
</cat><cat catid="some_generic_text_followed_by_something_specific1" pid="x2">
</cat>
<cat catid="some_generic_text_followed_by_something_specific2" pid="x3">
</cat>
<cat catid="some_generic_text_followed_by_something_specific2" pid="x4">
</cat>
<cat catid="some_generic_text_followed_by_something_specific3" pid="x5">
</cat>

So the task is to identify words like "specific1" and "specific2" and find all pid values that belong to these multiple keywords. In this case I find x1,x2,x3,x4 but not x5.
I then have to look up another xml with many nodes:
<prod prod-id="x1">
    <display-name xml:lang="x-default">some text</display-name>
</prod>
<prod prod-id="x2">
    <display-name xml:lang="x-default">some more text</display-name>
</prod>
<prod prod-id="x5">
    <display-name xml:lang="x-default">some text</display-name>
</prod>

and update in bulk the same text right before you see "some text" with "inserted keyword" followed by what was there. So the 1st example, it would say "inserted keyword some text". In essence, I'm prepending the text.
I can do any xslt version and will probably use some tool like XmlSpy or similar.
I did find a sort of similar question/answer here XSLT to lookup values in one XML and replace in another XML file but I don't understand xslt enough to make a modification for my example.
UPDATE
I have a minor correction to my very 1st xml above: It is actually:
<cat catid="c1">
   <parent>specific1</parent>
</cat>
<cat catid="c2">
   <parent>specific1</parent>
</cat>
<cat catid="c3">
   <parent>specific1</parent>
</cat>
<cat catid="c4">
   <parent>specific2</parent>
</cat>
<cat catid="c5">
   <parent>specific2</parent>
</cat>
<cat-assign catid="c1" pid="x13"/>
<cat-assign catid="c1" pid="x14"/>
<cat-assign catid="c1" pid="x15"/>
<cat-assign catid="c2" pid="x24"/>
<cat-assign catid="c2" pid="x43"/>
<cat-assign catid="c2" pid="x44"/>
<cat-assign catid="c3" pid="x45"/>
<cat-assign catid="c4" pid="x27"/>
<cat-assign catid="c5" pid="x31"/>
<cat-assign catid="c5" pid="x32"/>
<cat-assign catid="c5" pid="x33"/>
<cat-assign catid="c5" pid="x34"/>

*

*I need to look for an exact match "specific1" not using contains keyword

*Then find the catid (there will be multiple)

*In the same xml, find each

*finally look up the pid used to look up another xml doc

A: Assuming XSLT 3.0 (which the current version of XMLSpy supports) you can use the following which assumes the document you want to manipulate is the primary input and the URI of the other document is set as the parameter cat-uri:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    exclude-result-prefixes="xs"
    version="3.0">

    <xsl:param name="cat-uri" as="xs:string" select="'cat.xml'"/>

    <xsl:param name="new" as="xs:string" select="'inserted keyword'"/>

    <xsl:param name="word-list" as="xs:string*" select="'specific1', 'specific2'"/>

    <xsl:param name="cat-doc" select="doc($cat-uri)"/>

    <xsl:mode on-no-match="shallow-copy"/>

    <xsl:key name="match" match="cat" use="some $word in $word-list satisfies contains(@catid, $word)"/>

    <xsl:key name="ref" match="prod[@prod-id]/display-name" use="../@prod-id"/>

    <xsl:variable name="pids" select="key('match', true(), $cat-doc)/@pid"/>

    <xsl:template match="key('ref', $pids)/text()">
        <xsl:value-of select="$new || ' ' || ."/>
    </xsl:template>

</xsl:stylesheet>

As for your changed input, you would have to adapt the keys then, so to match the cat elements on the parent child element value you can declare a key <xsl:key name="cat-match" match="cat" use="parent"/> and then key('cat-match', $word-list, $cat-doc)/@catid gives us the catid attribute values of the cat-assign we need to reference. To do that, we can define another key <xsl:key name="cat-assign" match="cat-assign" use="@catid"/> and then key('cat-assign', key('cat-match', $word-list, $cat-doc)/@catid, $cat-doc)/@pid gives us the values to reference the prod elements in the primary input. The rest is unchanged:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    exclude-result-prefixes="xs"
    version="3.0">

    <xsl:param name="cat-uri" as="xs:string" select="'cat.xml'"/>

    <xsl:param name="new" as="xs:string" select="'inserted keyword'"/>

    <xsl:param name="word-list" as="xs:string*" select="'specific1', 'specific2'"/>

    <xsl:param name="cat-doc" select="doc($cat-uri)"/>

    <xsl:mode on-no-match="shallow-copy"/>

    <xsl:key name="cat-match" match="cat" use="parent"/>

    <xsl:key name="cat-assign" match="cat-assign" use="@catid"/>

    <xsl:key name="ref" match="prod[@prod-id]/display-name" use="../@prod-id"/>

    <xsl:variable name="pids" select="key('cat-assign', key('cat-match', $word-list, $cat-doc)/@catid, $cat-doc)/@pid"/>

    <xsl:template match="key('ref', $pids)/text()">
        <xsl:value-of select="$new || ' ' || ."/>
    </xsl:template>

</xsl:stylesheet>

When I run that inside Oxygen with Saxon 9.6 EE against the cat.xml being
<?xml version="1.0" encoding="UTF-8"?>
<root>
    <cat catid="c1">
        <parent>specific1</parent>
    </cat>
    <cat catid="c2">
        <parent>specific1</parent>
    </cat>
    <cat catid="c3">
        <parent>specific1</parent>
    </cat>
    <cat catid="c4">
        <parent>specific2</parent>
    </cat>
    <cat catid="c5">
        <parent>specific2</parent>
    </cat>
    <cat catid="c6">
        <parent>specific3</parent>
    </cat>
    <cat-assign catid="c1" pid="x13"/>
    <cat-assign catid="c1" pid="x1"/>
    <cat-assign catid="c1" pid="x15"/>
    <cat-assign catid="c2" pid="x24"/>
    <cat-assign catid="c2" pid="x43"/>
    <cat-assign catid="c2" pid="x44"/>
    <cat-assign catid="c3" pid="x45"/>
    <cat-assign catid="c4" pid="x27"/>
    <cat-assign catid="c5" pid="x31"/>
    <cat-assign catid="c5" pid="x2"/>
    <cat-assign catid="c5" pid="x33"/>
    <cat-assign catid="c5" pid="x34"/>
</root>

and the input document being
<?xml version="1.0" encoding="UTF-8"?>
<root>
    <prod prod-id="x1">
        <display-name xml:lang="x-default">some text</display-name>
    </prod>
    <prod prod-id="x2">
        <display-name xml:lang="x-default">some more text</display-name>
    </prod>
    <prod prod-id="x5">
        <display-name xml:lang="x-default">some text</display-name>
    </prod>
</root>

the result is
<?xml version="1.0" encoding="UTF-8"?><root>
    <prod prod-id="x1">
        <display-name xml:lang="x-default">inserted keyword some text</display-name>
    </prod>
    <prod prod-id="x2">
        <display-name xml:lang="x-default">inserted keyword some more text</display-name>
    </prod>
    <prod prod-id="x5">
        <display-name xml:lang="x-default">some text</display-name>
    </prod>
</root>


text:
Q: From Azure AD Token to Microsoft Graph Token in Next-Auth (react) Hi Stackoverflow community,
this is my first question here after not finding a solution to my problem.
To begin with, we are having an app registration on azure to our Azure Active Directory and configured our react-next-js project to authenticate with it.
export const authOptions: NextAuthOptions = {
  providers: [
    AzureADProvider({
      name: 'Azure Active Directory',
      clientId: process.env.AZURE_CLIENT_ID ?? 'undefined',
      clientSecret: process.env.AZURE_CLIENT_SECRET ?? 'undefined',
      tenantId: process.env.AZURE_TENANT_ID,
      authorization: {
        params: {
          scope: 'api://ownscope/general openid profile email user.read ',
        },
      },
    }),
  ],
  theme: {
    colorScheme: 'light',
  },
  callbacks: {
    /**
     * Controls
     * @param param{account, profile, user}
     * @returns True iff user is allowed to sign in
     */

    async signIn()
    {
      return true
    },
    // user, profile
    async jwt({ token, account }) {
      if (account) {
        token.access_token = account.access_token;
        try {
          const graphClient = getGraphClient(
            {access_token: account.access_token} as { access_token: string }
          )
          token.graphdata = await graphClient.api('/me').get()
        } catch (err) {
          console.error('Failed to load MS Graph data')
          console.error(err)
        }
      }
      return token
    },
    // , user
    async session({ session, token }) {
      // Transform graphdata to user model
      session.userdata = ToUser(token.graphdata)
      return session
    },
  },
  events: {
    async signIn(message) {
      console.log(
        'Logged in successfully: %s',
        JSON.stringify(message.user.name)
      )
    },
    async session(message) {
      console.log(
        'Session active: %s',
        JSON.stringify(message?.session?.user?.name)
      )
    },
  },
}

export default NextAuth(authOptions)

Which does work fine, the login screen is coming up and we can login with our user. The returned access_token is good and does have the 'aud' from our app registration:
AAD_Token
We need this token to access our API which is protected with this app registration (Azure API Management). And this works too.
But as you can see in our next-auth code, we want to get further user informations from Microsoft Graph Endpoint (The used graph client is microsoft/microsoft-graph-client). We added the scopes for profile and user.read in our authentication request.
And I tried to access the Graph endpoint with postman too. Which get's the response
{
    "error": {
        "code": "InvalidAuthenticationToken",
        "message": "Access token validation failure. Invalid audience.",
        "innerError": {
            "date": "2022-08-31T13:39:54",
            "request-id": "9e161f21-3eca-4b6e-8678-ab1edd803e13",
            "client-request-id": "9e161f21-3eca-4b6e-8678-ab1edd803e13"
        }
    }
}

Which does make sense since the checked audience is from our AAD and not the expected Microsoft Graph auth.
Removing our own scope from the request results in a Microsoft graph access token, but we can't access our API with it:
Graph Token
How can we get a valid Microsoft Graph token in next-auth after successfully login into our AAD account?


text:
Q: Prolog - print true or false in print_solution write method I want to print true or false based on some predicate predicate passing. For example, in Greek mythology Athena is not a descendant of Poseidon. I have all of the facts and rules correct to prove it as such, but cannot simply print in the print_solution method whether the predicate is true or not.
I have the rule descendant(athena, poseidon) that will print false in the interpreter as a single statement. E.g. false is printed if I:
$ prolog
['greek_mythology.pl'].
descendant(athena, poseidon).
false

I now want to write the same in my print_solution method:
print_solution :-
write('Athena is a descendant of Poseidon: '), write(?????), nl.

I tried assigning a variable in the solution and printing that:
print_solution :-
Z :- descendant(athena, poseidon),
write('Athena is a descendant of Poseidon: '), write(Z), nl.

but I get the error:
ERROR: /.../greek_mythology.pl:164:17: Syntax error: Operator priority clash

Out of desperation I tried checking to see if poseidon was in the list of descendant(athena, X):
setof(X, descendant(athena, X), Z), // [gaia,kronos,oranos,rheia,zeus]
member(poseidon, Z).

but that just gives back:
Z = [poseidon|_G3320] .

which I don't understand. Apparently member/2 only works on lists, and Z is apparently not a list:
is_list(Z).
false.

How can I simply print true or false in the write function if the predicate returns passes like it does in the interpreter console? Desired output: Athena is a descendant of Poseidon: false.

A: I think (not absolutely sure) that what you want is reification of the success or failure of a query to a truth value. A naive way to do it would be:
goal_success(Goal, true) :-
    Goal.
goal_success(Goal, false) :-
    \+ Goal.

(This has problems but read on)
Then, you can use it like this:
?- goal_success(descendant(athena, poseidon), S),
   /* write whatever */, write(S).

However, what you are trying to do is basically write your own meta-interpreter, and I am not sure it is really that useful. After all, what you show in your question is exactly how you would expect to interact with the Prolog top level (the Prolog interactive prompt). As a programmer (a human) what you want from Prolog is answers to your questions. What you give Prolog, however, is queries, and you get solutions to these queries. Your question is:

Is Athena a descendant of Poseidon?

You evaluate the query:
?- descendant(athena, poseidon).
false.

There is no solution to this query (let's not go into the whole "closed world assumption" discussion now, it is enough to say that not being able to find a proof means that the opposite is true...)
So we interpret this as:

Athena is not a descendant of Poseidon.

Usually, this should be enough. This is why it seems that you want to extend the Prolog top level, and write your own interpreter on top of it, which is of course fine, but more involved. Once you go down that road, you would like to interact with this interpreter like this maybe?
??- Is Athena a descendant to Poseidon?
?>> No, she is not!

Anyway, if you search the internet for "Prolog meta interpreter" you will get enough to get you started. "The Art of Prolog" by Sterling & Shapiro has a whole chapter on that, too.

A: You can use if/then/else construct in Prolog also
 print_solution :-
 (  descendant(athena, poseidon)
 -> Z = true
 ;  Z = false
 ),
 write('Athena is a descendant of Poseidon: '), write(Z), nl.

seems also could be more useful if parametrized
 print_solution(Desc, Anc) :-
 (  descendant(Desc, Anc)
 -> Z = true
 ;  Z = false
 ),
 format('~w is a descendant of ~w: ~w~n', [Desc, Anc, Z]).

 print_solution :- print_solution(athena, poseidon).


text:
Q: MemSQL select query 1705 error I am using memsql community version and I am able to execute some queries but getting error for few queries like
select * from policy;
Error code:
ERROR 1705 (HY000): The query cannot be executed.
MemSQL code generation has failed: Failed to delete .fin file.

A: This likely indicates a permissions problem or some other issue with your installation ([install dir]/plancache may not be writable by memsqld for example).  Did you install and start MemSQL via Ops?
There will probably be a more detailed error message inside of
[install dir]/tracelogs/memsql.log


text:
Q: Create datatable in angular component I am developing one Angular 2 application. I have one module called Home. This module has one component called with the same name.
HomeModule.ts:
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { HomeComponent } from './home.component';
import { Routes, RouterModule } from '@angular/router/';
import { DataTablesModule } from 'angular-datatables';

const routes: Routes = [
  {
    path : '',
    component : HomeComponent,
  },
];

@NgModule({
  imports: [
   CommonModule,
   RouterModule.forChild(routes),
   DataTablesModule
 ],
 declarations: [HomeComponent]
})
export class HomeModule { }

HomeComponent.ts:
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'dr-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
 dtOptions: DataTables.Settings = {};

  ngOnInit(): void {
    this.dtOptions = {
      data:
        [
          {
            "id": 860,
            "firstName": "Superman",
            "lastName": "Yoda"
          },
        ],
      columns:
        [
          {
            title: 'ID',
            data: 'id'
          }, {
            title: 'First name',
            data: 'firstName'
          }, {
            title: 'Last name',
            data: 'lastName'
          }
        ]
    };
  }
}

HomeComponent.html:

I need to add one button in HomeComponent.html for add dynamically rows in my datatable. How can I do this?
Thanks in advance.
David.

A: You need to build the actual data inside of the table. You can do this with something like...
HomeComponent.html

      id
      name

<input [(ngModel)]="input.id"></input>
<input [(ngModel)]="input.name"></input>
<button (click)="saveInput()">save</button>

and in HomeComponent.ts
public dataRows = [];
public input = {};

saveInput() {
  this.dataRows.push({id: this.input.id, name: this.input.name});
  this.input = {};
}

A: simple using below CMD you can generate the data table
ng generate  @angular/material:material-table --name=data-table


text:
Q: Given two positive integers a , b , $gcd(a, b) = 1$, prove for any integer n > ab-a-b there exist integers $x, y\ge0$ such that $ax+by = n$ Given two positive integers $a$, $b$  with $\gcd(a, b) = 1$, prove that for any integer $n > ab-a-b$  there exist non-negative integers $x$, $y$ such that $ax+by = n$
We can prove that for $c = ab-a-b$, there isn't such non-negative $x$ and $y$ with $ax+by = c$
Beacuse $gcd(a, b) = 1$, there exist $x_0$ and $y_0$ with $ax_0+by_0 = 1$.
For $n>c$, we have $anx_0+bny_0 = n$
Because $gcd(a, b) = 1$, so $a(nx_0-kb)+b(ny_0+ka) = n$, $\;k \in \mathbb{Z}$
I wander how to prove that there exists $k$ such that:
\begin{align}
nx_0 - kb &\geq 0 \\
ny_0 + ka &\ge 0
\end{align}


text:
Q: 0–127 range limit on WEXITSTATUS in old Unix? It is well known that, on many if not all Unixes, a process's exit status will be truncated to its lowest 8 bits when passed through _exit, waitpid, and WEXITSTATUS.  (Current iterations of POSIX specify that the status should not be truncated when passed through _exit and waitid, but that's not relevant to this question.)
Was it ever the case, possibly deep in the past, that the exit status would be truncated to its lowest seven bits when passed through whatever mechanism was the equivalent of _exit/waitpid/WEXITSTATUS at the time?  If so, on which historical implementation(s) was that, and how long ago?

A: 7-bit would be an unusual departure from the PDP-11, which according to the unix 2nd edition manual (p.144) dropped the exit status into

The low byte of r0 is available as status to the parent process.

R0 was a general purpose 16-bit register, and the low byte of that would be a full eight bits. And over in wait R0 has the process ID, while the high byte of MQ gets the low byte of R0, but that's still an 8-bit value.


text:
Q: Let other apps play background music I would like to add the functionality for other apps, such as Pandora or iTunes, to continue playing music while my Sprite Kit game is open.
How would I go about doing this? I apologize for the somewhat broadness of this question, I just can't find a lot of information on this.

A: Set your AVAudioSession category to Ambient.
import AVFoundation

    do {
        try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient)
        try AVAudioSession.sharedInstance().setActive(true)
    }
    catch let error as NSError {
        print(error)
    }

AVAudioSession Class Reference

A: I would also like to add the Objective-C answer:
[[AVAudioSession sharedInstance] setCategory:@"AVAudioSessionCategoryAmbient" error:nil];
[[AVAudioSession sharedInstance]setActive:true error:nil];

I can confirm this also worked in Sprite Kit when using [SKAction playSoundFileNamed: ] for my sound effects.


text:
Q: Header column datagrid I would like to create a datagrid with the following header
ID  Name  Key  Unique  Null  Value  Type
----------------------------------------

Right now I have two classes: dynamicentity and newproperty.
dynamicentity is as follows
    private int ID;
    private string entityName;
    private string Entitydescription;
    private List<NewProperty> addedProperties;

    public DynEntity(string name, string desc)
    {
        entityName = name;
        Entitydescription = desc;
        addedProperties = new List<NewProperty>();
    }

    public bool addNP(NewProperty data)
    {
        addedProperties.Add(data);
        return true;
    }

My newproperty class is as follows
    private int ID;
    private string PropertyName;
    private string StringPropertie;
    private bool isString;
    private int IntPropertie;
    private bool isInt;
    private float floatPropertie;
    private bool isFloat;
    private DateTime DatetimePropertie;
    private bool isDate;
    private bool boolPropertie;
    private bool isBool;
    private bool isKey;
    private bool allowNull;
    private bool isFK;
    private string FKEntityName;
    private bool isUnique;
    public NewProperty(int _id, string _propertyname, bool propType, bool key, bool isnull, bool isunic, string fkname)
    {
        ID = _id;
        PropertyName = _propertyname;
        boolPropertie = propType;
        isInt = false;
        isString = false;
        isFloat = false;
        isDate = false;
        isBool = true;
        isKey = key;
        allowNull = isnull;
        isUnique = isunic;
        if (fkname == "")
        {
            isFK = false;
        }
        else
        {
            isFK = true;
            FKEntityName = fkname;
        }
    }

    [DisplayName("ID")]
    public int PropID
    {
        get { return ID; }
        set
        {
            ID = value;
            OnPropertyChanged("ID");
        }
    }

    [DisplayName("Name")]
    public string PropName
    {
        get { return PropertyName; }
        set
        {
            PropertyName = value;
            OnPropertyChanged("Name");
        }
    }

My xaml is as follow
<DataGrid Name="dgUsers" ItemsSource="{Binding DEPropID}" AutoGenerateColumns="True" Grid.Column="1" Grid.ColumnSpan="3" Grid.Row="1">                          </DataGrid>

My viewmodel is:
private DynEntity _localDE;

        public DynEntityViewModel(DynEntity DynamicEntity)
        {
            _localDE = DynamicEntity;
        }

        public string DEName
        {
            get
            {
                return _localDE.EntityName;
            }
            set
            {
                _localDE.EntityName = value;
            }
        }

        public string DEDesc
        {
            get { return _localDE.EntityDescription; }
            set
            {
                _localDE.EntityDescription = value;
            }
        }

        public List<NewProperty> DEPropID
        {
            get { return _localDE.EntityProperties; }
        }

        public String Name
        {
            get { return _localDE.EntityProperties[0].PropName; }
        }

When returning a list of newproperty is there a way for me to modify the display header on the datagrid?

A: You can bind the header text property to a ViewModel property to change it dynamically or simply add DataGridTextColumn with text header you want:
something like this:
<DataGrid Name="dgUsers" ItemsSource="{Binding DEPropID}" AutoGenerateColumns="False" Grid.Column="1" Grid.ColumnSpan="3" Grid.Row="1">
      <DataGrid.Columns>
        <DataGridTextColumn Header="YourText" Width="*" Binding="{Binding YourProperty}"/>
      </DataGrid.Columns>
</DataGrid>

OR
<DataGrid Name="dgUsers" ItemsSource="{Binding DEPropID}" AutoGenerateColumns="False" Grid.Column="1" Grid.ColumnSpan="3" Grid.Row="1">
  <DataGrid.Columns>
    <DataGridTextColumn Header="{Binding DataContext.YourStringProperty}" Width="*" Binding="{Binding YourProperty}"/>
  </DataGrid.Columns>
</DataGrid>


text:
Q: How to check if a value in one column can contain more than value in another column I have the following dataframe:
df = pd.DataFrame()
df['id'] = [1, 1, 2, 2]
df['col1'] = [10, 10, 20, 20]
df['col2'] = [100, 200, 50, 50]
df['col3'] = [1, 2, 3, 4]

The goal
From this dataframe, I want to return the part of the dataframe where a value in col1 can have multiple values in col2 for a particular ID. In this case, id '1' has a value in col1 of 10, and 100 in col2. As id '1' also has a value of 10 in col1 in the second row, the value in col2 should also be 100. This is not the case for this id, however, it is the case for ID '2'. It should work both ways, so the values of col1 and col2 should just be consistent with each other for a ID. Column 3 contains other values that are not important for the matching, but should be included in the dataframe.
Desired output
The part of the dataframe where the values of the columns are not matching.
df = pd.DataFrame()
df['id'] = [1, 1]
df['col1'] = [10, 10]
df['col2'] = [100, 200]
df['col3'] = [1, 2]

A: You groupby and check the number of unique values for each value in col1 and if it is 1 you keep it:
df = df[(df.groupby(['id', 'col1'])['col2'].transform(lambda x: x.nunique()!=1))]
print(df)

id  col1  col2
2    20    50
2    20    50


text:
Q: Stopping a macports installed mysql daemon I'm trying to reset my root password on a macports installed MySQL on OS X. But none of the ways to do this that I can find works, for various reasons. One reason common to all is that I can't stop the mysql deamon.
As I understand it, I should be able to stop it with
sudo launchctl stop org.macports.mysql5

Which makes absolutely no difference. No error message, nothing. Is launchd really this sucky, or do I misuse it? Reasonably it should give me an error when it fails, but nope, nothing.
Trying to kill the processes with kill -9 just makes them restart again, so that doesn't work either.
I also tried
sudo launchctl unload org.macports.mysql5

But that gives me this error:
launchctl: Couldn't stat("org.macports.mysql5"): No such file or directory

(And I must confess I don't understand what "Unload configuration files and/or directories" means, which is what the Unload command apparently does according to the little docs I can find).
So, what now?

A: The correct answer is
sudo launchctl unload -w /Library/LaunchDaemons/org.macports.mysql5.plist

And you start it with
sudo launchctl load -w /Library/LaunchDaemons/org.macports.mysql5.plist

Thanks to kh13org for the pointer.


text:
Q: Sources of Entropy for Linux Let's say I want a gigabyte or so of random data from /dev/random, suitable for a one-time pad (so /dev/urandom is out.) How do I seed my /dev/random with enough entropy to do this? I am looking for specific commands and programs for this. I do not want to buy anything. I am using Arch Linux, if that makes a difference.

A: Unfortunately /dev/random is also not suitable for use in a one-time pad, at least not the kind of one-time pad (with provable security guarantees) that most people imagine when they think of or implement one-time pads. Most of the information below is summarized from the (very long) article at http://www.2uo.de/myths-about-urandom/
The problem is that /dev/random is not truly random; it uses a CSPRNG to generate its output. In fact, /dev/random uses the exact same CSPRNG as /dev/urandom. The only difference is that /dev/random blocks if its internal estimate of entropy is insufficient.
The word "estimate" in the previous sentence is key. Most people think that this estimate is always accurate and perfect, but in reality it's not at all accurate. The instant the estimate is wrong, you lose all the provable security guarantees of the one-time pad, and all you have left is computational security -- no better than if you had used /dev/urandom!
Getting the entropy estimate just a little bit wrong does not make your one-time pad just a little bit insecure. The provable security guarantee of a one-time pad is all or nothing.
The premise of this question is that the problems with /dev/random can be "fixed" by adding more entropy. Unfortunately, this premise is wrong. A malicious source of entropy is much worse than no entropy at all, because entropy sources often have access to internal data and can export this data covertly using RNG output -- see http://blog.cr.yp.to/20140205-entropy.html for a full discussion (too long to summarize here). In particular, a hardware source of entropy (as recommended by several other answers) is a very bad choice from a security perspective, since that hardware is in prime position to do malicious things, and it is essentially unauditable.

A: Two programs that can increase the entropy pool without requiring extra hardware are rng-tools and haveged. rng-tools uses RNGs available in modern CPUs and chipsets, haveged uses modern CPU randomness (cache behaviour etc.). Both are available in Arch, and the Arch wiki has an interesting page discussing them. I haven't tried using them to generate a gigabyte of data but it should be possible in a sensible amount of time.
You explicitly exclude buying anything, but just for completeness' sake there's an interesting article in LWN about entropy with NeuG, which includes discussion of haveged and various other approaches. You can buy an STM8S board capable of running NeuG for less than $10, or a FST-01 for $35.

A: Seems like an HW component is the best idea. There are some HW generator IC out there, but you have to trust them as they come.
Two probably good solution are to induce component to create noise; two major solution seems to be temperature bias and the avanche noise created with a diode (see http://web.archive.org/web/20061117145903/http://willware.net:8080/hw-rng.html)
As the components like gyro and accelerometer has becomed more sensible, making them work at highest sensitivity and using their LSB value can also a nice solution, but AFAIK nobody as audited it.
Is funny as there are a lot of paper on NOT do RNG, but not an HW implementation open and verified

A: You could use pycsprng.py.  Cryptographically secure?  I'm not quite sure, but I would like some peer-review.
python pycsprng.py | pv | dd of=data.file bs=1024 count=1000
The pipe to pv is optional, and will just help you know how much data has been transfered.
You may find that larger block-sizes (bs) increase perfomance.  You will have to adjust the count to not generate too large of a file if you increase the block-size.

A: What you get from an analog microphone channel when you don't plug in a microphone is usually just static.
Pipe that through bzip2, for example, for whitening, mix it with another source of randomness (urandom or another microphone jack), maybe pipe the result through openssl for good measure and what you get should be pretty random.
It would be difficult to prove any hard and fast security properties about the randomness of the result, though.

A: If you are using linux kernel 2.6.9 or newer on amd64 / x86_64 processor, virtual or physical environment, you may try ncomputers.org/pandom a true random number generator, that offers 8 KiB/s entropy of 64 ubits/64 bits through /dev/random

A: To generate 100 MB of hardware-generated random data, you can:

*

*Record 20 minutes of audio (96khz 16bit mono) with your computer's built-in microphone (available on a laptop). You will get a ~ 220 MB WAV file.

*Discard the non-useful bits, and shuffle the bits of binary data (many ways to do this) with some math

*Export the shuffled bits as a ~ 100 MB binary file
Here is an article about this: An attempt to generate true entropy and random data with audio (and your computer's built-in microphone).


text:
Q: What is the highest worth item to resell? I'm looking for the item that fetches the highest usual value (not counting "hot item" multiplier) in the Nook's Cranny general store. I.e., what sells higher than the expensive Nintendo Switch (worth 7,000 bells)?

A: Coelacanth, Great White Shark, Dorado and Stringfish sell for 15k bells each.

A: Found the whirlpool bath, which resells for 32,500 bells:

A: a crown sells for 250,000 bells and a royal crown sells for 300,000 bells


text:
Q: Using iFile to change lock screen passcode I would like to know where to go in iFile to be able to see your ipod passcode and be able to change the 4 digit code through iFile. I am running iOS 5.0.1.

A: It should be, is for sure in iOS6 and will ever be encrypted in future iOS versions. I doubt you can bypass the code.
However there is a securityleak in iOS 5 (since you have 5.0.1) I think you should check out this post online
The post contains this video, on how to bypass the lock. I hope that will help you out rather than changing the code via iFile.


text:
Q: Is there a WPF Control that can display my overview ? How can I use it? I am moving from a place with 2 rooms, to a place with 3 rooms.
I need an application that generates an overview regarding the stuff I need to move.
It needs to display for me, how many boxes need to be moved from one room to another.
Correction: (The boxes need to be items in general so I can do the same for say, plants)


text:
Q: How to export only part of a big mysql database We have a mysql database several GB in size. As we are developing on our local machines, we need a convenient way to export and import it.
We need to export only part of the whole DB. Is there a way to:
Select some range from table for instance customer an then select from other tables only rows that are pointed from or are pointing to the rows we just selected from the customer table and then recursively go deeper?
Or what are the other ways to accomplish exporting only part of the whole database in a way that it won't get corrupted?


text:
Q: Facebook Multiple Images upload I am trying to upload multiple images from my Application .
I would have array of images and i am using this code to upload all images . But while uploading my UI gets blocked if images are more . So Please suggest me How to start uploading in background or suggest me an alternate way ..
 HUD = [[MBProgressHUD alloc] initWithView:self.view];
HUD.labelText = @"Uploading Images";
[self.view addSubview:HUD];
[HUD show:YES];

NSMutableArray *aryFetchedImages = [self fetchPhotosForAlbum];

for (int i = 0; i < aryFetchedImages.count ; i++) {
    NSLog(@"img%d",i);
    [params setObject:@" " forKey:@"message"];
    [params setObject:UIImageJPEGRepresentation([aryFetchedImages objectAtIndex:i], 50.0f)  forKey:@"picture"];
    [FBRequestConnection startWithGraphPath:@"me/photos"
                                 parameters:params
                                 HTTPMethod:@"POST"
                          completionHandler:^(FBRequestConnection *connection,
                                              id result,
                                              NSError *error)
     {
         if (error)
         {
             //showing an alert for failure
            #ifdef DEBUG
                NSLog(@"Unable to share the photo please try later - Fail %@",error);
            #endif
         }
         else
         {
             //showing an alert for success
            #ifdef DEBUG
                NSLog(@"Photo %@ uploaded on Facebook Successfully",UIImageJPEGRepresentation([aryFetchedImages objectAtIndex:i], 50.0f));
            #endif
         }
     }];
}
[HUD show:NO];
[HUD removeFromSuperview];

A: I'm doing some modification in code please try this, and let me know
HUD = [[MBProgressHUD alloc] initWithView:self.view];
    HUD.labelText = @"Uploading Images";
    [self.view addSubview:HUD];
    [HUD show:YES];

    NSMutableArray *aryFetchedImages = [self fetchPhotosForAlbum];

    for (int i = 0; i < aryFetchedImages.count ; i++) {

    [self postImgWithMessage:[aryFetchedImages objectAtIndex:i];
    }

    [HUD show:NO];
    [HUD removeFromSuperview];

    //my code to be added

    -(void)postImgWithMessage:(UIImage *)image
    {
        NSArray *paths1 = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
        NSString *filePath =[[paths1 objectAtIndex:0] stringByAppendingPathComponent:@"image.png"];
        NSData *imageData = [NSData dataWithData:UIImagePNGRepresentation(image)];
        [imageData writeToFile:filePath atomically:YES];
        if (filePath == nil) return;
        NSURL *url = [NSURL URLWithString:@"https://graph.facebook.com/me/photos"];
        ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
        [request addFile:filePath forKey:@"file"];
        [request setPostValue:[userDefaults stringForKey:KToken] forKey:@"access_token"];
        [request setDidFinishSelector:@selector(sendToPhotosFinished:)];
        [request setDelegate:self];
        [request startAsynchronous];

    }

    - (void)sendToPhotosFinished:(ASIHTTPRequest *)request
    {
        //NSLog(@"photo sent");

    }

A: Dispatch queues let you execute arbitrary blocks of code either asynchronously or synchronously with respect to the caller. You can use dispatch queues to perform nearly all of the tasks that you used to perform on separate threads. The advantage of dispatch queues is that they are simpler to use and much more efficient at executing those tasks than the corresponding threaded code.Concurrency Programming Guide


text:
Q: Message database design in a chat app I'm working on a Chat App. You can chat with one person or create(join) a group. I'm considering how the database should be to store all messages.
I come up with two solutions:
Solution 1. Store all messages to one table;
Solution 2. Create a message database for every person or group that user joined.
Solution 1 is easy to achieve, but I don't know if it keep a good performance as the message grows.
The app runs on iOS and I'll use sqlite database. Any advice would be appreciated. Thanks in advance.

A: In general, having multiple tables with the same structure is one of the signs that your database is not properly normalized.
If you have separate tables, you cannot easily write queries that must look at multiple persons/groups, such as "With whom did I chat most often recently?"
Your database will grow either way.
You get efficient queries by not having to read all the data, which can be done by writing the queries correctly, and creating appropriate indexes.
See Query Planning, The SQLite Query Planner, and The Next Generation Query Planner.


text:
Q: Barcode using Java head less mode configuration In an application, for every order confirmation from customer side, an order confirmation mail is being sent to the customer.
So in that mail a barcode will be provided (barcode image and a barcode number under the image - as usual).
The following packages are used to achieve this.
org.krysalis.barcode4j., org.apache.avalon., javax.xml.transform.*
The problem is, X-vnc server(a port basically don't have much idea about this part) is what being used and it need to be removed due to some security reasons.
So the suggestions are to introduce JFreeChart or to Make use of java's headless mode configuration.
Can somebody tell me how I can make use of java's headless mode configuration for generating barcodes as JFreeChart is out of question from my investigation.
Note:- Barcode image is generated based on the order number. As order numbers are unique, the barcode images generated will also be unique.
EDIT
Thanks for the reply!
Application server which runs on Linux uses XVNC (Virtual screen based on X server) to act as virtual display. This is to support JVM to create barcode images.
So two things need to be achieved.

*

*Remove the xvnc dependency.

*Find an alternative for rendering the barcode image (headless mode may be not sure about this, so suggestions please  - Xvfb is not permitted though.

Note:- I could see a .Xauthority file of which I couldn't see the content, I am unable to open it. Any idea what this file will contain?
Many thanks in advance

A: In the article from Oracle you can find information about headless mode and how to convert an existing application to headless mode. It's a little bit old but it should work
http://www.oracle.com/technetwork/articles/javase/headless-136834.html