Monday, September 30, 2019

I/O Error on LG GSA-H12N DVD drive on Windows 7

I am facing an I/O Error when I try to burn DVD data discs on my LG GSA-H12N DVD drive on Windows 7. Note that I was able to do this same operation on the same hardware/software just a day earlier without any problems, but with Windows XP. The only change (AFAIK) has been the installation of Windows 7 to replace Windows XP on this PC.


Here is the error I get when I try to burn a DVD data disc using CDBurnerXP 4.2.7.1801:


alt text



Burning error occured


An error occured while burning the disc. Most likely the disc is not usable.
Usually these errors happen if the inserted media is not compatible to the drive or of poor quality.


(devNTSPTI_IO_Error) Could not write to Disc (LBA: 52864 Length: 32).


SCSI Pass-through Interface I/O Error. - 0xFF045D



Note that there can be no problem with the discs since I have been using the same discs (from the same box) just before the Windows 7 installation with no problems. The only change has been Windows 7.


I tried InfraRecorder v0.5 and ImgBurn v2.5 and got similar I/O errors:


alt text


Note that Windows 7 lists the LG GSA-H21N drive as being compatible (see this link).


I also checked the LG Drivers website and using the firware update from there updated the drive firmware from version UL01 to UL02. But, even this has not helped. The drive reads DVDs without any problem, but continues to produce coasters.


alt text


Could someone help me figure out what is the problem? Thanks :)

pointers - c++ * vs & in function declaration








When should I declare my variables as pointers vs objects passed-by-reference? They compile to the same thing in assembly (at least run-time asymptotically) so when should I use which?




void foo(obj* param)
void foo(obj& param)

Answer



My rule is simple: use * when you want to show that value is optional and thus can be 0.



Excluding from the rule: all the _obj_s around are stored in containers and you don't want to make your code look ugly by using everywhere foo(*value); instead of foo(value);
So then to show that value can't be 0 put assert(value); at the function begin.


windows 7 - How to reduce Hardware reserved memory on ASUS motherboards?

I have read lots of topics but i still couldn't lower the hardware reserved memory which is over 1GB




There is only 2.21 GB RAM that is being usable by the OS.
I had another computer where the usable RAM was 3.5GB. Though, that was Gigabyte motherboard which has no built-in graphic.



The OS is Windows 7 Ultimate 32Bit



Most of the hardware reserved memory i saw is being reserved for the PCI Express with most of its addresses are being reserved for the AMD Radeon.



enter image description here




You can see that there is the reserved addresses from 90000000 to DFFFFFFF on PCI bus.



I have updated the BIOS but that didn't help.
I also tried the Msconfig boot settings to uncheck the maximum memory but it did nothing.



Motherboard is ASUS TUF Z270 MARK 2



Are there any BIOS settings that i can disable to save more RAM?

php - Notice: Undefined index




I have a checkbox which can make a post password protected-







My Php tries to post-



 $password = htmlspecialchars(strip_tags($_POST['password']));


I get the undefined index error.




Now, if I try to check first if the password was set, I get the same error executing-



$sql = "INSERT INTO blog (timestamp,title,entry,password) VALUES ('$timestamp','$title','$entry','$password')";

$result = mysql_query($sql) or print("Can't insert into table blog.
" . $sql . "
" . mysql_error());


How do I fix it? Do I have to do it for every field like title text box and all?


Answer




Why are you stripping tags and escaping a boolean value? You could just do it like this:



$password = (isset($_POST['password']) && $_POST['password'] == 1) ? 1 : 0;


or:



$password = isset($_POST['password']) ? (bool) $_POST['password'] : 0;

asp.net mvc - Razor View throwing "The name 'model' does not exist in the current context"



After significant refactoring in my MVC 4 application, and Razor shows this error while debugging Views:





The name 'model' does not exist in the current context.




This is the offending line of code:



@model ICollection


I know that the usage of @model is correct.




Why is this happening? How can I fix it?


Answer



I think you have messed up the web.config file which lives in the Views folder.



Create a new project targeting the same .NET framework and copy its Views/web.config file on top of the one in your current project. This will fix your problem.



Also, as Dudeman3000 commented, if you have Areas in your MVC project they all have Views\web.config files too.


mysql - PHP MySQLI Prevent SQL Injection




I've build a website that will be going live soon and just have a couple questions about preventing SQL injection, I understand how to use mysqli_real_escape_string but I'm just wondering if I have to use that on all variables that I'm getting for my SQL statement and do I have to use it when I'm doing select statements also or just on insert update and delete? Also what other security would you recommend me implementing before I put the site live, thanks in advance for any help!


Answer



Any query can be injected whether it's read or write, persistent or transient. Injections can be performed by ending one query and running a separate one (possible with mysqli), which renders the intended query irrelevant.




Any input to a query from an external source whether it is from users or even internal should be considered an argument to the query, and a parameter in the context of the query. Any parameter in a query needs to be parameterized. This leads to a properly parameterized query that you can create a prepared statement from and execute with arguments. For example:



SELECT col1 FROM t1 WHERE col2 = ?


? is a placeholder for a parameter. Using mysqli, you can create a prepared statement using prepare, bind a variable (argument) to a parameter using bind_param, and run the query with execute. You don't have to sanitize the argument at all (in fact it's detrimental to do so). mysqli does that for you. The full process would be:



$stmt = mysqli->prepare("SELECT col1 FROM t1 WHERE col2 = ?");
$stmt->bind_param("s", $col2_arg);
$stmt->execute();



There is also an important distinction between parameterized query and prepared statement. This statement, while prepared, is not parameterized and is thus vulnerable to injection:



$stmt = mysqli->prepare("INSERT INTO t1 VALUES ($_POST[user_input])");


To summarize:





  • All Queries should be properly parameterized (unless they have no parameters)

  • All arguments to a query should be treated as hostile as possible no matter their source


javascript - Convert JS object to JSON string



If I defined an object in JS with:




var j={"name":"binchen"};


How can I convert the object to JSON? The output string should be:



'{"name":"binchen"}'

Answer



All current browsers have native JSON support built in. So as long as you're not dealing with prehistoric browsers like IE6/7 you can do it just as easily as that:




var j={"name":"binchen"};
JSON.stringify(j); // '{"name":"binchen"}'

android - NullPointerException FirebaseUser.getUid()' on a null object reference

here is the error

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.jams.socialnetwork, PID: 15878
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.jams.socialnetwork/com.example.jams.socialnetwork.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.google.firebase.auth.FirebaseUser.getUid()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2690)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2755)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1495)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6196)

at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:888)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:778)



Caused by: java.lang.NullPointerException: Attempt to invoke virtual method



'java.lang.String com.google.firebase.auth.FirebaseUser.getUid()' on a null object reference
at com.example.jams.socialnetwork.MainActivity.onCreate(MainActivity.java:52)
at android.app.Activity.performCreate(Activity.java:6698)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1140)

at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2643)



i have tried many thigs but can't understand that where i am doing wrong



java>
package com.example.jams.socialnetwork;



                     import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;

import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;


import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;

import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.squareup.picasso.Picasso;


import de.hdodenhof.circleimageview.CircleImageView;

