text:
Q: Hive: Partitioning by part of integer column I want to create an external Hive table, partitioned by record type and date (year, month, day). One complication is that the date format I have in my data files is a single value integer yyyymmddhhmmss instead of the required date format yyyy-mm-dd hh:mm:ss.
Can I specify 3 new partition column based on just single data value? Something like the example below (which doesn't work)
create external table cdrs (
record_id int,
record_detail tinyint,
datetime_start int
)
partitioned by (record_type int, createyear=datetime_start(0,3) int, createmonth=datetime_start(4,5) int, createday=datetime_start(6,7) int)
row format delimited
fields terminated by '|'
lines terminated by '\n'
stored as TEXTFILE
location 'hdfs://nameservice1/tmp/sbx_unleashed.db'
tblproperties ("skip.header.line.count"="1", "skip.footer.line.count"="1");

A: If you want to be able to use MSCK REPAIR TABLE to add the partition for you based on the directories structure you should use the following convention:

*

*The nesting of the directories should match the order of the partition columns.

*A directory name should be {partition column name}={value}

If you intends to add the partitions manually then the structure has no meaning.
Any set values can be coupled with any directory. e.g. -
alter table cdrs
add if not exist partition (record_type='TYP123',createdate=date '2017-03-22')
location 'hdfs://nameservice1/tmp/sbx_unleashed.db/2017MAR22_OF_TYPE_123';

Assuming directory structure -
.../sbx_unleashed.db/record_type=.../createyear=.../createmonth=.../createday=.../

e.g.
.../sbx_unleashed.db/record_type=TYP123/createyear=2017/createmonth=03/createday=22/

create external table cdrs
(
   record_id      int
  ,record_detail  tinyint
  ,datetime_start int
)
partitioned by (record_type int,createyear int, createmonth tinyint, createday tinyint)
row format delimited
fields terminated by '|'
lines terminated by '\n'
stored as TEXTFILE
location 'hdfs://nameservice1/tmp/sbx_unleashed.db'
tblproperties ("skip.header.line.count"="1", "skip.footer.line.count"="1")
;

Assuming directory structure -
.../sbx_unleashed.db/record_type=.../createdate=.../

e.g.
.../sbx_unleashed.db/record_type=TYP123/createdate=2017-03-22/

create external table cdrs
(
   record_id      int
  ,record_detail  tinyint
  ,datetime_start int
)
partitioned by (record_type int,createdate date)
row format delimited
fields terminated by '|'
lines terminated by '\n'
stored as TEXTFILE
location 'hdfs://nameservice1/tmp/sbx_unleashed.db'
tblproperties ("skip.header.line.count"="1", "skip.footer.line.count"="1")
;


text:
Q: If textfield is myTextField { condition } Is there a way we can do this in Swift?
var myTextfield: UITextfield

if textfield is myTextField {
   condition
}

I have tried and failed:
if UITextfield = myTextField
if textfield = myTextField
if UITextfield.type = myTextField

Also have tried "==" as comparison operator.

A: From Apple Documentation:

Swift also provides two identity operators (=== and !==), which you
  use to test whether two object references both refer to the same
  object instance.

A: Try the below
import UIKit

class ViewController: UIViewController, UITextFieldDelegate{

    //@IBOutlet weak var nameTF: UITextField! { didSet { nameTF.delegate = self } }
    //@IBOutlet weak var nameTF2: UITextField! { didSet { nameTF.delegate = self } }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        print("test")

        var myTextField: UITextField = UITextField(frame: CGRect(x: 0, y: 10, width: 200.00, height: 40.00));
        self.view.addSubview(myTextField)
        myTextField.backgroundColor = UIColor.redColor()
        myTextField.text = "some string"
        myTextField.borderStyle = UITextBorderStyle.Line
        myTextField.tag = 1
        myTextField.delegate = self

        var myTextField2: UITextField = UITextField(frame: CGRect(x: 0, y: 200, width: 200.00, height: 40.00));
        self.view.addSubview(myTextField2)
        myTextField2.backgroundColor = UIColor.redColor()
        myTextField2.borderStyle = UITextBorderStyle.Line
        myTextField2.tag = 2
        myTextField2.delegate = self

    }

     func textFieldDidBeginEditing(textField: UITextField) {
        if (textField.tag == 1 ) {
            print("first text field")
        }

        if (textField.tag == 2)
        {
            print("second text field")
        }

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to assign a value to texbox inside a gridview as itemTemplate i have a gridview with a item Template with a textbox, so i create a datatable in memory and assign to the gridview, but the values doesn't assign to the textbox in the item template.
How i assign a value of my datatable to the control inside grid.
grdNotas.Rows(numero).Cells(2).FindControl("txtf1")

doesn't put the property of text.
Dim tbnotasAlumnos As New DataTable

    For Each fila As DataRow In tbAlumnnoCurso.Rows
        tbnotasAlumnos = conexion.consultaNotaMateriaAQP(tbAlumnnoCurso.Rows(numero)(0).ToString, ddlmaterias.SelectedValue, txtQuimestre.Text, txtparcial.Text)
        'fill the textboxes
        grdNotas.Rows(numero).Cells(2).FindControl("txtf1")
        numero = numero + 1
    Next

how i can do it?

A: You need not only to find the control, but also to cast it to specific type. That will give you an access to textbox's properties
Dim txt As TextBox = CType(grdNotas.Rows(numero).Cells(2).FindControl("txtf1"), TextBox)
txt.Text = "value"


text:
Q: Unable to start windows As you can see from my question I'm really noob with Ubuntu. I have installed my Ubuntu on my computer. I was thinking that I will be able to make choice between Ubuntu and Windows after reboot the system. Now seems like I made a mistake.
I will try to explain what exactly I did:
Under Windows operating system I made a separate disk for Ubuntu. I run the installation files for Ubuntu from the USB. I select the drive which I made before for Ubuntu and then I selected file system ext4.
The device for boot loader installation I choose the same drive that I have made for the operating system Ubuntu. Probably here is the problem but I'm not sure.
I have to inform you also that my Windows system was using also "system reserved" although inside of the drive I couldn't find any saved files.
Probably is important to know also that when I start the installation wizard for Ubuntu the system was unable to find any other operation system in my machine although that I had installed Windows already.
I tried to use boot-repair-disk but I couldn't start because I need to make a bootable USB with the ISo but unfortunately I can't start UNetbootin.
I hope that you can understand what I mean even with my bad English.
Regards!

A: you can recover your windows using windows CD or Bootable USB. if you do not overwrite alredy.
if you have windows 8 or 7 CD than you can recover your windows.
for this you have to follow this steps.
Boot from the Windows install or repair CD appropriate to you version of Windows.
For Windows 8 or 7:
1 – Boot from repair disc > Choose Keyboard type > click Troubleshoot > click Advanced options > choose Automatic Repair
if that fails then use:
2 -Boot from Recovery disc or Install disc
-Boot from repair disc > Chose Keyboard type > click Troubleshoot > click Advanced options > choose Command Prompt
or
-Boot from Install disc > Click Next > click Repair your computer > click Troubleshoot > click Advanced options > choose Command Prompt
type > bootrec /fixmbr (writes mbr but does not overwrite partition table)
type > bootrec /fixboot (writes new boot sector to system partition)
type > bootrec /scanos (scans for other OS's that you might want to add to bcd)
(personally I find the above unneeded and only use the last step)
type > bootrec /rebuildbcd (scans for other OS's, unlike rebuildbcd it allows you to select the OS's you want to add to bcd)
Reboot
i hope that will work for you.

A: *

*Boot Ubuntu

*Open a terminal Ctrl+Alt+T

*Edit the file /etc/defaut/grub: sudo nano /etc/default/grub

*Change the line GRUB_TIMEOUT=0 to any value you like. The number you give here is how long this menu should be shown (in seconds) before booting the default entry, e.g. GRUB_TIMEOUT=10 for 10 seconds. If you want the menu to stay infinitely, until you select something, set the line to GRUB_TIMEOUT=-1.

*Save with Ctrl+O and exit with Ctrl+X.

*Run sudo update-grub another time.

The next time you boot, the menu will show up for the time span you set in step 4.


text:
Q: Images, sizes and different screens (fragmentation) I have a logo to put in a splashscreen. Currently, the image size is 960x320 pixels. I have read the developers google post, of the supported screens, but I don't have any idea of what size need to be in a ldpi, mdpi, hdpi or xhdpi.
I see a table in another answer that says:
ldpi x0.75
mdpi x1.00
hdpi x2.00

I don't know if this is true or not. Could someone shed some light? ^^

A: You can use android dpi (http://coh.io/adpi/) calculator to calculate image size for different resolution

A: So take 960x320 as your base density (1x = mdpi).
To get to the other ones you multiply the base size by the other sizes.
So to get to hdpi multiply you base by 1.5, 960x320:
960 x 1.5 = 1440
320 x 1.5 = 480

This applies from your base density which is generally mdpi.
ldpi = 960 x 0.75 and 320 x 0.75
mdpi = 960 x 1.0 and 320 x 1.0
hdpi = 960 x 1.5 and 320 x 1.5
xhdpi = 960 x 2.0 and 320 x 2.0
xxhdpi = 960 x 3.0 and 320 x 3.0

And so forth. Generally its best to use a calculator until you understand in more detail why they need to be like that.


text:
Q: javascript countdown lagging because of ajax calls I use a javascript song countdown on my radio website.
At every 10 seconds, the countdown lags (skipping 1 one more seconds), because of an ajax call to check if there's a new song:
function getcursong(){
  var result = null;
  var scriptUrl = "get_current_song.php";
  $.ajax({
    url: scriptUrl,
    type: 'get',
    dataType: 'html',
    async: false,
    success: function(data) {
        result = data;
    }
  });
  return result;
}

Looking in the console, I see that the GET call takes about 2 seconds.
get_current_song.php uses curl to get the current song from the icecast server.
Is there something I can do to prevent the countdown from lagging because of those ajax calls?
Below is get_current_song.php.
<?php
require('config.php');
$current_song = getStreamInfo();
function url_get_contents($Url) {
    if (!function_exists('curl_init')){
        die('CURL is not installed!');
    }
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $Url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch,CURLOPT_TIMEOUT,2);
    $output = curl_exec($ch);
    curl_close($ch);
    return $output;
}
function getStreamInfo(){
    $str = url_get_contents(SERVER.'/status.xsl?mount='.MOUNT);
    if(preg_match_all('/<td\s[^>]*class=\"streamdata\">(.*)<\/td>/isU', $str, $match)){
        $x = explode(" * ",$match[1][9]);
        return $x[1];
    }
}
?>
<?php
    echo $current_song;
?>

A: I assume that async: false is hijacking your countdown function. Do you need it to be false?

A: function ()
{
 var result = null;
 var scriptUrl = "get_current_song.php";
 $.ajax({
    url: scriptUrl,
    type: 'get',
    dataType: 'html',
    async: true,  // NEEDED TO BE TRUE
    success: function(data) {     // on success, I get the data
        song = $('#song').html();
        if (data != song && data != ""){
            setTimeout(function (){ $('#nowplaying').load('nowplaying.php'); }, 5000); // pourquoi fadeIn("slow"); ?!?
        }
    }
 });
}, 10000);


text:
Q: Reliable Excel API for handling complex Excel report (parsing & writing ~10,000 lines) that works with Java i know some similar question already exists, but I haven't found any satisfying answer yet.
I found several library such as Apache POI and JExcelAPI, however as I don't have any previous experience with any Java Excel API yet, perhaps some of you guys who experienced it before can enlighten me regarding the advantages and disadvantages of each API. My requirements are reliability and ease-of-use, because I have to parse and write numerous excel reports with ~10,000 lines in each file.
I'm also considering JXLS which can parse and write document using template to minimize coding effort, but based on my test, we have to hard-code the startRow and endRow when parsing (the startRow and endRow for my document is different for each file).

A: Actually, even the old versions of POI will support 10,000 rows - the limitation was either ~32000 or ~64000 rows.
But the latest POI supports the XML file formats for 2007, and therefore I'm sure memory will be your only limitation.
I use POI in a corporate application, and I've never had a problem with it.

A: Aspose.Cells for Java allows you to create or parse large Excel files in Java applications. The API is simple along with complete documentation and support. A large number of users have already incorporated it in their applications. It is easy to learn and any questions can be answered quickly through our support forum. You may try this and see if it helps in your scenario.
Disclosure: I work as developer evangelist at Aspose.

A: I've used JExcel with great success, although I can't say that any of those files were on the order of 10,000 rows per file.
I'd wonder if you'd be better off with a relational database with this volume of data.  Excel might have been a fine way to start, but maybe it's time to ask yourself if you've outgrown spreadsheets.


text:
Q: How to run background code in a asp.net-mvc/wcf app Based on this answer here, I need to put emails in a queue and have a background task run and send them. How do I do this with an architecture that is of ASP.NET-MVC and WCF?

*

*How do I build a queue (sql server)?

*How do I build a background task?

A: I think your solution is independant of the fact you're using MVC.
The way I've implemented this in the past is to persist the fact you need to sent an e-mail into the database and then process this using a Windows Service.
Another way to do this would be to utilize MSMQ as your storage medium. In general, MSMQ shouldn't be used to "store" data, only as a message transport mechanism, but it's certainly an option in this case.
In terms of developing a "queue", if the e-mails need ordered delivery for some reason, simply having a "RequestedDTTM" column in your database table would allow you to send them in the order they were requested.
Lastly, I would consider implementing a simply multi-threaded e-mail sender to maximize performance. Using the TPL in .NET 4.0 would make this pretty easy. Alternatively, you could use something like the SmartThreadPool library (available at codeplex.com) to manager your e-mail sender threads.
As was mentioned in the other answer you linked to, your UI shouldn't be doing this e-mail sending.

A: You can skin this cat many different ways.  The key being that the actual sending of the emails is asynchronous to the queuing of the email.

*

*Queue messages via WCF Service using MSMQ binding via this series of blog posts, which assumes IIS 7: MSMQ, WCF, and IIS: Getting Them to Play Nice.

*Queue messages to MSMQ.  MSMQ is a nice (sometimes underutilized) queue service built into Windows.  You'll write a Windows service to receive messages from this queue.  If you have IIS 7, then check out Death to Windows Services, Long Live AppFabric.  MSMQ is a breeze, but has some quirky constraints (4MB message size and availability)

*Queue messages to a 'sql queue'.  Create a table to hold basic queued message information and then stored procedures to wrap the queue semantics (e.g. you don't want multiple consumers to receive the same message).  Not difficult, but a little time consuming to get right.

*Queue messages to Service Broker (or even MSMQ) and write a Windows service that receives messages from the Service Broker Queue.  Service Broker handles the queueing semantics (competing consumers) for you.  The downside is that its a pain in the ass to administer.

HTH,
Z


text:
Q: Replacing a string using SQL Server Replace function - string has more than 4000 characters - what to do? I have a table, where I need to replace some values in a column.
The database is running on SQL Server 2005.
The problem is that some of the rows contain more than 4000 characters, which is giving the REPLACE function some trouble, since it demands that I cast the first parameter to the datatype NVARCHAR, and therefore any characters exceeding 4000, is being truncated.
Is there any workaround for this, other than writing an application that handles this issue?
The query in question is:
SELECT
   Replace(cast([Database].[dbo].[fruits].[Tekst] as NVARCHAR(MAX)), 'bananas', 'apples')
FROM [Database].[dbo].[fruits]

The column fruits is of datatype Text
Any input appreciated.

A: I suspect that you have just hit the limit for an individual value in SSMS.
Annoyingly it doesn't allow you to set this to be unlimited and the only way I know of displaying long text is via casting to XML as below.
select
(select Replace(cast([Database].[dbo].[fruits].[Tekst] as NVARCHAR(MAX)),'bananas','apples')  AS [processing-instruction(x)] FOR XML PATH(''), TYPE)
FROM [Database].[dbo].[fruits]

A: This demonstrates how REPLACE can handle longer string
SELECT CAST(REPLICATE(N'abc', 4000) AS nvarchar(MAX)) +
               REPLICATE(N'def', 4000)  +
               REPLICATE(N'abc', 4000)

SELECT LEN(
       CAST(REPLICATE(N'abc', 4000) AS nvarchar(MAX)) +
               REPLICATE(N'def', 4000)  +
               REPLICATE(N'abc', 4000)
       ) --11997

SELECT REPLACE(CAST(REPLICATE(N'abc', 4000) AS nvarchar(MAX)) +
               REPLICATE(N'def', 4000)  +
               REPLICATE(N'abc', 4000), 'def', 'ddeeff')

SELECT LEN(
       REPLACE(CAST(REPLICATE(N'abc', 4000) AS nvarchar(MAX)) +
               REPLICATE(N'def', 4000)  +
               REPLICATE(N'abc', 4000), 'def', 'ddeeff')
       ) --15996


text:
Q: PHP Curl to form this Post Request Can someone help me in forming this following POST request in PHP CURL ?
As mentioned in this URL : https://developer.amazon.com/public/apis/experience/cloud-drive/content/nodes
 curl -v -X POST --form
 'metadata={"name":"testVideo1","kind":"FILE"}' --form
 'content=@sample_iTunes.mp4'
 'https://content-na.drive.amazonaws.com/cdproxy/nodes?localId=testVideo1&suppress=deduplication'
 --header "Authorization: Bearer
 Atza|IQEBLjAsAhQ5zx7pKp9PCgCy6T1JkQjHHOEzpwIUQM"

this is what am trying... i want to form the above mentioned type curl request to the amazon server so i can upload a file into it. as there is no examples available am struck in this... can someone helps on this ?
            $fields = array(
                'multipart' => array(
                    'name' => 'testupload',
                    'content' => array(
                        'kind' => 'FILE',
                        'name' => 'hi.jpg',
                        'parents' => $parents
                        )
                )
            );

        $fields_string = json_encode($fields);

        //open connection
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $contenttype);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, 1);
            curl_setopt($ch, CURLOPT_POST, count($fields));
            curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);

        $result = curl_exec($ch);
        $httpstatus = curl_getinfo($ch, CURLINFO_HTTP_CODE);

