text:
Q: Windows Store app live tiles with images from pictures library I have an application that saves images to the pictures library. That works fine as I added permissions to use the pictures library in the app manifest.
I am now trying to create a live tile that will show these images which were saved to the picture library but i can't seem to get that working.
I saw that it is possible to create a URI to the app local folder or to the app installed folder, but I didn't find an example of using an absolute path or a relative path to the pictures library.
Any help would be appreciated
Thanks
XmlDocument wideTileXml = TileUpdateManager.GetTemplateContent(TileTemplateType.TileWide310x150Image);
XmlNodeList wideTileImageAttributes = wideTileXml.GetElementsByTagName("image");
((XmlElement)wideTileImageAttributes[0]).SetAttribute("src", fileAbsPath);
((XmlElement)wideTileImageAttributes[0]).SetAttribute("alt", "");

// Create a new tile notification.
updater.Update(new TileNotification(wideTileXml));

A: As described on http://msdn.microsoft.com/en-us/library/windows/apps/hh465439.aspx, tile image references can use ms-appx:///, ms-appdata:///, or http[s]:// URIs. That is.
As you suggest, then, you need to copy the image from the pictures library to your local app data. Use the StorageFile.copyAsync method for this. Also be aware, however, that tile images are limited to 200KB, and it's likely that most of the images in the Pictures library are far larger than that. This means that you'll need to change the size in the process. Scenario 2 of the Simple imaging sample has code for this.
Alternately, you can first call StorageFile.getScaledImageAsThumbnailAsync for the image in Pictures, requesting a thumbnail size appropriate for the tile template you're using. The thumbnail itself is returned as a StorageItemThumbnail which is a random access stream, so you'll need to copy those bytes into the file in local app data. You should be able to use the Simple imaging sample code again, picking it up where you have the input stream and going from there.
Another piece of code that I'll mention is written in JavaScript, but might be useful: it's scenario 11 of the JavaScript App tiles and badges sample, which is an image editor for tiles. You might be able to use some of the code here, though you'd have to translate to C#.


text:
Q: How to type "line1", "line2", "line3".... using for loop in python For example, I want to generate below output using a "for" loop, having the for loop automatically populate the number at the end of the word line:
line1
line2
line3
line4
line5
line6
line7

A: Here is how to do it with "f-strings" and the range() class object in a for loop:
for_loop_basic_demo.py:
#!/usr/bin/python3

END_NUM = 7
for i in range(1, END_NUM + 1):
    print(f"line{i}")

Run command:
./for_loop_basic_demo.py

Output:
line1
line2
line3
line4
line5
line6
line7

Going further: 3 ways to print
The 3 ways I'm aware of to print formatted strings in Python are:

*

*formatted string literals; AKA: "f-strings"

*the str.format() method, or

*the C printf()-like % operator

Here are demo prints with all 3 of those techniques to show each one for you:
#!/usr/bin/python3

END_NUM = 7
for i in range(1, END_NUM + 1):
    # 3 techniques to print:

    # 1. newest technique: formatted string literals; AKA: "f-strings"
    print(f"line{i}")

    # 2. newer technique: `str.format()` method
    print("line{}".format(i))

    # 3. oldest, C-like "printf"-style `%` operator print method
    # (sometimes is still the best method, however!)
    print("line%i" % i)

    print() # print just a newline char

Run cmd and output:
eRCaGuy_hello_world/python$ ./for_loop_basic_demo.py
line1
line1
line1

line2
line2
line2

line3
line3
line3

line4
line4
line4

line5
line5
line5

line6
line6
line6

line7
line7
line7

References:

*

****** This is an excellent read, and I highly recommend you read and study it!: Python String Formatting Best Practices

*Official Python documentation for all "Built-in Functions". Get used to referencing this: https://docs.python.org/3/library/functions.html

*

*The range() class in particular, which creates a range object which allows the above for loop iteration: https://docs.python.org/3/library/functions.html#func-range

A: You can use f strings.\
n = 7
for i in range(1, n + 1):
    print(f"line{i}")

redpajama_set_name: RedPajamaStackExchange


text:
Q: Discontinuous bijection from $[0,1]$ to $[0,1]$ Is it possible to construct a bijection from $[0,1]$ to $[0,1]$ with odd number of points of discontinuity ?
Thanks in advance

A: Yes. Think about graphs; can you draw a bijection with only one discontinuity? As an example, $$f(x)=\begin{cases}x &:\ x\in[0,1/2)\\ 3/2-x &:x\in[1/2,1]\end{cases}.$$

A: Yes. For example, $$f(x)=\begin{cases}\frac{1}{2} & x=0 \\ 1 & x = \frac{1}{2}\\0 & x=1 \\ x &\text{otherwise}\end{cases}$$

A: Just draw the graph of $y=x$. Choose any odd no. of points in $[0,1]$ and exchange their values. You are done.
Another solution will be $T$ at an angle of 45 degrees with upper half of its stand deleted.


text:
Q: Organize a excel sheet with a macro I have a really big Excel sheet with 2000 rows.
In the sheet I have names and next to the name a lot of "NO" and one "YES".
Each column has a different name.
I want to have a macro which automatically give me a sheet with the name and next to the name the name of the columns in which I have a "YES".
For example:
Name     A    B    C    D
God      NO   NO   YES  NO
Gosch    YES  NO   NO   NO
Josch    NO   YES  NO   NO
ME       NO   NO   YES  NO

Should look like:
Name
God    C
Gosch  A
Josch  B
ME     C

A: Try this:
Sub Demo()
    Dim srcSht As Worksheet, destSht As Worksheet
    Dim lastRow As Long, i As Long

    Set srcSht = ThisWorkbook.Sheets("Sheet3")  'change Sheet3 to your data sheet
    Set destSht = ThisWorkbook.Sheets("Sheet4") 'change Sheet4 to your output sheet

    With srcSht
        lastRow = .Cells(.Rows.Count, "A").End(xlUp).row    'last row in source sheet using column A
        destSht.Cells(1, 1) = "Name"
        destSht.Cells(1, 2) = "Column"
        For i = 2 To lastRow
            destSht.Cells(i, 1) = .Cells(i, 1)      'enter name in output sheet
            destSht.Cells(i, 2) = .Evaluate("=INDEX($B$1:$E$1,1,MATCH(""YES"",B" & i & ":E" & i & ",0))")   'enter column name in output sheet
        Next i
    End With
End Sub

You can do this easily using formula as below.
Enter the following formula in Cell G2
=INDEX($B$1:$E$1,1,MATCH("YES",B2:E2,0))

Drag/Copy down as required. See image for reference.


text:
Q: How to create a report in oracle report builder with text displayed only at the bottom of last page I am having a boilerplate text that should be printed on bottom of the last page of the report. But report builder wouldn't let me have the "print object on" property to "last" due to the reason suggested here: http://oracle.ittoolbox.com/groups/technical-functional/oracle-apps-l/error-while-setting-one-frame-property-to-last-page-914513
The solution/workaround seems to be there in a link in that page but it isn't displayed by the site it seems. If someone has a workaround please help me out here.
Edit: The boiler plate text should be outside the margin as per the requirement along with the page number.
Thanks.

A: I don't know the "workaround" but the way I'd do this is put the object in the normal print area, set Print Object On to Last Page, and change the margin so that it will be printed at the correct location. The page number will still be in the margin, but you can offset it back into the page area to sit on the same line as the boilerplate text if you wish.
+------------------------------------------------+
|                                                |
|                     margin                     |
|   +----------------------------------------+   |
| m |                                        | m |
| a |                                        | a |
| r |                                        | r |
| g |                                        | g |
| i |                                        | i |
| n |                                        | n |
|   |                                        |   |
|   |                                        |   |
|   |                                        |   |
|   |Boilerplate Text (Last Page)     PageNo |   |
|   +----------------------------------------+   |
+------------------------------------------------+

The "Boilerplate Text (Last Page)" bit is defined within the report page area, whereas the "PageNo" bit is defined in the margin area. Notice how I've reduced the bottom margin height.

A: i think i did something like that recently by checking if 'current page' == 'last page'
use 2 page number fields and a format trigger.
if i can find my old example i'll update this later.


text:
Q: .net Web Application set start page by code When creating a web application that doesn't have a "~/default.aspx" page, we would like to set the starting page to be "~/Pages/MyStartPage.aspx".
I know that the starting page property can be set in the IIS, or when we go to Project->Properties->Web-> and Set the Starting action to "Specific Page"=Pages/MyStartPage.aspx
Those options are not suitable to me since i need to do it by code.
Is there a class or setting in web.config that i can change that does that for me?
Thanks,
Maxim

A: I think your only option is to create a trivial Default.aspx page which generates a Response.Redirect to the other page.
The problem is that IIS does not ask your application what the starting URL should be; instead it tries the first one in its list against your application. So I don't think this can be configured inside your application.
If your site is set up to pass all requests to ASP.NET regardless of whether the file on disk exists (i.e. a wildcard mapping in IIS) then you can probably intercept the original ~/ request in global.asax and route that in code there. But if you can't configure the default document yourself in IIS I'd doubt you can set that up either - and setting up a wildcard mapping is I think a far too generally disruptive solution to just implement this one case anyway.

A: How about putting this in Default.aspx?
protected void Page_Load(object sender, EventArgs e)
{
    this.Response.Redirect("~/Pages/MyStartPage.aspx");
}

Or use Server.Transfer instead if you prefer.  You can even use fancy switching logic to send people to different places if your heart so desires.


text:
Q: Gnome shell: pressing the super key does not work I am using 11.10 with Gnome 3.2 and completely loving it. On one computer it works like a charm, but on another computer the super does not show the activities window. Mousing over the top-left corner does bring up the window, so I am not totally blocked, but I am really missing being able to just press the key to get there.
Does anybody have a clue how I could fix this?
[update]
In System Settings, Keyboard, there is an option to change the shortcut for Show the activities overview, but I can't set it to super (I guess because it is considered to be a modifier-key). Any idea how I can solve that?

A: Okay. You might have locked your super button.
Try unlock it on your keyboard. It usually has two icons - a window key and a lock.
In my case, I have unlocked the super button by pressing
Right Fn + F12
Then everything is working perfectly.
Update:
My another keyboard is unlocked with FN + WINDOW key.

A: Under gnome 3.4.2.1, I had to use "Meta is mapped to Win keys".
Now shortcuts with Super key work now.

A: finally found it myself.
In older Ubuntu versions, go to System Settings > Keyboard Layout > Layouts and then choose Options.
In newer Ubuntu versions, install Tweaks (sudo apt install gnome-tweaks) and open it, then Keyboard & Mouse and then choose Additional Layout Options.
There is an option for the Alt/Win key behaviour and there I had the option selected Meta is mapped to Win keys.
Deselecting that option, and choosing Alt and meta are on Alt keys fixes it for me. At least the super is working again to access the Activities. Not quite sure what the impact is of this choice.

A: In my case, I figured it was because "Overview Shortcut" was mapped to "Left Super", but I was clicking on "Right Super".
Install tweaks and go to "Keyboard & Mouse" tab as follows:

A: In case you use a laptop stand with an additional keyboard unplugging re plugging the additional keyboard might fix the issue with the super/activity key.

A: Gnome tweaks does not work for me. You can see the shortcuts from Settings > Keyboard > View and Customize Shortcuts, as the OP suggests.
Gnome developers apparently decided to map it to <Super + S> at some point. I can't change it back to Super either, but this at least tells you what it is mapped to.


text:
Q: NP Hard Longest Path Acyclic Modified I got stuck with this problem since the whole day.
When we are finding the longest path in a graph we first do topological sorting and then check the path of adjacent vertices and keep upgrading selecting the maximum of the edge weight or the alternate path from the other vertex.
So, we are able to solve this problem because of topological sorting which can be done only for acyclic graphs. Thus this type of question can be solved only for acyclic graph.