public class MainActivity extends AppCompatActivity {

private NavigationView navigationView;
private Toolbar mToolbar;
private DrawerLayout drawerLayout;
private ActionBarDrawerToggle actionBarDrawerToggle;
private RecyclerView postList;


private CircleImageView NavProfileImage;
private TextView NavProfileUserName;

private FirebaseAuth mAuth;
private DatabaseReference UserRef;
String currentUserID;


@Override

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


mAuth = FirebaseAuth.getInstance();
currentUserID = mAuth.getCurrentUser().getUid();
UserRef = FirebaseDatabase.getInstance().getReference().child("Users");



mToolbar = (Toolbar) findViewById(R.id.main_page_toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setTitle("Home");




drawerLayout = (DrawerLayout) findViewById(R.id.drawable_layout);
actionBarDrawerToggle = new ActionBarDrawerToggle(MainActivity.this, drawerLayout,R.string.drawer_Open, R.string.drawer_Close);
drawerLayout.addDrawerListener(actionBarDrawerToggle);

actionBarDrawerToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
navigationView = (NavigationView) findViewById(R.id.navigation_view);

View navView = navigationView.inflateHeaderView(R.layout.navigation_header);

NavProfileImage = (CircleImageView) navView.findViewById(R.id.nav_profile_image);
NavProfileUserName = (TextView) navView.findViewById(R.id.nav_user_full_name);







UserRef.child(currentUserID).addValueEventListener(new ValueEventListener()
{
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot)
{
if (dataSnapshot.exists())

{
String fullname = dataSnapshot.child("fullname").getValue().toString();
String image = dataSnapshot.child("profileimage").getValue().toString();

NavProfileUserName.setText(fullname);
Picasso.with(MainActivity.this).load(image).placeholder(R.drawable.profile).into(NavProfileImage);
}
}

@Override

public void onCancelled(@NonNull DatabaseError databaseError)
{

}
});




navigationView.setNavigationItemSelectedListener

(new NavigationView.OnNavigationItemSelectedListener()
{
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item)
{
UserMenuSelector(item);
return false;
}
});





}





@Override

protected void onStart()
{
super.onStart();

FirebaseUser currentUser =mAuth.getCurrentUser();

if(currentUser==null)
{
SendUserToLoginActivity();
}


else
{
CheckUserExistence();
}


}

private void CheckUserExistence()

{
final String current_user_id = mAuth.getCurrentUser().getUid();

UserRef.addValueEventListener(new ValueEventListener()
{
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot)
{
if (!dataSnapshot.hasChild(current_user_id))
{

SendUserToSetupActivity();
}
}

@Override
public void onCancelled(@NonNull DatabaseError databaseError)
{

}
});




}

private void SendUserToSetupActivity()
{
Intent SetupIntent = new Intent(MainActivity.this,SetupActivity.class);
SetupIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(SetupIntent);

finish();


}









private void SendUserToLoginActivity()
{
Intent LoginIntent = new Intent(MainActivity.this,LoginActivity.class);
LoginIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(LoginIntent);
finish();
}


@Override
public boolean onOptionsItemSelected(MenuItem item)
{
if(actionBarDrawerToggle.onOptionsItemSelected(item))
{
return true;
}

return super.onOptionsItemSelected(item);
}






private void UserMenuSelector(MenuItem item)
{
switch (item.getItemId())
{
case R.id.nav_profile:

Toast.makeText(this,"Profile",Toast.LENGTH_SHORT).show();
break;

case R.id.nav_post:
Toast.makeText(this,"Post",Toast.LENGTH_SHORT).show();
break;

case R.id.nav_home:
Toast.makeText(this,"Home",Toast.LENGTH_SHORT).show();
break;


case R.id.nav_friends:
Toast.makeText(this,"friends",Toast.LENGTH_SHORT).show();
break;

case R.id.nav_find_friends:
Toast.makeText(this,"find friends",Toast.LENGTH_SHORT).show();
break;

case R.id.nav_messages:

Toast.makeText(this,"message",Toast.LENGTH_SHORT).show();
break;

case R.id.nav_settings:
Toast.makeText(this,"Settings",Toast.LENGTH_SHORT).show();
break;

case R.id.nav_logout:
mAuth.signOut();
SendUserToLoginActivity();

break;
}
}


}

html - Change an HTML5 input's placeholder color with CSS




Chrome supports the placeholder attribute on input[type=text] elements (others probably do too).



But the following CSS doesn't do anything to the placeholder's value:





input[placeholder], [placeholder], *[placeholder] {
color: red !important;
}







Value will still remain grey instead of red.



Is there a way to change the color of the placeholder text?


Answer



Implementation




There are three different implementations: pseudo-elements, pseudo-classes, and nothing.




  • WebKit, Blink (Safari, Google Chrome, Opera 15+) and Microsoft Edge are using a pseudo-element: ::-webkit-input-placeholder. [Ref]

  • Mozilla Firefox 4 to 18 is using a pseudo-class: :-moz-placeholder (one colon). [Ref]

  • Mozilla Firefox 19+ is using a pseudo-element: ::-moz-placeholder, but the old selector will still work for a while. [Ref]

  • Internet Explorer 10 and 11 are using a pseudo-class: :-ms-input-placeholder. [Ref]

  • April 2017: Most modern browsers support the simple pseudo-element ::placeholder [Ref]




Internet Explorer 9 and lower does not support the placeholder attribute at all, while Opera 12 and lower do not support any CSS selector for placeholders.



The discussion about the best implementation is still going on. Note the pseudo-elements act like real elements in the Shadow DOM. A padding on an input will not get the same background color as the pseudo-element.



CSS selectors



User agents are required to ignore a rule with an unknown selector. See Selectors Level 3:




a group of selectors containing an invalid selector is invalid.





So we need separate rules for each browser. Otherwise the whole group would be ignored by all browsers.



::-webkit-input-placeholder { /* WebKit, Blink, Edge */
color: #909;
}
:-moz-placeholder { /* Mozilla Firefox 4 to 18 */
color: #909;

opacity: 1;
}
::-moz-placeholder { /* Mozilla Firefox 19+ */
color: #909;
opacity: 1;
}
:-ms-input-placeholder { /* Internet Explorer 10-11 */
color: #909;
}
::-ms-input-placeholder { /* Microsoft Edge */

color: #909;
}

::placeholder { /* Most modern browsers support this now. */
color: #909;
}







Usage notes




  • Be careful to avoid bad contrasts. Firefox's placeholder appears to be defaulting with a reduced opacity, so needs to use opacity: 1 here.

  • Note that placeholder text is just cut off if it doesn’t fit – size your input elements in em and test them with big minimum font size settings. Don’t forget translations: some languages need more room for the same word.

  • Browsers with HTML support for placeholder but without CSS support for that (like Opera) should be tested too.

  • Some browsers use additional default CSS for some input types (email, search). These might affect the rendering in unexpected ways. Use the properties -webkit-appearance and -moz-appearance to change that. Example:




    [type="search"] {
-moz-appearance: textfield;
-webkit-appearance: textfield;
appearance: textfield;
}

utf 8 - MD5 Hash of ISO-8859-1 string in Java



I'm implementing an interface for digital payment service called Suomen Verkkomaksut. The information about the payment is sent to them via HTML form. To ensure that no one messes with the information during the transfer a MD5 hash is calculated at both ends with a special key that is not sent to them.



My problem is that for some reason they seem to decide that the incoming data is encoded with ISO-8859-1 and not UTF-8. The hash that I sent to them is calculated with UTF-8 strings so it differs from the hash that they calculate.



I tried this with following code:




String prehash = "6pKF4jkv97zmqBJ3ZL8gUw5DfT2NMQ|13466|123456||Testitilaus|EUR|http://www.esimerkki.fi/success|http://www.esimerkki.fi/cancel|http://www.esimerkki.fi/notify|5.1|fi_FI|0412345678|0412345678|esimerkki@esimerkki.fi|Matti|Meikäläinen||Testikatu 1|40500|Jyväskylä|FI|1|2|Tuote #101|101|1|10.00|22.00|0|1|Tuote #202|202|2|8.50|22.00|0|1";
String prehashIso = new String(prehash.getBytes("ISO-8859-1"), "ISO-8859-1");