A: You're almost there.
Add this on the curl code.
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);

This will able to access the url using SSL/HTTPS.


text:
Q: Haskell is throwing the 57 - Undefined variable "f" error at me I've got a quick question. Haskell is throwing the 57 - Undefined variable "f" error at me and I've no idea why. I'd appreciate it if you could have a look at this.
Code:
eval :: Expr -> Environment -> Float
eval expr env = eval' expr
    where
    eval' :: Expr-> Float
    eval' (Num num) = num
    eval' (App app exprs) = foldl1 (f) (map eval' exprs) -- **Line 57**
    eval' (Id id) = 5
        where
        f = getFunctionForApp app                    -- **f is here**
        getFunctionForApp :: String -> (Float->Float->Float)
        getFunctionForApp "+" = (+)
        getFunctionForApp "-" = (-)
        getFunctionForApp "*" = (*)
        getFunctionForApp "/" = (/)
        getIdVal :: String -> Environment -> Float
        getIdVal id ((curId, val):envrs)
            |curId == id = val
            | otherwise = getIdVal id envrs

Type definition:
data Expr = Num Float | Id String | App String [ Expr ]
           deriving (Eq, Ord, Show)
type Environment = [ ( String, Float ) ]

A: I can't really say it, but after trying to decrypt the code I guess you meant the following:
eval :: Expr -> Environment -> Float
eval expr env = eval' expr
    where eval' :: Expr -> Float
          eval' (Num num) = num
          eval' (App app exprs) = foldl1 (f) (map eval' exprs)
              where f = getFunctionForApp app -- that has to be in this line
          eval' (Id id) = 5

(Now with the formatted code I'm sure that's it. where clauses only work for the line immediately before the clause)

A: The problem is that the inner where clause attaches to the line
eval' (Id id) = 5

but it's needed for the line above
eval' (App app exprs) = foldl1 (f) (map eval' exprs) -- **Line 57**

In general, each line of a function definition has its own scope. A where clause may refer to pattern variables from the line it's attached to, and scopes over only the remainder of that line.


text:
Q: Is it possible for me to instantiate the Journal Article object and set each property without constuctor? When I do this it doesn't compile when I run build.xml and deploy,
I want to do this as it looks much nicer than a huge method call with JournalArticleLocalServiceUtil.addArticle.
JournalArticle journalArticle = new JournalArticleImpl();
journalArticle.setDescription(description);