So, we are able to solve this problem because of topological sorting which can be done only for acyclic graphs. Thus this type of question can be solved only for acyclic graph.
Now, if I present another case. What if all the edge have the same weight and we don't look in the cycle of the graph. Is this solvable. Everytime I think about this I don't see any use of topological sorting if we can choose any source considering we have to choose the maximum number of nodes(longest path).
Is this also NP Hard or can we solve this?
PS : I went through this Longest acyclic path in a directed unweighted graph but there is just the algorithm to solve the longest path problem.

A: It's not clear what you mean by "not looking in the cycle", so I'll assume you mean that we don't consider taking edges between vertices in a cycle in our longest path.  In this case, you can compress your cycles into single vertices and use the algorithm you describe above.


text:
Q: How do you pass data from current activity to Previous activity I am trying to pass a value from Activity 3 to Activity 2 but I am getting null Value. If I click Back button its going to previous Activity but value is null.  Added the suggested Approach code below. but still not able to get the results.
Suggested Approach:

Activity :3

   override fun onBackPressed() {
        sendDataBackToPreviousActivity()
        super.onBackPressed()
     }

    private fun sendDataBackToPreviousActivity()
    {
        val navBarTitle21=intent.getStringExtra(TestProjectMenuViewHolder.TEST_TITLE_NAME)
        val intent=Intent().apply { putExtra("ReturnMessage",navBarTitle21)}
        setResult(Activity.RESULT_OK,intent)
    }

    Activity:2

    Main Class:
        companion object {
        const val START_ACTIVITY_3_REQUEST_CODE = 0
    }
  val intent=Intent(this,TestProjectMenuDetail::class.java)
        startActivityForResult(intent, START_ACTIVITY_3_REQUEST_CODE)

    Declared outside Main Class:

       override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (requestCode == START_ACTIVITY_3_REQUEST_CODE) {
            if (resultCode == Activity.RESULT_OK) {
                val message = data!!.getStringExtra("ReturnMessage")
                Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
                println("Message Value: $message")
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data)
        }
    }

First Approach:
    Activity:3
    val navBarTitle= intent.getStringExtra(TestMenuViewHolder.TEST_TITLE_KEY)
        supportActionBar?.title=navBarTitle//Something Like "StackOverFlow". THis is for back Button
            TestMenuDetail:
            val navBarTitle2=intent.getStringExtra(TestMenuViewHolder.TEST_TITLE_NAME)
            val TestVar=Intent(this@TestMenuDetail,TestMenuList::class.java)
            intent.putExtra("TestVar2",navBarTitle2)
            println("Test Value $navBarTitle2")//Test Value Hello

    Activity:2
    TestMenuList:
            val navBarTitle3=intent.getStringExtra("TestVar2")
            println("Helllo Test: $navBarTitle3")//Helllo Test: null

A: You should use startActivityForResult API to achieve your task.
Activity2.kt
class Activity2 : AppCompatActivity() {
    companion object {
        const val START_ACTIVITY_3_REQUEST_CODE = 0
    }

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

        // Start Activity3
        val intent = Intent(this, Activity3::class.java)
        startActivityForResult(intent, START_ACTIVITY_3_REQUEST_CODE)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (requestCode == START_ACTIVITY_3_REQUEST_CODE) {
            if (resultCode == Activity.RESULT_OK) {
                val message = data!!.getStringExtra("message")
                Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data)
        }
    }
}

Activity3.kt
class Activity3 : AppCompatActivity() {

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

    override fun onBackPressed() {
        sendDataBackToPreviousActivity()
        super.onBackPressed()
    }

    /**
     * Send data back to previous activity which start this one, you can call this method when users press on back key
     * or when users press on a view (button, image, etc) on this activity.
     */
    private fun sendDataBackToPreviousActivity() {
        val intent = Intent().apply {
            putExtra("message", "This is a message from Activity3")
            // Put your data here if you want.
        }
        setResult(Activity.RESULT_OK, intent)
    }
}

A: Ok here is what I would do:
Override the onBackPressed method and then pass the variable value inside the method with an Intent. And in activity 2 receive the value from activity 3.
In activity 3
@override
public void onBackPressed (){

    Intent intent = new Intent(getApplicationContext(), Activity2.class);

    intent.put("value_key", value);
    startActivity(intent);
}

Receive value in activity 2
getIntent.getValue("value_key");

Don't forget to check the syntax, I just wrote it from my phone. Hope it helps!

A: You can always use SharedPreferences, and then clear them, after receiving data in previous activity. It's 100% effective way. Put it:
val sharedPreference =  getSharedPreferences("prefs name",Context.MODE_PRIVATE)
var editor = sharedPreference.edit()
editor.putString("your value name","value")
editor.commit()

and get it:
sharedPreference.getString("your value name","default value")

but of course you have to open preferences again in previous activity ;)
val sharedPreference =  getSharedPreferences("prefs name",Context.MODE_PRIVATE)


text:
Q: Im trying to programmatically insert a WebView into my Code I have a surfaceview with a click listener attached to it.
When i click it, it shrinks it to half the width and half the Height... and places it in the Lower Right Corner via:
RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(
    getWindowManager().getDefaultDisplay().getWidth()/2,
    getWindowManager().getDefaultDisplay().getHeight()/2
);
rlp.setMargins(
  getWindowManager().getDefaultDisplay().getWidth()/2,
  getWindowManager().getDefaultDisplay().getHeight()/2,
  0,
  0);

It works as intended, but i want to place behind it Dynamically a webView.
I tried:
WebView wv = makeWebView();
//makeWebView(); is a method of my mainActivity, which simple does.
private Webview makeWebView(){ return new WebView(this); }

I cant seem to get it to be behind everything else though.  Am i doing something wrong?
my XML:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/RR1"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >

<LinearLayout
    android:id="@+id/LL1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <SurfaceView
        android:id="@+id/surfaceView1"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

</RelativeLayout>

my MainActivity:
package com.example.testfortim;

import android.os.Bundle;
import android.app.Activity;
import android.graphics.Color;
import android.view.Gravity;
import android.view.Menu;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //SurfaceView sv = new SurfaceView();
    SurfaceView sv = (SurfaceView)findViewById(R.id.surfaceView1);
    sv.setOnClickListener(new OnClickListener(){

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            LinearLayout ll = (LinearLayout)findViewById(R.id.LL1);
            //LinearLayout.LayoutParams llp = (LinearLayout.LayoutParams)ll.getLayoutParams();
            //RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(ll.getLayoutParams().width/2,ll.getLayoutParams().height/2);//(RelativeLayout.LayoutParams)ll.getLayoutParams();
            RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(
                    getWindowManager().getDefaultDisplay().getWidth()/2,
                    getWindowManager().getDefaultDisplay().getHeight()/2
                    );
            rlp.setMargins(getWindowManager().getDefaultDisplay().getWidth()/2, getWindowManager().getDefaultDisplay().getHeight()/2, 0, 0);
            ll.setLayoutParams(rlp);

            WebView wv = makeWebView();
            //wv.setBackgroundColor(0);
            //wv.setBackgroundResource(R.color.Blue);
            //wv.setBackgroundResource(Color.BLUE);
            wv.loadData("TEST", "text/html", "utf-8");
            RelativeLayout rl = (RelativeLayout)findViewById(R.id.RR1);
            //rl.addView(wv);

            //ll.addView(wv);

        }

    });

}

protected WebView makeWebView() {
    return new WebView(this);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
}

}

I resized the Linear Layout and moved that, so the Webview would need to be placed somewhere in RR1, from what i gather.   I was looking at various documentation, and it either wasnt quite what iw as looking for or MAYBE by randomness, i just didnt grasp it.
Do you have ideas as to how this is accomplished?
As a sidenote:  I have no idea why the onCreateOptionMenu method is there.  I dont plan on using it, and will prolly end up removing it.

A: Try rl.addView(wv, 0);
will do the trick :)


text:
Q: How to detect if file is mp3 using Apache tika TypeDetector? How with apache tika can I detect if file is mp3?
I am not looking for just file extension based detection.
I am using:
typeTika = new Tika(new TypeDetector());

but when I try detect a type answer is always:
     application/octet stream