String hash = Crypt.md5sum(prehash).toUpperCase();
String hashIso = Crypt.md5sum(prehashIso).toUpperCase();


Unfortunately both hashes are identical with value C83CF67455AF10913D54252737F30E21. The correct value for this example case is 975816A41B9EB79B18B3B4526569640E according to Suomen Verkkomaksut's documentation.




Is there a way to calculate MD5 hash in Java with ISO-8859-1 strings?



UPDATE: While waiting answer from Suomen Verkkomaksut, I found an alternative way to make the hash. Michael Borgwardt corrected my understanding of String and encodings and I looked for a way to make the hash from byte[].



Apache Commons is an excellent source of libraries and I found their DigestUtils class which has a md5hex function which takes byte[] input and returns a 32 character hex string.



For some reason this still doesn't work. Both of these return the same value:



DigestUtils.md5Hex(prehash.getBytes());
DigestUtils.md5Hex(prehash.getBytes("ISO-8859-1"));


Answer



Java has a standard java.security.MessageDigest class, for calculating different hashes.



Here is the sample code



include java.security.MessageDigest;

// Exception handling not shown


String prehash = ...

final byte[] prehashBytes= prehash.getBytes( "iso-8859-1" );

System.out.println( prehash.length( ) );
System.out.println( prehashBytes.length );

final MessageDigest digester = MessageDigest.getInstance( "MD5" );

digester.update( prehashBytes );


final byte[] digest = digester.digest( );

final StringBuffer hexString = new StringBuffer();

for ( final byte b : digest ) {
final int intByte = 0xFF & b;

if ( intByte < 10 )
{

hexString.append( "0" );
}

hexString.append(
Integer.toHexString( intByte )
);
}

System.out.println( hexString.toString( ).toUpperCase( ) );



Unfortunately for you it produces the same "C83CF67455AF10913D54252737F30E21" hash. So, I guess your Crypto class is exonerated. I specifically added the prehash and prehashBytes length printouts to verify that indeed 'ISO-8859-1' is used. In this case both are 328.



When I did presash.getBytes( "utf-8" ) it produced "9CC2E0D1D41E67BE9C2AB4AABDB6FD3" (and the length of the byte array became 332). Again, not the result you are looking for.



So, I guess Suomen Verkkomaksut does some massaging of the prehash string that they did not document, or you have overlooked.


gnome - lock screen vs logout in Linux