Does anyone know if it is possible in Liferay 6?
Edit: This is the output I get:
Buildfile: C:\opt\liferay-six1-dev\code\portlets\migration-portlet\build.xml
compile:
merge:
compile-java:
    [javac] Compiling 1 source file to C:\opt\liferay-six1-dev\code\portlets\migration-portlet\docroot\WEB-INF\classes
    [javac] C:\opt\liferay-six1-dev\code\portlets\migration-portlet\docroot\WEB-INF\src\com\liferay\migration\importdata\JournalArticleImport.java:138: cannot find symbol
    [javac] symbol  : class JournalArticle
    [javac] location: class com.liferay.migration.importdata.JournalArticleImport
    [javac]     private JournalArticle createJournalArticle(ExportedJournalArticle article) {
    [javac]             ^
    [javac] C:\opt\liferay-six1-dev\code\portlets\migration-portlet\docroot\WEB-INF\src\com\liferay\migration\importdata\JournalArticleImport.java:142: cannot find symbol
    [javac] symbol  : class JournalArticle
    [javac] location: class com.liferay.migration.importdata.JournalArticleImport
    [javac]         JournalArticle journalArticle = new JournalArticleImpl();
    [javac]         ^
    [javac] C:\opt\liferay-six1-dev\code\portlets\migration-portlet\docroot\WEB-INF\src\com\liferay\migration\importdata\JournalArticleImport.java:142: cannot find symbol
    [javac] symbol  : class JournalArticleImpl
    [javac] location: class com.liferay.migration.importdata.JournalArticleImport
    [javac]         JournalArticle journalArticle = new JournalArticleImpl();
    [javac]                                             ^
    [javac] 3 errors

BUILD FAILED
C:\opt\liferay-six1-dev\code\build-common-plugin.xml:403: The following error occurred while executing this line:
C:\opt\liferay-six1-dev\code\build-common.xml:94: Compile failed; see the compiler error output for details.

Total time: 1 second

A: As Jon mentions the library/jar for the implementation classes are not copied if you're using the Plugins SDK. Unfortunately you are not allowed to create the JournalArticle object directly from a plugin and you must use the JournalArticleLocalServiceUtil to have the object created.

A: Okay, now that we've got the compiler failure, it looks like you just haven't got the right libraries on the classpath.
Also, it looks like you're creating your own classes under the com.liferay package - you shouldn't be doing that unless you're building code for Liferay. If you're only building code which uses Liferay, you should be building it under your own organizational package.


text:
Q: What are the difference between void function and float function? I am still learning but... I don't think these functions:
void CalculateGross(float hours, float payrate, float *gross) //3.4
float CalculateGross(float hours, float payrate)              //3.4

do the same thing. So which is better practice? I'm assuming void is better?
/*

    3.0 Payroll Application

      3.1 PrintReportHeadings(inout reportFile as file)
      3.2 InitializeAccumulators(out totreg, totovt,totpayrate,totgross,totfed,
                                     totstate,totssi,totdefr, totnet as real)
      3.3 InputEmployeeData(out lastname, firstname as string,
                            out hours, payrate, defr as real)
      3.4 CalculateGross(in hours, payrate as real, out gross as real)
      3.5 computeTaxes(in g,d as real, out ft, st, ssit as real)
        3.5.1 cFed(in g,d as real, out fed as real)
        3.5.2 cState(in ft as real,out state as real)
        3.5.3 cSSI(in g,d as real, out ssi as real)
      3.7 PrintSummaryReport( ......)
     3.7.1 printTotals( ....)
     3.7.2 printAverages( ....)

*/

#include <stdio.h>
#include "TAXRATES.h"

void InputEmployeeData(char *lastname,char *firstname, // 3.3
                       float *hours,float *payrate, float *defr);
void CalculateGross(float hours, float payrate, float * gross); //3.4
float CalculateGross(float hours,float payrate); //3.4
extern void computeTaxes(float g,float d,float * ft,float *st,float *ssit); //3.5

int main(void)
{
    char ln[15+1];
    char fn[10+1];
    float fed,state,ssi;
    float g,h,p,d,n;

    InputEmployeeData(&ln[0],&fn[0],&h,&p,&d); // call 3.3
    g =  CalculateGross(h,p); // call 3.4
    // vs
    //CalculateGross(40.00,25.00,&g); // alternate call 3.4
    computeTaxes(g,d,ADDR(fed),ADDR(state),ADDR(ssi)); // call 3.5
    n = g-fed-state-ssi-d;
    printf("  Fed   =   %8.2f\n",fed);
    printf("  State =   %8.2f\n",state);
    printf("  SSI   =   %8.2f\n",ssi);
    printf("  Net   =   %8.2f\n",n);
    while(getchar() != '\n'); // flush(stdin)
    return 0;
}

void CalculateGross(float hours, float payrate, float * gross) //3.4
{
if (hours <= 40)
    *gross = hours * payrate;
  else
    *gross = 40* payrate + 1.5 * payrate * (hours-40);

}

float CalculateGross(float hours,float payrate) .. //3.4
{
  if (hours <= 40)
    return hours * payrate;
  else
    return 40* payrate + 1.5 * payrate * (hours-40);
}

void InputEmployeeData(char *lastname,char *firstname, // 3.3
                       float *hours,float *payrate, float *defr)
{
    printf(" Enter the name ==> ");
    scanf("%s%s",firstname,lastname);
    printf(" Enter the hours and payrate ==> ");
    scanf("%f%f",hours,payrate);
    printf("  Enter the deferred earning amount ==> ");
    scanf("%f",defr);
}

A: Functions should have input(s) and a single output. Void says do something. Pointers are great, but the intent is to calculate something. Use f(x) = y, not f(x, out y) when possible, of course.

A: void CalculateGross(float hours, float payrate, float * gross); //3.4
float CalculateGross(float hours,float payrate); //3.4

where:
void CalculateGross(float hours, float payrate, float * gross) //3.4
{
if (hours <= 40)
    *gross = hours * payrate;
else
    *gross = 40* payrate + 1.5 * payrate * (hours-40);

}

Here - it does NOT have any effect on your code. (you will get warnings.. but no impact) Why? The type before the function name defines the type of return for the function. What you get back if you do:
foo = CalculateGross (....);

Since CalculateGross does not return any value (it only operates on values internally), the return type has no impact anywhere else.
Which is correct? That is a different question. void is correct for all function where no value is returned. When you specify float, the compiler will check your function for return somevalue;. If not found it will generate a warning (or error).
So, if your function returns a value (or pointer), match the type to the type the function returns. If your function returns nothing, void is the proper return type.
Note: just because you declare a function void does not mean you cannot use return within the void function. You can use return; by itself to cause to function to return (bail out) at that point without returning a value.


text:
Q: Accessing fields of Tuples I have the following pig Script:
My file 1.txt has
A 1
B 2
C 3
D 4
grunt> A = load '1.txt' using PigStorage(' ') as (a:chararray,b:int);
grunt> B = foreach A generate A.a;
grunt> dump B;

It gives me the following error
ERROR org.apache.pig.tools.grunt.Grunt - ERROR 2997: Unable to recreate exception from backed error: org.apache.pig.backend.executionengine.ExecException: ERROR 0: Scalar has more than one row in the output. 1st : (A,1), 2nd :(B,2)

A: You don't have to reference a as A.a. Try this instead:
grunt> A = load '1.txt' using PigStorage(' ') as (a:chararray,b:int);
grunt> B = foreach A generate a;
grunt> dump B;

C.x is for grabbing a "column" out of a bag. Say C is a bag of items, then C.x will create a new bag of all of the x's in that bag. That's not what you want here. The foreach is iterating through the bag here for you.


text:
Q: Clear Row Data Based on Value in Google Sheet ( Specific Data ) appscript I am looking for a base on value clear specific row content/data and then hide row.
type value "Done" in { F Col } Clear Value of { E , C Col }
when everything  is done then hide row.

function ClearContentThenHideRow() {
  var s = SpreadsheetApp.getActive().getSheetByName('Main');
  s.showRows(1, s.getMaxRows());

  s.getRange('F:F')
    .getValues()
    .forEach( function (r, i) {
    if (r[0] == 'Done')
      //sheet.getRange(["C:C","E:E"]).clearContent(); // clear content not working
      s.hideRows(i + 1);
    });
}

A: Modification points:

*

*About sheet.getRange(["C:C","E:E"]).clearContent();,

*

*sheet is not declared.

*When you want to use the range list, please use getRangeList().

*When s.getRange('F1:F' + s.getLastRow()) is used instead of s.getRange('F:F'), I thought that the process cost will be able to be reduced a little.

When above points are reflected to your script, it becomes as follows.
Modified script:
function ClearContentThenHideRow() {
  var s = SpreadsheetApp.getActive().getSheetByName('Main');
  // s.showRows(1, s.getMaxRows()); <--- removed
  s.getRange('F1:F' + s.getLastRow())
    .getValues()
    .forEach(function (r, i) {
      if (r[0] == 'Done') {
        s.getRangeList(["C" + (i + 1), "E" + (i + 1)]).clearContent();
        s.hideRows(i + 1);
      }
    });
}

Reference:

*

*getRangeList(a1Notations) of Class Sheet


text:
Q: ESP32 ULP Coprocessor doesn´t wakeup from time My application should initialize the ULP coprocessor and the coprocessor should observe one GPIO. The ULP Timer should wake up the coprocessor in certain intervals and then the coprocessor should check the GPIO and turn on an LED, depending on the state of the GPIO.
I use the following code:
main.cpp
#include <soc/timer_group_reg.h>
#include <soc/timer_group_struct.h>

#include <freertos/FreeRTOS.h>
#include <freertos/task.h>
#include <freertos/event_groups.h>

#include "utils/ulp_utils.h"
#include "shared/shared_Debug.h"
#include "shared/shared_ResetCause.h"

#include <ulp_main.h>

extern "C" void app_main()
{
    if(ResetCause_isPowerOnReset())
    {
        DEBUG_INFO("Power-On-Reset occured!\n");

        DEBUG_INFO("Load ULP program...\n");
        ESP_ERROR_CHECK_WITHOUT_ABORT(ulp_load_binary(0, ulp_main_bin_start, (ulp_main_bin_end - ulp_main_bin_start) / sizeof(uint32_t)));
    }
    else if(ResetCause_isDeepSleepReset())
    {
        DEBUG_INFO("Deep sleep Reset occured!\n");

        DEBUG_INFO("Boot counter: ");
        DEBUG_INFO("{%u}\n", (uint16_t)ulp_Status);

        // TODO: Starting application
    }
    else
    {
        DEBUG_INFO("Unknown reset!\n");

        ResetCause_Print(rtc_get_reset_reason(0));
        ResetCause_Print(rtc_get_reset_reason(1));
    }

    // Start the execution of the ULP code
    DEBUG_INFO("Start ULP program...\n");
    ESP_ERROR_CHECK_WITHOUT_ABORT(ulp_run(&ulp_entry - RTC_SLOW_MEM));

    // Enable wake up from ULP and enter sleep mode
    DEBUG_INFO("Enter deep sleep...\n");
    ESP_ERROR_CHECK_WITHOUT_ABORT(esp_sleep_enable_ulp_wakeup());
    esp_deep_sleep_start();
}

ulp.S
#include "soc/soc_ulp.h"
#include "soc/sens_reg.h"
#include "soc/rtc_io_reg.h"
#include "soc/rtc_i2c_reg.h"
#include "soc/rtc_cntl_reg.h"
// The LED is connected on RTC GPIO 6
.set    LED,    6

// The input is connected on RTC GPIO 14y
.set    INPUT,   14

.bss
.global Status
Status:
    .long 0

.text

/** @brief Main entry point for the ULP coprocessor application.
 */
.global entry
entry:
    // Enable the ULP Timer
    WRITE_RTC_FIELD(RTC_CNTL_STATE0_REG, RTC_CNTL_ULP_CP_SLP_TIMER_EN, 1)

    // RTC GPIO 6 is used by the DAC. Enable the GPIO functionality
    WRITE_RTC_REG(RTC_IO_PAD_DAC1_REG, RTC_IO_PDAC1_MUX_SEL_S, 1, 1)

    // Set GPIO 6 as output
    WRITE_RTC_REG(RTC_GPIO_ENABLE_W1TS_REG, RTC_GPIO_ENABLE_W1TS_S + LED, 1, 1)

    // Set GPIO 13 as input
    WRITE_RTC_REG(RTC_GPIO_ENABLE_W1TC_REG, RTC_GPIO_ENABLE_W1TC_S + INPUT, 1, 1)

    // Read the state of the input pin
    READ_RTC_REG(RTC_GPIO_IN_REG, RTC_GPIO_IN_NEXT_S + INPUT, 1)

    // Save the result
    move    r3, Status
    st      r0, r3, 0

    // Compare the result
    and     r0, r0, 1
    jump    LED_Off, eq
    jump    LED_On

LED_On:
    WRITE_RTC_REG(RTC_GPIO_OUT_W1TS_REG, RTC_GPIO_OUT_DATA_W1TC_S + LED, 1, 1)

    // Wait for 5 seconds
    move    r1, 5000
    move    r2, WakeUp
    jump    Delay_ms

LED_Off:
    WRITE_RTC_REG(RTC_GPIO_OUT_W1TC_REG, RTC_GPIO_OUT_DATA_W1TC_S + LED, 1, 1)

    // Wait for 5 seconds
    move    r1, 5000
    move    r2, Exit
    jump    Delay_ms

/** @brief Disable the coprocessor and wake up the main processor cores.
 */
.global WakeUp
WakeUp:
    // Test if the main processor cores can be woken up by the coprocessor. Leave without wakening up the processor when the function is not enabled.
    READ_RTC_FIELD(RTC_CNTL_LOW_POWER_ST_REG, RTC_CNTL_RDY_FOR_WAKEUP)
    and     r0, r0, 1
    jump    Exit, eq

    // Wake up the main processor cores
    wake

    halt

/** @brief Exit the ULP coprocessor application, power down the coprocessor and restart the wake-up timer.
 */
.global Exit
Exit:
    halt

/** @brief      Delays the program execution by n milliseconds.
 *  @param r1   Delay time in milliseconds
 *  @param r2   Return address
 */
Delay_ms:
    // Wait for 8000 cycles (1 ms @ 8 MHz)
    wait    8000

    // Reduce the counter by one
    sub     r1, r1, 1

    // Jump to the address stored in "r2" if the last ALU operation was zero
    jump    r2, eq

    jump    Delay_ms

The ESP gets woken up by the coprocessor as long as the GPIO is high (also the LED is active), but the LED doesn´t light up again after I change the state of the GPIO back from low to high.

A: Just a tip, I don't know if this is the root cause, but I guess in this line  RTC_GPIO_OUT_DATA_W1TS_S should be with S instead of C:
LED_Off:
WRITE_RTC_REG(RTC_GPIO_OUT_W1TS_REG, RTC_GPIO_OUT_DATA_W1TC_S + LED, 1, 1)


text:
Q: Equals Method False For the same objects import java.io.*;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

        Dog dog1 = new Dog();
        Dog dog2 = new Dog();

        System.out.println(dog2.equals(dog1));

    }

    public static class Dog{

    }
}