(whatever I send: mp3, image etc it's always application/octet stream)
What can I do to determine if file is mp3 or not?
This question is not a duplicate.
Here someone use Tika with file extension detection.
This is not enough for me.
I need to know if file is mp3 or not based on file type and not on a file name. I can't find any info in documentation how to do this.
TypeDetector always return application/octet stream for all files types so I want to know how to use it to get info if file is mp3 or not.

A: Taken from the Apache Tika examples:
File file = new File("/path/to/file.mp3");

Tika tika = new Tika();
String type = tika.detect(file);
System.out.println(file + " : " + type);

That will detect on both the file contents and the file name. For an MP3 file, you'll get back audio/mpeg

A: Apache Tika can detect the MIME Type of each file. These days it's very common to use Multipurpose Internet Mail Extensions file type designators (MIME), and each file format has got its own MIME. In the following some of them are mentioned: (For more visit iana.org or fileformats.archiveteam.org)

*

*.mp3  --> audio/mpeg

*.mp4  --> video/mp4

*.flac --> audio/x-flac or audio/flac

*.png  --> image/png

*.jpg  --> image/jpeg

*.pdf  --> application/pdf

*.jar  --> application/java-archive
To use Tika in your project add the following maven dependency to your pom file:
<!-- Apache Tika: detects and extracts metadata and text from a variety of files -->
<dependency>
    <groupId>org.apache.tika</groupId>
    <artifactId>tika-core</artifactId>
    <version>2.0.0</version>
</dependency>

And then use the mentioned code to detect your file's MIME type.
File file = new File("/path/to/music.mp3");
Tika tika = new Tika();
String mimeType = tika.detect(file);
System.out.println(mimeType); // Prints the MIME type of the file


text:
Q: Tweeting from within meteor application I am trying to build an app with Meteor that involves the user signing in with twitter, facebook, or google+, and then posting to those accounts from within the application.
First I'm trying to get twitter to work. I have my twitter sign in working, with the permission to tweet on their behalf working, but how to I actually send a tweet?
I think I need this: https://dev.twitter.com/docs/api/1.1/post/statuses/update but I can't figure out how the authentication works with Meteor.
Are there any examples that can help me here? Or tutorials?

A: You need an API to help you a bit unless you want to do it manually using REST with Meteor.http. I'd recommend you get meteorite: https://github.com/oortcloud/meteorite
Its installed like a node module via npm install -g meteorite
Meteorite is a wrapper for meteor that lets you use the community packages over at http://atmosphere.meteor.com
The twitter package you could use is twitter-api installed via mrt add twitter-api : https://github.com/Sewdn/meteor-twitter-api
Once added using the server api you can add a tweet via:
Server JS
var twitter = new Twitter();

Meteor.methods({
    postTweet: function (text) {
        if(Meteor.user())
          twitter.postTweet(text),
          return true;
    }
});

Client JS
//Use this in your click handler where you want to post a tweet:

Meteor.call("postTweet", "This is Twweeeeeetttt!", function(err,result) {
    if(!err) {
        alert("Tweet posted");
    }
});

The api takes care of the user's oauth tokens so you don't have to worry too much


text:
Q: Can't login using root account I have Ubuntu installed on VMware on the shell screen I couldn't login with the Username: root and Password I was asked to login with is there a way around this?

A: Because of the tty tag you are using, I consider you just want to use root in tty and not GUI.
While installing you have created a regular user account which is able to use sudo command. in tty login using that user account. then to use root access for running commands use the sudo command:
sudo command-to-run

Remember when running sudo, it will asks for your account password, not root.
If you want to switch to root account you can also use sudo:
sudo -i

or
sudo -s

or even:
sudo su -

You can also select an specific shell to run, like this:
sudo -i /bin/zsh

Enabling root
If you want enable root account, so you are able to login using its credentials:
use one of above solutions to run passwd command to set a password for root account. E.g:
sudo passwd

then it will asks you for a new password. Also use sudo passwd -u root to make sure root account is unlocked now.

If you don't have any other user account to follow above instructions which is weired, use this solution to active your root account.


text:
Q: Swing application UI modelling I'm in the modelling phase of the UI of a Swing application. This application offers different stages of data processing. Each stage depends on the results given by the stage before. The different stages share no common widgets.
The card Layout is not a professionnal choice in my point of view. Do you know any other way to order widgets, or an example of a professionnal application dealing with that same issue?


text:
Q: Offset is not working with importrange in Google Sheet. Is there any workaround? I am trying to use an offset formula with importrange something as below.
=OFFSET(IMPORTRANGE("googlespreadsheetkey","sheet!A1"),MATCH(A5,IMPORTRANGE("googlespreadsheetkey","sheet!A:A"),0)-1,1,2,2)

It is giving me

"Argument must be a range" error.

Seperately, offset and importrange both working fine.
Thank you for any work around.

A: I think the error message means what is says - the first argument to offset must be a range (or what I would call a reference). So if you try doing this for instance
=offset(1,0,0)

instead of
=offset(A1,0,0)

you get the same error message.
In this case importrange is just giving you a set of numbers, not a reference to cell A1 in the other sheet.
If you imported the range into B1 (say) of the current sheet, then you could offset relative to that, but I don't know a way of using offset in another workbook.
So you have to do the import and the offset separately
=importrange("key","sheet1!A:C")

and then (assuming this imports into B1)
=offset(B1,match(A5,importrange("key","sheet1!A:A"),0)-1,1,2,2)

At least importrange is dynamic so if you update a cell in the original spreadsheet it will update in the current spreadsheet.
If what you are hoping to do is to select certain rows and columns from the imported data without having to import all the data into the current sheet first, there is a method for selecting certain rows from a range described here, so with the importrange it would look like this
=query({importrange("key","sheet1!A:C"), arrayformula(row(A:C))}, "select Col2, Col3 where Col4 <3")

*

*this would give you the first two rows and the last two columns (my test data has three columns).

A: I was also lookig to use Offset(importrange ...) but the simplest workaround I found it using an Index function with the following structure.
Index(  importrange(xx), 0 , MATCH( B2, importrange(xx A1:ZZZ1)) )
 in order to bring a full column   OR
Index(  importrange(xx), MATCH( B2, importrange(xx A:A)) , 0 )
 in order to bring a full row
Where the "0" is the key so the function brings all the rows of the desired string o column.

A: Thanks a lot @Tom Sharpe for the "query thing".
I simplified it a little :

=query(importrange("url of the external google sheet","sheet1!$B:$E"), "select Col2, Col3 where Col4 < 3")

(I found that $ is generally a good practice for importranges if you want to let your Google sheets a little bit more independant from each others)
Several tricks to succeed in using that :

*

*select is a sql-like but special google syntax, without from clause in
particular

*in this syntax, column names are imposed by Google and are 'Col'+column number, 1-based (so, first column of the range is Col1, the second is Col2, ..., so here Col4 is $E in the source sheet)

*and those column names are case sensitive ! (so, don't try it with col2 as I did first ...)


text:
Q: #if directive graying out the inactive branch in XCode Is there any setting to gray out the code which is not active in XCode preferences?
Eclipse IDE automatically grays out the inactive branch.
#if 1
    <code 1>
#else
    <code 2>
#endif

For the above code, <code 2> should be grayed out, as it is not active.

A: Xcode does not have this feature built-in. It may be possible to write an Xcode plugin to accomplish this, but you will face the following problems.

*

*The Xcode plugin API is unsupported and undocumented.

*Xcode plugins have to be rewritten for new versions of Xcode

*It is actually difficult to determine if code is active or not.

That last point takes some explaining. Let's say you have the following code
#ifndef SOME_UNUSED_DEFINE
    // Some code
#else
    // Some other code
#endif

Usually, the else code will be inactive. However, if the compiler is passed -DSOME_UNUSED_DEFINE, then it is reversed. The ifndef code block is inactive, and the else code is active.


text:
Q: Python library `arrow` throws AttributeError: unknown attribute: "months" I'm in process of upgrading an existing project. After upgrading arrow to 0.17.0, it starts throwing an exception when on attribute of months.
The issue goes away if downgrade arrow to 0.13.x; but I hope to upgrade to the latest version and fix the issue in the good way. Any input will be highly appreciated.
  ...
  File "/data/app/PROJECT/projectapp/rest/views.py", line 219, in get_precache_redeemable_codes
    create_ts__gte=arrow.now().replace(months=-1).datetime)) \
  File "/data/app/venv3.7/lib/python3.7/site-packages/arrow/arrow.py", line 807, in replace
    raise AttributeError('unknown attribute: "{}"'.format(key))
AttributeError: unknown attribute: "months"

In my application source code, the triggering function call is:
create_ts__gte=arrow.now().replace(months=-1).datetime)) \
  .select_related('customer') \
  .prefetch_related('orderitem_set')

The full trace of exception:
[27/Jan/2021 14:44:32] ERROR [django.request:230] Internal Server Error: /api/redeem/precache/
Traceback (most recent call last):
  File "/data/app/venv3.7/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner
    response = get_response(request)
  File "/data/app/venv3.7/lib/python3.7/site-packages/django/core/handlers/base.py", line 179, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/data/app/venv3.7/lib/python3.7/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
    return view_func(*args, **kwargs)
  File "/data/app/venv3.7/lib/python3.7/site-packages/django/views/generic/base.py", line 70, in view
    return self.dispatch(request, *args, **kwargs)
  File "/data/app/venv3.7/lib/python3.7/site-packages/rest_framework/views.py", line 509, in dispatch
    response = self.handle_exception(exc)
  File "/data/app/venv3.7/lib/python3.7/site-packages/rest_framework/views.py", line 469, in handle_exception
    self.raise_uncaught_exception(exc)
  File "/data/app/venv3.7/lib/python3.7/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception
    raise exc
  File "/data/app/venv3.7/lib/python3.7/site-packages/rest_framework/views.py", line 506, in dispatch
    response = handler(request, *args, **kwargs)
  File "/data/app/venv3.7/lib/python3.7/site-packages/rest_framework/decorators.py", line 50, in handler
    return func(*args, **kwargs)
  File "/data/app/PROJECT/projectapp/rest/views.py", line 219, in get_precache_redeemable_codes
    create_ts__gte=arrow.now().replace(months=-1).datetime)) \
  File "/data/app/venv3.7/lib/python3.7/site-packages/arrow/arrow.py", line 807, in replace
    raise AttributeError('unknown attribute: "{}"'.format(key))
AttributeError: unknown attribute: "months"


text:
Q: DataTable to JSON- lose extra formatting? I'm sure this has been answered somewhere, but I've read dozens of articles and pages with no joy. I need to pass a DataTable from a windows service to an asp.net page. It seemed that serializing to Json seemed a good idea, so I have this:
 [ServiceContract(Namespace = "DataGrabber")]
    public interface IDataGrabber
    {
        [OperationContract]
        [WebInvoke(Method="GET", BodyStyle=WebMessageBodyStyle.Bare, UriTemplate = "/Tables/{tablename}", ResponseFormat=WebMessageFormat.Json)]
        string GetData(string tablename);
    }