When one locks the screen under Windows, it is redirected to the same screen as in the login. Under Linux, a program is run that "captures" all the mouse and keyboard events. While xcreensaver does the job very nicely, the default one for gnome sometimes has a delay of several seconds between the exit of the screen saver animation and the lock of the screen (I haven't submitted such a bug yet, and I don't know if it is only in my machine or if it's a more generalized problem). Regardless of the nature of the problem, I was wondering if there is a cleaner, more robust way to lock the screen.



The implementation I was thinking of, would actually log the user out and take him back to the gdm screen. The programs being run as daemons could be kept running at a higher hierarchy level, and the gui programs could simply be paused? Also the current RAM memory could be dumped somewhere and later be recovered... Others could probably think of better implementations than I do.



Is a cleaner implementation necessary? Would it benefit the end user, or would it not be worth it?

Proper way to declare custom exceptions in modern Python?



What's the proper way to declare custom exception classes in modern Python? My primary goal is to follow whatever standard other exception classes have, so that (for instance) any extra string I include in the exception is printed out by whatever tool caught the exception.



By "modern Python" I mean something that will run in Python 2.5 but be 'correct' for the Python 2.6 and Python 3.* way of doing things. And by "custom" I mean an Exception object that can include extra data about the cause of the error: a string, maybe also some other arbitrary object relevant to the exception.




I was tripped up by the following deprecation warning in Python 2.6.2:



>>> class MyError(Exception):
... def __init__(self, message):
... self.message = message
...
>>> MyError("foo")
_sandbox.py:3: DeprecationWarning: BaseException.message has been deprecated as of Python 2.6



It seems crazy that BaseException has a special meaning for attributes named message. I gather from PEP-352 that attribute did have a special meaning in 2.5 they're trying to deprecate away, so I guess that name (and that one alone) is now forbidden? Ugh.



I'm also fuzzily aware that Exception has some magic parameter args, but I've never known how to use it. Nor am I sure it's the right way to do things going forward; a lot of the discussion I found online suggested they were trying to do away with args in Python 3.



Update: two answers have suggested overriding __init__, and __str__/__unicode__/__repr__. That seems like a lot of typing, is it necessary?


Answer



Maybe I missed the question, but why not:



class MyException(Exception):

pass


Edit: to override something (or pass extra args), do this:



class ValidationError(Exception):
def __init__(self, message, errors):

# Call the base class constructor with the parameters it needs
super(ValidationError, self).__init__(message)


# Now for your custom code...
self.errors = errors


That way you could pass dict of error messages to the second param, and get to it later with e.errors






Python 3 Update: In Python 3+, you can use this slightly more compact use of super():




class ValidationError(Exception):
def __init__(self, message, errors):

# Call the base class constructor with the parameters it needs
super().__init__(message)

# Now for your custom code...
self.errors = errors


php - Create a text file for download on-the-fly

Update #1


What has been posted below is spot on for getting it to output the file. What it is doing though is outputting the string data followed by the rest of the forms HTML. Is there any way to stop what is put into the file and what is just displayed to the browser.


Update #2


Just added exit() and all works fine. Thanks!


EOU


Hi,


I've been looking around and seen a few things similar but not quite fully got the grasp on what I need to do to achieve the task fully.


At the moment I have a form that a user supplies some details. On submit it is posted back to itself and the POST variables processed. I have a premade HTML web template for the information to be placed into which works fine and dandy just doing a str_replace.


What I am trying to do now is export that as a download to the user in a plain text document. So the end result being the user clicks submit on the form and they then have a download popup open with the modified webpage as a .txt file.


As far as I understand I need to do something using HTTPs headers functionality. What exactly though to achieve what I want I'm not sure. I only want the file to be available once, but I assume it has to be stored somewhere initally for the user to download which will then need cleaing up after manually?


Any help or points would be great! Thanks.

How can I set the default value for an HTML element?



I thought that adding a "value" attribute set on the











However, this did not work as I had expected. How can I set which element is selected by default?



Answer



Set selected="selected" for the option you want to be the default.





python - How do you remove duplicates from a list whilst preserving order?



Is there a built-in that removes duplicates from list in Python, whilst preserving order? I know that I can use a set to remove duplicates, but that destroys the original order. I also know that I can roll my own like this:




def uniq(input):
output = []
for x in input:
if x not in output:
output.append(x)
return output


(Thanks to unwind for that code sample.)




But I'd like to avail myself of a built-in or a more Pythonic idiom if possible.



Related question: In Python, what is the fastest algorithm for removing duplicates from a list so that all elements are unique while preserving order?


Answer



Here you have some alternatives: http://www.peterbe.com/plog/uniqifiers-benchmark



Fastest one:



def f7(seq):

seen = set()
seen_add = seen.add
return [x for x in seq if not (x in seen or seen_add(x))]


Why assign seen.add to seen_add instead of just calling seen.add? Python is a dynamic language, and resolving seen.add each iteration is more costly than resolving a local variable. seen.add could have changed between iterations, and the runtime isn't smart enough to rule that out. To play it safe, it has to check the object each time.



If you plan on using this function a lot on the same dataset, perhaps you would be better off with an ordered set: http://code.activestate.com/recipes/528878/



O(1) insertion, deletion and member-check per operation.




(Small additional note: seen.add() always returns None, so the or above is there only as a way to attempt a set update, and not as an integral part of the logical test.)


Sunday, September 29, 2019

feof - How does C handle EOF?

#include 

int main()
{
FILE* f=fopen("book2.txt","r");
char a[200];
while(!feof(f))
{
fscanf(f,"%s",a);

printf("%s ",a);
printf("%d\n",ftell(f));
}
fclose(f);
return 0;
}


I have the code above. book2.txt contains "abcdef abcdef" with the cursor move to a newline(ie:abcdef abcdef\n). I get the results below.




abcdef 6
abcdef 13
abcdef 19


I expect to get



abcdef 6
abcdef 13
15



What am I doing wrong?

looping through javascript nested objects in html displays [object object]?

I am trying to loop through a Javascript object to display the contents on the html page. The contents is from an API that has ben parsed into javascript Object. The loop works fine but every solution i come up with either gives me nothing in the html or display [object object][object object]



I have no idea why it keeps displaying this or how to get it displaying correctly.



The data held being got from the api call



[{"id":"68343","order_id":"77348","customer_id":"2","number":"1"}, 
{"id":"68344","order_id":"77348","customer_id":"2","number":"1"},
{"id":"68342","order_id":"77348","customer_id":"3","number":"1"}]



I get the data and parse



function(data){
var result = JSON.parse(data);
if(result.status == "success")
{
//need to loop through all data so that it displays in a html div



}


}


So i have tried the for loop:-



for (var objProp in result){

for (var obj in result[objProp]){

document.getElementById("orderItem").innerHTML = result[objProp]
[obj];
}
}


displays [object object]




another for loop



for (var key in result){
document.getElementById("orderItem").innerHTML =result[key];}


getting a single item back is ok



document.getElementById("orderItem").innerHTML = result.data[0].id;

Convert Timestamp to str value python pandas dataframe

Answer


I have dataframe
which looks like this



    Date        Player          Fee
0 2017-01-08 Steven Berghuis 6500000
1 2017-07-18 Jerry St. Juste 4500000
2 2017-07-18 Ridgeciano Haps 600000

3 2017-01-07 Sofyan Amrabat 400000


I want to change every date value to str if they match the condition



def is_in_range(x):
ses1 = pd.to_datetime('2013-02-01')
ses2 = pd.to_datetime('2014-02-01')
ses3 = pd.to_datetime('2015-02-01')
ses4 = pd.to_datetime('2016-02-01')

ses5 = pd.to_datetime('2017-02-01')
ses6 = pd.to_datetime('2018-02-01')

if x < ses1 :
x = '2012-13'
if x > ses2 and x < ses3 :
x = '2013-14'
if x > ses3 and x < ses4 :
x = '2014-15'
if x > ses4 and x < ses5 :

x = '2015-16'
if x > ses5 and x < ses6 :
x = '2016-17'
return ses6
aj = ajax_t['Date'].apply(is_in_range)
aj



TypeError Traceback (most recent call last)

in ()
18 x = '2016-17'
19 return ses6
---> 20 aj = ajax_t['Date'].apply(is_in_range)
21 aj



/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/pandas/core/series.py
in apply(self, func, convert_dtype, args, **kwds) 2353
else: 2354 values = self.asobject
-> 2355 mapped = lib.map_infer(values, f, convert=convert_dtype) 2356 2357 if len(mapped) and
isinstance(mapped[0], Series):




pandas/_libs/src/inference.pyx in pandas._libs.lib.map_infer
(pandas/_libs/lib.c:66645)()



in is_in_range(x)
15 if x > ses4 and x < ses5 :
16 x = '2015-16'
---> 17 if x > ses5 and x < ses6 :
18 x = '2016-17'
19 return ses6




pandas/_libs/tslib.pyx in pandas._libs.tslib._Timestamp.richcmp
(pandas/_libs/tslib.c:20281)()



TypeError: Cannot compare type 'Timestamp' with type 'str'




I get this error any suggestions,
Kindly

c# - How do I make a unit test to test a method that checks request headers?



I am very, very new to unit testing and am trying to write a test for a pretty simple method:



public class myClass : RequireHttpsAttribute
{
public override void OnAuthorization(AuthoizationContext filterContext)
{

var request = filterContext.HttpContext.Request;
var header = Convert.ToBoolean(request.Headers["Special-Header-Name"]);

if (!(header || request.IsSecureConnection))
{
HandleNonHttpsRequest(filterContext);
}
}
}



This method, which inherits from the RequireHttpsAttribute, checks if a certain header is present from a page, if it's missing or false, and the page is not secure, then it will call HandleNonHttpsRequest, otherwise it does nothing.



We are using Moq and Nunit for testing. I have found some resources to help build a fakeHttpContext with Moq, but honestly I'm not sure how to use it or where to go within my unit tests to ensure that fake HttpContexts are or are not causing the HandleNonHttpsRequest method to call.



I really appreciate any guidance with this issue.


Answer



// arrange
var context = new Mock();
var request = new Mock();

var headers = new NameValueCollection
{
{ "Special-Header-Name", "false" }
};
request.Setup(x => x.Headers).Returns(headers);
request.Setup(x => x.HttpMethod).Returns("GET");
request.Setup(x => x.Url).Returns(new Uri("http://www.example.com"));
request.Setup(x => x.RawUrl).Returns("/home/index");
context.Setup(x => x.Request).Returns(request.Object);
var controller = new Mock();


var actionDescriptor = new Mock();
var controllerContext = new ControllerContext(context.Object, new RouteData(), controller.Object);
var filterContext = new AuthorizationContext(controllerContext, actionDescriptor.Object);
var sut = new myClass();

// act
sut.OnAuthorization(filterContext);

// assert

Assert.IsInstanceOfType(filterContext.Result, typeof(RedirectResult));
var redirectResult = (RedirectResult)filterContext.Result;
Assert.AreEqual("https://www.example.com/home/index", redirectResult.Url);

php - Laravel5 status 500

I've been trying to import an existing Laravel project on the Cloud9 IDE. I set up and installed everything required but fail to load the web. The developer console shows "Failed to load resource: the server responded with a status of 500 (Internal Server Error)"



Lot of people said it is about the written permission for the "storage" and "bootstraps" folder, so I gave written permission for all files in the whole workspace, but still it gave the same error. I checked the apache error log but can't see the corresponding log. Also, normal PHP files(hello world) are loaded successfully but not the Laravel related pages. The code of public/index.php:




require DIR.'/../bootstrap/autoload.php';



$app = require_once DIR.'/../bootstrap/app.php';




$kernel = $app->make(Illuminate\Contracts\Http\Kernel::class);



$response = $kernel->handle(
$request = Illuminate\Http\Request::capture() );



$response->send();



$kernel->terminate($request, $response);





The status 500 error appears on $response->send();

Exception 'open failed: EACCES (Permission denied)' on Android

Answer


Answer




I am getting




open failed: EACCES (Permission denied)





on the line OutputStream myOutput = new FileOutputStream(outFileName);



I checked the root, and I tried android.permission.WRITE_EXTERNAL_STORAGE.



How can I fix this problem?



try {
InputStream myInput;

myInput = getAssets().open("XXX.db");


// Path to the just created empty db
String outFileName = "/data/data/XX/databases/"
+ "XXX.db";

// Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);

// Transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];

int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}

// Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
buffer = null;

outFileName = null;
}
catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}

Answer



I had the same problem... The was in the wrong place. This is right:




 

...

...

...






The uses-permission tag needs to be outside the application tag.


python - How to access environment variable values?



I set an environment variable that I want to access in my Python application. How do I get this value?



Answer



Environment variables are accessed through os.environ



import os
print(os.environ['HOME'])


Or you can see a list of all the environment variables using:



os.environ



As sometimes you might need to see a complete list!



