qid
int64
1
74.6M
question
stringlengths
45
24.2k
date
stringlengths
10
10
metadata
stringlengths
101
178
response_j
stringlengths
32
23.2k
response_k
stringlengths
21
13.2k
20,247,923
I'm making a program that change the color of the background, for example, when I press white, change background to white, black to black, and so on... and after have pressed a button the others disappear and I have already done that but what I want to do is that each tap on the Textview the buttons appear/disappear. how can I do this? this is my code ``` LinearLayout myLayout; LinearLayout myLayout2; // Declare UI elements private Button firstButton; private Button secondButton, thirdButton; // private ImageView changeBackground; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); myLayout = (LinearLayout) findViewById(R.id.myLayout); myLayout2 = (LinearLayout) findViewById(R.id.myLayout2); // Initialize the UI components firstButton = (Button) findViewById(R.id.button1); // When we creating a button and if we expect that to use for event handling we have to set the listener firstButton.setOnClickListener(this); secondButton = (Button) findViewById(R.id.button2); secondButton.setOnClickListener(this); thirdButton = (Button) findViewById(R.id.button3); thirdButton.setOnClickListener(this); } @Override public void onClick(View v) { // Parameter v stands for the view that was clicked. switch(v.getId()) { case R.id.button1: myLayout.setBackgroundColor(Color.WHITE); myLayout2.setVisibility(View.INVISIBLE); break; case R.id.button2: myLayout.setBackgroundColor(Color.BLACK); myLayout2.setVisibility(View.INVISIBLE); break; case R.id.button3: myLayout.setBackgroundColor(Color.RED); myLayout2.setVisibility(View.INVISIBLE); break; } } ``` the xml ``` <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:background="#A9F5F2" android:id="@+id/myLayout" tools:context=".MainActivity" > <TextView android:id="@+id/textView1" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:text="@string/hello_world" /> <LinearLayout android:id="@+id/myLayout2" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="#D8D8D8" android:orientation="horizontal" android:gravity="center" tools:context=".MainActivity" > <Button android:id="@+id/button1" style="?android:attr/buttonStyleSmall" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/white" /> <Button android:id="@+id/button2" style="?android:attr/buttonStyleSmall" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBaseline="@+id/button1" android:layout_alignBottom="@+id/button1" android:layout_toRightOf="@+id/button1" android:text="@string/black" /> <Button android:id="@+id/button3" style="?android:attr/buttonStyleSmall" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBaseline="@+id/button2" android:layout_alignBottom="@+id/button2" android:layout_toRightOf="@+id/button2" android:text="@string/red" /> </LinearLayout> </LinearLayout> ```
2013/11/27
['https://Stackoverflow.com/questions/20247923', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2958480/']
the problem was that i was calling a function (one click) and then nothing triggered. I change the code and now it's working super! here you can check it out: <http://bootply.com/97366> View: Is the same that in my question, but only changed the modal name to "myModal". Js File: ``` $('#myModal').on('show', function() { var id = $(this).data('id'), username = $(this).data('usern'); $('#myModal .modal-body p').html("Desea eliminar al usuario " + '<b>' + username + '</b>' + ' ?'); }) $('.confirm-delete').on('click', function(e) { e.preventDefault(); var id = $(this).data('id'); var user = $(this).data('title'); $('#myModal').data('id', id).modal('show'); $('#myModal').data('usern', user).modal('show'); }); $('#btnYes').click(function() { var id = $('#myModal').data('id'); $.ajax({ url: 'deleteFrontUser', type: 'POST', data: 'id='+id, success: function(html){ $('[data-id='+id+']').parents('tr').remove(); $('#myModal').modal('hide'); } }); return false; }); ``` What i also did, was to add "data-title" atribute in the html, like this: ``` <td><a href="#" class="confirm-delete btn mini red-stripe" role="button" data-title="{$frontuser->username}" data-id="{$frontuser->id}">Eliminar {$frontuser->id} {$frontuser->username} </a></td> ``` data-title stores the username so jquery can sustract it later. Please notice that i'm using smarty template engine. Hope this can help newbies like me :)
Try saving the id you pass there (I suppose it's the id of the user in the list) to a global variable which will be always overridden with the last id of the corresponding row where you pressed the delete button. and then you can just call the modal like this: ``` $('#myModal3').modal('show'); ``` After this you can get the id from the global variable and pass it to the ajax post
1,214,269
I created a console application using C# that references external DLLs. When I run it on my dev machine, everything works fine. On the production machine, I get a "type initiatization" error. Looking into this, it seems it may because the app can't find the referenced DLLs. On my dev box, the referenced DLLs are in the GAC, but not on the production one. When removing the DLLs from the GAC on the dev box, the same error occurs (unless I run it from a local Visual Studio build in debug mode). I'm more familiar with web site setups, and know there that the DLLs can be placed in the bin directory or the GAC so they can be found by the web application. But I'm not sure about how this works for console apps. I'm reluctant to put the DLL into the GAC on the production box, as it's only needed for this one small application. Are there other ways for me to deploy the console app and have it find its required assemblies? Here is the exception I'm getting: > > Error 1 The type or namespace name 'Entry' could not be found (are you > missing a using directive or an assembly reference?) C:\Documents and > Settings\Hacker\My Documents\Visual Studio > 2005\Projects\basic\basic\Program.cs 10 8 basic > > >
2009/07/31
['https://Stackoverflow.com/questions/1214269', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']
The simplest answer is to put the DLL's in the same directory as the Console Application and it will find them. The longer answer is fairly complex as there are many factors which influence how and where the CLR looks for referenced assemblies. I encourage you to take a look at the following article from MSDN which goes into great detail as to how this works. * <http://msdn.microsoft.com/en-us/magazine/cc164080.aspx>
When you examine the exception you get (and you may need to dive into the inner exception), you should see a log of all the locations searched (the "fusion log"). I'd recommend just placing the dependent DLLs in the same directory as your console app.
1,214,269
I created a console application using C# that references external DLLs. When I run it on my dev machine, everything works fine. On the production machine, I get a "type initiatization" error. Looking into this, it seems it may because the app can't find the referenced DLLs. On my dev box, the referenced DLLs are in the GAC, but not on the production one. When removing the DLLs from the GAC on the dev box, the same error occurs (unless I run it from a local Visual Studio build in debug mode). I'm more familiar with web site setups, and know there that the DLLs can be placed in the bin directory or the GAC so they can be found by the web application. But I'm not sure about how this works for console apps. I'm reluctant to put the DLL into the GAC on the production box, as it's only needed for this one small application. Are there other ways for me to deploy the console app and have it find its required assemblies? Here is the exception I'm getting: > > Error 1 The type or namespace name 'Entry' could not be found (are you > missing a using directive or an assembly reference?) C:\Documents and > Settings\Hacker\My Documents\Visual Studio > 2005\Projects\basic\basic\Program.cs 10 8 basic > > >
2009/07/31
['https://Stackoverflow.com/questions/1214269', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']
The simplest answer is to put the DLL's in the same directory as the Console Application and it will find them. The longer answer is fairly complex as there are many factors which influence how and where the CLR looks for referenced assemblies. I encourage you to take a look at the following article from MSDN which goes into great detail as to how this works. * <http://msdn.microsoft.com/en-us/magazine/cc164080.aspx>
The GAC ([Global Assembly Cache](http://msdn.microsoft.com/en-us/library/yf1d93sz%28VS.80%29.aspx)) registers your .dll's so you don't have to have them in the working directory of your application. All of .NET's .dll's (System.IO.dll, System.dll, etc) are registered through the GAC which means you don't have to have them in your application's directory. By default, if a .dll is not registered in the GAC, then the program will look in it's own directory for the missing .dll. So, you have three choices: 1. Add your referenced .dll's to the GAC, or 2. Add your referenced .dll's to the working directory of your application 3. Go to your references on the solution/project and select properties for that reference, set "CopyLocal = true" (Credit to Partha above for this)
1,214,269
I created a console application using C# that references external DLLs. When I run it on my dev machine, everything works fine. On the production machine, I get a "type initiatization" error. Looking into this, it seems it may because the app can't find the referenced DLLs. On my dev box, the referenced DLLs are in the GAC, but not on the production one. When removing the DLLs from the GAC on the dev box, the same error occurs (unless I run it from a local Visual Studio build in debug mode). I'm more familiar with web site setups, and know there that the DLLs can be placed in the bin directory or the GAC so they can be found by the web application. But I'm not sure about how this works for console apps. I'm reluctant to put the DLL into the GAC on the production box, as it's only needed for this one small application. Are there other ways for me to deploy the console app and have it find its required assemblies? Here is the exception I'm getting: > > Error 1 The type or namespace name 'Entry' could not be found (are you > missing a using directive or an assembly reference?) C:\Documents and > Settings\Hacker\My Documents\Visual Studio > 2005\Projects\basic\basic\Program.cs 10 8 basic > > >
2009/07/31
['https://Stackoverflow.com/questions/1214269', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']
The simplest answer is to put the DLL's in the same directory as the Console Application and it will find them. The longer answer is fairly complex as there are many factors which influence how and where the CLR looks for referenced assemblies. I encourage you to take a look at the following article from MSDN which goes into great detail as to how this works. * <http://msdn.microsoft.com/en-us/magazine/cc164080.aspx>
``` - Right click on the assembly name in your project reference. - select Properties - In the properties window set CopyLocal to true ```
1,214,269
I created a console application using C# that references external DLLs. When I run it on my dev machine, everything works fine. On the production machine, I get a "type initiatization" error. Looking into this, it seems it may because the app can't find the referenced DLLs. On my dev box, the referenced DLLs are in the GAC, but not on the production one. When removing the DLLs from the GAC on the dev box, the same error occurs (unless I run it from a local Visual Studio build in debug mode). I'm more familiar with web site setups, and know there that the DLLs can be placed in the bin directory or the GAC so they can be found by the web application. But I'm not sure about how this works for console apps. I'm reluctant to put the DLL into the GAC on the production box, as it's only needed for this one small application. Are there other ways for me to deploy the console app and have it find its required assemblies? Here is the exception I'm getting: > > Error 1 The type or namespace name 'Entry' could not be found (are you > missing a using directive or an assembly reference?) C:\Documents and > Settings\Hacker\My Documents\Visual Studio > 2005\Projects\basic\basic\Program.cs 10 8 basic > > >
2009/07/31
['https://Stackoverflow.com/questions/1214269', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']
The simplest answer is to put the DLL's in the same directory as the Console Application and it will find them. The longer answer is fairly complex as there are many factors which influence how and where the CLR looks for referenced assemblies. I encourage you to take a look at the following article from MSDN which goes into great detail as to how this works. * <http://msdn.microsoft.com/en-us/magazine/cc164080.aspx>
You can deploy referenced dlls where you want. You have to add an App.config (add/new item/application configuration file) to your base project and use the tag probing (configuration/runtime/assemblybinding/probing) to indicate a path for your dlls. You have to copy the dll or dlls to that path and add a reference to it in your project. In reference properties put "copy local" to "false".
1,214,269
I created a console application using C# that references external DLLs. When I run it on my dev machine, everything works fine. On the production machine, I get a "type initiatization" error. Looking into this, it seems it may because the app can't find the referenced DLLs. On my dev box, the referenced DLLs are in the GAC, but not on the production one. When removing the DLLs from the GAC on the dev box, the same error occurs (unless I run it from a local Visual Studio build in debug mode). I'm more familiar with web site setups, and know there that the DLLs can be placed in the bin directory or the GAC so they can be found by the web application. But I'm not sure about how this works for console apps. I'm reluctant to put the DLL into the GAC on the production box, as it's only needed for this one small application. Are there other ways for me to deploy the console app and have it find its required assemblies? Here is the exception I'm getting: > > Error 1 The type or namespace name 'Entry' could not be found (are you > missing a using directive or an assembly reference?) C:\Documents and > Settings\Hacker\My Documents\Visual Studio > 2005\Projects\basic\basic\Program.cs 10 8 basic > > >
2009/07/31
['https://Stackoverflow.com/questions/1214269', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']
The GAC ([Global Assembly Cache](http://msdn.microsoft.com/en-us/library/yf1d93sz%28VS.80%29.aspx)) registers your .dll's so you don't have to have them in the working directory of your application. All of .NET's .dll's (System.IO.dll, System.dll, etc) are registered through the GAC which means you don't have to have them in your application's directory. By default, if a .dll is not registered in the GAC, then the program will look in it's own directory for the missing .dll. So, you have three choices: 1. Add your referenced .dll's to the GAC, or 2. Add your referenced .dll's to the working directory of your application 3. Go to your references on the solution/project and select properties for that reference, set "CopyLocal = true" (Credit to Partha above for this)
When you examine the exception you get (and you may need to dive into the inner exception), you should see a log of all the locations searched (the "fusion log"). I'd recommend just placing the dependent DLLs in the same directory as your console app.
1,214,269
I created a console application using C# that references external DLLs. When I run it on my dev machine, everything works fine. On the production machine, I get a "type initiatization" error. Looking into this, it seems it may because the app can't find the referenced DLLs. On my dev box, the referenced DLLs are in the GAC, but not on the production one. When removing the DLLs from the GAC on the dev box, the same error occurs (unless I run it from a local Visual Studio build in debug mode). I'm more familiar with web site setups, and know there that the DLLs can be placed in the bin directory or the GAC so they can be found by the web application. But I'm not sure about how this works for console apps. I'm reluctant to put the DLL into the GAC on the production box, as it's only needed for this one small application. Are there other ways for me to deploy the console app and have it find its required assemblies? Here is the exception I'm getting: > > Error 1 The type or namespace name 'Entry' could not be found (are you > missing a using directive or an assembly reference?) C:\Documents and > Settings\Hacker\My Documents\Visual Studio > 2005\Projects\basic\basic\Program.cs 10 8 basic > > >
2009/07/31
['https://Stackoverflow.com/questions/1214269', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']
``` - Right click on the assembly name in your project reference. - select Properties - In the properties window set CopyLocal to true ```
When you examine the exception you get (and you may need to dive into the inner exception), you should see a log of all the locations searched (the "fusion log"). I'd recommend just placing the dependent DLLs in the same directory as your console app.
1,214,269
I created a console application using C# that references external DLLs. When I run it on my dev machine, everything works fine. On the production machine, I get a "type initiatization" error. Looking into this, it seems it may because the app can't find the referenced DLLs. On my dev box, the referenced DLLs are in the GAC, but not on the production one. When removing the DLLs from the GAC on the dev box, the same error occurs (unless I run it from a local Visual Studio build in debug mode). I'm more familiar with web site setups, and know there that the DLLs can be placed in the bin directory or the GAC so they can be found by the web application. But I'm not sure about how this works for console apps. I'm reluctant to put the DLL into the GAC on the production box, as it's only needed for this one small application. Are there other ways for me to deploy the console app and have it find its required assemblies? Here is the exception I'm getting: > > Error 1 The type or namespace name 'Entry' could not be found (are you > missing a using directive or an assembly reference?) C:\Documents and > Settings\Hacker\My Documents\Visual Studio > 2005\Projects\basic\basic\Program.cs 10 8 basic > > >
2009/07/31
['https://Stackoverflow.com/questions/1214269', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']
The GAC ([Global Assembly Cache](http://msdn.microsoft.com/en-us/library/yf1d93sz%28VS.80%29.aspx)) registers your .dll's so you don't have to have them in the working directory of your application. All of .NET's .dll's (System.IO.dll, System.dll, etc) are registered through the GAC which means you don't have to have them in your application's directory. By default, if a .dll is not registered in the GAC, then the program will look in it's own directory for the missing .dll. So, you have three choices: 1. Add your referenced .dll's to the GAC, or 2. Add your referenced .dll's to the working directory of your application 3. Go to your references on the solution/project and select properties for that reference, set "CopyLocal = true" (Credit to Partha above for this)
You can deploy referenced dlls where you want. You have to add an App.config (add/new item/application configuration file) to your base project and use the tag probing (configuration/runtime/assemblybinding/probing) to indicate a path for your dlls. You have to copy the dll or dlls to that path and add a reference to it in your project. In reference properties put "copy local" to "false".
1,214,269
I created a console application using C# that references external DLLs. When I run it on my dev machine, everything works fine. On the production machine, I get a "type initiatization" error. Looking into this, it seems it may because the app can't find the referenced DLLs. On my dev box, the referenced DLLs are in the GAC, but not on the production one. When removing the DLLs from the GAC on the dev box, the same error occurs (unless I run it from a local Visual Studio build in debug mode). I'm more familiar with web site setups, and know there that the DLLs can be placed in the bin directory or the GAC so they can be found by the web application. But I'm not sure about how this works for console apps. I'm reluctant to put the DLL into the GAC on the production box, as it's only needed for this one small application. Are there other ways for me to deploy the console app and have it find its required assemblies? Here is the exception I'm getting: > > Error 1 The type or namespace name 'Entry' could not be found (are you > missing a using directive or an assembly reference?) C:\Documents and > Settings\Hacker\My Documents\Visual Studio > 2005\Projects\basic\basic\Program.cs 10 8 basic > > >
2009/07/31
['https://Stackoverflow.com/questions/1214269', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']
``` - Right click on the assembly name in your project reference. - select Properties - In the properties window set CopyLocal to true ```
You can deploy referenced dlls where you want. You have to add an App.config (add/new item/application configuration file) to your base project and use the tag probing (configuration/runtime/assemblybinding/probing) to indicate a path for your dlls. You have to copy the dll or dlls to that path and add a reference to it in your project. In reference properties put "copy local" to "false".
162,148
I recently transferred a virtualbox machine from my laptop to my recently reinstalled desktop. The image works fine on my laptop, but when I try to boot it on my new machine, I get dumped to an "EFI Shell" where it asks me about my hard drives rather than booting the machine. I want it to boot to the actual machine image rather than this shell. How can I fix this?
2012/07/10
['https://askubuntu.com/questions/162148', 'https://askubuntu.com', 'https://askubuntu.com/users/74997/']
It turns out that as I was messing around with getting the machine to load (due to Virtualization technologies being disabled), I clicked one too many items on the image settings page. To fix this, go to the "Settings" page for the virtual machine, and click "System". Under the "motherboard" options, be sure that "Enable EFI (special OSes only)" is unchecked. Then click "OK", and try to boot the machine again. The option that was checked is basically how you get into the [EFI Interface](http://www.virtualbox.org/manual/ch03.html#efi).
1. in Efi shell: `edit startup.nsh` 2. add line `FS0:\EFI\Path\To\Desired.efi` 3. Save, reboot.
43,751,628
I am trying to update and insert using one file. Following code can insert the data but when i try to update it is not working but data is also going to else part when i try to update it. **Flow Homepage -> Insert/Update UI -> Insert/Update Operation** Homepage which display all the data. There is update and delete link button. Now you got idea that id is already passing. ``` <!DOCTYPE> <?php session_start(); /*if(!isset($_SESSION["isLogin"])) { header("location:index.php"); }*/ ?> <html> <head> <title></title> <?php include_once("include.html"); include_once("dbconfig.php"); ?> </head> <body> <?php include_once("navbar.html"); ?> <div class="main mainContentMargin"> <div class="row"> <?php $sth = $pdo->prepare("SELECT * FROM product_master where isActive='y' order by id desc"); $sth->execute(); ?> <div class="card col s12"> <table class="responsive-table centered striped"> <thead> <tr> <th style="width: 15%">Product Name</th> <th>Description</th> <th style="width: 15%">Price</th> <th>Update</th> <th>Delete</th> </tr> </thead> <tbody> <?php while ($row = $sth->fetch(PDO::FETCH_ASSOC)) { ?> <tr> <td style="width: 15%"><?php echo $row["p_name"] ?></td> <td ><?php echo $row["description"] ?></td> <td style="width: 15%"><?php echo $row["price"]." Rs./".$row["unit"] ?></td> <td style="width:5%"><a href="product.php?id=<?php echo $row["id"] ?>"><i class="material-icons">mode_edit</i></a></td> <td style="width:5%"><a href="delete.php?id=<?php echo $row["id"] ?>"><i class="material-icons">mode_delete</i></a></td> </tr> <?php } ?> </tbody> </table> </div> </div> </div> <?php include_once("footer.html");?> </body> </html> ``` Insert / Update UI ``` <?php session_start(); /*if(!isset($_SESSION["isLogin"])) { header("location:index.php"); }*/ ?> <html> <head> <title></title> <?php include_once("include.html"); include_once("dbconfig.php"); ?> </head> <body> <?php include_once("navbar.html"); ?> <?php $product=""; $descritpion=""; $price=""; $unit=""; $ins_up="Insert"; if(isset($_REQUEST["id"])) { $sth = $pdo->prepare("SELECT * FROM product_master where id=".$_REQUEST["id"]); $sth->execute(); while ($row = $sth->fetch(PDO::FETCH_ASSOC)) { $product=$row["p_name"]; $descritpion=$row["description"]; $price=$row["price"]; $unit=$row["unit"]; $ins_up="Update"; } } ?> <div class="main mainContentMargin"> <div class="row"> <form method="post" action="insertProduct.php"> <div class="card col s12"> <div class="card-content"> <div class="input-field"> <input type="text" name="txtProductname" id="txtProductname" value="<?php echo $product ?>"> <label for="txtProductname">Product Name</label> </div> <div class="input-field"> <textarea name="txtDesc" id="txtDesc" class="materialize-textarea" value="<?php echo $descritpion ?>"></textarea> <label for="txtDesc">Description</label> <script> $(document).ready(function($) { $('#txtDesc').val("<?php echo $descritpion ?>"); }); </script> </div> <div class="input-field"> <input type="number" name="txtProductprice" id="txtProductprice" value="<?php echo $price ?>"> <label for="txtProductprice">Price</label> </div> <div> <?php if($unit=="pcs" || $unit=="") { ?> <input name="group1" type="radio" id="pcsUnit" value="pcs" checked /> <label for="pcsUnit">Pcs.</label> <input name="group1" type="radio" id="pcsKg" value="kg" /> <label for="pcsKg">KG.</label> <?php } else { ?> <input name="group1" type="radio" id="pcsUnit" value="pcs" /> <label for="pcsUnit">Pcs.</label> <input name="group1" type="radio" id="pcsKg" value="kg" checked /> <label for="pcsKg">KG.</label> <?php } ?> </div> </div> <div class="card-action"> <div class="input-field"> <input type="submit" class="btn" name="btnInsert" id="btnInsert" value="<?php echo $ins_up ?>"></td> </div> </div> </div> </form> </div> </div> <?php include_once("footer.html");?> </body> </html> ``` Insert / Update Operation File ``` <?php include("dbconfig.php"); if(isset($_REQUEST["id"])) $id=$_REQUEST["id"]; $name=$_REQUEST["txtProductname"]; $description=$_REQUEST["txtDesc"]; $price=$_REQUEST["txtProductprice"]; $unit=$_REQUEST["group1"]; if($_REQUEST["btnInsert"]!="Update") { $stmt=$pdo->prepare("INSERT INTO product_master (p_name, description, price,unit,isActive) VALUES (:p_name, :description, :price,:unit,:isActive)"); $isActive='y'; $stmt->bindParam(':isActive', $isActive); } else { $stmt=$pdo->prepare("update product_master SET p_name=:p_name , description=:description , price=:price , unit=:unit where id=:id"); $stmt->bindParam(":id",$id); } $stmt->bindParam(':p_name', $name); $stmt->bindParam(':description', $description); $stmt->bindParam(':price', $price); $stmt->bindParam(':unit', $unit); $stmt->execute(); if($stmt->rowCount()) { echo 'success'; } else { echo 'update failed'; } //header('Location: home.php'); ?> ``` DBConfig ``` <?php $pdo = new PDO("mysql:host=localhost; dbname=db_inventory;","root",""); $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $pdo->exec("set names utf8"); ?> ```
2017/05/03
['https://Stackoverflow.com/questions/43751628', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4995030/']
`$id` is not defined when you run your `UPDATE`. While you have defined `id` while you're on on the GUI page, the value is not passed with the next request to the script that actually queries your database. Add the following line to your form: ``` <input type="hidden" name="id" value="<?php echo htmlentities($_GET['id']); ?>" /> ```
Make user your id is retrieved properly. In your form i didn't any input element for the **id**. So when you try to get from the request it always comes empty. If you server error logs are on, you might get the error **undefined variable $id...**
72,695,685
I am working with JetEngine forms and i need to add a dropdown of users to select from in one of the form. is there any way to do this? i dont see any field type of users and also for the select option. if i choose filled dynamicly i have some pre build functions to get the data but none for the users? How can I set this dropdown or build a function to be show as one of the dynamiclly generated options? I have not found much on serching this issue and not in their documentation
2022/06/21
['https://Stackoverflow.com/questions/72695685', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2022193/']
Here I got the solution and it works. ``` const [loading, setLoading] = useState(false); const [data, setData] = useState([]); const getCMSID = () => { let url = `${URL}/store-api/category`; let getId = { method: 'POST', headers: { 'Content-Type': 'application/json', Accept: 'application/json', 'sw-access-key': `${API_KEY}`, }, }; fetch(url, getId) .then(res => res.json()) .then(json => { getCMSPage(json.elements[0].cmsPageId); }) .catch(err => console.error('error:' + err)); const getCMSPage = gId => { const cmsUrl = `${URL}/store-api/cms/${gId}`; let getcms = { method: 'POST', headers: { 'Content-Type': 'application/json', Accept: 'application/json', 'sw-access-key': `${API_KEY}`, }, }; fetch(cmsUrl, getcms) .then(res => res.json()) .then(json => { setData(json.sections); setLoading(false); }) .catch(err => console.error('Error:' + err)); }; }; useEffect(() => { getCMSID(); }, []); ``` @credit **Nayeem M. Muzahid**
***useState*** hook is asynchronous. So do not set something using ***useState*** and use it inside the same function. As per your code, you can just use the ID directly without using the set value. ``` const [loading, setLoading] = useState(true); const [data, setData] = useState([]); const [id, setId] = useState(' '); const getCMSID = () => { let url = `${URL}/store-api/category`; let getId = { method: 'POST', headers: { 'Content-Type': 'application/json', Accept: 'application/json', 'sw-access-key': `${API_KEY}`, }, }; fetch(url, getId) .then(res => res.json()) .then(json => { return setId(json.elements[0].cmsPageId)}) .catch(err => console.error('error:' + err)); const getCMSPage = () => { const cmsUrl = `${URL}/store-api/cms/${globalID}`; let getcms = { method: 'POST', headers: { 'Content-Type': 'application/json', Accept: 'application/json', 'sw-access-key': `${API_KEY}`, }, }; fetch(cmsUrl, getcms) .then(res => res.json()) .then(json => { setData(json.sections); setLoading(false); }) .catch(err => console.error('Error:' + err)); }; getCMSPage(); }; useEffect(() => { getCMSID(); }, []); ``` And use the value of the hook outside the function if you need it.
27,812,897
I have a Node / Mongoose / MongoDB project which I use Selenium WebDriver for integration tests. Part of my testcase setup is to wipe the database before each test. I accomplish this via command line using the method that's heavily accepted here [Delete everything in a MongoDB database](https://stackoverflow.com/questions/3366397/delete-everything-in-a-mongodb-database) ``` mongo [database] --eval "db.dropDatabase();" ``` The problem is however that after running this command, Mongo no longer enforces any unique fields, such as the following as defined by my Mongoose Schema: ``` new Mongoose.Schema name : type : String required : true unique : true ``` If I restart `mongod` after the `dropDatabase` then the unique constraints are enforced again. However since my `mongod` is run by a separate process, restarting it as part of my test case set up would be cumbersome, and I'm hoping unnecessary. Is this a bug or am I missing something?
2015/01/07
['https://Stackoverflow.com/questions/27812897', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/698289/']
As you stated, your `mongod` (or multiple ones) is a separate process to your application, and as such your application has no knowledge of what has happened when you dropped the database. While the collections and indeed the database will be created when accessed by default, this is not true of all the indexes you defined. Index creation actually happens on application start-up, as is noted in this passage from the documentation: > > When your application starts up, Mongoose automatically calls ensureIndex for each defined index in your schema. ... > > > It does not automatically happen each time a model is accessed, mostly because that would be excessive overhead, even if the index is in place and the server does nothing, it's still additional calls that you don't want preceeding every "read", "update", "insert" or "delete". So in order to have this "automatic" behavior "fire again", what you need to do is "restart" your application and this process will be run again on connection. In the same way, when your "application" cannot connect to the `mongod` process, it re-tries the connection and when reconnected the automatic code is run. Alternately, you can code a function you could call to do this and expose the method from an API so you could link this function with any other external operation that does something like "drop database": ```js function reIndexAllModels(callback) { console.log("Re-Indexing all models"); async.eachLimit( mongoose.connection.modelNames(), 10, function(name,callback) { console.log("Indexing %s", name); mongoose.model(name).ensureIndexes(callback); }, function(err) { if(err) throw err; console.log("Re-Indexing done"); callback(); } ); } ``` That will cycle through all registered models and re-create all indexes that are assigned to them. Depending on the size of registered models, you probably don't want to run all of these in parallel connections. So to help a little here, I use `async.eachLimit` in order to keep the concurrent operations to a manageable number.
Thanks to Neil Lunn for pointing out the pitfalls of `dropDatabase` and re-indexing. Ultimately, I went for the following command line solution, and removing the `dropDatabase` command. ``` mongo [database] --eval "db.getCollectionNames().forEach(function(n){db[n].remove()});" ```
9,249,793
> > **Possible Duplicate:** > > [MySQL delete row from multiple tables](https://stackoverflow.com/questions/2214433/mysql-delete-row-from-multiple-tables) > > > I have 5 tables: * members * member\_videos * member\_photos * member\_friends * member\_pages When I delete that member, I want to delete all his records from these tables. `member_id` exist in all tables. I'm doing this with 5 queries for each table. Can I use `LEFT JOIN` or something like this do to this in one query?
2012/02/12
['https://Stackoverflow.com/questions/9249793', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1020895/']
Yes, you can. ``` DELETE m, mv, mp, mf, mpp FROM members AS m LEFT JOIN member_videos AS mv ON mv.member_id = m.id LEFT JOIN member_photos AS mp ON mp.member_id = m.id LEFT JOIN member_friends AS mf ON mf.member_id = m.id LEFT JOIN member_pages AS mpp ON mpp.member_id = m.id WHERE m.id = 12 ```
I don't think you can. However, I think you can separate the queries with ; and give it as one query to mysql\_query() or whatever you're using. For example: ``` mysql_query('DELETE * FROM members WHERE user_id = 4; DELETE * FROM member_videos WHERE user_id = 4;'); ``` and so on :)
9,249,793
> > **Possible Duplicate:** > > [MySQL delete row from multiple tables](https://stackoverflow.com/questions/2214433/mysql-delete-row-from-multiple-tables) > > > I have 5 tables: * members * member\_videos * member\_photos * member\_friends * member\_pages When I delete that member, I want to delete all his records from these tables. `member_id` exist in all tables. I'm doing this with 5 queries for each table. Can I use `LEFT JOIN` or something like this do to this in one query?
2012/02/12
['https://Stackoverflow.com/questions/9249793', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1020895/']
<http://dev.mysql.com/doc/refman/5.0/en/delete.html> Check this page, there is a section for multiple-tables DELETE.
I don't think you can. However, I think you can separate the queries with ; and give it as one query to mysql\_query() or whatever you're using. For example: ``` mysql_query('DELETE * FROM members WHERE user_id = 4; DELETE * FROM member_videos WHERE user_id = 4;'); ``` and so on :)
9,249,793
> > **Possible Duplicate:** > > [MySQL delete row from multiple tables](https://stackoverflow.com/questions/2214433/mysql-delete-row-from-multiple-tables) > > > I have 5 tables: * members * member\_videos * member\_photos * member\_friends * member\_pages When I delete that member, I want to delete all his records from these tables. `member_id` exist in all tables. I'm doing this with 5 queries for each table. Can I use `LEFT JOIN` or something like this do to this in one query?
2012/02/12
['https://Stackoverflow.com/questions/9249793', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1020895/']
Yes, you can. ``` DELETE m, mv, mp, mf, mpp FROM members AS m LEFT JOIN member_videos AS mv ON mv.member_id = m.id LEFT JOIN member_photos AS mp ON mp.member_id = m.id LEFT JOIN member_friends AS mf ON mf.member_id = m.id LEFT JOIN member_pages AS mpp ON mpp.member_id = m.id WHERE m.id = 12 ```
<http://dev.mysql.com/doc/refman/5.0/en/delete.html> Check this page, there is a section for multiple-tables DELETE.
52,937,718
Having the following dataframe: ``` UserID TweetLanguage 2014-08-25 21:00:00 001 english 2014-08-27 21:04:00 001 arabic 2014-08-29 22:07:00 001 espanish 2014-08-25 22:09:00 002 english 2014-08-26 22:09:00 002 espanish 2014-08-25 22:09:00 003 english ``` I need to plot the weekly number of users who have posted in more than one language. For example, in the above dataframe, user 001 and 002 have tweeted in more than one languages. So in the plot, the corresponding value for this week should be 2. Same story for other weeks.
2018/10/22
['https://Stackoverflow.com/questions/52937718', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5413088/']
``` df.groupby([pd.Grouper(freq='W'), 'User ID'])['TweetLanguage'].nunique().unstack().plot() ```
``` df.groupby(pd.Grouper(key='datetime', freq='W')).apply(lambda df:\ df.groupby('UserID').apply(lambda df: len(df.TweetLanguage.value_counts()))) ``` This is a one liner that will seperate the week and get number of language in a week ``` df.groupby('UserID').apply(lambda df: len(df.TweetLanguage.value_counts())) ``` This will return a series with index: value of user ID : number of language used for each week..
52,937,718
Having the following dataframe: ``` UserID TweetLanguage 2014-08-25 21:00:00 001 english 2014-08-27 21:04:00 001 arabic 2014-08-29 22:07:00 001 espanish 2014-08-25 22:09:00 002 english 2014-08-26 22:09:00 002 espanish 2014-08-25 22:09:00 003 english ``` I need to plot the weekly number of users who have posted in more than one language. For example, in the above dataframe, user 001 and 002 have tweeted in more than one languages. So in the plot, the corresponding value for this week should be 2. Same story for other weeks.
2018/10/22
['https://Stackoverflow.com/questions/52937718', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5413088/']
``` df.groupby([pd.Grouper(freq='W'), 'User ID'])['TweetLanguage'].nunique().unstack().plot() ```
Use 2 `groupbys`. The first finds the users who post in more than one language every week, the second counts how many there are per week. ``` (df.groupby([df.index.year.rename('year'), df.index.week.rename('week'), 'UserID']).TweetLanguage.nunique() > 1).groupby(level=[0,1]).sum() #year week #2014 35 2.0 #Name: TweetLanguage, dtype: float64 ```
153,204
I am working with Goole map in a VF page.Consider that Account object has Geolocation field. Based on the user location I have mapped the center point in the map and got the bounds of the map using getBounds() function in javascript. `GetBounds` returns two Geolocations SouthWest and NorthEast. How I can query all the accounts within those two geolocations?
2016/12/20
['https://salesforce.stackexchange.com/questions/153204', 'https://salesforce.stackexchange.com', 'https://salesforce.stackexchange.com/users/19084/']
If you can get a latitude/longitude pair from those Geolocations on the page, you should be able to find records within a radius of those points via the `DISTANCE` and `GEOLOCATION` functions used in a `WHERE` clause. The specifics of these functions are discussed in the [Geolocation based SOQL Queries](https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/sforce_api_calls_soql_geolocate.htm) documentation. If the [release notes](https://developer.salesforce.com/releases/release/Summer15/queries) are correct, you can preform queries such as the ones below: ``` Double myLatitude = 10; Double myLongitude = 10; List accountList = [SELECT Id, Name, BillingLatitude, BillingLongitude FROM Account WHERE DISTANCE(My_Location_Field__c, GEOLOCATION(:myLatitude, :myLongitude), 'mi') < 10]; Location myLocation = Location.newInstance(10, 10); Double myDistance = 100; List accountList = [SELECT Id, Name, BillingLatitude, BillingLongitude FROM Account WHERE DISTANCE(My_Location_Field__c, :myLocation, 'mi') < :myDistance]; ``` The key of these queries is in the `WHERE` clause. Querying based on the results of a query filtered by a formula to determine the distance between the specified point, provided by the javascript on your page, and the location of each record should provide the behavior you are looking for. --- Below is an example of a page/controller which would be setup to perform these queries. Page Example ============ ``` <apex:actionFunction name="GetRecordsAtLocation" action="{!GetRecordsAtLocation}" rerender="ResultsPanel"> <apex:param name="Longitude" assignTo="{!Longitude}" value="" /> <apex:param name="Latitude" assignTo="{!Latitude}" value="" /> </apex:actionFunction> <!-- ... --> <script> var someGeolocation = something.GetBounds(); GetRecordsAtLocation(someGeolocation.Longitude, someGeolocation.Latitude); </script> ``` As you can see, you'll need a way to pass the values from your page's javascript, over to the controller. This is where using an `actionFunction` comes in handy. Controller Example ================== ``` public List<Account> accountsAtLocation { get; set; } public Double Longitude { get; set; } public Double Latitude { get; set; } public PageReference GetRecordsAtLocation() { accountsAtLocation = [SELECT Id, Name, BillingLatitude, BillingLongitude FROM Account WHERE DISTANCE(My_Location_Field__c, GEOLOCATION(:Latitude, :Longitude), 'mi') < 10]; return null; } ``` You'll need a function setup to perform the query based on values set by the `actionFunction`, and then save those records to a variable which you can access on the page.
Finally Google developer doc helped me. Here is the solution, ``` //Creating the map var mapOptions = {center: myLatLng , zoom: 8, mapTypeId: google.maps.MapTypeId.ROADMAP}; //Link with page component var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions); //Get the bounds of the map this will return LatLngBounds var bounds = map.getBounds(); ver newGeolocation = new google.maps.LatLng(13, 81); //Bounds will check whether given geolocation exist within the bounds if(bounds.contains(newGeolocation) { //Got the location which exist within the current map bounds } ``` > > **google.maps.LatLngBounds** class has the inbuild function > **contains(latLng:LatLng|LatLngLiteral)** > Return Value: boolean Returns > true if the given lat/lng is in this bounds. > > >
7,182,762
I'm using Netbeans to compile and sign all my jars, all with the same certificate. However, when I run Webstart with Sun Java SE 6, I get the error Found unsigned entry in resource .. .jar. I messed around with adding and removing jars, etc, but no luck. As far as I know the keystore is in the build directory and gets created on every *clean and build*. It gives this error not for one jar, but multiple (switching orders of jars led me to believe this). I'm using Netbeans 7. I booted Windows this morning and got the error, which I didn't have yesterdag or before. I'm pulling my hair out, Webstart and the like is driving me crazy! Any help would be really appreciated. Edit: The manifest files all look alright btw. Edit: The jnlp looks fine as well, and didnt change any from before it broke.
2011/08/24
['https://Stackoverflow.com/questions/7182762', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1925248/']
Enabling JAR caching should fix the problem. It's a common bug that exists in Java for *years*. For details, see my blogpost: <https://www.nowaker.net/post/found-unsigned-entry-in-resource-java-web-start.html>
I restarted the pc again and it works again. Must've been something weird with the Java JRE or something...
66,117
According to Judaism illicit relations are forbidden. I always thought that the way one can control his lustful desires is by marrying. In the *Garden of Peace*, Rabbi Shalom Arush says that a man cannot be a giver if he has lust towards his wife. That is, he should nullify all his lust towards his wife and only focus on giving to her. Is this opinion unique to the Breslov way of thought or are there other opinions that support this idea?
2015/12/09
['https://judaism.stackexchange.com/questions/66117', 'https://judaism.stackexchange.com', 'https://judaism.stackexchange.com/users/3006/']
This discussion centers around the mishna in avos towards the end of chapter two (either mishna 12 or 17, depending on your print) "all your deeds should be lishem shomayim". Rambam offers two different approaches between his pirush on the mishna and in his shmona perakim, which is echoed in the two different approaches in the shulchan aruch brought in shalom's answer. See there and the sources in Shalom's sources for a better understanding. There is also the gemara in Bava Basra 16a which praises Avraham for having never concentrated on Sarah's beauty, brought in Rashi on Lech Licha 12 11. This would give credence to the no personal enjoyment approach. This is all Midas Chasidus though. A possibly unattainable goal for which the true benefit is gained simply by a different approach to life. There are many examples in the Talmud where a wife's beauty is appreciated for shalom bayis. In fact the seffer chasidim says it is not allowed to marry someone one finds unattractive as he will spend the rest of his life secretly praying for her to die. So as with all Midas Chasidus, a disclaimer is in order, not to ruin the main mitzvah while chasing chasing the extra credit. Especially when this mitzvah involves another human being who might not appreciate the lisheim shomayim approach, see the parenthetical story. (Sad story disclaimer: I had a friend in yeshiva who was the type of masmid who actually learned in his sleep. Seriously. Actual gemara came out of his mouth in his sleep. He impressed all of us cynics. Well, a couple of years into his marriage his wife asked him\* what goes through his mind when they were together. He told her all his higher kavanos and all his lisheim shomayim intentions. She divorced him and took the kids. * I know because this wife's confidant was another friend's wife)
There are some *very, very* different views on the subject in different sources. [More is discussed here.](https://judaism.stackexchange.com/a/33902/21) Satmar thought has similar language, by the way. And many other groups feel that's unworkable. The Shulchan Aruch in Or HaChaim uses very strong language about "only for her", but in Even HaEzer that does not appear. Most notably, the Aruch HaShulchan modifies the Shulchan Aruch's language from "only for her" to "also about her." That's an approach that I've heard from many contemporary marital educators: in a healthy relationship, it can't be *entirely* about only one person.
66,117
According to Judaism illicit relations are forbidden. I always thought that the way one can control his lustful desires is by marrying. In the *Garden of Peace*, Rabbi Shalom Arush says that a man cannot be a giver if he has lust towards his wife. That is, he should nullify all his lust towards his wife and only focus on giving to her. Is this opinion unique to the Breslov way of thought or are there other opinions that support this idea?
2015/12/09
['https://judaism.stackexchange.com/questions/66117', 'https://judaism.stackexchange.com', 'https://judaism.stackexchange.com/users/3006/']
Ezra and his generation of Anshei Keneses haGdolah tried to put in place legislation requiring a man to go to the miqvah the morning after relations, "so that he should not copulate like a rooster". I don't know if this was an estimate of the right level of annoyance the next morning, or so that the man who did overdue it would pay a social penalty because someone would eventually notice how often he goes. This legislation was never accepted by the masses, and therefore did not become binding. (Shulchan Arukh, OC 88:1) But the motive behind the attempt tells you something. Similarly, Nachmanides on "qedoshim tihyu, qi Qadosh Ani -- be holy, for I Am Holy" (Vayiqra 19:2) says that the mitzvah is to avoid being a "naval bireshus haTorah -- a knave with [what would otherwise be] the permission of the Torah". Or, as Nachmanides is explained by Rav Shimon Shkop (introduction, Shaarei Yosher), to avoid those distractions from one's commitment to holiness. What is knavely behavior? "The person who is driven by appetite (ba’al ta’avah) will find room to indulge in lustful behavior with his wife or his numerous u wives, and to be among those that swill wine and guzzle meat (per Prov 23:20), and will speak freely using all those vulgarities that are not explicitly prohibited by the Torah. ... Therefore this verse comes, after [the Torah] has enumerated those things that are completely prohibited, commanding in a general way to separate ourselves from excessive material indulgence and to restrict ourselves in sexual intercourse, as the Rabbis say, “Sages ought not to be found with their wives like roosters” [Berakhos 22a], but only engage in sexual relations according to that which is needed to fulfill the mitzvot connected therewith." Those mitzvos being the connecting with another person "and he shall be attached to his wife and become another person" (Bereishis 2:24) and procreation (Bereishis 1:28). Similar to Rav Shimon Shkop's take on the Ramban, that overdoing it is defined by distractions to holiness, we find Rav Moshe Chaim Luzzatto writing in Mesilas Yesharim (ch. 14) writes (bracketed insertion and emphasis mine): > > Separation in relation to pleasures, which we spoke of in the previous chapter [where it is given as one of three types of "separation"], consists in one’s taking from the world only what is essential to him. This type of Separation encompasses anything which provides pleasure to any one of the senses, whether the pleasure be gained through food, **cohabitation**, clothing, strolls, conversation or similar means, exceptions obtaining only at such times when deriving pleasure through these means is a mitzvah. > > > So there is a call to refrain from overdoing sex, but the definition of "overdoing" is when it gets to the point that you lose sight of bonding to one's spouse, a very contextual and subjective frequency.
There are some *very, very* different views on the subject in different sources. [More is discussed here.](https://judaism.stackexchange.com/a/33902/21) Satmar thought has similar language, by the way. And many other groups feel that's unworkable. The Shulchan Aruch in Or HaChaim uses very strong language about "only for her", but in Even HaEzer that does not appear. Most notably, the Aruch HaShulchan modifies the Shulchan Aruch's language from "only for her" to "also about her." That's an approach that I've heard from many contemporary marital educators: in a healthy relationship, it can't be *entirely* about only one person.
3,392,055
Need some hints how to solve the following differential equation $$xy'= \sqrt{y^2+x^2}+y$$ Just don't know how to begin. Thank you.
2019/10/13
['https://math.stackexchange.com/questions/3392055', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/680628/']
Alternatively, you could try to make use of the hyperbolic identity $$\cosh^2t - \sinh^2t = 1 \implies \cosh^2t = 1 + \sinh^2t$$ and use the inspired substitution $$y = x\sinh\left(f(x)\right)$$ which simplifies nicely: $$x(\sinh(f(x)) + xf'(x)\cosh(f(x))) = |x|\cosh(f(x))+x\sinh(f(x)) \implies f'(x) = \frac{1}{|x|}$$ which implies the solution is of the form $$y = x\sinh(\text{sgn}(x)(\log(|x|)+C)) = \frac{1}{2}(Cx^2 - C^{-1})$$ So it's an upward parabola on both sides. (the $C$'s in the final answer must be positive since they are the end result of an exponentiation).
Square both sides then replace $\sqrt{y^2+x^2}$ by $xy'-y$ This becomes $$x^2(y')^2+y^2-xy'(1+y)-y=0$$ Now you could you appropriate subsitution
65,788,251
I am using reselect lib in my React project. Here is a code: ``` const App = () => { // const { tickets, isFetching, error } = useSelector(({ tickets }) => tickets) // <- this works good const { sorterTabs, selected } = useSelector(({ sorter }) => sorter) const { isFetching } = useSelector(({ tickets }) => tickets) const dispatch = useDispatch() const tickets = useSelector(sorterSelector) // <- this doesn't work good const handleSorterClick = ({ target }) => { dispatch(getSelectedSorter(target.getAttribute('name'))) } const renderedTickets = tickets.map((ticket) => { // <- problem: I have undefined here because selector returns undefined const src = `http://pics.avs.io/99/36/${ticket.carrier}.png` return ( <Ticket key={ticket.price + ticket.segments[0].duration} ticket={ticket} price={ticket.price} src={src} segment={ticket.segments} /> ) }).slice(0,5) useEffect(() => { dispatch(fetchData()) }, []) return ( <div className="container"> <Header /> <div className="content"> <Filter /> <div className="content__item"> <div className="content__item__sorting"> <Sorter sorterTabs={sorterTabs} selected={selected} handleSorterClick={handleSorterClick} /> </div> {isFetching ? <img src={preloader} alt="preloader" /> : <div className="content__item__tickets"> {renderedTickets} </div> } </div> </div> </div> ) } ``` Code for selector: ``` const allTickets = state => state.tickets.tickets // <- this gets undefined const selected = state => state.sorter.selected export const sorterSelector = createSelector( [allTickets, selected], (tickets, selec) => { if (selec === "Самый дешевый") { tickets.sort((a, b) => { return a.price - b.price }) } else { tickets.sort((a, b) => { return (a.segments[0].duration + a.segments[1].duration) - (b.segments[0].duration + b.segments[1].duration) }) } } ) ``` As I mentioned in the App's code, first commented line (where I destructure the object) works good: I'm fetching tickets from the server, put them in redux state, get them in App's component and render them. But if I create selector by `createSelector` function from 'reselect' lib and put it in `useSelector` function like I mentioned in the code `const tickets = useSelector(sorterSelector)`, I got mistake: `TypeError: Cannot read property 'map' of undefined`. Tickets are not returned from the state, but state is empty. That means that `fetchData` function didn't work. What am I doing wrong here? How to use it properly? UPD: this doesn't work too `const tickets = useSelector((state) => sorterSelector(state))`
2021/01/19
['https://Stackoverflow.com/questions/65788251', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13115642/']
This is a nice example of when to actually use [arrow functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions) in favor of regular functions! Because regular functions—like in your code—establish their own `this` scope you no longer have access to the `this` scope you are interested in, namely the scope of your surroungding class. Many D3 methods are called with `this` set to the current DOM element: > > with *this* as the current DOM element (*nodes*[*i*]) > > > To be able to use your class instance's methods by referring to them using `this` you can just use an arrow function which does not come with its own scope but captures the scope of its surrounding context, i.e. your class/instance. Your methods should therefore look like this: ``` .attr('x', d => this.x(d.dayNumber)) ```
The `this` has a type of SVGRectElement because it is inside a regular anonymous function. In D3, methods for manipulating nodes replace the `this` context with the own DOM Element that is being manipulated, in your case a `<rect>`. The `<rect>` nodes don't have x or y methods, hence the type error. Replacing the anonymous functions with arrow functions [preserves the `this` from the outside](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions): ```js .attr('x', (d: HeatmapData) => { return this.x(d.dayNumber) }) .attr('y', (d: HeatmapData) => { return this.y(d.timeOfDay) }) ``` Now, the `this` inside the function is the same `this` from the outside, which in your case is the class that contain svg, x, xAxis, y and yAxis.
34,602,460
I'm teaching myself JavaScript and I'm trying to make a random background color appear when a button is clicked. Below you can find my code: HTML Code ``` <!DOCTYPE html> <html> <head> <title>Day 4</title> <link rel="stylesheet" type="text/css" href="css/foundation.min.css"> <link rel="stylesheet" type="text/css" href="css/style.css"> </head> <body id="background"> <div class="row"> <div class="columns small-12"> <ul class="menu"> <li><a href="index.html">Home</a></li> <li><a href="http://carter3689.tumblr.com/">Blog</a></li> </ul> </div> <div class="row"> <div class="columns small-12"> <div class="container center"> <button id="button"class="button center" onclick="randomColors">Click Here for Color of the Day</button> </div> </div> </div> </div> <script src="js/random-color.js"></script> </body> </html> ``` Here is my CSS Code: ``` .background{ background-color: #ECECEA; } .text-padding{ padding: 50px; } input{ width:250px !important; padding-left: 50px; } .inline{ list-style-type: none; } .container{ margin-left: 500px; } ``` And lastly, my JavaScript Code. This is where I'm having most of my trouble to be honest. ``` function randomcolor(){ document.getElementById('background').style.color =randomColors(); } function randomColors(){ return '#' + Math.floor(Math.random() * 16777215).toString(16); console.log("I'm working now") } ``` Any help you can provide would be extremely helpful as this is all a learning experience for me. Thanks in advance!
2016/01/05
['https://Stackoverflow.com/questions/34602460', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5069799/']
It seems like its basically already been answered by others, but there is nothing wrong with repetition. 1. You are calling `randomColors()` instead of `randomcolor()`. 2. You really shouldn't be using getElementById on the body tag. You can just use document.body to get the body. 3. You need to use `style.background` or `style.backgroundColor` to get the background color instead of text color. 4. You should be including your js scripts in `<head>` instead of near the bottom of your html document to ensure they are loaded before functions from them are called.
First, you're using the wrong function in your callback. Use `onclick='randomcolor()'`. Make sure your JS functions are defined in the `<head>` of the document. Finally, `document.getElementById('background').style.color` is the text color, not the background color. Use `document.getElementById('background').style.background = randomColors();`
34,602,460
I'm teaching myself JavaScript and I'm trying to make a random background color appear when a button is clicked. Below you can find my code: HTML Code ``` <!DOCTYPE html> <html> <head> <title>Day 4</title> <link rel="stylesheet" type="text/css" href="css/foundation.min.css"> <link rel="stylesheet" type="text/css" href="css/style.css"> </head> <body id="background"> <div class="row"> <div class="columns small-12"> <ul class="menu"> <li><a href="index.html">Home</a></li> <li><a href="http://carter3689.tumblr.com/">Blog</a></li> </ul> </div> <div class="row"> <div class="columns small-12"> <div class="container center"> <button id="button"class="button center" onclick="randomColors">Click Here for Color of the Day</button> </div> </div> </div> </div> <script src="js/random-color.js"></script> </body> </html> ``` Here is my CSS Code: ``` .background{ background-color: #ECECEA; } .text-padding{ padding: 50px; } input{ width:250px !important; padding-left: 50px; } .inline{ list-style-type: none; } .container{ margin-left: 500px; } ``` And lastly, my JavaScript Code. This is where I'm having most of my trouble to be honest. ``` function randomcolor(){ document.getElementById('background').style.color =randomColors(); } function randomColors(){ return '#' + Math.floor(Math.random() * 16777215).toString(16); console.log("I'm working now") } ``` Any help you can provide would be extremely helpful as this is all a learning experience for me. Thanks in advance!
2016/01/05
['https://Stackoverflow.com/questions/34602460', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5069799/']
What happened is when your html loads, the onclick handler is undefined because your script hasn't been loaded as yet.. .hence you will get an an error in your console.log stating that your function is undefined. Move script tag above your onclick handler. **Snippet using .onclick** ```js document.getElementById('button').onclick=randomcolor; function randomcolor(){ document.getElementById('background').style.backgroundColor =randomColors(); } function randomColors(){ var result='#' + Math.floor(Math.random() * 16777215).toString(16); console.log(result); return result; } ``` ```css .background{ background-color: #ECECEA; } .text-padding{ padding: 50px; } input{ width:250px !important; padding-left: 50px; } .inline{ list-style-type: none; } .container{ margin-left: 500px; } ``` ```html <title>Day 4</title> <link rel="stylesheet" type="text/css" href="css/foundation.min.css"> <link rel="stylesheet" type="text/css" href="css/style.css"> <body id="background"> <div class="row"> <div class="columns small-12"> <ul class="menu"> <li><a href="index.html">Home</a></li> <li><a href="http://carter3689.tumblr.com/">Blog</a></li> </ul> </div> <div class="row"> <div class="columns small-12"> <div class="container center"> <button id="button"class="button center">Click Here for Color of the Day</button> </div> </div> </div> </div> </html> ``` **Snippet using `addEventListener`** ```js document.getElementById('button').addEventListener('click',randomcolor,false) function randomcolor(){ document.getElementById('background').style.backgroundColor =randomColors(); } function randomColors(){ var result='#' + Math.floor(Math.random() * 16777215).toString(16); console.log(result); return result; } ``` ```css .background{ background-color: #ECECEA; } .text-padding{ padding: 50px; } input{ width:250px !important; padding-left: 50px; } .inline{ list-style-type: none; } .container{ margin-left: 500px; } ``` ```html <title>Day 4</title> <link rel="stylesheet" type="text/css" href="css/foundation.min.css"> <link rel="stylesheet" type="text/css" href="css/style.css"> <body id="background"> <div class="row"> <div class="columns small-12"> <ul class="menu"> <li><a href="index.html">Home</a></li> <li><a href="http://carter3689.tumblr.com/">Blog</a></li> </ul> </div> <div class="row"> <div class="columns small-12"> <div class="container center"> <button id="button"class="button center">Click Here for Color of the Day</button> </div> </div> </div> </div> </html> ```
First, you're using the wrong function in your callback. Use `onclick='randomcolor()'`. Make sure your JS functions are defined in the `<head>` of the document. Finally, `document.getElementById('background').style.color` is the text color, not the background color. Use `document.getElementById('background').style.background = randomColors();`
34,602,460
I'm teaching myself JavaScript and I'm trying to make a random background color appear when a button is clicked. Below you can find my code: HTML Code ``` <!DOCTYPE html> <html> <head> <title>Day 4</title> <link rel="stylesheet" type="text/css" href="css/foundation.min.css"> <link rel="stylesheet" type="text/css" href="css/style.css"> </head> <body id="background"> <div class="row"> <div class="columns small-12"> <ul class="menu"> <li><a href="index.html">Home</a></li> <li><a href="http://carter3689.tumblr.com/">Blog</a></li> </ul> </div> <div class="row"> <div class="columns small-12"> <div class="container center"> <button id="button"class="button center" onclick="randomColors">Click Here for Color of the Day</button> </div> </div> </div> </div> <script src="js/random-color.js"></script> </body> </html> ``` Here is my CSS Code: ``` .background{ background-color: #ECECEA; } .text-padding{ padding: 50px; } input{ width:250px !important; padding-left: 50px; } .inline{ list-style-type: none; } .container{ margin-left: 500px; } ``` And lastly, my JavaScript Code. This is where I'm having most of my trouble to be honest. ``` function randomcolor(){ document.getElementById('background').style.color =randomColors(); } function randomColors(){ return '#' + Math.floor(Math.random() * 16777215).toString(16); console.log("I'm working now") } ``` Any help you can provide would be extremely helpful as this is all a learning experience for me. Thanks in advance!
2016/01/05
['https://Stackoverflow.com/questions/34602460', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5069799/']
It seems like its basically already been answered by others, but there is nothing wrong with repetition. 1. You are calling `randomColors()` instead of `randomcolor()`. 2. You really shouldn't be using getElementById on the body tag. You can just use document.body to get the body. 3. You need to use `style.background` or `style.backgroundColor` to get the background color instead of text color. 4. You should be including your js scripts in `<head>` instead of near the bottom of your html document to ensure they are loaded before functions from them are called.
What happened is when your html loads, the onclick handler is undefined because your script hasn't been loaded as yet.. .hence you will get an an error in your console.log stating that your function is undefined. Move script tag above your onclick handler. **Snippet using .onclick** ```js document.getElementById('button').onclick=randomcolor; function randomcolor(){ document.getElementById('background').style.backgroundColor =randomColors(); } function randomColors(){ var result='#' + Math.floor(Math.random() * 16777215).toString(16); console.log(result); return result; } ``` ```css .background{ background-color: #ECECEA; } .text-padding{ padding: 50px; } input{ width:250px !important; padding-left: 50px; } .inline{ list-style-type: none; } .container{ margin-left: 500px; } ``` ```html <title>Day 4</title> <link rel="stylesheet" type="text/css" href="css/foundation.min.css"> <link rel="stylesheet" type="text/css" href="css/style.css"> <body id="background"> <div class="row"> <div class="columns small-12"> <ul class="menu"> <li><a href="index.html">Home</a></li> <li><a href="http://carter3689.tumblr.com/">Blog</a></li> </ul> </div> <div class="row"> <div class="columns small-12"> <div class="container center"> <button id="button"class="button center">Click Here for Color of the Day</button> </div> </div> </div> </div> </html> ``` **Snippet using `addEventListener`** ```js document.getElementById('button').addEventListener('click',randomcolor,false) function randomcolor(){ document.getElementById('background').style.backgroundColor =randomColors(); } function randomColors(){ var result='#' + Math.floor(Math.random() * 16777215).toString(16); console.log(result); return result; } ``` ```css .background{ background-color: #ECECEA; } .text-padding{ padding: 50px; } input{ width:250px !important; padding-left: 50px; } .inline{ list-style-type: none; } .container{ margin-left: 500px; } ``` ```html <title>Day 4</title> <link rel="stylesheet" type="text/css" href="css/foundation.min.css"> <link rel="stylesheet" type="text/css" href="css/style.css"> <body id="background"> <div class="row"> <div class="columns small-12"> <ul class="menu"> <li><a href="index.html">Home</a></li> <li><a href="http://carter3689.tumblr.com/">Blog</a></li> </ul> </div> <div class="row"> <div class="columns small-12"> <div class="container center"> <button id="button"class="button center">Click Here for Color of the Day</button> </div> </div> </div> </div> </html> ```
19,363,489
I want to set all C-x command to be M-x so I can keep my thumb in my left hand on ALT button. But what is the function which C-h and C-x run? Thanks.
2013/10/14
['https://Stackoverflow.com/questions/19363489', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2767553/']
Control-X is bound to the function `Control-X-prefix`, which is a keymap (a table associating keystrokes with commands). So to set `\M-x` to work like `\C-x`, just do the following: ``` (define-key global-map "\M-x" 'Control-X-prefix) ``` All that said, instead of rebinding emacs I would recommend that you look into remapping your keyboard: Many window managers (X11, OS X and many Windows set-ups included) give you ways to customize various modifier keys (e.g., turning Left-Alt into another Control.) Look into them, you may find a set up you like.
Use `C-x C-h` to see the `C-x` bindings. Load [`help-fns+.el`](http://www.emacswiki.org/emacs/download/help-fns%2b.el) and use `C-h M-k` with `ctl-x-map` and `help-map` to see all bindings for `C-x` and `C-h`.
2,840,303
For every open set $ G \subset \mathbb{R}^n$ and $ \epsilon > 0 $ there exist a finite collection of compact intervals $\{ I\_j \quad|\quad j=1,2,...m\}$ in $ \mathbb{R}^n $ such that $\cup^{j=1}\_{m}I\_j \subset G $ and $ m(G\backslash \cup^{j=1}\_{m}I\_j)< \epsilon $ where m denotes lebesgue measure. NOTE : compact interval in $\mathbb{R}^n$ is $[a\_1,b\_1]\times[a\_2,b\_2]\times...\times[a\_n, b\_n]$ where $[a\_i,b\_i] $ are real closed intervals for each i. **EDIT**: $m(G)$ is finite. sorry, I forget to write.
2018/07/04
['https://math.stackexchange.com/questions/2840303', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/402639/']
This follows from the fact that every open set in $\mathbb{R}^n$ is a countable disjoint union of compact intervals. Indeed, if $G = \cup\_{k=1}^\infty I\_k$, then since $\sum\_k m(I\_k) = m(G) < \infty$, we may take $K$ so that $\sum\_{k > K} m(I\_k) < \epsilon$. Then $\cup\_{k=1}^K I\_k$ does the trick. See page 7 for the proof of the first fact I stated <http://assets.press.princeton.edu/chapters/s8008.pdf>
This is false. For example take $G= \mathbb R^n$.
19,455,400
I have a shell script that runs on AIX 7.1 and the purpose of it is to archive a bunch of different directories using CPIO. We pass in the directories to be archived to CPIO from a flat file called synclive\_cpio.list. Here is a snippet of the script.. ``` #!/bin/ksh CPIO_LIST="$BASE/synclive_cpio.list" DUMP_DIR=/usr4/sync_stage LOG_FILE=/tmp/synclive.log run_cpio() { while LINE=: read -r f1 f2 do sleep 1 cd $f1 echo "Sending CPIO processing for $f1 to background." >> $LOG_FILE time find . -print | cpio -o | gzip > $DUMP_DIR/$f2.cpio.gz & done <"$CPIO_LIST" wait } ``` Here is what we have in the synclive.cpio.list file... ``` /usr2/devel_config usr2_devel_config /usr/local usr_local /usr1/config usr1_config /usr1/releases usr1_releases ``` When the CPIO is running, it will archive everything in the passed directory.. what I would like to do is try to exclude a few file extension types such as \*.log and \*.tmp as we don't need to archive those. Any idea how to change run\_cpio() block to support this? Thanks.
2013/10/18
['https://Stackoverflow.com/questions/19455400', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']
Exclude them in the `find` command ``` time find . ! \( -name '*.log' -o -name '*.tmp' \) -print | cpio -o | gzip > $DUMP_DIR/$f2.cpio.gz & ``` You can keep adding `-o *.suffix` to the list.
Another method is to use egrep -v in the pipeline. I believe that would be a teeny tiny bit more efficient. ``` time find . -print | egrep -v '\.(tmp|log)$' | cpio -o | gz ``` To me, it is also easier to read and modify if the list gets really long.
20,469,861
in my application I have a TableView that displays all the posts made by users of the app ... I noticed that the date on social networks of the post is written based on the current date, for example: The post was made ​​2 hours ago In your opinion what is the best method to accomplish this? There are no tutorials or guides where I can figure out how to get this? Thank you all for future councils
2013/12/09
['https://Stackoverflow.com/questions/20469861', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2773233/']
Once you have NSDate of some event and your current date you can use NSCalendar to calculate the difference between them in calendar units you want. And then you can generate your user-readable string based on that (e.g. you may want to use only the largest non-zero date component): ``` NSCalendar *calendar = [NSCalendar currentCalendar]; unsigned int unitFlags = NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit; NSDateComponents *components = [calendar components:unitFlags fromDate:startDate toDate:endDate options:0]; if ([components month] > 0) { // some months ago } else if if ([components day] > 0) { // some days ago } etc ```
Basically, create a timestamp using whenever a post is created. Then compare that to the current time.
20,469,861
in my application I have a TableView that displays all the posts made by users of the app ... I noticed that the date on social networks of the post is written based on the current date, for example: The post was made ​​2 hours ago In your opinion what is the best method to accomplish this? There are no tutorials or guides where I can figure out how to get this? Thank you all for future councils
2013/12/09
['https://Stackoverflow.com/questions/20469861', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2773233/']
This problem has already been solved for you; use the excellent [FormatterKit](https://github.com/mattt/FormatterKit#ttttimeintervalformatter), specifically the time interval formatter component of it.
Basically, create a timestamp using whenever a post is created. Then compare that to the current time.
14,482,707
I am needing help forming a jquery selector to return elements which are missing a particular child element. Given the following HTML fragment: ``` <div id="rack1" class="rack"> <span id="rackunit1" class="rackspace"> <span id="component1">BoxA</span> <span id="label1">Space A</span> </span> <span id="rackunit2" class="rackspace"> <span id="label2">Space B</span> </span> <span id="rackunit3" class="rackspace"> <span id="component2">BoxA</span> <span id="label3">Space C</span> </span> </div> <div id="rack2" class="rack"> <span id="rackunit4" class="rackspace"> <span id="component3">BoxC</span> <span id="label4">Space D</span> </span> <span id="rackunit5" class="rackspace"> <span id="label5">Space E</span> </span> <span id="rackunit6" class="rackspace"> <span id="component4">BoxD</span> <span id="label6">Space F</span> </span> </div> ``` Find for me the rackunit spans with NO component span. Thus far I have: $(".rack .rackspace") to get me all of the rackunit spans, not sure how to either exclude those with a component span or select only those without one...
2013/01/23
['https://Stackoverflow.com/questions/14482707', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/681009/']
I guess the following should work: ``` $(".rack .rackspace:not(:has(span[id^=component]))"). ... ``` **DEMO:** <http://jsfiddle.net/WbCzj/>
You could use [`.filter()`](http://api.jquery.com/filter/): ``` $('.rack .rackspace').filter(function() { return $(this).find('span[id^="component"]').length === 0; }); ```
2,915,329
Does anyone know if there is a way to "transform" specific sections of values instead of replacing the whole value or an attribute? For example, I've got several appSettings entries that specify the URLs for different webservices. These entries are slightly different in the dev environment than the production environment. Some are less trivial than others ``` <!-- DEV ENTRY --> <appSettings> <add key="serviceName1_WebsService_Url" value="http://wsServiceName1.dev.example.com/v1.2.3.4/entryPoint.asmx" /> <add key="serviceName2_WebsService_Url" value="http://ma1-lab.lab1.example.com/v1.2.3.4/entryPoint.asmx" /> </appSettings> <!-- PROD ENTRY --> <appSettings> <add key="serviceName1_WebsService_Url" value="http://wsServiceName1.prod.example.com/v1.2.3.4/entryPoint.asmx" /> <add key="serviceName2_WebsService_Url" value="http://ws.ServiceName2.example.com/v1.2.3.4/entryPoint.asmx" /> </appSettings> ``` Notice that on the fist entry, the only difference is **".dev" from ".prod".** On the second entry, the subdomain is different: **"ma1-lab.lab1"** from **"ws.ServiceName2"** So far, I know I can do something like this in the `Web.Release.Config`: ``` <add xdt:Locator="Match(key)" xdt:Transform="SetAttributes(value)" key="serviceName1_WebsService_Url" value="http://wsServiceName1.prod.example.com/v1.2.3.4/entryPoint.asmx" /> <add xdt:Locator="Match(key)" xdt:Transform="SetAttributes(value)" key="serviceName2_WebsService_Url" value="http://ws.ServiceName2.example.com/v1.2.3.4/entryPoint.asmx" /> ``` However, every time the Version for that webservice is updated, I would have to update the `Web.Release.Config` as well, which defeats the purpose of simplfying my `web.config` updates. I know I could also split that URL into different sections and update them independently, but I rather have it all in one key. I've looked through the available `web.config` Transforms but nothings seems to be geared towars what I am trying to accomplish. These are the websites I am using as a reference: [Vishal Joshi's blog](http://vishaljoshi.blogspot.com/2009/03/web-deployment-webconfig-transformation_23.html), [MSDN Help](http://msdn.microsoft.com/en-us/library/dd465326(VS.100).aspx), and [Channel9 video](http://channel9.msdn.com/shows/10-4/10-4-Episode-10-Making-Web-Deployment-Easier/)
2010/05/26
['https://Stackoverflow.com/questions/2915329', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/80268/']
As a matter of fact you can do this, but it is not as easy as you might think. You can create your own config transformation. I have just written a very detailed blog post at <http://sedodream.com/2010/09/09/ExtendingXMLWebconfigConfigTransformation.aspx> regarding this. But here are the hightlights: * Create Class Library project * Reference Web.Publishing.Tasks.dll *(under %Program Files (x86)%MSBuild\Microsoft\VisualStudio\v10.0\Web folder)* * Extend Microsoft.Web.Publishing.Tasks.Transform class * Implement the Apply() method * Place the assembly in a well known location * Use xdt:Import to make the new transform available * Use transform **Here is the class I created to do this replace** ``` namespace CustomTransformType { using System; using System.Text.RegularExpressions; using System.Xml; using Microsoft.Web.Publishing.Tasks; public class AttributeRegexReplace : Transform { private string pattern; private string replacement; private string attributeName; protected string AttributeName { get { if (this.attributeName == null) { this.attributeName = this.GetArgumentValue("Attribute"); } return this.attributeName; } } protected string Pattern { get { if (this.pattern == null) { this.pattern = this.GetArgumentValue("Pattern"); } return pattern; } } protected string Replacement { get { if (this.replacement == null) { this.replacement = this.GetArgumentValue("Replacement"); } return replacement; } } protected string GetArgumentValue(string name) { // this extracts a value from the arguments provided if (string.IsNullOrWhiteSpace(name)) { throw new ArgumentNullException("name"); } string result = null; if (this.Arguments != null && this.Arguments.Count > 0) { foreach (string arg in this.Arguments) { if (!string.IsNullOrWhiteSpace(arg)) { string trimmedArg = arg.Trim(); if (trimmedArg.ToUpperInvariant().StartsWith(name.ToUpperInvariant())) { int start = arg.IndexOf('\''); int last = arg.LastIndexOf('\''); if (start <= 0 || last <= 0 || last <= 0) { throw new ArgumentException("Expected two ['] characters"); } string value = trimmedArg.Substring(start, last - start); if (value != null) { // remove any leading or trailing ' value = value.Trim().TrimStart('\'').TrimStart('\''); } result = value; } } } } return result; } protected override void Apply() { foreach (XmlAttribute att in this.TargetNode.Attributes) { if (string.Compare(att.Name, this.AttributeName, StringComparison.InvariantCultureIgnoreCase) == 0) { // get current value, perform the Regex att.Value = Regex.Replace(att.Value, this.Pattern, this.Replacement); } } } } } ``` **Here is web.config** ``` <?xml version="1.0"?> <configuration> <appSettings> <add key="one" value="one"/> <add key="two" value="partial-replace-here-end"/> <add key="three" value="three here"/> </appSettings> </configuration> ``` Here is my config transform file ``` <?xml version="1.0"?> <configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform"> <xdt:Import path="C:\Program Files (x86)\MSBuild\Custom\CustomTransformType.dll" namespace="CustomTransformType" /> <appSettings> <add key="one" value="one-replaced" xdt:Transform="Replace" xdt:Locator="Match(key)" /> <add key="two" value="two-replaced" xdt:Transform="AttributeRegexReplace(Attribute='value', Pattern='here',Replacement='REPLACED')" xdt:Locator="Match(key)"/> </appSettings> </configuration> ``` **Here is the result after transformation** ``` <?xml version="1.0"?> <configuration> <appSettings> <add key="one" value="one-replaced"/> <add key="two" value="partial-replace-REPLACED-end"/> <add key="three" value="three here"/> </appSettings> </configuration> ```
Just as an update, if you're using Visual Studio 2013, you should reference %Program Files (x86)%MSBuild\Microsoft\VisualStudio\v12.0\Web\Microsoft.Web.XmlTransform.dll instead.
67,850,085
basically my code stops working after my first input where i chose one of the following cases, but it should keep on workin until i choose case x. can anybody help and tell me where the issue is? ``` #include <stdio.h> #include <math.h> #include <stdlib.h> #include <time.h> int main(){ char choice; int a,b,c,s; int F; printf("Objekttyp wahlen:\n (R) Rechteck\n (E) Ellipse\n (D) Dreieck\n (x) Exit\n"); choice = getchar(); while(choice == '\n'){ choice = getchar(); } switch(choice){ case 'R': printf("Seitenlaengen a,b des Rechtecks: "); scanf("%d%d" &&a, &b); F = a * b; printf("F = %d", F); break; case 'E': printf("Halbachsen der Ellipse: "); scanf("%d%d" &&a, &b); F = 3.14 * a * b; printf("F = %d", F); break; case 'D': printf("Seitenlaengen a,b,c des Dreiecks: "); scanf("%d%d%d" &&a,b,c); printf("F = %d", F); break; case 'x': exit(0); break; default : printf("Ungueltige Eingabe!\n\n"); }while(choice != 'x'); } ```
2021/06/05
['https://Stackoverflow.com/questions/67850085', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/16137524/']
use a do-while loop, instead of switch-while because the switch while loop doesn't exist, at least not in c++ or c. ``` #include <stdio.h> #include <math.h> #include <stdlib.h> #include <time.h> int main(){ char choice; int a,b,c,s; int F; do{ printf("Objekttyp wahlen:\n (R) Rechteck\n (E) Ellipse\n (D) Dreieck\n (x) Exit\n"); choice = getchar(); while(choice == '\n'){ choice = getchar(); } switch(choice){ case 'R': printf("Seitenlaengen a,b des Rechtecks: "); scanf("%d%d" &&a, &b); F = a * b; printf("F = %d", F); break; case 'E': printf("Halbachsen der Ellipse: "); scanf("%d%d" &&a, &b); F = 3.14 * a * b; printf("F = %d", F); break; case 'D': printf("Seitenlaengen a,b,c des Dreiecks: "); scanf("%d%d%d" &&a,b,c); printf("F = %d", F); break; case 'x': exit(0); break; default : printf("Ungueltige Eingabe!\n\n"); } }while(choice != 'x'); } ```
**Beautiful code format:** ``` #include <stdio.h> #include <math.h> #include <stdlib.h> #include <time.h> int main(){ char choice; int a,b,c,s; int F; do{ printf("Objekttyp wahlen:\n (R) Rechteck\n (E) Ellipse\n (D) Dreieck\n (x) Exit\n"); choice = getchar(); while(choice == '\n'){ choice = getchar(); } switch(choice){ case 'R': printf("Seitenlaengen a,b des Rechtecks: "); scanf("%d%d", &a, &b); F = a * b; printf("F = %d\n", F); break; case 'E': printf("Halbachsen der Ellipse: "); scanf("%d%d", &a, &b); F = 3.14 * a * b; printf("F = %d\n", F); break; case 'D': printf("Seitenlaengen a,b,c des Dreiecks: "); scanf("%d%d%d", &a, &b, &c); printf("F = %d\n", F); break; case 'x': exit(0); break; default : printf("Ungueltige Eingabe!\n\n"); } }while(choice != 'x'); } ``` **there is other problem:** change ``` scanf("%d%d" &&a, &b); ``` to ``` scanf("%d%d", &a, &b); ```
67,850,085
basically my code stops working after my first input where i chose one of the following cases, but it should keep on workin until i choose case x. can anybody help and tell me where the issue is? ``` #include <stdio.h> #include <math.h> #include <stdlib.h> #include <time.h> int main(){ char choice; int a,b,c,s; int F; printf("Objekttyp wahlen:\n (R) Rechteck\n (E) Ellipse\n (D) Dreieck\n (x) Exit\n"); choice = getchar(); while(choice == '\n'){ choice = getchar(); } switch(choice){ case 'R': printf("Seitenlaengen a,b des Rechtecks: "); scanf("%d%d" &&a, &b); F = a * b; printf("F = %d", F); break; case 'E': printf("Halbachsen der Ellipse: "); scanf("%d%d" &&a, &b); F = 3.14 * a * b; printf("F = %d", F); break; case 'D': printf("Seitenlaengen a,b,c des Dreiecks: "); scanf("%d%d%d" &&a,b,c); printf("F = %d", F); break; case 'x': exit(0); break; default : printf("Ungueltige Eingabe!\n\n"); }while(choice != 'x'); } ```
2021/06/05
['https://Stackoverflow.com/questions/67850085', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/16137524/']
use a do-while loop, instead of switch-while because the switch while loop doesn't exist, at least not in c++ or c. ``` #include <stdio.h> #include <math.h> #include <stdlib.h> #include <time.h> int main(){ char choice; int a,b,c,s; int F; do{ printf("Objekttyp wahlen:\n (R) Rechteck\n (E) Ellipse\n (D) Dreieck\n (x) Exit\n"); choice = getchar(); while(choice == '\n'){ choice = getchar(); } switch(choice){ case 'R': printf("Seitenlaengen a,b des Rechtecks: "); scanf("%d%d" &&a, &b); F = a * b; printf("F = %d", F); break; case 'E': printf("Halbachsen der Ellipse: "); scanf("%d%d" &&a, &b); F = 3.14 * a * b; printf("F = %d", F); break; case 'D': printf("Seitenlaengen a,b,c des Dreiecks: "); scanf("%d%d%d" &&a,b,c); printf("F = %d", F); break; case 'x': exit(0); break; default : printf("Ungueltige Eingabe!\n\n"); } }while(choice != 'x'); } ```
By the way: If you want to output the German umlauts in the console (for example `"Ungültige Eingabe!\n\n"`), you can write: `printf("Ung\x81 \bltige Eingabe!\n\n");` The console is using the [codepage 850](https://de.wikipedia.org/wiki/Codepage_850)... `printf("Seitenl\x84 \bngen a,b des Rechtecks: ");` You just have to put a space after \x81 so that the next character is not interpreted with the previos characters. You can undo this extra space with \b.
67,850,085
basically my code stops working after my first input where i chose one of the following cases, but it should keep on workin until i choose case x. can anybody help and tell me where the issue is? ``` #include <stdio.h> #include <math.h> #include <stdlib.h> #include <time.h> int main(){ char choice; int a,b,c,s; int F; printf("Objekttyp wahlen:\n (R) Rechteck\n (E) Ellipse\n (D) Dreieck\n (x) Exit\n"); choice = getchar(); while(choice == '\n'){ choice = getchar(); } switch(choice){ case 'R': printf("Seitenlaengen a,b des Rechtecks: "); scanf("%d%d" &&a, &b); F = a * b; printf("F = %d", F); break; case 'E': printf("Halbachsen der Ellipse: "); scanf("%d%d" &&a, &b); F = 3.14 * a * b; printf("F = %d", F); break; case 'D': printf("Seitenlaengen a,b,c des Dreiecks: "); scanf("%d%d%d" &&a,b,c); printf("F = %d", F); break; case 'x': exit(0); break; default : printf("Ungueltige Eingabe!\n\n"); }while(choice != 'x'); } ```
2021/06/05
['https://Stackoverflow.com/questions/67850085', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/16137524/']
By the way: If you want to output the German umlauts in the console (for example `"Ungültige Eingabe!\n\n"`), you can write: `printf("Ung\x81 \bltige Eingabe!\n\n");` The console is using the [codepage 850](https://de.wikipedia.org/wiki/Codepage_850)... `printf("Seitenl\x84 \bngen a,b des Rechtecks: ");` You just have to put a space after \x81 so that the next character is not interpreted with the previos characters. You can undo this extra space with \b.
**Beautiful code format:** ``` #include <stdio.h> #include <math.h> #include <stdlib.h> #include <time.h> int main(){ char choice; int a,b,c,s; int F; do{ printf("Objekttyp wahlen:\n (R) Rechteck\n (E) Ellipse\n (D) Dreieck\n (x) Exit\n"); choice = getchar(); while(choice == '\n'){ choice = getchar(); } switch(choice){ case 'R': printf("Seitenlaengen a,b des Rechtecks: "); scanf("%d%d", &a, &b); F = a * b; printf("F = %d\n", F); break; case 'E': printf("Halbachsen der Ellipse: "); scanf("%d%d", &a, &b); F = 3.14 * a * b; printf("F = %d\n", F); break; case 'D': printf("Seitenlaengen a,b,c des Dreiecks: "); scanf("%d%d%d", &a, &b, &c); printf("F = %d\n", F); break; case 'x': exit(0); break; default : printf("Ungueltige Eingabe!\n\n"); } }while(choice != 'x'); } ``` **there is other problem:** change ``` scanf("%d%d" &&a, &b); ``` to ``` scanf("%d%d", &a, &b); ```
11,161,920
I'm writing an iPad app that uses an Audio Queue. I'm running into an error resulting from calling AudioSessionInitialize more than once. I'm trying to find a way to test whether or not AudioSessionInitialize has already been called to avoid this, but so far no luck. Does anyone have a way to do this? Thanks in advanced.
2012/06/22
['https://Stackoverflow.com/questions/11161920', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1475624/']
You could just wrap it in a dispatch\_once block as per: ``` static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ AudioSessionInitialize(NULL, NULL, InterruptionListenerCallback, clientData); // Perform other setup here... }); ``` although you may find it easier in the long term to use implicit initialisation of your session and handle events through a delegate, as discussed here: [Audio Session Programming Guide - Initializing Your Audio Session](http://developer.apple.com/library/ios/#documentation/Audio/Conceptual/AudioSessionProgrammingGuide/Configuration/Configuration.html#//apple_ref/doc/uid/TP40007875-CH3-SW4)
Since the audio session is currently a global property, you could set a C global variable flag when initializing, and then check this global variable before attempting to (re)initialize. However a dispatch\_once block would be less likely to incur race condition bugs if your app is multi-threaded.
130,190
Here is my problem Let $H(x)=\Phi(\frac{Ax+b}{\sqrt{2}})$ where $A$, $b$ are some non-negative constant and $\Phi$ is the CDf of a standard normal distribution. I want to find $$\int x \, dH(x)$$ I thought maybe integration by parts which yields: $$x H(x)-\int H(x) \, dx$$ And now I'm not sure how to proceed or if it's possible to take the integral of a CDf
2012/04/10
['https://math.stackexchange.com/questions/130190', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/28789/']
\begin{eqnarray} \lim\_{x\to\infty}\left(1+\frac{f(x)}x\right)^x &=&\lim\_{x\to\infty}\exp \left(x\log \left(1+\frac{f(x)}x \right) \right)=\exp \left(\lim\_{x\to\infty}x\log \left(1+\frac{f(x)}x\right)\right)\\ \ \\ &=&\exp \left(\lim\_{x\to\infty}x \left(\frac{f(x)}x+o\left(\frac1{x^2}\right)\right)\right) =\exp \left(\lim\_{x\to\infty}f(x)+o\left(\frac1{x}\right)\right)\\ \ \\ &=&\exp \left(\lim\_{x\to\infty}f(x)\right). \end{eqnarray} The limit exchange in the second equality is justified by the fact that the exponential is continuous and that the expression inside converges.
Since there exist $\lim\limits\_{x\to 0}f(x)=l$ we have that $f$ is bounded in the neighborhood of $\infty$. So $\lim\limits\_{x\to\infty}\frac{f(x)}{x}=0$ and we can write $$ \lim\limits\_{x\to\infty}\left(1+\frac{f(x)}{x}\right)^x= \lim\limits\_{x\to\infty}\left(\left(1+\frac{f(x)}{x}\right)^{\frac{x}{f(x)}}\right)^{f(x)}= \lim\limits\_{x\to\infty}\left(\left(1+\frac{f(x)}{x}\right)^{\frac{x}{f(x)}}\right)^{\lim\limits\_{x\to\infty}f(x)}= e^l $$
361,282
During review of an article I found an erroneous sentence: > > The known predators of the plant are sheep, donkeys ... > > > I am an engineer, with not so much knowledge in ecology. Based on my earlier studies I suggested to change *predators* to *consumers*. I checked it with a search on the net. Surprisingly I found too few hits in my search. *Consumers of a plant* is acceptable? Can you recommend alternatives?
2016/12/01
['https://english.stackexchange.com/questions/361282', 'https://english.stackexchange.com', 'https://english.stackexchange.com/users/162691/']
According to the wikibook [Predation and Herbivory](https://en.wikibooks.org/wiki/Ecology/Predation_and_Herbivory): > > ecologically, predation is defined as any interaction between two organisms that results in a flow of energy between them. This definition is applicable to both plants and animals. There are four commonly recognized types of predation: (1) carnivory, (2) herbivory, (3) parasitism, and (4) mutualism. > > > So, this reference, in ecological situations, clearly accepts an animal eating a plant as a "predator" of that plant. --- However, in more general non-technical contexts, dictionary.reference.com defines a [predator](http://www.dictionary.com/browse/predator?s=t) as (depending on which of its sources you use) either: > > any organism that exists by preying upon other organisms > > > or > > any carnivorous animal > > > The second definition would preclude its usage for eating plants. The first hinges upon the definition of "preying". Using dictionary.reference.com again, [prey](http://www.dictionary.com/browse/prey) as a verb is: > > to seize and devour prey > > > where that prey (as a noun) is: > > an animal hunted or seized for food > > > I would therefore suggest that unless you are talking to a technical ecological (or possibly biological?) crowd, **predator** would not be an appropriate term. --- Possible terms (thanks to Hotlicks for the first one, and typing it into [thesaurus.com](http://www.thesaurus.com/browse/eater?s=t) gave the other two): > > **eater**: from the verb to [eat](http://www.dictionary.com/browse/eater?s=t): to take into the mouth and swallow for nourishment > > > **devourer**: from the verb to [devour](http://www.dictionary.com/browse/devourer?s=t): to swallow or eat up hungrily, voraciously, or ravenously > > > **[consumer](http://www.dictionary.com/browse/consumer?s=t)**: an organism, usually an animal, that feeds on plants or other animals. > > >
Most of the online definitions of 'predator' such as [the ODO](https://en.oxforddictionaries.com/definition/predator), [the Cambridge](http://dictionary.cambridge.org/dictionary/english/predator) and [the Macmillan](http://www.macmillandictionary.com/dictionary/british/predator) define 'predator' as an animal which eats other animals so it would seem that to describe a herbivore as a predator of plants is not really valid. Not only that but there is a difference between predation on animals and the majority of grazing because predation involves killing, or at least seriously and permanently injuring, the target: whereas most grazing involves eating only part of the plant which, in most cases, regenerates. Creatures like us who eat the entire root, or the whole, of some plants like potatoes and carrots are only a subset of herbivores and omnivores.
84,640
I found this sentence in [an article about japanese swords](https://newsinslowjapanese.com/2020/03/24/nisj-354-japanese-swords/) > > 日本刀と他の刀との違いは、どれだけ波紋と鉄が美しい**か**にこだわっている**か**です > > > The translation is > > The difference between japanese swords and other swords **is** how much the ripples and iron are particular to their beauty > > > But since か is used to carry a sense of questioning shouldn't it be more like > > The difference between japanese swords and other swords **could be** how much the ripples and iron are particular to their beauty > > > Any help on how to parse and understand どれだけ波紋と鉄が美しいかにこだわっているかです would be appreciated :)
2021/03/17
['https://japanese.stackexchange.com/questions/84640', 'https://japanese.stackexchange.com', 'https://japanese.stackexchange.com/users/41902/']
The basic structure of this sentence is: > > 日本刀と他の刀との違いはX**です**。 > > The difference between Japanese swords and other swords **is** (in) X. > > > The "is" in the translation simply corresponds to the copula です at the end of the original sentence. There is no need to change it to something else like "could be". The "X" part consists of two nested [embedded questions](https://japanese.stackexchange.com/a/13038/5010): > > 【どれだけ【刃文と鉄が美しい**か**】にこだわっている**か**】 > > 【how much [blacksmiths] are particular about 【whether their [*hamon*](https://en.wikipedia.org/wiki/Hamon_(swordsmithing)) and iron are beautiful】】 > > > (I believe 波紋 is a misspelling and thus "ripple" is a mistranslation. The correct kanji is [刃文](https://ja.wikipedia.org/wiki/%E5%88%83%E6%96%87). That said, this misspelling is understandable because 刃文 has a wavy appearance.)
I would parse it this way: > > The difference between Japanese swords and other swords is this: How much do they care about "how beautiful are the ripples and iron?"? > > > And since this way there are essentially two implicit questions in this phrase it makes sense that there are two か.
99,835
Yesterday I heard of the [Bland-Altman plot](https://en.wikipedia.org/wiki/Bland%E2%80%93Altman_plot) for the first time. I have to compare two methods of measuring blood pressure, and I need to produce a Bland-Altman plot. I am not sure if I get everything about it right, so here's what I think I know: I have two sets of data. I calculate their mean (x value) and their difference (y value) and plot it around the axis y = mean of difference. Then, I calculate the standard deviation of the difference, and plot it as "limits of agreement". This is what I do not understand - limits of what agreement? What means 95% agreement in layman's terms? Is that supposed to tell me (provided that all points of the scatter graph are between the "limits of agreement") that the methods have 95% match?
2014/05/23
['https://stats.stackexchange.com/questions/99835', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/46069/']
Have you looked at [the Wikipedia entry](https://en.wikipedia.org/wiki/Bland%E2%80%93Altman_plot) I linked in your question? You don't plot "the mean of the data", but for each data point measured in two ways, you plot the difference in the two measurements ($y$) against the average of the two measurements ($x$). Using R and some toy data: ```r > set.seed(1) > measurements <- matrix(rnorm(20), ncol=2) > measurements [,1] [,2] [1,] -0.6264538 1.51178117 [2,] 0.1836433 0.38984324 [3,] -0.8356286 -0.62124058 [4,] 1.5952808 -2.21469989 [5,] 0.3295078 1.12493092 [6,] -0.8204684 -0.04493361 [7,] 0.4874291 -0.01619026 [8,] 0.7383247 0.94383621 [9,] 0.5757814 0.82122120 [10,] -0.3053884 0.59390132 > xx <- rowMeans(measurements) # x coordinate: row-wise average > yy <- apply(measurements, 1, diff) # y coordinate: row-wise difference > xx [1] 0.4426637 0.2867433 -0.7284346 -0.3097095 0.7272193 -0.4327010 0.2356194 0.8410805 0.6985013 0.1442565 > yy [1] 2.1382350 0.2061999 0.2143880 -3.8099807 0.7954231 0.7755348 -0.5036193 0.2055115 0.2454398 0.8992897 > plot(xx, yy, pch=19, xlab="Average", ylab="Difference") ``` ![Bland-Altman plot without limits of agreement](https://i.stack.imgur.com/vdzoe.png) To get the limits of agreement (see under "Application" in the Wikipedia page), you calculate the mean and the standard deviation of the differences, i.e., the $y$ values, and plot horizontal lines at the mean $\pm 1.96$ standard deviations. ```r > upper <- mean(yy) + 1.96*sd(yy) > lower <- mean(yy) - 1.96*sd(yy) > upper [1] 3.141753 > lower [1] -2.908468 > abline(h=c(upper,lower), lty=2) ``` ![Bland-Altman plot with limits of agreement](https://i.stack.imgur.com/piesA.png) (You can't see the upper limit of agreement because the plot only goes up to $y\approx 2.1$.) As to the interpretation of the plot and the limits of agreement, again look to Wikipedia: > > If the differences within mean ± 1.96 SD are not clinically important, the two methods may be used interchangeably. > > >
If you would like to do this in Python you can use this code ```py import matplotlib.pyplot as plt import numpy as np from numpy.random import random %matplotlib inline plt.style.use('ggplot') ``` I just added the last line because I like the ggplot style. ```py def plotblandaltman(x,y,title,sd_limit): plt.figure(figsize=(20,8)) plt.suptitle(title, fontsize="20") if len(x) != len(y): raise ValueError('x does not have the same length as y') else: for i in range(len(x)): a = np.asarray(x) b = np.asarray(x)+np.asarray(y) mean_diff = np.mean(b) std_diff = np.std(b, axis=0) limit_of_agreement = sd_limit * std_diff lower = mean_diff - limit_of_agreement upper = mean_diff + limit_of_agreement difference = upper - lower lowerplot = lower - (difference * 0.5) upperplot = upper + (difference * 0.5) plt.axhline(y=mean_diff, linestyle = "--", color = "red", label="mean diff") plt.axhline(y=lower, linestyle = "--", color = "grey", label="-1.96 SD") plt.axhline(y=upper, linestyle = "--", color = "grey", label="1.96 SD") plt.text(a.max()*0.85, upper * 1.1, " 1.96 SD", color = "grey", fontsize = "14") plt.text(a.max()*0.85, lower * 0.9, "-1.96 SD", color = "grey", fontsize = "14") plt.text(a.max()*0.85, mean_diff * 0.85, "Mean", color = "red", fontsize = "14") plt.ylim(lowerplot, upperplot) plt.scatter(x=a,y=b) ``` And finaly I just make some random values and compare them in this function ```py x = np.random.rand(100) y = np.random.rand(100) plotblandaltman(x,y,"Bland-altman plot",1.96) ``` [![Bland-altman plot](https://i.stack.imgur.com/OYo2f.png)](https://i.stack.imgur.com/OYo2f.png) With some minor modification, you can easily add a for-loop and make several plots
21,694
When some living being like dog or any mini bacteria are killed, since they are not self aware or concious do they feel the same type of pain as we do? what is the difference between their suffering and our suffering?
2017/07/24
['https://buddhism.stackexchange.com/questions/21694', 'https://buddhism.stackexchange.com', 'https://buddhism.stackexchange.com/users/-1/']
Dogs don't forget pain. You only have to look at a dog that has been continuously beaten and then cringes or tries to bite anyone who tries to pet it. Yes it has become an automatic reaction but there must be some kind of memory there about humans not being trustworthy.
Its very clear that dogs are conscious and feel the same pain as humans do and the suffering is the same suffering If by self aware you mean mindful- than most people arent mindful 99.9999% of the time --- many many monks if good ones are not mindful most of the time About bacteria i cant say much
21,694
When some living being like dog or any mini bacteria are killed, since they are not self aware or concious do they feel the same type of pain as we do? what is the difference between their suffering and our suffering?
2017/07/24
['https://buddhism.stackexchange.com/questions/21694', 'https://buddhism.stackexchange.com', 'https://buddhism.stackexchange.com/users/-1/']
Its very clear that dogs are conscious and feel the same pain as humans do and the suffering is the same suffering If by self aware you mean mindful- than most people arent mindful 99.9999% of the time --- many many monks if good ones are not mindful most of the time About bacteria i cant say much
In all [31 planes of existence](http://www.accesstoinsight.org/ptf/dhamma/sagga/loka.html) there is attachment to life except for the plane for [Unconscious Beings (asaññasatta)](https://suttacentral.net/define/asa%C3%B1%C3%B1asatt%C4%81). So a dog feels pain thus like us. Also any being in any plane are self aware except for enlightened beings who do not have self conceiving. Also we all lose some notion of suffering otherwise hence why 1st Noble Truth is not readily comprehensible.
21,694
When some living being like dog or any mini bacteria are killed, since they are not self aware or concious do they feel the same type of pain as we do? what is the difference between their suffering and our suffering?
2017/07/24
['https://buddhism.stackexchange.com/questions/21694', 'https://buddhism.stackexchange.com', 'https://buddhism.stackexchange.com/users/-1/']
Dogs don't forget pain. You only have to look at a dog that has been continuously beaten and then cringes or tries to bite anyone who tries to pet it. Yes it has become an automatic reaction but there must be some kind of memory there about humans not being trustworthy.
It is hard to say unless you are an animal or bacteria. In general observation, it appears animals such as dogs enjoy the sex and they feel the pain. According to Buddhist teaching animals possess five aggregate same as the human. Interesting video to watch. In this video, it is explained in plain English that any living and breathing organism has consciousness and how we interpret pain and pleasure. [Your brain hallucinates your conscious reality | Anil Seth](https://youtu.be/lyu7v7nWzfo)
21,694
When some living being like dog or any mini bacteria are killed, since they are not self aware or concious do they feel the same type of pain as we do? what is the difference between their suffering and our suffering?
2017/07/24
['https://buddhism.stackexchange.com/questions/21694', 'https://buddhism.stackexchange.com', 'https://buddhism.stackexchange.com/users/-1/']
Dogs don't forget pain. You only have to look at a dog that has been continuously beaten and then cringes or tries to bite anyone who tries to pet it. Yes it has become an automatic reaction but there must be some kind of memory there about humans not being trustworthy.
I think that (according to Buddhism) humans, animals, ghosts, and residents of hell all belong to the same kind of category: all "[sentient](https://en.wikipedia.org/wiki/Sentient_beings_(Buddhism))", all composed of the five skandhas, and all subject to suffering. Since all belong to the same continuum (i.e. samsara), I expect that they all "lose memory" and that their "suffering finishes" in much the same way. I don't consider a dog as like a bacterium, by the way: IMO a bacterium is more like a plant than an animal. I think different schools of Buddhism differ on whether plants are "sentient" and have any "consciousness". **don't they just forget or loose the momory of their suffering after it is finished?** Isn't that more-or-less true (or untrue) of people too?
21,694
When some living being like dog or any mini bacteria are killed, since they are not self aware or concious do they feel the same type of pain as we do? what is the difference between their suffering and our suffering?
2017/07/24
['https://buddhism.stackexchange.com/questions/21694', 'https://buddhism.stackexchange.com', 'https://buddhism.stackexchange.com/users/-1/']
Dogs don't forget pain. You only have to look at a dog that has been continuously beaten and then cringes or tries to bite anyone who tries to pet it. Yes it has become an automatic reaction but there must be some kind of memory there about humans not being trustworthy.
More primitive life forms, such as worms or fish, have a nervous system, therefore their nervous system experiences physical pain. Dogs are probably more complex and have emotions such as lust, love, *emotional* attachment; that makes them experience *emotional* sorrow & unhappiness. However. as we can directly experience, homo sapiens (people) have the *egoistic* attachment (*upadana*) of self-identity (*sakkaya ditthi*), which is born from thought conception. This *upadana* of *sakkaya ditthi* is the '*suffering*' ('*dukkha*') Buddhism seeks to eliminate. I think it is a fair assumption worms & fish cannot create the *upadana* of *sakkaya ditthi*; and probably also dogs. > > *Bhikkhu, ‘**I am**’ **is a conceiving**; ‘**I am** this’ is a conceiving; ‘**I** shall be’ is a conceiving; ‘**I** shall not be’ is a conceiving; ‘**I** shall > be possessed of form’ is a conceiving; ‘**I** shall be formless’ is a > conceiving; ‘**I** shall be percipient’ is a conceiving; ‘**I** shall be > non-percipient’ is a conceiving; ‘**I** shall be > neither-percipient-nor-non-percipient’ is a conceiving. **Conceiving is > a disease, conceiving is a tumour, conceiving is a dart**. By overcoming > all conceivings, bhikkhu, one is called a sage at peace. MN 140* > > >
21,694
When some living being like dog or any mini bacteria are killed, since they are not self aware or concious do they feel the same type of pain as we do? what is the difference between their suffering and our suffering?
2017/07/24
['https://buddhism.stackexchange.com/questions/21694', 'https://buddhism.stackexchange.com', 'https://buddhism.stackexchange.com/users/-1/']
Its very clear that dogs are conscious and feel the same pain as humans do and the suffering is the same suffering If by self aware you mean mindful- than most people arent mindful 99.9999% of the time --- many many monks if good ones are not mindful most of the time About bacteria i cant say much
I think that (according to Buddhism) humans, animals, ghosts, and residents of hell all belong to the same kind of category: all "[sentient](https://en.wikipedia.org/wiki/Sentient_beings_(Buddhism))", all composed of the five skandhas, and all subject to suffering. Since all belong to the same continuum (i.e. samsara), I expect that they all "lose memory" and that their "suffering finishes" in much the same way. I don't consider a dog as like a bacterium, by the way: IMO a bacterium is more like a plant than an animal. I think different schools of Buddhism differ on whether plants are "sentient" and have any "consciousness". **don't they just forget or loose the momory of their suffering after it is finished?** Isn't that more-or-less true (or untrue) of people too?
21,694
When some living being like dog or any mini bacteria are killed, since they are not self aware or concious do they feel the same type of pain as we do? what is the difference between their suffering and our suffering?
2017/07/24
['https://buddhism.stackexchange.com/questions/21694', 'https://buddhism.stackexchange.com', 'https://buddhism.stackexchange.com/users/-1/']
Dogs don't forget pain. You only have to look at a dog that has been continuously beaten and then cringes or tries to bite anyone who tries to pet it. Yes it has become an automatic reaction but there must be some kind of memory there about humans not being trustworthy.
In all [31 planes of existence](http://www.accesstoinsight.org/ptf/dhamma/sagga/loka.html) there is attachment to life except for the plane for [Unconscious Beings (asaññasatta)](https://suttacentral.net/define/asa%C3%B1%C3%B1asatt%C4%81). So a dog feels pain thus like us. Also any being in any plane are self aware except for enlightened beings who do not have self conceiving. Also we all lose some notion of suffering otherwise hence why 1st Noble Truth is not readily comprehensible.
21,694
When some living being like dog or any mini bacteria are killed, since they are not self aware or concious do they feel the same type of pain as we do? what is the difference between their suffering and our suffering?
2017/07/24
['https://buddhism.stackexchange.com/questions/21694', 'https://buddhism.stackexchange.com', 'https://buddhism.stackexchange.com/users/-1/']
Its very clear that dogs are conscious and feel the same pain as humans do and the suffering is the same suffering If by self aware you mean mindful- than most people arent mindful 99.9999% of the time --- many many monks if good ones are not mindful most of the time About bacteria i cant say much
More primitive life forms, such as worms or fish, have a nervous system, therefore their nervous system experiences physical pain. Dogs are probably more complex and have emotions such as lust, love, *emotional* attachment; that makes them experience *emotional* sorrow & unhappiness. However. as we can directly experience, homo sapiens (people) have the *egoistic* attachment (*upadana*) of self-identity (*sakkaya ditthi*), which is born from thought conception. This *upadana* of *sakkaya ditthi* is the '*suffering*' ('*dukkha*') Buddhism seeks to eliminate. I think it is a fair assumption worms & fish cannot create the *upadana* of *sakkaya ditthi*; and probably also dogs. > > *Bhikkhu, ‘**I am**’ **is a conceiving**; ‘**I am** this’ is a conceiving; ‘**I** shall be’ is a conceiving; ‘**I** shall not be’ is a conceiving; ‘**I** shall > be possessed of form’ is a conceiving; ‘**I** shall be formless’ is a > conceiving; ‘**I** shall be percipient’ is a conceiving; ‘**I** shall be > non-percipient’ is a conceiving; ‘**I** shall be > neither-percipient-nor-non-percipient’ is a conceiving. **Conceiving is > a disease, conceiving is a tumour, conceiving is a dart**. By overcoming > all conceivings, bhikkhu, one is called a sage at peace. MN 140* > > >
21,694
When some living being like dog or any mini bacteria are killed, since they are not self aware or concious do they feel the same type of pain as we do? what is the difference between their suffering and our suffering?
2017/07/24
['https://buddhism.stackexchange.com/questions/21694', 'https://buddhism.stackexchange.com', 'https://buddhism.stackexchange.com/users/-1/']
I think that (according to Buddhism) humans, animals, ghosts, and residents of hell all belong to the same kind of category: all "[sentient](https://en.wikipedia.org/wiki/Sentient_beings_(Buddhism))", all composed of the five skandhas, and all subject to suffering. Since all belong to the same continuum (i.e. samsara), I expect that they all "lose memory" and that their "suffering finishes" in much the same way. I don't consider a dog as like a bacterium, by the way: IMO a bacterium is more like a plant than an animal. I think different schools of Buddhism differ on whether plants are "sentient" and have any "consciousness". **don't they just forget or loose the momory of their suffering after it is finished?** Isn't that more-or-less true (or untrue) of people too?
More primitive life forms, such as worms or fish, have a nervous system, therefore their nervous system experiences physical pain. Dogs are probably more complex and have emotions such as lust, love, *emotional* attachment; that makes them experience *emotional* sorrow & unhappiness. However. as we can directly experience, homo sapiens (people) have the *egoistic* attachment (*upadana*) of self-identity (*sakkaya ditthi*), which is born from thought conception. This *upadana* of *sakkaya ditthi* is the '*suffering*' ('*dukkha*') Buddhism seeks to eliminate. I think it is a fair assumption worms & fish cannot create the *upadana* of *sakkaya ditthi*; and probably also dogs. > > *Bhikkhu, ‘**I am**’ **is a conceiving**; ‘**I am** this’ is a conceiving; ‘**I** shall be’ is a conceiving; ‘**I** shall not be’ is a conceiving; ‘**I** shall > be possessed of form’ is a conceiving; ‘**I** shall be formless’ is a > conceiving; ‘**I** shall be percipient’ is a conceiving; ‘**I** shall be > non-percipient’ is a conceiving; ‘**I** shall be > neither-percipient-nor-non-percipient’ is a conceiving. **Conceiving is > a disease, conceiving is a tumour, conceiving is a dart**. By overcoming > all conceivings, bhikkhu, one is called a sage at peace. MN 140* > > >
21,694
When some living being like dog or any mini bacteria are killed, since they are not self aware or concious do they feel the same type of pain as we do? what is the difference between their suffering and our suffering?
2017/07/24
['https://buddhism.stackexchange.com/questions/21694', 'https://buddhism.stackexchange.com', 'https://buddhism.stackexchange.com/users/-1/']
I think that (according to Buddhism) humans, animals, ghosts, and residents of hell all belong to the same kind of category: all "[sentient](https://en.wikipedia.org/wiki/Sentient_beings_(Buddhism))", all composed of the five skandhas, and all subject to suffering. Since all belong to the same continuum (i.e. samsara), I expect that they all "lose memory" and that their "suffering finishes" in much the same way. I don't consider a dog as like a bacterium, by the way: IMO a bacterium is more like a plant than an animal. I think different schools of Buddhism differ on whether plants are "sentient" and have any "consciousness". **don't they just forget or loose the momory of their suffering after it is finished?** Isn't that more-or-less true (or untrue) of people too?
It is hard to say unless you are an animal or bacteria. In general observation, it appears animals such as dogs enjoy the sex and they feel the pain. According to Buddhist teaching animals possess five aggregate same as the human. Interesting video to watch. In this video, it is explained in plain English that any living and breathing organism has consciousness and how we interpret pain and pleasure. [Your brain hallucinates your conscious reality | Anil Seth](https://youtu.be/lyu7v7nWzfo)
24,514
Basically I have created a function which takes two lists of dicts, for example: ``` oldList = [{'a':2}, {'v':2}] newList = [{'a':4},{'c':4},{'e':5}] ``` My aim is to check for each dictionary key in the oldList and if it has the same dictionary key as in the newList update the dictionary, else append to the oldList. So in this case the key 'a' from oldList will get updated with the value 4, also since the keys b and e from the newList don't exist in the oldList append the dictionary to the oldList. Therefore you get `[{'a': 4}, {'v': 2}, {'b': 4}, {'e': 5}]`. Is there a better way to do this? ``` def sortList(oldList, newList): for new in newList: #{'a':4},{'c':4},{'e':5} isAdd = True for old in oldList: #{'a':2}, {'v':2} if new.keys()[0] == old.keys()[0]: #a == a isAdd = False old.update(new) # update dict if isAdd: oldList.append(new) #if value not in oldList append to it return oldList sortedDict = sortList([{'a':2}, {'v':2}],[{'a':4},{'b':4},{'e':5}]) print sortedDict [{'a': 4}, {'v': 2}, {'b': 4}, {'e': 5}] ```
2013/03/29
['https://codereview.stackexchange.com/questions/24514', 'https://codereview.stackexchange.com', 'https://codereview.stackexchange.com/users/23629/']
``` def sortList(oldList, newList): ``` Python convention is to lowercase\_with\_underscores for pretty much everything besides class names ``` for new in newList: #{'a':4},{'c':4},{'e':5} isAdd = True ``` Avoid boolean flags. They are delayed gotos and make it harder to follow your code. In this case, I'd suggest using an else: block on the for loop. ``` for old in oldList: #{'a':2}, {'v':2} if new.keys()[0] == old.keys()[0]: #a == a isAdd = False old.update(new) # update dict if isAdd: oldList.append(new) #if value not in oldList append to it return oldList sortedDict = sortList([{'a':2}, {'v':2}],[{'a':4},{'b':4},{'e':5}]) print sortedDict ``` Why are you calling it sortList? You are merging lists, not sorting anything... Your whole piece of code would be quicker if implemented using dicts: ``` # convert the lists into dictionaries old_list = dict(item.items()[0] for item in oldList) new_list = dict(item.items()[0] for item in newList) # actually do the work (python already has a function that does it) old_list.update(new_list) # covert back to the list format return [{key:value} for key, value in old_list.items()] ``` All of which raises the question: why aren't these dicts already? What are you trying to do with this list of dicts stuff?
You don't need the `isAdd` flag, instead you can structure your for loops like this: ``` for new, old in newList, oldList: if new.keys()[0] == old.keys()[0]: old.update(new) else: oldList.append(new) return oldList ``` As well, you might want to look at [PEP](http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html) documents for coding style For reference, here is the rest of your code with those standards in place: ``` def sort_list(old_list, new_list): for new, old in new_list, old_list: if new.keys()[0] == old.keys()[0]: old.update(new) else: old_list.append(new) return old_list sorted_dict = sort_list([{'a':2}, {'v':2}],[{'a':4},{'b':4},{'e':5}]) print sorted_dict [{'a': 4}, {'v': 2}, {'b': 4}, {'e': 5}] ``` Oh, and I'm assuming you are doing this for practice/homework, but the [dict.update(iterable)](http://docs.python.org/2/library/stdtypes.html#dict.update) method does this exact thing far, far faster than you ever could.
24,514
Basically I have created a function which takes two lists of dicts, for example: ``` oldList = [{'a':2}, {'v':2}] newList = [{'a':4},{'c':4},{'e':5}] ``` My aim is to check for each dictionary key in the oldList and if it has the same dictionary key as in the newList update the dictionary, else append to the oldList. So in this case the key 'a' from oldList will get updated with the value 4, also since the keys b and e from the newList don't exist in the oldList append the dictionary to the oldList. Therefore you get `[{'a': 4}, {'v': 2}, {'b': 4}, {'e': 5}]`. Is there a better way to do this? ``` def sortList(oldList, newList): for new in newList: #{'a':4},{'c':4},{'e':5} isAdd = True for old in oldList: #{'a':2}, {'v':2} if new.keys()[0] == old.keys()[0]: #a == a isAdd = False old.update(new) # update dict if isAdd: oldList.append(new) #if value not in oldList append to it return oldList sortedDict = sortList([{'a':2}, {'v':2}],[{'a':4},{'b':4},{'e':5}]) print sortedDict [{'a': 4}, {'v': 2}, {'b': 4}, {'e': 5}] ```
2013/03/29
['https://codereview.stackexchange.com/questions/24514', 'https://codereview.stackexchange.com', 'https://codereview.stackexchange.com/users/23629/']
A list of 1-pair dictionaries makes no sense as data structure. You should join them to create a single dictionary. This way all your code reduces to: ``` d1 = {'a': 2, 'b': 2} d2 = {'a': 4, 'c': 4, 'e': 5} d3 = dict(d1, **d2) # {'a': 4, 'b': 2, 'c': 4, 'e': 5} ``` If you are going to union/merge dicts a lot, you can create a handy abstraction, more general than `dict(d1, **d2)`: ``` def merge_dicts(d1, d2): return dict(itertools.chain(d1.items(), d2.items())) ``` To convert list of dictionaries to a dictionary is simple: ``` d2 = dict(list(d.items())[0] for d in new_list) # {'a': 4, 'c': 4, 'e': 5} ```
You don't need the `isAdd` flag, instead you can structure your for loops like this: ``` for new, old in newList, oldList: if new.keys()[0] == old.keys()[0]: old.update(new) else: oldList.append(new) return oldList ``` As well, you might want to look at [PEP](http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html) documents for coding style For reference, here is the rest of your code with those standards in place: ``` def sort_list(old_list, new_list): for new, old in new_list, old_list: if new.keys()[0] == old.keys()[0]: old.update(new) else: old_list.append(new) return old_list sorted_dict = sort_list([{'a':2}, {'v':2}],[{'a':4},{'b':4},{'e':5}]) print sorted_dict [{'a': 4}, {'v': 2}, {'b': 4}, {'e': 5}] ``` Oh, and I'm assuming you are doing this for practice/homework, but the [dict.update(iterable)](http://docs.python.org/2/library/stdtypes.html#dict.update) method does this exact thing far, far faster than you ever could.
24,514
Basically I have created a function which takes two lists of dicts, for example: ``` oldList = [{'a':2}, {'v':2}] newList = [{'a':4},{'c':4},{'e':5}] ``` My aim is to check for each dictionary key in the oldList and if it has the same dictionary key as in the newList update the dictionary, else append to the oldList. So in this case the key 'a' from oldList will get updated with the value 4, also since the keys b and e from the newList don't exist in the oldList append the dictionary to the oldList. Therefore you get `[{'a': 4}, {'v': 2}, {'b': 4}, {'e': 5}]`. Is there a better way to do this? ``` def sortList(oldList, newList): for new in newList: #{'a':4},{'c':4},{'e':5} isAdd = True for old in oldList: #{'a':2}, {'v':2} if new.keys()[0] == old.keys()[0]: #a == a isAdd = False old.update(new) # update dict if isAdd: oldList.append(new) #if value not in oldList append to it return oldList sortedDict = sortList([{'a':2}, {'v':2}],[{'a':4},{'b':4},{'e':5}]) print sortedDict [{'a': 4}, {'v': 2}, {'b': 4}, {'e': 5}] ```
2013/03/29
['https://codereview.stackexchange.com/questions/24514', 'https://codereview.stackexchange.com', 'https://codereview.stackexchange.com/users/23629/']
A list of 1-pair dictionaries makes no sense as data structure. You should join them to create a single dictionary. This way all your code reduces to: ``` d1 = {'a': 2, 'b': 2} d2 = {'a': 4, 'c': 4, 'e': 5} d3 = dict(d1, **d2) # {'a': 4, 'b': 2, 'c': 4, 'e': 5} ``` If you are going to union/merge dicts a lot, you can create a handy abstraction, more general than `dict(d1, **d2)`: ``` def merge_dicts(d1, d2): return dict(itertools.chain(d1.items(), d2.items())) ``` To convert list of dictionaries to a dictionary is simple: ``` d2 = dict(list(d.items())[0] for d in new_list) # {'a': 4, 'c': 4, 'e': 5} ```
``` def sortList(oldList, newList): ``` Python convention is to lowercase\_with\_underscores for pretty much everything besides class names ``` for new in newList: #{'a':4},{'c':4},{'e':5} isAdd = True ``` Avoid boolean flags. They are delayed gotos and make it harder to follow your code. In this case, I'd suggest using an else: block on the for loop. ``` for old in oldList: #{'a':2}, {'v':2} if new.keys()[0] == old.keys()[0]: #a == a isAdd = False old.update(new) # update dict if isAdd: oldList.append(new) #if value not in oldList append to it return oldList sortedDict = sortList([{'a':2}, {'v':2}],[{'a':4},{'b':4},{'e':5}]) print sortedDict ``` Why are you calling it sortList? You are merging lists, not sorting anything... Your whole piece of code would be quicker if implemented using dicts: ``` # convert the lists into dictionaries old_list = dict(item.items()[0] for item in oldList) new_list = dict(item.items()[0] for item in newList) # actually do the work (python already has a function that does it) old_list.update(new_list) # covert back to the list format return [{key:value} for key, value in old_list.items()] ``` All of which raises the question: why aren't these dicts already? What are you trying to do with this list of dicts stuff?
74,616,016
How do I add a string/integer into an existing text file at a specific location? My sample text looks like below: ```txt No, Color, Height, age 1, blue,70, 2, white,65, 3, brown,49, 4, purple,71, 5, grey,60, ``` My text file has 4 columns, three columns have text, how do I write to any row in the fourth column? If I want to write 12 to the second row, the updated file (sample.txt) should look like this: ```txt No, Color, Height, age 1, blue,70,12 2, white,65, 3, brown,49, 4, purple,71, 5, grey,60, ``` I have tried this: ```py with open("sample.txt",'r') as file: data =file.readlines() data[1]. split(",") [3] = 1 with open ('sample.txt', 'w') as file: file.writelines(data) with open ('sample.txt', 'r') as file: print (file. Read()) ``` But it does not work. Your help is needed.
2022/11/29
['https://Stackoverflow.com/questions/74616016', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5255512/']
Here's the proper `case_when` syntax. ``` df <- data.frame(x = c("A", "B", "C", "D")) library(dplyr) df <- df %>% mutate(y = case_when(x %in% c("A", "D") ~ 1, x %in% c("B", "C") ~ 0, TRUE ~ NA_real_)) df #> x y #> 1 A 1 #> 2 B 0 #> 3 C 0 #> 4 D 1 ```
You're combining syntaxes in a way that makes sense in speech but not in code. Generally you can't use `foo == "G" | "H"`. You need to use `foo == "G" | foo == "H"`, or the handy shorthand `foo %in% c("G", "H")`. Similarly `x %in% df == "A"` doesn't make sense `x %in% df` makes sense. `df == "A"` makes sense. Putting them together `x %in% df == ...` does not make sense to R. (Okay, it does make sense to R, but not the same sense it does to you. R will use its Order of Operations which evaluates `x %in% df` first and gets a `result` from that, and then checks whether that `result == "A"`, which is not what you want.) Inside a `dplyr` function like `mutate`, you don't need to keep specifying `df`. You pipe in `df` and now you just need to use the column `x`. `x %in% df` looks like you're testing whether the column `x` is in the data frame `df`, which you don't need to do. Instead use `x %in% c("A", "D")`. Aron's answer shows the full correct syntax, I hope this answer helps you understand why.
72,278,607
I am having a problem with my java and xml code. As I am using the Android Studio IDE I can see the good version of the app page I wanna make, while when I export it to my phone and build it it isn't working and everything is on top of each ither. I will be showing the code and pictures of what I see in the ide and what I get on my phone. I hope you can help resolve this issue as I am a beginner android developer since I mainly on web and this issue is really bothering me. Thanks! **activity\_main.xml** ``` <?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#fffa94" tools:context=".Definition"> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginEnd="88dp" android:text="What About Anemia?" android:textSize="25dp" app:layout_constraintEnd_toEndOf="parent" tools:layout_editor_absoluteY="128dp" /> <ImageView android:id="@+id/imageView" android:layout_width="wrap_content" android:layout_height="wrap_content" app:srcCompat="@drawable/secondpage" tools:layout_editor_absoluteX="0dp" tools:layout_editor_absoluteY="128dp" /> <TextView android:id="@+id/textView2" android:layout_width="347dp" android:layout_height="189dp" android:text="Anemia is defined as a low number of red blood cells. In a routine blood test, anemia is reported as a low hemoglobin or hematocrit. Hemoglobin is the main protein in your red blood cells. It carries oxygen, and delivers it throughout your body. If you have anemia, your hemoglobin level will be low too. If it is low enough, your tissues or organs may not get enough oxygen." android:textAlignment="center" tools:layout_editor_absoluteX="32dp" tools:layout_editor_absoluteY="382dp" /> <TextView android:id="@+id/textView3" android:layout_width="248dp" android:layout_height="56dp" android:text="HOME" android:textAlignment="center" android:textSize="40dp" tools:layout_editor_absoluteX="81dp" tools:layout_editor_absoluteY="27dp" /> <TextView android:id="@+id/textView4" android:layout_width="401dp" android:layout_height="50dp" android:text="What are the symptoms?" android:textAlignment="center" android:textSize="25dp" tools:layout_editor_absoluteX="5dp" tools:layout_editor_absoluteY="571dp" /> <TextView android:id="@+id/textView5" android:layout_width="413dp" android:layout_height="197dp" android:text="Fatigue. \n Weakness. \n Pale or yellowish skin. \n Irregular heartbeats. \n Shortness of breath. \n Diziness or lightheadedness. \n Chest pain. \n Cold hands and feet." android:textAlignment="center" tools:layout_editor_absoluteX="0dp" tools:layout_editor_absoluteY="629dp" /> </androidx.constraintlayout.widget.ConstraintLayout> ``` **MainActivity.java** ``` package com.example.allagainstanemia; import android.content.Intent; import android.os.Bundle; import com.google.android.material.snackbar.Snackbar; import android.widget.Button; import androidx.appcompat.widget.Toolbar; import androidx.appcompat.app.AppCompatActivity; import android.view.View; import androidx.navigation.NavController; import androidx.navigation.Navigation; import androidx.navigation.ui.AppBarConfiguration; import androidx.navigation.ui.NavigationUI; import com.example.allagainstanemia.databinding.ActivityMainBinding; import android.view.Menu; import android.view.MenuItem; public class MainActivity extends AppCompatActivity { private AppBarConfiguration appBarConfiguration; private ActivityMainBinding binding; private Button button2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); binding = ActivityMainBinding.inflate(getLayoutInflater()); setContentView(binding.getRoot()); this.button2 = (Button) findViewById(R.id.button2); button2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent otheractivity = new Intent(getApplicationContext(), Definition.class); startActivity(otheractivity); finish(); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } @Override public boolean onSupportNavigateUp() { NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main); return NavigationUI.navigateUp(navController, appBarConfiguration) || super.onSupportNavigateUp(); } } ``` **Picture of my ide result** [![enter image description here](https://i.stack.imgur.com/CdnE3.png)](https://i.stack.imgur.com/CdnE3.png) **Screenshot of the app in my phone** [![enter image description here](https://i.stack.imgur.com/BR9Kj.jpg)](https://i.stack.imgur.com/BR9Kj.jpg) *Thank you for your time!*
2022/05/17
['https://Stackoverflow.com/questions/72278607', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/19070139/']
Even though you have arranged your views in the appropriate position for the design they don't have constraints. You can see that error in under the views in `activity_main.xml`. so try this layout which has some basic constraints. You can change the constraints as per your need ``` <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#fffa94" tools:context=".Definition"> <androidx.core.widget.NestedScrollView android:id="@+id/nestedScrollView3" android:layout_width="0dp" android:layout_height="0dp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent"> <androidx.constraintlayout.widget.ConstraintLayout android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="36dp" android:text="What About Anemia?" android:textSize="25dp" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/textView3" /> <ImageView android:id="@+id/imageView" android:layout_width="0dp" android:layout_height="0dp" app:layout_constraintDimensionRatio="3:1" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/textView" app:srcCompat="@drawable/secondpage" /> <TextView android:id="@+id/textView2" android:layout_width="347dp" android:layout_height="189dp" android:text="Anemia is defined as a low number of red blood cells. In a routine blood test, anemia is reported as a low hemoglobin or hematocrit. Hemoglobin is the main protein in your red blood cells. It carries oxygen, and delivers it throughout your body. If you have anemia, your hemoglobin level will be low too. If it is low enough, your tissues or organs may not get enough oxygen." android:textAlignment="center" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/imageView" /> <TextView android:id="@+id/textView3" android:layout_width="248dp" android:layout_height="56dp" android:layout_marginTop="52dp" android:text="HOME" android:textAlignment="center" android:textSize="40dp" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintHorizontal_bias="0.496" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <TextView android:id="@+id/textView4" android:layout_width="401dp" android:layout_height="50dp" android:text="What are the symptoms?" android:textAlignment="center" android:textSize="25dp" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/textView2" /> <TextView android:id="@+id/textView5" android:layout_width="413dp" android:layout_height="197dp" android:layout_marginTop="69dp" android:text="Fatigue. \n Weakness. \n Pale or yellowish skin. \n Irregular heartbeats. \n Shortness of breath. \n Diziness or lightheadedness. \n Chest pain. \n Cold hands and feet." android:textAlignment="center" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="@+id/textView4" /> </androidx.constraintlayout.widget.ConstraintLayout> </androidx.core.widget.NestedScrollView> </androidx.constraintlayout.widget.ConstraintLayout> ```
Try this I have made proper constraint with UI ``` <?xml version="1.0" encoding="utf-8"?> <androidx.core.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#fffa94"> <androidx.constraintlayout.widget.ConstraintLayout android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:id="@+id/textView3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="20dp" android:text="HOME" android:textAlignment="center" android:textSize="40sp" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="20dp" android:text="What About Anemia?" android:textSize="25sp" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/textView3" /> <ImageView android:id="@+id/imageView" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="50dp" android:contentDescription="@string/app_name" android:src="@mipmap/ic_launcher" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/textView" /> <TextView android:id="@+id/textView2" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="20dp" android:text="Anemia is defined as a low number of red blood cells. In a routine blood test, anemia is reported as a low hemoglobin or hematocrit. Hemoglobin is the main protein in your red blood cells. It carries oxygen, and delivers it throughout your body. If you have anemia, your hemoglobin level will be low too. If it is low enough, your tissues or organs may not get enough oxygen." android:textAlignment="center" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/imageView" /> <TextView android:id="@+id/textView4" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="50dp" android:text="What are the symptoms?" android:textAlignment="center" android:textSize="25sp" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/textView2" /> <TextView android:id="@+id/textView5" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="25dp" android:text="Fatigue. \n Weakness. \n Pale or yellowish skin. \n Irregular heartbeats. \n Shortness of breath. \n Diziness or lightheadedness. \n Chest pain. \n Cold hands and feet." android:textAlignment="center" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/textView4" /> </androidx.constraintlayout.widget.ConstraintLayout> </androidx.core.widget.NestedScrollView> ```
72,278,607
I am having a problem with my java and xml code. As I am using the Android Studio IDE I can see the good version of the app page I wanna make, while when I export it to my phone and build it it isn't working and everything is on top of each ither. I will be showing the code and pictures of what I see in the ide and what I get on my phone. I hope you can help resolve this issue as I am a beginner android developer since I mainly on web and this issue is really bothering me. Thanks! **activity\_main.xml** ``` <?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#fffa94" tools:context=".Definition"> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginEnd="88dp" android:text="What About Anemia?" android:textSize="25dp" app:layout_constraintEnd_toEndOf="parent" tools:layout_editor_absoluteY="128dp" /> <ImageView android:id="@+id/imageView" android:layout_width="wrap_content" android:layout_height="wrap_content" app:srcCompat="@drawable/secondpage" tools:layout_editor_absoluteX="0dp" tools:layout_editor_absoluteY="128dp" /> <TextView android:id="@+id/textView2" android:layout_width="347dp" android:layout_height="189dp" android:text="Anemia is defined as a low number of red blood cells. In a routine blood test, anemia is reported as a low hemoglobin or hematocrit. Hemoglobin is the main protein in your red blood cells. It carries oxygen, and delivers it throughout your body. If you have anemia, your hemoglobin level will be low too. If it is low enough, your tissues or organs may not get enough oxygen." android:textAlignment="center" tools:layout_editor_absoluteX="32dp" tools:layout_editor_absoluteY="382dp" /> <TextView android:id="@+id/textView3" android:layout_width="248dp" android:layout_height="56dp" android:text="HOME" android:textAlignment="center" android:textSize="40dp" tools:layout_editor_absoluteX="81dp" tools:layout_editor_absoluteY="27dp" /> <TextView android:id="@+id/textView4" android:layout_width="401dp" android:layout_height="50dp" android:text="What are the symptoms?" android:textAlignment="center" android:textSize="25dp" tools:layout_editor_absoluteX="5dp" tools:layout_editor_absoluteY="571dp" /> <TextView android:id="@+id/textView5" android:layout_width="413dp" android:layout_height="197dp" android:text="Fatigue. \n Weakness. \n Pale or yellowish skin. \n Irregular heartbeats. \n Shortness of breath. \n Diziness or lightheadedness. \n Chest pain. \n Cold hands and feet." android:textAlignment="center" tools:layout_editor_absoluteX="0dp" tools:layout_editor_absoluteY="629dp" /> </androidx.constraintlayout.widget.ConstraintLayout> ``` **MainActivity.java** ``` package com.example.allagainstanemia; import android.content.Intent; import android.os.Bundle; import com.google.android.material.snackbar.Snackbar; import android.widget.Button; import androidx.appcompat.widget.Toolbar; import androidx.appcompat.app.AppCompatActivity; import android.view.View; import androidx.navigation.NavController; import androidx.navigation.Navigation; import androidx.navigation.ui.AppBarConfiguration; import androidx.navigation.ui.NavigationUI; import com.example.allagainstanemia.databinding.ActivityMainBinding; import android.view.Menu; import android.view.MenuItem; public class MainActivity extends AppCompatActivity { private AppBarConfiguration appBarConfiguration; private ActivityMainBinding binding; private Button button2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); binding = ActivityMainBinding.inflate(getLayoutInflater()); setContentView(binding.getRoot()); this.button2 = (Button) findViewById(R.id.button2); button2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent otheractivity = new Intent(getApplicationContext(), Definition.class); startActivity(otheractivity); finish(); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } @Override public boolean onSupportNavigateUp() { NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main); return NavigationUI.navigateUp(navController, appBarConfiguration) || super.onSupportNavigateUp(); } } ``` **Picture of my ide result** [![enter image description here](https://i.stack.imgur.com/CdnE3.png)](https://i.stack.imgur.com/CdnE3.png) **Screenshot of the app in my phone** [![enter image description here](https://i.stack.imgur.com/BR9Kj.jpg)](https://i.stack.imgur.com/BR9Kj.jpg) *Thank you for your time!*
2022/05/17
['https://Stackoverflow.com/questions/72278607', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/19070139/']
You have used `tools:layout_editor_absoluteX` and `tools:layout_editor_absoluteY` in your XML file. The `tools:` keyword is used to add attributes to views when you are in your IDE designing your XML file and won't apply to the build version and also you have forgot to add constraints when you've used constraint layout. ```xml <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#fffa94" tools:context=".Definition"> <androidx.core.widget.NestedScrollView android:id="@+id/nestedScrollView3" android:layout_width="0dp" android:layout_height="0dp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent"> <androidx.constraintlayout.widget.ConstraintLayout android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="36dp" android:text="What About Anemia?" android:textSize="25dp" app:layout_constraintTop_toBottomOf="@+id/textView3" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent" /> <ImageView android:id="@+id/imageView" android:layout_width="0dp" android:layout_height="0dp" app:layout_constraintDimensionRatio="3:1" app:layout_constraintTop_toBottomOf="@+id/textView" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent" app:srcCompat="@drawable/secondpage" /> <TextView android:id="@+id/textView2" android:layout_width="347dp" android:layout_height="189dp" android:text="Anemia is defined as a low number of red blood cells. In a routine blood test, anemia is reported as a low hemoglobin or hematocrit. Hemoglobin is the main protein in your red blood cells. It carries oxygen, and delivers it throughout your body. If you have anemia, your hemoglobin level will be low too. If it is low enough, your tissues or organs may not get enough oxygen." android:textAlignment="center" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toBottomOf="@+id/imageView" app:layout_constraintStart_toStartOf="parent" /> <TextView android:id="@+id/textView3" android:layout_width="248dp" android:layout_height="56dp" android:layout_marginTop="52dp" android:text="HOME" android:textAlignment="center" android:textSize="40dp" app:layout_constraintHorizontal_bias="0.5" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <TextView android:id="@+id/textView4" android:layout_width="401dp" android:layout_height="50dp" android:text="What are the symptoms?" android:textAlignment="center" android:textSize="25dp" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toBottomOf="@+id/textView2" /> <TextView android:id="@+id/textView5" android:layout_width="413dp" android:layout_height="197dp" android:layout_marginTop="69dp" android:text="Fatigue. \n Weakness. \n Pale or yellowish skin. \n Irregular heartbeats. \n Shortness of breath. \n Diziness or lightheadedness. \n Chest pain. \n Cold hands and feet." android:textAlignment="center" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toTopOf="@+id/textView4" /> </androidx.constraintlayout.widget.ConstraintLayout> </androidx.core.widget.NestedScrollView> </androidx.constraintlayout.widget.ConstraintLayout> ```
Try this I have made proper constraint with UI ``` <?xml version="1.0" encoding="utf-8"?> <androidx.core.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#fffa94"> <androidx.constraintlayout.widget.ConstraintLayout android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:id="@+id/textView3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="20dp" android:text="HOME" android:textAlignment="center" android:textSize="40sp" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="20dp" android:text="What About Anemia?" android:textSize="25sp" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/textView3" /> <ImageView android:id="@+id/imageView" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="50dp" android:contentDescription="@string/app_name" android:src="@mipmap/ic_launcher" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/textView" /> <TextView android:id="@+id/textView2" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="20dp" android:text="Anemia is defined as a low number of red blood cells. In a routine blood test, anemia is reported as a low hemoglobin or hematocrit. Hemoglobin is the main protein in your red blood cells. It carries oxygen, and delivers it throughout your body. If you have anemia, your hemoglobin level will be low too. If it is low enough, your tissues or organs may not get enough oxygen." android:textAlignment="center" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/imageView" /> <TextView android:id="@+id/textView4" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="50dp" android:text="What are the symptoms?" android:textAlignment="center" android:textSize="25sp" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/textView2" /> <TextView android:id="@+id/textView5" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="25dp" android:text="Fatigue. \n Weakness. \n Pale or yellowish skin. \n Irregular heartbeats. \n Shortness of breath. \n Diziness or lightheadedness. \n Chest pain. \n Cold hands and feet." android:textAlignment="center" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/textView4" /> </androidx.constraintlayout.widget.ConstraintLayout> </androidx.core.widget.NestedScrollView> ```
244,842
After running in the Exchange Shell add-MailboxPermission "user X" -user UserY Fullaccess to give userY the ability to access UserX's mailbox, is there anyway that User X can tell that User Y now has full access?
2011/03/08
['https://serverfault.com/questions/244842', 'https://serverfault.com', 'https://serverfault.com/users/73606/']
This is not detectable in Outlook, OWA or any other Exchange client, which is how all standard users usually access Exchange; however, a skilled user (or an administrator) *could* detect it by looking at the actual permissions on the AD user object or on the Exchange mailbox; this requires no actual console access to the Exchange server or to DCs, it can be accomplished with administrative tools running on any client system.
No, unless UserY alters the content in a way that can be noticeable.
244,842
After running in the Exchange Shell add-MailboxPermission "user X" -user UserY Fullaccess to give userY the ability to access UserX's mailbox, is there anyway that User X can tell that User Y now has full access?
2011/03/08
['https://serverfault.com/questions/244842', 'https://serverfault.com', 'https://serverfault.com/users/73606/']
This is not detectable in Outlook, OWA or any other Exchange client, which is how all standard users usually access Exchange; however, a skilled user (or an administrator) *could* detect it by looking at the actual permissions on the AD user object or on the Exchange mailbox; this requires no actual console access to the Exchange server or to DCs, it can be accomplished with administrative tools running on any client system.
The user (user X) that has had the permissions changed on their mailbox will not know unless the mailbox is opened on another users (User Y) machine, and User Y makes changes to the contents of the mailbox. In the past I have dealt with managers who have demanded this capability, and things got really ugly when the manager was accidentally deleting/changing items in that users mailbox.
64,814,676
I have a simple HTMLAudioElement element: ``` let player = new Audio() player.src = 'file://' + _filePath player.load() ``` This pauses and plays by using the play/pause media keys while the windows isn't focused, **Q:** how do I make it ignore the play/pause keys? I'm using electron but not sure if this is a chrome or electron implementation so I'm tagging both.
2020/11/13
['https://Stackoverflow.com/questions/64814676', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5905035/']
Found an answer in this question: [Disable media control keys with javascript](https://stackoverflow.com/questions/59347480/disable-media-control-keys-with-javascript), thanks @PableWeb18 We can just override the media key listeners: ``` navigator.mediaSession.setActionHandler('play', function() { /* Code excerpted. */ }); navigator.mediaSession.setActionHandler('pause', function() { /* Code excerpted. */ }); navigator.mediaSession.setActionHandler('seekbackward', function() { /* Code excerpted. */ }); navigator.mediaSession.setActionHandler('seekforward', function() { /* Code excerpted. */ }); navigator.mediaSession.setActionHandler('previoustrack', function() { /* Code excerpted. */ }); navigator.mediaSession.setActionHandler('nexttrack', function() { /* Code excerpted. */ }); ```
To override a function you can use `prototype`, see the example below: ```js var audio = new Audio(); Audio.prototype.play = function() { console.log('Play override') }; Audio.prototype.stop = function() { console.log('Stop override') }; audio.play(); audio.stop(); ``` `EDIT:` So just add the primary function inside a var and after you done, put in together using prototype again: ```js var audio = new Audio('https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3'); var play = audio.play; var pause = audio.pause; Audio.prototype.play = function() { console.log('Nothing happened') }; Audio.prototype.pause = function() { console.log('Nothing happened') }; audio.play(); audio.pause(); Audio.prototype.play = play; Audio.prototype.pause = pause; audio.play(); setTimeout(function() { audio.pause() }, 5000) ```
12,114,174
Specifically, why would it help to fix a PermGen OutOfMemoryError issue? Also, bonus points for an answer that points me to the documentation on JVM arguments...
2012/08/24
['https://Stackoverflow.com/questions/12114174', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/242135/']
The permanent space is where the classes, methods, internalized strings, and similar objects used by the VM are stored and never deallocated (hence the name). [This Oracle article](http://www.oracle.com/technetwork/java/javase/gc-tuning-6-140523.html) succinctly presents the working and parameterization of the HotSpot GC and advises you to augment this space if you load many classes (this is typically the case for application servers and some IDE like Eclipse) : > > The permanent generation does not have a noticeable impact on garbage > collector performance for most applications. However, some > applications dynamically generate and load many classes; for example, > some implementations of JavaServer Pages (JSP) pages. These > applications may need a larger permanent generation to hold the > additional classes. If so, the maximum permanent generation size can > be increased with the command-line option -XX:MaxPermSize=. > > > Note that [this other Oracle documentation](http://www.oracle.com/technetwork/java/javase/tech/vmoptions-jsp-140102.html) lists the other HotSpot arguments. **Update :** Starting with Java 8, both the permgen space and this setting are gone. The memory model used for loaded classes and methods is different and isn't limited (with default settings). You should not see this error any more.
`-XX:PermSize -XX:MaxPermSize` are used to set size for Permanent Generation. Permanent Generation: The Permanent Generation is where class files are kept. These are the result of compiled classes and JSP pages. If this space is full, it triggers a Full Garbage Collection. If the Full Garbage Collection cannot clean out old unreferenced classes and there is no room left to expand the Permanent Space, an Out‐of‐ Memory error (OOME) is thrown and the JVM will crash.
12,114,174
Specifically, why would it help to fix a PermGen OutOfMemoryError issue? Also, bonus points for an answer that points me to the documentation on JVM arguments...
2012/08/24
['https://Stackoverflow.com/questions/12114174', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/242135/']
The permanent space is where the classes, methods, internalized strings, and similar objects used by the VM are stored and never deallocated (hence the name). [This Oracle article](http://www.oracle.com/technetwork/java/javase/gc-tuning-6-140523.html) succinctly presents the working and parameterization of the HotSpot GC and advises you to augment this space if you load many classes (this is typically the case for application servers and some IDE like Eclipse) : > > The permanent generation does not have a noticeable impact on garbage > collector performance for most applications. However, some > applications dynamically generate and load many classes; for example, > some implementations of JavaServer Pages (JSP) pages. These > applications may need a larger permanent generation to hold the > additional classes. If so, the maximum permanent generation size can > be increased with the command-line option -XX:MaxPermSize=. > > > Note that [this other Oracle documentation](http://www.oracle.com/technetwork/java/javase/tech/vmoptions-jsp-140102.html) lists the other HotSpot arguments. **Update :** Starting with Java 8, both the permgen space and this setting are gone. The memory model used for loaded classes and methods is different and isn't limited (with default settings). You should not see this error any more.
In Java 8 that parameter is commonly used to print a warning message like this one: > > Java HotSpot(TM) 64-Bit Server VM warning: ignoring option > MaxPermSize=512m; support was removed in 8.0 > > > The reason why you get this message in Java 8 is because Permgen has been replaced by Metaspace to address some of PermGen's drawbacks (as you were able to see for yourself, one of those drawbacks is that it had a fixed size). FYI: an article on Metaspace: <http://java-latte.blogspot.in/2014/03/metaspace-in-java-8.html>
12,114,174
Specifically, why would it help to fix a PermGen OutOfMemoryError issue? Also, bonus points for an answer that points me to the documentation on JVM arguments...
2012/08/24
['https://Stackoverflow.com/questions/12114174', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/242135/']
`-XX:PermSize -XX:MaxPermSize` are used to set size for Permanent Generation. Permanent Generation: The Permanent Generation is where class files are kept. These are the result of compiled classes and JSP pages. If this space is full, it triggers a Full Garbage Collection. If the Full Garbage Collection cannot clean out old unreferenced classes and there is no room left to expand the Permanent Space, an Out‐of‐ Memory error (OOME) is thrown and the JVM will crash.
In Java 8 that parameter is commonly used to print a warning message like this one: > > Java HotSpot(TM) 64-Bit Server VM warning: ignoring option > MaxPermSize=512m; support was removed in 8.0 > > > The reason why you get this message in Java 8 is because Permgen has been replaced by Metaspace to address some of PermGen's drawbacks (as you were able to see for yourself, one of those drawbacks is that it had a fixed size). FYI: an article on Metaspace: <http://java-latte.blogspot.in/2014/03/metaspace-in-java-8.html>
35,996,096
I am trying to find the number of Strings that only appear exactly once in an `ArrayList`. How many I achieve this (preferably with the best possible time complexity)? Below is my method: ``` public static int countNonRepeats(WordStream words) { ArrayList<String> list = new ArrayList<String>(); for (String i : words) { list.add(i); } Collections.sort(list); for (int i = 1; i < list.size(); i++) { if (list.get(i).equals(list.get(i - 1))) { list.remove(list.get(i)); list.remove(list.get(i - 1)); } } System.out.println(list); return list.size(); } ``` Why doesn't it remove the String at `list.get(i)` and `list.get(i-1)`?
2016/03/14
['https://Stackoverflow.com/questions/35996096', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5938067/']
Here's one simple suggestion: 1. First, sort your array by alphanumerical order 2. Iterate through with a loop, `if( !list.get(i).equals(list.get(i+1)) ) → unique` 3. If you find duplicates, increment `i` until you reach a different string This will have the complexity of the sorting algorithm, since step 2+3 should be O(n)
Is there any specific need of using an `ArrayList`? You can do it easily by using a `HashSet`. Here is the code snippet: ``` public static void main (String[] args) { String[] words = {"foo","bar","foo","fo","of","bar","of","ba","of","ab"}; Set<String> set = new HashSet<>(); Set<String> common = new HashSet<>(); for (String i : words) { if(!set.add(i)) { common.add(i); } } System.out.println(set.size() - common.size()); } ``` Output: ``` 3 ``` Here is the modified code: ``` public static int countNonRepeats(WordStream words) { Set<String> set = new HashSet<>(); Set<String> common = new HashSet<>(); for (String i : words) { if(!set.add(i)) { common.add(i); } } return (set.size() - common.size()); } ```
35,996,096
I am trying to find the number of Strings that only appear exactly once in an `ArrayList`. How many I achieve this (preferably with the best possible time complexity)? Below is my method: ``` public static int countNonRepeats(WordStream words) { ArrayList<String> list = new ArrayList<String>(); for (String i : words) { list.add(i); } Collections.sort(list); for (int i = 1; i < list.size(); i++) { if (list.get(i).equals(list.get(i - 1))) { list.remove(list.get(i)); list.remove(list.get(i - 1)); } } System.out.println(list); return list.size(); } ``` Why doesn't it remove the String at `list.get(i)` and `list.get(i-1)`?
2016/03/14
['https://Stackoverflow.com/questions/35996096', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5938067/']
Here's one simple suggestion: 1. First, sort your array by alphanumerical order 2. Iterate through with a loop, `if( !list.get(i).equals(list.get(i+1)) ) → unique` 3. If you find duplicates, increment `i` until you reach a different string This will have the complexity of the sorting algorithm, since step 2+3 should be O(n)
You can use hashmap to achieve this.With this approach we can count the occurrence of all the words, If we are interested in only unique words then access the element having count = 1. **`HashMap<String,Integer>`** - key represents the String from arraylist and Integer represents the count of occurrence. ``` ArrayList<String> list = new ArrayList<String>(); HashMap<String, Integer> hashMap = new HashMap<String, Integer>(); for (int i = 0; i < list.size(); i++) { String key = list.get(i); if (hashMap.get(key) != null) { int value = hashMap.get(key); value++; hashMap.put(key, value); } else { hashMap.put(key, 1); } } int uniqueCount = 0; Iterator it = hashMap.entrySet().iterator(); while (it.hasNext()) { Map.Entry pair = (Map.Entry) it.next(); if ((int) pair.getValue() == 1) uniqueCount++; } System.out.println(uniqueCount); ```
35,996,096
I am trying to find the number of Strings that only appear exactly once in an `ArrayList`. How many I achieve this (preferably with the best possible time complexity)? Below is my method: ``` public static int countNonRepeats(WordStream words) { ArrayList<String> list = new ArrayList<String>(); for (String i : words) { list.add(i); } Collections.sort(list); for (int i = 1; i < list.size(); i++) { if (list.get(i).equals(list.get(i - 1))) { list.remove(list.get(i)); list.remove(list.get(i - 1)); } } System.out.println(list); return list.size(); } ``` Why doesn't it remove the String at `list.get(i)` and `list.get(i-1)`?
2016/03/14
['https://Stackoverflow.com/questions/35996096', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5938067/']
Here's one simple suggestion: 1. First, sort your array by alphanumerical order 2. Iterate through with a loop, `if( !list.get(i).equals(list.get(i+1)) ) → unique` 3. If you find duplicates, increment `i` until you reach a different string This will have the complexity of the sorting algorithm, since step 2+3 should be O(n)
There is no need for sorting. A better approach would be to use two HashSet One for maintaining repeating and one for non-repeating words. Since HashSet internally uses HashMap, Ideally contains, get, put operation has o(1) complexity. So the overall complexity of this approach would be o(n). ``` public static int countNonRepeats(List<String> words) { Set<String> nonRepeating = new HashSet<String>(); Set<String> repeating = new HashSet<String>(); for (String i : words) { if(!repeating.contains(i)) { if(nonRepeating.contains(i)){ repeating.add(i); nonRepeating.remove(i); }else { nonRepeating.add(i); } } } System.out.println(nonRepeating.size()); return nonRepeating.size(); } ```
35,996,096
I am trying to find the number of Strings that only appear exactly once in an `ArrayList`. How many I achieve this (preferably with the best possible time complexity)? Below is my method: ``` public static int countNonRepeats(WordStream words) { ArrayList<String> list = new ArrayList<String>(); for (String i : words) { list.add(i); } Collections.sort(list); for (int i = 1; i < list.size(); i++) { if (list.get(i).equals(list.get(i - 1))) { list.remove(list.get(i)); list.remove(list.get(i - 1)); } } System.out.println(list); return list.size(); } ``` Why doesn't it remove the String at `list.get(i)` and `list.get(i-1)`?
2016/03/14
['https://Stackoverflow.com/questions/35996096', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5938067/']
Is there any specific need of using an `ArrayList`? You can do it easily by using a `HashSet`. Here is the code snippet: ``` public static void main (String[] args) { String[] words = {"foo","bar","foo","fo","of","bar","of","ba","of","ab"}; Set<String> set = new HashSet<>(); Set<String> common = new HashSet<>(); for (String i : words) { if(!set.add(i)) { common.add(i); } } System.out.println(set.size() - common.size()); } ``` Output: ``` 3 ``` Here is the modified code: ``` public static int countNonRepeats(WordStream words) { Set<String> set = new HashSet<>(); Set<String> common = new HashSet<>(); for (String i : words) { if(!set.add(i)) { common.add(i); } } return (set.size() - common.size()); } ```
You can use hashmap to achieve this.With this approach we can count the occurrence of all the words, If we are interested in only unique words then access the element having count = 1. **`HashMap<String,Integer>`** - key represents the String from arraylist and Integer represents the count of occurrence. ``` ArrayList<String> list = new ArrayList<String>(); HashMap<String, Integer> hashMap = new HashMap<String, Integer>(); for (int i = 0; i < list.size(); i++) { String key = list.get(i); if (hashMap.get(key) != null) { int value = hashMap.get(key); value++; hashMap.put(key, value); } else { hashMap.put(key, 1); } } int uniqueCount = 0; Iterator it = hashMap.entrySet().iterator(); while (it.hasNext()) { Map.Entry pair = (Map.Entry) it.next(); if ((int) pair.getValue() == 1) uniqueCount++; } System.out.println(uniqueCount); ```
35,996,096
I am trying to find the number of Strings that only appear exactly once in an `ArrayList`. How many I achieve this (preferably with the best possible time complexity)? Below is my method: ``` public static int countNonRepeats(WordStream words) { ArrayList<String> list = new ArrayList<String>(); for (String i : words) { list.add(i); } Collections.sort(list); for (int i = 1; i < list.size(); i++) { if (list.get(i).equals(list.get(i - 1))) { list.remove(list.get(i)); list.remove(list.get(i - 1)); } } System.out.println(list); return list.size(); } ``` Why doesn't it remove the String at `list.get(i)` and `list.get(i-1)`?
2016/03/14
['https://Stackoverflow.com/questions/35996096', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5938067/']
There is no need for sorting. A better approach would be to use two HashSet One for maintaining repeating and one for non-repeating words. Since HashSet internally uses HashMap, Ideally contains, get, put operation has o(1) complexity. So the overall complexity of this approach would be o(n). ``` public static int countNonRepeats(List<String> words) { Set<String> nonRepeating = new HashSet<String>(); Set<String> repeating = new HashSet<String>(); for (String i : words) { if(!repeating.contains(i)) { if(nonRepeating.contains(i)){ repeating.add(i); nonRepeating.remove(i); }else { nonRepeating.add(i); } } } System.out.println(nonRepeating.size()); return nonRepeating.size(); } ```
You can use hashmap to achieve this.With this approach we can count the occurrence of all the words, If we are interested in only unique words then access the element having count = 1. **`HashMap<String,Integer>`** - key represents the String from arraylist and Integer represents the count of occurrence. ``` ArrayList<String> list = new ArrayList<String>(); HashMap<String, Integer> hashMap = new HashMap<String, Integer>(); for (int i = 0; i < list.size(); i++) { String key = list.get(i); if (hashMap.get(key) != null) { int value = hashMap.get(key); value++; hashMap.put(key, value); } else { hashMap.put(key, 1); } } int uniqueCount = 0; Iterator it = hashMap.entrySet().iterator(); while (it.hasNext()) { Map.Entry pair = (Map.Entry) it.next(); if ((int) pair.getValue() == 1) uniqueCount++; } System.out.println(uniqueCount); ```
317,552
I'm trying to export a layer via QTiles, gotten from the Data Source Manager and connecting to ([USGSHydroCached](https://basemap.nationalmap.gov/arcgis/rest/services/USGSHydroCached/MapServer)). I have QTiles set to zoom levels `0-20` and `Render tiles outside of layers extent` checked (basemap goes up to `20`). For some reason, the hydro layer only shows up to zoom level `17` (as per Leaflet). At zoom levels `18,19,20` the layer disappears. QTiles is generating folders and files up to zoom level `20` (assuming this is the extent checkbox). Is there a way to have it render the tile beyond that zoom level (poor resolution is fine)?
2019/04/02
['https://gis.stackexchange.com/questions/317552', 'https://gis.stackexchange.com', 'https://gis.stackexchange.com/users/139763/']
The layer info at the link you provide indicates the MapServer should provide tiles up to level 19, not 20 as you'd like. But that shouldn't create problems at level 17! However, I've played around with zooming in on the layer the QGis map window and it shows up at scales up to 1:6019, but not more detailed than that. So there's something funny with the tiles being returned by the server at levels 17+. QTiles is a red herring here, it's just that's what's asking for the layer at detailed scales. Since it's actually a simple line layer, it would be much better if you could find a vector (rather than tile/raster) source for it. I tried a trick that often works, to try to connect to it as an ArcGisFeatureServer rather than MapServer, replacing MapServer with FeatureServer in the URI, but that didn't work. Your ideal solution would be to hunt and see a FeatureServer or WFS source for it. Failing that, you can get a jagged version by exporting it in the region of interest at a scale that works, and then loading that into your map instead. To do that, load it in, zoom into a generous area well beyond your area of interest, right click on the layer in the layer tree and choose Export / Save as... Then do the following; note VRT is off, click on Map Canvas Extent to set the region that will be exported, and the resolution 2.388657133974685 is chosen since that's the resolution of a Level 16 tile that works. Then use your saved .tif rather than the MapServer version. [![enter image description here](https://i.stack.imgur.com/swbnR.png)](https://i.stack.imgur.com/swbnR.png) If you want to get fancy, keep both layers, but make them visible at different scales via layer properties. And/or vectorize the raster you saved, and then style it to your heart's content (color, line thickness etc) that will then render properly at any scale level (just of course with the level of underlying detail you exported, no more no less).
As @Houska has noted the map service that you are using only provides tiles down to level 17. However, the data supplied in the map service is the [USGS National Hydrography Dataset](https://www.usgs.gov/core-science-systems/ngp/national-hydrography/access-national-hydrography-products) which is freely available to download in vector form, so if you want to generate tiles at any zoom level, this can be done by using a styled version of the vector NHD data.
28,175
After some research surrounding this I can't seem to fix this issue. So for a project I made a simple module with some variables that simply has to make an OAuth1 call and return some data. The provider of the website advised me to use : <https://github.com/thephpleague/oauth1-client> So in my module I initialised another composer.json and required the package above. It gets correctly installed to the vendor map in my module. However whenever I call the new OAuth() or new OAuth1() it can't be found. I've tried adding it while using the packagepath in the top of my module.php as well as my moduleVariable.php but to no avail. I was wondering if I'm doing something wrong? Or forgetting something? What's the best way to add composer libraries to your own custom module? Best regards!
2018/10/23
['https://craftcms.stackexchange.com/questions/28175', 'https://craftcms.stackexchange.com', 'https://craftcms.stackexchange.com/users/8359/']
Twig has an [interpolation syntax](https://twig.symfony.com/doc/2.x/templates.html#string-interpolation) (using `#{}` inside a double-quoted string) to accomplish this: ``` {% set location = block.locationVacancies %} {% set entries = craft .entries .section('careers') .search("locationVacancies:#{location}") .all() %} ``` --- In addition, you can be more explicit about the values you’re searching for (and avoid any kind of sneaky `search` capabilities/side-effects exposed by using raw query input): ``` {% set location = block.locationVacancies %} {% set entries = craft .entries .section('careers') .locationVacancies("*#{location}*") .all() %} ``` …or even using Twig object syntax… ``` {% set location = block.locationVacancies %} {% set entries = craft.entries({ section: 'careers', locationVacancies: "*#{location}*" }).all() %} ``` (`locationVacancies: location` will also work, but disables partial matching) > > It should be noted: if you're looking to associate multiple explicit entries, you can also make the field within your (presumed) Matrix Block an `Entries` field, which establishes actual relationships in the database—accessing such a field (`myBlock.myLocationEntriesField.all()`) will return that list of Entries, exactly as set in the admin) If you just need a dynamic search param, what you have is a fine solution! > > >
```twig {% set location = block.locationVacancies %} {% set entries = craft .entries .section('careers') .search('locationVacancies:"' ~ location ~ '"') .find() %} ```
44,790,947
I am working on music app so I am trying to do a button when I click it the song be repeating and the background change I have two background one of them I want to make it background of the button when play the song once and the another when the song is repeating ``` package khaledbanafa.shaylat; import android.media.MediaPlayer; import android.os.Build; import android.support.annotation.RequiresApi; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.RelativeLayout; import android.widget.SeekBar; import android.widget.TextView; import android.widget.ToggleButton; import java.io.IOException; import static android.app.PendingIntent.getActivity; import static khaledbanafa.shaylat.R.drawable.play; public class ha extends AppCompatActivity { MediaPlayer x; RelativeLayout mylayout; TextView textView; TextView textView2; TextView textView3; SeekBar seekBar; boolean pressed = false; @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_on); final Button a = (Button) findViewById(R.id.button1); a.setText("ارفع الراس يا حربي"); final Button b = (Button) findViewById(R.id.button2); b.setText("سما سما"); final Button c = (Button) findViewById(R.id.button3); c.setText("الحربي للحربي فدا"); final Button d = (Button) findViewById(R.id.button4); d.setText("العبو ياحرب دام العمر فاني"); final Button e = (Button) findViewById(R.id.button5); e.setText("حرب الحرايب"); final Button f = (Button) findViewById(R.id.button6); f.setText("حرب الحرايب لحن دحة"); final Button g = (Button) findViewById(R.id.button7); g.setText("حرب الدول"); final Button h = (Button) findViewById(R.id.button8); h.setText("حرب ماتنقص تزود"); final Button i = (Button) findViewById(R.id.button9); i.setText("حنا اهل الفخر"); final Button j = (Button) findViewById(R.id.button10); j.setText("ياحرب شوشو والعبو"); Button play = (Button) findViewById(R.id.buttonplay); Button pause = (Button) findViewById(R.id.buttonpause); Button stop = (Button) findViewById(R.id.buttonstop); final Button repeat = (Button)findViewById(R.id.repeat); Button nextmedia = (Button)findViewById(R.id.nextmedia); textView = (TextView)findViewById(R.id.textView); textView2 = (TextView)findViewById(R.id.textView2); textView3 = (TextView)findViewById(R.id.textView3); seekBar = (SeekBar)findViewById(R.id.seekBar); final SeekBar SEK = new SeekBar(ha.this); SEK.setPadding(150,0,140,0); SEK.setX(0); SEK.setY(1659); SEK.setProgressDrawable(getDrawable(R.drawable.red_scrubber_progress)); SEK.setThumb(getDrawable(R.drawable.red_scrubber_control)); mylayout = (RelativeLayout)findViewById(R.id.onrel); SEK.setLayoutParams(new RelativeLayout.LayoutParams( RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT)); play.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(x != null) x.start(); } }); stop.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(x != null) x.stop(); textView.setText(""); mylayout.removeView(SEK); mylayout.addView(SEK); SEK.setProgress(0); SEK.setMax(0); } }); pause.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(x != null) x.pause(); } }); a.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mylayout.removeView(seekBar); mylayout.removeView(SEK); stopPlaying(); x = MediaPlayer.create(ha.this, R.raw.haone); class mythread extends Thread { public void run() { while (x != null) { try { Thread.sleep(1000); } catch (Exception e) { } SEK.post(new Runnable() { @Override public void run() { SEK.setProgress(x.getCurrentPosition()); int tim = (SEK.getMax() / 1000); int m = tim / 60; int s = tim % 60; ///////// int tim0 = (SEK.getProgress() / 1000); int m0 = tim0 / 60; int s0 = tim0 % 60; textView2.setText(m0 + ":" + s0); textView3.setText(m + ":" + s); } }); } } } SEK.setMax(x.getDuration()); mythread my = new mythread(); textView.setText(a.getText()); mylayout.addView(SEK); my.start(); x.start(); SEK.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { int progresval; @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { progresval = progress;} @Override public void onStartTrackingTouch(SeekBar seekBar) {} @Override public void onStopTrackingTouch(SeekBar seekBar) { x.seekTo(progresval); } });} }); b.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mylayout.removeView(seekBar);mylayout.removeView(SEK);stopPlaying(); x = MediaPlayer.create(ha.this, R.raw.hatwo);class mythread extends Thread { public void run() {while (x != null) {try {Thread.sleep(1000);} catch (Exception e) {} SEK.post(new Runnable() { @Override public void run() { SEK.setProgress(x.getCurrentPosition()); int tim = (SEK.getMax()/1000); int m = tim/60; int s= tim %60; ///////// int tim0 = (SEK.getProgress()/1000); int m0 = tim0/60; int s0 = tim0%60; textView2.setText(m0+":"+s0); textView3.setText(m+":"+s);}});}}} SEK.setMax(x.getDuration());mythread my = new mythread(); textView.setText(b.getText()); mylayout.addView(SEK); my.start();x.start(); SEK.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { int progresval; @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { progresval = progress;} @Override public void onStartTrackingTouch(SeekBar seekBar) {} @Override public void onStopTrackingTouch(SeekBar seekBar) { x.seekTo(progresval); } }); } }); c.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mylayout.removeView(seekBar);mylayout.removeView(SEK);stopPlaying(); x = MediaPlayer.create(ha.this, R.raw.hathree);class mythread extends Thread { public void run() {while (x != null) {try {Thread.sleep(1000);} catch (Exception e) {} SEK.post(new Runnable() { @Override public void run() { SEK.setProgress(x.getCurrentPosition()); int tim = (SEK.getMax()/1000); int m = tim/60; int s= tim %60; ///////// int tim0 = (SEK.getProgress()/1000); int m0 = tim0/60; int s0 = tim0%60; textView2.setText(m0+":"+s0); textView3.setText(m+":"+s);}});}}} SEK.setMax(x.getDuration());mythread my = new mythread(); textView.setText(c.getText()); mylayout.addView(SEK); my.start();x.start(); SEK.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { int progresval; @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { progresval = progress;} @Override public void onStartTrackingTouch(SeekBar seekBar) {} @Override public void onStopTrackingTouch(SeekBar seekBar) { x.seekTo(progresval); } }); } }); d.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mylayout.removeView(seekBar);mylayout.removeView(SEK);stopPlaying(); x = MediaPlayer.create(ha.this, R.raw.hafour);class mythread extends Thread { public void run() {while (x != null) {try {Thread.sleep(1000);} catch (Exception e) {} SEK.post(new Runnable() { @Override public void run() { SEK.setProgress(x.getCurrentPosition()); int tim = (SEK.getMax()/1000); int m = tim/60; int s= tim %60; ///////// int tim0 = (SEK.getProgress()/1000); int m0 = tim0/60; int s0 = tim0%60; textView2.setText(m0+":"+s0); textView3.setText(m+":"+s);}});}}} SEK.setMax(x.getDuration());mythread my = new mythread(); textView.setText(d.getText()); mylayout.addView(SEK); my.start();x.start(); SEK.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { int progresval; @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { progresval = progress;} @Override public void onStartTrackingTouch(SeekBar seekBar) {} @Override public void onStopTrackingTouch(SeekBar seekBar) { x.seekTo(progresval); } }); } }); e.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mylayout.removeView(seekBar);mylayout.removeView(SEK);stopPlaying(); x = MediaPlayer.create(ha.this, R.raw.hafive);class mythread extends Thread { public void run() {while (x != null) {try {Thread.sleep(1000);} catch (Exception e) {} SEK.post(new Runnable() { @Override public void run() { SEK.setProgress(x.getCurrentPosition()); int tim = (SEK.getMax()/1000); int m = tim/60; int s= tim %60; ///////// int tim0 = (SEK.getProgress()/1000); int m0 = tim0/60; int s0 = tim0%60; textView2.setText(m0+":"+s0); textView3.setText(m+":"+s);}});}}} SEK.setMax(x.getDuration());mythread my = new mythread(); textView.setText(e.getText()); mylayout.addView(SEK); my.start();x.start(); SEK.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { int progresval; @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { progresval = progress;} @Override public void onStartTrackingTouch(SeekBar seekBar) {} @Override public void onStopTrackingTouch(SeekBar seekBar) { x.seekTo(progresval); } }); } }); f.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mylayout.removeView(seekBar);mylayout.removeView(SEK);stopPlaying(); x = MediaPlayer.create(ha.this, R.raw.hasix);class mythread extends Thread { public void run() {while (x != null) {try {Thread.sleep(1000);} catch (Exception e) {} SEK.post(new Runnable() { @Override public void run() { SEK.setProgress(x.getCurrentPosition()); int tim = (SEK.getMax()/1000); int m = tim/60; int s= tim %60; ///////// int tim0 = (SEK.getProgress()/1000); int m0 = tim0/60; int s0 = tim0%60; textView2.setText(m0+":"+s0); textView3.setText(m+":"+s);}});}}} SEK.setMax(x.getDuration());mythread my = new mythread(); textView.setText(f.getText()); mylayout.addView(SEK); my.start();x.start(); SEK.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { int progresval; @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { progresval = progress;} @Override public void onStartTrackingTouch(SeekBar seekBar) {} @Override public void onStopTrackingTouch(SeekBar seekBar) { x.seekTo(progresval); } }); } }); g.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mylayout.removeView(seekBar);mylayout.removeView(SEK);stopPlaying(); x = MediaPlayer.create(ha.this, R.raw.haseven);class mythread extends Thread { public void run() {while (x != null) {try {Thread.sleep(1000);} catch (Exception e) {} SEK.post(new Runnable() { @Override public void run() { SEK.setProgress(x.getCurrentPosition()); int tim = (SEK.getMax()/1000); int m = tim/60; int s= tim %60; ///////// int tim0 = (SEK.getProgress()/1000); int m0 = tim0/60; int s0 = tim0%60; textView2.setText(m0+":"+s0); textView3.setText(m+":"+s);}});}}} SEK.setMax(x.getDuration());mythread my = new mythread(); textView.setText(g.getText()); mylayout.addView(SEK); my.start();x.start(); SEK.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { int progresval; @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { progresval = progress;} @Override public void onStartTrackingTouch(SeekBar seekBar) {} @Override public void onStopTrackingTouch(SeekBar seekBar) { x.seekTo(progresval); } }); } }); h.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mylayout.removeView(seekBar);mylayout.removeView(SEK);stopPlaying(); x = MediaPlayer.create(ha.this, R.raw.haeight);class mythread extends Thread { public void run() {while (x != null) {try {Thread.sleep(1000);} catch (Exception e) {} SEK.post(new Runnable() { @Override public void run() { SEK.setProgress(x.getCurrentPosition()); int tim = (SEK.getMax()/1000); int m = tim/60; int s= tim %60; ///////// int tim0 = (SEK.getProgress()/1000); int m0 = tim0/60; int s0 = tim0%60; textView2.setText(m0+":"+s0); textView3.setText(m+":"+s);}});}}} SEK.setMax(x.getDuration());mythread my = new mythread(); textView.setText(h.getText()); mylayout.addView(SEK); my.start();x.start(); SEK.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { int progresval; @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { progresval = progress;} @Override public void onStartTrackingTouch(SeekBar seekBar) {} @Override public void onStopTrackingTouch(SeekBar seekBar) { x.seekTo(progresval); } }); } }); i.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mylayout.removeView(seekBar);mylayout.removeView(SEK);stopPlaying(); x = MediaPlayer.create(ha.this, R.raw.hanine);class mythread extends Thread { public void run() {while (x != null) {try {Thread.sleep(1000);} catch (Exception e) {} SEK.post(new Runnable() { @Override public void run() { SEK.setProgress(x.getCurrentPosition()); int tim = (SEK.getMax()/1000); int m = tim/60; int s= tim %60; ///////// int tim0 = (SEK.getProgress()/1000); int m0 = tim0/60; int s0 = tim0%60; textView2.setText(m0+":"+s0); textView3.setText(m+":"+s);}});}}} SEK.setMax(x.getDuration());mythread my = new mythread(); textView.setText(i.getText()); mylayout.addView(SEK); my.start();x.start(); SEK.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { int progresval; @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { progresval = progress;} @Override public void onStartTrackingTouch(SeekBar seekBar) {} @Override public void onStopTrackingTouch(SeekBar seekBar) { x.seekTo(progresval); } }); } }); j.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mylayout.removeView(seekBar);mylayout.removeView(SEK);stopPlaying(); x = MediaPlayer.create(ha.this, R.raw.haten);class mythread extends Thread { public void run() {while (x != null) {try {Thread.sleep(1000);} catch (Exception e) {} SEK.post(new Runnable() { @Override public void run() { SEK.setProgress(x.getCurrentPosition()); int tim = (SEK.getMax()/1000); int m = tim/60; int s= tim %60; ///////// int tim0 = (SEK.getProgress()/1000); int m0 = tim0/60; int s0 = tim0%60; textView2.setText(m0+":"+s0); textView3.setText(m+":"+s);}});}}} SEK.setMax(x.getDuration());mythread my = new mythread(); textView.setText(j.getText()); mylayout.addView(SEK); my.start();x.start(); SEK.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { int progresval; @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { progresval = progress;} @Override public void onStartTrackingTouch(SeekBar seekBar) {} @Override public void onStopTrackingTouch(SeekBar seekBar) { x.seekTo(progresval); } }); } }); } public void onDestroy(){ super.onDestroy(); if(x != null) x.stop(); } private void stopPlaying() { if (x != null) { x.stop(); x.release(); x = null; } } } ```
2017/06/27
['https://Stackoverflow.com/questions/44790947', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7872328/']
Anything is possible in the magical world of software, not only can it be done but there are many different ways of achieving it. Here is a rough example: <https://jsfiddle.net/n6fm39ww/> HTML ``` <select name="start_time"> </select> <select name="end_time"> <option value="default">Pick a start time</option> </select> ``` JS ``` // Add each option to start_times for (var hour = 9; hour <= 21; hour++) { var option = "<option value='"+hour+"'>"+hour+"</option>"; $('[name="start_time"]').append(option); } // When the start time is changed, set the end time $('[name="start_time"]').on('change', function() { // This is the start time chosen var start_time = $(this).val(); // Remove the default option $('[name="end_time"]').find('option').remove(); // Add options after the start time for (var hour = parseInt(start_time) + 1; hour <= 24; hour++) { var option = "<option value='"+hour+"'>"+hour+"</option>"; $('[name="end_time"]').append(option); } }); ```
Please make sure to provide code samples in the future. Here is an example of how that is done: <https://jsfiddle.net/c6432wee/> --- Say we have two selects. `<select id="startTime"> <option value="na">Please Select A Time</option> <option value=1>1:00PM</option> </select>` `<select id="endTime"> <option value="na">Please Select A Time</option> <option value=1>1:00PM</option> </select>` We start by setting the end time hidden `$('#endTime').css('display', 'none');` Then we register an event handler. Everytime it is changed, we look at the value to see if it different from our default placeholder. ``` $('#startTime').change(function () { if($('#startTime').val() !== 'na') { $('#endTime').css('display', 'initial'); } }); ``` If it is, we set endTime back to its initial display state. `$('#endTime').css('display', 'initial');`
12,930,583
I have been trying to upload an image using CodeIgniter's File Upload class. The image is used for a user's avatar. Here is a snippet for my code: ``` //upload file if($_FILES['image']['name'] != ''){ if (!file_exists($dirpath)) mkdir($dirpath); $this->load->library('upload'); $config['upload_path'] = $dirpath; $config['allowed_types'] = 'gif|jpg|jpeg|png|GIF|JPG|JPEG|PNG'; $config['max_size'] = '0'; $config['max_width'] = '0'; $config['max_height'] = '0'; $config['file_name'] = $_FILES['image']['name']; $config['overwrite'] = true; $config['remove_spaces'] = false; $this->upload->initialize($config); $data = ""; $error = ""; $photo_result = $this->upload->do_upload('image'); if ($photo_result) if($action == 'update'){ foreach (glob($dirpath.'/'.$old_image.'*') as $file) if (file_exists($file))unlink ($file); } if($new_resto->resized == 0){ if(resize_image($widths,$theuser)) $this->usermodel->update($theuser->id, array('resized'=>1), 'object',$authorization); } echo json_encode(array('config'=>$config,'upload_data'=>$this->upload->data())); } } ``` The file upload is supposedly successful, because when I print out `$this->upload->data()`, it shows that the upload data is not empty. The strange thing is, this code works for creating new users, but when I try to update users, the file is not uploaded. I have tried using `chmod($dirpath, 0777)` before the upload, and `chmod($dirpath, 0755)` after, still no luck. Any ideas? Thanks.
2012/10/17
['https://Stackoverflow.com/questions/12930583', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/805183/']
My mistake, I assigned `$old_image` after I updated the data, so `$old_image` contains the current image name, causing it to be deleted when i call `unlink($file)`. Problem solved :)
Please update your Upload.php class with previous version of CodeIgniter
22,018,987
I've got the following crash in `GameHelper.java`: > > [main] java.lang.NullPointerException at > com.google.android.gms.common.ConnectionResult.startResolutionForResult(Unknown > Source) at > com.google.example.games.basegameutils.GameHelper.resolveConnectionResult(GameHelper.java:752) > at > com.google.example.games.basegameutils.GameHelper.onConnectionFailed(GameHelper.java:729) > > > The only reason I think that could happen is if `mActivity == null` at `GameHelper.java:752`: ```java mConnectionResult.startResolutionForResult(mActivity, RC_RESOLVE); ``` `mActivity` gets null on `onStop()` Is it possible that GameHelper.java has bug and can crash if `onConnectionFailed()` happens after `onStop()` is called? Thanks. EDITED: It happened after update to the latest Play API (rev 15) together with the updated GameHelper.java.
2014/02/25
['https://Stackoverflow.com/questions/22018987', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1986565/']
EDIT: This now has been fixed in latest GameHelper version: <https://github.com/playgameservices/android-samples/commit/e7b3758c136b5b434f1dfd9ca8c03f75aad70f09> OLD ANSWER: For me it happens on the start of the app, when Google Play Services asks me to sign in and if I click cancel, this same error happens. So when leaving from your own activity to sign in activity, it dispatches onStop event, and fails to connect because of the user initiated process, which is resolvable, thus the error happens. So my quick hack was changing: ``` catch (SendIntentException e) ``` to simply ``` catch (Exception e) ``` So it would also catch Null pointer exception Of course in this case the signup process might not proceed, so I initate relogin on another action and it seems to work for now. More thorough hack could be trying to resolve the result on activity start, for that we define pending resolution variable: ``` // Are we expecting the result of a resolution flow? boolean mExpectingResolution = false; boolean mPendingResolution = false; ``` Then on the error line we check if activity is not null ``` if(mActivity != null) mConnectionResult.startResolutionForResult(mActivity, RC_RESOLVE); else mPendingResolution = true; ``` And on start we check and try to resolve it: ``` if(mPendingResolution && mConnectionResult != null) try { mConnectionResult.startResolutionForResult(mActivity, RC_RESOLVE); } catch (SendIntentException e) { e.printStackTrace(); } ``` This should help until the official resolution from lib supporters :)
Today is 16th september 2014 and I still facing this problem. I don't know why anyone else did not answer about to comment GameHelper line. In onStop method there is a line to set mActivity variable as null. I commented this line (like below) and my app is working properly. ``` /** Call this method from your Activity's onStop(). */ public void onStop() { debugLog("onStop"); assertConfigured("onStop"); if (mGoogleApiClient.isConnected()) { debugLog("Disconnecting client due to onStop"); mGoogleApiClient.disconnect(); } else { debugLog("Client already disconnected when we got onStop."); } mConnecting = false; mExpectingResolution = false; // let go of the Activity reference //mActivity = null; //COMMENT THIS LINE!!!! //COMMENT ABOVE LINE } ``` Is there any problem doing that:?
26,003,797
Assuming that there are many elements in a webpage how do i apply CSS to: * All the `<hr>` that are AFTER an unordered list * All the `<hr>` that are AFTER `<div>` * All the `<span>` which are inside `<p><article>` * All the `<span>` which are inside `<article>` Example: ``` #first > p > em { background: #739D00; color: #C7F83E; padding: .1em; } ```
2014/09/23
['https://Stackoverflow.com/questions/26003797', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3257288/']
The appropriate selectors, in order: ``` ul + hr {} div + hr {} p > article span {} article span {} ``` Remarks: ======== The `+` selector selects all elements **immediately** after a given element. In general, `A + B`, will cause the first element `B` that follows after any element `A`, to be styled. You can also use `~` in place of `+`, which would select all elements after a given element, no matter how far after. **With `ul ~ hr`** ``` <ul></ul> <hr /><!-- i get styled --> <hr /><!-- me too --> <hr /><!-- me too --> ``` **With `ul + hr`** ``` <ul></ul> <hr /><!-- i get styled --> <hr /><!-- nope --> <hr /><!-- nope --> ``` `>` is for direct descendant. My assumption of your questions: ``` <ul></ul> <hr /><!-- You want to style THIS --> <div></div> <hr /><!-- You want to style THIS --> <hr /><!-- ... but not this --> <p> <article> <!-- there may be more nested elements here... ---> <span></span><!-- You want to style THIS --> </article> </p> <article> <!-- there may be more nested elements... --> <span></span><!-- you want to style THIS --> </article> ```
You can use those selectors: * [Next-sibling combinator](http://dev.w3.org/csswg/selectors3/#adjacent-sibling-combinators) (`+`) For example, `ul + hr` matches all `hr` that are immediately preceded by an `ul` (ignoring non-element nodes). * [Following-sibling combinator](http://dev.w3.org/csswg/selectors3/#general-sibling-combinators) (`~`) For example, `ul ~ hr` matches all `hr` that are preceded (not necessarily immediately) by an `ul`. * [Child combinator](http://dev.w3.org/csswg/selectors3/#child-combinators) (`>`) For example, `article > span` matches all `span` that are children of an `article`. * [Descendant combinator](http://dev.w3.org/csswg/selectors3/#descendant-combinators) () For example, `article span` matches all `span` that are descendants of an `article`.
26,003,797
Assuming that there are many elements in a webpage how do i apply CSS to: * All the `<hr>` that are AFTER an unordered list * All the `<hr>` that are AFTER `<div>` * All the `<span>` which are inside `<p><article>` * All the `<span>` which are inside `<article>` Example: ``` #first > p > em { background: #739D00; color: #C7F83E; padding: .1em; } ```
2014/09/23
['https://Stackoverflow.com/questions/26003797', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3257288/']
The appropriate selectors, in order: ``` ul + hr {} div + hr {} p > article span {} article span {} ``` Remarks: ======== The `+` selector selects all elements **immediately** after a given element. In general, `A + B`, will cause the first element `B` that follows after any element `A`, to be styled. You can also use `~` in place of `+`, which would select all elements after a given element, no matter how far after. **With `ul ~ hr`** ``` <ul></ul> <hr /><!-- i get styled --> <hr /><!-- me too --> <hr /><!-- me too --> ``` **With `ul + hr`** ``` <ul></ul> <hr /><!-- i get styled --> <hr /><!-- nope --> <hr /><!-- nope --> ``` `>` is for direct descendant. My assumption of your questions: ``` <ul></ul> <hr /><!-- You want to style THIS --> <div></div> <hr /><!-- You want to style THIS --> <hr /><!-- ... but not this --> <p> <article> <!-- there may be more nested elements here... ---> <span></span><!-- You want to style THIS --> </article> </p> <article> <!-- there may be more nested elements... --> <span></span><!-- you want to style THIS --> </article> ```
Instead of `<hr>`, use border-bottom article is a block-level item that essentially replaces a `<div>` tag, and `<p>` tags should be within `<article>`, ``` article {border-bottom:#C3F 8px solid} article span {font-size:200%; color:#C3F} ul {border-bottom:#C3F 8px solid} ``` and in html, looks like this: ``` <article> <h1>article headline</h1> <p> My paragraph here <span> with a span section</span> and a border below the article, not paragraph.</p> <p>Another paragraph here</p> </article> <ul><li>Item one</li> <li>Item two</l> </ul> ```
26,003,797
Assuming that there are many elements in a webpage how do i apply CSS to: * All the `<hr>` that are AFTER an unordered list * All the `<hr>` that are AFTER `<div>` * All the `<span>` which are inside `<p><article>` * All the `<span>` which are inside `<article>` Example: ``` #first > p > em { background: #739D00; color: #C7F83E; padding: .1em; } ```
2014/09/23
['https://Stackoverflow.com/questions/26003797', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3257288/']
You can use those selectors: * [Next-sibling combinator](http://dev.w3.org/csswg/selectors3/#adjacent-sibling-combinators) (`+`) For example, `ul + hr` matches all `hr` that are immediately preceded by an `ul` (ignoring non-element nodes). * [Following-sibling combinator](http://dev.w3.org/csswg/selectors3/#general-sibling-combinators) (`~`) For example, `ul ~ hr` matches all `hr` that are preceded (not necessarily immediately) by an `ul`. * [Child combinator](http://dev.w3.org/csswg/selectors3/#child-combinators) (`>`) For example, `article > span` matches all `span` that are children of an `article`. * [Descendant combinator](http://dev.w3.org/csswg/selectors3/#descendant-combinators) () For example, `article span` matches all `span` that are descendants of an `article`.
Instead of `<hr>`, use border-bottom article is a block-level item that essentially replaces a `<div>` tag, and `<p>` tags should be within `<article>`, ``` article {border-bottom:#C3F 8px solid} article span {font-size:200%; color:#C3F} ul {border-bottom:#C3F 8px solid} ``` and in html, looks like this: ``` <article> <h1>article headline</h1> <p> My paragraph here <span> with a span section</span> and a border below the article, not paragraph.</p> <p>Another paragraph here</p> </article> <ul><li>Item one</li> <li>Item two</l> </ul> ```
846,279
I have found a lot of very solid articles/answers about this topic: * <https://askubuntu.com/a/555812/574648> * <https://unix.stackexchange.com/a/213984> * <https://askubuntu.com/a/662567/574648> And of course: * <https://wiki.archlinux.org/index.php/Xrandr> * <https://wiki.archlinux.org/index.php/HiDPI#Multiple_displays> However, I'm still struggling. My laptop is Dell XPS15. Its display is 3840x2160. I have tried different external monitors, but at the moment the one I use is also Dell with resolution 1920x1080. When I connect external monitor, some of the panels immediately become very small on 3840x2160 screen. When I try to scale up build-in display, chrome scales, my IDE scales, but displays window along with other windows like NVIDIA X Server settings stay very small. I have tried to play with **Scale all window contents to match** in **Display** but to no avail. It's either too big on the external screen or to small on the build-in. I have also tried xrandr with scale param but it gives me: ``` xrandr --output HDMI-1 --scale 2x2 X Error of failed request: BadValue (integer parameter out of range for operation) Major opcode of failed request: 140 (RANDR) Minor opcode of failed request: 26 (RRSetCrtcTransform) Value in failed request: 0x40 Serial number of failed request: 38 Current serial number in output stream: 39 ``` **Ideally, I want several windows of the same application(let's say Chrome or Intellij Idea to be open on different displays and scale independently on them).** ### EDIT I am not looking for **Scale for menus and title bar**, I like the way the bars are. I want windows contents scaled independently. **Displays** UI forces me to either scale all windows to match Built-id display or the external display. As a result: 1. *Scale all window contents to match* Build-In Display: Build-In Display - everything looks perfect; External Display - everything is huge. 2. *Scale all window contents to match* External Display: Build-In Display - very small; External Display - everything looks perfect.
2016/11/06
['https://askubuntu.com/questions/846279', 'https://askubuntu.com', 'https://askubuntu.com/users/574648/']
I have nvidia driver `340.98` with GT218M [NVS 3100M], Xubuntu 16.04, any results below are from this environment if I don't mention otherwise. Here is [my testing environment info](https://paste.ubuntu.com/23738679/), the output of: ``` sudo apt-get install pastebinit; \ sudo sh -c "lsb_release -sd; \ dmidecode -s system-product-name; echo ==; \ lshw -c display; echo ==; \ xrandr --verbose; echo ==; \ cat /etx/X11/xorg.conf" \ | tee ~/Desktop/ubuntu-graphic-info.txt \ | pastebinit ``` Weird and complex stack to debug specially using proprietary drivers. Most of the time, I get unexpected behaviors, may be due to lack of knowledge about the current Linux graphics stack setup. * I wrote [this answer](https://askubuntu.com/a/727897/26246) before, that may introduce some debugging tools like `xtrace` * Avoid running multiple/sequential `xrandr` commands, only after X server reset. Same command may have different result depending on previous commands. I have noticed that with `--scale` (see test case from my answer, linked above) `--transform` & `--fb`. Still don't know an easy way only by logout/login. So always logout/login before making another trial. * Screenshots take only pixel size image from FB, so I will add camera photos to show the real results. Method 1: `xrandr --output .. --scale HCoefxVCoef` or `--scale-from WxH` ------------------------------------------------------------------------ *Note, works fine for me. `--scale` is a shortcut for `--transform`, see method3* (VGA-0 below DP-3) ``` xrandr \ --output DP-3 --mode 1280x800 --scale 1x1 --pos 0x0 --fb 2880x2600 \ --output VGA-0 --mode 1440x900 --scale 2x2 --pos 0x800 ``` or: ``` xrandr \ --output DP-3 --mode 1280x800 --pos 0x0 --fb 2880x2600 \ --output VGA-0 --mode 1440x900 --scale-from 2880x1800 --pos 0x800 ``` FrameBuffer size calculation: ``` width = max(1280,1440*2) = 2880 height = 800+900*2 = 2600 ``` Results: * nvidia xrandr scale screenshot [![nvidia xrandr scale screenshot](https://i.stack.imgur.com/bMfka.jpg)](https://i.stack.imgur.com/bMfka.jpg) * nvidia xrandr scale photo [![nvidia xrandr scale photo](https://i.stack.imgur.com/ZfLTd.jpg)](https://i.stack.imgur.com/ZfLTd.jpg) Method 2: `nvidia-settings` View Port In/Out -------------------------------------------- *Note, doesn't work well. `nvidia-settings` does not change frame-buffer to the required size as in `xrandr` command.* It seems a bug (kind of, `nvidia` has its own FB), need more research. Tried to replicate `xrandr` setup directly using `nvidia-settings` (I used xrandr from method1, marked down nvidia setting, reset settings, then used nvidia-settings directly): 1. `gksu nvidia-settings` → X Server Display Configuration 2. Select external monitor → advanced... 3. Make *ViewPortIn* & *Panning* double of *ViewPortOut* (which is the same as original resolution) 4. Leave internal monitor unchanged then *Apply* Example: * [Internal monitor nvidia settings](https://i.stack.imgur.com/CtJeC.png) ``` Position: +0+0 ViewPortIn: 1280x800 ViewPortOut: 1280x800+0+0 Panning: 1280x800 ``` * [External monitor nvidia settings](https://i.stack.imgur.com/01eEa.png) ``` Position: +1280+0 (rightof) or +0+800 (below) ViewPortIn: 2880x1800 ViewPortOut: 1440x900+0+0 Panning: 2880x1800 ``` Results: Notice the mouse pointer, it can reach all edges of the 2nd monitor even it only draws the top left quarter. * nvidia-settings viewportin screenshot [![nvidia-settings viewportin screenshot](https://i.stack.imgur.com/Rbc6N.jpg)](https://i.stack.imgur.com/Rbc6N.jpg) * nvidia-settings viewportin photo [![nvidia-settings viewportin photo](https://i.stack.imgur.com/CQP6D.jpg)](https://i.stack.imgur.com/CQP6D.jpg) **Update:** Well, I could finally get a workaround trick. Add 1px to the width or height of panning (`Panning`) ``` Panning: 2881x1800 or 2880x1801 ``` New Results: I can't explain this, just the background is corrupted if i use below, otherwise every thing seems ok. * nvidia-settings viewportin with panning trick screenshot [![nvidia-settings viewportin with panning trick screenshot - below](https://i.stack.imgur.com/NTz0h.png)](https://i.stack.imgur.com/NTz0h.png) lowered the color quality of above picture to make less then 2MB imgur limit [![nvidia-settings viewportin with panning trick screenshot - right of](https://i.stack.imgur.com/G10Yf.jpg)](https://i.stack.imgur.com/G10Yf.jpg) * nvidia -settings viewportin with panning trick photo [![nvidia-settings viewportin with panning trick photo - below](https://i.stack.imgur.com/jawMN.jpg)](https://i.stack.imgur.com/jawMN.jpg) [![nvidia-settings viewportin with panning trick photo - right of](https://i.stack.imgur.com/FdUyv.jpg)](https://i.stack.imgur.com/FdUyv.jpg) Method 3: `xrandr --output .. --transform "H,0,0,0,V,0,0,0,1"` -------------------------------------------------------------- *Note, works fine for me, same as method1* (VGA-0 right of DP-3) ``` xrandr \ --output DP-3 -primary --mode 1280x800 --pos 0x0 --transform "1,0,0,0,1,0,0,0,1" --fb 4160x1800 \ --output VGA-0 --mode 1440x900 --transform "2,0,0,0,2,0,0,0,1" --right-of DP-3 ``` FrameBuffer size calculation: ``` width = 1280+1440*2 = 4160 height = max(800,900*2) = 1800 ``` Results: * nvidia xrandr transform screenshot [![nvidia xrandr transform screenshot](https://i.stack.imgur.com/tbDD0.jpg)](https://i.stack.imgur.com/tbDD0.jpg) * nvidia xrandr transform photo [![nvidia xrandr transform photo](https://i.stack.imgur.com/8yEPb.jpg)](https://i.stack.imgur.com/8yEPb.jpg)
I found a simple solution. I am running Ubuntu 18.04. This is my xrandr output: ``` light@light:~$ xrandr Screen 0: minimum 8 x 8, current 5760 x 2160, maximum 32767 x 32767 HDMI-0 connected 1920x1080+3840+92 (normal left inverted right x axis y axis) 476mm x 268mm 1920x1080 60.00*+ 59.94 50.00 1680x1050 59.95 1600x900 60.00 1440x900 59.89 1280x1024 60.02 1280x800 59.81 1280x720 60.00 59.94 50.00 1024x768 60.00 800x600 60.32 720x576 50.00 720x480 59.94 640x480 59.94 59.93 DP-0 connected primary 3840x2160+0+0 (normal left inverted right x axis y axis) 382mm x 214mm 3840x2160 60.02*+ 48.02 DP-1 disconnected (normal left inverted right x axis y axis) DP-2 disconnected (normal left inverted right x axis y axis) DP-1-1 disconnected (normal left inverted right x axis y axis) HDMI-1-1 disconnected (normal left inverted right x axis y axis) DP-1-2 disconnected (normal left inverted right x axis y axis) HDMI-1-2 disconnected (normal left inverted right x axis y axis) light@light:~$ ``` I simply ran the below command and it worked perfectly: ``` light@light:~$ xrandr --output HDMI-0 --scale 2x2 --mode 1920x1080 light@light:~$ ``` `--scale 2x2` implies make everything on external screen twice as small. `--mode` is the resolution you want. That's it
28,630,360
I want to read a number as a String, and split its characters to an integer array, and find the sum of it's digits by looping through that integers array. This is my code so far: ``` public static void main(String[] args) { Scanner S = new Scanner(System.in); String Number = S.next(); int counterEnd = Number.length(); int sum = 0 ; for ( int i = 0 ; i < counterEnd ; i++) { sum += sum + (Number.charAt(i)); } System.out.println(sum); } ``` Unfortunately, this code prints the sum of ASCII not the digits.
2015/02/20
['https://Stackoverflow.com/questions/28630360', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3301836/']
You can subtract the `'0'` character (i.e. `'1' - '0'` is `49 - 48` = `1`): ``` sum += Number.charAt(i) - '0'; ```
You could, has @August suggested, substract the character `'0'` to obtain the numeric value of the character (I find this approach kind of hackish). Or you can use [`Character.getNumericValue`](http://docs.oracle.com/javase/7/docs/api/java/lang/Character.html#getNumericValue(char)) to achieve this: ``` sum += Character.getNumericValue(Number.charAt(i)); //note it's sum += theDigit; not sum += sum + theDigit ``` You might also want to look at the enhanced for loop, as you basically don't need the index here: ``` for(char c : Number.toCharArray()) { sum += Character.getNumericValue(c); } ``` As of Java 8 you could also do it like this: ``` int sum = Number.chars().map(Character::getNumericValue).sum(); ``` It basically gets a `Stream` of the characters in the `String`, map each character to its corresponding numeric value and sum them.
28,630,360
I want to read a number as a String, and split its characters to an integer array, and find the sum of it's digits by looping through that integers array. This is my code so far: ``` public static void main(String[] args) { Scanner S = new Scanner(System.in); String Number = S.next(); int counterEnd = Number.length(); int sum = 0 ; for ( int i = 0 ; i < counterEnd ; i++) { sum += sum + (Number.charAt(i)); } System.out.println(sum); } ``` Unfortunately, this code prints the sum of ASCII not the digits.
2015/02/20
['https://Stackoverflow.com/questions/28630360', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3301836/']
You can subtract the `'0'` character (i.e. `'1' - '0'` is `49 - 48` = `1`): ``` sum += Number.charAt(i) - '0'; ```
``` sum+= Integer.parseInt(String.valueOf(Number.charAt(i))); ```
28,630,360
I want to read a number as a String, and split its characters to an integer array, and find the sum of it's digits by looping through that integers array. This is my code so far: ``` public static void main(String[] args) { Scanner S = new Scanner(System.in); String Number = S.next(); int counterEnd = Number.length(); int sum = 0 ; for ( int i = 0 ; i < counterEnd ; i++) { sum += sum + (Number.charAt(i)); } System.out.println(sum); } ``` Unfortunately, this code prints the sum of ASCII not the digits.
2015/02/20
['https://Stackoverflow.com/questions/28630360', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3301836/']
You can subtract the `'0'` character (i.e. `'1' - '0'` is `49 - 48` = `1`): ``` sum += Number.charAt(i) - '0'; ```
You can do it like this: ``` public static void main(String[] args) { Scanner S = new Scanner(System.in); String n = S.next(); int sum = 0; for (int i = 0; i < n.length(); i++) { sum += Integer.parseInt(n.substring(i, i+1)); } System.out.println(sum); } ``` Note: Replacing the body of the for loop with: ``` int offset = (n.substring(i, i+1).equals("-")) ? 1 : 0; sum += Integer.parseInt(n.substring(i, i+1+offset)); i+=offset; ``` Will allow the program to take negative numbers. Ex: Inputting ``` -24 ``` Would return a positive 2.
28,630,360
I want to read a number as a String, and split its characters to an integer array, and find the sum of it's digits by looping through that integers array. This is my code so far: ``` public static void main(String[] args) { Scanner S = new Scanner(System.in); String Number = S.next(); int counterEnd = Number.length(); int sum = 0 ; for ( int i = 0 ; i < counterEnd ; i++) { sum += sum + (Number.charAt(i)); } System.out.println(sum); } ``` Unfortunately, this code prints the sum of ASCII not the digits.
2015/02/20
['https://Stackoverflow.com/questions/28630360', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3301836/']
You could, has @August suggested, substract the character `'0'` to obtain the numeric value of the character (I find this approach kind of hackish). Or you can use [`Character.getNumericValue`](http://docs.oracle.com/javase/7/docs/api/java/lang/Character.html#getNumericValue(char)) to achieve this: ``` sum += Character.getNumericValue(Number.charAt(i)); //note it's sum += theDigit; not sum += sum + theDigit ``` You might also want to look at the enhanced for loop, as you basically don't need the index here: ``` for(char c : Number.toCharArray()) { sum += Character.getNumericValue(c); } ``` As of Java 8 you could also do it like this: ``` int sum = Number.chars().map(Character::getNumericValue).sum(); ``` It basically gets a `Stream` of the characters in the `String`, map each character to its corresponding numeric value and sum them.
``` sum+= Integer.parseInt(String.valueOf(Number.charAt(i))); ```
28,630,360
I want to read a number as a String, and split its characters to an integer array, and find the sum of it's digits by looping through that integers array. This is my code so far: ``` public static void main(String[] args) { Scanner S = new Scanner(System.in); String Number = S.next(); int counterEnd = Number.length(); int sum = 0 ; for ( int i = 0 ; i < counterEnd ; i++) { sum += sum + (Number.charAt(i)); } System.out.println(sum); } ``` Unfortunately, this code prints the sum of ASCII not the digits.
2015/02/20
['https://Stackoverflow.com/questions/28630360', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3301836/']
You could, has @August suggested, substract the character `'0'` to obtain the numeric value of the character (I find this approach kind of hackish). Or you can use [`Character.getNumericValue`](http://docs.oracle.com/javase/7/docs/api/java/lang/Character.html#getNumericValue(char)) to achieve this: ``` sum += Character.getNumericValue(Number.charAt(i)); //note it's sum += theDigit; not sum += sum + theDigit ``` You might also want to look at the enhanced for loop, as you basically don't need the index here: ``` for(char c : Number.toCharArray()) { sum += Character.getNumericValue(c); } ``` As of Java 8 you could also do it like this: ``` int sum = Number.chars().map(Character::getNumericValue).sum(); ``` It basically gets a `Stream` of the characters in the `String`, map each character to its corresponding numeric value and sum them.
You can do it like this: ``` public static void main(String[] args) { Scanner S = new Scanner(System.in); String n = S.next(); int sum = 0; for (int i = 0; i < n.length(); i++) { sum += Integer.parseInt(n.substring(i, i+1)); } System.out.println(sum); } ``` Note: Replacing the body of the for loop with: ``` int offset = (n.substring(i, i+1).equals("-")) ? 1 : 0; sum += Integer.parseInt(n.substring(i, i+1+offset)); i+=offset; ``` Will allow the program to take negative numbers. Ex: Inputting ``` -24 ``` Would return a positive 2.
35,994,855
I have a dictionary of dictionary as below: ``` ls = [{'0': {'1': '1','2': '0.5','3': '1'},'1': {'0': '0.2','2': '1','3': '0.8'},}] ``` I would like to select k-largest values with their keys for each key of dictionary (ls). I have written below commands. It just gives me the k-largest keys without their values. **Python Code:** ``` import heapq k=2 for dic in ls: for key in dic: print(heapq.nlargest(k, dic[key], key=dic[key].get)) ``` **Output** ``` ['2', '3'] ['3', '1'] ``` I need to have value of each selected key.
2016/03/14
['https://Stackoverflow.com/questions/35994855', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6062233/']
* First of all, I just wanted to check why you have `ls = [{'0': {'1': '1','2': '0.5','3': '1'},'1': {'0': '0.2','2': '1','3': '0.8'},}]` This is a list containing a dict, which doesn't match your description in the question. * Here is a solution that uses dict comprehensions that should give you what you want :) ``` def get_n_largest_vals(n, d): x = {key: heapq.nlargest(len, map(int, d[key])) for key in d} return {key: map(str, x[key]) for key in x} ``` Here it is being used for your problem: ``` ls = [{'0': {'1': '1','2': '0.5','3': '1'},'1': {'0': '0.2','2': '1','3': '0.8'},}] d = ls[0] get_n_largest_vals(2, d) >>> {'0': ['3', '2'], '1': ['3', '2']} ```
How about: ``` from operator import itemgetter for d in ls: for key, d2 in d.items(): print(dict(heapq.nlargest(k, d2.items(), key=itemgetter(1)))) ``` Notice that your *values* are still *strings* so they'd be lexically ordered, which is not what you want, because `'2' > 12'` And the dictionary is not ordered!
239
Is it acceptable to ask **fitness equipment** related questions on Fitness.SE? I'm specifically referring to my treadmill and my question would be along the lines of *why does my treadmill do X at certain speeds*? Looking at the [FAQ](https://fitness.stackexchange.com/faq), I see that **gear and gadgets used during exercise** is fair game but I suspect this question may be off topic. Obviously I haven't asked it yet on the chance it will be closed as off-topic, hence why I don't have anything to link to.
2012/01/13
['https://fitness.meta.stackexchange.com/questions/239', 'https://fitness.meta.stackexchange.com', 'https://fitness.meta.stackexchange.com/users/2698/']
Our [faq](https://fitness.stackexchange.com/faq) states "gear and gadgets used during exercise" is on-topic. Presumably, as I said in [my comment](https://fitness.meta.stackexchange.com/questions/239/questions-about-fitness-equipment#comment459_239) on your question, a question about fitness equipment should be on-topic. Recommendations are debatable and might be closed as "Not Constructive" but are not entirely off-topic. Your question of, "Why does my treadmill do X at certain speeds?" sounds like it is fair game for the site. Without knowing what your question exactly is, as Ivo [pointed out](https://fitness.meta.stackexchange.com/questions/239/questions-about-fitness-equipment#comment457_239), (and since you made your meta post, you don't appear to have posted it), it's not as clear as to whether it is on-topic or not.
This question is similar to asking questions on SO related to specific IDEs, rather than the code generated by them. It seems that on SO these questions are acceptable [[1]](https://stackoverflow.com/questions/tagged/eclipse)[[2]](https://stackoverflow.com/questions/tagged/xcode)[[3]](https://stackoverflow.com/questions/tagged/visual-studio), so I suggest that it would be appropriate here as well. Simply tag them "fitness-equipment" or the like.
239
Is it acceptable to ask **fitness equipment** related questions on Fitness.SE? I'm specifically referring to my treadmill and my question would be along the lines of *why does my treadmill do X at certain speeds*? Looking at the [FAQ](https://fitness.stackexchange.com/faq), I see that **gear and gadgets used during exercise** is fair game but I suspect this question may be off topic. Obviously I haven't asked it yet on the chance it will be closed as off-topic, hence why I don't have anything to link to.
2012/01/13
['https://fitness.meta.stackexchange.com/questions/239', 'https://fitness.meta.stackexchange.com', 'https://fitness.meta.stackexchange.com/users/2698/']
This question is similar to asking questions on SO related to specific IDEs, rather than the code generated by them. It seems that on SO these questions are acceptable [[1]](https://stackoverflow.com/questions/tagged/eclipse)[[2]](https://stackoverflow.com/questions/tagged/xcode)[[3]](https://stackoverflow.com/questions/tagged/visual-studio), so I suggest that it would be appropriate here as well. Simply tag them "fitness-equipment" or the like.
Shopping recommendations have typically been off topic. The [stackexchange blog post](http://blog.stackoverflow.com/2010/11/qa-is-hard-lets-go-shopping/) defines how they should be rephrased: > > Here’s one way to ask: > > > Q: What’s the best low light point-and-shoot camera? > > > A: Canon S90 and Lumix LX3. > > > Here’s another way to ask: > > > Q: How do I tell which point-and-shoot cameras take good low light > photos? > > > A: I strongly recommend looking for something with > > > a fast lens (2.0 at least) reasonable ISO handling (at least 400, but > preferably 800) the biggest sensor available The sum of these factors > are really critical for low light situations. > > > From: <http://blog.stackoverflow.com/2010/11/qa-is-hard-lets-go-shopping/>
239
Is it acceptable to ask **fitness equipment** related questions on Fitness.SE? I'm specifically referring to my treadmill and my question would be along the lines of *why does my treadmill do X at certain speeds*? Looking at the [FAQ](https://fitness.stackexchange.com/faq), I see that **gear and gadgets used during exercise** is fair game but I suspect this question may be off topic. Obviously I haven't asked it yet on the chance it will be closed as off-topic, hence why I don't have anything to link to.
2012/01/13
['https://fitness.meta.stackexchange.com/questions/239', 'https://fitness.meta.stackexchange.com', 'https://fitness.meta.stackexchange.com/users/2698/']
Our [faq](https://fitness.stackexchange.com/faq) states "gear and gadgets used during exercise" is on-topic. Presumably, as I said in [my comment](https://fitness.meta.stackexchange.com/questions/239/questions-about-fitness-equipment#comment459_239) on your question, a question about fitness equipment should be on-topic. Recommendations are debatable and might be closed as "Not Constructive" but are not entirely off-topic. Your question of, "Why does my treadmill do X at certain speeds?" sounds like it is fair game for the site. Without knowing what your question exactly is, as Ivo [pointed out](https://fitness.meta.stackexchange.com/questions/239/questions-about-fitness-equipment#comment457_239), (and since you made your meta post, you don't appear to have posted it), it's not as clear as to whether it is on-topic or not.
Shopping recommendations have typically been off topic. The [stackexchange blog post](http://blog.stackoverflow.com/2010/11/qa-is-hard-lets-go-shopping/) defines how they should be rephrased: > > Here’s one way to ask: > > > Q: What’s the best low light point-and-shoot camera? > > > A: Canon S90 and Lumix LX3. > > > Here’s another way to ask: > > > Q: How do I tell which point-and-shoot cameras take good low light > photos? > > > A: I strongly recommend looking for something with > > > a fast lens (2.0 at least) reasonable ISO handling (at least 400, but > preferably 800) the biggest sensor available The sum of these factors > are really critical for low light situations. > > > From: <http://blog.stackoverflow.com/2010/11/qa-is-hard-lets-go-shopping/>
14,074,731
Is it valid HTML to use IRIs containing non-ASCII characters as attribute values (e.g. for `href` attributes) instead of URIs? Are there any differences among the HTML flavors (HTML and XHTML, 4 and 5)? At least [RFC 3986](https://www.rfc-editor.org/rfc/rfc3986#page-16) seems to imply that it isn't. I realize that it would probably be safer (regarding older and IRI-unaware software) to use percent encoding, but I'm looking for a definitive answer with regards to the standard. So far, I've done some tests with the [W3C validator](http://validator.w3.org/), and unescaped unicode characters in URIs don't trigger any warnings or errors with HTML 4/5 and XHTML 4/5 doctypes (but of course the absence of error messages doesn't imply the absence of errors). At least chrome also supports raw UTF-8 IRIs, but percent-escapes them before firing an HTTP request. Also, my web server (lighttpd) seems to support UTF-8 characters in their percent-encoded as well as in unencoded form in an HTTP request.
2012/12/28
['https://Stackoverflow.com/questions/14074731', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1016939/']
HTML 4.01 is straightforward enough. Different attributes have different rules as to what they can contain, but if we're dealing with the href attribute on an `<a>` element, then the [HTML 4 spec, section B.2.1 Non-ASCII characters in URI attribute values](http://www.w3.org/TR/html4/appendix/notes.html#non-ascii-chars) says: > > ... the following href value is illegal: > > > `<A href="http://foo.org/Håkon">...</A>` > > > HTML5 is different. It says [IRIs are valid providing they comply with some additional conditions.](http://www.w3.org/html/wg/drafts/html/CR/infrastructure.html#valid-url) > > A URL is a valid URL if at least one of the following conditions > holds: > > > * The URL is a valid URI reference [RFC3986]. > * The URL is a valid IRI reference and it has no query component. [RFC3987] > * The URL is a valid IRI reference and its query component contains no unescaped non-ASCII characters. [RFC3987] > * The URL is a valid IRI reference and the character encoding of the URL's Document is UTF-8 or a UTF-16 encoding. [RFC3987] > > > XHTML 1.x follows the same rules as HTML 4.01. XHTML5 is the same as HTML5.
When in doubt, read the official HTML specs for definitive answers. HTML 4 does not support IRIs at all. They must be encoded as URIs per [RFC 3987 Section 3.1](https://www.rfc-editor.org/rfc/rfc3987#section-3.1), or encode non-ASCII URI data as UTF-8 with percent encoding per [HTML4 Section B.2.1](http://www.w3.org/TR/html4/appendix/notes.html#non-ascii-chars) HTML 5 supports both URIs and IRIs in all places where URLs are allowed, per [HTML5 Section 2.6](http://www.w3.org/html/wg/drafts/html/CR/infrastructure.html#urls).
3,428,999
Prove $\sin(\sqrt x)$ is not periodic. My wrong assumption was non-periodicity is due to the injectivity of the square root, but, then this would work for any positive real number, but it doesn't, and $\sin(x^2)$ isn't periodic either, so injectivity fails. I find this example more interesting because it is defined on the interval $[0,+\infty)$ so it can't be periodic on the interval $(-\infty,0).$ On the other hand, $\;\sin\left(\sqrt{x}\right)\;=\sin\left(\sqrt{x+\tau}\right)$ seems hopeless. How does composition behave in general when talking about periodicity? Our assistant said the answer lays in irrationality in examples of this kind: $\sin\left(\sqrt{2}x\right),$ but it seems clumsy, incomplete and too intuitive to claim there is no common multiple halfway the solution... At some point I get some expression I don't know what to do with. Also, what does almost periodic in English mean? Are constants, signum, Dirichlet's and Moebius function almost periodic? as far as I'm concerned, they don't have the least period? Or does it refer to floor and ceiling?
2019/11/09
['https://math.stackexchange.com/questions/3428999', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/721644/']
Hint: Consider at what points $\sin(\sqrt x)$ is equal to $0$. If the function were periodic, could those points get further and further apart?
Let us look at zeroes of $$f(x) = \sin \sqrt x $$ The zeroes of this function are $$x=0, x= \pi ^2, x=4\pi ^2, x=9\pi ^2,....$$ which are not equi-distance. For a periodic function we have to have $f(x+P)=f(x)$ for some period $P$ so if you get $ f(x)=0$ , you have to have $$f(x+P)=f(x+2P)=... =0$$ that is zeroes happen at equal distances.
3,428,999
Prove $\sin(\sqrt x)$ is not periodic. My wrong assumption was non-periodicity is due to the injectivity of the square root, but, then this would work for any positive real number, but it doesn't, and $\sin(x^2)$ isn't periodic either, so injectivity fails. I find this example more interesting because it is defined on the interval $[0,+\infty)$ so it can't be periodic on the interval $(-\infty,0).$ On the other hand, $\;\sin\left(\sqrt{x}\right)\;=\sin\left(\sqrt{x+\tau}\right)$ seems hopeless. How does composition behave in general when talking about periodicity? Our assistant said the answer lays in irrationality in examples of this kind: $\sin\left(\sqrt{2}x\right),$ but it seems clumsy, incomplete and too intuitive to claim there is no common multiple halfway the solution... At some point I get some expression I don't know what to do with. Also, what does almost periodic in English mean? Are constants, signum, Dirichlet's and Moebius function almost periodic? as far as I'm concerned, they don't have the least period? Or does it refer to floor and ceiling?
2019/11/09
['https://math.stackexchange.com/questions/3428999', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/721644/']
Hint: Consider at what points $\sin(\sqrt x)$ is equal to $0$. If the function were periodic, could those points get further and further apart?
Let $f$ be periodic with period $T$. Then for $f(g(u))$ to be periodic with period $U$, we need $$g(u+U)=g(u)+kT$$ for some integer constant $k$. Now if $$h(u):=g(u)-kT\frac uU,$$ $$h(u+U)=g(u+U)-kT\frac{u+U}U=g(u)+kT-kT\frac{u+U}U=h(u)$$ and $h$ is periodic. Finally, $g$ must be of the form $$g(u)=kT\frac uU+h(u)$$ where $h$ is periodic of period $U$. --- E.g. let $f(x)=\{x\}$, which is periodic with period $1$ and let us choose $h(x)=\sin(x)$ (period $2\pi$). We also choose $k=2$ and get $$g(x)=\frac x\pi+\sin(x).$$ This gives us a nice psychedelic function. [![enter image description here](https://i.stack.imgur.com/YLZZs.png)](https://i.stack.imgur.com/YLZZs.png)
536,207
I download a tarball containing only one directory; this directory has a very long name. I desire to change that directory's name once I extract it from the tarball but I prefer another way than `mkdir` with `strip-components 1` and `-C`. I consider `mv` but I prefer to automatically hold the directory's name in a variable in advance; I thought command substitution might help by holding output **in the form of** directory name but I can't see how it can be selective only for a name (or of any particular directory) in the tarball. How is it possible with command substitution or if not, what alternative is possible?
2019/08/19
['https://unix.stackexchange.com/questions/536207', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/-1/']
I'm not sure if I understood your question correctly but I think you're looking for something like this: ``` $ dir="$(tar tf archive.tar | cut -d / -f1 | uniq)" $ echo "$dir" tar-very-long-nime-very-very-long ```
With GNU tar you can use a sed-like expression to transform the file names: ``` tar -xf archive.tar.gz --xform='s,^very_long_name,short,' ``` Read about the whole thing [here](https://www.gnu.org/software/tar/manual/tar.html#SEC115).
536,207
I download a tarball containing only one directory; this directory has a very long name. I desire to change that directory's name once I extract it from the tarball but I prefer another way than `mkdir` with `strip-components 1` and `-C`. I consider `mv` but I prefer to automatically hold the directory's name in a variable in advance; I thought command substitution might help by holding output **in the form of** directory name but I can't see how it can be selective only for a name (or of any particular directory) in the tarball. How is it possible with command substitution or if not, what alternative is possible?
2019/08/19
['https://unix.stackexchange.com/questions/536207', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/-1/']
The following assumes that you are working with an archive in the current directory. ``` tar -x -f "$archivedir.tar" mv "$archivedir" new-name ``` This assumes that the variable `$archivedir` contains the name of the `tar` archive without the `.tar` suffix and that this is also the name of the directory that will be created when extracting the archive. It extracts the archive and renames the created directory. If you have the filename of the `tar` archive in `$tararchive` and if the filename suffix is `.tar` (included in the value of `$tararchive`): ``` tar -x -f "$tararchive" mv "$(basename "$tararchive" .tar)" new-name ``` The `"$(basename "$tararchive" .tar)"` bit could be replaced by `"${tararchive%.tar}"`.
With GNU tar you can use a sed-like expression to transform the file names: ``` tar -xf archive.tar.gz --xform='s,^very_long_name,short,' ``` Read about the whole thing [here](https://www.gnu.org/software/tar/manual/tar.html#SEC115).
17,961,813
I have the following: ``` var catCreyz = function() { console.log('maaaow'); }.call() ``` and when I test its type: ``` typeof catCreyz ``` The result returned is: > > undefined > > > Why?
2013/07/31
['https://Stackoverflow.com/questions/17961813', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1061967/']
[Function.prototype.call](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call) returns what the function being called returns. Your function returns nothing ``` var catCreyz = function() { console.log('maaaow'); }.call() //logs undefined console.log(catCreyz); var result = function() { return "foo"; }.call() //logs foo console.log(result); var myFunc = function() { console.log('maaaow'); } //logs the function console.log(myFunc); ```
Call executes the function, and you're missing a return statement in your function, Javascript does not return the last expression like other languages. You must explicitly return a value, else you get undefined. If you want an instance of catCreyz, then take the call() off the expression.
107,132
we are using custom module for finding shipping charges and **we wrote the list of supported zip codes in below code**. what we need is instead of saving zip codes in code, we want to **save list of zip codes in database**. we saved list of zip codes in backend as below. Now we have to connect this DB to below code, so that only these zip codes should allow to place an order. [![enter image description here](https://i.stack.imgur.com/FR78E.png)](https://i.stack.imgur.com/FR78E.png) ``` <?php class module_Mpperproductshipping_Model_Carrier_LocalDelivery extends Mage_Shipping_Model_Carrier_Abstract { /* Use group alias */ protected $_code = 'mpperproductshipping'; public function collectRates(Mage_Shipping_Model_Rate_Request $request){ $postCode = $request->getDestPostcode(); $restrictedCodes = array( 110001, 110002, ); //restricted values. they can come from anywhere if (!in_array($postCode, $restrictedCodes)) { return false; } $result = Mage::getModel('shipping/rate_result'); /* Edited by vikas_mage */ $postcode=$request->getDestPostcode(); $countrycode=$request->getDestCountry(); $items=$request->getAllItems(); /* End Editing by vikas_mage */ $postcode=str_replace('-', '', $postcode); $shippingdetail=array(); /* one start */ $shippostaldetail=array('countrycode'=>$countrycode,'postalcode'=>$postcode,'items'=>$items); /* one end */ /* tt start - ship charges never work $shippostaldetail=array('countrycode'=>$countrycode,'postalcode'=>$postcode); tt end */ foreach($items as $item) { $proid=$item->getProductId(); $options=$item->getProductOptions(); $mpassignproductId=$options['info_buyRequest']['mpassignproduct_id']; if(!$mpassignproductId) { foreach($item->getOptions() as $option) { $temp=unserialize($option['value']); if($temp['mpassignproduct_id']) { $mpassignproductId=$temp['mpassignproduct_id']; } } } if($mpassignproductId) { $mpassignModel = Mage::getModel('mpassignproduct/mpassignproduct')->load($mpassignproductId); $partner = $mpassignModel->getSellerId(); } else { $collection=Mage::getModel('marketplace/product') ->getCollection()->addFieldToFilter('mageproductid',array('eq'=>$proid)); foreach($collection as $temp) { $partner=$temp->getUserid(); } } $product=Mage::getModel('catalog/product')->load($proid)->getWeight(); $weight=$product*$item->getQty(); if(count($shippingdetail)==0){ array_push($shippingdetail,array('seller_id'=>$partner,'items_weight'=>$weight,'product_name'=>$item->getName(),'qty'=>$item->getQty(),'item_id'=>$item->getId())); }else{ $shipinfoflag=true; $index=0; foreach($shippingdetail as $itemship){ if($itemship['seller_id']==$partner){ $itemship['items_weight']=$itemship['items_weight']+$weight; $itemship['product_name']=$itemship['product_name'].",".$item->getName(); $itemship['item_id']=$itemship['item_id'].",".$item->getId(); $itemship['qty']=$itemship['qty']+$item->getQty(); $shippingdetail[$index]=$itemship; $shipinfoflag=false; } $index++; } if($shipinfoflag==true){ array_push($shippingdetail,array('seller_id'=>$partner,'items_weight'=>$weight,'product_name'=>$item->getName(),'qty'=>$item->getQty(),'item_id'=>$item->getId())); } } } $shippingpricedetail=$this->getShippingPricedetail($shippingdetail,$shippostaldetail); if($shippingpricedetail['errormsg']!==""){ Mage::getSingleton('core/session')->setShippingCustomError($shippingpricedetail['errormsg']); return $result; } /*store shipping in session*/ $shippingAll=Mage::getSingleton('core/session')->getData('shippinginfo'); $shippingAll[$this->_code]=$shippingpricedetail['shippinginfo']; Mage::getSingleton('core/session')->setData('shippinginfo',$shippingAll); $method = Mage::getModel('shipping/rate_result_method'); $method->setCarrier($this->_code); $method->setCarrierTitle(Mage::getStoreConfig('carriers/'.$this->_code.'/title')); /* Use method name */ $method->setMethod($this->_code); $method->setMethodTitle(Mage::getStoreConfig('carriers/'.$this->_code.'/name')); $method->setCost($shippingpricedetail['handlingfee']); $method->setPrice($shippingpricedetail['handlingfee']); $result->append($method); return $result; } public function getShippingPricedetail($shippingdetail,$shippostaldetail) { $shippinginfo=array(); $handling=0; $session = Mage::getSingleton('checkout/session'); $customerAddress = $session->getQuote()->getShippingAddress(); /* Edited by vikas_boy */ $customerPostCode = $shippostaldetail['postalcode']; $items = $shippostaldetail['items']; /* End Editing by vikas_boy */ /* one */ foreach($shippingdetail as $shipdetail) { $seller = Mage::getModel("customer/customer")->load($shipdetail['seller_id']); $sellerAddress = $seller->getPrimaryShippingAddress(); $distance = $this->getDistanse($sellerAddress->getPostcode(),$customerPostCode); // echo "distance ".$distance;die; $price = 0; $itemsarray=explode(',',$shipdetail['item_id']); foreach($items as $item) { $proid=$item->getProductId(); $options=$item->getProductOptions(); $mpassignproductId=$options['info_buyRequest']['mpassignproduct_id']; if(!$mpassignproductId) { foreach($item->getOptions() as $option) { $temp=unserialize($option['value']); if($temp['mpassignproduct_id']) { $mpassignproductId=$temp['mpassignproduct_id']; } } } if ($item->getHasChildren()){ continue; } $mpshippingcharge = 0; $localDistance = Mage::getStoreConfig('marketplace/mpperproductshipping/local_shipping_distance'); $regionalDistance = Mage::getStoreConfig('marketplace/mpperproductshipping/regional_shipping_distance'); $stateDistance = Mage::getStoreConfig('marketplace/mpperproductshipping/state_shipping_distance'); if(in_array($item->getId(),$itemsarray)) { if($mpassignproductId) { if($distance < $localDistance) { $mpshippingcharge=Mage::getModel('mpassignproduct/mpassignproduct')->load($mpassignproductId)->getLocalShippingCharge(); } elseif($distance > $localDistance && $distance < $regionalDistance) { $mpshippingcharge=Mage::getModel('mpassignproduct/mpassignproduct')->load($mpassignproductId)->getRegionalShippingCharge(); } elseif($distance > $regionalDistance) { $mpshippingcharge=Mage::getModel('mpassignproduct/mpassignproduct')->load($mpassignproductId)->getStateShippingCharge(); } } else { // echo "imte ".$item->getProductId(); if($distance < $localDistance) { $mpshippingcharge=Mage::getModel('catalog/product')->load($item->getProductId())->getMpLocalShippingCharge(); // echo "imte ".$item->getProductId(); // echo "ship ".$mpshippingcharge; } elseif($distance > $localDistance && $distance < $regionalDistance) { $mpshippingcharge=Mage::getModel('catalog/product')->load($item->getProductId())->getMpRegionalShippingCharge(); } elseif($distance > $regionalDistance) { $mpshippingcharge=Mage::getModel('catalog/product')->load($item->getProductId())->getMpStateShippingCharge(); } } /* tt */ // echo "test ".$mpshippingcharge;die; if(!is_numeric($mpshippingcharge)){ $price=$price+floatval($this->getConfigData('defalt_ship_amount')* floatval($item->getQty())); }else{ $price=$price+($mpshippingcharge * floatval($item->getQty())); } /* tt end */ /* one if(floatval($mpshippingcharge)==0){ $price=$price+floatval($this->getConfigData('defalt_ship_amount')); }else{ $price=$price+$mpshippingcharge; } one end */ } } $handling = $handling+$price; $submethod = array(array('method'=>Mage::getStoreConfig('carriers/'.$this->_code.'/title'),'cost'=>$price,'error'=>0)); array_push($shippinginfo,array('seller_id'=>$shipdetail['seller_id'],'methodcode'=>$this->_code,'shipping_ammount'=>$price,'product_name'=>$shipdetail['product_name'],'submethod'=>$submethod,'item_ids'=>$shipdetail['item_id'])); } $msg=""; return array('handlingfee'=>$handling,'shippinginfo'=>$shippinginfo,'errormsg'=>$msg); } /* one end */ /* tt start */ private function getDistanse($origin,$destination) { $url = "http://maps.googleapis.com/maps/api/distancematrix/json?origins=".$origin.",india&destinations=".$destination.",india&mode=driving&language=en-EN&sensor=false"; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_PROXYPORT, 3128); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); $response = curl_exec($ch); curl_close($ch); $response_all = json_decode($response); $distance = $response_all->rows[0]->elements[0]->distance->value / 1000; if($distance==0){ $zips = array( $origin,$destination // ... etc ... ); $geocoded = array(); $serviceUrl = "http://maps.googleapis.com/maps/api/geocode/json?components=postal_code:%s&sensor=false"; $curl = curl_init(); foreach ($zips as $zip) { curl_setopt($curl, CURLOPT_URL, sprintf($serviceUrl, urlencode($zip))); curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE); $data = json_decode(curl_exec($curl)); $info = curl_getinfo($curl); if ($info['http_code'] != 200) { // Request failed } else if ($data->status !== 'OK') { // Something happened, or there are no results } else { $geocoded[$zip] =$data->results[0]->geometry->location; } } $distance=$this->DistAB($geocoded[$zips[0]]->lat,$geocoded[$zips[0]]->lng,$geocoded[$zips[1]]->lat,$geocoded[$zips[1]]->lng); } return $distance; } /* tt end * / /* tt start */ public function DistAB($lat_a,$lon_a,$lat_b,$lon_b) { $measure_unit = 'kilometers'; $measure_state = false; $measure = 0; $error = ''; $delta_lat = $lat_b - $lat_a ; $delta_lon = $lon_b - $lon_a ; $earth_radius = 6372.795477598; $alpha = $delta_lat/2; $beta = $delta_lon/2; $a = sin(deg2rad($alpha)) * sin(deg2rad($alpha)) + cos(deg2rad($this->lat_a)) * cos(deg2rad($this->lat_b)) * sin(deg2rad($beta)) * sin(deg2rad($beta)) ; $c = asin(min(1, sqrt($a))); $distance = 2*$earth_radius * $c; $distance = round($distance, 4); $measure = $distance; return $measure; } } ```
2016/03/21
['https://magento.stackexchange.com/questions/107132', 'https://magento.stackexchange.com', 'https://magento.stackexchange.com/users/12982/']
Create a module called '**ZipcodeChecker**' **config.xml** is ``` <?xml version="1.0"?> <config> <modules> <SR_ZipcodeChecker> <version>0.0.0.1 </SR_ZipcodeChecker> </modules> <frontend> <routers> <checkout> <args> <modules> <SR_ZipcodeChecker before="Mage_Checkout">SR_ZipcodeChecker_Checkout</SR_ZipcodeChecker> </modules> </args> </checkout> </routers> </frontend> <global> <helpers> <zipcodechecker> <class>SR_ZipcodeChecker_Helper</class> </zipcodechecker> </helpers> </global> </config> ``` Create a controller 'app/code/local/SR/ZipcodeChecker/controllers/Checkout/OnepageController.php' ``` require_once Mage::getModuleDir('controllers', 'Mage_Checkout') . DS . 'OnepageController.php'; class SR_ZipcodeChecker_Checkout_OnepageController extends Mage_Checkout_OnepageController { /** * Perform address validation on checkout billing address. */ public function saveBillingAction() { $address = Mage::app()->getRequest()->getPost('billing', array()); $result = array(); if(isset($address['use_for_shipping']) && ($address['use_for_shipping'])) { $result = Mage::helper('zipcodechecker')->validateZipCode($address); } if (empty($result['error'])) { parent::saveBillingAction(); } else { $this->getResponse()->setHeader('Content-type', 'application/json'); $this->getResponse()->setBody(Mage::helper('core')->jsonEncode($result['error'])); } } /** * Perform address validation on checkout shipping address. */ public function saveShippingAction() { $address = Mage::app()->getRequest()->getPost('shipping', array()); $result = Mage::helper('zipcodechecker')->validateZipCode($address); if (empty($result['error'])) { parent::saveShippingAction(); } else { $this->getResponse()->setHeader('Content-type', 'application/json'); $this->getResponse()->setBody(Mage::helper('core')->jsonEncode($result['error'])); } } } ``` Create a helper for performing global action 'app/code/local/SR/ZipcodeChecker/Helper/Data.php' ``` class SR_ZipcodeChecker_Helper_Data extends Mage_Core_Helper_Abstract { protected $zipCode = array('90001', '90004'); public function validateZipCode($address) { $result = array(); if(isset($address['postcode']) && $address['postcode']) { if(!(in_array($address['postcode'], $this->zipCode))) { $result['error'] = 'Zipcode not allowed'; } } else { $result['error'] = 'Zipcode not allowed'; } return $result; } } ```
If you want receive data from the your module field (`textarea` in system config), you could use next solution: ``` public function getRestrictedZipCodes() { // Replace 'test/module/zips' with the original path from the system.xml file $restrictedCodesString = Mage::getStoreConfig('test/module/zips'); $restrictedCodesString = preg_replace('/\s+/', '', $restrictedCodesString); $restrictedCodes = explode(',', $restrictedCodesString); if (!empty($restrictedCodes) && is_array($restrictedCodes)) { array_walk($restrictedCodes, 'trim'); $restrictedCodes = array_filter($restrictedCodes); } return $restrictedCodes; } ``` Update code: ``` public function collectRates(Mage_Shipping_Model_Rate_Request $request) { $postCode = $request->getDestPostcode(); $restrictedCodes = $this->getRestrictedZipCodes(); //changes if (!in_array($postCode, $restrictedCodes)) { return false; } // other code..... ``` Test field: [![Test field in system configuration](https://i.stack.imgur.com/aqBR1.png)](https://i.stack.imgur.com/aqBR1.png) Result: [![Result in debug](https://i.stack.imgur.com/12vRZ.png)](https://i.stack.imgur.com/12vRZ.png) If you want get your zip codes anywhere you can always use `getRestrictedZipCodes()` method. You can find path to the field in the *system.xml* file of your module (in the *etc* directory) If you want to transfer your zip code values elsewhere in the database, you will need to create a separate collection and source model for your zip codes.
107,132
we are using custom module for finding shipping charges and **we wrote the list of supported zip codes in below code**. what we need is instead of saving zip codes in code, we want to **save list of zip codes in database**. we saved list of zip codes in backend as below. Now we have to connect this DB to below code, so that only these zip codes should allow to place an order. [![enter image description here](https://i.stack.imgur.com/FR78E.png)](https://i.stack.imgur.com/FR78E.png) ``` <?php class module_Mpperproductshipping_Model_Carrier_LocalDelivery extends Mage_Shipping_Model_Carrier_Abstract { /* Use group alias */ protected $_code = 'mpperproductshipping'; public function collectRates(Mage_Shipping_Model_Rate_Request $request){ $postCode = $request->getDestPostcode(); $restrictedCodes = array( 110001, 110002, ); //restricted values. they can come from anywhere if (!in_array($postCode, $restrictedCodes)) { return false; } $result = Mage::getModel('shipping/rate_result'); /* Edited by vikas_mage */ $postcode=$request->getDestPostcode(); $countrycode=$request->getDestCountry(); $items=$request->getAllItems(); /* End Editing by vikas_mage */ $postcode=str_replace('-', '', $postcode); $shippingdetail=array(); /* one start */ $shippostaldetail=array('countrycode'=>$countrycode,'postalcode'=>$postcode,'items'=>$items); /* one end */ /* tt start - ship charges never work $shippostaldetail=array('countrycode'=>$countrycode,'postalcode'=>$postcode); tt end */ foreach($items as $item) { $proid=$item->getProductId(); $options=$item->getProductOptions(); $mpassignproductId=$options['info_buyRequest']['mpassignproduct_id']; if(!$mpassignproductId) { foreach($item->getOptions() as $option) { $temp=unserialize($option['value']); if($temp['mpassignproduct_id']) { $mpassignproductId=$temp['mpassignproduct_id']; } } } if($mpassignproductId) { $mpassignModel = Mage::getModel('mpassignproduct/mpassignproduct')->load($mpassignproductId); $partner = $mpassignModel->getSellerId(); } else { $collection=Mage::getModel('marketplace/product') ->getCollection()->addFieldToFilter('mageproductid',array('eq'=>$proid)); foreach($collection as $temp) { $partner=$temp->getUserid(); } } $product=Mage::getModel('catalog/product')->load($proid)->getWeight(); $weight=$product*$item->getQty(); if(count($shippingdetail)==0){ array_push($shippingdetail,array('seller_id'=>$partner,'items_weight'=>$weight,'product_name'=>$item->getName(),'qty'=>$item->getQty(),'item_id'=>$item->getId())); }else{ $shipinfoflag=true; $index=0; foreach($shippingdetail as $itemship){ if($itemship['seller_id']==$partner){ $itemship['items_weight']=$itemship['items_weight']+$weight; $itemship['product_name']=$itemship['product_name'].",".$item->getName(); $itemship['item_id']=$itemship['item_id'].",".$item->getId(); $itemship['qty']=$itemship['qty']+$item->getQty(); $shippingdetail[$index]=$itemship; $shipinfoflag=false; } $index++; } if($shipinfoflag==true){ array_push($shippingdetail,array('seller_id'=>$partner,'items_weight'=>$weight,'product_name'=>$item->getName(),'qty'=>$item->getQty(),'item_id'=>$item->getId())); } } } $shippingpricedetail=$this->getShippingPricedetail($shippingdetail,$shippostaldetail); if($shippingpricedetail['errormsg']!==""){ Mage::getSingleton('core/session')->setShippingCustomError($shippingpricedetail['errormsg']); return $result; } /*store shipping in session*/ $shippingAll=Mage::getSingleton('core/session')->getData('shippinginfo'); $shippingAll[$this->_code]=$shippingpricedetail['shippinginfo']; Mage::getSingleton('core/session')->setData('shippinginfo',$shippingAll); $method = Mage::getModel('shipping/rate_result_method'); $method->setCarrier($this->_code); $method->setCarrierTitle(Mage::getStoreConfig('carriers/'.$this->_code.'/title')); /* Use method name */ $method->setMethod($this->_code); $method->setMethodTitle(Mage::getStoreConfig('carriers/'.$this->_code.'/name')); $method->setCost($shippingpricedetail['handlingfee']); $method->setPrice($shippingpricedetail['handlingfee']); $result->append($method); return $result; } public function getShippingPricedetail($shippingdetail,$shippostaldetail) { $shippinginfo=array(); $handling=0; $session = Mage::getSingleton('checkout/session'); $customerAddress = $session->getQuote()->getShippingAddress(); /* Edited by vikas_boy */ $customerPostCode = $shippostaldetail['postalcode']; $items = $shippostaldetail['items']; /* End Editing by vikas_boy */ /* one */ foreach($shippingdetail as $shipdetail) { $seller = Mage::getModel("customer/customer")->load($shipdetail['seller_id']); $sellerAddress = $seller->getPrimaryShippingAddress(); $distance = $this->getDistanse($sellerAddress->getPostcode(),$customerPostCode); // echo "distance ".$distance;die; $price = 0; $itemsarray=explode(',',$shipdetail['item_id']); foreach($items as $item) { $proid=$item->getProductId(); $options=$item->getProductOptions(); $mpassignproductId=$options['info_buyRequest']['mpassignproduct_id']; if(!$mpassignproductId) { foreach($item->getOptions() as $option) { $temp=unserialize($option['value']); if($temp['mpassignproduct_id']) { $mpassignproductId=$temp['mpassignproduct_id']; } } } if ($item->getHasChildren()){ continue; } $mpshippingcharge = 0; $localDistance = Mage::getStoreConfig('marketplace/mpperproductshipping/local_shipping_distance'); $regionalDistance = Mage::getStoreConfig('marketplace/mpperproductshipping/regional_shipping_distance'); $stateDistance = Mage::getStoreConfig('marketplace/mpperproductshipping/state_shipping_distance'); if(in_array($item->getId(),$itemsarray)) { if($mpassignproductId) { if($distance < $localDistance) { $mpshippingcharge=Mage::getModel('mpassignproduct/mpassignproduct')->load($mpassignproductId)->getLocalShippingCharge(); } elseif($distance > $localDistance && $distance < $regionalDistance) { $mpshippingcharge=Mage::getModel('mpassignproduct/mpassignproduct')->load($mpassignproductId)->getRegionalShippingCharge(); } elseif($distance > $regionalDistance) { $mpshippingcharge=Mage::getModel('mpassignproduct/mpassignproduct')->load($mpassignproductId)->getStateShippingCharge(); } } else { // echo "imte ".$item->getProductId(); if($distance < $localDistance) { $mpshippingcharge=Mage::getModel('catalog/product')->load($item->getProductId())->getMpLocalShippingCharge(); // echo "imte ".$item->getProductId(); // echo "ship ".$mpshippingcharge; } elseif($distance > $localDistance && $distance < $regionalDistance) { $mpshippingcharge=Mage::getModel('catalog/product')->load($item->getProductId())->getMpRegionalShippingCharge(); } elseif($distance > $regionalDistance) { $mpshippingcharge=Mage::getModel('catalog/product')->load($item->getProductId())->getMpStateShippingCharge(); } } /* tt */ // echo "test ".$mpshippingcharge;die; if(!is_numeric($mpshippingcharge)){ $price=$price+floatval($this->getConfigData('defalt_ship_amount')* floatval($item->getQty())); }else{ $price=$price+($mpshippingcharge * floatval($item->getQty())); } /* tt end */ /* one if(floatval($mpshippingcharge)==0){ $price=$price+floatval($this->getConfigData('defalt_ship_amount')); }else{ $price=$price+$mpshippingcharge; } one end */ } } $handling = $handling+$price; $submethod = array(array('method'=>Mage::getStoreConfig('carriers/'.$this->_code.'/title'),'cost'=>$price,'error'=>0)); array_push($shippinginfo,array('seller_id'=>$shipdetail['seller_id'],'methodcode'=>$this->_code,'shipping_ammount'=>$price,'product_name'=>$shipdetail['product_name'],'submethod'=>$submethod,'item_ids'=>$shipdetail['item_id'])); } $msg=""; return array('handlingfee'=>$handling,'shippinginfo'=>$shippinginfo,'errormsg'=>$msg); } /* one end */ /* tt start */ private function getDistanse($origin,$destination) { $url = "http://maps.googleapis.com/maps/api/distancematrix/json?origins=".$origin.",india&destinations=".$destination.",india&mode=driving&language=en-EN&sensor=false"; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_PROXYPORT, 3128); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); $response = curl_exec($ch); curl_close($ch); $response_all = json_decode($response); $distance = $response_all->rows[0]->elements[0]->distance->value / 1000; if($distance==0){ $zips = array( $origin,$destination // ... etc ... ); $geocoded = array(); $serviceUrl = "http://maps.googleapis.com/maps/api/geocode/json?components=postal_code:%s&sensor=false"; $curl = curl_init(); foreach ($zips as $zip) { curl_setopt($curl, CURLOPT_URL, sprintf($serviceUrl, urlencode($zip))); curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE); $data = json_decode(curl_exec($curl)); $info = curl_getinfo($curl); if ($info['http_code'] != 200) { // Request failed } else if ($data->status !== 'OK') { // Something happened, or there are no results } else { $geocoded[$zip] =$data->results[0]->geometry->location; } } $distance=$this->DistAB($geocoded[$zips[0]]->lat,$geocoded[$zips[0]]->lng,$geocoded[$zips[1]]->lat,$geocoded[$zips[1]]->lng); } return $distance; } /* tt end * / /* tt start */ public function DistAB($lat_a,$lon_a,$lat_b,$lon_b) { $measure_unit = 'kilometers'; $measure_state = false; $measure = 0; $error = ''; $delta_lat = $lat_b - $lat_a ; $delta_lon = $lon_b - $lon_a ; $earth_radius = 6372.795477598; $alpha = $delta_lat/2; $beta = $delta_lon/2; $a = sin(deg2rad($alpha)) * sin(deg2rad($alpha)) + cos(deg2rad($this->lat_a)) * cos(deg2rad($this->lat_b)) * sin(deg2rad($beta)) * sin(deg2rad($beta)) ; $c = asin(min(1, sqrt($a))); $distance = 2*$earth_radius * $c; $distance = round($distance, 4); $measure = $distance; return $measure; } } ```
2016/03/21
['https://magento.stackexchange.com/questions/107132', 'https://magento.stackexchange.com', 'https://magento.stackexchange.com/users/12982/']
Create a module called '**ZipcodeChecker**' **config.xml** is ``` <?xml version="1.0"?> <config> <modules> <SR_ZipcodeChecker> <version>0.0.0.1 </SR_ZipcodeChecker> </modules> <frontend> <routers> <checkout> <args> <modules> <SR_ZipcodeChecker before="Mage_Checkout">SR_ZipcodeChecker_Checkout</SR_ZipcodeChecker> </modules> </args> </checkout> </routers> </frontend> <global> <helpers> <zipcodechecker> <class>SR_ZipcodeChecker_Helper</class> </zipcodechecker> </helpers> </global> </config> ``` Create a controller 'app/code/local/SR/ZipcodeChecker/controllers/Checkout/OnepageController.php' ``` require_once Mage::getModuleDir('controllers', 'Mage_Checkout') . DS . 'OnepageController.php'; class SR_ZipcodeChecker_Checkout_OnepageController extends Mage_Checkout_OnepageController { /** * Perform address validation on checkout billing address. */ public function saveBillingAction() { $address = Mage::app()->getRequest()->getPost('billing', array()); $result = array(); if(isset($address['use_for_shipping']) && ($address['use_for_shipping'])) { $result = Mage::helper('zipcodechecker')->validateZipCode($address); } if (empty($result['error'])) { parent::saveBillingAction(); } else { $this->getResponse()->setHeader('Content-type', 'application/json'); $this->getResponse()->setBody(Mage::helper('core')->jsonEncode($result['error'])); } } /** * Perform address validation on checkout shipping address. */ public function saveShippingAction() { $address = Mage::app()->getRequest()->getPost('shipping', array()); $result = Mage::helper('zipcodechecker')->validateZipCode($address); if (empty($result['error'])) { parent::saveShippingAction(); } else { $this->getResponse()->setHeader('Content-type', 'application/json'); $this->getResponse()->setBody(Mage::helper('core')->jsonEncode($result['error'])); } } } ``` Create a helper for performing global action 'app/code/local/SR/ZipcodeChecker/Helper/Data.php' ``` class SR_ZipcodeChecker_Helper_Data extends Mage_Core_Helper_Abstract { protected $zipCode = array('90001', '90004'); public function validateZipCode($address) { $result = array(); if(isset($address['postcode']) && $address['postcode']) { if(!(in_array($address['postcode'], $this->zipCode))) { $result['error'] = 'Zipcode not allowed'; } } else { $result['error'] = 'Zipcode not allowed'; } return $result; } } ```
create an extension what will provide a section in system configuration(You can create this by silk module creator). and corresponding messages. and create an Ajax for front-end check. and fetch data from that system->configuration part and do your checking part. enjoy.. :)
107,132
we are using custom module for finding shipping charges and **we wrote the list of supported zip codes in below code**. what we need is instead of saving zip codes in code, we want to **save list of zip codes in database**. we saved list of zip codes in backend as below. Now we have to connect this DB to below code, so that only these zip codes should allow to place an order. [![enter image description here](https://i.stack.imgur.com/FR78E.png)](https://i.stack.imgur.com/FR78E.png) ``` <?php class module_Mpperproductshipping_Model_Carrier_LocalDelivery extends Mage_Shipping_Model_Carrier_Abstract { /* Use group alias */ protected $_code = 'mpperproductshipping'; public function collectRates(Mage_Shipping_Model_Rate_Request $request){ $postCode = $request->getDestPostcode(); $restrictedCodes = array( 110001, 110002, ); //restricted values. they can come from anywhere if (!in_array($postCode, $restrictedCodes)) { return false; } $result = Mage::getModel('shipping/rate_result'); /* Edited by vikas_mage */ $postcode=$request->getDestPostcode(); $countrycode=$request->getDestCountry(); $items=$request->getAllItems(); /* End Editing by vikas_mage */ $postcode=str_replace('-', '', $postcode); $shippingdetail=array(); /* one start */ $shippostaldetail=array('countrycode'=>$countrycode,'postalcode'=>$postcode,'items'=>$items); /* one end */ /* tt start - ship charges never work $shippostaldetail=array('countrycode'=>$countrycode,'postalcode'=>$postcode); tt end */ foreach($items as $item) { $proid=$item->getProductId(); $options=$item->getProductOptions(); $mpassignproductId=$options['info_buyRequest']['mpassignproduct_id']; if(!$mpassignproductId) { foreach($item->getOptions() as $option) { $temp=unserialize($option['value']); if($temp['mpassignproduct_id']) { $mpassignproductId=$temp['mpassignproduct_id']; } } } if($mpassignproductId) { $mpassignModel = Mage::getModel('mpassignproduct/mpassignproduct')->load($mpassignproductId); $partner = $mpassignModel->getSellerId(); } else { $collection=Mage::getModel('marketplace/product') ->getCollection()->addFieldToFilter('mageproductid',array('eq'=>$proid)); foreach($collection as $temp) { $partner=$temp->getUserid(); } } $product=Mage::getModel('catalog/product')->load($proid)->getWeight(); $weight=$product*$item->getQty(); if(count($shippingdetail)==0){ array_push($shippingdetail,array('seller_id'=>$partner,'items_weight'=>$weight,'product_name'=>$item->getName(),'qty'=>$item->getQty(),'item_id'=>$item->getId())); }else{ $shipinfoflag=true; $index=0; foreach($shippingdetail as $itemship){ if($itemship['seller_id']==$partner){ $itemship['items_weight']=$itemship['items_weight']+$weight; $itemship['product_name']=$itemship['product_name'].",".$item->getName(); $itemship['item_id']=$itemship['item_id'].",".$item->getId(); $itemship['qty']=$itemship['qty']+$item->getQty(); $shippingdetail[$index]=$itemship; $shipinfoflag=false; } $index++; } if($shipinfoflag==true){ array_push($shippingdetail,array('seller_id'=>$partner,'items_weight'=>$weight,'product_name'=>$item->getName(),'qty'=>$item->getQty(),'item_id'=>$item->getId())); } } } $shippingpricedetail=$this->getShippingPricedetail($shippingdetail,$shippostaldetail); if($shippingpricedetail['errormsg']!==""){ Mage::getSingleton('core/session')->setShippingCustomError($shippingpricedetail['errormsg']); return $result; } /*store shipping in session*/ $shippingAll=Mage::getSingleton('core/session')->getData('shippinginfo'); $shippingAll[$this->_code]=$shippingpricedetail['shippinginfo']; Mage::getSingleton('core/session')->setData('shippinginfo',$shippingAll); $method = Mage::getModel('shipping/rate_result_method'); $method->setCarrier($this->_code); $method->setCarrierTitle(Mage::getStoreConfig('carriers/'.$this->_code.'/title')); /* Use method name */ $method->setMethod($this->_code); $method->setMethodTitle(Mage::getStoreConfig('carriers/'.$this->_code.'/name')); $method->setCost($shippingpricedetail['handlingfee']); $method->setPrice($shippingpricedetail['handlingfee']); $result->append($method); return $result; } public function getShippingPricedetail($shippingdetail,$shippostaldetail) { $shippinginfo=array(); $handling=0; $session = Mage::getSingleton('checkout/session'); $customerAddress = $session->getQuote()->getShippingAddress(); /* Edited by vikas_boy */ $customerPostCode = $shippostaldetail['postalcode']; $items = $shippostaldetail['items']; /* End Editing by vikas_boy */ /* one */ foreach($shippingdetail as $shipdetail) { $seller = Mage::getModel("customer/customer")->load($shipdetail['seller_id']); $sellerAddress = $seller->getPrimaryShippingAddress(); $distance = $this->getDistanse($sellerAddress->getPostcode(),$customerPostCode); // echo "distance ".$distance;die; $price = 0; $itemsarray=explode(',',$shipdetail['item_id']); foreach($items as $item) { $proid=$item->getProductId(); $options=$item->getProductOptions(); $mpassignproductId=$options['info_buyRequest']['mpassignproduct_id']; if(!$mpassignproductId) { foreach($item->getOptions() as $option) { $temp=unserialize($option['value']); if($temp['mpassignproduct_id']) { $mpassignproductId=$temp['mpassignproduct_id']; } } } if ($item->getHasChildren()){ continue; } $mpshippingcharge = 0; $localDistance = Mage::getStoreConfig('marketplace/mpperproductshipping/local_shipping_distance'); $regionalDistance = Mage::getStoreConfig('marketplace/mpperproductshipping/regional_shipping_distance'); $stateDistance = Mage::getStoreConfig('marketplace/mpperproductshipping/state_shipping_distance'); if(in_array($item->getId(),$itemsarray)) { if($mpassignproductId) { if($distance < $localDistance) { $mpshippingcharge=Mage::getModel('mpassignproduct/mpassignproduct')->load($mpassignproductId)->getLocalShippingCharge(); } elseif($distance > $localDistance && $distance < $regionalDistance) { $mpshippingcharge=Mage::getModel('mpassignproduct/mpassignproduct')->load($mpassignproductId)->getRegionalShippingCharge(); } elseif($distance > $regionalDistance) { $mpshippingcharge=Mage::getModel('mpassignproduct/mpassignproduct')->load($mpassignproductId)->getStateShippingCharge(); } } else { // echo "imte ".$item->getProductId(); if($distance < $localDistance) { $mpshippingcharge=Mage::getModel('catalog/product')->load($item->getProductId())->getMpLocalShippingCharge(); // echo "imte ".$item->getProductId(); // echo "ship ".$mpshippingcharge; } elseif($distance > $localDistance && $distance < $regionalDistance) { $mpshippingcharge=Mage::getModel('catalog/product')->load($item->getProductId())->getMpRegionalShippingCharge(); } elseif($distance > $regionalDistance) { $mpshippingcharge=Mage::getModel('catalog/product')->load($item->getProductId())->getMpStateShippingCharge(); } } /* tt */ // echo "test ".$mpshippingcharge;die; if(!is_numeric($mpshippingcharge)){ $price=$price+floatval($this->getConfigData('defalt_ship_amount')* floatval($item->getQty())); }else{ $price=$price+($mpshippingcharge * floatval($item->getQty())); } /* tt end */ /* one if(floatval($mpshippingcharge)==0){ $price=$price+floatval($this->getConfigData('defalt_ship_amount')); }else{ $price=$price+$mpshippingcharge; } one end */ } } $handling = $handling+$price; $submethod = array(array('method'=>Mage::getStoreConfig('carriers/'.$this->_code.'/title'),'cost'=>$price,'error'=>0)); array_push($shippinginfo,array('seller_id'=>$shipdetail['seller_id'],'methodcode'=>$this->_code,'shipping_ammount'=>$price,'product_name'=>$shipdetail['product_name'],'submethod'=>$submethod,'item_ids'=>$shipdetail['item_id'])); } $msg=""; return array('handlingfee'=>$handling,'shippinginfo'=>$shippinginfo,'errormsg'=>$msg); } /* one end */ /* tt start */ private function getDistanse($origin,$destination) { $url = "http://maps.googleapis.com/maps/api/distancematrix/json?origins=".$origin.",india&destinations=".$destination.",india&mode=driving&language=en-EN&sensor=false"; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_PROXYPORT, 3128); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); $response = curl_exec($ch); curl_close($ch); $response_all = json_decode($response); $distance = $response_all->rows[0]->elements[0]->distance->value / 1000; if($distance==0){ $zips = array( $origin,$destination // ... etc ... ); $geocoded = array(); $serviceUrl = "http://maps.googleapis.com/maps/api/geocode/json?components=postal_code:%s&sensor=false"; $curl = curl_init(); foreach ($zips as $zip) { curl_setopt($curl, CURLOPT_URL, sprintf($serviceUrl, urlencode($zip))); curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE); $data = json_decode(curl_exec($curl)); $info = curl_getinfo($curl); if ($info['http_code'] != 200) { // Request failed } else if ($data->status !== 'OK') { // Something happened, or there are no results } else { $geocoded[$zip] =$data->results[0]->geometry->location; } } $distance=$this->DistAB($geocoded[$zips[0]]->lat,$geocoded[$zips[0]]->lng,$geocoded[$zips[1]]->lat,$geocoded[$zips[1]]->lng); } return $distance; } /* tt end * / /* tt start */ public function DistAB($lat_a,$lon_a,$lat_b,$lon_b) { $measure_unit = 'kilometers'; $measure_state = false; $measure = 0; $error = ''; $delta_lat = $lat_b - $lat_a ; $delta_lon = $lon_b - $lon_a ; $earth_radius = 6372.795477598; $alpha = $delta_lat/2; $beta = $delta_lon/2; $a = sin(deg2rad($alpha)) * sin(deg2rad($alpha)) + cos(deg2rad($this->lat_a)) * cos(deg2rad($this->lat_b)) * sin(deg2rad($beta)) * sin(deg2rad($beta)) ; $c = asin(min(1, sqrt($a))); $distance = 2*$earth_radius * $c; $distance = round($distance, 4); $measure = $distance; return $measure; } } ```
2016/03/21
['https://magento.stackexchange.com/questions/107132', 'https://magento.stackexchange.com', 'https://magento.stackexchange.com/users/12982/']
If you want receive data from the your module field (`textarea` in system config), you could use next solution: ``` public function getRestrictedZipCodes() { // Replace 'test/module/zips' with the original path from the system.xml file $restrictedCodesString = Mage::getStoreConfig('test/module/zips'); $restrictedCodesString = preg_replace('/\s+/', '', $restrictedCodesString); $restrictedCodes = explode(',', $restrictedCodesString); if (!empty($restrictedCodes) && is_array($restrictedCodes)) { array_walk($restrictedCodes, 'trim'); $restrictedCodes = array_filter($restrictedCodes); } return $restrictedCodes; } ``` Update code: ``` public function collectRates(Mage_Shipping_Model_Rate_Request $request) { $postCode = $request->getDestPostcode(); $restrictedCodes = $this->getRestrictedZipCodes(); //changes if (!in_array($postCode, $restrictedCodes)) { return false; } // other code..... ``` Test field: [![Test field in system configuration](https://i.stack.imgur.com/aqBR1.png)](https://i.stack.imgur.com/aqBR1.png) Result: [![Result in debug](https://i.stack.imgur.com/12vRZ.png)](https://i.stack.imgur.com/12vRZ.png) If you want get your zip codes anywhere you can always use `getRestrictedZipCodes()` method. You can find path to the field in the *system.xml* file of your module (in the *etc* directory) If you want to transfer your zip code values elsewhere in the database, you will need to create a separate collection and source model for your zip codes.
create an extension what will provide a section in system configuration(You can create this by silk module creator). and corresponding messages. and create an Ajax for front-end check. and fetch data from that system->configuration part and do your checking part. enjoy.. :)
29,349,499
I was looking for some solution about adding new value into list. Eg. I have list of values ``` n = c(2, 3, 5) s = c("aa", "bb", "cc", "dd", "ee") b = c(TRUE, FALSE, TRUE, FALSE, FALSE) x = list(n, s, b, 3) # x contains copies of n, s, b ``` and I need to add value 6 to list x to have in x[[1]] 2, 3, 5, 6 values. How do I do that?
2015/03/30
['https://Stackoverflow.com/questions/29349499', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4274408/']
The reason why nothing was being written to the Difference file is because it was not closed. In my create\_diff proc, I forgot to include the command: `close $dso1` Therefore once the script finished running, only then it would write to the file. However, right after the diff proc, I compress the files, and since it cannot write to a compressed file, the file would be empty. Tldr; I did not close the file I was writing the differences to.
``` set status [catch {exec diff $file1 $file2} result] ``` "status" is **not** `diff`'s exit status, it is `catch`'s exit status. Not the same. To get `diff`'s exit status: ``` if {$status == 1} { set err_type [lindex $::errorCode 0] if {$err_type eq "NONE"} { # diff exited with exit status 0 but printed something # to stderr } elseif {$err_type eq "CHILDSTATUS"} { # diff returned non-zero status set diff_exit_status [lindex $::errorCode end] if {$diff_exit_status == 1} { # diff results in $result } else { # diff had some kind of trouble } } } ```
14,863,806
Well I've did do my research and I just can't seem to figure this out. So long story short, I'm using something like this: btw, "(WebsiteInfo)" is just to sensor out my website/database information. ``` $SQL = new PDO('mysql:dbname=(WebsiteInfo);host=(WebsiteInfo);charset=utf8', '(WebsiteInfo)', '(WebsiteInfo)'); $SQL -> setAttribute(PDO::ATTR_EMULATE_PREPARES, false); $SQL -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); ``` Now, that's just currently just to start the database connect up. Which btw is mostly just a copy/paste code I found on this website too which is to prevent MySQL injection. Actually from this link [How can I prevent SQL injection in PHP?](https://stackoverflow.com/questions/60174/how-to-prevent-sql-injection-in-php). If there's anything wrong with it, I wouldn't mind advice or tips. As long as if it makes sense because I just started using databases probably not even a week ago so everything is new to me. Now there's this: ``` $Exicu = $SQL -> prepare("SELECT `tags` FROM `users` WHERE `user_id` = :a ") -> execute(array( ':a' => 16)); ``` `$Exicu` is just there, because I have been trying to get the results from the query (if I said that right). Also the 16 is the users ID, but this will change often so that's why 16 isn't just tossed in the prepare statement. I've tried a lot of things but none of them worked. It either didn't work or made the PHP crash. But anyway, things I already tried for `$Exicu` is `$Exicu->rowCount()`, `$Exicu->bindParam`, a while loop with `$row = $Exicu->fetch()`, `$SQL->query($Exicu)->fetchAll();`, a `foreach` loop with `($Exicu->fetch(PDO::FETCH_ASSOC) as $row)`, `$Exicu->get_result()`, `echo PDO::query($Exicu);`, `echo mysql_result($Exicu)`, and just `echo $Exicu`. Yes I know, that looks pretty sloppy. But none of these seemed to work to just show me the `tags` from the database of the specific user. So that's pretty much what I need help with. There's no problem when I use something like this `echo mysql_result( mysql_query("SELECT (etc,etc)") )` but that doesn't have protection from MySQL injections.
2013/02/13
['https://Stackoverflow.com/questions/14863806', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1733856/']
I do my PDO queries like this: ``` $user_id = 16; $query = $SQL->prepare('SELECT tags FROM users WHERE user_id = :uid'); $query->bindValue(':uid', $user_id, PDO::PARAM_INT); $query->execute(); while ($row = $query->fetch(PDO::FETCH_ASSOC)) { echo $row['tags']; } ``` This will select data from the database, bind values in it safely and then we echo out the results. The loop is needed to iterate through every result returned from the query. You can skip the looping part and create a variable like in the `while` statement, and use `$row` as an array with your results.
There is a thing called *user defined function*. I am wondering why noone on this site ever using them. For some reason everyone is ready to make a mile long single line of chained methods, instead of clean and concise function call: ``` $user_id = 16; $tags = getone('SELECT tags FROM users WHERE user_id = ?',array($user_id)); ``` there are many ways to create such a function. A quick and dirty one ``` function getone($sql, $data) { global $SQL; $stmt = $SQL->prepare($sql); $stmt->execute($data); return reset($stmt->fetch()); } ``` but of course it would be better to make set of functions and put them in a class
50,848
This is my first question on here so I hope I'm not breaking any rules, but I have a problem: I have a site that uses an Adobe Site Catalyst for its online analytics. The suite supports tagging through JavaScript and when implemented, it looks something like this that is placed on `http://www.mydomain.com`: ``` <script language="JavaScript" type="text/javascript"> s.channel="/my-tracking-tag/" </script>` ``` The problem is that Google is reading this JavaScript and interpreting the `s.channel` string as a relative location on my website and is crawling it. I then get a 404 error in Google Webmaster Tools saying that the URL `http://www.mydomain.com/my-tracking-tag/` does not exist, and that it was linked to by the URL that the JavaScript tag code was on. Is there any to avoid this behavior? I thought about adding URL with a 404 error to my *robots.txt* file but tracking campaigns are constantly updating and it would be burdensome to update the text file with the constantly updating tags. I also though about structuring the string in `s.channel` as something like `'s.channel= "/" + "my-tracking-tag" + "/"` but I'm not sure if that would due the trick, and would also require implementation guidelines to be developed for the future.
2013/07/16
['https://webmasters.stackexchange.com/questions/50848', 'https://webmasters.stackexchange.com', 'https://webmasters.stackexchange.com/users/-1/']
I've encountered this as well. It's annoying that Google is reporting 404 errors on something you never actually link to, but only based on their heuristic that finds links in JavaScript code. These reported errors don't seem to indicate actual problems than need to be addressed. [Google's John Mueller posted this on Google+](https://johnmu.com/painful-crawl-errors/): > > 1. **404 errors on invalid URLs do not harm your site’s indexing or ranking in any way.** It doesn’t matter if there are 100 or 10 million, they won’t harm your site’s ranking. <http://googlewebmastercentral.blogspot.ch/2011/05/do-404s-hurt-my-site.html> > 2. In some cases, crawl errors may come from a legitimate structural issue within your website or CMS. How you tell? Double-check the origin of the crawl error. If there's a broken link on your site, in your page's static HTML, then that's always worth fixing. (thanks [Martino Mosna](https://plus.google.com/114158417244913509295/posts)) > 3. What about the funky URLs that are “clearly broken?” When our algorithms like your site, they may try to find more great content on it, for example by trying to discover new URLs in JavaScript. If we try those “URLs” and find a 404, that’s great and expected. We just don’t want to miss anything important (insert overly-attached Googlebot meme here). <http://support.google.com/webmasters/bin/answer.py?answer=1154698> > 4. You don’t need to fix crawl errors in Webmaster Tools. The “mark as fixed” feature is only to help you, if you want to keep track of your progress there; it does not change anything in our web-search pipeline, so feel free to ignore it if you don’t need it. > <http://support.google.com/webmasters/bin/answer.py?answer=2467403> > 5. We list crawl errors in Webmaster Tools by priority, which is based on several factors. If the first page of crawl errors is clearly irrelevant, you probably won’t find important crawl errors on further pages. > <http://googlewebmastercentral.blogspot.ch/2012/03/crawl-errors-next-generation.html> > 6. There’s no need to “fix” crawl errors on your website. Finding 404’s is normal and expected of a healthy, well-configured website. If you have an equivalent new URL, then redirecting to it is a good practice. Otherwise, you should not create fake content, you should not redirect to your homepage, you shouldn’t robots.txt disallow those URLs -- all of these things make it harder for us to recognize your site’s structure and process it properly. We call these “soft 404” errors. > <http://support.google.com/webmasters/bin/answer.py?answer=181708> > 7. Obviously - if these crawl errors are showing up for URLs that you care about, perhaps URLs in your Sitemap file, then that’s something you should take action on immediately. If Googlebot can’t crawl your important URLs, then they may get dropped from our search results, and users might not be able to access them either. > > >
The only thing that is impacted by this is your crawling budget so unless it’s millions of urls I wouldn’t worry about it
42,297,695
I have a numpy binary array like this: ``` np_bin_array = [0 1 0 0 1 0 0 0 0 1 1 0 0 1 0 1 0 1 1 0 1 1 0 0 0 1 1 0 1 1 0 0 0 1 1 0 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] ``` It was 8-bit string characters of a word originally, starting from the left, with 0's padding it out. I need to convert this back into strings to form the word again and strip the 0's and the output for the above should be 'Hello'. Thanks for your help!
2017/02/17
['https://Stackoverflow.com/questions/42297695', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7580607/']
You can firstly interpret the bits into an array, using [`numpy.packbits()`](https://docs.scipy.org/doc/numpy/reference/generated/numpy.packbits.html), then convert it to an array of bytes by applying [`bytearray()`](https://docs.python.org/3.6/library/functions.html#bytearray), then `decode()` it to be a normal string. The following code ``` import numpy np_bin_array = [0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] print(bytearray(numpy.packbits(np_bin_array)).decode().strip("\x00")) ``` gives ``` Hello ```
This one works to me. I had a boolean array though, so had to make an additional conversion. ``` def split_list(alist,max_size=1): """Yield successive n-sized chunks from l.""" for i in range(0, len(alist), max_size): yield alist[i:i+max_size] result = "".join([chr(i) for i in (int("".join([str(int(j)) for j in letter]), base=2) for letter in split_list(np_bin_array, 8)) if i != 0]) ```