public class DataGrabber : IDataGrabber
    {

        public string GetData(string TableName)
        {
            DataTable result;

            switch (TableName)
            {
                case "firstTable":
                    result = Grabber.firstTable;
                    break;
                //SNIP MORE
            }

            return GetJson(result);
        }

        public string GetJson(DataTable dt)
        {
            System.Web.Script.Serialization.JavaScriptSerializer serializer = new

            System.Web.Script.Serialization.JavaScriptSerializer();
            List<Dictionary<string, object>> rows =
              new List<Dictionary<string, object>>();
            Dictionary<string, object> row = null;

            foreach (DataRow dr in dt.Rows)
            {
                row = new Dictionary<string, object>();
                foreach (DataColumn col in dt.Columns)
                {
                    row.Add(col.ColumnName.Trim(), dr[col]);
                }
                rows.Add(row);
            }
            return serializer.Serialize(rows);
        }

And my config:
<?xml version="1.0"?>
<configuration>

  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
  </startup>
  <system.serviceModel>
    <services>
      <service behaviorConfiguration="DefaultBehavior" name="DataGrabber">
      <endpoint address="http://localhost:9001/DataGrabber"
        binding="webHttpBinding" bindingConfiguration="WebBinding" name="Rest"
        contract="DataGrabber.IDataGrabber" />
      </service>
    </services>
    <bindings>
      <webHttpBinding>
        <binding name="WebBinding">
          <security mode="None" />
        </binding>
      </webHttpBinding>
    </bindings>
    <behaviors>
      <serviceBehaviors>
        <behavior name="DefaultBehavior">
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="true"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>
</configuration>

This works OK, but my resulting JSON has lots of escaped quotes, like this:

"[{\"lat\":51.75,\"lng\":-1.25,\"score\":7},{\"lat\":31.780001,\"lng\":35.23,\"score\":7},{\"lat\":47.717999,\"lng\":-116.951599,\"score\":9},{\"lat\":33.990799,\"lng\":-118.460098,\"score\":1},{\"lat\":34.746498,\"lng\":-92.289597,\"score\":10},{\"lat\":-31.9522,...

This is rejected by online parsers, and won't serialize back to a DataTable in my client application. If I strip out all the extra stuff by using the "htmlviewer" instead of "textviewer" while debugging in VS, it's fine for the parsers. I tried using the Newtonsoft library too, and it resulted in similar output- so what am I missing?

A: Typical. Straight after posting I found the answer.
So because I was converting to a string, it was getting double encoded. Instead, I needed to output a stream.
So both my interface and method are now set to return a System.IO.Stream, and the output is generated thus:
return new MemoryStream(Encoding.UTF8.GetBytes(GetJson(result)));


text:
Q: Adding more sense to jquery auto suggestions I have implemented jquery auto suggestions in my application which has a bunch of cities in it. The problem is it showing every strings which has the entered query. if i type how it shows all the strings which has 'how' in it in between..
The following is the list of results i get if i type how but i prefer to get it in a different order which i descrided and i don't want to show other results. I dont want to show other results.
Bhowra Bh
Chalk howa <--------------------------------This should come third
Chowka Ghat
Chowrigacha
Howbagh Jabalpur <--------------------------This should come first
Howrah <------------------------------------This should come second
Khowang
Ladhowal
Majhowalia
MHOW
Mhow
Mount Howrah <------------------------------This should come fourth
Pehowa Road
Pipalwali Chowki
Saheed Ishwar Chowdhary H

how do is make this work. here is the code i use.. or is there any other way to achieve this in javascript without jquery..?
$(".selector").autocomplete(/*parameters*/);

NOTE: I use an array to store the city names and use them as source for auto complete. And i don't use AJAX

A: You can use a callback to do the filtering and sorting yourself.
$(".selector").autocomplete(
  source: function(request, response) {
              // filter parameters based on request.term
              response(/*params*/, request.term);
          }
);

It's also possible to alter the search term at that point, but that wouldn't work in this case.


text:
Q: $lookup returning all data I'm in the following scenario: I have two collections, medicos and clinicas. Medicos is related to clinicas by its ObjectId. What I want is to get just the clinicas who have medicos inside it. So I have this code:
Clinicas.aggregate([
            $group: {
                _id: {
                    nome: "$nome"
                }

            }
        },
        {
            $lookup: {
                from: "medicos",
                localField: "medico.medicoId",
                foreignField: "_id._id",
                as: 'result'
            }
        },

But something is wrong: it returns all medicos in the as: 'result'. For example: I have 4 documents in the medicos collection, and two documents in clinicas collection. The first clinicas has 2 medicos and the second one has 1 but the as: 'result' array brings to me all medicos documents for the 2 clinicas collection, as you can see.
 this have 2 medicos
Model medicos
const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const MedicoSchema = new Schema({
  //cod_medico:{type:Integer},
  nome:{
    type: String,
    required: true,
    maxlength: 80
  },
},
);

module.exports = mongoose.model('medicos', MedicoSchema);

And in the database the collection name is also 'medicos'

A: The error is in the group, you are first changing the id and after this, joining the data using the new id. Try to change the order of the pipeline, or removing the group stage. Like this:
db.clinica.aggregate([
    {
        $lookup: {
            from: "medicos",
            localField: "medico.medicoId",
            foreignField: "_id",
            as: 'result'
        }
    },

])


text:
Q: Moving data to fit new data model I am about to deploy a new version of an app. The new version has a very different structure to it, with many new custom objects. In some cases a custom object has been split into two separate large custom objects. In other cases there are objects in which sections have been moved over to another already existing object.
My big dilemma is how to properly migrate this data to fit the new data model. In a good amount of cases it will involve moving data from one object to another, and I am not sure how to do that.
Can somebody give me some advice or tips on the best way to approach this ?
Thank you very much.

A: It's hard to give any specific advice without knowing the actual complexity, but here is something to get started
Back up current data - use Data Loader to Extract all data and keep a back up
You could refresh a sandbox as a backup of Code / Config before starting any deployment.
Have a pictorial representation of how the old data model relates to the new world and use this to cut up the data into csv files so that they can be imported into the new data tables.
Create External Id fields if it will help you relate data from related child tables to parent tables.
Prepare the csv files, data load into new data structure, save mapping files for repeatable loads.
If you have access to a Full Copy Sandbox, refresh it from Production and rehearse the data split / migration before doing it in Production, so you can uncover any runtime gotchas (triggers, workflows, validation rules, the works...)


text:
Q: How to add Gunicorn to Django app running in docker? I have a django app running with a docker in a Digitalocean droplet.
My question is, where do I add the gunicorn.socket and the gunicorn.service? In the Django Docker app or in the DigitalOcean running the docker?
`gunicorn.socket is:
[Unit]
Description=gunicorn socket

[Socket]
ListenStream=/run/gunicorn.sock

[Install]
WantedBy=sockets.target

and gunicorn.service is:
[Unit]
Description=gunicorn daemon
Requires=gunicorn.socket
After=network.target

[Service]
User=sammy
Group=www-data
WorkingDirectory=/home/sammy/myprojectdir
ExecStart=/home/sammy/myprojectdir/myprojectenv/bin/gunicorn \
          --access-logfile - \
          -k uvicorn.workers.UvicornWorker \
          --workers 3 \
          --bind unix:/run/gunicorn.sock \
          myproject.asgi:application

[Install]
WantedBy=multi-user.target


text:
Q: Opening FileName:LineNumber in Xcode from AppCode I want switch from AppCode to Xcode and continue editing file on the same line.
Solution based on UI Automation seems working.
Is the are any solution how to do the same without UI Automation; without need of showing Open Quickly dialog and typing FileName:LineNumber?
Thanks!

Solution based on UI Automation.
The code below will open File -> Open Quickly ... dialog, then will type into File or Symbol search field and finally will hit Enter:
//
// File: openFileInXcode.scpt
//
function run(argv) {
    locationToOpen = argv[0]
    if (locationToOpen == undefined) {
        doSysLog("Nothing to do. Exiting...")
        return
    }
    openFileinXcode(locationToOpen)
}

function openFileinXcode(location) {
    var appXcode = Application('Xcode')
    appXcode.activate()
    doSysLog("Opening file: " + location)
    delay(0.2)

    var appSysEvents = Application('System Events')
    appSysEvents.keystroke('o', { using: ['command down', 'shift down'] })
    appSysEvents.keystroke(location)
    appSysEvents.keyCode(36)
}

function doSysLog(message) {
    app = Application.currentApplication()
    app.includeStandardAdditions = true
    app.doShellScript('syslog -s -l W "WaveLabs Automation: ' + message + '"')
    console.log(message)
}

Usage from command line:
 osascript -l JavaScript "/path/to/openFileInXcode.scpt" "AppDelegate.swift:11"

Usage from AppCode:

*

*Go to File -> Preferences -> Tools -> External Tools

*Add new tool and configure parameters using macros (i.e. $FileName$:$LineNumber$)

Update 07.06.2016: Detail description of External Tool setup:

*

*Program: /bin/bash

*Parameters: -c "[[ -r ~/.bashrc ]] && . ~/.bashrc; osascript -l JavaScript \"$PATH_TO_YOUR_SCRIPTS_DIR/OpenFileInXcode.scpt\" \"$FileName$:$LineNumber$\""

*Working directory: $ProjectFileDir$


text:
Q: How to read from and write to EEPROM suing SPI communication I am using PIC32MX350F128L Microcontroller to read from and write to EEPROM(SST26VF032B) using SPI communication. SPI communication in this program is working, I have checked it by sending JEDEC code which is provided in the SST26VF032B datasheet. So when i send 0x9F i am getting 3 bytes of data as mentioned in the datasheet. When i run now i am sending a string of data to a specific address of eeprom  and getting 0xff in return. I am erasing the eeprom before writing into it. So i think i am getting 0xff after erasing the eeprom. The writing, reading operations are not working. If i send a string of value or a BYTE i am getting 0xff in return. So can u guys please suggest me where i am going wrong. I am using UART for debugging purpose to read values recieved through spi communication. The complete code is below, i am using MPLAB X.
Best Regards
Sandesh
#include <xc.h>
#include <stdio.h>
#include <plib.h>
#include <p32xxxx.h>

/* Configuration Bits */

#pragma config FSRSSEL = PRIORITY_7     // Shadow Register Set Priority Select (SRS Priority 7)
#pragma config PMDL1WAY = ON            // Peripheral Module Disable Configuration (Allow only one reconfiguration)
#pragma config IOL1WAY = ON             // Peripheral Pin Select Configuration (Allow only one reconfiguration)

// DEVCFG2
#pragma config FPLLIDIV = DIV_2         // PLL Input Divider (2x Divider)
#pragma config FPLLMUL = MUL_20         // PLL Multiplier (20x Multiplier)
#pragma config FPLLODIV = DIV_1        // System PLL Output Clock Divider (PLL Divide by 1)

// DEVCFG1
#pragma config FNOSC = PRIPLL             // Oscillator Selection Bits (Primary Osc (XT,HS,EC))
#pragma config FSOSCEN = ON             // Secondary Oscillator Enable (Enabled)
#pragma config IESO = ON                // Internal/External Switch Over (Enabled)
#pragma config POSCMOD = HS            // Primary Oscillator Configuration (XT osc mode)
#pragma config OSCIOFNC = ON            // CLKO Output Signal Active on the OSCO Pin (Enabled)
#pragma config FPBDIV = DIV_1          // Peripheral Clock Divisor (Pb_Clk is Sys_Clk/8)
#pragma config FCKSM = CSECME           // Clock Switching and Monitor Selection (Clock Switch Disable, FSCM Disabled)
#pragma config WDTPS = PS1048576        // Watchdog Timer Postscaler (1:1048576)
#pragma config WINDIS = OFF             // Watchdog Timer Window Enable (Watchdog Timer is in Non-Window Mode)
#pragma config FWDTEN = OFF             // Watchdog Timer Enable (WDT Disabled (SWDTEN Bit Controls))
#pragma config FWDTWINSZ = WINSZ_25     // Watchdog Timer Window Size (Window Size is 25%)

// DEVCFG0
#pragma config DEBUG = OFF              // Background Debugger Enable (Debugger is Disabled)
#pragma config JTAGEN = OFF             // JTAG Enable (JTAG Disabled)
#pragma config ICESEL = ICS_PGx2        // ICE/ICD Comm Channel Select (Communicate on PGEC2/PGED2)
#pragma config PWP = OFF                // Program Flash Write Protect (Disable)
#pragma config BWP = OFF                // Boot Flash Write Protect bit (Protection Disabled)
#pragma config CP = OFF                 // Code Protect (Protection Disabled)

/* MACRO DEFINITIONS */

/* Defining the Slave Select Pin */
#define SS      LATDbits.LATD9

/* Defining the System Clock Frequency */
#define SYSCLK  40000000

 /* Macro to get array size in bytes
 * note that array size can't be found after passing pointer to a function */
#define LEN(x)  (sizeof(x) / sizeof(x[0]))

/* SST26VF032B EEPROM instructions */

/* Write Enable */
#define WREN    0x06

/* Write Disable */
#define WRDI    0x04

/* Initialize Start of Write Sequence */
#define WRITE   0x02

/* Initialize Start of Read Sequence */
#define READ    0x03

/*  Erase all sectors of Memory */
#define CE      0xc7

/*  Read STATUS Register */
#define RDSR    0x05

/* Function Prototypes */

/* UART bit configuration */
void Bitconfig_uart(void);

/* SPI Initialization */
void SPI1_Init(void);

/* UART Initialization */
void Init_uart(void);

/* Send a Character Byte through UART */
void UART5PutChar(char Ch);

/* Function to Read and Write SPI1 buffer */
int SPI1_transfer( int b);

/* Function to check the Status of SPI */
void waitBusy();

/* Function to erase the contents in EEPROM */
void eraseEEPROM();

/* Function to Read data from EEPROM */
void readEEPROM( int address, char* loadArray, int loadArray_size);

/* Function to Write to EEPROM */
void writeEEPROM( int address, char* storeArray, int storeArray_size);

/* Global Variables Declaration */
/* Declare variables to check the functionality of EEPROM */
int i,j = 0;
char st = 0x9F;
char rec;
int x,y,z;

/*******************************************************************************
* Function Name: main()
********************************************************************************
* Summary:
*  Initializes SPI
*  Erase EEPROM
*  Writes to EEPROM
*  Read from EEPROM
*
* Parameters:
*  None.
*
* Return:
*  None.
*
*******************************************************************************/
int main()
{

    int i;
    /* Clock Setting */
    SYSTEMConfigPerformance(SYSCLK);

    /* UART bit configuration */
    Bitconfig_uart();

    /* Set the Controller OScillator Register bits */
    //OSCCON = 0x00002200;

    /* Initialize a String to Write to EEPROM and an array to Read back contents */
    char writeData[] = "123456789ABCDEF";

    /* Array to read 35 bytes of data */
    char readData[15];

    /* SPI Initialization */
    SPI1_Init();

    /* UART Initialization */
    Init_uart();

    /* Erase contents of EEPROM */
    eraseEEPROM();

    /* Write contents of writeData array to address 180 */
    writeEEPROM( 0x1000, writeData, LEN(writeData));

    /*
     JEDEC Code (working) getting output as per datasheet (0x9F = 159)
    SS=0;
    SPI1_transfer(159);
    x=SPI1_transfer(0);
    UART5PutChar(x);
    y=SPI1_transfer(0);
    UART5PutChar(y);
    z=SPI1_transfer(0);
    UART5PutChar(z);
    */
    while(1)
    {
        /* Read contents of EEPROM into readData array
         * start at address 180 and read up to 180+length(readData) */
        readEEPROM( 0x1000, readData, LEN(readData) );
    }
} /* END main() */

/*******************************************************************************
* Function Name: SPI1_Init()
********************************************************************************
* Summary:
*  SPI1 Initialization
*
* Parameters:
*  None.
*
* Return:
*  None.
*
*******************************************************************************/
void SPI1_Init(void)
{
    /* Configure Peripheral Pin Select (PPS) for the SPI1 module
    * Note: SS will be toggled manually in code
    * SCK is hardwired to pin 55 */

    /* Output Pin Selection */
    RPE5R = 8;
    SDI1R = 3;

    /* RB4 (Slave Select 1) : output */
    TRISDbits.TRISD9 = 0;

    /* SPI configuration */

    /* SPI1CON Register Configuration
     * MSTEN: Master Mode Enable bit = 1 (Master)
     * CKP (clock polarity control) = 0
     * CKE (clock edge control) = 1
     * ON: SPI Peripheral On bit
     * 8-bit, Master Mode */
    SPI1CON = 0x8120;

    /* SPI1BRG Register Configuration */
    SPI1BRG = 0x4D;
    //REFOCONbits.ON = 1;
   // REFOCONbits.DIVSWEN = 1;
}

/*******************************************************************************
* Function Name: SPI1_transfer()
********************************************************************************
* Summary:
*  Write to and Read from SPI1 buffer
*
* Parameters:
*  char b - Writes a Character to Buffer
*
* Return:
*  Char - Returns the Character Read from EEPROM
*
*******************************************************************************/
int SPI1_transfer( int b)
{
    /* write to buffer for TX */
    SPI1BUF = b;

    /* wait transfer complete */
    while(!SPI1STATbits.SPIRBF);

    /* read the received value */
    return SPI1BUF;
} /* END SPI1_transfer() */

/*******************************************************************************
* Function Name: waitBusy()
********************************************************************************
* Summary:
*  Checks if EEPROM is ready to be modified and waits if not ready
*
* Parameters:
*  None.
*
* Return:
*  None.
*
*******************************************************************************/
void waitBusy()
{
    char status = 0;

    do{
        /* Select EEPROM */
        SS = 0;

        /* Read EEPROM status register */
        SPI1_transfer(RDSR);

        /* send dummy byte to receive incoming data */
        status = SPI1_transfer(0);

        /* Release EEPROM */
        SS = 1;
    }

    /* write-in-progress while status<0> set to '1' */
    while( status & 0x01);

} /* END waitBusy() */

/*******************************************************************************
* Function Name: readEEPROM()
********************************************************************************
* Summary:
* Reads data from EEPROM
*
* Parameters:
* Inputs:  address - EEPROM address
*          loadArray - array to load EEPROM data to
*          loadArray_size - number of bytes of EEPROM data to load into array
*
* Return:
*  None.
*
*******************************************************************************/
void readEEPROM( int address, char* loadArray, int loadArray_size)
{
    int i;

    /* Wait until EEPROM is not busy */
    waitBusy();

    /* Select EEPROM */
    SS = 0;

    /* Initiate Read */
    SPI1_transfer( READ);

    /* Address must be 16-bits but we're transferring it in two 8-bit sessions */
    SPI1_transfer( address >> 16);
    SPI1_transfer( address >> 8);
    SPI1_transfer( address);

    /* Request and store loadArray_size number of bytes into loadArray */
    for( i=0 ; i<loadArray_size ; i++)
    {
        /* send dummy byte to read 1 byte */
        loadArray[i] = SPI1_transfer( 0x00);
    }
    /* Release EEPROM */
    SS = 1;

        /* UART Test */
        for(i=0;i<35;i++)
        {
            UART5PutChar(loadArray[i]);
            for(j=0;j<20000;j++)
            {}
        }

} /* END readEEPROM() */

/*******************************************************************************
* Function Name: writeEEPROM()
********************************************************************************
* Summary:
* Write data to EEPROM
*
* Parameters:
* Inputs:  address -  EEPROM address
*          storeArray - array of which contents are stored in EEPROM
*          storeArray_size - number of bytes in array to store into EEPROM
*
* Return:
*  None.
*
*******************************************************************************/

void writeEEPROM( int address, char* storeArray, int storeArray_size)
{
    int i;

    /* Wait until EEPROM is not busy */
    waitBusy();

    /* Select EEPROM */
    SS = 0;

    /* Send WRITE_ENABLE command */
    SPI1_transfer( WREN);

    /* Release EEPROM */
    SS = 1;

    /* Select EEPROM again after WREN cmd */
    SS = 0;

    /* Initiate Write */
    SPI1_transfer( WRITE);

    SPI1_transfer( address >> 16 );
    SPI1_transfer( address >> 8 );
    SPI1_transfer( address );

    /* write 1 byte at a time from array */
    /* MSB at lowest address (0 - first letter in string) */
    for( i=0 ; i<storeArray_size; i++)
    {
            /* Initiate Write */
            SPI1_transfer( WRITE);
            SPI1_transfer( (address+i) >> 16 );
            SPI1_transfer( (address+i) >> 8 );
            SPI1_transfer( address+i );

        SPI1_transfer( storeArray[i]);
    }
    /* Release EEPROM */
    SS = 1;

} /* END writeEEPROM() */

/*******************************************************************************
* Function Name: eraseEEPROM()
********************************************************************************
* Summary:
* Erase entire contents of EEPROM
*
* Parameters:
*  None
*
* Return:
*  None.
*
*******************************************************************************/
void eraseEEPROM()
{
    /* Wait until EEPROM is not busy */
    waitBusy();

    /* Select EEPROM */
    SS = 0;

    /* Send WRITE_ENABLE command */
    SPI1_transfer( WREN);

    /* Release EEPROM */
    SS = 1;

    /* Select EEPROM again after WREN cmd */
    SS = 0;

    /* send CHIP_ERASE command */
    SPI1_transfer( CE);

    /* Release EEPROM */
    SS = 1;

} /* END eraseEEPROM() */

/*******************************************************************************
* Function Name: Init_uart()
********************************************g************************************
* Summary:
* Initialize UART4
*
* Parameters:
*  None
*
* Return:
*  None.
*
*******************************************************************************/
void Init_uart()
{
    /* Enable UART */
   U5MODEbits.ON = 1 ;

   /* set baud rate(9600) */
   U5BRG = 521;

   /* Set U4STA Register for Enabling tx and rx */
   U5STA=0x9400;

}

/*******************************************************************************
* Function Name: UART4PutChar(unsigned char Ch)
********************************************************************************
* Summary:
* Send data from controller to putty GUI
*
* Parameters:
* input
* unsigned char Ch -  To Send a byte of data over UART
*
* Return:
*  None.
*
*******************************************************************************/
void UART5PutChar(char Ch)
{
while(U5STAbits.UTXBF == 1);
U5TXREG=Ch;
}

/*******************************************************************************
* Function Name: Bitconfig_uart()
********************************************************************************
* Summary:
* UART Pin Configuration
*
* Parameters:
*  None
*
* Return:
*  None.
*
*******************************************************************************/
void Bitconfig_uart(void)
{
    /* UART4 Initialization */
   // OSCCON=0x00002200;

    /* Set pins as digital */
    ANSELBbits.ANSB2 = 0;
    ANSELBbits.ANSB0 = 0;

    /* Set UART Tx pin as Output */
    TRISBbits.TRISB0 = 0;  //in controler tx
    TRISBbits.TRISB2 = 1; // in controller RX

    /* Peripheral Pin select for UART4 */
    U5RXR=0x07;
    RPB0R=0x04;
}

A: I faced the same problem for 3 long days until I found that there's a 18bytes long register called Block Protection Register BPR.
You need to set its bits to 0, according to the memory area you want to write.
So I read the BPR (send command 0x72 followed by 18 byte read) and I found it was not at zero everywhere in my case.
Reading on page 41 of the datasheet you can see that after a power on the BPR register is set to 5555 FFFFFFFF FFFFFFFF, so it protects from write the whole memory.
So for testing purpose I tried to clears it completely, and there's a specific command (0x98) for that purpose, allowing you to write anywhere in the whole memory.
But be sure to write enable the memory (command 0x06) before sending the clear BPR command (command 0x98).
At this point if you read the BPR (command 0x72) you will read 00 at every of its 10 bytes. (And this means the whole memory is now writeable)
In this state the write now finally works for me.
(I sent WriteEnable - SectorErase - SectorRead - WriteEnable - SectorWrite - SectorRead and it now works!)
Hope it helps, the datasheet is very chaotic about that.
P.S.
Somewhere the datasheet says that BPR is 18 bytes long, it is wrong, the BPR is only 10 bytes long


text:
Q: OSStatus-43 Error I am keeping recorded audio file reference in SQLite database. When I am fetching the data and trying to play I find the error OSStatus-43. If there is any solution?

A: That's fnfErr for "file not found." Without more specific info or code, I can't help you more. Probably Core Audio is trying to open a file with your audio and the path is wrong.

A: I ran into an error -43 when trying to play a remote mp3 file over http. I got around this by using an AVPlayer instead of an AVAudioPlayer.


text:
Q: How can I express list comprehension in terms of higher order functions? This program has the aim of using a higher-order function to represent a list comprehension, where it takes a function (a -> b) and filter p: (a -> Bool) and a list: [Int] to produce a list. However, a series of errors occur:

*

*Couldn't match expected type Bool -> [Int] with actual type [b0]

*The function map is applied to three arguments, but its type (a1 -> b0) -> [a1] -> [b0] has only two. listcomprehension f p xs = map f filter(p xs)

*Couldn't match expected type a1 -> b0 with actual type (a, b)

*Couldn't match expected type [a1] with actual type (a0 -> Bool) -> [a0] -> [a0].

listcomprehension :: (a -> b) -> (a -> Bool) -> [Int] -> [Int]
 listcomprehension f p xs = map f filter(p xs)
I have tried a different approach where I wrote:
listcomprehension :: (a -> b) -> [Int] -> [Int]
listcomprehension f xs = map f filter(p xs)

The error in the second solution is that p is not in scope. This leads to a dilemma of whether or not to add p as either way it results in an error, the question is how to include p as a parameter in the function?

A:
where it takes a function (a,b).

(a, b) is not a function. (a, b) is a 2-tuple, for a function, you need to rewrite this to a -> b.
Since you only work with a list of Ints, you furthermore can not use a -> b as a mapping function, and a -> Bool as a filtering function. These functions should be f :: Int -> Int and p :: Int -> Bool
You furthermore use the brackets the wrong way. In order to let this work, it should be:
listcomprehension :: (Int -> Int) -> (Int -> Bool) -> [Int] -> [Int]
listcomprehension f xs = map f (filter p xs)
or we can generalize this function further to:
listcomprehension :: (a -> b) -> (a -> Bool) -> [a] -> [b]
listcomprehension f xs = map f (filter p xs)
The above is however not a list comprehension expression. You can implement such list comprehension expression with:
listcomprehension :: (a -> b) -> (a -> Bool) -> [a] -> [b]
listcomprehension f xs = [f x | x <- xs, p x]


text:
Q: Exporting MODIS AOD monthly(mean) composite for 5 years I am writing a code in Google Earth Engine, in which I want to export the image composite of mean monthly MODIS AOD for 5 years.
I am writing the following code, but whenever I try to run it the webpage got hang and says Aw Snap.
var createaodcomposite = function () {
  var yearstart = 2005;
  var yearend = 2009;
  var listaod = ee.Image([]);
  for (var loopYear = yearstart; loopYear <= yearend; loopYear = +1) {
    var start = ee.Date.fromYMD(loopYear, 6, 01);
    var end = ee.Date.fromYMD(loopYear, 12, 25);

    var aod = ee.ImageCollection("MODIS/006/MCD19A2_GRANULES")
      .select('Optical_Depth_047')
      .filterBounds(geometry)
      .filterDate(start, end)
    var finalop = aod.reduce(ee.Reducer.median()).clip(study).rename(loopYear.toString());
    var filename = ("Optical_Depth_047_").concat(loopYear.toString());

    listaod = listaod.addBands(finalop.rename(filename));
  }
  print(listaod, 'List AOD')
  Export.image.toDrive({
    image: listfin,
    description: 'yearly_AOD_ts',
    //Image resolution is 1000m
    scale: 1000,
    region: study,
    crs: 'epsg:4326',
  })
}
var comp = createaodcomposite();
print(comp)

A: In this case, you're good with client-side loop. That is, if you hadn't turned it into an infinite loop.
for (var loopYear = yearstart; loopYear <= yearend; loopYear = +1)

You want this to be:
for (var loopYear = yearstart; loopYear <= yearend; loopYear += 1)


text:
Q: How to bring key pad in windows phone to normal/standard state programatically? I have a windows phone 8 application (chat application). I have a text box for typing messages. When I type a message(and press send), which ends with something like a question mark or exclamatory mark, I need the keypad to show alphabets instead of showing the symbols which I last used. How can I achieve this?
Tell me if I need to post anything else.

A: All you have to do, is put "Chat"-input scope to your textbox.
<TextBox InputScope="Chat" />

If you then press enter, it will change from symbols to the alphabets.
If your sending works with button, then you have to focus to the textbox in send-button's tap event.

A: You could do something like this:
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
this.Loaded += new RoutedEventHandler(MainPage_Loaded);
}

private void MainPage_Loaded(object sender, RoutedEventArgs e)
{
InputScope isScope1 = new InputScope();
InputScopeName isScopeNumber = new InputScopeName();
isScopeNumber.NameValue = InputScopeNameValue.Number;
isScope1.Names.Add(isScopeNumber);

textBox2.InputScope = isScope1;

InputScope isScope = new InputScope();
InputScopeName isScopeName = new InputScopeName();
isScopeName.NameValue = InputScopeNameValue.EmailUserName;
isScope.Names.Add(isScopeName);

textBox3.InputScope = isScope;

}
}

Best reference for this would be:
http://msdn.microsoft.com/en-us/library/windowsphone/develop/hh393998(v=vs.105).aspx
Hope it helps!


text:
Q: How to write generic functions that take types which are themselves generic? I'm looking to write a function that takes different types which primarily differ in (const / mut) of a member, which themselves take a generic type.
To simplify the question, I'm looking to write a function which takes either a constant or mutable struct. eg:
pub struct PtrConst<T> {
    ptr: *const T,
}
pub struct PtrMut<T> {
    ptr: *mut T,
}

How could I write a function that takes either a PtrConst<SomeType> or PtrMut<SomeType>?

This snippet is rather long, but I've attempted to simplify it.
Playbook link.
// ---------------------------------------------------------------------------
// Test Case: This isn't working!

// How to make a generic function?
// See below for 'PtrConst' & 'PtrMut'.

pub trait PtrAnyFuncs {
    fn new() -> Self;
    fn is_null(&self) -> bool;
}

pub trait PtrAny:
    Deref +
    Copy +
    Clone +
    PartialEq +
    PtrAnyFuncs +
    {}

impl<TPtr> PtrAny for TPtr where TPtr:
    Deref +
    Copy +
    Clone +
    PartialEq +
    PtrAnyFuncs +
    {}

fn generic_test<T: PtrAny<MyStruct>>(a: T) {
    if a.is_null() {
        println!("Test: NULL");
    } else {
        println!("Test: {} {}", a.my_val_a, a.my_val_b);
    }
}

// ---------------------------------------------------------------------------
// Attempt to use generic function

struct MyStruct {
    pub my_val_a: usize,
    pub my_val_b: usize,
}

fn main() {
    let mut a: MyStruct = MyStruct { my_val_a: 10, my_val_b: 2, };
    let b: MyStruct = MyStruct { my_val_a: 4, my_val_b: 4, };

    let a_ptr = PtrMut::new(&mut a as *mut MyStruct);
    let b_ptr = PtrConst::new(&a as *const MyStruct);

    generic_test(a_ptr);
    generic_test(b_ptr);
}

// ---------------------------------------------------------------------------
// PtrMut

use std::ops::{
    Deref,
    DerefMut,
};

#[repr(C)]
#[derive(Hash)]
pub struct PtrMut<T> {
    ptr: *mut T,
}

impl<T> PtrAnyFuncs for PtrMut<T> {
    #[inline(always)]
    fn new(ptr: *mut T) -> PtrMut<T> {
        PtrMut { ptr: ptr as *mut T }
    }

    #[inline(always)]
    fn is_null(&self) -> bool {
        self.ptr == ::std::ptr::null_mut()
    }
}

impl<T> PtrMut<T> {
    #[inline(always)]
    pub fn null() -> PtrMut<T> {
        PtrMut { ptr: ::std::ptr::null_mut() }
    }

    #[inline(always)]
    pub fn as_pointer(&self) -> *mut T {
        self.ptr
    }

    // only for 'PtrMut'
    #[inline(always)]
    pub fn as_const(&self) -> PtrConst<T> {
        PtrConst::new(self.ptr as *const T)
    }
}

impl<T> Copy for PtrMut<T> { }
impl<T> Clone for PtrMut<T> {
    #[inline(always)]
    fn clone(&self) -> PtrMut<T> { *self }
}

impl<T> Deref for PtrMut<T> {
    type Target = T;

    #[inline(always)]
    fn deref(&self) -> &T {
        unsafe { &*self.ptr }
    }
}

impl<T> DerefMut for PtrMut<T> {
    #[inline(always)]
    fn deref_mut(&mut self) -> &mut T {
        unsafe { &mut *self.ptr }
    }
}

impl<T> PartialEq for PtrMut<T> {
    fn eq(&self, other: &PtrMut<T>) -> bool {
        self.ptr == other.ptr
    }
}

// ---------------------------------------------------------------------------
// PtrConst

#[repr(C)]
#[derive(Hash)]
pub struct PtrConst<T> {
    ptr: *const T,
}

impl<T> PtrAnyFuncs for PtrConst<T> {
    #[inline(always)]
    fn new(ptr: *const T) -> PtrConst<T> {
        PtrConst { ptr: ptr as *const T }
    }

    #[inline(always)]
    fn is_null(&self) -> bool {
        self.ptr == ::std::ptr::null_mut()
    }
}

impl<T> PtrConst<T> {

    #[inline(always)]
    pub fn null() -> PtrConst<T> {
        PtrConst { ptr: ::std::ptr::null_mut() }
    }

    #[inline(always)]
    pub fn as_pointer(&self) -> *const T {
        self.ptr
    }
}

impl<T> Copy for PtrConst<T> { }
impl<T> Clone for PtrConst<T> {
    #[inline(always)]
    fn clone(&self) -> PtrConst<T> { *self }
}

impl<T> Deref for PtrConst<T> {
    type Target = T;

    #[inline(always)]
    fn deref(&self) -> &T {
        unsafe { &*self.ptr }
    }
}

// no DerefMut for PtrConst, only PtrMut
impl<T> PartialEq for PtrConst<T> {
    fn eq(&self, other: &PtrConst<T>) -> bool {
        self.ptr == other.ptr
    }
}

A: The solution is to make your trait generic over the pointee type:
pub trait PtrAny<T>: ...

impl<T, TPtr> PtrAny<T> for TPtr where TPtr: ...

Note that this doesn't fix your linked code example, because Rust can't abstract over (non-)mutability.

A: Thanks to help from @futile & @oli_obk_ on IRC, here is a working example of the code in the question.

*

*PtrAny and PtrAnyFuncs needed to take a type.

*PtrAnyFuncs needed to use assosiated types so the argument to new could be made generic across *mut and *const.

*Deref needed to declare the type that it de-references to Deref<Target=T>
Working code:
pub trait PtrAnyFuncs<T> {
    type InnerPtr;

    fn new(ptr: Self::InnerPtr) -> Self;
    fn is_null(&self) -> bool;
}

pub trait PtrAny<T>:
    Deref<Target=T> +
    Copy +
    Clone +
    PartialEq +
    PtrAnyFuncs<T> +
    {}

impl<TPtr, T> PtrAny<T> for TPtr where TPtr:
    Deref<Target=T> +
    Copy +
    Clone +
    PartialEq +
    PtrAnyFuncs<T> +
    {}

fn generic_test<T: PtrAny<MyStruct>>(a: T) {
    if a.is_null() {
        println!("Test: NULL");
    } else {
        println!("Test: {} {}", a.my_val_a, a.my_val_b);
    }
}

// ---------------------------------------------------------------------------
// Attempt to use generic function

struct MyStruct {
    pub my_val_a: usize,
    pub my_val_b: usize,
}

fn main() {
    let mut a: MyStruct = MyStruct { my_val_a: 10, my_val_b: 2, };
    let b: MyStruct = MyStruct { my_val_a: 4, my_val_b: 4, };

    let a_ptr = PtrMut::new(&mut a as *mut MyStruct);
    let b_ptr = PtrConst::new(&b as *const MyStruct);

    generic_test(a_ptr);
    generic_test(b_ptr);
}

// ---------------------------------------------------------------------------
// PtrMut

use std::ops::{
    Deref,
    DerefMut,
};

#[repr(C)]
#[derive(Hash)]
pub struct PtrMut<T> {
    ptr: *mut T,
}

impl<T> PtrAnyFuncs<T> for PtrMut<T> {
    type InnerPtr = *const T;

    #[inline(always)]
    fn new(ptr: Self::InnerPtr) -> PtrMut<T> {
        PtrMut { ptr: ptr as *mut T }
    }

    #[inline(always)]
    fn is_null(&self) -> bool {
        self.ptr == ::std::ptr::null_mut()
    }
}

impl<T> PtrMut<T> {

    #[inline(always)]
    pub fn null() -> PtrMut<T> {
        PtrMut { ptr: ::std::ptr::null_mut() }
    }

    #[inline(always)]
    pub fn as_pointer(&self) -> *mut T {
        self.ptr
    }

    // only for 'PtrMut'
    #[inline(always)]
    pub fn as_const(&self) -> PtrConst<T> {
        PtrConst::new(self.ptr as *const T)
    }
}

impl<T> Copy for PtrMut<T> { }
impl<T> Clone for PtrMut<T> {
    #[inline(always)]
    fn clone(&self) -> PtrMut<T> { *self }
}

impl<T> Deref for PtrMut<T> {
    type Target = T;

    #[inline(always)]
    fn deref(&self) -> &T {
        unsafe { &*self.ptr }
    }
}

impl<T> DerefMut for PtrMut<T> {
    #[inline(always)]
    fn deref_mut(&mut self) -> &mut T {
        unsafe { &mut *self.ptr }
    }
}

impl<T> PartialEq for PtrMut<T> {
    fn eq(&self, other: &PtrMut<T>) -> bool {
        self.ptr == other.ptr
    }
}

// ---------------------------------------------------------------------------
// PtrConst

#[repr(C)]
#[derive(Hash)]
pub struct PtrConst<T> {
    ptr: *const T,
}

impl<T> PtrAnyFuncs<T> for PtrConst<T> {
    type InnerPtr = *const T;

    #[inline(always)]
    fn new(ptr: Self::InnerPtr) -> PtrConst<T> {
        PtrConst { ptr: ptr as *const T }
    }

    #[inline(always)]
    fn is_null(&self) -> bool {
        self.ptr == ::std::ptr::null_mut()
    }
}

impl<T> PtrConst<T> {
    #[inline(always)]
    pub fn null() -> PtrConst<T> {
        PtrConst { ptr: ::std::ptr::null_mut() }
    }

    #[inline(always)]
    pub fn as_pointer(&self) -> *const T {
        self.ptr
    }
}

impl<T> Copy for PtrConst<T> { }
impl<T> Clone for PtrConst<T> {
    #[inline(always)]
    fn clone(&self) -> PtrConst<T> { *self }
}

impl<T> Deref for PtrConst<T> {
    type Target = T;

    #[inline(always)]
    fn deref(&self) -> &T {
        unsafe { &*self.ptr }
    }
}

// no DerefMut for PtrConst, only PtrMut
impl<T> PartialEq for PtrConst<T> {
    fn eq(&self, other: &PtrConst<T>) -> bool {
        self.ptr == other.ptr
    }
}


text:
Q: I need different fields in every stage of lead , do I need to create new module or what? Hi I need to develop CRM for my company. I choose OpenERP CRM module. It has stages and everything but I need that on every stage there must be some fields(some of them are required to move to next stage and some of them are optional) on leads page. Either I dont know the database structure or something else. So where to add fields (i mean in which object or table) One I was thinking to create a new module and use res_parter and user and create whole new CRM module. But then I was thinking that whats the benefit if I have to development. I am new in OpenERP , could not find my answer. Can somebody help me in this regard?

A: You should customize the lead by extending it and adding the fields you need, then you can "play" with views for showing the fields, or making them required, as you like.
Also, if you say "So where to add fields (i mean in which object or table)" means that you didn't read the developer docs :) Once you'll read them you'll find out that you don't need to know the tables in order to customize objects. After you read the docs, a good starting point is to have a look at other modules out there.
Have also a look at this.

A: You have done good choice of OE for the CRM, their module CRM is really mature on this vertical. Now you have Some specific requirement that "(some of them are required to move to next stage and some of them are optional"  So I will Suggest few point here,

*

*Your few of last line "But then I was thinking that whats the benefit if I have to dvelopment." Yes You are completely light, Why todo it again, and OE also believe same. Here what you need is few hacks like fields_view_get, you need to create new small module which will inherit the crm.lead object and play with few code hack which will do job for you,

*Second Point is in CRM lead Stage is M2o relation field and they are linked with CRM Section that  is sales Team so this point, so this need more effort to integrate you requirement but yes developer point of view it is not much complex job at all.

*Why we need new module for feature reason is if you will create new module then in future if up upgrade your crm module with oe crm then you will not fill conflicts and your new module will like Plug able module ot OE. You can look in it apps.openerp.com for some existing modules, As they have more then 2k module, so it is quite possible you will get what you need.;) Or something similler
Hope This will help
Let me know if still has Doughts ,


text:
Q: Create user identified as admin The syntax is this:
CREATE USER 'Adrian' IDENTIFIED BY 'Admin';

GRANT ALL ON `Spital`.* TO 'Adrian';
GRANT SELECT, INSERT, TRIGGER, UPDATE, DELETE ON TABLE `Spital`.* TO 'Adrian';
GRANT SELECT, INSERT, TRIGGER ON TABLE `Spital`.* TO 'Adrian';
GRANT SELECT ON TABLE `Spital`.* TO 'Adrian';
GRANT EXECUTE ON ROUTINE `Spital`.* TO 'Adrian';

How can I create the routine?
This is what is showing after that syntax:
CREATE USER 'Adrian' IDENTIFIED BY 'Admin'

Error Code: 1396. Operation CREATE USER failed for 'Adrian'@'%'

A: This error occurs when you first deleted a user with DELETE FROM ... and are now trying to recreate it.
You first need to say DROP USER ... then you can recreate again.
for more details you can check:
https://sebhastian.com/mysql-error-1396/#:~:text=The%20MySQL%20ERROR%201396%20occurs,from%20your%20MySQL%20database%20server.


text:
Q: Detecting and recovering from "hanging" bluetooth python connection I have a bluetooth connection between a Raspberry Pi 3b+ and an Arduino Mega, using the RPi built-in module, and an HC-05 module on the Arduino. Bi-directional communication works like a charm, for minutes to sometimes, hours at a time.
Then, at seemingly random times, the python code hangs, blocked on the sock.recv() function. I can kill it via ctrl-c, and restart it, and it usually reconnects without a problem.
I know Bluetooth is a little finicky and so while any suggestions of how to make the communication more robust and extend the runtime-until-hanging are definitely appreciated, what I'm more interested in is how to detect this "hanging" and recover from it. i.e.: I want to just kill the connection and try to reconnect from within the Python program, rather than me having to see this myself and react to it.
This is what I have so far in python:
#!/usr/bin/python3

import datetime
import socket
import sys
import time

import bluetooth

COMMAND_START_CHAR = '<'
COMMAND_END_CHAR = '>'
LOGFILE = 'bt.log'

def SearchForFullCommand(buffer):
  """Puts fully formed commands from buffer into a list, returning the remaining buffer.

  We expect commands to be demarcated by COMMAND_START_CHAR and COMMAND_END_CHAR.  The
  buffer may have zero or more such commands. This function finds all demarcated commands,
  strips off those demarcations, and returns the remaining buffer.  Any text that arrives
  before a COMMAND_START_CHAR is discarded.

  Args:
    buffer: string representing the text received so far.

  Returns:
    A 2-tuple, where the first element is the remaining buffer, and the second element
    is a potentially empty list of identified commands.
  """
  commands = []
  while COMMAND_END_CHAR in buffer:
    end_pos = buffer.find(COMMAND_END_CHAR)
    if COMMAND_START_CHAR in buffer[:end_pos]:
      start_pos = buffer.find(COMMAND_START_CHAR) + len(COMMAND_START_CHAR)
      commands.append(buffer[start_pos:end_pos])
    buffer = buffer[end_pos+len(COMMAND_END_CHAR):]
  return (buffer, commands)  # no command found

def Log(s):
  """Appends message s to the logfile."""
  with open(LOGFILE, 'a') as f:
    f.write('%s\n' % s)

def ConnectBluetooth(address, port):
  """Attempts to make one connection to the given address and port."""
  sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
  sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
  try:
    sock.connect((address, port))
  except (bluetooth.btcommon.BluetoothError) as e:
    Log('Failed to connect: %s' % e)
    return None
  return sock

def ConnectBluetoothRetry(address, port, seconds):
  """Attempts to make connections for a number of seconds, exiting program on fail."""
  second = 0
  while second < seconds:
    sock = ConnectBluetooth(address, port)
    if sock:
      Log('Connected after %d seconds' % second)
      return sock
    time.sleep(1)
    second += 1
  Log('Failed to connect after %d seconds' % second)
  sys.exit()

def main():
  """Sends sequential numbers over bluetooth, and receives & parses anything sent."""
  sys.stderr = open(LOGFILE, 'a')

  start = time.time()
  timestring = datetime.datetime.fromtimestamp(start).strftime('%Y-%m-%d %H:%M:%S')
  Log('Started at %s' % timestring)

  bd_addr = '98:D3:11:FC:42:16'
  port = 1
  sock = ConnectBluetoothRetry(bd_addr, port, 10)

  buffer = ''
  x = 0

  while True:
    try:
      recv = sock.recv(1024)
    except (bluetooth.btcommon.BluetoothError) as e:
      Log('Failed to receive: %s' % e)
      sock.close()
      sock = ConnectBluetoothRetry(bd_addr, port, 10)
    Log('.. %s (len=%d) after running for %.3f hours' % (
        recv, len(recv), (time.time() - start) / 60**2))
    buffer += recv.decode()
    buffer, commands = SearchForFullCommand(buffer)
    if commands:
      for n, command in enumerate(commands):
        Log('Received full command #%d: %s' % (n, command))

    send = COMMAND_START_CHAR+str(x)+COMMAND_END_CHAR
    try:
      sock.send(send)
    except (bluetooth.btcommon.BluetoothError) as e:
      Log('Failed to send %s: %s' % (send, e))
      sock.close()
      sock = ConnectBluetoothRetry(bd_addr, port, 10)
    Log('Sent %s' % send)

    x += 1
    time.sleep(1)

main()

When working well, the python log file looks like this:
.. b'646>' (len=4) after running for 0.843 hours
Received full command #0: 646
Sent <2526>
.. b'<647>' (len=5) after running for 0.843 hours
Received full command #0: 647
Sent <2527>
.. b'<' (len=1) after running for 0.844 hours
Sent <2528>
.. b'648>' (len=4) after running for 0.844 hours

Then, noticing it had stopped working, I killed it, and then restarted it:
KeyboardInterrupt
Started at 2020-05-03 11:15:07
Failed to connect: [Errno 16] Device or resource busy
Failed to connect: [Errno 16] Device or resource busy
Failed to connect: [Errno 16] Device or resource busy
Failed to connect: [Errno 16] Device or resource busy
Failed to connect: [Errno 16] Device or resource busy
Failed to connect: [Errno 16] Device or resource busy
Failed to connect: [Errno 16] Device or resource busy
Failed to connect: [Errno 16] Device or resource busy
Failed to connect: [Errno 16] Device or resource busy
Failed to connect: [Errno 16] Device or resource busy
Failed to connect after 10 seconds

I try again:
Started at 2020-05-03 11:15:42
Failed to connect: [Errno 112] Host is down
Failed to connect: [Errno 112] Host is down
Failed to connect: [Errno 112] Host is down
Connected after 3 seconds
.. b'1146><1147><1148><1149><1150><1151><1152><1153><1154><1155><1156><1157><1158><1159><1160><1161><1162><1163><1164><1165><1166><1' (len=127) after running for 0.005 hours
Received full command #0: 1147
Received full command #1: 1148
Received full command #2: 1149

... and it runs for another hour or two, before hanging again. I'm not physically moving either sender or receiver - they're within a foot of each other - so it's not range. Though I have tried disconnecting the Arduino, and repowering it, and they do reconnect without a problem within the still-running Python process.
The Arduino code, though I don't think its as relevant, is here:
long n = 1;

void setup()
{
    Serial.begin(9600);

    // HC-05 default serial speed for communcation mode is 9600
    Serial1.begin(9600);
}

void loop()
{
    Serial1.print("<");
    Serial1.print(n);
    Serial1.print(">");
    if(Serial1.available() > 0){ // Checks whether data is comming from the serial port
      Serial.println(Serial1.readString());} // Reads the data from the serial port
    delay(1000);
    n++;
}

Thanks for any help or suggestions!

A: I could not get the socket connection to last more than a few hours despite a few days of different approaches & efforts; I only went down the socket rabbit hole because I was unable to figure out how to use pySerialTransfer, or even just serial, over bluetooth.
So, going back to the serial approach, after a bit more effort and investigation, I was ultimately able to get that approach working for a stable (over 1 day at this point) bluetooth connection between Raspberry Pi & HC-05 on Arduino.
Code is here.


text:
Q: Hook useFetch rerender four times Reactjs v17, axios, react-router-dom v6.
hook useFetchAndLoad performs 4 rendering.
I know there are two renders, the first to load the component, then the useEffect. But what about the other two?
Then I read that having the <React.StrictMode> renders it four times. Remove StricMode, but it still renders 4 times.
I think I have it: load the component, the useEffect, response.data, setLoading(false). There are the 4 renderings.
It is right?
Question: Is it okay to render four times?
    import axios from "axios";
    import { useEffect, useState } from "react";

    export function useFetchAndLoad(id) {

      const [response, setResponse] = useState({});
      const [error, setError] = useState(null);
      const [loading, setLoading] = useState(false);

      useEffect(() => {
        const controller = new AbortController();

        const llamarEndPoint = async () => {
          setLoading(true);
          try {
            const response = await axios.get(`https://rickandmortyapi.com/api/character/${id}`, { signal: controller.signal });
            setResponse(response.data);
          } catch (error) {
            setError(error.message);
          } finally {
            setLoading(false);
          }
        }

        llamarEndPoint();

        return () => {
          setLoading(false);
          controller.abort();
        }
      }, [id]);
      console.log(response)
      if (response ) {

      }

      return { loading, response, error };
    }

    import React, {
    } from 'react'
    import {
      Link,
      Outlet,
      useLocation,
    } from 'react-router-dom';

    const RickAndMorty = () => {

      const location = useLocation();
      console.log(location);
      // console.log("4 Links")
      return (

Rick and Morty

<Link to="1">Rick</Link>

<Link to="2">Morty</Link>

<Link to="3">3otro</Link>

<Link to="4">4otro</Link>

            <Outlet />

      )
    }

    export default RickAndMorty

    import {useParams} from 'react-router-dom';
    import { useFetchAndLoad } from '../../hook/useFetchAndLoad';

    const Api = () => {

      const params = useParams();
      const id = parseInt(params.id);

      const { loading, response, error } = useFetchAndLoad(id);

      return (

Api

          {loading ?
Loading...
 : response.name ?? error}

      )
    }

    export default Api;