The objects are the same, but equals method says its false. Why? Is it not true? Class is empty. Thanks in advance

A: I would advise you to see the documentation: https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#equals(java.lang.Object)

The equals method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any non-null reference values x and y, this method returns true if and only if x and y refer to the same object (x == y has the value true).

Because you have not overridden the .equals(Object) method and provided a looser equivalence test, the super-class (i.e., the Object class) version of .equals(...) is called. Because dog1 and dog2 refer to different objects occupying different memory space, by default, they are not equivalent. You must supply your own equivalence test to overcome this.

A: If you don't override the equals method of your Dog class, it falls back on the one from the Object class, that compares object's addresses. You have two instances of Dog, so two different addresses, so they're not equal.

A: You should read the javadoc on the Object equals method.  These objects are not the same by default behavior of the method; you would need to override it to have it return true.

A: The class Dog does not override the default equals method so the default will apply (which is basically ==) and as dog1 and dog2 are two separate instances of Dog this will be false.
If you want to be able to discriminate in a different way, you should override the equals method and put your comparison logic in it.

A: Everytime you use new keyword while initializing, it means new instance. And two different object instances can be equal or not, depending upon equal definition of your class. The default equals method definition compares memory addresses, which would be different in this case.


text:
Q: Azure Key Vault Service to store credentials My Azure PaaS service supports authenticating directly with OAUTH (Event Hub).
How do you distribute the credentials for this securely to Confidential Clients?
Sorry i'm new to Cloud Development.

A: As you mentioned, you can use Azure keyvault to store the client secret of your Azure AD App Registration.
Just add the client app/user account to the Azure keyvault Access Policy with the correct permission, then only them can access your azure keyvault to retrieve the client secret.
Update:
You need to create a new Azure AD App Registration used to access the keyvault(this AD App is just to access keyvault, not access to eventhub), store its client id and secret as the environment variables, then use the SDK to get the secret. After that, use ClientSecretCredential to access eventhub.
TokenCredential credential = new ClientSecretCredential("<tenantId>", "<clientId>", "<clientSecret>");

var fullyQualifiedNamespace = "<< FULLY-QUALIFIED EVENT HUBS NAMESPACE (like something.servicebus.windows.net) >>";
var eventHubName = "<< NAME OF THE EVENT HUB >>";

await using (var producer = new EventHubProducerClient(fullyQualifiedNamespace, eventHubName, credential))
{
    using EventDataBatch eventBatch = await producer.CreateBatchAsync();
    eventBatch.TryAdd(new EventData(new BinaryData("First")));
    eventBatch.TryAdd(new EventData(new BinaryData("Second")));

    await producer.SendAsync(eventBatch);
}

Reference - Using an Active Directory principal with the Event Hub clients
Note: Actually, if your code will be deployed to the Azure service that supports Managed Identity(MSI), e.g. Azure App service, VM, etc, the best practice is to use MSI to auth eventhub, no need to create the AD Apps and use their client secrets, neither the keyvault.
Reference - Authenticate a managed identity with Azure Active Directory to access Event Hubs Resources


text:
Q: NavigationView.setNavigationItemSelectedListener Not working I post this message because I realy search a solution but nothing works.
I try to get an interaction with the item in the menu on a Navigation Drawer Layout.
I work on Android Studio and I picked the base tamplate for Navigation Drawer that Android Studio makes.
Here is my code :
public class MenuActivity extends AppCompatActivity{

    private AppBarConfiguration mAppBarConfiguration;
    private NavigationView navView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_menu);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        DrawerLayout drawerLayout = findViewById(R.id.drawer_layout);

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        this.navView = navigationView;

        mAppBarConfiguration = new AppBarConfiguration.Builder(
                R.id.nav_home, R.id.nav_gallery, R.id.nav_slideshow)
                .setDrawerLayout(drawerLayout)
                .build();
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
        NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
        NavigationUI.setupWithNavController(this.navView, navController);

        navigationView.setNavigationItemSelectedListener(menuItem -> {
            int id=menuItem.getItemId();
            if (id == R.id.nav_home) {
                Toast.makeText(getApplicationContext(), "Home", Toast.LENGTH_SHORT).show();
            }
            NavigationUI.onNavDestinationSelected(menuItem,navController);
            drawerLayout.closeDrawer(GravityCompat.START);
            return true;
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            Toast.makeText(getApplicationContext(), "Home", Toast.LENGTH_SHORT).show();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onSupportNavigateUp() {
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
        return NavigationUI.navigateUp(navController, mAppBarConfiguration)
                || super.onSupportNavigateUp();
    }
}

I tried to put a setNavigationItemSelectedListener on my navigationView to get the menuItems that where clicked, plus I've put an Toast to make shure that it was well fonctionning but the Toast never appeared.
To be complete, here is my XML :
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    tools:showIn="navigation_view">

    <item
        android:id="@+id/nav_home"
        android:icon="@drawable/ic_menu_camera"
        android:title="@string/menu_home" />
    <item
        android:id="@+id/nav_gallery"
        android:icon="@drawable/ic_menu_gallery"
        android:title="@string/menu_gallery" />
    <item
        android:id="@+id/nav_slideshow"
        android:icon="@drawable/ic_menu_slideshow"
        android:title="@string/menu_slideshow" />
    <item
        android:id="@+id/nav_connexion"
        android:title="@string/connexion" />

</menu>

I also tried to put a Toast on onOptionsItemSelected and the Toast works perfectly, so I don't understant why the Toast on the menuItems don't work.
Here is my arborescence of XML directories.

And here is my XML file for the setting Toast:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/action_settings"
        android:orderInCategory="100"
        android:title="@string/action_settings"
        app:showAsAction="never" />
</menu>


text:
Q: Definite Integral Solve the following : $$\int_0^1 x^5 \sqrt{1 - x^2}dx $$
Any ideas ?I haven't been able to make any progress on this exercise , it's driving me insane , since there's probably no big deal to the solution.. Thanks a lot in advance for your patience !

A: HINT:
$$\int_0^1x^5\sqrt{1-x^2}\ dx=\int_0^1 x^4\sqrt{1-x^2}\ xdx$$
Set $\displaystyle 1-x^2=y^2\implies x\ dx=-y\ dy$ and $x^2=1-y^2$


text:
Q: Force a camera to always open in portrait mode in android Is it possible to open the Camera Intent in android in only portrait  mode, that is even if the user flipped the device, the camera will still be in portrait mode,
I tried the following answer: Force Portrait Mode but didn't work, Thanks

A: Try it -
private void setCameraDisplayOrientation(Activity activity,
         int cameraId, android.hardware.Camera camera) {
     android.hardware.Camera.CameraInfo info =
             new android.hardware.Camera.CameraInfo();
     android.hardware.Camera.getCameraInfo(cameraId, info);
     int rotation = activity.getWindowManager().getDefaultDisplay()
             .getRotation();
     int degrees = 0;
     switch (rotation) {
         case Surface.ROTATION_0: degrees = 0; break;
         case Surface.ROTATION_90: degrees = 90; break;
         case Surface.ROTATION_180: degrees = 180; break;
         case Surface.ROTATION_270: degrees = 270; break;
     }

     int result;
     if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
         result = (info.orientation + degrees) % 360;
         result = (360 - result) % 360;  // compensate the mirror
     } else {  // back-facing
         result = (info.orientation - degrees + 360) % 360;
     }
     camera.setDisplayOrientation(result);
 }

private void initCamera() {
     if(mCamera == null) {
          mCamera = Camera.open();
          setCameraDisplayOrientation(activity, CameraInfo.CAMERA_FACING_BACK, mCamera);
          mCamera.unlock();
      }
}


text:
Q: Binding datasource to Barseries I am attempting a telerik barseries control to plot some data. This is only my sample and I cant get it to working. I followed the examples available and read about data binding and still cant get to why this is not working for me.
Here is what I have done.
Define a basic class:
    public class CountClass
    {
        private int count;
        private string name;

        public string Name
        {
            get
            {
                return name
            }
            set
            {
                name= value;
            }
        }

        public int Count
        {
            get
            {
                return count;
            }
            set
            {
                count= value;
            }
        }

        public CountClass(string tempname, int value)
        {
            name = tempname;
            count = value;
        }
    }

public class QClass : Telerik.Windows.Controls.ViewModelBase
{
    private CountClass q1;
    private CountClass q2;

public QClass()
        {
        }

    public CountClass Q1
    {
        get
        {
            q1 = new CountClass ("Count1", 100);
            return q1;
        }
    }

    public CountClass Q2
    {
        get
        {
            q2 = new CountClass ("Count2", 200);
            return q2;
        }
    }
}

public partial class MainPage : UserControl
this.DataContext = new SilverlightApplication2.QClass();

And xaml:
<chartView:BarSeries ItemsSource="{Binding Q1}"
    FontFamily="Segoe UI"
    FontSize="10"/>

What am I doing wrong?

A: Bind to a List (or any other collection) even if it contains only one item.
public List<CountClass> Q1List {get{...}}

And your binding:
<chartView:BarSeries ItemsSource="{Binding Q1List}" .../>