# using get will return `None` if a key is not present rather than raise a `KeyError`
print(os.environ.get('KEY_THAT_MIGHT_EXIST'))

# os.getenv is equivalent, and can also give a default value instead of `None`
print(os.getenv('KEY_THAT_MIGHT_EXIST', default_value))



Python default installation on Windows is C:\Python. If you want to find out while running python you can do:



import sys
print(sys.prefix)

Is there any difference between "and" and "&&" operators in PHP?




I have the following code and don't think and is needed, i.e. && should be used, as there is nothing to assign the left part to?



if($_REQUEST['foo'] != 'abc' and $_REQUEST['bar'] == 'def')
{
echo "all your base";
}



So it should be:



if($_REQUEST['foo'] != 'abc' && $_REQUEST['bar'] == 'def')
{
echo "all your base";
}

Answer



In your case, && and and do the same thing, but take a look at the operator precedence. You can see that && and and are not on the same level, so mixing that could give you unexpected results in some cases - I recommend always using &&, but that's your choice.



javascript - Validation for xxx-xxx-xxxx or (xxx)xxx-xxxx










Whats the regex for




xxx-xxx-xxxx
or
(xxx)xxx-xxxx


I can create regex for the first one with



/^\d{3}-\d{3}-\d{4}$/



but how to add rule in this so it can also handle the second one?


Answer



You can use this: -



/^(?:\(\d{3}\)|\d{3}-)\d{3}-\d{4}$/

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures?




I'm doing micro-optimization on a performance critical part of my code and came across the sequence of instructions (in AT&T syntax):



add %rax, %rbx
mov %rdx, %rax
mov %rbx, %rdx


I thought I finally had a use case for xchg which would allow me to shave an instruction and write:




add  %rbx, %rax
xchg %rax, %rdx


However, to my dimay I found from Agner Fog's instruction tables, that xchg is a 3 micro-op instruction with a 2 cycle latency on Sandy Bridge, Ivy Bridge, Broadwell, Haswell and even Skylake. 3 whole micro-ops and 2 cycles of latency! The 3 micro-ops throws off my 4-1-1-1 cadence and the 2 cycle latency makes it worse than the original in the best case since the last 2 instructions in the original might execute in parallel.



Now... I get that the CPU might be breaking the instruction into micro-ops that are equivalent to:



mov %rax, %tmp
mov %rdx, %rax

mov %tmp, %rdx


where tmp is an anonymous internal register and I suppose the last two micro-ops could be run in parallel so the latency is 2 cycles.



Given that register renaming occurs on these micro-architectures, though, it doesn't make sense to me that this is done this way. Why wouldn't the register renamer just swap the labels? In theory, this would have a latency of only 1 cycle (possibly 0?) and could be represented as a single micro-op so it would be much cheaper.


Answer



Supporting efficient xchg is non-trivial, and presumably not worth the extra complexity it would require in various parts of the CPU. A real CPU's microarchitecture is much more complicated than the mental model that you can use while optimizing software for it. For example, speculative execution makes everything more complicated, because it has to be able to roll back to the point where an exception occurred.



Making fxch efficient was important for x87 performance because the stack nature of x87 makes it (or alternatives like fld st(2)) hard to avoid. Compiler-generated FP code (for targets without SSE support) really does use fxch a significant amount. It seems that fast fxch was done because it was important, not because it's easy. Intel Haswell even dropped support for single-uop fxch. It's still zero-latency, but decodes to 2 uops on HSW and later (up from 1 in P5, and PPro through IvyBridge).




xchg is usually easy to avoid. In most cases, you can just unroll a loop so it's ok that the same value is now in a different register. e.g. Fibonacci with add rax, rdx / add rdx, rax instead of add rax, rdx / xchg rax, rdx. Compilers generally don't use xchg reg,reg, and usually hand-written asm doesn't either. (This chicken/egg problem is pretty similar to loop being slow (Why is the loop instruction slow? Couldn't Intel have implemented it efficiently?). loop would have been very useful for for adc loops on Core2/Nehalem where an adc + dec/jnz loop causes partial-flag stalls.)



Since xchg is still slow-ish on previous CPUs, compilers wouldn't start using it with -mtune=generic for several years. Unlike fxch or mov-elimination, a design-change to support fast xchg wouldn't help the CPU run most existing code faster, and would only enable performance gains over the current design in rare cases where it's actually a useful peephole optimization.








There are 4 operand sizes of xchg, 3 of which use the same opcode with REX or operand-size prefixes. (xchg r8,r8 is a separate opcode, so it's probably easier to make the decoders decode it differently from the others). The decoders already have to recognize xchg with a memory operand as special, because of the implicit lock prefix, but it's probably less decoder complexity (transistor-count + power) if the reg-reg forms all decode to the same number of uops for different operand sizes.




Making some r,r forms decode to a single uop would be even more complexity, because single-uop instructions have to be handled by the "simple" decoders as well as the complex decoder. So they would all need to be able to parse xchg and decide whether it was a single uop or multi-uop form.






AMD and Intel CPUs behave somewhat similarly from a programmer's perspective, but there are many signs that the internal implementation is vastly different. For example, Intel mov-elimination only works some of the time, limited by some kind of microarchitectural resources, but AMD CPUs that do mov-elimination do it 100% of the time (e.g. Bulldozer for the low lane of vector regs).



See Intel's optimization manual, Example 3-25. Re-ordering Sequence to Improve Effectiveness of Zero-Latency MOV Instructions, where they discuss overwriting the zero-latency-movzx result right away to free up the internal resource sooner. (I tried the examples on Haswell and Skylake, and found that mov-elimination did in fact work significantly more of the time when doing that, but that it was actually slightly slower in total cycles, instead of faster. The example was intended to show the benefit on IvyBridge, which probably bottlenecks on its 3 ALU ports, but HSW/SKL only bottleneck on resource conflicts in the dep chains and don't seem to be bothered by needing an ALU port for more of the movzx instructions.)



I don't know exactly what needs tracking in a limited-size table(?) for mov-elimination. Probably it's related to needing to free register-file entries as soon as possible when they're no longer needed, because Physical Register File size limits rather than ROB size can be the bottleneck for the out-of-order window size. Swapping around indices might make this harder.




xor-zeroing is eliminated 100% of the time on Intel Sandybridge-family; it's assumed that this works by renaming to a physical zero register, and this register never needs to be freed.



If xchg used the same mechanism that mov-elimination does, it also could probably only work some of the time. It would need to decode to enough uops to work in cases where it isn't handled at rename. (Or else the issue/rename stage would have to insert extra uops when an xchg will take more than 1 uop, like it does when un-laminating micro-fused uops with indexed addressing modes that can't stay micro-fused in the ROB, or when inserting merging uops for flags or high-8 partial registers. But that's a significant complication that would only be worth doing if xchg was a common and important instruction.)



Note that xchg r32,r32 has to zero-extend both results to 64 bits, so it can't be a simple swap of RAT (Register Alias Table) entries. It would be more like truncating both registers in-place. And note that Intel CPUs never eliminate mov same,same. It does already need to support mov r32,r32 and movzx r32, r8 with no execution port, so presumably it has some bits that indicate that rax = al or something. (And yes, Intel HSW/SKL do that, not just Ivybridge, despite what Agner's microarch guide says.)



We know P6 and SnB had upper-zeroed bits like this, because xor eax,eax before setz al avoids a partial-register stall when reading eax. HSW/SKL never rename al separately in the first place, only ah. It may not be a coincidence that partial-register renaming (other than AH) seems to have been dropped in the same uarch that introduced mov-elimination (Ivybridge). Still, setting that bit for 2 registers at once would be a special case that required special support.