useFetchAndLoad.js:36 {}
useFetchAndLoad.js:36 {}
useFetchAndLoad.js:36 {id: 2, name: 'Morty Smith'}
useFetchAndLoad.js:36 {id: 2, name: 'Morty Smith'}

A: You're not logging loading, but my crystal ball's best guess is that if you were, you'd see
useFetchAndLoad.js:36 loading = false {}
useFetchAndLoad.js:36 loading = true {}
useFetchAndLoad.js:36 loading = true {id: 2, name: 'Morty Smith'}
useFetchAndLoad.js:36 loading = false {id: 2, name: 'Morty Smith'}

so yes, everything's quite correct.


text:
Q: get status and version of an epic I  extracted via a rest/agile/1.0/board/{boardId}/epic the epics belonging to a board.
The epics that i get from the api do not have the status and the version, is there another method to get the epics with their status and version?
Example of an epic that i get from the api
{
"id": 162380,
  "key": "BCUSP-1",
  "self": "xxxx/rest/agile/1.0/epic/162380",
  "name": "1. Référentiel PS-CE",
  "summary": "Référentiel PS-CE",
  "color": {
"key": "color_9"
   },
  "done": false
}


text:
Q: Reboot EC2 Amazon Linux (Redhat-based) from script I would like to reboot my Linux from a Script.  The script does not run as root.
Using sudo reboot produces