text:
Q: prevent submit button with jquery ui dialog combined with knockout if statement I have an issue where I'm using the KO if tags to bring dialog code into the DOM when requested.  On the dialog is a form with a submit button.
I wish to prevent the submit button from submitting using e.preventDefault();
The trouble lies that on document load because the dialog is not in the DOM this over-ride function is not working.
I've created a JSFiddle here to demonstrate the issue:
http://jsfiddle.net/rZBhx/4/
model = new function () {};
model.functions = ko.observable();
model.data = ko.observable();
model.data.status = ko.observable("Status: model is live");
model.data.visible = ko.observable(false);

model.functions.showDialog = function (dialogVisible) {
    if (dialogVisible == true) {
        model.data.status("Status: Darth Dialog Activated");
        model.data.visible(true);
        $("#darthDialog").dialog({
            modal: true
        });
    } else {

        model.data.status("Status: Darth Dialog Deactivated");
        $("#darthDialog").dialog('close');
        model.data.visible(false);
    }

};

ko.applyBindings(model);

$(function preventSubmit(e) {

    $("#submissionForm").submit(function (e) {
        e.preventDefault();
        model.status("Status: Saved by Ko.da");
        return false;

    });
});

As a side note, in my fiddle the cancel button only works once with the ko if statements.
I'm not sure why this is.   In my live site this isn't happening.
If you remove the

from the HTML then the submit is prevented, and the cancel button continues to work.
Is there someway this can be made to work, whilst keeping the KO if's?

A: The easiest thing for you to do is to use a submit binding on the form element inside of your block. Then, when it is visible (bound), the submit handler will be attached to the current DOM elements.
<form action="/darkSide/submission" data-bind="submit: submitForm" id="submissionForm" method="post">
Then, just add a submitForm function (or whatever you want to call it on your model).
Sample here: http://jsfiddle.net/rniemeyer/gDkXf/
You may also want to take a look at using a custom binding to encapsulate the logic around the jQuery UI dialog.  Take a look at this answer: integrating jquery ui dialog with knockoutjs


text:
Q: Parse JSON string to a JSON Object in C# without writing extra object classes I'm new to C# and I am building a WPF app. Right now I trying to figure out how I can parse a JSON string like this:
{
   "Name": "Apple",
   "ExpiryDate": "2008-12-28T00:00:00","Price": 3.99,
   "Sizes": ["Small","Medium","Large"]
}

into a JSON Object magically.
I did some search online and all the solutions requires writing an object class that has the same structure as the JSON string. The string above is just an example and the actually JSON response is much more complicated, so I don't want to write a huge class for it.
Is there a library that allows me to do something similar to these:
JsonObject jo = new JsonObject(JsonString);
string name = jo["Name"]; // And the name would have "Apple" as its value

A: I'd recommend you use Json.NET as your JSON library. The following code creates a dynamic object that you can work with. magic is actually an instance of JObject in your example, by the way.
dynamic magic = JsonConvert.DeserializeObject(jsonStr);
string name1 = magic.Name;    // "Apple"
string name2 = magic["Name"]; // "Apple"


text:
Q: Supremum and Infimum of $ S=\{x|x=-(1/n)+[1+(-1)^n]n^2,n \geq 1\}$
Quoting: find the supremum and infimum of S. State whether there are in S
  $$ S=\{x|x=-(1/n)+[1+(-1)^n]n^2,n \geq 1\}$$

I am new to new to this.
What I did is substituting some values for n:
When $n = 1$ , then $ x= -1$
When $n = 2$ . then $x = -1/2 +8$
When $n = 3$  , then $x = -1/3$
When $n = 4$  , then $x  = -1/4 +32$
Looking at the pattern, It seems to me that we have as lower bounds: any number less than -1, infimum -1
there is no upper bound, $Sup(S)= \infty$ .
Is this correct? Is there another way a bit more efficient?
Much appreciated

A: You're on the right track, but plugging in values isn't enough for a rigorous proof. When $n = 1$, $x = -1$, so $\inf(S)\leq -1$. Also, $$-\frac{1}{n}+(1+(-1)^n)n^2\geq -\frac{1}{n}\geq -1$$ so $-1$ is a lower bound for $S$. Therefore, $\inf(S) = -1$. Next, letting $n$ be even, we have $n = 2k$ for some $k\geq 1$. Then, $$-\frac{1}{n}+(1+(-1)^n)n^2 = -\frac{1}{2k}+8k^2$$ and $$\lim_{k\to \infty} \left[-\frac{1}{2k}+8k^2\right] = \infty$$ which implies that for any $y$, there is some $k$ such that $-\frac{1}{2k}+8k^2 > y$. Thus, there is no finite upper bound for $S$, so $\sup(S) = \infty$. Therefore, $S$ contains its infimum, but not its supremum.


text:
Q: Windows file permissions/ownership are preventing me syncing between computers I have been using Google Backup and Sync for some time but I just decided it would be nice if I could use it for properly syncing so that data on all my Windows machines could essentially be the same, i.e. all use the same Gmail account Drive.
Everything has been working nicely. But today I tackled the files used by MySQL (in fact MariaDB MySQL fork).
If I modify some data on one machine (machine "A"), several files get changed: ibdata1, ib_logfile0 and ib_logfile1. These then get mirrored to the Cloud location (i.e. GDrive remote site). Unfortunately, these 3 files (and a couple of other MySQL files) don't then replace the existing files on machine B.
When I look at the reason why GB&S is saying "can't sync" for these files on machine B it says "You don't have permission to sync these files".
I take this to mean because the MySQL service is being run by the owner SYSTEM.
I've tried a couple of times to understand how Windows file ownership and permissions work in reality (it seems to be different to some of the explanations out there). But is there a quick or not-so-quick fix for this problem?
A few more details
Looking at the existing ibdata1 file on machine B (where the incoming replacement of this file is not being allowed to replace it), I find that in fact the owner is said to me "M17A/Mike", where M17A is the name of the computer.
Under the "Security" tab for the file, there are four entries under "Group or user names": Authenticated Users, SYSTEM, Administrators (M17A\Administrators) and Users (M17A\Users).  All 4 of these have "Full control" ticked (I set this myself earlier today trying to solve this problem).
Rather than ownership/control, could it be something to do with the fact that the MySQL service has these files under its control as long as it is operating? Again is there any solution to this?

PS there's another problem with this, which is the size of these MySQL files: a tiny modification to one record in one dbase triggers the uploading of over 100 MB of files (the 3 main files mentioned above) by GB&S, followed by the downloading of them to sync the other computers attached to the same account.  But this is a separate and less urgent problem.

A: The googledrivesync.exe executable runs as the user who starts the application. This would typically be the user currently signed in to the computer. This means your user accounts needs to have full control permissions on any files / folders you want Google Backup and Sync to access. Best practice would be to make sure that full control permissions are granted to your user account on the google drive folder and those permissions are propagated to all subfolders and files.

Rather than ownership/control, could it be something to do with the
  fact that the MySQL service has these files under its control as long
  as it is operating? Again is there any solution to this?

Yes. This is why Google Backup and Sync cannot modify the file. This is not a Google Backup and Sync limitation. This is a limitation (or rather a protection) in the operating system that prevents one process from modifying a file that is open in another process.
There is not a solution for that.
Unfortunately, you're running in to problems with all cloud sync tools and to a greater extent the problem of file sharing in general. You're trying to use it to sync an in-use database file. Even if the application that is accessing the file is designed in such a way that multiple processes can share the file, it still wouldn't work well with a cloud sync tool. You are not working with live data on cloud synced folders. Instead, one machine modifies the file and the changes are uploaded to the cloud, then the second machine recognizes the changes and downloads the file. There is lag, and no guarantee that both machines will always have a reliable internet connection. There is no mechanism to insuring the integrity between these file level changes. The two machines are never accessing the "same" file as is the case with an application that may be designed to work together with multiple users on the same local network.
For that reason, use Google Backup and Sync to sync files that a have a low likelihood of being used by multiple machines at the same time.
A work around in your situation would be to setup a manual process where Machine A backs up the MySQL database to a file and then allow that file to sync to Machine B. Then, Machine B restores that backup file to the MySQL database on Machine B. Perform this process when you want to "refresh" the data on Machine B.

A: Backup & Sync will refuse to sync certain files, if they are marked "hidden" or "system" or other flags.
Unfortunately some hidden/system files are required for the operation of some software.   Especially if you're trying to sync an AppData folder for an app running on your machine.
FWICT, Backup & Sync has no setting to change whether or not it will synchronize hidden files.   There were a large number of people complaining 2 years ago that they wanted to turn off this feature, and, rather than making it a setting or switch, it appears it's now the default and only behavior.
So, it's possible that Backup & Sync will simply not sync your files.

A: Solution that worked for me is to delete the file from the computer and upload it directly to google drive via the browser and let it sync back to the computer.