xchg r64,r64 could maybe just swap the RAT entries, but decoding that differently from the r32 case is yet another complication. It might still need to trigger partial-register merging for both inputs, but add r64,r64 needs to do that, too.




Also note that an Intel uop (other than fxch) only ever produces one register result (plus flags). Not touching flags doesn't "free up" an output slot; For example mulx r64,r64,r64 still takes 2 uops to produce 2 integer outputs on HSW/SKL, even though all the "work" is done in the multiply unit on port 1, same as with mul r64 which does produce a flag result.)



Even if it is as simple as "swap the RAT entries", building a RAT that supports writing more than one entry per uop is a complication. What to do when renaming 4 xchg uops in a single issue group? It seems to me like it would make the logic significantly more complicated. Remember that this has to be built out of logic gates / transistors. Even if you say "handle that special case with a trap to microcode", you have to build the whole pipeline to support the possibility that that pipeline stage could take that kind of exception.



Single-uop fxch requires support for swapping RAT entries (or some other mechanism) in the FP RAT (fRAT), but it's a separate block of hardware from the integer RAT (iRAT). Leaving out that complication in the iRAT seems reasonable even if you have it in the fRAT (pre-Haswell).



Issue/rename complexity is definitely an issue for power consumption, though. Note that Skylake widened a lot of the front-end (legacy decode and uop cache fetch), and retirement, but kept the 4-wide issue/rename limit. SKL also added replicated execution units on more port in the back-end, so issue bandwidth is a bottleneck even more of the time, especially in code with a mix of loads, stores, and ALU.



The RAT (or the integer register file, IDK) may even have limited read ports, since there seem to be some front-end bottlenecks in issuing/renaming many 3-input uops like add rax, [rcx+rdx]. I posted some microbenchmarks (this and the follow-up post) showing Skylake being faster than Haswell when reading lots of registers, e.g. with micro-fusion of indexed addressing modes. Or maybe the bottleneck there was really some other microarchitectural limit.