sudo: sorry, you must have a tty to run sudo.

A plain reboot gives the error

Need to be root

I know I can edit my sudoers file, but is there an easier way?

A: Amazon provides a library for all of these type of functions, so that they can be performed at the EC2 level, without resorting to bad ideas within the virtual machine itself.
You can use ec2-reboot-instances instance_id to request EC2 to reboot any instance, including itself. An instance can fetch its own ID using either:
curl -s http://169.254.169.254/latest/meta-data/instance-id

or
ec2-metadata -i

so as a one-liner on the command line, you would use this:
ec2-reboot-instances -O YOURAWSKEY -W YOURAWSSECRET --region=YOURREGION $(ec2-metadata -i |cut -d':' -f 2)

The full list of EC2 function is here.

A: The reboot , halt and shutdown commands usually require root for security reasons [1].
Writing on google how to run sudo in a script it answers with

Add your script to the /etc/sudoers file with the NOPASSWD attribute, so that it is permitted to run without prompting for a password. You can tie this down to a specific user (or set of users), or allow it to be run with sudo by anyone on your system.

Fair enough if you can limit the above to a one line script that launches only the reboot command. This however will expose your computer to be rebooted without password from that script+user configuration.
The alternative it will expose you to the risk that everyone will have the possibility to restart your machine. Read the answers [2,4,5] for example