text:
Q: Graph Plot in JFreeChart On the X axis my data points(20 of them) take values between 0 and 0.2. My X axis should have range from 0 to 1. On the Y axis corresponding values are between 0.8 and 0.86. When I plot this graph using NumberAxis in JFreeChart I get very dense graph especially in the interval X belongs to 0.01 to 0.02.(so I can't see much)
Is it meaningful to use log scale for X axis in this case? How should I adjust LogAxis in JFreeChart here?

A: To use LogAxis, just create the axis and set it as the plot's domain:
LogAxis xAxis = new LogAxis("X");
plot.setDomainAxis(xAxis);

LogAxisDemo1, shown among the XY Charts in the demo, is a complete example. LogarithmicAxis may be a more visually appealing alternative.

A: Using log scale for x-coordinates is sensible. One approach without trying to figure out the right syntax for LogAxis is to transform the data points from {x, y} to {log(x), y} and use the normal linear scale charting.


text:
Q: Get HTML from web page shared from browser through intent I'm looking to get the HTML from a web page shared by the user with my app.
So I have this intent filter:
<intent-filter>
    <action android:name="android.intent.action.SEND"/>
    <category android:name="android.intent.category.DEFAULT"/>
    <data android:mimeType="text/plain"/>
</intent-filter>

And the code in my activity:
String action = intent.getAction();
if (action.equalsIgnoreCase(Intent.ACTION_SEND) &&
intent.hasExtra(Intent.EXTRA_TEXT)) {
    String s = intent.getStringExtra(Intent.EXTRA_TEXT);
    output.setText(s); //output: a TextView that holds the URL
}

This outputs the link.. but I need the HTML. Any thoughts? thanks!

A: Use an HTTP client API (OkHttp, HttpUrlConnection, etc.) and make an HTTP GET request for that URL. IOW, do what a Web browser does.


text:
Q: How to install SWT_XYGraph_2.1.0 widget into Eclipse I searched Google, but did not see how to add a widgit, like SWT_XYGraph_2.1.0, to Eclipse, such that when I go to the SWT designer view, I see the control in the palette.
I saw articles that said to import a jar, do " | Build Path | Configure Build Path... | Add External Jars...", however that does not add the widget to the palette.
I also saw articles that talked of copying the features and plugin files to the appropriate eclipse folder, but I do not see any feature files. What I see is:
org.csstudio.swt.widgets.source_2.1.0.201209121549.jar
org.csstudio.swt.widgets_2.1.0.201209121549.jar
org.csstudio.swt.xygraph.source_2.1.0.201209121540.jar
org.csstudio.swt.xygraph_2.1.0.201209121540.jar

What is the step-by-step guide on how I can import the SWT widgit into Eclipse and see the widget.
Note, I already added the 49.jar widgit file using 'Configure Build Path', although I guess that I can remove it just as easily.
Also, do I place the widget files into the

I am running Eclipse on Windows, but app needs to work on CENTOS Linux as well.
Eclipse Standard/SDK
Version: Kepler Service Release 1
Build id: 20130919-0819
I am using WindowBuilder.

A: Look at the documentation for WindowBuilder: Custom Composites & Panels. It allows you to add any Composite subclass (I assume XYGraph is one; if it's a Canvas subclass instead, wrapping it in a Composite should be simple).


text:
Q: Serial communication with scientific instrument I have a scientific instrument which is controlled by an old computer running SCO Unix. I would like to write a Windows application to control the instrument to get rid of the old Unix machine.
I have been able to monitor the serial communication between the Unix PC and the instrument and have determined the setup of the serial port (baud rate, data bits, stop bits, etc.). The initial communication between the PC and the instruments is the PC sending a string of 18 null (00) characters and the instrument responding with another string of null characters.
I then connected my Windows PC directly to the instrument and sent a string of 18 null characters to the instrument (using Eltima Software Serial Port Monitor) but there was no response from the instrument. I have tried all variations of flow control and parity settings yet still can't get a response from the instrument.
Am I missing something here?

A: Please, research the states of the DTR or RTS hardware flow control signals, because the device may control it.


text:
Q: Is it possible to connect to multiple VPN networks at once via Network Manager? Is it possible to connect more VPN networks at once via Network Manager?
I am running Ubuntu 12.04.1 LTS.
For now I am only able to switch between preconfigured VPN connections. It`s quite annoying as I need to be connected to two or more VPN networks simultaneously.
For example on Windows OpenVPN clients, it is possible.

A: This is a known limitation of network-manager-openvpn. You can subscribe to https://bugs.launchpad.net/ubuntu/+source/network-manager-openvpn/+bug/671024 and mark the bug as affecting you.
As mentioned in the first comment, it is possible to connect to multiple VPNs but not via Network Manager.

A: It seems that what you want is not possible at the moment. There are a lot of bugs on this issue like this and it was assigned to upstream.
Even so, you can connect multiple vpns at once as described in this answer. You can write you own configuration file by reading "Manually configuring your connection" section in this Ubuntu help page.

A: You can't do it with Network Manager, but yes, using Network Manager and pptp.
Here is how I make it works in my case.

*

*Connect to the first VPN using Network Manager.

*Connect to the second VPN with command pon vpn2, use poff vpn2 to disconect the second VPN.

To make the command pon works, you will need to create the followed files in your system:
file /etc/ppp/peers/vpn2:
pty "pptp VPNIpAddress --nolaunchpppd"
name YourUsername
remotename PPTP
require-mppe-128
file /etc/ppp/options.pptp
ipparam vdc

file /etc/ppp/options.pptp:
lock
noauth
refuse-pap
refuse-eap
refuse-chap
refuse-mschap
nobsdcomp
nodeflate

Of course the content of these files is depends on your VPN servers.
In my case I also should to add the ip-up.d/ rules, to add the necessary routes.
file /etc/ppp/ip-up.d/vpn2
#!/bin/bash
case "$PPP_REMOTE" in
        YourVPNGatewayIPHere)
        route add ....
        route add ....
        ...
                ;;
    *)
esac

Don't forget: sudo chmod +x /etc/ppp/ip-up.d/vpn2
Also you will need to edit the file /etc/ppp/chap-secrets and add there your credentials.
After this, connecting to VPN1 with Network Manager, run:
sudo pon vpn2

Check syslog if something goes wrong.

A: With 12.10 (network-manager 0.9.6), you can connect to multiple VPNs using the network settings:

*

*System settings (gnome-control-center)

*Network

*Select each VPN and set it to "on".

You can also use the nmcli tool; see http://cweiske.de/tagebuch/networkmanager-vpn.htm for more information.


text:
Q: Are compact subsets of $\mathbb{R}$ with the compact complement topology closed? Given the usual topology $\tau$ on $\Bbb{R}$, define the compact complement topology on $\mathbb{R}$ to be $$\tau'=\{A\subseteq \Bbb{R}:A^C\text{ is compact in }(\Bbb{R},\tau)\} \cup \{\emptyset \}.$$ Are compacts sets in $(\Bbb{R},\tau')$ closed (in $(\mathbb{R} , \tau')$)?
After one hour's struggle I could not prove this. I can see that all compact sets in $(\Bbb{R},\tau)$ are still compact in $(\Bbb{R},\tau')$ and they are trivially closed, but this is certainly not equivalent to the claim to prove.

A: You are correct. Clearly $\Bbb Z$ is not $\tau'$-closed, since it's not $\tau$-compact, but I claim that it is $\tau'$-compact. Let $\mathscr{U}$ be a $\tau'$-open cover of $\Bbb Z$. Fix $U_0\in\mathscr{U}$; then $\Bbb R\setminus U_0$ is $\tau$-compact and hence bounded. But then $\Bbb Z\setminus U_0$ is bounded and therefore finite, so only finitely many members of $\mathscr{U}$ are needed to cover it.


text:
Q: SQLAlchemy: Should I commit an update between two queries? In a single session, if I want to:
// make a query on Foo table to get one instance
// update this instance
// commit() or not?
// make the same query on Foo table

Will I get the same result in these two queries? That's to say, is it necessary to commit the update before query on the table within a single session?
Thanks!

A: It is not necessary to commit prior to making the query again. As a general principle, updates within a transaction (session) will be visible to subsequent queries in that same transaction, even prior to a commit.
Having said that, doing the same exact query twice within a transaction might be "code smell".  It's worth considering, since the updated object is already memory, is it really necessary to query the object again?
Also, depending on the database isolation level, the second query is not guaranteed to return the same result set as the first one.  This can happen if another transaction modifies the data prior to the second query.

A: It's not necessary to do both commits, as each transaction is visible to subsequent actions in the database (or queries).
You can just put the commit at the end, although I am not sure if multiple commits will affect runtime.


text:
Q: Deep merging configs of host app and addon in ember Normally config/environment.js files of host application and addon are merged. But top level only.
For example:
//addon config/environment.js
module.exports = function() {
    return {
        addonRootVar: 'exist after merge'
        APP: {
            addonDeepVar: 'doesn\'t exist in resulting config'
        }
    }
}

//host app config/environment.js
module.exports = function() {
return {
    hostRootVar: 'exist after merge'
        APP: {
            hostDeepVar: 'whole APP property will be overwritten :('
        }
    }
}

Is it possible to deepMerge configs?(to have both addonDeepVar and hostDeepVar present in resulting config) If yes – How?

A: I've made a mistake. Actually configs are merged(deep) by default. But the config is generated once per ember-cli server start(no recreation when file changes). So every time you modify any of the configs, you have to relaunch server in order to avoid the unpredictability.


text:
Q: Excel solver style constrained optimisation/constraint programming in R I'm trying to write some R code to perform constrained optimisation, where the constraints are not of the usual (g(x) < c) type.
An example of the type of problem I am trying to solve is the following:
A company is trying to determine how much to produce each year for the next 5 years, given an assumed price for each year. It can produce upto X per year, but over any given 3 year window can produce no more than 2X. In addition, in any given year, it cannot produce less than 0.5X unless it produces 0X. Other constraints may be equally impossible to write as a set equation (eg if X > a, Y < c).
I'm very comfortable solving this type of thing in Excel Solver, as it's relatively easy to be very flexible with these sort of restrictions (eg each year have an if statement that looks at the quantity produced in current, past, and next year, and returns 0 if less than 2X, sum the if statements in a cell, and set the constraint of that variable equal to 0).
It's just gotten too large to realistically do in excel. I'm pretty comfortable in R but haven't done this sort of thing. If anyone can point me to a useful package or a good way of managing a lot of dynamic constraints rely on If statements etc, I would be super appreciative!

A: You can use IF statements in optimization problems. This will make the problem nonlinear, so you need a nonlinear solver (Excel solver contains GRG2 which is quite a good NLP solver). However, IFs may make the problem discontinuous or non-differentiable. This can cause problems. E.g., the solver may get stuck and report a local optimum, instead of a global one.
It may be better to reformulate the model using binary variables. Often this will make the model otherwise linear. Disadvantage: it often requires some skill and experience to come up with and implement these reformulations. The exact form of these reformulations is often solver-dependent (e.g. it may depend on whether the solver supports indicator constraints or SOS sets) and very problem-dependent.


text:
Q: Arduino + sim900 + xively I have a problem, I'm new to Arduino and I'm totally a beginner.
I bought a SIM900 Quad-band GSM / GPRS Shield for Arduino (http://cgi.ebay.com/ws/eBayISAPI.dll?ViewItem&item=221176159800&ssPageName=ADME:X:RTQ:US:1123) and I have two problems.
(I use the test code that is found in the library)
First
the device does not read every message, but only a few. one read and then 3 does not, then 2 read and then 4 do not read .....
Second
I do not know how to connect to xively, no examples.
I know how to connect and send data via an ethernet shield, but with SIM900 Quad-band GSM / GPRS Shield do not know how.
I download the library from http://www.gsmlib.org/download.html and fix the first problem with sms.
but I do not find a solution to the second problem, and I can not find and I need a  simple example to send data to xively.
So if anyone can help I would be grateful

A: You'll need to learn how to have the SIM900 perform HTTP operations. Study the example shown in Step 8 at this Cooking Hacks tutorial
For posting data to Xively, study this example.
You'll need to merge how you communicate from the SIM900 with the right HTTP sequences in order to upload data to Xively.


text:
Q: Is there a mathematical proof that reactive power regulates voltage? So after studying the power triangle and trying to conceptualize real power and reactive power, I seem to have come across a contradiction, at least in my own head. Most explanations disregard reactive power as "useless" power or power that we don't want to pay for. But then i came across the fact that reactive power is needed to control voltage. "In general terms, decreasing reactive power causes voltage to fall while increasing it causes voltage to rise." Well, aside from just believing it, i would like to see some type of mathematical proof that shows it? I know the equation for reactive power (Q)=VIsin(theta), but i don't see the relationship that shows reactive power helps control voltage.
Quote is taken from: https://electrical-engineering-portal.com/how-reactive-power-is-helpful-to-maintain-a-system-healthy

A:
Most explanations disregard reactive power as "useless" power or power that we don't want to pay for.

Such explanations are wrong. Sources of such information should probably be avoided.
"Reactive power" is a common term for reactive volt-amperes (VARs). Reactive volt-amperes have one very important use, they provide the magnetic fields for every electromagnetic mechanism. Induction motors represent most of the requirement for VARs, but transformers, AC solenoids and relays also require VARs.
Since VARs represent energy that is continually circulated back and forth between the source and load, the only power consumed is due to losses. That is a small amount and is measured as watts when it occurs on the consumer side of the meter. On the utility side of the meter, the losses are a concern for the utility. The utility is also concerned with the use of transmission capacity to carry current that is not delivering power.
Only synchronous generators and capacitors can provide VARs to magnetic loads. If capacitors are connected near the magnetic loads, that avoids the associated transmission losses and frees up generating, transmission and distribution capacity to provide more real power. However if too much capacitance is added to supply VARs, the utility must accept the extra VARs. Only synchronous generators and inductors can accept VARs from excess capacitance. Since utilities are not expecting excess capacitance, they are not prepared to add inductance. The synchronous generators may have difficulty with that kind of load. The result would be excess voltage.

"In general terms, decreasing reactive power causes voltage to fall while increasing it causes voltage to rise." Well, aside from just believing it, i would like to see some type of mathematical proof that shows it?

Since the statement is not entirely correct, there is no proof. Understanding what can happen requires studying the "V curves" for synchronous generators. It is also necessary to understand the various limits on the safe operating conditions for synchronous generators and transmission system component.
More re increased voltage
In order to overcome voltage drops in the transmission system, the voltage at the generator must be higher (on a percentage basis) than the voltage seen by a customer. If the customer had been "consuming VARs," adding capacitors would reduce the current and voltage drop in the transmission lines. That would tend to increase the voltage at the meter, but the utility would adjust the generator to keep the customer voltage within limits. If the customer begins to supply vars, that would tend to make the voltage higher at the customer location. To some extent, VARs supplied by one customer may be absorbed by other customers. That would tend to make that customer's voltage higher than the voltage seen by other consumers.

A: Current through an inductor causes a 90° phase-shifted voltage over it. The more current, the more voltage, the more reactive power.
In contrary to a resistor, neither the reactive power nor the induced voltage is lost to the circuit as heat, so you can do neat things with it. The simplest example are autotransformers. Look that up. A more complicated example are quadrature boosters used to control power distribution in parallel pathes of an electrical grid.
More into theory, transformers and AC induction motors cannot function without inductive reactive power as they need a magnetization current for their function.


text:
Q: Is it possible to access server control from page method? I would like to update a Gridviews datasource using JQuery and page methods, but I'm not sure how to access the Gridview control I created on the page. I know I can't access the instance of it, but I want to access the id so just rebind it.
Is this possible?

A: Is there something specific you are doing with this Gridview? If not, I would also suggest (as Niels suggests) to use an ajax call (use jQuery) and instead of a Gridview try a Table. Check this nice HTML Gridview out. It uses jQuery, JSON, WebService.
Good luck!

A: If you want to update you have to build a webmethod. Seet his page for more information: http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/
If you got a Webmethod, you can access that function by calling something like:
$.ajax({
    url: "page.aspx/webmethodname",
    success : function(data){}
})

But then you have to build your Gridview through code.
Or use default Ajax from asp.net: http://www.ezineasp.net/post/ASP-Net-AJAX-GridView-Loading.aspx


text:
Q: javascript and VB.net returning incorrect results We are noticing this occurs BOTH in javascript and in VB.net 2.0.  So basically both  in server side and client side code.
Basically if you run this equation 975328 - 153279.43 you get the following answer 822048.57000000007.
However, if you run 975328 - 153279.4, 975328 - 153279.433, or 975328 - 153279.5 everything is returned correctly.
Any ideas has to WHY the system calcuates the 975328 - 153279.43 with an answer with 11 decimal places? Not to mention adding the 7 in the 11th decimal place, thus making the equation answer incorrect.
Of course I know I can trim, set the answer to appropiate decimal places, etc., etc., but we are more interested to know WHY it returns such an answer.
Bare in mind, the above is proven by just entering the equation into the immidiate window, thus ellimnating varibables such as object types, etc., etc.
Thanks for the help,
Ken

A: For the same reason you can't accurately express 1/3 as a decimal (base 10).  You may enter your numbers in base 10, but all the arithmetic happens in base 2 (binary).  So that base 10 value must first be converted to base 2, and you likely end up needing more bits to represent it than are used for the standard double type, if it's even possible to accurately represent number in binary at all.
Another common number to investigate for this error is .1.  When converted to binary, any decimal number with .1 repeats forever after the decimal point.  Thus, there's no way to accurately express the value in binary.
In VB.Net, you at least have the Decimal type you can use handle this kind of thing. IT's much, much slower, but it should accurately handle this kind of calculation.  I'm not sure the javascript solution is.

A: You need to be aware that floating point numbers will only have a fixed precision. You cannot correctly display all numbers via floating point, so some calculations can cause this imprecision to "surface"
A floating point number is presented as an "int" + a bitshift...
Take a look here: http://en.wikipedia.org/wiki/Floating_point
Internal representationFloating-point numbers are typically packed into a computer datum as the sign bit, the exponent field, and the significand (mantissa), from left to right. For the IEEE 754 binary formats they are apportioned as follows:

Type Sign Exponent Significand Total bits Exponent bias Bits precision

Half   1    5          10           16              15          11
(IEEE 754-2008)

Single 1    8          23           32             127          24

Double 1   11          52           64            1023          53

Quad   1   15         112          128           16383         113

A: Javascript uses float datatype to store those values, and in summary, float data type does not store exact number in memory.  Usually, its best to use integers to perform calculations and then you can always divide by 100.0 to cast to whatever decimal point you wish.  Alternatively you can use toFixed(DECIMAL_PLACES) on the object to round it to the decimal point you wish.


text:
Q: Как вывести числа в отдельный txt файл? Нужна помощь. Есть программа(пример ниже) хочу что-бы переменная dry_count выводилась в отдельный txt файл после закрытия программы. dry_count отвечает за количество выводящих строк в консоль, их нужно посчитать и вывести в отдельный txt.
from colorama import *
import random
import time
import os

adr = ['241', '4325', '4356']

word = ['Ho', 'Ia', 'Choose']

i = 1

dry_count = 0

while i < 10:
    print(Fore.YELLOW + 'Адресс:', random.choice(adr), '|', Fore.YELLOW + 'Бал 0', '|', Fore.YELLOW + 'Слова:', random.choice(word))
    dry_count + 1
    time.sleep(0.05)

Помогите пожалуйста!

*

*Элемент списка


text:
Q: How to convert innerHTML into an array where I can use .size() function. etc I would like to put an innerHTML I got into an array, from there I can access its size and each character in it. (Each character takes 1 slot in the array).
For example
<script type=text/javascript>

var tester=document.getElementById("mydiv").innerHTML;

//testerArray = conversion function goes here? <<<<<

alert (testerArray.size());
alert (testerArray[2]);

</script>

Help is appreciated! Thanks!!

A: .length already does this for strings.

A: how about
var tester=document.getElementById("mydiv").innerHTML;

alert(tester.length);
alert(tester.charAt(2));

A: testerArray = [].slice.call( tester );
there is no .size() for arrays though and you could already use .length for the string. If you actually need array functions, then this is ok


text:
Q: Android SqliteAssetHelper copy user saved data I am using SQLiteAssetHelper utility to manage the copying of the database from my asset folder. In the app, the user enters some data into the database and as soon as I upgrade the db, all the data gets deleted cause I have set setForcedUpgrade();. I heard you can use upgrade scripts, but I think they do not help me in this case as the data is unique for each user. How can I solve this?

A:
all the data gets deleted cause I have set setForcedUpgrade();

Then do not call setForcedUpgrade().

I heard you can use upgrade scripts, but I think they do not help me in this case as the data is unique for each user.

The primary point of upgrade scripts is to allow you to upgrade the schema without harming existing data, "as the data is unique for each user".

How can I solve this?

Use upgrade scripts. Or, override onUpgrade(), as you would with a regular SQLiteOpenHelper, as onUpgrade() is not final.


text:
Q: Lazily evaluated indexed sequence type I need to build a sequence of objects that are loaded from an external resource. This loading being an expensive operation needs to be delayed until the time the objects are needed. After the collection is built, I need an indexed access to the contained objects. Does Scala standard library provide a collection suited to this use case? If not, what will be the best way to implement it?
Edit:
The indexed lookup should preferably be an O(1) operation.

A: To my knowledge, there's nothing that fit in the standard library. A solution might be to use a kind of Lazy wrapper for your objects:
class Lazy[A](operation: => A) {
  lazy val get = operation
}

And then you can build your Collection[Lazy[A] with any kind of collection you want to use.

A: It sounds like you want a Stream.

A: Strange, Miles recently tweeted about this. A reply then points out to Need at the end of Name.scala in scalaz and another one points to specs' LazyParameter.
Little testing with Need:
import scalaz._
import Scalaz._
val longOp = { var x = 0; () => {println("longOp"); x += 1; x }}
val seq = Seq(Need(longOp()), Need(longOp()))
val sum = seq.map(_.value).sum
val sum = seq.map(_.value).sum

val v = Need(longOp())
val s = v.map("got " + _)
println(s.value)
println(s.value)

prints:
longOp: () => Int = <function0>
seq: Seq[scalaz.Name[Int]] = List(
  scalaz.Name$$anon$2@1066d88, scalaz.Name$$anon$2@1011f1f)
longOp
longOp
sum: Int = 3
sum: Int = 3
v: scalaz.Name[Int] = scalaz.Name$$anon$2@133ef6a
s: scalaz.Name[java.lang.String] = scalaz.Name$$anon$2@11696ec
longOp
got 3
got 3

So longOp is only called once on first access of value.


text:
Q: I need to use jquery validation with update panel I need to use jquery validation with update panel  but update pannel refresh the validations
how this problem can be solved

A: hai sanjay,
jQuery and MS AJAX do not play well together.  Once an asp.net 'AJAX' call is made, any jQuery assignments are lost.  YOu will have to take some extra precuations or use a little different approach to make them work.  Check out this article:
http://encosia.com/2009/03/25/document-ready-and-pageload-are-not-the-same/
and this jQuery event:
http://docs.jquery.com/Events/live
jQuery library can be easily integrated with ASP.Net Ajax applications. Remember the ready event will not fire for an asynchronous postback caused from UpdatePanel control. The ASP.Net AJAX equivalent of ready() function is endRequest event.
<script type="text/JavaScript" language="JavaScript">
    function pageLoad()
    {
       var manager = Sys.WebForms.PageRequestManager.getInstance();
       manager.add_endRequest(endRequest);
    }
    function endRequest(sender, args)
    {
      //Do all what you want to do in jQuery ready function
    }
</script>


text:
Q: How to write a for loop which creates a model and has a function which references that same model I am trying to run a post hoc analysis on an unbalanced two way anova using the anova_test funciton in the rstatix package. I need to run this post hoc test iteratively, as I have ~26 response (y) variables. My first step is to create models of all my y variables with relation to group and treatment. I have successfully managed to do this, creating a single list with 26 models:
models <- map(data[,y1:y26], ~(lm(.x ~data$group*data$treatment)))
Now comes the part I'm stuck on. Referring to these models iteratively. I would like to run the following code for every y variable I have:
group_by(group) %>%
anova_test(y ~ treatment, error = models(y), type = 3)

where my y changes every time and as it does, the "model" (referred to in the error = term) is updated accordingly. I'm struggling with this bit since first set of models I make is used to inform the second set of models.
However, if I run just one y variable through this whole bit of code at one time, I get the appropriate results.
model <- lm(y ~ group*treatment, data = data)

data %>%
group_by(group) %>%
anova_test(y ~ treatment, error = model, type = 3)

I have tried creating a for loop as well as using the map function in the purrr package but I have been unsuccessful. I am new to for loops and purrr so I am sure it's a simple fix I just can't see it.
Basically I want a way to run
data %>%
group_by(group) %>%
anova_test(y ~ treatment, error = model, type = 3)

iteratively for different y variables (y1, y2, ..., y26) while also referring to the approprite model (model$y1, model$y2, ..., model$26).
Thanks for your help!

A: Well you didn't give any data so let's use toothgrowth.  You seem to like the model format, so let's build a list of models.  You could do this in an automated fashion but to make it clear lets do it by hand.  The call purrr::map with the anova_test function.  You'll get a list back.  Since you're in charge of naming the list elements go to town.
Updated answer May 18th.  Now using map2 since you want two different models passed build a list for each...
library(rstatix)
library(purrr)

ToothGrowth$len2 <- ToothGrowth$len^2 # for variety

models <- list(model1 = lm(len ~ supp*dose, ToothGrowth),
               model2 = lm(len ~ dose*supp, ToothGrowth),
               model3 = lm(len2 ~ dose*supp, ToothGrowth),
               model4 = lm(len2 ~ supp*dose, ToothGrowth))

models2 <- list(model1 = lm(len ~ supp, ToothGrowth),
               model2 = lm(len ~ dose, ToothGrowth),
               model3 = lm(len2 ~ dose, ToothGrowth),
               model4 = lm(len2 ~ supp, ToothGrowth))

# one model
purrr::map(models, ~ anova_test(.x, type = 3))

# now with model for error term
purrr::map2(models, models2, ~ anova_test(.x, error = .y, type = 3))
#> Coefficient covariances computed by hccm()
#> Coefficient covariances computed by hccm()
#> Coefficient covariances computed by hccm()
#> Coefficient covariances computed by hccm()
#> $model1
#> ANOVA Table (type III tests)
#>
#>      Effect DFn DFd      F        p p<.05   ges
#> 1      supp   1  58  4.058 0.049000     * 0.065
#> 2      dose   1  58 12.717 0.000734     * 0.180
#> 3 supp:dose   1  58  1.588 0.213000       0.027
#>
#> $model2
#> ANOVA Table (type III tests)
#>
#>      Effect DFn DFd      F        p p<.05   ges
#> 1      dose   1  58 33.626 2.92e-07     * 0.367
#> 2      supp   1  58 10.729 2.00e-03     * 0.156
#> 3 dose:supp   1  58  4.200 4.50e-02     * 0.068
#>
#> $model3
#> ANOVA Table (type III tests)
#>
#>      Effect DFn DFd      F        p p<.05   ges
#> 1      dose   1  58 36.028 1.35e-07     * 0.383
#> 2      supp   1  58  7.128 1.00e-02     * 0.109
#> 3 dose:supp   1  58  2.709 1.05e-01       0.045
#>
#> $model4
#> ANOVA Table (type III tests)
#>
#>      Effect DFn DFd      F        p p<.05   ges
#> 1      supp   1  58  2.684 0.107000       0.044
#> 2      dose   1  58 13.566 0.000508     * 0.190
#> 3 supp:dose   1  58  1.020 0.317000       0.017

A: Thanks to Nirgrahamuk from the rstudio community forum for this answer:
map(names(models_1) ,
    ~ anova_test(data=group_by(df,edge),
                 formula = as.formula(paste0(.x,"~ trt")),
                 error = models_1[[.x]],
                 type = 3))

(see their full answer at: https://community.rstudio.com/t/trouble-using-group-by-and-map2-together/66730/8?u=mvula)
Created on 2020-05-20 by the reprex package (v0.3.0)


text:
Q: Can't Knit R Markdown File When I Use ggplot with it I'm currently doing an R Markdown File of an analysis I recently finished using R. With that, whenever I add details, I click Knit to ensure everything I added goes well on the HTML knit file.
I noticed that when I used ggplot on my R Markdown file, the file doesn't knit anymore and it says:

Error while opening file - No Such File or directory.

But when I deleted the ggplot command, it gets knitted again.

But this time, without the visualization, it gets knitted again.

UPDATE: I see this error message on the console tab everytime I use ggplot on my .rmd file.
So with that, I call on install.packages("ggplot2") & library("ggplot2") on my .rmd file. However, I get this error instead.

How will I be able to retain the ggplot command and at the same time be able to knit the file? As an added reference, the ggplot command executes on the .rmd file, it just doesn't knit. Can someone help me please?


text:
Q: Multiply span text based on radio button and Jquery slider selection I am trying to put together a selection flow for a product, and I am having a slight issue with defining a value.
Essentially what I am trying to do is have a total output based on which option they choose which is multiplied by the amount of lines. I'm not sure on how to do this however as the slider doesn't go up in regular increments.

$("#slider").slider(
    {
        value:1,
        min: 0,
        max: 9,
        step: 1,
    }
);

var items =[ '1
line','2
lines','3
lines','4
lines','5
lines','8
lines','10
lines','15
lines','20+
lines'];

var s = $("#slider");

s.slider({
  min:1,
  max:items.length
});

var oneBig = 100 / (items.length - 1);

$.each(items, function(key,value){
  var w = oneBig;
  if(key === 0 || key === items.length-1)
    w = oneBig/2;

  $("#legend").append(""+value+"</laben>");

});

//sum start ///////////////

$(":radio").on("change", function(){
    var total = 0;
    $(":radio:checked").each(function(){
        total += Number(this.value);
    });

   $("#total").text(total);
});
h3 {
  margin-top:30px;
}

#slider label {
    position: absolute;
    width: 20px;
    margin-left: -10px;
    text-align: center;
    margin-top: 20px;
}

#slider {
    width: 100%;
    margin: 2em auto;
}

.lines {
    font-size:10px;

}

label {
    display: inline-block;
    text-align:center;
    line-height: 1.5;
    font-weight:bold;
}
label:first-child {
    text-align:left;
}
label:last-child {
    text-align:right;
}

.slide-col #slider a {
    border: 1px solid #fff;
    background: #1b2a3d;
}
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/smoothness/jquery-ui.min.css" rel="stylesheet" type="text/css" />

<input class="qty1" name="phone" type="radio" value="5.99" />option 1
<input class="qty1" name="phone" type="radio" value="9.99" />option 2
<input class="qty1" name="phone" type="radio" value="7.99" />option 3

Your total is: £0.00

A: Update: You may customize slider's values. Also adding function to calculate total value.

let $slider = $('#slider'),
    $legend = $('#legend'),
    $total = $('#total'),
    total = 0,
    lines = [1, 2, 3, 4, 5, 8, 10, 15, 20];

lines.forEach( (value, key) => {
  let oneBig = 100 / (lines.length - 1);
  let width = (key === 0 || key === lines.length -1) ?
              oneBig / 2 : oneBig;
  let text = (key !== lines.length - 1) ?
              value + '
lines' : value + '+
lines';
  let label = $('')
                .css({ 'width': width + '%'})
                .html(text);
  $legend.append(label);
});

$(":radio").on("change", function(){
  updateTotal(lines[$slider.slider("option", "value")]);
});

$slider.slider({
  value: 0,
  min: 0,
  max: 8,
  step: 1,
  create: () => {
    updateTotal(lines[$slider.slider('value')]);
  },
  slide: (events, ui) => {
    updateTotal(lines[ui.value]);
  }
});

function updateTotal (value) {
  total = value * $("input[name='phone']:checked").val();
  $total.text(total.toFixed(2));
}
h3 {
  margin-top: 10px;
}

#slider label {
    position: absolute;
    width: 20px;
    margin-left: -10px;
    text-align: center;
    margin-top: 20px;
}

#slider {
    width: 100%;
    margin: 1em auto;
}

.lines {
    font-size:10px;

}

label {
    display: inline-block;
    text-align:center;
    line-height: 1.5;
    font-weight:bold;
}
label:first-child {
    text-align:left;
}
label:last-child {
    text-align:right;
}

.slide-col #slider a {
    border: 1px solid #fff;
    background: #1b2a3d;
}
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/smoothness/jquery-ui.min.css" rel="stylesheet" type="text/css" />

<input class="qty1" name="phone" type="radio" value="5.99" checked/>option 1
<input class="qty1" name="phone" type="radio" value="9.99" />option 2
<input class="qty1" name="phone" type="radio" value="7.99" />option 3

Your total is: £0.00

A: Try something like this : http://jsfiddle.net/b64Ug/224/
if you notice, I have attached the 'slide' attribute to your slider which will be invoked every time the slider value changed. You may want to add some checks for the edge cases.
$("#slider").slider(
    {
        value:1,
        min: 0,
        max: 9,
        step: 1,
    }
);
var valueMap = [0, 1, 2, 3, 4, 5, 8, 10, 15, 20];

var items =[ '1
line','2
lines','3
lines','4
lines','5
lines','8
lines','10
lines','15
lines','20+
lines'];

var s = $("#slider");

s.slider({
  min:1,
  max:items.length,
  slide: function( event, ui ) {
        $("#total").text("$" +  (valueMap[ui.value] * $('input[name=phone]:checked').val()));
      }
});

var oneBig = 100 / (items.length - 1);

$.each(items, function(key,value){
  var w = oneBig;
  if(key === 0 || key === items.length-1)
    w = oneBig/2;

  $("#legend").append(""+value+"</laben>");

});

//sum start ///////////////

$(":radio").on("change", function(){
    var total = 0;
    $(":radio:checked").each(function(){
        total = Number(this.value) * valueMap[Number($( "#slider" ).slider( "value" ))];
    });

   $("#total").text(total);
});


text:
Q: Convert normal Python script to REST API Here I have an excel to pdf conversion script. How can I modify it to act as a REST API?
import os
import comtypes.client
SOURCE_DIR = 'D:/projects/python'
TARGET_DIR = 'D:/projects/python'
app = comtypes.client.CreateObject('Excel.Application')
app.Visible = False
infile = os.path.join(os.path.abspath(SOURCE_DIR), 'ratesheet.xlsx')
outfile = os.path.join(os.path.abspath(TARGET_DIR), 'ratesheet.pdf')
doc = app.Workbooks.Open(infile)
doc.ExportAsFixedFormat(0, outfile, 1, 0)
doc.Close()
app.Quit()

A: You can use Python's Flask lightweight Rest Framework to make your program accessible for REST Calls. Check this tutorial: http://flask.pocoo.org/docs/1.0/tutorial/
There you can simply get the file input in POST format and once the file is converted send a downloadable link to the end user. You have to tweak this code I wrote with a friend for similar purposes:
import os
from flask import Flask, request, redirect, url_for
from werkzeug import secure_filename

PROJECT_HOME = os.path.dirname(os.path.realpath(__file__))
UPLOAD_FOLDER  = '{}/uploads/'.format(PROJECT_HOME)
ALLOWED_EXTENSIONS = set(['txt','pdf', 'vcf'])

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS

@app.route("/", methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        file = request.files['file']
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            _path = os.path.abspath("<FILE PATH>")
            uf = str(uuid.uuid4())
            # DO YOUR AMAZING STUFF HERE
            return redirect(url_for('index'))
    return """
    <!doctype html>
    <title>Upload new File</title>

Upload new File

    <form action="" method=post enctype=multipart/form-data>

<input type=file name=file>
         <input type=submit value=Upload>
    </form>

%s

    """ % "
".join(os.listdir(app.config['UPLOAD_FOLDER'],))

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=5001, debug=True)