But how does 1-uop fxch work? IDK how it's done in Sandybridge / Ivybridge. In P6-family CPUs, an extra remapping table exists basically to support FXCH. That might only be needed because P6 uses a Retirement Register File with 1 entry per "logical" register, instead of a physical register file (PRF). As you say, you'd expect it to be simpler when even "cold" register values are just a pointer to a PRF entry. (Source: US patent 5,499,352: Floating point register alias table FXCH and retirement floating point register array (describes Intel's P6 uarch).




One main reason the rfRAT array 802 is included within the present invention fRAT logic is a direct result of the manner in which the present invention implements the FXCH instruction.




(Thanks Andy Glew (@krazyglew), I hadn't thought of looking up patents to find out about CPU internals.) It's pretty heavy going, but may provide some insight into the bookkeeping needed for speculative execution.




Interesting tidbit: the patent describes integer as well, and mentions that there are some "hidden" logical registers which are reserved for use by microcode. (Intel's 3-uop xchg almost certain uses one of these as a temporary.)






We might be able to get some insight from looking at what AMD does.



Interestingly, AMD has 2-uop xchg r,r in K10, Bulldozer-family, Bobcat/Jaguar, and Ryzen. (But Jaguar xchg r8,r8 is 3 uops. Maybe to support the xchg ah,al corner case without a special uop for swapping the low 16 of a single reg).



Presumably both uops read the old values of the input architectural registers before the first one updates the RAT. IDK exactly how this works, since they aren't necessarily issued/renamed in the same cycle (but they are at least contiguous in the uop flow, so at worst the 2nd uop is the first uop in the next cycle). I have no idea if Haswell's 2-uop fxch works similarly, or if they're doing something else.




Ryzen is a new architecture designed after mov-elimination was "invented", so presumably they take advantage of it wherever possible. (Bulldozer-family renames vector moves (but only for the low 128b lane of YMM vectors); Ryzen is the first AMD architecture to do it for GP regs too.) xchg r32,r32 and r64,r64 are zero-latency (renamed), but still 2 uops each. (r8 and r16 need an execution unit, because they merge with the old value instead of zero-extending or copying the entire reg, but are still only 2 uops).



Ryzen's fxch is 1 uop. AMD (like Intel) probably isn't spending a lot of transistors on making x87 fast (e.g. fmul is only 1 per clock and on the same port as fadd), so presumably they were able to do this without a lot of extra support. Their micro-coded x87 instructions (like fyl2x) are faster than on recent Intel CPUs, so maybe Intel cares even less (at least about the microcoded x87 instruction).



Maybe AMD could have made xchg r64,r64 a single uop too, more easily than Intel. Maybe even xchg r32,r32 could be single uop, since like Intel it needs to support mov r32,r32 zero-extension with no execution port, so maybe it could just set whatever "upper 32 zeroed" bit exists to support that. Ryzen doesn't eliminate movzx r32, r8 at rename, so presumably there's only an upper32-zero bit, not bits for other widths.






What Intel might be able to do cheaply if they wanted to:




It's possible that Intel could support 2-uop xchg r,r the way Ryzen does (zero latency for the r32,r32 and r64,r64 forms, or 1c for the r8,r8 and r16,r16 forms) without too much extra complexity in critical parts of the core, like the issue/rename and retirement stages that manage the Register Alias Table (RAT). But maybe not, if they can't have 2 uops read the "old" value of a register when the first uop writes it.



Stuff like xchg ah,al is definitely a extra complication, since Intel CPUs don't rename partial registers separately anymore, except AH/BH/CH/DH.






xchg latency in practice on current hardware



Your guess about how it might work internally is good. It almost certainly uses one of the internal temporary registers (accessible only to microcode). Your guess about how they can reorder is too limited, though.

In fact, one direction has 2c latency and the other direction has ~1c latency.



00000000004000e0 <_start.loop>:
4000e0: 48 87 d1 xchg rcx,rdx # slow version
4000e3: 48 83 c1 01 add rcx,0x1
4000e7: 48 83 c1 01 add rcx,0x1
4000eb: 48 87 ca xchg rdx,rcx
4000ee: 48 83 c2 01 add rdx,0x1
4000f2: 48 83 c2 01 add rdx,0x1
4000f6: ff cd dec ebp

4000f8: 7f e6 jg 4000e0 <_start.loop>


This loop runs in ~8.06 cycles per iteration on Skylake. Reversing the xchg operands makes it run in ~6.23c cycles per iteration (measured with perf stat on Linux). uops issued/executed counters are equal, so no elimination happened. It looks like the dst <- src direction is the slow one, since putting the add uops on that dependency chain makes things slower than when they're on the dst -> src dependency chain.



If you ever want to use xchg reg,reg on the critical path (code-size reasons?), do it with the dst -> src direction on the critical path, because that's only about 1c latency.






Other side-topics from comments and the question





The 3 micro-ops throws off my 4-1-1-1 cadence




Sandybridge-family decoders are different from Core2/Nehalem. They can produce up to 4 uops total, not 7, so the patterns are 1-1-1-1, 2-1-1, 3-1, or 4.



Also beware that if the last uop is one that can macro-fuse, they will hang onto it until the next decode cycle in case the first instruction in the next block is a jcc. (This is a win when code runs multiple times from the uop cache for each time it's decoded. And that's still usually 3 uops per clock decode throughput.)



Skylake has an extra "simple" decoder so it can do 1-1-1-1-1 up to 4-1 I guess, but > 4 uops for one instruction still requires the microcode ROM. Skylake beefed up the uop cache, too, and can often bottleneck on the 4 fused-domain uops per clock issue/rename throughput limit if the back-end (or branch misses) aren't a bottleneck first.





I'm literally searching for ~1% speed bumps so hand optimization has been working out on the main loop code. Unfortunately that's ~18kB of code so I'm not even trying to consider the uop cache anymore.




That seems kinda crazy, unless you're mostly limiting yourself to asm-level optimization in shorter loops inside your main loop. Any inner loops within the main loop will still run from the uop cache, and that should probably be where you're spending most of your time optimizing. Compilers usually do a good-enough job that it's not practical for a human to do much over a large scale. Try to write your C or C++ in such a way that the compiler can do a good job with it, of course, but looking for tiny peephole optimizations like this over 18kB of code seems like going down the rabbit hole.



Use perf counters like idq.dsb_uops vs. uops_issued.any to see how many of your total uops came from the uop cache (DSB = Decode Stream Buffer or something). Intel's optimization manual has some suggestions for other perf counters to look at for code that doesn't fit in the uop cache, such as DSB2MITE_SWITCHES.PENALTY_CYCLES. (MITE is the legacy-decode path). Search the pdf for DSB to find a few places it's mentioned.



Perf counters will help you find spots with potential problems, e.g. regions with higher than average uops_issued.stall_cycles could benefit from finding ways to expose more ILP if there are any, or from solving a front-end problem, or from reducing branch-mispredicts.







As discussed in comments, a single uop produces at most 1 register result




As an aside, with a mul %rbx, do you really get %rdx and %rax all at once or does the ROB technically have access to the lower part of the result one cycle earlier than the higher part? Or is it like the "mul" uop goes into the multiplication unit and then the multiplication unit issues two uops straight into the ROB to write the result at the end?




Terminology: the multiply result doesn't go into the ROB. It goes over the forwarding network to whatever other uops read it, and goes into the PRF.




The mul %rbx instruction decodes to 2 uops in the decoders. They don't even have to issue in the same cycle, let alone execute in the same cycle.



However, Agner Fog's instruction tables only list a single latency number. It turns out that 3 cycles is the latency from both inputs to RAX. The minimum latency for RDX is 4c, according to InstlatX64 testing on both Haswell and Skylake-X.



From this, I conclude that the 2nd uop is dependent on the first, and exists to write the high half of the result to an architectural register. The port1 uop produces a full 128b multiply result.



I don't know where the high-half result lives until the p6 uop reads it. Perhaps there's some sort of internal queue between the multiply execution unit and hardware connected to port 6. By scheduling the p6 uop with a dependency on the low-half result, that might arrange for the p6 uops from multiple in-flight mul instructions to run in the correct order. But then instead of actually using that dummy low-half input, the uop would take the high half result from the queue output in an execution unit that's connected to port 6 and return that as the result. (This is pure guess work, but I think it's plausible as one possible internal implementation. See comments for some earlier ideas).



Interestingly, according to Agner Fog's instruction tables, on Haswell the two uops for mul r64 go to ports 1 and 6. mul r32 is 3 uops, and runs on p1 + p0156. Agner doesn't say whether that's really 2p1 + p0156 or p1 + 2p0156 like he does for some other insns. (However, he says that mulx r32,r32,r32 runs on p1 + 2p056 (note that p056 doesn't include p1).)




Even more strangely, he says that Skylake runs mulx r64,r64,r64 on p1 p5 but mul r64 on p1 p6. If that's accurate and not a typo (which is a possibility), it pretty much rules out the possibility that the extra uop is an upper-half multiplier.


html - PHP email does not work

I am creating an email form for a website and the html code is as follows.



        



























































* Mandatory fields




Tried the php code (in contact_process.php) below a lot but does not email the form to the specified email.



if(isset($_POST['email'])) {


$email_to = "johmwe@outlook.coM";

$email_subject = "Feedback Form Submissions";


function died($error) {
// your error code can go here
echo "We are very sorry, but there were error(s) found with the form you submitted. ";
echo "These errors appear below.

";
echo $error."

";

echo "Please go back and fix these errors.

";
die();
}

// validation expected data exists
if(!isset($_POST['first_name']) ||
!isset($_POST['last_name']) ||
!isset($_POST['email']) ||
!isset($_POST['telephone']) ||
!isset($_POST['comments'])) {

died('We are sorry, but there appears to be a problem with the form you submitted.');
}

$first_name = $_POST['first_name']; // required
$last_name = $_POST['last_name']; // required
$email_from = $_POST['email']; // required
$telephone = $_POST['telephone']; // not required
$comments = $_POST['comments']; // required

$error_message = "";

$email_exp = '/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
if(!preg_match($email_exp,$email_from)) {
$error_message .= 'The Email Address you entered does not appear to be valid.
';
}
$string_exp = "/^[A-Za-z .'-]+$/";
if(!preg_match($string_exp,$first_name)) {
$error_message .= 'The First Name you entered does not appear to be valid.
';
}
if(!preg_match($string_exp,$last_name)) {
$error_message .= 'The Last Name you entered does not appear to be valid.
';

}
if(strlen($comments) < 2) {
$error_message .= 'The Comments you entered do not appear to be valid.
';
}
if(strlen($error_message) > 0) {
died($error_message);
}
$email_message = "Form details below.\n\n";

function clean_string($string) {

$bad = array("content-type","bcc:","to:","cc:","href");
return str_replace($bad,"",$string);
}

$email_message .= "First Name: ".clean_string($first_name)."\n";
$email_message .= "Last Name: ".clean_string($last_name)."\n";
$email_message .= "Email: ".clean_string($email_from)."\n";
$email_message .= "Telephone: ".clean_string($telephone)."\n";
$email_message .= "Comments: ".clean_string($comments)."\n";



// creating email headers
$headers = 'From: '.$email_from."\r\n".
'Reply-To: '.$email_from."\r\n" .
'X-Mailer: PHP/' . phpversion();
@mail($email_to, $email_subject, $email_message, $headers);
?>

Thank you for contacting us. We will be in touch with you very soon.


}
die();
?>


Can someone please check the code and what am I doing wrong.



Further more, I would like to include an auto respond to the sender and a CAPTCHA image if possible for security issues.

'twin-peaks' tag wiki - Movies & TV



Television show of the 90s involving solving the mystery of the death of a high school girl of the Pacific Northwest, Laura Palmer, and the supernatural events surrounding the principal suspects, their friends, and enemies.







There is no tag wiki for this tag … yet!



Tag wikis help introduce newcomers to the tag. They contain an overview of the topic defined by the tag, along with guidelines on its usage.



All registered users may propose new tag wikis.




(Note that if you have less than 20000 reputation, your tag wiki will be peer reviewed before it is published.)


What are the differences in die() and exit() in PHP?

What are the differences between die() and exit() functions in PHP?



I think both have the same functionality, but I doubt there is something different in both... what is it?

[unable to retrieve full-text content]

php - return single array from json by passing a value

I have a json that I need to filter a specific key and value from


the following json


{
"5": {
"Owner": "94EAC",
"Record":"0121ln"
},
"15": {
"Owner": "009AC",
"Record":"0120Pc"
},
"1": {
"Owner": "00G11A",
"Record":"000lPcn"
},
"199": {
"Owner": "00G1y9",
"Record":"01211cn"
},
"33": {
"Owner": "001AC",
"Record":"0121n"
}

}


I would like to be able to pass the first int and get back array for that number.
For example if I pass 15 I get


 {
"Owner": "009AC",
"Record":"0120Pc"
}

I tried foreach loop but cannot set specific value for the first int


If I assign $data = json

then $date[15] didn't work
$data->15 also didn't work


I did also use the json decode and was able to print an array but wasn't able to get a single value
Any help would be great, I did spend all day and still cannot get an answer.
Thank you

java - How to read and save an Integer, Double, and String to a variable?



For a online course I'm taking,I'm trying to save the 2nd set of integer, double, and string that I defined to variables, after reading them (the 2nd set) using a scanner. The problem is I don't know how to do that to the 2nd set of variables that I defined. I've tried instantiating them to a new variable,but I keep running into errors. I need help to read each variable and then save them.




 import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

public static void main(String[] args) {
int i = 4;

double d = 4.0;
String s = "HackerRank ";


int j = 4;
double y = 9.0;
String k = "is the best place to learn and practice coding!";


int j = new j();

double y = new y();
String k = new k();
j.scanner.nextInt();
y.scanner.nextDouble();
k.scanner.nextLine();


System.out.print(j + i);
System.out.print(d + y);
System.out.print(s + k);


Answer



A call to nextLine() may return an empty string if there are no characters between the end of the last read and the beginning of the next line.



s1 = scan.nextLine();
s1 = scan.nextLine();


So to complete that challenge use the above code when you read the input from the user. And the entire code goes as follows.




import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

public static void main(String[] args) {
int i = 4;

double d = 4.0;
String s = "HackerRank ";

Scanner scan = new Scanner(System.in);
int i1;
double d1;
String s1;

i1 = scan.nextInt();
d1 = scan.nextDouble();

s1 = scan.nextLine();
s1 = scan.nextLine();

System.out.println(i+i1);
System.out.println(d+d1);
System.out.println(s+s1);
scan.close();
}
}


scope - Global variables in Javascript across multiple files



A bunch of my JavaScript code is in an external file called helpers.js. Inside the HTML that calls this JavaScript code I find myself in need of knowing if a certain function from helpers.js has been called.




I have attempted to create a global variable by defining:



var myFunctionTag = true;


In global scope both in my HTML code and in helpers.js.



Heres what my html code looks like:





...

...




Is what I am trying to do even feasible?


Answer



You need to declare the variable before you include the helpers.js file. Simply create a script tag above the include for helpers.js and define it there.





...


Reading a file line by line into elements of an array in Python




So in Ruby I can do the following:



testsite_array = Array.new
y=0
File.open('topsites.txt').each do |line|
testsite_array[y] = line
y=y+1
end



How would one do that in Python?


Answer



testsite_array = []
with open('topsites.txt') as my_file:
for line in my_file:
testsite_array.append(line)



This is possible because Python allows you to iterate over the file directly.



Alternatively, the more straightforward method, using f.readlines():



with open('topsites.txt') as my_file:
testsite_array = my_file.readlines()

How to parse JSON in Java

I have the following JSON text. How can I parse it to get the values of pageName, pagePic, post_id, etc.?



{
"pageInfo": {
"pageName": "abc",
"pagePic": "http://example.com/content.jpg"
},
"posts": [

{
"post_id": "123456789012_123456789012",
"actor_id": "1234567890",
"picOfPersonWhoPosted": "http://example.com/photo.jpg",
"nameOfPersonWhoPosted": "Jane Doe",
"message": "Sounds cool. Can't wait to see it!",
"likesCount": "2",
"comments": [],
"timeOfPost": "1234567890"
}

]
}

java - Got SQLException table doesn't exist using quartz jdbcstore



Iam implementing Quartz Scheduler using jdbcstore.I got exception like qrtz_TRIGGERS is not available.




2013-05-03 07:58:38,211 -  - DEBUG, [main], com.mchange.v2.c3p0.impl.DefaultConnectionTester, Testing a Connection in response to an Exception:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'myData.qrtz_TRIGGERS' doesn't exist


But actually table is available in my database and the table name is qrtz_triggers.the table name is all are small letters. So How to resolve this issue and my quartz properties below



org.quartz.scheduler.instanceName = APP1_SCHEDULER
org.quartz.threadPool.class = org.quartz.simpl.SimpleThreadPool
org.quartz.threadPool.threadCount = 4
org.quartz.threadPool.threadsInheritContextClassLoaderOfInitializingThread = true


#specify the jobstore used
org.quartz.jobStore.class = org.quartz.impl.jdbcjobstore.JobStoreTX
org.quartz.jobStore.driverDelegateClass = org.quartz.impl.jdbcjobstore.StdJDBCDelegate
org.quartz.jobStore.useProperties = false

#The datasource for the jobstore that is to be used
org.quartz.jobStore.dataSource = myDS

#quartz table prefixes in the database

org.quartz.jobStore.tablePrefix = qrtz_
org.quartz.jobStore.misfireThreshold = 60000
org.quartz.jobStore.isClustered = false

#The details of the datasource specified previously
org.quartz.dataSource.myDS.driver = com.mysql.jdbc.Driver
org.quartz.dataSource.myDS.URL = jdbc:mysql://localhost:3306/myData
org.quartz.dataSource.myDS.user = root
org.quartz.dataSource.myDS.password = root
org.quartz.dataSource.myDS.maxConnections = 20


Answer



Try renaming your table to qrtz_TRIGGERS? It looks like this is what the scheduler is looking for.


Using or in if statement (Python)

You can't use it like that. The or operator must have two boolean operands. You have a boolean and a string. You can write



weather == "Good!" or weather == "Great!": 


or



weather in ("Good!", "Great!"): 



Especially in the case of python, non empty strings evaluate to True, so



weather == "Good" or "Great":


will always be true, because "Great" is always true, making it a difficult mistake to spot.

Saturday, September 28, 2019

javascript - Loop inside React JSX



I'm trying to do something like the following in React JSX (where ObjectRow is a separate component):




for (var i=0; i < numrows; i++) {

}




I realize and understand why this isn't valid JSX, since JSX maps to function calls. However, coming from template land and being new to JSX, I am unsure how I would achieve the above (adding a component multiple times).


Answer



Think of it like you're just calling JavaScript functions. You can't use a for loop where the arguments to a function call would go:



return tbody(
for (var i = 0; i < numrows; i++) {
ObjectRow()
}
)



See how the function tbody is being passed a for loop as an argument, and of course that's a syntax error.



But you can make an array, and then pass that in as an argument:



var rows = [];
for (var i = 0; i < numrows; i++) {
rows.push(ObjectRow());
}

return tbody(rows);





You can use basically the same structure when working with JSX:



var rows = [];
for (var i = 0; i < numrows; i++) {
// note: we add a key prop here to allow react to uniquely identify each

// element in this array. see: https://reactjs.org/docs/lists-and-keys.html
rows.push();
}
return {rows};


Incidentally, my JavaScript example is almost exactly what that example of JSX transforms into. Play around with Babel REPL to get a feel for how JSX works.


jquery - Run javascript function when user finishes typing instead of on key up?



I want to trigger an ajax request when the user has finished typing in a text box. I don't want it to run the function on every time the user types a letter because that would result in A LOT of ajax requests, however I don't want them to have to hit the enter button either.



Is there a way so I can detect when the user has finished typing and then do the ajax request?




Using jQuery here!
Dave


Answer



So, I'm going to guess finish typing means you just stop for a while, say 5 seconds. So with that in mind, lets start a timer when the user releases a key and clear it when they press one. I decided the input in question will be #myInput.



Making a few assumptions...



//setup before functions
var typingTimer; //timer identifier
var doneTypingInterval = 5000; //time in ms, 5 second for example

var $input = $('#myInput');

//on keyup, start the countdown
$input.on('keyup', function () {
clearTimeout(typingTimer);
typingTimer = setTimeout(doneTyping, doneTypingInterval);
});

//on keydown, clear the countdown
$input.on('keydown', function () {

clearTimeout(typingTimer);
});

//user is "finished typing," do something
function doneTyping () {
//do something
}

hard drive - Leaving bad sectors in unformatted partition?

Laptop was acting really weird, and copy and seek times were really slow, so I decided to scan the hard drive surface. I have a couple hundr...