... you need to add the suid-Bit [3,4,5] to those commands. But be aware, everyone on your system, that has access to the shell could then shutdown your machine.

But I'm convinced too that to use the suid it is a Bad Idea.
In the comment of [2] again it is suggested to modify with visudo...
%sudo ALL = NOPASSWD: /sbin/reboot

but at this point it's better to do a one line script to reboot for your user and to limit to that one only the reboot capability. (So you cannot reboot even as your user without password if not with that script).


text:
Q: Error in h(simpleError(msg, call)) in Ridge/Lasso Regression I am trying to run ridge/lasso with the glmnetand onehot package and getting an error.
library(glmnet)
library(onehot)
set.seed(123)

Sample <- HouseData[1:1460, ]
smp_size <- floor(0.5 * nrow(Sample))
train_ind <- sample(seq_len(nrow(Sample)), size = smp_size)
train <- Sample[train_ind, ]
test <- Sample[-train_ind, ]

############Ridge & Lasso Regressions ################

# Define the response for the training + test set
y_train <- train$SalePrice
y_test <- test$SalePrice

# Define the x training and test
x_train <- train[,!names(train)=="SalePrice"]
x_test <- test[,!names(train)=="SalePrice"]
str(y_train)

## encoding information for training set
x_train_encoded_data_info <- onehot(x_train,stringsAsFactors = TRUE, max_levels = 50)
x_train_matrix <- (predict(x_train_encoded_data_info,x_train))
x_train_matrix <- as.matrix(x_train_matrix)

# create encoding information for x test
x_test_encoded_data_info <- onehot(x_test,stringsAsFactors = TRUE, max_levels = 50)
x_test_matrix <- (predict(x_test_encoded_data_info,x_test))
str(x_train_matrix)

###Calculate best lambda
cv.out <- cv.glmnet(x_train_matrix, y_train,
                    alpha = 0, nlambda = 100,
                    lambda.min.ratio = 0.0001)

best.lambda <- cv.out$lambda.min
best.lambda
model <- glmnet(x_train_matrix, y_train, alpha = 0, lambda = best.lambda)
results_ridge <- predict(model,newx=x_test_matrix)

I know my data is clean and my matrices are the same size, But I keep getting this error when I try to run my prediction.

Error in h(simpleError(msg, call)) : error in evaluating the argument 'x' in selecting a method for function 'as.matrix': Cholmod error 'X and/or Y have wrong dimensions' at file ../MatrixOps/cholmod_sdmult.c, line 90

My professor has also told me to one-hot encode before I split my data, but that makes no sense to me.

A: It's hard to debug that specific error because it's not entirely clear where the onehot function in your code is coming from; it doesn't exist in base R or the glmnet package.
That said, I would recommend using the old built-in standby function model.matrix (or its sparse cousin, sparse.model.matrix, if you have larger datasets) for creating the x argument to glmnet. model.matrix will automatically one-hot encode factor or categorical variables for you. It requires a model formula as input, which you can create from your dataset as shown below.
# create the model formula
y_variable <- "SalePrice"
model_formula <- as.formula(paste(y_variable, "~",
                                  paste(names(train)[names(train) != y_variable], collapse = "+")))
# test & train matrices
x_train_matrix <- model.matrix(model_formula, data = train)[, -1]
x_test_matrix <- model.matrix(model_formula, data = test)[, -1]

###Calculate best lambda
cv.out <- cv.glmnet(x_train_matrix, y_train,
                    alpha = 0, nlambda = 100,
                    lambda.min.ratio = 0.0001)

A second, newer option would be to use the built-in glmnet function makeX(), which builds matrices off of your test/train dataframes. This can just be fed into cv.glmnet as the x argument as below.
## option 2: use glmnet built in function to create x matrices
x_matrices <- glmnet::makeX(train = train[, !names(train) == "SalePrice"],
                            test = test[, !names(test) == "SalePrice"])

###Calculate best lambda
cv.out <- cv.glmnet(x_matrices$x, y_train,
                    alpha = 0, nlambda = 100,
                    lambda.min.ratio = 0.0001)


text:
Q: How to create an array with string elements? I want to declare an array like this:
panel = ['A0', 'A1', 'A2', 'A3', 'A4', 'A5'];

so that panel(1) = A0.
The problem is that it takes the complete thing as one element, like this: A0A1A2A3A4A5
with panel(1) = A, panel(2) = 0, and so on.
How can such an array be created?

A: Using a cell array will generate the behavior you're expecting. You define a cell array using {} brackets, rather than [], and access the elements using {} instead of ().
panel = {'A0', 'A1', 'A2', 'A3', 'A4', 'A5'};
disp(panel{1});

A: Either you can use cell arrays as explained in DMR's answer or the following approaches:

*

*Use multiple rows instead of a single row like this:
panel = ['A0'; 'A1'; 'A2'; 'A3'; 'A4'; 'A5'];

then A0 can be accessed using: panel(1,:), A1 using panel(2,:), ...

*If you have MATLAB 2017a, you can create string arrays like this:
panel = ["A0", "A1", "A2", "A3", "A4", "A5"];

and then A0 can be accessed using: panel(1), A1 using panel(2), ...


text:
Q: CVS history....can't get it work An really embarrassing question: I have specified my CVS root, and within
this CVS root I have a repository, let call it REP. Within REP, I have
a file TEST.TXT where I wanna see all revisions of it. Unfortunately,
I cant get this work, i tried the following:
cvs history TEST.TXT
cvs history /REP/TEST.TXT
cvs history REP/TEST.TXT

Anyone an idea what I am doing wrong? Do i miss a command that tells CVS which repository
I am referring to?
Many thanks!

A: I vaguely remember cvs... :-)
The usual way to tell cvs which repository you are using is with the CVSROOT environment variable. If the repository is on localhost then this can just be a full pathname.
The usual way to get revision history on a file is not to examine the repository-wide history file, but rather it is to run the cvs log command which will extract the rcs revision information for a given file or subtree.
Example:
$ echo $CVSROOT
/home/ross/cvs
$ cvs log q.rb

RCS file: /home/ross/cvs/R3/q.rb,v
Working file: q.rb
head: 1.1
branch: 1.1.1
locks: strict
access list:
symbolic names:
    R1: 1.1.1.1
    ROSS: 1.1.1
keyword substitution: kv
total revisions: 2; selected revisions: 2
description:
----------------------------
revision 1.1
date: 2009-11-12 10:36:27 -0800;  author: ross;  state: Exp;  commitid: MlYKy8V908Lmagbu;
branches:  1.1.1;
Initial revision
----------------------------
revision 1.1.1.1
date: 2009-11-12 10:36:27 -0800;  author: ross;  state: Exp;  lines: +0 -0;  commitid: MlYKy8V908Lmagbu;
initial import
=============================================================================


text:
Q: Redirecting a page to another while reporting 301 I have a page at example.com/news.php. This page is already indexed by Google. I would like to ditch this page and instead use example.com/news.
So essentially I need to report 301 on news.php and also redirect any request to /news to news.php.
When I am using the below in .htaccess I am getting a redirect loop:
Redirect        301 /news.php   http://example.com/news
RewriteRule     ^news$  news.php [L]

How would I go about doing the desired?

A: Try :
RewriteEngine on

RewriteCond %{THE_REQUEST} /news\.php [NC]
RewriteRule ^ /news [L,R=301]

RewriteRule     ^news/?$    news.php [L]

Edit as per your comment :
To redirect any php file , you can use :
RewriteEngine on

RewriteCond %{THE_REQUEST} /([^.]+)\.php [NC]
RewriteRule ^ /%1 [L,R=301]

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule     ^(.+)/?$    $1.php [L]