text
stringlengths
64
89.7k
meta
dict
Q: Adding a static gridline to a JFreeChart time series chart I am trying to implement a timeseries chart with a peculiar requirement in JFreeChart. I can draw the chart, but I don't know how to implement the vertical red line at the last value in the chart. It should always be in the same spot and should always intersect with the last value. I am absolutely out of ideas on how this would be done. I was thinking that it might be possible to implement it as a static gridline, but I don't know how to specify one. Also, the size of the charts will be static, so some roundabout way of doing this is acceptable, hopefully without introducing any 3rd party libraries. An image of what I am trying to achieve can be found here. Thanks. A: Well, I solved it using a marker. Here's the code that does it: JFreeChart chart = ChartFactory.createTimeSeriesChart(...); XYPlot plot = chart.getXYPlot(); Long timestampToMark = new Date().getTime(); Marker m = new ValueMarker(timestampToMark); m.setStroke(new BasicStroke(2)); m.setPaint(Color.RED); plot.addDomainMarker(m); Maybe someone else will find this useful.
{ "pile_set_name": "StackExchange" }
Q: Sharepoint Online: Get List Items from Documents List with over 5000 Items using Powershell My goal is to create a powershell script that will change the created by value in my Sharepoint online documents list. Fyi this list contains 10005 items. I'm at the very beggining and already stuck because of this error: Exception calling "ExecuteQuery" with "0" argument(s): "The attempted operation is prohibited because it exceeds the list view threshold enforced by the administrator." Here is my script: ##Variables for Processing $SiteUrl = "https://xyz.sharepoint.com/sites/xyz" $UserName ="[email protected]" $Password ="xyz" $ListName ="Documents" #Setup Credentials to connect $Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($UserName,(ConvertTo-SecureString $Password -AsPlainText -Force)) #Setup the context $Context = New-Object Microsoft.SharePoint.Client.ClientContext($SiteUrl) $Context.Credentials = $Credentials #Get the list (documents) $Web = $context.Web $documentsList = $Web.Lists.GetByTitle($ListName) #Get All List items $ListItems = $documentsList.GetItems([Microsoft.SharePoint.Client.CamlQuery]::CreateAllItemsQuery()) $context.Load($ListItems) $context.ExecuteQuery() Write-host "Total Number of List Items found:"$ListItems.count I want to loop through the list items and change the created by value. How do you get around the 5000 item limit in this case? Thank you. A: I'd like to thank Lee_MSFT for his help. I used the code and inspiration from here. I'm answering my own question for those who are looking for something complete. Note that I was able to change the Created By value in my Sharepoint online documents list containing 10005 items, ONLY if I changed the Modified By value at the same time. If I only tried to do the Created By value, I would not be able to change anything. An explanation was found here The solution that worked 100%, see code: ##Variables for Processing $SiteUrl = "https://xyz.sharepoint.com/" $UserName ="[email protected]" $Password ="xyz" $ListName ="Documents" #Setup Credentials to connect $Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($UserName,(ConvertTo-SecureString $Password -AsPlainText -Force)) #Setup the context $Context = New-Object Microsoft.SharePoint.Client.ClientContext($SiteUrl) $Context.Credentials = $Credentials #Get the list (documents) $Web = $context.Web #$Lists = $web.Lists; $documentsList = $Web.Lists.GetByTitle($ListName) $context.Load($documentsList) # Prepare the query $BatchSize = 500 $query = New-Object Microsoft.SharePoint.Client.CamlQuery $Query.ViewXml = "<View Scope='RecursiveAll'><Query><OrderBy><FieldRef Name='ID' Ascending='TRUE'/></OrderBy></Query><RowLimit Paged='TRUE'>$BatchSize</RowLimit></View>" #Get the User $UserID="[email protected]" $User = $Context.Web.EnsureUser($UserID) $Context.Load($user) #Get All List items #change Created By and Modified By do { $ListItems = $documentsList.GetItems($query) $Context.Load($ListItems) $Context.ExecuteQuery() $query.ListItemCollectionPosition = $ListItems.ListItemCollectionPosition foreach($item in $listItems) { Try { # Add each item $item["Author"]=$User $item['Editor'] = $User $item.Update() $Context.ExecuteQuery() } Catch [System.Exception] { # This shouldn't happen, but just in case Write-Host $_.Exception.Message } } } While($query.ListItemCollectionPosition -ne $null)
{ "pile_set_name": "StackExchange" }
Q: What causes this bigger SourceAlpha than SourceGraphic I was trying to make the following box have a bigger clickable area: <svg width="150" height="150"> <rect x="10.5" y="10.5" width="10" height="10" stroke="black" stroke-width="3" fill="none"/> </svg> so to do that, I messed around a bit with filters; first I applied a color matrix, and then I wanted to start changing the size of the black background part, but it was somehow already bigger than the original graphic: <svg width="150" height="150"> <filter id="fillBlack"> <feColorMatrix type="matrix" in="SourceAlpha" result="blackBox" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1"/> <feComposite operator="over" in="SourceGraphic" in2="blackBox"/> </filter> <rect x="50" y="50" width="10" height="10" filter="url(#fillBlack)" stroke="transparent" stroke-width="50" fill="white"/> </svg> Now, this seems to come pretty close to my desired result already, but there are two problems: firstly, I really don't understand why this would work, and secondly, because I don't know what causes this, I can't resize the black background. It seems like the background is always 10% bigger; try changing the values for width and height on the <rect>, and the black background will be a border of 10% the entered width/height around the original box So what causes the SourceAlpha to be bigger, and how do I actually resize the black background so I can have it the size I want? PS: I'd very much prefer not to put another <rect> over the current one, but rather I'd have everything done with a filter like what I've got here. A: By default, the filter region is 10% bigger on all sides. This is to allow for filter primitives like feGaussianBlur which can make the graphic bigger. You can change the filter effects region by using the attributes x, y, width and height on the <filter> element. They default to -10%, -10%, 120% and 120% respectively. I recommend reading the section on filters in the SVG spec. But even though filters can result in something being drawn larger, it shouldn't change the actual size or shape of the region that responds to pointer events. There is only one way I can think of that you can use to make the click area larger without adding extra elements. Give the shape a large, but invisible, stroke width Set pointer-events="all" Setting pointer-events to "all" makes both the stroke and fill areas sensitive even if they are invisible. Compare the behaviour of the squares in this example. rect:hover { fill: orange; } <svg width="350" height="200"> <rect x="50" y="50" width="100" height="100" fill="red"/> <rect x="200" y="50" width="100" height="100" fill="green" stroke="black" stroke-opacity="0" stroke-width="40" pointer-events="all"/> </svg>
{ "pile_set_name": "StackExchange" }
Q: MKOverlay update flashing In my app, I use an MKPolyline to track the user's path. Sometimes (and not all the time, which I don't understand), when a new line segment gets added to the map, the entire line flashes. Sometimes it doesn't. This is the code being used to add the lines: CLLocationCoordinate2D coords[2]; coords[0] = CLLocationCoordinate2DMake(newLocation.coordinate.latitude, newLocation.coordinate.longitude); coords[1] = CLLocationCoordinate2DMake(oldLocation.coordinate.latitude, oldLocation.coordinate.longitude); MKPolyline* line = [MKPolyline polylineWithCoordinates:coords count:2]; [mapView addOverlay:line]; Am I missing something? Edit: This usually happens upon the app's return from being sent to the background. I'm not exactly sure why, though, because I am only adding an overlay, not modifying the entire mapView.overlays array. ...right? A: This may not be related, but Apple does state in the Managing the Map's Overlay Objects section of the Location Awareness Programming Guide... Because the map view is an interface item, any modifications to the overlays array should be synchronized and performed on the application’s main thread.
{ "pile_set_name": "StackExchange" }
Q: Symfony2 Form Mapping Issue Im having issues with data mapping to an entity after it is submitted The Entity: <?php namespace Site\UserBundle\Entity; use Doctrine\ORM\Mapping as ORM; use Doctrine\ORM\EntityManager; use JMS\Serializer\Annotation as Serializer; use JMS\Serializer\Annotation\Groups; use Symfony\Component\Security\Core\User\AdvancedUserInterface; use Symfony\Component\Validator\Constraints as Assert; use Doctrine\Common\Collections\ArrayCollection; /** * UserAddress * * @ORM\Table(name="user_address") * @ORM\Entity * * @Serializer\ExclusionPolicy("all") * ---------- SERIALIZER GROUPS ----- * all -- All entries */ class UserAddress { /** * @var integer * * @ORM\Column(name="id", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="IDENTITY") * * @Serializer\Type("integer") * @Serializer\Expose * @serializer\SerializedName("ID") * @serializer\Groups({"all"}) */ public $ID; /** * @var integer * * @ORM\Column(name="user_id", type="integer", nullable=false) */ public $UserId; /** * @var integer * * @ORM\Column(name="level_id", type="integer", nullable=false) * * @Serializer\Type("integer") * @Serializer\Expose * @serializer\SerializedName("LevelId") * @serializer\Groups({"all"}) */ public $LevelId; /** * @var integer * * @ORM\Column(name="address_type_id", type="integer", nullable=false) * * @Serializer\Type("integer") * @Serializer\Expose * @serializer\SerializedName("AddressTypeId") * @serializer\Groups({"all"}) * * @Assert\NotBlank() */ public $AddressTypeId; /** * @var string * * @ORM\Column(name="address_data", type="text", nullable=false) * * @Serializer\Type("string") * @Serializer\Expose * @serializer\SerializedName("Address Data") * @serializer\Groups({"all"}) * * @Assert\NotBlank() */ public $AddressData; /** * @var integer * * @ORM\Column(name="public_yn", type="integer", nullable=false) * * @Serializer\Type("boolean") * @Serializer\Expose * @serializer\SerializedName("PublicYN") * @serializer\Groups({"all"}) * * @Assert\NotBlank() */ public $PublicYN; /** * @var integer * * @ORM\Column(name="primary_yn", type="integer", nullable=false) * * @Serializer\Type("boolean") * @Serializer\Expose * @serializer\SerializedName("PrimaryYN") * @serializer\Groups({"all"}) * * @Assert\NotBlank() */ public $PrimaryYN; /** * @ORM\ManyToOne(targetEntity="Site\UserBundle\Entity\UserMain", inversedBy="UserAddress") * @ORM\JoinColumn(name="user_id", referencedColumnName="user_id") */ public $User; /** * @ORM\ManyToOne(targetEntity="Site\UserBundle\Entity\UserAddressType", inversedBy="UserAddress") * @ORM\JoinColumn(name="address_type_id", referencedColumnName="address_type_id") * * @Serializer\Type("Site\UserBundle\Entity\UserAddressType") * @Serializer\Expose * @serializer\SerializedName("UserAddressType") * @serializer\Groups({"all"}) */ public $UserAddressType; /** * Get ID * * @return integer */ public function getID() { return $this->ID; } /** * Set UserId * * @param integer $userId * @return UserAddress */ public function setUserId($userId) { $this->UserId = $userId; return $this; } /** * Get UserId * * @return integer */ public function getUserId() { return $this->UserId; } /** * Set LevelId * * @param integer $levelId * @return UserAddress */ public function setLevelId($levelId) { $this->LevelId = $levelId; return $this; } /** * Get LevelId * * @return integer */ public function getLevelId() { return $this->LevelId; } /** * Set AddressTypeId * * @param integer $addressTypeId * @return UserAddress */ public function setAddressTypeId($addressTypeId) { $this->AddressTypeId = $addressTypeId; return $this; } /** * Get AddressTypeId * * @return integer */ public function getAddressTypeId() { return $this->AddressTypeId; } /** * Set AddressData * * @param string $addressData * @return UserAddress */ public function setAddressData($addressData) { $this->AddressData = $addressData; return $this; } /** * Get AddressData * * @return string */ public function getAddressData() { return $this->AddressData; } /** * Set PublicYN * * @param integer $publicYN * @return UserAddress */ public function setPublicYN($publicYN) { $this->PublicYN = $publicYN; return $this; } /** * Get PublicYN * * @return integer */ public function getPublicYN() { return $this->PublicYN; } /** * Set PrimaryYN * * @param integer $primaryYN * @return UserAddress */ public function setPrimaryYN($primaryYN) { $this->PrimaryYN = $primaryYN; return $this; } /** * Get PrimaryYN * * @return integer */ public function getPrimaryYN() { return $this->PrimaryYN; } /** * Set User * * @param \Site\UserBundle\Entity\UserMain $user * @return UserAddress */ public function setUser(\Site\UserBundle\Entity\UserMain $user = null) { $this->User = $user; return $this; } /** * Get User * * @return \Site\UserBundle\Entity\UserMain */ public function getUser() { return $this->User; } /** * Set UserAddressType * * @param \Site\UserBundle\Entity\UserAddressType $userAddressType * @return UserAddress */ public function setUserAddressType(\Site\UserBundle\Entity\UserAddressType $userAddressType = null) { $this->UserAddressType = $userAddressType; return $this; } /** * Get UserAddressType * * @return \Site\UserBundle\Entity\UserAddressType */ public function getUserAddressType() { return $this->UserAddressType; } } The form is: namespace Site\UserBundle\Form; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolverInterface; use Doctrine\ORM\EntityRepository; class UserAddressType extends AbstractType { /** * @param FormBuilderInterface $builder * @param array $options */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('UserId','hidden') ->add('LevelId', 'integer', array( 'label'=>'Sort Rate (Order)' )) ->add('AddressTypeId', 'entity', array( 'class'=>'SiteUserBundle:UserAddressType', 'query_builder'=> function(EntityRepository $er){ return $er->createQueryBuilder('t') ->orderBy('t.AddressDescription', 'ASC'); }, 'property'=>'AddressDescription', 'label'=>'Address Type' )) ->add('AddressData', 'text') ->add('PublicYN', 'choice', array( 'choices' => array( 'false'=>'Private', 'true'=>'Public'), 'required'=>true, 'label'=>'Pubicly Visable' )) ->add('PrimaryYN', 'choice', array( 'choices' => array( 'false'=>'Secondary', 'true'=>'Primary'), 'required'=>true, 'label'=>'Primary Contact', )) ->add('save', 'submit', array( 'label'=>'Add Address', 'attr'=>array( 'class'=>'btn btn-primary', ), )) ; } /** * @param OptionsResolverInterface $resolver */ public function setDefaultOptions(OptionsResolverInterface $resolver) { $resolver->setDefaults(array( 'data_class' => 'Site\UserBundle\Entity\UserAddress', 'csrf_protection'=>false, )); } /** * @return string */ public function getName() { return 'Create_User_Address'; } } Controller Function is: (I'm using fosrestbundle) public function newAddressAction($userid, Request $request) { $statusCode = 201; $address = new UserAddress(); $address->setUserId($userid); $form = $this->createForm( new UserAddressType(), $address, array( 'method'=>'GET', )); $form->handleRequest($request); if($form->isValid()){ $em = $this->getDoctrine()->getManager(); $em->persist($address); $em->flush(); return new Response('User Added to system'); } return $this->render('SiteUserBundle:UserAddress:newUserAddress.html.twig', array( 'form' => $form->createView(), )); } The Twig template is very simple. All the data is posted correctly to the server: (Query String Parameters ) Create_User_Address[LevelId]:0 Create_User_Address[AddressTypeId]:5 Create_User_Address[AddressData]:555-555-5555 Create_User_Address[PublicYN]:false Create_User_Address[PrimaryYN]:false Create_User_Address[save]: Create_User_Address[UserId]:3 but i keep getting the following error: An exception occurred while executing 'INSERT INTO user_address (user_id, level_id, address_type_id, address_data, public_yn, primary_yn) VALUES (?, ?, ?, ?, ?, ?)' with params [null, 0, null, "555-555-5555", "false", "false"]: SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'user_id' cannot be null As you can see the UserID and AddressTypeId fields are not mapping from the form to the Entity. I have looked over the code for all 3 pieces over and ove and for the life of me i can't see where the mismatch is happening. I did at one point change the names of those two fields in the Entity but i deleted all the getters and setters and regenerated them as well as clear the dev cache. My hunch is there is a file somewhere in Symfony2 there is a mapping class that is wrong but i can't find it.. Thanks all EDIT: I tried clearing the doctrine cache as stated here: Symfony2 doctrine clear cache . app/console doctrine:cache:clear-metadata app/console doctrine:cache:clear-query app/console doctrine:cache:clear-result this resulted in the same error being generated,so the cache issue may be off the table. EDIT: As per Isaac's suggestion i removed ->add('UserId', 'hidden') . The form still posted with the same error message. The field is being generated correctly to the page; <input type="hidden" id="Create_User_Address_UserId" name="Create_User_Address[UserId]" class=" form-control" value="3"> and as you can see from the Query Parameters above being posted back to the server correctly. EDIT: I tracked the issue down to the User and UserAddressType variables. If i remove these two variables and their getters and setters the form works perfectly without other modifications of my code. I should note that these two variables are joins to other entities. Some how they seem to be wiping out the data being submitted by the forms. A: As per lsouza suggestion I had to create a data transformer. namespace Site\UserBundle\Form\DataTransformer; use Symfony\Component\Form\DataTransformerInterface; use Symfony\Component\Form\Exception\TransformationFailedException; use Doctrine\Common\Persistence\ObjectManager; use Site\UserBundle\Entity\UserAddressType; class AddressTypeToNumber implements DataTransformerInterface { /** * @var ObjectManager */ private $om; /** * @param ObjectManager $om */ public function __construct(ObjectManager $om) { $this->om = $om; } /** * Transforms an object(val) to a string * * @param UserAddressType|null $val * @return string */ public function transform($val) { if (null === $val) { return ""; } return array(); } /** * Transfers a string to an object (UserAddressType) * * @param string $val * @return UserAddressType|null * @throws TransformationFailedException if object is not found */ public function reverseTransform($val) { if (!$val) { return null; } $addId = $this->om ->getRepository('SiteUserBundle:UserAddressType') ->findOneBy(array('AddressTypeId' => $val)); if (null === $addId) { throw new TransformationFailedException(sprintf( 'An Address Type with the ID of "%s" does not exsist in the system', $val )); } return $addId; } } Please note that the Transformer function is currently returning null but this should return a value that can be used by the form. Some other notes that may help others are that the form class needs to be changed as well. The setDefaultOptions function needs the following added to the $resolver variable: ->setRequired(array( 'em', )) ->setAllowedTypes(array( 'em'=>'Doctrine\Common\Persistence\ObjectManager', )); The buildForm function needs to be changed slightly to accept the em option: public function buildForm(FormBuilderInterface $builder, array $options) { $em = $options['em']; $transformer = new AddressTypeToNumber($em); The field needs to be change to the varrable that holds the relationship in the Entity and not the field that is use in the link: ->add( $builder->create('UserAddressType', 'entity', array( 'class' => 'SiteUserBundle:UserAddressType', 'property' => 'AddressDescription', 'label' => 'Address Type' )) ->addModelTransformer($transformer) ) Finally in your controller you need to pass an instance of $this->getDoctrine()->getManager() to the form class: $form = $this->createForm( new UserAddressType(), $address, array( 'em' => $this->getDoctrine()->getManager(), )); I hope this helps others.
{ "pile_set_name": "StackExchange" }
Q: "How to fix 'class, interface, or enum expected' for my code I am unable to find the solution for my code, I receive a 'class, interface, or enum expected' when trying to compile my code. I have tried to research on how to fox the problem but I was unfortunately unable to do so as it seems like nothing is working for me...also if there are any errors that would lead up to it not working once this part is fixed, please let me know as to what I can change! The code: class MyDate { //properties of date object private int day, month, year; //Constructor with arguments public MyDate(int day, int month, int year) { this.day = day; this.month = month; this.year = year; } public boolean isValidDate() { if (month > 12 || month < 1 || day < 1) { // if negative values found return false; } else if (year <= 1582 && month <= 10 && day <= 15) { // starting date // checking return false; } // for 31 day months else if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) { if (day > 31) { return false; } } // for 30 day months else if (month == 4 || month == 6 || month == 9 || month == 11) { if (day > 30) { return false; } } else if (month == 2) // February check { if (isLeapYear()) // Leap year check for February { if (day > 29) { return false; } } else { if (day > 28) { return false; } } } return true; } // checks if this year is leap year private boolean isLeapYear() { if (year % 4 != 0) { return false; } else if (year % 400 == 0) { return true; } else if (year % 100 == 0) { return false; } else { return true; } } /** * @return the day */ public int getDay() { return day; } /** * @param day * the day to set */ public void setDay(int day) { this.day = day; } /** * @return the month */ public int getMonth() { return month; } /** * @param month * the month to set */ public void setMonth(int month) { this.month = month; } /** * @return the year */ public int getYear() { return year; } /** * @param year * the year to set */ public void setYear(int year) { this.year = year; } @Override public String toString() { return day + "/" + month + "/" + year; } } import java.util.Scanner; public class MyCalendar { //enums for days of week public static enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY; }; //enum for month of year public static enum Month { JANUARY, FEBRUARY, MARCH, APRIL, MAY, JUNE, JULY, AUGUST, SEPTEMBER, OCTOBER, NOVEMBER, DECEMBER; }; //enums for week numbers public static enum Week { FIRST, SECOND, THIRD, FOURTH; }; //to store Date object private MyDate date; //constructor taking mydate object public MyCalendar(MyDate enteredDate) { this.date = enteredDate; } //main method public static void main(String[] args) { boolean validDate = false; //valid date false Scanner input = new Scanner(System.in); //scanner for input MyDate enteredDate = null; //till valid date found while (!validDate) { System.out.print("Enter the date as day month year : "); //taking input and creating date object enteredDate = new MyDate(input.nextInt(), input.nextInt(), input.nextInt()); //validdating date object if (enteredDate.isValidDate()) { //if valid MyCalendar myCalendar = new MyCalendar(enteredDate); //creating calendar object myCalendar.printDateInfo(); //printing date info myCalendar.printCalendar(); //printing calendar validDate = true; //setting validate to true } else { System.out.println("Please enter a Valid Date..."); } } input.close(); } // returns number of days in current month private int getNumberOfDays() { int days = 31; int month = date.getMonth(); if (month == 4 || month == 6 || month == 9 || month == 11) days = 30; return days; } //print calendar of this month public void printCalender() { System.out.println("\n\nThe Calendar of "+Month.values() [date.getMonth()-1]+" "+date.getYear()+" is :"); int numberOfMonthDays = getNumberOfDays(); Day firstWeekdayOfMonth = getDayOfWeek(1, date.getMonth(), date.getYear()); int weekdayIndex = 0; System.out.println("SUN MON TUE WED THU FRI SAT"); // The order of days // depends on your // calendar for (int day = 0; Day.values()[day] != firstWeekdayOfMonth; day++) { System.out.print(" "); // this loop to print the first day in his // correct place weekdayIndex++; } for (int day = 1; day <= numberOfMonthDays; day++) { if (day < 10) System.out.print(day + " "); else System.out.print(day); weekdayIndex++; if (weekdayIndex == 7) { weekdayIndex = 0; System.out.println(); } else { System.out.print(" "); } } System.out.println(); } //method to print about date information in literal form public void printDateInfo() { System.out.println(date + " is a " + getDayOfWeek(date.getDay(), date.getMonth(), date.getYear()) + " located in the " + Week.values()[getWeekOfMonth() - 1] + " week of " + Month.values()[date.getMonth() - 1] + " " + date.getYear()); } /* * gets day of the week, returns enum type Day * * day of week (h) = (q+(13*(m+1)/5)+K+(K/4)+(J/4)+5J)%7 ,q- day of month, * m- month, k = year of century (year%100), J = (year/100) */ public Day getDayOfWeek(int day, int month, int year) { int q = day; int m = month; if (m < 3) { m = 12 + date.getMonth(); year = year - 1; } int K = year % 100; int J = year / 100; //calculating h value int h = (q + (13 * (m + 1) / 5) + K + (K / 4) + (J / 4) + 5 * J) % 7; Day output = null; if (h < Day.values().length && h >= 0) { output = Day.values()[h - 1]; //getting respective enum value } return output; //returning enum value } // get week number of current date public int getWeekOfMonth() { int days = date.getDay(); int weeks = days / 7; days = days % 7; if (days > 0) weeks++; return weeks; } } The error: MyCalendar.java:120: class, interface, or enum expected import java.util.Scanner; ^ Error given when I move the import to the top (UPDATED): MyCalendar.java:164: cannot find symbol symbol : method printCalendar() location: class MyCalendar myCalendar.printCalendar(); //printing calendar Expected code: java MyCalendar 29/02/2019 29/02/2019 in not a valid date, please re-input a valid date: 25/05/2019 25/05/2019 is a Saturday and located in the fourth week of May 2019 The calendar of May 2019 is: SUN MON TUE WED THU FRI SAT 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 A: the method public void printCalender() should be called or invoked as printCalender() not as printCalendar() your method is printCalender() whereas you are calling printCalendar() which does not exist.
{ "pile_set_name": "StackExchange" }
Q: jQuery get attributes and values of element Say I have this HTML code: <img id="idgoeshere" src="srcgoeshere" otherproperty="value" /> I can reference the element by its id: $('#idgoeshere')) Now, I want to get all the properties and their values on that element: src=srcgoeshere otherproperty=value Is there some way I can do that programmatically using jQuery and/or plain Javascript? A: You can get a listing by inspecting the attributes property: var attributes = document.getElementById('idgoeshere').attributes; // OR var attributes = $('#idgoeshere')[0].attributes; alert(attributes[0].name); alert(attributes[0].value); $(attributes).each(function() { // Loop over each attribute }); A: The syntax is $('idgoeshere').attr('otherproperty') For more information - http://api.jquery.com/attr/
{ "pile_set_name": "StackExchange" }
Q: Find the possible value of $x$ for $ \Bigg\vert \frac{3|x|-2}{|x|-1} \Bigg\vert \ge2 \ $ Find the possible value of $x$ for $$ \left\vert \frac{3|x|-2}{|x|-1} \right\vert \ge 2.$$ A: Set $y = |x|$ and cross-multiply to get $$|3y-2| \ge 2|y-1|$$ This is equivalent to $$9y^2-12y+4 = |3y-2|^2 \ge 4|y-1|^2 = 4y^2-8y+4$$ or $y(5y-4) \ge 0$. Therefore $y \in \langle -\infty, 0] \cup \left[\frac45, +\infty\right\rangle$. Hence $|x| \ge \frac45$ or $|x| = 0$ and by inspection in the original equation we also get $|x| \ne 1$. We conclude $x \in \Big(\left\langle -\infty, -\frac45\right] \cup \{0\} \cup\left[ \frac45, -\infty\right\rangle \Big)\setminus \{-1,1\}$.
{ "pile_set_name": "StackExchange" }
Q: How can I get my first epic mount in WoW? I'm close to level 85 and I want to know the easiest way to get my first epic mount that's different from the common mounts I can buy from vendors. Which one should I go for? And how can I obtain it? I'm a troll hunter. A: You can find detailed information on available mounts at WoWpedia. I'm not going to list all available mounts here, but you can find them all at that page. I'll try to summarize the general approaches you can take to getting a more exciting epic flying mount. Basic wyverns are available from vendors when you hit level 70 and buy the Artisan (300) flying skill. Other mounts like the various drakes are typically available as faction mounts or rare drops. Some are boss drops such as the Bronze Drake, others are reputation rewards such as the Netherwing Drake Mounts or the Red Drake. If you're a tailor, you can craft a flying carpet or its winterized version. Engineers and alchemists can also create flying mounts for themselves. You can also buy this blue wind rider from Dalaran, but it's not terribly different from the common mounts except in colour. Last but not least, there are mounts like the Violet Proto-drake that are awarded for getting certain achievements. As you can see, the list of options is long and varied. Since you're nearing level 85, pretty much any of these should be available to you at least as far as plain level requirements go. Which mount you should go for first depends entirely on what you feel like getting and how much time/gold you're prepared to spend to do it. A: The easiest mount to get that is epic is the Bronze Drake. To ride this mount you will need to purchase Artisan Riding (300) from a flying trainer. You will find the bronze Drake in the Culling of Stratholme Dungeon on Heroic difficulty. On heroic you will be timed so taking a tank and a healer from your guild will make it easier on you. Once you are through the last corridor of the dungeon, the final boss is to the right, but to the left you will find the other boss who drops this Drake 100% of the time.
{ "pile_set_name": "StackExchange" }
Q: Reading the certifcate information of a web page Suppose I visit a web page www.example.com and is successfully loaded into my browser. When this page is loaded, we can see the certificate information www.example.com by clicking on padlock icon (on left side of address). The certificate includes the information like owner/organisation, connection status, certificate verified by, cookies set by the page and so on. Is there any way to get this information programmatically from the browser like by using javascript/Ajax or any other language. A: I found this link very helpful: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/How_to_check_the_secruity_state_of_an_XMLHTTPRequest_over_SSL
{ "pile_set_name": "StackExchange" }
Q: How to enable hibernation in 15.04? I did a clean install of 15.04, tried to enable hibernation per instruction from http://ubuntuhandbook.org/index.php/2014/10/enable-hibernate-option-in-ubuntu-14-10-unity/ but it works only if I boot with upstart and not with systemd. How can I get it to work with systemd? EDIT>After installing hibernate package I can run it from the terminal, but still it is not available in the shutdown menu. A: Create the following file: /etc/polkit-1/localauthority/10-vendor.d/com.ubuntu.desktop.pkla Copy / paste the following content into it: [Enable hibernate by default in upower] Identity=unix-user:* Action=org.freedesktop.upower.hibernate ResultActive=yes [Enable hibernate by default in logind] Identity=unix-user:* Action=org.freedesktop.login1.hibernate;org.freedesktop.login1.handle-hibernate-key;org.freedesktop.login1;org.freedesktop.login1.hibernate-multiple-sessions;org.freedesktop.login1.hibernate-ignore-inhibit ResultActive=yes Log out and check that you can see the hibernate menu item on the login screen, do the same once you logged in. The reason the above manual step needs to be done is that they seem to have disabled hibernate by default in Ubuntu 15.04.
{ "pile_set_name": "StackExchange" }
Q: More on "Cylinder shading with pgf TiKZ" In his answer to Cylinder shading with PGF/TikZ, Jake provides a code to draw a shaded cylinder with a not shaded top. This code draws a cylinder node (from shapes.geometric library) and after that, with a second draw command, an ellipse is drawn over it. I've tried to join both steps within a mycylinder/.style with an append after command option without any success. I still don't completely understand what \pgfinterruptpath, \pgfextra do, so may be my code is not correct. I imagine that covering ellipse must be drawn after shading the cylinder but I don't know how to do it. Could you explain what's wrong? \documentclass[tikz,border=1mm]{standalone} \usetikzlibrary{calc,fit,backgrounds,positioning,arrows,shapes.geometric} \begin{document} \begin{tikzpicture}[font=\sffamily\small, >=stealth', mycylinder/.style={ draw, shape=cylinder, alias=cyl, % Will be used by the ellipse to reference the cylinder aspect=1.5, minimum height=3cm, minimum width=2cm, left color=blue!30, right color=blue!60, middle color=blue!10, % Has to be called after left color and middle color outer sep=-0.5\pgflinewidth, % to make sure the ellipse does not draw over the lines shape border rotate=90, append after command={% \pgfextra{% \pgfinterruptpath % \begin{pgfonlayer}{foreground layer} \fill [blue!10] let \p1 = ($(\tikzlastnode.before top)!0.5! (\tikzlastnode.after top)$), \p2 = (\tikzlastnode.top), \p3 = (\tikzlastnode.before top), \n1={veclen(\x3-\x1,\y3-\y1)}, \n2={veclen(\x2-\x1,\y2-\y1)}, \n3={atan2((\y2-\y1),(\x2-\x1))} in (\p1) ellipse [x radius=\n1, y radius = \n2, rotate=\n3]; % \end{pgfonlayer} \endpgfinterruptpath% } } } ] % Left cylinder. Wrong one. % I would like to draw right cylinder with only one command. \path node [mycylinder, label=below:Wrong] (disc) {}; % Right cylinder. Correct one but with two commands. \path node [mycylinder, right=1cm of disc, label=below:Good] (disc2) {}; \fill [blue!10] let \p1 = ($(cyl.before top)!0.5!(cyl.after top)$), \p2 = (cyl.top), \p3 = (cyl.before top), \n1={veclen(\x3-\x1,\y3-\y1)}, \n2={veclen(\x2-\x1,\y2-\y1)}, \n3={atan2((\y2-\y1),(\x2-\x1))} in (\p1) ellipse [x radius=\n1, y radius = \n2, rotate=\n3]; \end{tikzpicture} \end{document} A: TikZ already includes the possibility to insert a separate path in the current one: the edge. (Unfortunately, you cannot use pgfonlayer here. But as the argument append after command will be executed after the node has been placed, this shouldn’t be an issue here.) Since the CVS version swapped the arguments to the atan2 function (atan2(x, y) to atan2(y, x)), I also included a small block in the preamble to sort this out and define the functions atanXY and atanYX. I also chose to not change the outer seps but instead to subtract \pgflinewidth directly from the radius. It is an annoyance that these values cannot be accessed after the node. Code \documentclass[tikz]{standalone} \usetikzlibrary{calc,shapes.geometric} \pgfmathparse{atan2(0,1)} \ifdim\pgfmathresult pt=0pt % atan2(y, x) \tikzset{declare function={atanXY(\x,\y)=atan2(\y,\x);atanYX(\y,\x)=atan2(\y,\x);}} \else % atan2(x, y) \tikzset{declare function={atanXY(\x,\y)=atan2(\x,\y);atanYX(\y,\x)=atan2(\x,\y);}} \fi \begin{document} \begin{tikzpicture}[font=\sffamily\small, mycylinder/.style={draw, shape=cylinder, aspect=1.5, minimum height=+3cm, minimum width=+2cm, left color=blue!30, right color=blue!60, middle color=blue!10, shape border rotate=90, append after command={% let \p{cyl@center} = ($(\tikzlastnode.before top)!0.5! (\tikzlastnode.after top)$), \p{cyl@x} = ($(\tikzlastnode.before top)-(\p{cyl@center})$), \p{cyl@y} = ($(\tikzlastnode.top) -(\p{cyl@center})$) in (\p{cyl@center}) edge[draw=none, fill=blue!10, to path={ ellipse [x radius=veclen(\p{cyl@x})-1\pgflinewidth, y radius=veclen(\p{cyl@y})-1\pgflinewidth, rotate=atanXY(\p{cyl@x})]}] () }}] \node[mycylinder, label=below:Better?] {}; \end{tikzpicture} \end{document} Output Another idea. The cylinder shape already has the option to fill the two parts differently with the options cylinder body fill=<color>, cylinder end fill=<color> and the switch cylinder uses custom fill. Unfortunately, the shading in cylinder end fill=blue!10, cylinder uses custom fill, preaction={draw=red, left color=blue!30, right color=blue!60, middle color=blue!10} will be drawn on top of the cylinder end fill (which is done in a behindbackgroundpath) even though the shading itself is in a preaction. It may be possible to solve this with a custom shape. The keys Cylinder end shade and Cylinder body shade actually are implemented by setting their content with \tikzset and using \tikz@finish (similar how the backgroundpath and the foregroundpath are applied). Code \documentclass[tikz]{standalone} \usetikzlibrary{shapes.geometric} \pgfset{ Cylinder end fill/.initial=, Cylinder body fill/.initial=, Cylinder end shade/.initial=, Cylinder body shade/.initial=} \makeatletter \pgfdeclareshape{Cylinder}{% \inheritsavedanchors[from=cylinder]% \inheritbackgroundpath[from=cylinder]% \inheritanchorborder[from=cylinder]% \inheritanchor[from=cylinder]{center}\inheritanchor[from=cylinder]{shape center}% \inheritanchor[from=cylinder]{mid}\inheritanchor[from=cylinder]{mid east}% \inheritanchor[from=cylinder]{mid west}\inheritanchor[from=cylinder]{base}% \inheritanchor[from=cylinder]{base east}\inheritanchor[from=cylinder]{base west}% \inheritanchor[from=cylinder]{north}\inheritanchor[from=cylinder]{south}% \inheritanchor[from=cylinder]{east}\inheritanchor[from=cylinder]{west}% \inheritanchor[from=cylinder]{north east}\inheritanchor[from=cylinder]{south west}% \inheritanchor[from=cylinder]{south east}\inheritanchor[from=cylinder]{north west}% \inheritanchor[from=cylinder]{before top}\inheritanchor[from=cylinder]{top}% \inheritanchor[from=cylinder]{after top}\inheritanchor[from=cylinder]{before bottom}% \inheritanchor[from=cylinder]{bottom}\inheritanchor[from=cylinder]{after bottom}% \behindbackgroundpath{% \ifpgfcylinderusescustomfill% \getcylinderpoints% \pgf@x\xradius\relax% \advance\pgf@x-\outersep\relax% \edef\xradius{\the\pgf@x}% \pgf@y\yradius\relax% \advance\pgf@y-\outersep\relax% \edef\yradius{\the\pgf@y}% {% \pgftransformshift{\centerpoint}% \pgftransformrotate{\rotate}% \pgfpathmoveto{\afterbottom}% \pgfpatharc{90}{270}{\xradius and \yradius}% \pgfpathlineto{\beforetop\pgf@y-\pgf@y}% \pgfpatharc{270}{90}{\xradius and \yradius}% \pgfpathclose% \edef\pgf@temp{\pgfkeysvalueof{/pgf/Cylinder body fill}}% \ifx\pgf@temp\pgfutil@empty \edef\pgf@temp{\pgfkeysvalueof{/pgf/Cylinder body shade}}% \ifx\pgf@temp\pgfutil@empty \pgfusepath{discard}% \else % make shading: \begingroup \expandafter\tikzset\expandafter{\pgf@temp} \tikz@finish \fi \else \pgfsetfillcolor{\pgf@temp}% \pgfusepath{fill}% \fi % \pgfpathmoveto{\beforetop}% \pgfpatharc{90}{-270}{\xradius and \yradius}% \pgfpathclose \edef\pgf@temp{\pgfkeysvalueof{/pgf/Cylinder end fill}}% \ifx\pgf@temp\pgfutil@empty \edef\pgf@temp{\pgfkeysvalueof{/pgf/Cylinder end shade}}% \ifx\pgf@temp\pgfutil@empty \pgfusepath{discard}% \else % make shading: \begingroup \expandafter\tikzset\expandafter{\pgf@temp} \tikz@finish \fi \else \pgfsetfillcolor{\pgf@temp}% \pgfusepath{fill}% \fi }% \fi }% } \makeatother \begin{document} \begin{tikzpicture}[font=\sffamily\small, opacity=1, mycylinder/.style={shape=Cylinder, aspect=1.5, minimum height=+3cm, draw, cylinder uses custom fill, Cylinder end fill=blue!10, Cylinder body shade={left color=blue!30, right color=blue!60, middle color=blue!10}, minimum width=+2cm, shape border rotate=90, }] \node[mycylinder, label=below:Betterer?] {}; \end{tikzpicture} \end{document} Output
{ "pile_set_name": "StackExchange" }
Q: SQL to answer: which customers were active in a given month, based on activate/deactivate records Given a table custid | date | action 1 | 2011-04-01 | activate 1 | 2011-04-10 | deactivate 1 | 2011-05-02 | activate 2 | 2011-04-01 | activate 3 | 2011-03-01 | activate 3 | 2011-04-01 | deactivate The database is PostgreSQL. I want an SQL query to show customers that were active at any stage during May. So, in the above, that would be 1 and 2. I just can't get my head around the way to approach this. Any pointers? update Customer 2 was active during May, as he was activated Before May, and not Deactivated since he was Activated. As in, I'm alive this Month, but wasn't born this month, and I've not died. select distinct custid from MyTable where action = 'active' and date >= '20110501' and date < '20110601' This approach won't work, as it only shows activations during may, not 'actives'. A: Note: This would be a starting point and only works for 2011. Ignoring any lingering bugs, this code (for each customer) looks at 1) The customer's latest status update before may and 2) Did the customer become active during may? SELECT Distinct CustId FROM MyTable -- Start with the Main table -- So, was this customer active at the start of may? LEFT JOIN -- Find this customer's latest entry before May of This Year (select max(Date) from MyTable where Date < '2011-05-01') as CustMaxDate_PreMay on CustMaxDate_PreMay.CustID = MyTable.CustID -- Return a record "1" here if the Customer was Active on this Date LEFT JOIN (select 1 as Bool, date from MyTable ) as CustPreMay_Activated on CustPreMay_Activated.Date = CustMaxDate_PreMay.Date and CustPreMay_Activated.CustID = MyTable.CustID and CustPreMay_Activated = 'activated' -- Fallback plan: If the user wasn't already active at the start of may, did they turn active during may? If so, return a record here "1" LEFT JOIN (select 1 as Bool from MyTable where Date <= '2011-05-01' and Date < '2011-06-01' and action = 'activated') as TurnedActiveInMay on TurnedActiveInMay .CustID = MyTable.CustID -- The Magic: If CustPreMay_Activated is Null, then they were not active before May -- If TurnedActiveInMay is also Null, they did not turn active in May either WHERE ISNULL(CustPreMay_Activated.Bool, ISNULL(TurnedActiveInMay.Bool, 0)) = 1 Note: You might need replace the `FROM MyTable' with From (Select distinct CustID from MyTable) as Customers It is unclear to me just looking at this code whether or not it will A) be too slow or B) somehow cause dupes or problems due starting the FROM clause @ MYTable which may contain many records per customer. The DISTINCT clause probably takes care of this, but figured I'd mention this workaround. Finally, I'll leave it to you to make this work across different years. A: Try this select t2.custid from ( -- select the most recent entry for each customer select custid, date, action from cust_table t1 where date = (select max(date) from cust_table where custid = t1.custid) ) as t2 where t2.date < '2011-06-01' -- where the most recent entry is in May or is an activate entry -- assumes they have to have an activate entry before they get a deactivate entry and (date > '2011-05-01' or [action] = 'activate')
{ "pile_set_name": "StackExchange" }
Q: How to only create table if it doesn't exist? Using "object_id('table') IS NULL" doesn't work? I would like to check if the table does not exist, then create one, otherwise, insert data into it. use tempdb if object_id('guest.my_tmpTable') IS NULL begin CREATE TABLE guest.my_tmpTable ( id int, col1 varchar(100) ) end --- do insert here ... The first time run, the table was created but the 2nd run the sybase complains the table already exist. Thanks! A: The reason is that the entire statement - if and its "true" part are compiled as one. If the table exists during compilation - error. So you could put the CREATE TABLE statement into a dynamic sql statemetn EXEC('CREATE TABLE....') Then all that Sybase sees at compilation is: IF object_id('mytab') IS NULL EXEC('something or other') The contents of EXEC are not compiled until execution, by when you know there's no table and all is well.
{ "pile_set_name": "StackExchange" }
Q: How to covert this expression to LINQ Hi I have this FilterAlerts Function which I think can be implemented using LINQ. I am fairly new to C# and need help converting it. Also is there a better way to assign errors to the expression in the end? new public BusinessProfileStateModel Create(BusinessProfileViewModel profileViewModel) { var businessProfileState = base.Create(profileViewModel); if (profileViewModel != null) { businessProfileState.DialogLocations = profileViewModel.DialogLocations; businessProfileState.IsCommunityMember = profileViewModel.IsCommunityMember; businessProfileState.IsLocalReport = profileViewModel.IsLocalReport; businessProfileState.IsMultiLocation = profileViewModel.IsMultiLocation; } return FilterAlerts(businessProfileState); } private BusinessProfileStateModel FilterAlerts(BusinessProfileStateModel businessProfileStateModel) { var errors = new List<BPAlert>(); foreach (BPAlert alert in businessProfileStateModel.Display.Alerts.AllAlerts) { if (AlertFinderUtil.IsValidAlertTypeId(alert)) { errors.Add(alert); } } businessProfileStateModel.Display.Alerts.AllAlerts = errors; return businessProfileStateModel; } } A: You can try this. businessProfileStateModel.Display.Alerts.AllAlerts = businessProfileState.Display.Alerts.AllAlerts.Where(alert => AlertFinderUtil.IsValidAlertTypeId(alert)).ToList(); Hope it helps!
{ "pile_set_name": "StackExchange" }
Q: How to store in a variable an echo | cut result? for example echo "filename.pdf" | cut -d'.' -f 1 This way I get the "filename" string. I'd like to store it in a variable called FILE and then use it like this: DIR=$PATH/$FILE.txt So, my script wants to create a file.txt with the same name of the pdf (not a copy of the file, just the name) This way I tried to assign the result of echo | cut FILE= but I get only "path/.txt" so the filename is missing. A: FILE=$(echo "filename.pdf" | cut -d'.' -f 1)
{ "pile_set_name": "StackExchange" }
Q: How do you enable short-tag syntax in codeigniter? I have an app (CodeIgniter) that uses the <?=$variable?> syntax instead of <?php echo $variable; ?> and I would like for it to work on my local host. What is it that I need to enable in my php.ini file to do this? Please note, I am not asking how to enable short_open_tag, but how to enable this in CodeIgniter. Thanks in advance.. A: In CodeIgniter's config.php: /* |-------------------------------------------------------------------------- | Rewrite PHP Short Tags |-------------------------------------------------------------------------- | | If your PHP installation does not have short tag support enabled CI | can rewrite the tags on-the-fly, enabling you to utilize that syntax | in your view files. Options are TRUE or FALSE (boolean) | */ $config['rewrite_short_tags'] = FALSE; This will also mean that it isn't host dependent. A: Read on this: PHP Short Open Tag: Convenient Shortcut or Short Changing Security? A: Search for php.ini file in your php installed directory open it by any text editor then just you search again "short_open_tag" if you find that line like ";short_open_tag = Off" then just remove the ";" and restart your apache server it will work. But I highly request you not to use php short tag due to not all the web server accept the php short tag.
{ "pile_set_name": "StackExchange" }
Q: Can I install heat mat and backer board over cork flooring? I am installing a new bathroom floor. I plan on getting an electric underfloor heating mat, 2 backer boards for under the heating, screed the mat and tile over this. My question is can I place the back boards on the cork vinyl(even though it's got glue on top) or do I need to remove the cork. Another option is cleaning the glue off the cork and using the cork as the subfloor. Is this possible? Thanks for the help, first timer here. A: When I am redoing a bathroom and adding the needed backer board to a subfloor assembly, I would remove all existing finish floors no matter how many to get back down to the original subfloor. Then evaluate that, repair it if needed, add to it if needed to make it stiff enough for tile, then add the one layer of 1/4" backer board, then the heating wires, screed, then thinset and tile. All these layers together will add up to a reasonably thick floor, if the all original flooring is not removed, you will have a potentially sizable rise in height from one floor to another A: I've never had to do this (install tile over cork), but I think you need to remove the cork. Backer/cement boards needs to be firmly fastened to the sub-floor. Any kind of softness, give, or "springiness" will be transferred up the tiles and will cause the tiles or the tile joints to crack.
{ "pile_set_name": "StackExchange" }
Q: Why wont this position properly using css? This should be simple, it is just three div tags inside of another div tag. The three div tags should just line up in a row. Instead they are lined up vertically. Nothing I do seems to fix it. <head> <link href="css.css" rel="stylesheet" type="text/css" /> </head> <body> <?php function NameChange($num) { $card = $_POST["state".$num]; $spaces = " "; $underscore = "_"; $imagename = str_replace($spaces, $underscore, $card); return $imagename; } ?> <div id="main"> <div id="3c1"> <?php echo '<script type="text/javascript"> function myPopup1() { window.open( "images/'.NameChange(1).'.jpg", "myWindow", "status = 1, height = 691, width = 468, resizable = 0" ) } </script>'; echo '<script type="text/javascript"> function myPopup2() { window.open( "images/'.NameChange(2).'.jpg", "myWindow", "status = 1, height = 691, width = 468, resizable = 0" ) } </script>'; echo '<script type="text/javascript"> function myPopup3() { window.open( "images/'.NameChange(3).'.jpg", "myWindow", "status = 1, height = 691, width = 468, resizable = 0" ) } </script>'; echo '<img src=images/'.NameChange(1).'_tn.jpg />'; echo "<br />"; echo '<input type="button" onClick="myPopup1()" value="Image">'; echo '<script type="text/javascript"> function myPopup1t() { window.open( "/'.$_POST[state1].'.html", "myWindow", "status = 1, height = 691, width = 468, resizable = 0" ) } </script>'; echo '<input type="button" onClick="myPopup1t()" value="Meaning">'; ?> </div> <div id="3c2"> <?php echo '<img src=images/'.NameChange(2).'_tn.jpg />'; echo "<br />"; echo '<input type="button" onClick="myPopup2()" value="Image">'; echo '<script type="text/javascript"> function myPopup2t() { window.open( "/'.$_POST[state2].'.html", "myWindow", "status = 1, height = 691, width = 468, resizable = 0" ) } </script>'; echo '<input type="button" onClick="myPopup2t()" value="Meaning">'; ?> </div> <div id="3c3"> <?php echo '<img src=images/'.NameChange(3).'_tn.jpg />'; echo "<br />"; echo '<input type="button" onClick="myPopup3()" value="Image">'; echo '<script type="text/javascript"> function myPopup3t() { window.open( "/'.$_POST[state3].'.html", "myWindow", "status = 1, height = 691, width = 468, resizable = 0" ) } </script>'; echo '<input type="button" onClick="myPopup3t()" value="Meaning">'; ?> </div> </div> </body> And the CSS #main { width: 808px; margin-right: auto; margin-left: auto; left: auto; right: auto; border-top-style: solid; border-right-style: solid; border-bottom-style: solid; border-left-style: solid; } #main #3c1 { height: 200px; width: 200px; display: inline; } #main #3c2 { height: 200px; width: 200px; display: inline; } #main #3c3 { height: 200px; width: 200px; display: inline; } A: If display:inline is not doing the right thing thing you can float the divs. <div> <div style="float:left">stuff</div> <div style="float:left">stuff</div> <div style="float:left">stuff</div> <br style="clear:both;"/> </div> A: The id's cannot start with numbers. You cannot set height and width (among other attributes) on inline elements. Use display:inline-block for that. Also use a single class if all 3 divs will have the exact same CSS rules.
{ "pile_set_name": "StackExchange" }
Q: netbeans form loading issues Error in loading component: [jDialog]->mainPanel->titleBar cannot create instance of <qualified classname> The component cannot be loaded. Error in loading layout: [JDialog]->mainPanel->[layout] Failed to initialize layout of this container Errors occured in loading the form data. It is not recommended to use this form now in editable mode - data that could not be loaded would be lost after saving the form. Please go through the reported errors, try to fix them if possible, and open the form again. If you choose to open the form as View Only you may see which beans are missing. recently moved a class that was being used in several forms but all the paths in both form and java files were updated to point to the new location. Anyone know what could cause an error like this? Things I have tried: clean + build, removeing and re-adding all library jar files, making sure the title bar and the old version in SVN were identical except for the package changes. Doing the same comparison with their respective form files. A: In the View menu there is an IDE log option that allowed me to see what was happening behind the scenes to cause this error. custom code for the text of one of the labels was throwing an exception.
{ "pile_set_name": "StackExchange" }
Q: UNIX: List files in directory with relative path The question is: What command would you use to list the text files in your fileAsst directory (using a relative path)? The previous question was: Give a command to list the names of those text files, using an absolute path to the fileAsst directory as part of your command. The answer was: ~/UnixCourse/fileAsst/*.txt I was wondering how I can list the files in this directory using a relative path. I've tried several commands including: ls ~/UnixCourse/fileAsst/*.txt|awk -F"/" '{print $NF}' (cd ~/UnixCourse/fileAsst/*.txt && ls ) and a bunch of others. But it keeps telling me their invalid. I know it has to be a correct answer because others have gotten past this. But right now I'm stuck and extremely frustrated =( UPDATE: After going to the CS lab someone helped me figure out the problem. I needed to be in a certain working directory at first, and I wasn't. After switching to that directory all I needed was the command: ../UnixCourse/fileAsst/*.txt and that took care of it for me. Thanks to everyone that helped and I hope this helps someone else. A: try: $ cd ~/UnixCourse/fileAsst/ $ find . as a one-liner (executing in a sub-shell) $ (cd ~/UnixCourse/fileAsst/ && find .) another approach $ (cd ~/UnixCourse && ls fileAsst/*.txt $ ls ~/UnixCourse/fileAsst/*.txt
{ "pile_set_name": "StackExchange" }
Q: Car AC sometime cold sometimes not Recently I have noticed that the air from ac vents sometimes cold, but sometime less cool/fan mode for a while, before return to cold. I also noticed almost continuous "hissing" sound from around the place where cabin filter is located. I checked the low pressure when AC is on max, it shows 32 PSI on ambient temp of 33C (91F) at 48% humidity. Refrigerant is R134a. I have visited repair shop once, and they suspect the selenoid valve in ac compressor gets dirty, so they cleaned it. But I could feel the problem persist, but it does feel better, (the "fan mode" get shorter). They said, the clutch is engaging when its not cold, so its not a clutch or belt issue. I wonder if is it caused by not enough refrigerant? Note : When AC is off, the low pressure is 80 PSI. Thanks! A: I would suggest few areas to inspect. When you notice no cold air from the vent outlets, go and check the A/C tubing under the hood. At least some of them must be freezing cold. Depending on the A/C system type, you might or might not have an orifice valve inside one of the A/C tubes - this will make one part of the tube hot and the other part freezing cold. You can have the refrigerant amount checked by A/C shop - let them suck everything out and refill it back and watch for the difference in amounts. It will cost you few bucks for the job and for some of the refrigerant as not everything can be recovered from the system. If you suspect leak, let the system be tested for leaks. Be aware though, that the vacuum test done by A/C machine doesn't necessarily find a leak unless it's big enough. Best if they have some sort of leak detectors.
{ "pile_set_name": "StackExchange" }
Q: spring application-security configuration bean scan In my project, I needed a custom userDetailsService, So I declaire it like this in certain package: @Service @Ihm(name = "userDetailsService")// ignore Ihm, it's just a custom annotation, which works fine public class UserDetailsServiceImpl implements UserDetailsService And in my application-security.xml file, I added component-scan, <context:component-scan base-package="path(including the userDetailsService for sure)" /> <context:annotation-config /> which didn't help me find my annotated bean, I got bean no defined exception. The only way worked in my case is : 1.remove the service annotation 2.create the bean in the application-security.xml with beans:bean,id,class. this works fine. What's more funny is this, when I kept both the component-scan, and the annotation, I got an ID duplicated(more than one bean, ask to specify the ID) error. More than one UserDetailsService registered. Please use a specific Id reference in <remember-me/> <openid-login/> or <x509 /> elements. So this means the @Service did create the bean, but y won't the security.xml find it? A: Spring Security is auto wiring beans on bean names, for the UserDetailsService that is userDetailsService. @Service public class UserDetailsServiceImpl implements UserDetailsService The code above (like your code) will lead to a bean of the type UserDetailsService however the name is userDetailsServiceImpl and not userDetailsService and hence your bean is never used by Spring Security nor detected by it. (See Spring Reference Guide for naming conventions_ To fix this either change the spring security configuration and put in a reference to your userDetailsServiceImpl bean <authentication-manager> <authentication-provider user-service-ref='userDetailsServiceImpl'/> </authentication-manager> or change the name of your bean by providing the name in the @Service annotation. @Service("userDetailsService") public class UserDetailsServiceImpl implements UserDetailsService Either way will work. Links Using other authentication providers Naming autodetected components
{ "pile_set_name": "StackExchange" }
Q: javascript weird behavior (with Jquery) I have the following code function exibirDialog(div) { $("#divDialogo").ready(function() { $("#divDialogo").dialog({ open: function() { }, close: function() { $(this).dialog("destroy"); }, buttons: { "Print": function() { var popUp = window.open('Print.aspx', "Print", "menubar=0,location=0,height=700,width=700"); //alert(popUp); var x = popUp.document.getElementById('content'); div.clone().appendTo(x); }, "Close": function() { $(this).dialog("destroy"); } } }); }); } Its like: When I click in the Print button the system opens a popup (print.aspx) and copy the div element into the 'content' element. The weird beheavior is: This only works when I uncomment the line "//alert(popUp);" Somebody knows how I do to do this works without the alert? A: The alert gives the page just enough time to load. Your line var x = popUp.document.getElementById('content'); is executed before the content object has the opportunity to be rendered. And because it is not yet on the page, you cannot yet append to it. To wait for the page to load, use the window.opener object. More information about that is available here: http://www.webreference.com/js/tutorial1/opener.html
{ "pile_set_name": "StackExchange" }
Q: SP13: Image behind Table (HTML) I have content editor web part that I have applied html for a table. I would like to upload an image (through HTML script), but I want the image to appear behind the table. I tried using the following code to add the image behind the table, but the image did not appear. <table align="center" style="width: 94%; height: 96%, background="myimage.gif"> Not sure what I am doing incorrectly. Can anyone help me with the issue? Thanks! A: you can use the below css code for background image: background-image: url("Image.jpg"); background-repeat:no-repeat; background-position:top; background-size:cover;
{ "pile_set_name": "StackExchange" }
Q: Alternative approaches to a Minecraft Redstone Simulator I'm just programming a Minecraft Redstone Simulator for Android. I'm doing the simulation with some variations of Dijkstra, but I heard, that the real simulator does something different and updates every redstone block every redstone tick. How is notch doing it? Update I know that he uses a HashSet, this doesn't look like Dijkstra, does it? A: I will call anything that's redstone-related a "redstone block". Every tick, Minecraft iterates through the hashset and updates each redstone block. When more redstone blocks are added, the hashset size is increased, and everything that was in the previous, smaller hashset is scrambled into a random order.
{ "pile_set_name": "StackExchange" }
Q: Eclipse change theme Yesterday when I close eclipse everything was fine. Today I open eclipse and it looks very strange. Some buttons are missing.... and other visual changes. How can I change it back to default look. Btw I'm using: Eclipse Java EE IDE for Web Developers. Version: Mars Release (4.5.0) Build id: 20150621-1200 A: As mentioned in my comment, you can launch eclipse in clean mode by issuing eclipse -clean
{ "pile_set_name": "StackExchange" }
Q: Duplicate calls when using concatMap I want to display in a view the next upcoming event a user is registered to. To do so I need first to retrieve the closest event (in time) the user is registered to and then retrieve the information of this event. Has the list of event a user is registered to is dynamic and so is the event information I need to use two Observable in a row. So I tried to use concatMap but I can see that the getEvent function is called 11 times... I don't understand why and how I could do this better. Here is my controller //Controller nextEvent$: Observable<any>; constructor(public eventService: EventService) { console.log('HomePage constructor'); } ngOnInit(): void { // Retrieve current user this.cuid = this.authService.getCurrentUserUid(); this.nextEvent$ = this.eventService.getNextEventForUser(this.cuid); } The EventService (which contains the getEvent function called 11 times) // EventService getEvent(id: string, company?: string): FirebaseObjectObservable<any> { let comp: string; company ? comp = company : comp = this.authService.getCurrentUserCompany(); console.log('EventService#getEvent - Getting event ', id, ' of company ', comp); let path = `${comp}/events/${id}`; return this.af.object(path); } getNextEventForUser(uid: string): Observable<any> { let company = this.authService.getCurrentUserCompany(); let path = `${company}/users/${uid}/events/joined`; let query = { orderByChild: 'timestampStarts', limitToFirst: 1 }; return this.af.list(path, { query: query }).concatMap(event => this.getEvent(event[0].id)); } And finally my view <ion-card class="card-background-image"> <div class="card-background-container"> <ion-img src="sports-img/img-{{ (nextEvent$ | async)?.sport }}.jpg" width="100%" height="170px"></ion-img> <div class="card-title">{{ (nextEvent$ | async)?.title }}</div> <div class="card-subtitle">{{ (nextEvent$ | async)?.timestampStarts | date:'fullDate' }} - {{ (nextEvent$ | async)?.timestampStarts | date:'HH:mm' }}</div> </div> <ion-item> <img class="sport-icon" src="sports-icons/icon-{{(nextEvent$ | async)?.sport}}.png" item-left> <h2>{{(nextEvent$ | async)?.title}}</h2> <p>{{(nextEvent$ | async)?.sport | hashtag}}</p> </ion-item> <ion-item> <ion-icon name="navigate" isActive="false" item-left small></ion-icon> <h3>{{(nextEvent$ | async)?.location.main_text}}</h3> <h3>{{(nextEvent$ | async)?.location.secondary_text}}</h3> </ion-item> <ion-item> <ion-icon name="time" isActive="false" item-left small></ion-icon> <h3>{{(nextEvent$ | async)?.timestampStarts | date:'HH:mm'}} - {{(nextEvent$ | async)?.timestampEnds | date:'HH:mm'}}</h3> </ion-item> </ion-card> A: The this.af.list(path, { query: query }).concatMap(event => this.getEvent(event[0].id)) is a cold Observable. This means that each time you perform a subscription on it, it will re-execute the underlying stream, which means re-calling the getEvent method. async implicitly subscribes to the Observable, which is why if you count up (nextEvent$ | async) calls in your template, you will see where the 11 comes from. &tldr You need to share the subscription to the stream: this.nextEvent$ = this.eventService.getNextEventForUser(this.cuid) // This shares the underlying subscription between subscribers .share(); The above will connect the stream the first time it is subscribed to but will then subsequently share that subscription between all of the subscribers.
{ "pile_set_name": "StackExchange" }
Q: ggplot2: Stat_function misbehaviour with log scales I am trying to plot a point histogram (a histogram that shows the values with a point instead of bars) that is log-scaled. The result should look like this: MWE: Lets simulate some Data: set.seed(123) d <- data.frame(x = rnorm(1000)) To get the point histogram I need to calculate the histogram data (hdata) first hdata <- hist(d$x, plot = FALSE) tmp <- data.frame(mids = hdata$mids, density = hdata$density, counts = hdata$counts) which we can plot like this p <- ggplot(tmp, aes(x = mids, y = density)) + geom_point() + stat_function(fun = dnorm, col = "red") p to get this graph: In theory we should be able to apply the log scales (and set the y-limits to be above 0) and we should have a similar picture to the target graph. However, if I apply it I get the following graph: p + scale_y_log10(limits = c(0.001, 10)) The stat_function clearly shows non-scaled values instead of producing a figure closer to the solid line in the first picture. Any ideas? Bonus Are there any ways to graph the histogram with dots without using the hist(..., plot = FALSE) function? EDIT Workaround One possible solution is to calculate the dnorm-data outside of ggplot and then insert it as a line. For example tmp2 <- data.frame(mids = seq(from = min(tmp$mids), to = max(tmp$mids), by = (max(tmp$mids) - min(tmp$mids))/10000)) tmp2$dnorm <- dnorm(tmp2$mids) # Plot it ggplot() + geom_point(data = tmp, aes(x = mids, y = density)) + geom_line(data = tmp2, aes(x = mids, y = dnorm), col = "red") + scale_y_log10() This returns a graph like the following. This is basically the graph, but it doesn't resolve the stat_function issue. A: library(ggplot2) set.seed(123) d <- data.frame(x = rnorm(1000)) ggplot(d, aes(x)) + stat_bin(geom = "point", aes(y = ..density..), #same breaks as function hist's default: breaks = pretty(range(d$x), n = nclass.Sturges(d$x), min.n = 1), position = "identity") + stat_function(fun = dnorm, col = "red") + scale_y_log10(limits = c(0.001, 10))
{ "pile_set_name": "StackExchange" }
Q: In vb.net what's the deal with these variable being surrounded by sharp parenthesis? I was reviewing some of my colleagues vb.net code the other day and was mystified at a new level - Unfortunately I don't have the code at hand but it looked something like this: Public Class foo Public Function [new]([bar] As String, [baz] As String) As String Return String.Concat([bar], baz) End Function End Class I have never seen these sharp parenthesis surrounding the name of the function and variable. Anyone can explain to me what the purpose of this is. A: It's because "new" is a keyword and using [ ] is telling the compiler that it should read the keyword as a literal string instead. This way you can use keywords as variable and method names ... if you wanted. I think the usage around the variables [bar] and [baz] is just .... well, because he could.
{ "pile_set_name": "StackExchange" }
Q: Algorithm for Parking Space Allocator System In my office, there are 200 employees who come to the office in their car. But my parking space has slots for parking 160 cars only. Now I want to design and develop an application that issues parking tickets to employees by doing a fair allocation of parking slots. For solving this problem, I was thinking of designing some algorithm like below: We have 200 employees, 5 working days and 160 available parking slots. Create a pool of 5 colors and assign one color to each of the employees. 40 - green - Mon, Tue, Wed, Thur 40 - blue - Tue, Wed, Thur, Fri 40 - red - Wed, Thur, Fri, Mon 40 - white - Thur, Fri, Mon, Tue 40 - black - Fri, Mon, Tue, Wed With this, we will have only 160 cars coming to the office on any given day. Now I want to enhance the above algorithm to make this system more effective and efficient for the following use-case: Employees can apply for a leave, in such cases, his assigned ticket will be unused and parking slot will remain empty - not a very efficient use of the resource. I want to distribute such empty slots to other employees in a fair manner. What is the most, or at the very least, a more optimal algorithm for solving this? A: It's easier to understand this system if you change the way the color codes are explained: Blue = No parking on Mon Red = No parking on Tue White = No parking on Wed Black = No parking on Thr Green = No parking on Fri Once you see that, this is actually not a complicated problem: Employees can apply for a leave, in such cases, his assigned ticket will be unused and parking slot will remain empty - not a very efficient use of the resource. I want to distribute such empty slots to other employees in a fair manner. What is the most, or at the very least, a more optimal algorithm for solving this? It's Monday and I'm calling in sick. I have a green ticket. Someone with a blue ticket could use it. Pick a blue ticket name out of a hat and give them my green ticket for the day. Done. If you fear someone wining twice before someone wins once you could switch to a single deck shuffle. It doesn't tip the odds in favor of anyone but it limits how unlucky someone can be. The drawback is it requires you to preserve state. The lucky winner just has to hope I called in before they got on the bus. Assigning these tickets is easy. Communicating assignment changes is the harder problem to solve.
{ "pile_set_name": "StackExchange" }
Q: How can Silent Image be used to obscure vision in combat in 5E? In my party I have a warlock who is partial to illusion magic. At second level, he took the 'Misty Visions' invocation, with the intent of using Silent Image to keep the party shrouded in illusory fog during combat. His logic is that because the party knows it is an illusion, they are never hindered by it, but the enemies are effectively blinded to the players until they manage to discern the illusion. In one instance, this resulted in two party members swinging with advantage on a bugbear who couldn't see them, and who had to use his action on the next turn to inspect the illusion. In this situation, Silent Image gives most of the benefits of Darkness, a second level spell, without negatively affecting the party, and without costing a spell slot. I don't want to have to tell the player "No, that's too OP," but I'm not sure how to interpret the mechanics in a way that isn't broken. In short: What does RAW say about using Silent Image on top of or between close quarters combatants? How can Silent Image be interpreted/altered such that it can provide some benefit in combat, while maintaining the intended power level? A: Cost This is not without cost to the warlock; he has chosen to use one of his two invocations to get this thereby forgoing other choices. In addition, he uses an action to cast it and an action to move it; unless your battles are very static he would need to move it a lot. Remember, the most limited resource any creature has is not its spell slots or hit dice; it is its actions, it only gets one per turn. Good players know this and they should be thinking every turn "Is this the best thing I can do with my action right now?" Innovation This is a very clever and imaginative use of the spell - this is something that you should encourage in your players; not discourage. I have had a wizard use Silent Image to create an picture of a hallway that the rogue could walk behind; this not only gave advantage, it also allowed sneak attack against, coincidently, a bugbear. Disadvantages A 15 foot cube of fog rolling towards the bugbear is going to negate surprise (its just not natural) and allow it to make an active perception check to find out where the PCs are in the cloud. The bugbear can then use its action to attack (with disadvantage); following which it can see through the cloud because "Physical interaction with the image reveals it to be an illusion" - sticking your morning star into it qualifies as "physical interaction". It doesn't work that way, anyhow You say: " because the party knows it is an illusion, they are never hindered by it". Where does it say that in the rules? The relevant text of the spell is: Physical interaction with the image reveals it to be an illusion, because things can pass through it. A creature that uses its action to examine the image can determine that it is an illusion with a successful Intelligence (Investigation) check against your spell save DC. If a creature discerns the illusion for what it is, the creature can see through the image. There are only 2 ways to see through the image, "Physical interaction" or "use your action" and make a save. Knowing that it is an illusion doesn't allow you to see through it.
{ "pile_set_name": "StackExchange" }
Q: How can I create scrollable columns in Bootstrap? I created a new template file template-home2.php in a Wordpress Theme. In there I have a row with 3 columns, I would like to make each of these columns scrollable instead of the entire page. How can I achieve that? I have a class scrollable that I apply to the outer section of the page to make it scrollable. <section class="<?php if( get_theme_mod( 'hide-player' ) == 0 ){ echo "w-f-md";} ?>" id="ajax-container"> <section class="hbox stretch bg-black dker"> <section> <section class="vbox"> <section class="scrollable"> <div class="row"> <div class="col-md-5 no-padder no-gutter"> some data </div> <div class="col-md-4 no-padder no-gutter"> some data </div> <div class="col-md-3 no-padder no-gutter"> some data </div> </div> </section> </section> </section> </section> </section> When I remove the class β€œscrollable” from the main section and include it in the column div, the column disappears and the other 2 columns overflow on the elements below. This is the relevant CSS .scrollable { overflow-x: hidden; overflow-y: auto; } .no-touch .scrollable.hover { overflow-y: hidden; } .no-touch .scrollable.hover:hover { overflow: visible; overflow-y: auto; } .slimScrollBar { border-radius: 5px; border: 2px solid transparent; border-radius: 10px; background-clip: padding-box !important; } Thank you for your help. UPDATED CODE .homecol1, .homecol2, .homecol3 { position: absolute; overflow-y: scroll; } <section class="<?php if( get_theme_mod( 'hide-player' ) == 0 ){ echo "w-f-md";} ?>" id="ajax-container"> <section class="hbox stretch bg-black dker"> <section> <section class="vbox"> <section class="scrollable"> <div class="row"> <div class="col-md-5 no-padder no-gutter homecol1"> some data </div> <div class="col-md-4 no-padder no-gutter homecol2"> some data </div> <div class="col-md-3 no-padder no-gutter homecol3"> some data </div> </div> </section> </section> </section> </section> </section> A: To achieve this, you will first need to give each column a class. Then you need to give them the following properties: .your-class { position: absolute; overflow-y: scroll; } You may also want to give your body the property overflow: hidden; Please tell me if this works and if not I'll help further! Edit: Created a JSFiddle https://jsfiddle.net/mjmwaqfp/2/
{ "pile_set_name": "StackExchange" }
Q: MongoDB increment number in subdocument My mongoDB document looks like this: { valOne: "one", valTwo: "two", valThree: { threeOne: 0, threeTwo: 0 } } i would like to increment either "threeOne" or "threeTwo" depending on the user request. My code so far: var whichFieldToUpdate = request.body.field; //can be either threeOne or threeTwo var id = new BSON.ObjectID(request.body.id); //contains document id db.collection('name').update({_id: id}, {$inc: { ?????? } }, function(err, result) { }); ???? should be something like this: {$inc: {valThree: {whichFieldToUpdate : 1 } } A: var field = 'valThree.' + request.body.field; var inc = {}; inc[field] = 1; db.collection('name').update({_id: id}, {$inc: inc } }, function(err, result) { });
{ "pile_set_name": "StackExchange" }
Q: How does this "integration" work? $\vec{x}\cdot\frac{\partial \vec{x}}{\partial y}= \frac{\partial}{\partial y}(\frac{1}{2}\vec{x}^{2})$ Various derivations I recently looked up contained this sort of "steps". I fail to understand how what I suppose to be the Sum/Integral over $xdx$ can equal $xdx$ itself Ex.: $$\frac{d}{dt}(\dot{\vec{r}_i}\cdot\frac{\partial\dot{\vec{r}_i}}{\partial\dot{q_j}})-\dot{\vec{r}_i}\cdot\frac{\partial\dot{\vec{r}_i}}{\partial q_j}=\frac{d}{dt}\frac{\partial}{\partial\dot{q_j}}(\frac{1}{2}\dot{\vec{r}_i}^{2})-\frac{\partial}{\partial q_j}\cdot(\frac{1}{2}\dot{\vec{r}_i}^{2})$$ But I have yet to understand what exactly is happening here :( I would be pleased if you could tell me what I am missing. A: Take it from the RHS instead, and use the product rule: \begin{align} \frac{\partial}{\partial y}\left(\frac{1}{2}x^2\right) & =\frac{1}{2}\left[ \frac{\partial x}{\partial y}\cdot x+ x\cdot\frac{\partial x}{\partial y} \right] \\ & = x\cdot\frac{\partial x}{\partial y}, \end{align} because the dot product is commutative.
{ "pile_set_name": "StackExchange" }
Q: Policy for SE employees influencing community decisions using mod powers Under what conditions, if ever, is it acceptable for SE employees to influence community matters on the Meta site of a community they do not actively participate in by upvoting or downvoting posts? I’m not talking about removing spam or obviously remove-worthy content, but about using voting powers, granted only as part of the employee mod diamond and not earned as privilege, to modify the outcome of community-related votes by upvoting or downvoting individual posts. Examples for community matters: questions of scope community projects (for example: contests or blogs) community ads A: Most of the time it is a bad idea for SE employees to intervene in anything but obvious cases (the big exception is if the mods are unavailable). Moderator actions by unfamiliar users are much more likely to create some controversy than if the site mods had performed them. So in any case that isn't entirely obvious, SE employees should generally prefer to notify the site mods and let them handle it. Jeff and Joel used to be more active in using mod powers, and I experienced that on Skeptics as a mod directly. They certainly had a point when they acted, but it would have been much smoother if they had asked us mods to handle those issues instead of acting themselves on issues that weren't settled at that time. There are some exceptions that we just have to accept, these are mostly legal issues like DMCA notices. I personally don't think it's a big deal if an SE employee performs a mod action. But there are a lot of ways to screw this up that create drama and additional work for the mods. One thing I'd like to emphasize is that site mods should feel comfortable to override SE employees when they perform moderator actions, unless the SE employees indicate that there are legal reasons or they're enforcing the "Be Nice" rules. The details of running a site are up to the local community, if SE has a fundamental issue with how a site is run they have to take it to meta and discuss it directly with the mods. Otherwise the sites should feel free to set their rules within the scope of the code of conduct. I misread the question when answering, and my points are about the main site. But my answer isn't really different for meta. They should behave the same way as the site mods, and if there is conflict the site mods should feel free to override the decisions of SE employees unless they indicate that there are legal reasons or that the issue is violating one of the few global rules like the code of conduct. And there are no rules about who can vote on meta sites. I have proposed in the past to only allow users active on the main site to cast votes on meta, but that didn't go anywhere. It doesn't seem useful to try to establish any rules on voting as it is secret, so you could never enforce them anyway A: My short two cents: I see no problem if it's restricted to upvote or downvote only. Those are not mod powers, anyone can gain them quickly enough. Most employees have the association bonus so can upvote anywhere anyway, the missing 20 rep for downvote are really trivial. I do have a problem with using actual mod/high rep powers like closing questions, deleting posts etc. A: My personal perspective: First off, in my opinion, a hard-and-fast rule is not appropriate here. Voting is private, so a rule banning voting not enforceable. There's no point in making a rule that can't be enforced. Also, what makes sense will depend on the context, so a bright-line rule is not appropriate. Instead, I think it makes the most sense to focus on norms and principles, and what we'd advocate for. Our general principle is that of self-governance: a site is run by the site's community, and we want policy decisions to be made by those who are part of the community, rather than by outsiders. We'd also like people to be informed about the issues before voting. Generally speaking, we'd probably discourage people who aren't active in the community and aren't informed about the issues from voting on policy questions. Another principle is that of self-governance: empirically, communities seem to work better when they make their own decisions and are given authority and empowered to do that. So, if SE employees vote on a heated issue, there's a risk that this sense gets violated, and that can lead to dysfunctional results. I would hope that SE employees will take this into account before taking a position. But I think it's also important to recognize that there are situations where SE employees may have an important and valuable contribution to make. They may bring useful experience from other sites, or a helpful perspective. It would be great to have them involved in those cases. I also think it doesn't make sense to lump all SE employees together. To give an example, there may be a significant difference between a CM vs a marketing representative. A CM is likely going to bring a lot of experience in related matters, and I'd love to have CMs participating in our meta discussions. As a general rule of thumb, I think we should trust SE employees to self-assess the situation, and welcome and encourage them to participate in meta discussions and upvote or downvote posts if they feel that the benefits outweigh the risks. If it becomes a problem, we could discuss, but I don't think it's worth setting a more specific general rule. Lest it be unclear, I think it's absolutely appropriate for SE employees to participate in meta discussion by posting questions, answers, and comments. Finally, I'd like to provide some context. You mention "using voting powers, granted only as part of the employee mod diamond and not earned as privilege" -- I think some perspective is in order here. It only takes 101 reputation to have the privilege to upvote, and 125 reputation to have the privilege to downvote. Are we really arguing about a privilege that's granted to people at 101 reputation, or 125 reputation? There's nothing magical about the reputation threshold; it's a heuristic for identifying people who have some experience with the site and some exposure to the model. Indeed, you can gain 101 reputation via the association bonus with no experience or activity on the site at all, as long as you have some activity on some other Stack Exchange site. I think it's likely that most SE employees are going to have that at least as much as someone who uses their association bonus to upvote a post on Meta, or a new user who just received 125 reputation, so I can't see a big deal here with SE employees having that privilege. Related: Should Community Managers remain impartial during Moderator elections?.
{ "pile_set_name": "StackExchange" }
Q: How do you determine the proper rate of descent for landing? I'm trying to use a simulator to learn to land properly. One part that I'm finding really tricky is picking a proper rate of descent. I know I'm supposed to do my best to keep it so I have two red lights and two white lights on the Precision Approach Path Indicator (PAPI), but at the moment I basically am just eyeballing it and adjusting my course whenever the lights aren't right. I have to assume, though, that for any given airspeed there is a rate of descent I can maintain that will keep me right in the middle of the preferred glide slope for that airport. I just have no idea how to figure it out. Is there an application or formula that is preferred for this? Or is it time to learn Vector Calculus? PS- I did check this question to see if it related. But that question is about starting the descent from cruise. I'm talking about rate of descent for final. I did also check this answer, but it's about using the PAPI/VASI lights. I'm looking for a formula to figure out the proper rate of descent during final for a given speed. A: Assuming you want a 3 degree glide slope, just take 5 times your ground speed in knots as a starting point. As an example, approaching at 90kt ground speed in a light aircraft, go for 450feet per minute. at 140kt in a jet, try 700fpm. If you're flying a jet outside of 4 miles, and the controller wants you to keep the speed up at 200kt then descend 1000fpm. It's not perfect, but it works pretty well for a first guess, and you can adjust as necessary. Of course, your ground speed is not the same as your air speed, and even for a constant IAS it will likely vary as you descend and the wind changes. Another way to think about this is that a 3 degree glideslope is almost exactly 300ft per nautical mile. If you're 2 miles out and 700 feet up, then you need to descend a bit faster, conversely, if you're at 500 feet, you need to descend slower. A third related rule of thumb is that your final approach speed (in CAS, although IAS is good enough in most aircraft) is 1.3 times your stall speed in the landing configuration (Vso). So if you stall at 100 knots, you want to approach at 130KIAS. IFR approaches are all about having an initial guess at these numbers in your head, trying them out, and then adjusting as the conditions require. If you're good at the guesses then the adjustments will be very small.
{ "pile_set_name": "StackExchange" }
Q: Updating IIS 5.0 to IIS 6.0 I want to update the IIS server from 5.0 to 6.0 or higher. The condition is that I cant upgrade the server. My machine is Windows XP SP3 Is there any way I can only update the IIS. A: You can install IIS Express 7.5 on Windows XP. Note that the Express version is a lightweight (yet fully featured) version of IIS meant for development purposes, not production hosting. You shouldn't use Windows XP as a production server anyway.
{ "pile_set_name": "StackExchange" }
Q: Should I invest my time in making my site HTTPS-only? I'm building a Django website that does not need to have registration/authentication. The only sensitive part is a form with a reCaptcha v2. Of course I'm embedding the CSRF token, which then I read with Javascript and send it with Ajax requests. Is HTTPS needed in this case? I'm somewhat confused, since as far as I know the token can be used only once. A: Is HTTPS needed in this case? In every case that I can think of HTTPS is beneficial. The trivial case is if you don't have sessions, why would you need a secure connection if there are no sessions and everything is public? Having a secure connection actually helps your Google PageRank, and it also helps the user feel more secure by visiting your site If you actually have sessions and dynamic content the benefits are of course more substantial. One easy way to implement SSL/TLS certificates is using CloudFlare or some similar service.
{ "pile_set_name": "StackExchange" }
Q: Python Port Scanner 2.1 I made lots of changes to the script presented in my previous question. I was tempted to edit that one with the new code, but it would invalidate @200_success's helpful answer. It was also disallowed on a Meta thread. So I apologize for the new question, but it seemed like the right thing to do. Again, any and all tips are appreciated! Also, this is my first time writing any docstrings, so if I'm breaking convention, let me know. #!/usr/bin/env python3 import argparse import errno import functools import multiprocessing import os import platform import socket import time from concurrent.futures import ThreadPoolExecutor from concurrent.futures import ProcessPoolExecutor DEFAULT_HOST = '127.0.0.1' DEFAULT_TIMEOUT = 1 DEFAULT_THREADS = 512 PORT_RANGE = range(1, 65536) def tcp_ping(host, port): """ Attempts to connect to host:port via TCP. Arguments: host: IP address or URL to hit port: Port to hit Returns: port number, if it's available; otherwise False """ try: with socket.socket() as sock: sock.connect((host, port)) print(str(port) + ' Open') return port except socket.timeout: return False except socket.error as socket_error: if socket_error.errno == errno.ECONNREFUSED: return False raise def perform_scan(host, use_threads = False): """ Perform a scan on all valid ports (1 - 65535), either by spawning threads or forking processes. Arguments: host: IP address or URL to scan use_threads: whether or not to use threads; default behaviour is to fork processes Returns: list of available ports """ if use_threads: executor = ThreadPoolExecutor(max_workers = DEFAULT_THREADS) else: executor = ProcessPoolExecutor() with executor: ping_partial = functools.partial(tcp_ping, host) return list(filter(bool, executor.map(ping_partial, PORT_RANGE))) def is_address_valid(host): """ Validate the host's existence by attempting to establish a connection to it on port 80 (HTTP). Arguments: host: IP address or URL to validate Returns: bool indicating whether the host is valid """ try: with socket.socket() as sock: sock.connect((host, 80)) return True except socket.gaierror: return False except (socket.timeout, socket.error): return True def scan_ports(host = DEFAULT_HOST, timeout = DEFAULT_TIMEOUT): """ Scan all possible ports on the specified host. If the operating system is detected as Windows, the ports will be scanned by spawning threads. Otherwise, new processes will be forked. Arguments: host: IP address or URL to scan timeout: connection timeout when testing a port """ # Set defaults if CLI arguments were passed in but not specified if host is None: host = DEFAULT_HOST if timeout is None: timeout = DEFAULT_TIMEOUT # Strip the protocol from the URL, if present if '://' in host: host = host[host.index('://') + 3:] # Set the timeout for all subsequent connections socket.setdefaulttimeout(timeout) # Validate the IP/host by testing a connection if not is_address_valid(host): print('DNS lookup for \'' + host + '\' failed.') return # Perform the scan. On Windows, thread. On all others, fork. print('Scanning ' + host + ' ...') start_time = time.clock() if os.name == 'nt': print('Running on Windows OS.') available_ports = perform_scan(host, use_threads = True) elif os.name == 'posix': print('Running on *Nix OS.') available_ports = perform_scan(host) else: print('Unidentified operating system: ' + os.name + ' [' + platform.system() + ' ' + platform.version() + ']') available_ports = perform_scan(host) end_time = time.clock() print('Done.') # Display results print() print('Time elapsed: ' + format(end_time - start_time, '.2f') + ' sec') available_ports.sort() print() print(str(len(available_ports)) + ' ports available.') print(available_ports) def main(): arg_parser = argparse.ArgumentParser() arg_parser.add_argument('-ip', '--host', help = 'IP address/host to scan') arg_parser.add_argument('-t', '--timeout', help = 'Connection timeout in seconds', type = int) args = arg_parser.parse_args() scan_ports(args.host, args.timeout) if __name__ == '__main__': main() A: Trying to connect to TCP port 80 in order to check whether the DNS lookup succeeds is overkill. You should just call socket.gethostbyname(). A: I notice a few little things that I would adjust just from a housekeeping perspective. You import multiprocessing but I don't see where it is used.. I would remove if it is not needed. some small pep8 stuff - Keyword args should not have spaces around the equal, 2 blank lines between each function, and more than 80 line length on the argpase.add_arg near the bottom.
{ "pile_set_name": "StackExchange" }
Q: Find all functions from $\mathbb{Z}$ to $\mathbb{Z}$ such that $f(x+y)=f(x)+f(y)$. Find all functions from $\mathbb{Z}$ to $\mathbb{Z}$ such that $f(x+y)=f(x)+f(y)$. We showed these claims: Claim1. $f(0)=0$. Claim2. $f(-x)=-f(x)$. But, how should I show that there is no other $g$ function from $\mathbb{Z}$ to $\mathbb{Z}$ which satisfies $g(x+y)=g(x)+g(y)$. A: Hint: Every positive integer is a sum of 1's.
{ "pile_set_name": "StackExchange" }
Q: Subtract aggregate of only certain rows from only other certain rows in the same table? product saletype qty ----------------------------- product1 regular 10 product1 sale 1 product1 feature 2 I have a sales table as seen above, and products can be sold 1 of 3 different ways (regular price, sale price, or feature price). All sales regardless of type accumulate into regular, but sale and feature also accumulate into their own "saletype" also. So in the above example, I've sold 10 products total (7 regular, 1 sale, 2 feature). I want to return the regular quantity minus the other two columns as efficiently as possible, and also the other saletypes too. Here is how I am currently doing it: create table query_test (product varchar(20), saletype varchar(20), qty int); insert into query_test values ('product1','regular',10), ('product1','sale',1), ('product1','feature',2) select qt.product, qt.saletype, CASE WHEN qt.saletype = 'regular' THEN sum(qt.qty)-sum(lj.qty) ELSE sum(qt.qty) END as [qty] from query_test qt left join ( select product, sum(qty) as [qty] from query_test where saletype in ('sale','feature') group by product ) lj on lj.product=qt.product group by qt.product, qt.saletype; ...which yields what I am after: product saletype qty ----------------------------- product1 feature 2 product1 regular 7 product1 sale 1 But I feel like there has to be a better way than essentially querying the same information twice. A: You can use the window function sum and some arithmetic to do this. select product, saletype, case when saletype='regular' then 2*qty-sum(qty) over(partition by product) else qty end as qty from query_test This assumes there is atmost one row for saletype 'regular'.
{ "pile_set_name": "StackExchange" }
Q: Cannot read the next data row for the dataset 'Dataset3',Conversion Failed when converting varchar value to datatype int I am running a report with 3 parameters. The second parameter gets populated according to the value selected in the First parameter and the third parameter gets populated according to the second. I can select multiple values in 2nd and 3rd parameter. When I select 2 values in the second parameter the third one get populated and when I do SELECT ALL even then it works . But when I select 3 or more values it throws an error. An error has during local reporting Cannot read the next data row for the dataset 'Dataset3', Conversion Failed when converting the varchar value '430.2' to datatype int Can you please tell me what my approach should be. A: Can you please tell me what my approach should be. The problem is with the data and the dataset queries. You should run the query behind dataset 2 and determine what the 3 values are that start giving you trouble. Inspect if those values are in fact of the correct data type (the type of your parameter). Quite possibly one of the values is "430.2" whereas the type of your parameter is INT. If that doesn't work, then you should execute your query behind dataset 3 so that the parameter in the WHERE myval IN (@Param3) bit is replaced by a comma-seperated list of the values you retrieved with the earlier query. If those both turn up nothing then the next step may be to run the SQL Profiler and pick up the actual queries SSRS is sending to the server. Pick out those queries, and try to run them manually to debug the problem. One additional thing you may want to check is if the field mapping settings for your datasets matches the types that are actually returned by the dataset queries.
{ "pile_set_name": "StackExchange" }
Q: Understanding Deadlocks in MySQL I am new to MySQL, I used to work in Oracle database. I am having some problem in resolving Deadlocks in my application. Please help me to understand the issue. Table Definition: CREATE TABLE `APPLICATION` ( `ID` varchar(60) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL, `APPLICATION_NUMBER` varchar(35) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL, `STATUS` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL, `SUB_STATUS` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL, `SOURCE_TYPE` varchar(30) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL, `SOURCE_ID` varchar(30) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL, `SOURCE_CHANNEL` varchar(60) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL, `PRODUCT_PROGRAM` varchar(30) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL, `LOAN_TYPE` varchar(30) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL, `ASSIGNED_TO` varchar(60) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL, `CREATED_BY` varchar(60) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL, `CREATION_DATE` datetime DEFAULT NULL, `LAST_UPDATE_DT` datetime DEFAULT NULL, `LAST_UPDATE_BY` varchar(60) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL, `LOAN_AMOUNT` decimal(38,0) DEFAULT NULL, `INSURANCE_OPT_IN` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL, `RCU_STATUS` varchar(30) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL, `TVR_COMMENTS` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL, `TVR_DECISION` varchar(60) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL, `MM_PAID_TO` varchar(60) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL, `PURPOSE_OF_LOAN` varchar(60) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL, `MARGIN_MONEY` double DEFAULT NULL, `PAYMENT_MODE` varchar(60) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL, `IS_ELIGIBLE` decimal(1,0) DEFAULT NULL, `CRM_STATUS` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL, `CRM_REASON` varchar(150) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL, `IS_INTERESTED_CLI` varchar(1) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL, `IS_INTERESTED_CI` varchar(1) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL, `CRITICAL_ILLNESS` varchar(30) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL, `CREDIT_LIFE_INSURANCE` varchar(30) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL, `CREATE_USER` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL, `CREATE_DATE` datetime DEFAULT NULL, `LAST_UPDATE_USER` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL, `LAST_UPDATE_DATE` datetime DEFAULT NULL, `STATUS_ID` bigint(35) DEFAULT NULL, `SUBSTATUS_ID` bigint(35) DEFAULT NULL, `DOCUMEMNTUPLOAD_COMMENTS` varchar(2000) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL, `DOCUMEMNTUPLOAD_ACK` decimal(1,0) DEFAULT NULL, `NO_OF_FINANCIERS_FOR_ALL_ASSET` decimal(3,0) DEFAULT NULL, `DUPLICATED_FROM` varchar(100) DEFAULT NULL, PRIMARY KEY (`ID`) USING BTREE, UNIQUE KEY `UK_APPLICATION` (`APPLICATION_NUMBER`), KEY `FK_APL_STATID` (`STATUS_ID`) USING BTREE, KEY `FK_APL_SUBSTATID` (`SUBSTATUS_ID`) USING BTREE, CONSTRAINT `FK_APL_STATID` FOREIGN KEY (`STATUS_ID`) REFERENCES `STATUS` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT, CONSTRAINT `FK_APL_SUBSTATID` FOREIGN KEY (`SUBSTATUS_ID`) REFERENCES `SUB_STATUS` (`ID`) ON DELETE RESTRICT ON UPDATE RESTRICT ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci My Deadlock Details from the SHOW ENGINE INNODB STATUS: ------------------------ LATEST DETECTED DEADLOCK ------------------------ 2019-11-22 04:48:06 0x2ad75cf91700 *** (1) TRANSACTION: TRANSACTION 291327, ACTIVE 37 sec fetching rows mysql tables in use 1, locked 1 LOCK WAIT 48 lock struct(s), heap size 8400, 1540 row lock(s), undo log entries 5 MySQL thread id 14042, OS thread handle 47099630130944, query id 4174847 172.29.24.227 bpapi updating UPDATE APPLICATION SET NO_OF_FINANCIERS_FOR_ALL_ASSET = 7 WHERE id >'' AND APPLICATION_NUMBER = '001601' *** (1) WAITING FOR THIS LOCK TO BE GRANTED: RECORD LOCKS space id 3803 page no 21 n bits 144 index PRIMARY of table `BAPIDB`.`APPLICATION` trx id 291327 lock_mode X waiting Record lock, heap no 72 PHYSICAL RECORD: n_fields 42; compact format; info bits 128 0: len 30; hex 65646466383861382d633733342d346561332d393665302d396366343234; asc eddf88a8-c734-4ea3-96e0-9cf424; (total 36 bytes); 1: len 6; hex 000000046e42; asc nB;; 2: len 7; hex 02000000fa0518; asc ;; 3: len 6; hex 303031353930; asc 001590;; 4: len 4; hex 31303033; asc 1003;; 5: len 4; hex 31303033; asc 1003;; 6: SQL NULL; 7: SQL NULL; 8: len 6; hex 506f7274616c; asc Portal;; 9: SQL NULL; 10: SQL NULL; 11: SQL NULL; 12: len 30; hex 35633131613436612d303963302d313165612d396533372d396165613961; asc 5c11a46a-09c0-11ea-9e37-9aea9a; (total 36 bytes); 13: SQL NULL; 14: len 5; hex 99a4ac4b92; asc K ;; 15: len 11; hex 427573696e657373415049; asc BusinessAPI;; 16: SQL NULL; 17: SQL NULL; 18: SQL NULL; 19: SQL NULL; 20: SQL NULL; 21: SQL NULL; 22: SQL NULL; 23: SQL NULL; 24: SQL NULL; 25: SQL NULL; 26: len 7; hex 53554343455353; asc SUCCESS;; 27: len 27; hex 5265636f72642055706461746564205375636365737366756c6c79; asc Record Updated Successfully;; 28: SQL NULL; 29: SQL NULL; 30: SQL NULL; 31: SQL NULL; 32: SQL NULL; 33: SQL NULL; 34: SQL NULL; 35: SQL NULL; 36: SQL NULL; 37: SQL NULL; 38: SQL NULL; 39: SQL NULL; 40: SQL NULL; 41: SQL NULL; *** (2) TRANSACTION: TRANSACTION 291891, ACTIVE 4 sec starting index read mysql tables in use 1, locked 1 22 lock struct(s), heap size 1136, 10 row lock(s), undo log entries 8 MySQL thread id 13972, OS thread handle 47104466163456, query id 4178089 172.29.25.88 bpapi updating UPDATE APPLICATION SET APPLICATION_NUMBER=IFNULL('001590', APPLICATION_NUMBER), STATUS=IFNULL('1003', STATUS), SUB_STATUS=IFNULL('1003', SUB_STATUS), CRM_STATUS=IFNULL('SUCCESS', CRM_STATUS), CRM_REASON=IFNULL('Record Created Successfully', CRM_REASON) WHERE ID='eddf88a8-c734-4ea3-96e0-9cf424ced71e' *** (2) HOLDS THE LOCK(S): RECORD LOCKS space id 3803 page no 21 n bits 144 index PRIMARY of table `BAPIDB`.`APPLICATION` trx id 291891 lock mode S locks rec but not gap Record lock, heap no 72 PHYSICAL RECORD: n_fields 42; compact format; info bits 128 0: len 30; hex 65646466383861382d633733342d346561332d393665302d396366343234; asc eddf88a8-c734-4ea3-96e0-9cf424; (total 36 bytes); 1: len 6; hex 000000046e42; asc nB;; 2: len 7; hex 02000000fa0518; asc ;; 3: len 6; hex 303031353930; asc 001590;; 4: len 4; hex 31303033; asc 1003;; 5: len 4; hex 31303033; asc 1003;; 6: SQL NULL; 7: SQL NULL; 8: len 6; hex 506f7274616c; asc Portal;; 9: SQL NULL; 10: SQL NULL; 11: SQL NULL; 12: len 30; hex 35633131613436612d303963302d313165612d396533372d396165613961; asc 5c11a46a-09c0-11ea-9e37-9aea9a; (total 36 bytes); 13: SQL NULL; 14: len 5; hex 99a4ac4b92; asc K ;; 15: len 11; hex 427573696e657373415049; asc BusinessAPI;; 16: SQL NULL; 17: SQL NULL; 18: SQL NULL; 19: SQL NULL; 20: SQL NULL; 21: SQL NULL; 22: SQL NULL; 23: SQL NULL; 24: SQL NULL; 25: SQL NULL; 26: len 7; hex 53554343455353; asc SUCCESS;; 27: len 27; hex 5265636f72642055706461746564205375636365737366756c6c79; asc Record Updated Successfully;; 28: SQL NULL; 29: SQL NULL; 30: SQL NULL; 31: SQL NULL; 32: SQL NULL; 33: SQL NULL; 34: SQL NULL; 35: SQL NULL; 36: SQL NULL; 37: SQL NULL; 38: SQL NULL; 39: SQL NULL; 40: SQL NULL; 41: SQL NULL; *** (2) WAITING FOR THIS LOCK TO BE GRANTED: RECORD LOCKS space id 3803 page no 21 n bits 144 index PRIMARY of table `BAPIDB`.`APPLICATION` trx id 291891 lock_mode X locks rec but not gap waiting Record lock, heap no 72 PHYSICAL RECORD: n_fields 42; compact format; info bits 128 0: len 30; hex 65646466383861382d633733342d346561332d393665302d396366343234; asc eddf88a8-c734-4ea3-96e0-9cf424; (total 36 bytes); 1: len 6; hex 000000046e42; asc nB;; 2: len 7; hex 02000000fa0518; asc ;; 3: len 6; hex 303031353930; asc 001590;; 4: len 4; hex 31303033; asc 1003;; 5: len 4; hex 31303033; asc 1003;; 6: SQL NULL; 7: SQL NULL; 8: len 6; hex 506f7274616c; asc Portal;; 9: SQL NULL; 10: SQL NULL; 11: SQL NULL; 12: len 30; hex 35633131613436612d303963302d313165612d396533372d396165613961; asc 5c11a46a-09c0-11ea-9e37-9aea9a; (total 36 bytes); 13: SQL NULL; 14: len 5; hex 99a4ac4b92; asc K ;; 15: len 11; hex 427573696e657373415049; asc BusinessAPI;; 16: SQL NULL; 17: SQL NULL; 18: SQL NULL; 19: SQL NULL; 20: SQL NULL; 21: SQL NULL; 22: SQL NULL; 23: SQL NULL; 24: SQL NULL; 25: SQL NULL; 26: len 7; hex 53554343455353; asc SUCCESS;; 27: len 27; hex 5265636f72642055706461746564205375636365737366756c6c79; asc Record Updated Successfully;; 28: SQL NULL; 29: SQL NULL; 30: SQL NULL; 31: SQL NULL; 32: SQL NULL; 33: SQL NULL; 34: SQL NULL; 35: SQL NULL; 36: SQL NULL; 37: SQL NULL; 38: SQL NULL; 39: SQL NULL; 40: SQL NULL; 41: SQL NULL; *** WE ROLL BACK TRANSACTION (2) My Understanding: UPDATE APPLICATION SET NO_OF_FINANCIERS_FOR_ALL_ASSET = 7 WHERE id >'' AND APPLICATION_NUMBER = '001601'; This transaction is Causing the dead lock, This is waiting to get lock_mode X. UPDATE APPLICATION SET APPLICATION_NUMBER=IFNULL('001590', APPLICATION_NUMBER), STATUS=IFNULL('1003', STATUS), SUB_STATUS=IFNULL('1003', SUB_STATUS), CRM_STATUS=IFNULL('SUCCESS', CRM_STATUS), CRM_REASON=IFNULL('Record Created Successfully', CRM_REASON) WHERE ID='eddf88a8-c734-4ea3-96e0-9cf424ced71e'; holds the lock mode S and also trying to hold a lock_mode X which is waiting The second update is rolled back. My Questions are: Why the second update is holding and lock_mode S ? Shouldn't be lock_mode X is sufficient? These are updating two different rows, and I think that lock_mode S is the main culprit. Am I correct? How to avoid this dead lock. A: Update statements may set shared locks on secondary indexes or there are other statements within the 2nd transactions that set the shared lock before the update. As mysql manual says: The UPDATE operation also takes shared locks on affected secondary index records when performing duplicate check scans prior to inserting new secondary index records, and when inserting new secondary index records. However, in InnoDB all secondary indexes also include the primary key, so a secondary key lock does affect the primary key as well. But to be honest, if it had an exclusive lock only, that would not change the outcome. No, you are not correct. In the 1st link mysql manual also says: A locking read, an UPDATE, or a DELETE generally set record locks on every index record that is scanned in the processing of the SQL statement. It does not matter whether there are WHERE conditions in the statement that would exclude the row. InnoDB does not remember the exact WHERE condition, but only knows which index ranges were scanned. You wrote in a comment that you added the unique index on application_number column after posting your question. This means that your 1st sql statement locks the entire table because id >'' matches all records and application_number field was not indexed. So, regardless of the fact that your 1st sql statement updates a single record only, you managed to lock the entire table. Which brings us to your last question. You cannot and must not avoid deadlocks: these are an essential feature of resolving certain race conditions. There are two things you can do: a) handle the deadlock error (restart transaction, error message, etc). b) minimize the chances of a deadlock occuring. How can you minimize the chances of a deadlock occuring? Use appropriate indexes and where criteria to minimize the number of records locked by a statement; avoid using long running transactions; minimize the use of explicit locking (for update, for share). Your adding the unique index on application_number is a really good start, but you must verify using explain that it is used by mysql.
{ "pile_set_name": "StackExchange" }
Q: sbt: finding correct path to files/folders under resources directory I've a simple project structure: WordCount | |------------ project |----------------|---assembly.sbt | |------------ resources |------------------|------ Message.txt | |------------ src |--------------|---main |--------------------|---scala |--------------------------|---org |-------------------------------|---apache |----------------------------------------|---spark |----------------------------------------------|---Counter.scala | |------------ build.sbt here's how Counter.scala looks: package org.apache.spark object Counter { def main(args: Array[String]): Unit = { val sc = new SparkContext(new SparkConf()) val path: String = getClass.getClassLoader.getResource("Message.txt").getPath println(s"path = $path") // val lines = sc.textFile(path) // val wordsCount = lines // .flatMap(line => line.split("\\s", 2)) // .map(word => (word, 1)) // .reduceByKey(_ + _) // // wordsCount.foreach(println) } } notice that the commented lines are actually correct, but the path variable is not. After building the fat jar with sbt assembly and running it with spark-submit, to see the value of path, I get: path = file:/home/me/WordCount/target/scala-2.11/Counter-assembly-0.1.jar!/Message.txt you can see that path is assigned to the jar location and, mysteriously, followed by !/ and then the file name Message.txt!! on the other hand when I'm inside the WordCount folder, and I run the repl sbt console and then write scala> getClass.getClassLoader.getResource("Message.txt").getPath I get the correct path (without the file:/ prefix) res1: String = /home/me/WordCount/target/scala-2.11/classes/Message.txt Question: 1 - why is there two different outputs from the same command? (i.e. getClass.getClassLoader.getResource("...").getPath) 2 - how can I use the correct path, which appears in the console, inside my source file Counter.scala? for anyone who wants to try it, here's my build.sbt: name := "Counter" version := "0.1" scalaVersion := "2.11.8" resourceDirectory in Compile := baseDirectory.value / "resources" // allows us to include spark packages resolvers += "bintray-spark-packages" at "https://dl.bintray.com/spark-packages/maven/" resolvers += "Typesafe Simple Repository" at "http://repo.typesafe.com/typesafe/simple/maven-releases/" resolvers += "MavenRepository" at "https://mvnrepository.com/" libraryDependencies += "org.apache.spark" %% "spark-core" % "2.4.0" % "provided" and the spark-submit command is: spark-submit --master local --deploy-mode client --class org.apache.spark.Counter /home/me/WordCount/target/scala-2.11/Counter-assembly-0.1.jar A: 1 - why is there two different outputs from the same command? By command, I am assuming you mean getClass.getClassLoader.getResource("Message.txt").getPath. So I would rephrase the question as why does the same method call to classloader getResource(...) return two different result depending on sbt console vs spark-submit. The answer is because they use different classloader with each having different classpath. console uses your directories as classpath while spark-submit uses the fat JAR, which includes resources. When a resource is found in a JAR, the classloader returns a JAR URL, which looks like jar:file:/home/me/WordCount/target/scala-2.11/Counter-assembly-0.1.jar!/Message.txt. The whole point of using Apache Spark is to distribute some work across multiple computers, so I don't think you want to see your machine's local path in production.
{ "pile_set_name": "StackExchange" }
Q: getting data from nested span tags I'm trying to get weather data using this website http://openweathermap.org/find?q= and the info i need lies in the following code: <p> <span class="badge badge-info">6.2Β°Π‘ </span> " temperature from 5 to 7.8Β°Π‘, wind 1.17m/s. clouds 0%, 1031 hpa" </p> I am using the following mechanism to do that: import urllib url = 'http://openweathermap.org/find?q=' + str(b) htmlfile = urllib.urlopen(url) htmltext = htmlfile.read() regex = '<span class="badge badge-info">(.+?)</span>' pattern = re.compile(regex) temp = re.findall(pattern,htmltext) print temp But the result i get is this: ["'+temp +'\xc2\xb0\xd0\xa1 "] and it's the same for every keyword i search (the b seen above) What am i doing wrong? Also how can i get the rest of the info included in the paragraph tag? Thanks in advance A: In fact, you can't get this temperature data from the site in question, it's not being included as static html. Your original regex worked, but it was finding the text temp +'Β°Π‘ or thereabouts, which is in a javascript function. You could use Selenium, but it's much easier to get the data from the same place the Javascript function gets it from, the OpenWeatherMap API: import urllib import json place = "Santa Monica" apiurl = "http://api.openweathermap.org/data/2.5/weather?q={}&appid=2de143494c0b295cca9337e1e96b00e0".format(urllib.quote(place)) jsonfile = urllib.urlopen(apiurl) jsontext = jsonfile.read() result = json.loads(jsontext) temp_K = result['main']['temp'] temp = (temp_K - 273.15)*(9/5) + 32 print(temp) Note that temperature comes back in Kelvin. This gives you: 49.51 It's chilly in Santa Monica today :) [removed original answer based on BeautifulSoup, which would not work because the DOM element was generated by Javascript, so it doesn't exist in the static HTML] A: Why not use their JSON API instead of parsing the HTML? It would be much easier. You'll have all the data available to you, and you can reconstruct the paragraph using that data. import json import urllib url = 'http://api.openweathermap.org/data/2.5/weather?units=metric&q=' + str(b) request = urllib.urlopen(url) text = request.read() data = json.loads(text) print u"{}\xb0C from {} to {}\xb0C, wind {}m/s, clouds {}%, {} hpa".format( data['main']['temp'], data['main']['temp_min'], data['main']['temp_max'], data['wind']['speed'], data['clouds']['all'], data['main']['pressure']) You can read more about their API here: http://openweathermap.org/api EDIT: Added Β°C in the string :)
{ "pile_set_name": "StackExchange" }
Q: How to handle the if-else in promise then? In some case, when I get a return value from a promise object, I need to start two different then() precesses depend on the value's condition, like: promise().then(function(value){ if(//true) { // do something } else { // do something } }) I'm thinking maybe I can write it like: promise().then(function(value){ if(//true) { // call a new function which will return a new promise object ifTruePromise().then(); } else { ifFalsePromise().then(); } }) but with this, I have two questions: I'm not sure if it's a good idea to start a new promise-then process in a promise; what if I need the two process to call one function in the last? It means they have the same "terminal" I tried to return the new promise to keep the original chain like: promise().then(function(value){ if(//true) { // call a new function which will return a new promise object // and return it return ifTruePromise(); } else { // do something, no new promise // hope to stop the then chain } }).then(// I can handle the result of ifTruePromise here now); but in this case, whether it's true or false, the next then will work. SO, what's the best practice to handle it? A: As long as your functions return a promise, you can use the first method that you suggest. The fiddle below shows how you can take different chaining paths depending on what the first resolved value will be. function myPromiseFunction() { //Change the resolved value to take a different path return Promise.resolve(true); } function conditionalChaining(value) { if (value) { //do something return doSomething().then(doSomethingMore).then(doEvenSomethingMore); } else { //do something else return doSomeOtherThing().then(doSomethingMore).then(doEvenSomethingMore); } } function doSomething() { console.log("Inside doSomething function"); return Promise.resolve("This message comes from doSomeThing function"); } function doSomeOtherThing() { console.log("Inside doSomeOtherthing function"); return Promise.resolve("This message comes from doSomeOtherThing function"); } function doSomethingMore(message) { console.log(message); return Promise.resolve("Leaving doSomethingMore"); } function doEvenSomethingMore(message) { console.log("Inside doEvenSomethingMore function"); return Promise.resolve(); } myPromiseFunction().then(conditionalChaining).then(function () { console.log("All done!"); }). catch (function (e) { }); You can also just make one conditional chaining, assign the return promise to a variable and then keep executing the functions that should be run either way. function conditionalChaining(value){ if (value) { //do something return doSomething(); } else{ //do something else return doSomeOtherThing(); } } var promise = myPromiseFunction().then(conditionalChaining); promise.then(function(value){ //keep executing functions that should be called either way }); A: I have written a simple package for conditional promise usage. If you want to check it out: npm page: https://www.npmjs.com/package/promise-tree and github: https://github.com/shizongli94/promise-tree In response of comments asking for how the package solves the problem: 1, It has two objects. 2, Branch object in this package is a temporary storage place for the functions such as onFulfilled and onRejected that you want to use in then() or catch(). It has methods such as then() and catch() which take the same arguments as the counterparts in Promise. When you pass in a callback in Branch.then() or Branch.catch(), use the same syntax as Promise.then() and Promise.catch(). Then do nothing but storing the callbacks in an array. 3, Condition is a JSON object that stores the conditions and other information for checking and branching. 4, You specify conditions (boolean expression) using condition object in promise callbacks. Condition then stores the information you pass in. After all necessary information is provided by user, condition object uses a method to construct completely new Promise object that takes promise chain and callback information previously stored in Branch object. A little tricky part here is that you (as the implementer, not user) have to resolve/reject the Promise you first constructed manually before chaining the stored callbacks. This is because otherwise, the new promise chain won't start. 5, Thanks to event loop, Branch objects can be instantiated either before or after you have a stem Promise object and they won't interfere with each other. I use the terms "branch" and "stem" here because the structure resembles a tree. Example code can be found on both npm and github pages. By the way, this implementation also enables you have branches within a branch. And branches do not have to be at the same place you check conditions.
{ "pile_set_name": "StackExchange" }
Q: profile 2 module with services module i am creating a web service for user registration. I just add some fields in user registration form using profile2 module. How can i integrate this with services module. i just want to make a services with the new fields A: I'm assuming you're familiar with Services. In your endpoint, Copy the pattern here: array( 'name' => 'username', 'type' => 'string', 'description' => 'A valid username', 'source' => array('data' => 'username'), 'optional' => FALSE, ), array( 'name' => 'password', 'type' => 'string', 'description' => 'A valid password', 'source' => array('data' => 'password'), 'optional' => FALSE, ), For your arguments, and add your field machine names. Inside your callback, you can set $form_state['values'][...] with the passed values, and then use drupal_form_submit('user_register_form', $form_state); To register the user.
{ "pile_set_name": "StackExchange" }
Q: How to change speed of a wav file while retaining the sampling frequency in Python I wish to change the speed of an audio file (in the .wav format) by small amounts(Β±25%). The catch is that I need to retain the previous sample rate of the file. Both solutions involving a change of speed and pitch, and change of speed only (tempo change) are welcome, as ideally I would like to do both separately. A: You can use ffmpeg for that purpose: ffmpeg -i in.wav -filter:a "atempo=0.5" out.wav If you want to call it from Python, you can use ffmpy. import ffmpy ff = ffmpy.FFmpeg(inputs={"in.wav": None}, outputs={"out.wav": ["-filter:a", "atempo=0.5"]}) ff.run()
{ "pile_set_name": "StackExchange" }
Q: What key sizes are allowed within TLS if the DHE_RSA is the only key exchange allowed? Can I make assumptions about minimum and maximum key sizes if all I know about a TLS server is the fact that it uses DHE_RSA for key exchange? Can the server be configured to use weak key sizes for RSA and/or DH (e.g. 512-bit public key size) and still have a sucessful TLS connection? A: The cipher suites in SSL/TLS do not specify minimum or maximum sizes for the asymmetric keys involved in the key exchange or the certificates (the old "export" cipher suites specified maximum sizes, but these have been deprecated). Annex F.1.1.3 contains this text: Because TLS allows the server to provide arbitrary DH groups, the client should verify that the DH group is of suitable size as defined by local policy. which means that it is up to the implementations to enforce the size constraints that they wish to see enforced. In practice, RSA and DH keys which are way too small (smaller than 512 bits) will be rejected by many implementations (and when using RSA key exchange without DHE, there is an absolute minimum of 465 bits for the RSA modulus, otherwise the key exchange cannot take place at all). Many implementations will also reject keys beyond a rather large size (e.g. more than 4096 bits), because of internal constraints in the implementation. If you want to make sure that short keys will make the handshake fail, then you have to configure or implement it yourself on the system you control (client or server). Microsoft has pushed an update which deactivates support for RSA and DSA keys shorter than 1024 bits -- which implies that prior to this update, they were supported. However, the Diffie-Hellman group used with DHE is not from the certificates layer, but chosen by the SSL server code itself.
{ "pile_set_name": "StackExchange" }
Q: Vue async components are loading without delay regardless of the the 'delay' parameter I am using Advanced-Async-Components to load async component after loading of the app. So I have tried the following code: Index.vue <template> <div class=""> <Async></Async> </div> </template> <script> // async component import LoadComp from '@/components/Loading' import ErrorComp from '@/components/Error' const Async = () => ({ // The component to load. Should be a Promise component: import('@/components/Async'), // A component to use while the async component is loading loading: Load, // A component to use if the load fails error: ErrorComp, // Delay before showing the loading component. Default: 200ms. delay: 4000, // <--- this is not effecting the loading of component // The error component will be displayed if a timeout is // provided and exceeded. Default: Infinity. timeout: 3000 }) export default { components: { Async } } </script> Async.vue <template lang="html"> <div class=""> Lorem ipsum dolor sit amet, con .... very larger string/data </div> </template> <script> export default { } </script> <style lang="css"> </style> The above code works fine but it has no effect of delay parameter (Index.vue). According to official docs delay is Delay before showing the loading component. It should load the component after 4000ms but it loads instantly. Why is this happening? Is there any other way to achieve this apart from using setTimeout? Additional Info I used webpack template to build the project using vue-cli Vue version : ^2.4.2 A: This is happening because the delay option sets the amount of delay in milliseconds before showing the loading component, which is the component you have specified via the loading option to display while the async component is loading (the documentation is poorly-worded on this one). In the below example, two async components are loaded after one second. The first has no delay and the its loading component (LoadingComponent) will display immediately. The second has a delay of 500, meaning that after half a second, it will display its loading component. const LoadingComponent = { template: `<h1>Loading...</h1>` } const NumberBoxComponent = { template: `<h1>123123</h1>` } const AsyncComponent1 = () => ({ component: new Promise((resolve) => { setTimeout(() => { resolve(NumberBoxComponent) }, 1000) }), loading: LoadingComponent, }) const AsyncComponent2 = () => ({ component: new Promise((resolve) => { setTimeout(() => { resolve(NumberBoxComponent) }, 1000) }), loading: LoadingComponent, delay: 500 }) new Vue({ el: '#app', components: { 'async-component1': AsyncComponent1, 'async-component2': AsyncComponent2 } }) <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.4/vue.min.js"></script> <div id="app"> <async-component1></async-component1> <async-component2></async-component2> </div> If you want to delay the actual loading of the async component, you should use setTimeout.
{ "pile_set_name": "StackExchange" }
Q: Inequality for moments of sums Suppose the random variables $X_i$ are independent and satisfy $E[X_i] = 0$. Then the following inequality holds: $$E\left[\left(\sum \limits_{i = 1}^n X_i\right)^4\right] = \sum \limits_{i = 1}^n E[X_i^4] + 3\sum \limits_{i \ne j} E[X_i^2X_j^2] \le 3\left(\sum \limits_{i = 1}^n E[X_i^4] + \sum \limits_{i \ne j} \sqrt{E[X_i^4]}\sqrt{E[X_j^4]}\right) = 3\left(\sum \limits_{i = 1}^n \sqrt{E[X_i^4]}\right)^2$$ Now I would like to generalize this inequality to moments of order 6 [or higher]. My best guess is that the inequality $$E\left[\left(\sum \limits_{i = 1}^n X_i\right)^6\right] \le C \left(\sum \limits_{i = 1}^n E[X_i^6]^{1/3}\right)^3$$ holds, where $C$ is an absolute constant. Can someone provide a proof/ source for the last inequality? Or perhaps a source for a similar inequality? The "similar inequality" should provide at least $E\left[\left(\sum \limits_{i = 1}^n X_i\right)^6\right] = O(n^3)$ in the i.i.d. case. A: The inequality is actually correct. It follows from Theorems 3 in a Rosenthal paper from 1970 (Israel J. Math. 8, 273-303). Rosenthal proves the following inequality for $p > 2$ and independent, centered Random variables $X_i \in L^p$: $$E\left[\left|\sum \limits_{i = 1}^n X_i\right|^p\right] \le C(p) \max\left\{\sum \limits_{i = 1}^n E[ \left|X_i\right|^p], \left(\sum \limits_{i = 1}^n E[X_i^2]\right)^{p/2}\right\}.$$ The inequality in my original post follows from two applications of Jensen's inequality: $$\left(\sum \limits_{i = 1}^n E[\left|X_i\right|^p]\right)^{2/p} = n^{2/p} \left(\sum \limits_{i = 1}^n \frac{1}{n}E[\left|X_i\right|^p]\right)^{2/p} \le n^{2/p - 1} \sum \limits_{i = 1}^n E[\left|X_i\right|^p]^{2/p} \le \sum \limits_{i = 1}^n E[\left|X_i\right|^p]^{2/p}$$ $$E[X_i^2] \le E[\left|X_i\right|^p]^{2/p}$$
{ "pile_set_name": "StackExchange" }
Q: iOS/xcode/objective-c: How to instantiate view controller after signup After a successful sign up, I want users to go through a process where they provide photo etc. Similar code to that below worked to load the login page but code below is not working to load a separate view controller in storyboard "newuser". Would appreciate any suggestions on how to fix. - (void)presentNewUserInterface { UIViewController* rootController = [[UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]] instantiateViewControllerWithIdentifier:@"newuser"]; UINavigationController* navigation = [[UINavigationController alloc] initWithRootViewController:rootController]; self.window.rootViewController = navigation; } A: Instead of: - (void)presentNewUserInterface { UIViewController* rootController = [[UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]] instantiateViewControllerWithIdentifier:@"newuser"]; UINavigationController* navigation = [[UINavigationController alloc] initWithRootViewController:rootController]; self.window.rootViewController = navigation; } Try: - (void)presentNewUserInterface { UIViewController* rootController = [[UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]] instantiateViewControllerWithIdentifier:@"newuser"]; UINavigationController* navigation = [[UINavigationController alloc] initWithRootViewController:rootController]; [self presentViewController:navigation animated:YES completion:nil]; } You aren't presenting your new navigation controller in your example. Is there a particular reason why you would be trying to replace your rootViewController? That shouldn't be needed. My example should be sufficient for displaying your next flow in the user sign up process.
{ "pile_set_name": "StackExchange" }
Q: Force x86 CLR on an 'Any CPU' .NET assembly In .NET, the 'Platform Target: Any CPU' compiler option allows a .NET assembly to run as 64Β bit on a x64 machine, and 32Β bit on an x86 machine. It is also possible to force an assembly to run as x86 on an x64 machine using the 'Platform Target: x86' compiler option. Is it possible to run an assembly with the 'Any CPU' flag, but determine whether it should be run in the x86 or x64 CLR? Normally this decision is made by the CLR/OS Loader (as is my understanding) based on the bitness of the underlying system. I am trying to write a C# .NET application that can interact with (read: inject code into) other running processes. x64 processes can only inject into other x64 processes, and the same with x86. Ideally, I would like to take advantage of JIT compilation and the Any CPU option to allow a single application to be used to inject into either x64 or x86 processes (on an x64 machine). The idea is that the application would be compiled as Any CPU. On an x64 machine, it would run as x64. If the target process is x86, it should relaunch itself, forcing the CLR to run it as x86. Is this possible? A: You can find out how an application will run and change it statically using the CorFlags application. To find out how the application will run, use: corflags <PathToExe> To change how the application will run, use: corflags /32bit+ <PathToExe> This will make the EXE file run as a 32-bit process. The information about how the assembly should run is stored in the PE header. See Stack Overflow question How to find if a native DLL file is compiled as x64 or x86?. If you want to inject code at run time, you have to write a .NET profiler in C++/COM. See .NET Internals: The Profiling API and Profiling (Unmanaged API Reference) for more details. You'll need to implement the JitCompilationStarted callback and do your work there. If you go in this direction, you'll have to build the injecting DLL file both as x86 and x64. The native DLL files will be loaded by the CLR once the following environment variables will be set: Cor_Enable_Profiling=0x1 COR_PROFILER={CLSID-of-your-native-DLL-file} If you have it set correctly then the 64-bit version will 'see' the 64 bit processes and the 32-bit version will 'see' the 32-bit processes. A: It has been a while since I tried this, but I believe that the bitness of the process that calls the assembly determines whether it will be JITed as x86 or x64. So if you write a small console application and build it as x86, and another as x64, running one or the other will cause other assemblies loaded into the process to run as 32 or 64 bit. This, of course, assumes you are running on a 64 bit machine. A: I'm not sure whether I can help you with this. But this is my experience. I have a host application,A.exe ( compiled as x86), and I have a client application, B.exe ( compiled as ANY CPU), from the host application. And I launch B.exe from A.exe, using the System.Diagnostic.Process class. The issue now is if I put the two on a x64 machine, then A.exe will run as x86, whereas the B.exe will run as x64. But if A.exe calls assembly c ( c.dll, which is compiled as Any CPU), and B.exe also calls c.dll, then c.dll will follow the application that calls it. In other words, in 64 bit machine when A.exe calls it, it will behave like x86 dll, whereas when B.exe calls it, it will behave like x64.
{ "pile_set_name": "StackExchange" }
Q: Efficiency of checking for null varbinary(max) column? Using SQL Server 2008. Example table : CREATE table dbo.blobtest (id int primary key not null, name nvarchar(200) not null, data varbinary(max) null) Example query : select id, name, cast((case when data is null then 0 else 1 end) as bit) as DataExists from dbo.blobtest Now, the query needs to return a "DataExists" column, that returns 0 if the blob is null, else 1. This all works fine, but I'm wondering how efficient it is. i.e. does SQL server need to read in the whole blob to its memory, or is there some optimization so that it just does enough reads to figure out if the blob is null or not ? (FWIW, the sp_tableoption "large value types out of row" option is set to OFF for this example). A: It uses the NULL bitmap. So no.
{ "pile_set_name": "StackExchange" }
Q: How to merge two arrays in JS? I have two arrays like below. A = [{fruit: apple, number:4 }, {fruit: pear, number: 3}] B = [{qual: good}, {qual: bad}] And My goal is getting an array like below. C = [{fruit: apple, number:4, qual: good }, {fruit: pear, number: 3, qual: bad}] The length of A, B is same. I can make this using 'for loop'. But how can I make it using 'some array methods' like 'concat' or 'map'? A: You can use map and spread syntax let A = [{fruit: 'apple', number:4 }, {fruit: 'pear', number: 3}] let B = [{qual: 'good'}, {qual: 'bad'}] let C = A.map((value, index) => ({ ...value, ...B[index] })) console.log(C) Index is used to access respective value from second array, and merged into a single object using spread syntax
{ "pile_set_name": "StackExchange" }
Q: Getting ID1s that doesn't have occurrences on group of ID2s Suppose I have two columns, ID1 and ID2. I want the query to return ID values where it doesn't have any occurrences of group of ID2s. ID1 ID2 1 3 1 4 1 5 2 1 2 3 3 1 3 6 4 4 4 7 5 1 5 8 Suppose I want ID1 to return IDs which doesn't have (3,4,5) values, the result should be 3,5 here. What should be the query in postgresql? Thanks A: You can use the following query: SELECT ID1 FROM mytable GROUP BY ID1 HAVING COUNT(CASE WHEN ID2 IN(3,4,5) THEN 1 END) = 0 Demo here This will return ID1 values that are not related to even one ID2 value contained in (3,4,5).
{ "pile_set_name": "StackExchange" }
Q: VNC in reverse Direction I am developing a Remote Desktop application Like Tight VNC But the Problem is the end that broadcasts the Screenshots doesn't have a Public IP However the recieving end have.I was planing to use TightVNC Source Code. So is it feasible to use TightVNC Source for this purpouse as I dont see any such option in Tight VNC where the Sending end doesn't have Public IP. A: VNC allows for the Viewer / Client to start in "Listen-Mode" and wait for a server to connect. This is the reverse connection you speak of. Some tools provide a VNC Server contained in a Windows Exe that connects to a definded Viewer on startup, it allows Remote Support behind a home router. See the docs for more Infos (look for "Add new client" on Server Tray Icon) Clarification: When I want to use Tight VNC to Remote your PC (See your Desktop), I would normally do: Connect my Client to your Server on your Public IP Reverse VNC: You Add my Public IP to your Server wich connects to my Client
{ "pile_set_name": "StackExchange" }
Q: How to get unchanged device id from ios7 device programmatically I need to get the unique device id to populate unique user id in the database. I have used the following code to get that. NSString *strApplicationUUID= [[[UIDevice currentDevice] identifierForVendor] UUIDString]; But when I am reinstalling the app, the UUID is changing all the time. But as far as I know the device id never changes. For that I used below code with the third party SSKeychain to save and retrieve the old UDID: NSString *Appname = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleName"]; NSString *strApplicationUUID = [SSKeychain passwordForService:Appname account:@"manab"]; if (strApplicationUUID == nil) { strApplicationUUID = [[[UIDevice currentDevice] identifierForVendor] UUIDString]; [SSKeychain setPassword:strApplicationUUID forService:Appname account:@"manab"]; } Now the problem is when the version of that Application is changed i.e app v2.0 form app v1.0 then again the UDID changed. So the logic is clear to me that I am not getting the unique UDID all the time, I am just getting UDID as vendor or App basis. How to get that by programatically? Is there any other way to get that, please show me the right Direction. A: I have solved this by using advertisingIdentifier. As I have seen there that advertisingIdentifier is "An alphanumeric string unique to each device, ..." For that I have used it as the unique identifier (though it is used for the serving advertisements). My code is: -(NSString*)UniqueAppId { NSString *Appname = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleName"]; NSString *strApplicationUUID = [SSKeychain passwordForService:Appname account:@"manab"]; if (strApplicationUUID == nil) { strApplicationUUID = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString]; [SSKeychain setPassword:strApplicationUUID forService:Appname account:@"manab"]; } return strApplicationUUID; } and just calling it when needed as [self UniqueAppId];
{ "pile_set_name": "StackExchange" }
Q: Question about definition for tag "dynamic-linking" Question: is the definition correct? If not, what should the correct definition be? Here is the definition: Dynamic linking is the process of resolving at runtime a program's external function calls or dependencies. It is usually performed at compile time by the linker. This definition seems to be wildly incorrect - the second sentence, itself incorrect, contradicts the first. The impression I am under regarding how things work in terms of binary creation and process creation can be summarized by the following (GCC + x86 Linux environment): preprocessing -> compilation (compile time) -> assembly -> linking (link time) then execve (user space) -> exec (kernel) -> dynamic linker -> process (user space) Since I don't know anything about dynamic linking in the context of other systems such as MS Windows and since the definition needs to be sufficiently generic, I am not in a position where I can suggest a new, correct and broadly applicable definition. For reference, this question was prompted by some documentation I read over in order to answer Could not find ld-linux-x86-64.so.2 in strace output A: Yep, seems wrong, we'll need to fix it. From Linkers and Loaders Ch.10: Dynamic linking defers much of the linking process until a program starts running. It provides a variety of benefits that are hard to get otherwise: Dynamically linked shared libraries are easier to create than static linked shared libraries. Dynamically linked shared libraries are easier to update than static linked shared libraries. The semantics of dynamically linked shared libraries can be much closer to those of unshared libraries. Dynamic linking permits a program to load and unload routines at runtime, a facility that can otherwise be very difficult to provide. This is probably too long for a tag definition so we'll need to trim it somewhat. It also refers to linking itself which is defined elsewhere.
{ "pile_set_name": "StackExchange" }
Q: Cannot write file '..../public/scripts/script.js' because it would overwrite input file I have a project created in Visual Studio 2017 using the TypeScript Basic Node.js Express 4 Application template. I have a file /public/scripts/script.js meant for download to the client. When I tried to build the application I get: TS5055 Cannot write file 'd:/documents/visual studio 2017/Projects/ExpressApp/ExpressApp/public/scripts/script.js' because it would overwrite input file. What does this error mean? Why would it want to write to this file? The error is there even if I exclude this file from the Project. How do I rectify this? I renamed the folder from scripts to js and the problem is still the same. The only way to build successfully was to delete the file. Where then do I place files meant for the client? Is there documentation available on the Visual Studio project folder structure for a TypeScript/Node project? A: From the tip by @unional I found my answer, ie, have an explicit exclude option in tsconfig.json. According to typescriptlang.org: the compiler defaults to including all TypeScript (.ts, .d.ts and .tsx) files in the containing directory and subdirectories except those excluded using the "exclude" property. JS files (.js and .jsx) are also included if allowJs is set to true If exclude is not specified, then only node_modules and a couple of others are excluded. The following worked for me: "exclude": [ "node_modules", "public"] Note that exclude is not a property of compilerOptions but is at the same level as compilerOptions in tsconfig.json. A: Another option that works in VSCode is to use '"outFile":"out.js"' under '"CompilerOptions"' section to have a separate output file. This way you can still check those files, but not get the writing error.
{ "pile_set_name": "StackExchange" }
Q: Refactor Gatsby Image Query I am currently using Gatsby and gatsby-image within my IndexPage component. I am looking to refactor the code below into a single React component, as there is unnecessary duplication: ... return ( <div> <h1>Startups</h1> <p>Copy</p> <Img fluid={props.data.imageOne.childImageSharp.fluid}/> </div> <div> <h1>People</h1> <p>Copy</p> <Img fluid={props.data.imageTwo.childImageSharp.fluid}/> </div> <div> <h1>Data</h1> <p>Copy</p> <Img fluid={props.data.imageThree.childImageSharp.fluid}/> </div> </div> ) export const fluidImage = graphql` fragment fluidImage on File { childImageSharp { fluid(maxWidth: 1000) { ...GatsbyImageSharpFluid } } } ` export const pageQuery = graphql` query { imageOne: file(relativePath: { eq: "igemA.png" }) { ...fluidImage } imageTwo: file(relativePath: { eq: "inephemeraA.png" }) { ...fluidImage } imageThree: file(relativePath: { eq: "polypA.png" }) { ...fluidImage } } That resembles something like this: const NewComponent = (props) => ( <div> <h1>props.heading</h1> <p>props.body</p> <Img fluid={props.data.[props.image].childImageSharp.fluid}/> </div> ) How can I change the graphql query so that I can render an image depending on the props passed to the NewComponent? A: Unless I have misunderstood, I don't think you need to change your query to accomplish that. Just pass the result of each query to your child component as a prop. // components/newComponent.js import React from "react" import Img from "gatsby-image" const NewComponent = ({ image, heading, body }) => ( <> <h1>{ heading }</h1> <p>{ body }</p> <Img fluid={ image.childImageSharp.fluid } /> </> ) export default NewComponent // index.js import React from "react" import {graphql} from "gatsby" import NewComponent from "../components/newComponent" const IndexPage = ({ data }) => { const { imageOne, imageTwo } = data return ( <> <NewComponent image={ imageOne } heading="heading 1" body="body 1" /> <NewComponent image={ imageTwo } heading="heading 1" body="body 2" /> </> )} export default IndexPage export const fluidImage = graphql` fragment fluidImage on File { childImageSharp { fluid(maxWidth: 1000) { ...GatsbyImageSharpFluid } } } ` export const pageQuery = graphql` query { imageOne: file(relativePath: { eq: "gatsby-astronaut.png" }) { ...fluidImage } imageTwo: file(relativePath: { eq: "gatsby-icon.png" }) { ...fluidImage } } ` Here is a CodeSandbox to test the above.
{ "pile_set_name": "StackExchange" }
Q: Why do my photos looked washed out when using my telephoto lens? I own an aging Nikon D40 and recently picked up a new telephoto lens: the Nikkor 55mm-300mm f/4.5-5.6. I've noticed that when I zoom in on subjects, the color in my photos often looks washed out. Here is an example: 55mm: 1/800 sec, ISO 200, f/4.5 (aperture priority) 300mm zoomed in on the brick building to the back/right: 1/640 sec, ISO 200, f/5.6 (aperture priority), and yes, that is the old Natty Boh factory in Baltimore, MD if you were interested ;) EDIT (a crop of the 55mm version was requested): The 300mm one seems like it is too bright, and the colors are not as vibrant. Is this a fault of the lens, or the body? Or do I just need to fiddle with the settings some more? Any suggestions? (more exif data from the above pictures can be supplied if requested) A: Try taking some pictures from a little closer, and see if the problem doesn't go away. It's quite normal for almost all pictures taken at a substantial distance to look somewhat washed out. The dust/haze/smog/pollution/heat waves/etc., in the air reflect and refract light enough to reduce the contrast and wash out colors. This tends to be at a minimum after a large rain fall, which tends to "wash" a lot of the dust and such out of the air. Nonetheless, you're only minimizing the tendency, not removing it completely. As for comparing to the shorter lens, it's pretty simple: with the short lens, most of what you're seeing clearly is a lot closer. As things "fade" into the distance, they also get smaller in a hurry, so the lack of detail and washed out colors aren't nearly as apparent. At the same time, if you look in the first picture, and compare the factory in the distance to the buildings at the bottom of the frame, it's still quite apparent that the closer buildings show much richer color. Edit: doing a quick look at the "levels" in the picture reveals a great deal of the problem almost immediately: This is somewhat overexposed -- the whites look a bit clipped (the spike at the far right) and there's nothing even close to a true black. Simply picking a reasonable black level makes the picture look much more "zippy" (though I may have gone a bit overboard in this case): Doing this on a JPEG inevitably loses some quality, but if you have a raw image, you probably have enough extra data to do this adjustment with less (or no) quality loss. Some of the original lack of contrast is almost certainly due to atmospheric effects -- but as you can see, a minor adjustment gets a lot closer to what you probably want. Nonetheless, I'd say the original exposure looks a bit off -- it's open to question whether you're seeing a symptom of a real problem, or just an isolated incident. A: Some lenses have more inherent contrast than others. It usually won't vary due to the zoom factor of a lens, because it's more dependent on the glass and number of elements in the lens. A UV filter or other protective filter can reduce the contrast of a lens. If you're using one, try taking it off. A polarizing filter is the only one that might be of benefit, but you should still experiment with it both ways. Atmospheric haze will degrade the contrast of an image. Waiting for the right atmospheric conditions or lighting will definitely help. Post processing can overcome much of the problem. Here's an example of what a couple of minutes can do; I did this with Paint Shop Pro, but you should be able to get similar results with your favorite image editor. A: The haze or smog in the atmosphere can't really be avoided and for that particular scene, you can see the haze around the area that you then zoomed in on. That being said, it appears you haven't looked at processing the image. Do you shoot raw? If so, you should boost the contrast, possibly the saturation, adjust the white balance and more and you should have a lot of room to work that seemingly dull photo into something more vivid and clear. As well, you might want to use lens correction to counteract the moderate vignetting in the zoomed in frame.
{ "pile_set_name": "StackExchange" }
Q: React.JS TypeError: Cannot read property 'value' of undefined Having an issue with a react form and I can't figure it out. I am getting TypeError: Cannot read property 'value' of undefined when submitting. The issue started when I added "location" to the form. Not sure how this is causing it to break as I am just adding another item to the form. I have attempted to fix any typos, and when I take out the "location" it submits with no issue. import React from "react"; import Firebase from "firebase"; import config from "./config"; class App extends React.Component { constructor(props) { super(props); Firebase.initializeApp(config); this.state = { pallets: [] }; } componentDidMount() { this.getUserData(); } componentDidUpdate(prevProps, prevState) { if (prevState !== this.state) { this.writeUserData(); } } writeUserData = () => { Firebase.database() .ref("/") .set(this.state); console.log("DATA SAVED"); }; getUserData = () => { let ref = Firebase.database().ref("/"); ref.on("value", snapshot => { const state = snapshot.val(); this.setState(state); }); }; handleSubmit = event => { event.preventDefault(); let name = this.refs.name.value; let QTY = this.refs.QTY.value; let uid = this.refs.uid.value; let location = this.refs.location.value; if (uid && name && QTY && location) { const { pallets } = this.state; const devIndex = pallets.findIndex(data => { return data.uid === uid; }); pallets[devIndex].name = name; pallets[devIndex].QTY = QTY; pallets[devIndex].location = location; this.setState({ pallets }); } else if (name && QTY && location) { const uid = new Date().getTime().toString(); const { pallets } = this.state; pallets.push({ uid, name, QTY, location }); this.setState({ pallets }); } this.refs.name.value = ""; this.refs.QTY.value = ""; this.refs.uid.value = ""; this.refs.location.value = ""; }; removeData = pallet => { const { pallets } = this.state; const newState = pallets.filter(data => { return data.uid !== pallet.uid; }); this.setState({ pallets: newState }); }; updateData = pallet => { this.refs.uid.value = pallet.uid; this.refs.name.value = pallet.name; this.refs.QTY.value = pallet.QTY; this.refs.location.value =pallet.location; }; render() { const { pallets } = this.state; return ( <React.Fragment> <div className="container"> <div className="row"> <div className="col-xl-12"> <h1>Creating Pallet App</h1> </div> </div> <div className="row"> <div className="col-xl-12"> {pallets.map(pallet => ( <div key={pallet.uid} className="card float-left" style={{ width: "18rem", marginRight: "1rem" }} > <div className="card-body"> <h5 className="card-title">{pallet.name}</h5> <p className="card-text">{pallet.QTY}</p> <p className="card-text">{pallet.location}</p> <button onClick={() => this.removeData(pallet)} className="btn btn-link" > Delete </button> <button onClick={() => this.updateData(pallet)} className="btn btn-link" > Edit </button> </div> </div> ))} </div> </div> <div className="row"> <div className="col-xl-12"> <h1>Add new pallet here</h1> <form onSubmit={this.handleSubmit}> <div className="form-row"> <input type="hidden" ref="uid" /> <div className="form-group col-md-6"> <label>Name</label> <input type="text" ref="name" className="form-control" placeholder="Name" /> </div> <div className="form-group col-md-6"> <label>QTY</label> <input type="text" ref="QTY" className="form-control" placeholder="QTY" /> </div> <div className="form-group col-md-6"> <label>Location</label> <input type="text" ref="QTY" className="form-control" placeholder="Location" /> </div> </div> <button type="submit" className="btn btn-primary"> Save </button> </form> </div> </div> </div> </React.Fragment> ); } } export default App; A: You haven't created a ref named location Change: <input type="text" ref="QTY" className="form-control" placeholder="Location" /> to: <input type="text" ref="location" className="form-control" placeholder="Location" />
{ "pile_set_name": "StackExchange" }
Q: Genomic Range Query in Python Recently, I worked on one of the Codility Training - Genomic Range Query (please refer to one of the evaluation report for the detail of the task. The solution in Python is based on prefix sum, and was adjust in accordance to this article. import copy def solution(S, P, Q): length_s = len(S) length_q = len(Q) char2digit_dict = {'A':1, 'C':2, 'G':3, 'T':4} str2num = [0]*length_s count_appearances = [[0, 0, 0, 0]]*(length_s+1) cur_count = [0, 0, 0, 0] for i in range(0, length_s): str2num[i] = char2digit_dict[S[i]] cur_count[str2num[i]-1] += 1 count_appearances[i+1] = copy.deepcopy(cur_count) results = [] for i in range(0, length_q): if Q[i] == P[i]: results.append(str2num[Q[i]]) elif count_appearances[Q[i]+1][0] > count_appearances[P[i]][0]: results.append(1) elif count_appearances[Q[i]+1][1] > count_appearances[P[i]][1]: results.append(2) elif count_appearances[Q[i]+1][2] > count_appearances[P[i]][2]: results.append(3) elif count_appearances[Q[i]+1][3] > count_appearances[P[i]][3]: results.append(4) return results However, the evaluation report said that it exceeds the time limit for large-scale testing case (the report link is above). The detected time complexity is \$O(M * N)\$ instead of \$O(M + N)\$. But in my view, it should be \$O(M + N)\$ since I ran a loop for \$N\$ and \$M\$ independently (\$N\$ for calculating the prefix sum and \$M\$ for getting the answer). Could anyone help me to figure out what the problem is for my solution? I get stuck for a long time. Any performance improvement trick or advice will be appreciated. A: I'm not sure that I trust Codility's detected time complexity. As far as I know, it's not possible to programmatically calculate time complexity, but it is possible to plot out a performance curve over various sized datasets and make an estimation. That being said, there are a number of unnecessary overhead in your code and so it is possible that Codility is interpreting that overhead as a larger time complexity. As for your code, Python is all about brevity and readability and generally speaking, premature optimization is the devil. Some of your variable names are not in proper snake case (str2num, char2digit_dict). List memory allocation increases by a power of 2 each time it surpasses capacity, so you really don't have to pre-allocate the memory for it, it's marginal. You convert your string into a list of digits, but then only ever use it in a way that could be fulfilled with your original dict. The list of digits is not really needed since you are already computing a list of prefix sums. In the C solution it was important to calculate the len of the P/Q list first so that it's not recalculated every time, but in Python, range (xrange in Python2) is evaluated for i exactly once. It's not necessary to deepcopy cur_count as it only contains integers, which are immutable. You can copy the list by just slicing itself, list[:] Instead of constantly making references to count_appearances (up to 4x each iteration), you could just make the reference once and store it. This will also make it easier to update your references if the structure of P and Q were to change in any way. Cleaning up your code in the ways I mentioned gives me: def solution(S, P, Q): cost_dict = {'A':1, 'C':2, 'G':3, 'T':4} curr_counts = [0,0,0,0] counts = [curr_counts[:]] for s in S: curr_counts[cost_dict[s]-1] += 1 counts.append(curr_counts[:]) results = [] for i in range(len(Q)): counts_q = counts[Q[i] + 1] counts_p = counts[P[i]] if Q[i] == P[i]: results.append(cost_dict[S[Q[i]]]) elif counts_q[0] > counts_p[0]: results.append(1) elif counts_q[1] > counts_p[1]: results.append(2) elif counts_q[2] > counts_p[2]: results.append(3) elif counts_q[3] > counts_p[3]: results.append(4) return results which gets a perfect score on Codility.
{ "pile_set_name": "StackExchange" }
Q: JSP and Servlet NullPointer - display class attribute in text field I am creating a project with JSP & Servlet (and entity beans) and I am trying to create a form where a user registers as a customer and is then redirected to a reservation page. I want to keep the Id for the Customer that just registered and fill it into a disabled text field and then create a reservation on the next page. But whenever I try to load the customer class through jsp the whole application crashes with a NullPointerException. It seems like the program crashes when it reaches the jsp-tags to fetch my customer, since it does print out the c.cPnr to the console as well as the test in the JSP-file. <%@ page import = "g24.isp.ejb.Customer" %> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Welcome to Ski Village!</title> <link rel="stylesheet" href="new/css/normalize.css"> <link rel="stylesheet" href="new/css/stylesheet.css"> <link href='https://fonts.googleapis.com/css?family=Fjalla+One|Poppins:400,500,600' rel='stylesheet' type='text/css'> <script src="javascript/script.js" type="text/javascript"></script> </head> <body> <% System.out.println("test"); %> <% Customer c = (Customer) session.getAttribute("customer"); %> <div id="container"> <!-- HEADER + MENU --> <header> <div class="logo"><!-- Ski Village Logo --></div> <div class="menu"> <ul> <li> <a href="index.html"> Home </a></li> <li class="left-menu"> <a href="about.html"> About </a></li> <li class="right-menu"> <a href="booking.html" id="selected"> Book </a></li> <li> <a href="index.html" > Test</a></li> </ul> </div> </header> <!-- PAGE CONTENT --> <div id="wrapper"> <div class="center-form"> <form action="/HotelClient/HotelServlet" name="resForm" method="post"> <input type="text" name="cPnr" value="<%= c.getcPnr() %>" > <input type="number" name="week" min="1" max="52" placeholder="Select week" > <select name="cno"> <option value="1">Adventure Cabin </option> <option value="2">Cozy Cabin </option> <option value="3">Snowy Cabin </option> <option value="4">Hacker Cabin </option> </select> <input type="submit" name="checkres" value="Check availability"> <input type="submit" name="submitresform" value="Create reservation" type="hidden"> <input name="operation" value="bajskorv" type="hidden"> </form> </div> <!-- FOOTER + SOCIAL ICONS --> <footer> <a href="http://facebook.com/"><img src="img/facebook-logo.png" class="social-icon" alt="facebook logo"></a> <a href="http://instagram.com/"><img src="img/instagram-logo.png" class="social-icon" alt="instagram logo"></a> <a href="http://twitter.com/"><img src="img/twitter-logo.png" class="social-icon" alt="twitter logo"></a> <p>&copy; 2016 | Ski Village</p> </footer> </div> </div> </body> </html> Servlet code: package g24.isp.servlets; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import javax.ejb.EJB; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import g24.isp.ejb.Cabin; import g24.isp.ejb.Customer; import g24.isp.ejb.Hotel; import g24.isp.ejb.Reservation; import g24.isp.facade.Facade; import g24.isp.facade.FacadeLocal; import g24.isp.ejb.MethodClass; /** * Servlet implementation class HotelServlet */ @WebServlet("/HotelServlet") public class HotelServlet extends HttpServlet { private static final long serialVersionUID = 1L; @EJB private FacadeLocal facade; /** * @see HttpServlet#HttpServlet() */ public HotelServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse * response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub PrintWriter out = response.getWriter(); out.println("MainServlet-doGet"); out.close(); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub String url = "did not get an url"; // Get hidden field String operation = request.getParameter("operation"); MethodClass mc = new MethodClass(); if (operation.equals("createcustomer")) { String cPnr = request.getParameter("txtcPnr"); String cAddress = request.getParameter("txtcAddress"); String cPhone = request.getParameter("txtcPhone"); String cName = request.getParameter("txtcName"); if (facade.findByCpnr(cPnr) == null) { Customer customer = new Customer(); customer.setcPnr(cPnr); customer.setcAddress(cAddress); customer.setcPhone(cPhone); customer.setcName(cName); facade.createCustomer(customer); url = "/new/reservation.jsp"; } else { url = "new/newcust.jsp"; } } else if (operation.equals("createreservation")) { String cpnr = request.getParameter("txtcPnr"); int week = mc.ParseStringToInt(request.getParameter("week")); int cno = mc.ParseStringToInt(request.getParameter("cno")); Customer cs = facade.findByCpnr(cpnr); Cabin cb = facade.findByCabinNo(cno); if (cb != null && cs != null) { Reservation res = new Reservation(); res.setCabin(cb); res.setCustomer(cs); res.setrDate(week); facade.createReservation(res); url = "/Index.jsp"; } else { System.out.println("Did not enter if statement"); url = "/Index.jsp"; } } else if (operation.equals("newcustomer")) { url = "/new/newcust.jsp"; } else if (operation.equals("setcustomer")) { System.out.println("Servlet - Create reservation"); String cpnr = request.getParameter("txtcPnr"); System.out.println(cpnr); url = "/new/reservation.jsp"; Customer customer = facade.findByCpnr(cpnr); if (customer != null) { System.out.println(customer.getcName()); session.setAttribute("customer", customer); url = "/reservation.jsp"; } else { System.out.println("Customer value is null"); } } System.out.println(url); RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url); dispatcher.forward(request, response); } } A: I solved the problem - i was trying to find the customer by accessing the facade.findBycPnr() method. The solution was to session.setAttribute(customer, cust) when creating the customer.
{ "pile_set_name": "StackExchange" }
Q: Do I need glib (OSX)? One of the options when installing emacs in OSX (through homebrew) is support for glib. It's not included by default. What does it buy me to install? Any downsides? Thanks! A: No, I don't think you need glib. According to brew cat emacs, the --glib option actually means --with-file-notification=gfile, and run ./configure --help inside Emacs source root directory tells: --with-file-notification=LIB use a file notification library (LIB one of: yes, inotify, kqueue, gfile, w32, no) In my experience, kqueue is used on OSX by default (as long as you don't set the option by yourself).
{ "pile_set_name": "StackExchange" }
Q: Why can I replace one word in a text file but not another? I'm reading through the following text file word for word a replacing the words "@name@" and "@festival@". My program works perfectly for @name@ but only changes the first @festival@, but not the second. I have no idea why. John Doe Room 213-A Generic Old Building School of Information Technology Programming State University New York NY 12345-0987 USA To: @name@ Subject: Season's greetings: @festival@ Dear @name@, A very @festival@ to you and your family! Your sincerely, John void Main::readFile() { while (v.size() != 0) { string name; name = v.at(v.size()-1); v.pop_back(); std::ofstream out(name + ".txt"); ifstream file; file.open("letter.txt"); string word; string comma; char x; word.clear(); while (!file.eof()) { x = file.get(); while (x != ' ' && x != std::ifstream::traits_type::eof()) { if (word == "@name@") { word = name; } if (word == "@festival@") { word = "THISISATEST!!!!!!!!!!!!!!"; } word = word + x; x = file.get(); } out << word + " "; word.clear(); } } A: First of all, see Why is iostream::eof inside a loop condition considered wrong? This isn't an elegant solution... but a better improvement to your original code. (I'll leave you to think of a more efficient solution): void Main::readFile() { while (v.size() != 0) { string name; name = v.at(v.size()-1); v.pop_back(); std::ofstream out(name + ".txt"); ifstream file; file.open("letter.txt"); string festival = "THISISATEST!!!"; string line, nameHolder = "@name@", festivalHolder = "@festival@"; while (std::getline(file, line)) { std::size_t n_i = line.find(nameHolder); if(n_i != std::string::npos) line.replace(n_i, nameHolder.size(), name); std::size_t f_i = line.find(festivalHolder); if(f_i != std::string::npos) line.replace(f_i, festivalHolder.size(), festival); out << line << '\n'; } }
{ "pile_set_name": "StackExchange" }
Q: Syntax error in bytes(" ".format(), encoding="utf-8") When running this: import hashlib hash1 = hashlib.md5(b'admin:Pentester Academy:asdds').hexdigest() hash2 = hashlib.md5(b'GET:/lab/webapp/digest/1').hexdigest() nonce = "526f295f84bcafc67598cd8e760a9cc5" response_unhashed = (bytes("{}:{}:{}".format(hash1, nonce, hash2)), encoding='utf-8') response_md5hashed = hashlib.md5(response_unhashed).hexdigest() print(response_md5hashed) I get this... Traceback (most recent call last): File "C:\Users\Adrian\Desktop\Infosec\Notes\Programming\example.py", line 7 response_unhashed = (bytes("{}:{}:{}".format(hash1, nonce, hash2)), encoding='utf-8') ^ SyntaxError: invalid syntax Where's the syntax error? Checked some of the bytes() and format() documentation but couldn't find any clues. A: There are parentheses that are in wrong order. Try bytes("{}:{}:{}".format(hash1,nonce,hash2), encoding = "utf-8") Instead of (bytes("{}:{}:{}".format(hash1, nonce, hash2)), encoding='utf-8')
{ "pile_set_name": "StackExchange" }
Q: Cherry picking git commit SHAs back into a parent branch My git repo has a master and a development branch on the origin server (GitHub). I cut a feature branch from development and made way too many commits to it, and am left with a handful of commits that I want merged/added back to development, and a whole bunch of ones that I don't want added back in. Is this possible to do? That is, if you have, say 50 commits on a feature branch, and only want to add, say, 8 of them back to a parent branch, can you cherry pick those 8 (if you know their commit SHAs) and add them in? If not, why? And if so, what's the magical git command to do so? A: There are multiple ways to do what you're asking. I can say this even though the question is ambiguous; it just happens that there are a different many ways, depending on which result you're looking for. One of those ways - the one you're baiting with the way you phrased your question - is the cherry-pick command. But I don't recommend it because there are easier ways. For example, in your case you can use git rebase. You can look at cherry-pick as a special case of rebase, or you can look at rebase as a way to (among other things) automate a series of cherry-picks. In any case, as a smaller/more easily shown example, say you start with x -- o -- x -- x <--(master) \ A -- B -- C -- D -- E -- F -- G -- H -- I -- J <--(branch) and you want to keep just three commits, which correspond in some way to B, G, and J. Now I say "correspond in some way" because there are two ways to look at "only keeping certain commits". Suppose at o you have some files, including a directory foo containing the file o. And suppose that each commit A through J adds a file to foo; A adds foo/A, B adds foo/B, etc. Therefore at commit G, for example, you have a TREE that includes foo/o, foo/A, foo/B, foo/C, foo/D, foo/E, foo/F, and foo/G. (In general, of course, each commit might edit one or more files; but the difference I'm asking about is easiest to illustrate if each commit just creates a separate file. The principle is the same either way, as long as you realize that "edit a file", to git, means "add some lines, delete some lines, change some lines"). Now at a fundamental level, a commit in git is a snapshot of the entire content. So "keep commits B, G, and J could mean you want x -- o -- x -- x <--(master) \ AB -- CDEFG -- HIJ <--(branch) where AB has a tree containing foo/A and foo/B; and CDEFG has a TREE containing foo/A, foo/B, foo/C, foo/D, foo/E, foo/F, and foo/G; etc. A lot of people think of a commit as a set of changes - i.e. the patch that would convert the commit's parent's TREE into the commit's TREE. Even though git as a whole doesn't work that way, rebase does treat commits in much that way. So if you think that way, maybe you want x -- o -- x -- Z <--(master) \ B' -- G' -- J' <--(branch) where B' makes the same changes relative to o as B had made relative to A. That would mean that B' has a TREE with foo/B (but not foo/A); and G' has a TREE with foo/B and foo/G; etc. Either way, an interactive rebase will do the job. It'll create the new, fewer commits that you want, and move branch to refer to them; and you can proceed from there. If you want to keep the branch based at o, you might do something like git rebase -i `git merge-base master branch` branch It would be simpler to say git rebase -i master branch which will still operate on the correct set of commits; the difference is that the latter command will make the first "new" commit's parent Z instead of o. Whichever command you issue will bring up a text editor with a TODO list containing an entry for each commit from A through J. Each entry starts with the command pick by default. We'll change some of those commands. If you want commits like AB, CDEFG, and HIJ, then you'll use the command squash. This says to combine the patch for a commit with the patch for the one before it. So you'd change the commands for B (to combine B with A yielding AB), D, E, F, and G (to get CDEFG), and I and J. On the other hand, if you just want B', G', and J', then you would use the drop command (or just remove the unwanted commits from the TODO list). You would change the lines for A, C, D, E, F, H, and I. As I noted, this is just one of several ways. At its core git is a content storage system that's well suited (specialized even) to storing a project history. It's very flexible in how it lets you modify the content, though it does try to protect against any potentially-accidental loss of content.
{ "pile_set_name": "StackExchange" }
Q: understanding workings of cursor Trying to change some stores procedures and query's for better performance. For some part, it's rewriting cursor syntax. To do this,I must fully understand how they work. I tried this simple ETL example, but it does not give me the expected result. Basically, doing an UPSERT here with a cursor. Example code: CREATE TABLE #Destination (PersonID INT, FirstName VARCHAR(10), LastName VARCHAR (10)) INSERT INTO #Destination VALUES (101, 'M', 'Donalds') INSERT INTO #Destination VALUES (102, NULL, 'Richards') INSERT INTO #Destination VALUES (103, 'Rianna', 'Lock') INSERT INTO #Destination VALUES (104, 'Leo', 'Svensson') CREATE TABLE #SourceTable (PersonID INT, FirstName VARCHAR(10), LastName VARCHAR (10)) INSERT INTO #Destination VALUES (102, 'Diana', 'Richards') INSERT INTO #SourceTable VALUES (103, 'Rianna', 'Locks') INSERT INTO #SourceTable VALUES (106, 'Cleo', 'Davung') DECLARE @PersonID INT DECLARE @Firstname VARCHAR (10) DECLARE @Lastname VARCHAR (10) DECLARE SimpleCursor CURSOR FOR SELECT PersonID, FirstName, LastName FROM #SourceTable Open SimpleCursor FETCH NEXT FROM SimpleCursor INTO @PersonID, @Firstname, @Lastname WHILE @@FETCH_STATUS = 0 BEGIN IF EXISTS ( SELECT PersonID FROM #Destination WHERE PersonID = @PersonID ) UPDATE #Destination SET #Destination.FirstName = #SourceTable.FirstName, #Destination.LastName = #SourceTable.LastName FROM #SourceTable WHERE #Destination.PersonID = #SourceTable.PersonID ELSE INSERT INTO #Destination SELECT PersonID, Firstname, Lastname FROM #SourceTable FETCH NEXT FROM SimpleCursor INTO @PersonID, @Firstname, @Lastname END CLOSE SimpleCursor DEALLOCATE SimpleCursor SELECT * FROM #Destination What am I missing here? I am not updating anything, while PersonID 102 and 103 do exist. Thanks a lot. A: You're not using the variables you fetched the values into in your UPDATE or INSERT statements. Try: ... IF EXISTS (SELECT * FROM #Destination WHERE PersonID = @PersonID) BEGIN UPDATE #Destination SET FirstName = @FirstName, LastName = @LastName WHERE PersonID = @PersonID; END ELSE BEGIN INSERT INTO #Destination (PersonID, FirstName, LastName) VALUES (@PersonID, @FirstName, @LastName); END; ...
{ "pile_set_name": "StackExchange" }
Q: Using git diff, how can I get added and modified lines numbers? Assuming I have a text file alex bob matrix will be removed git repo and I have updated it to be alex new line here another new line bob matrix git Here, I have added lines number (2,3) and updated line number (6) How can I get these line numbers info using git diff or any other git command? A: git diff --stat will show you the output you get when committing stuff which is the one you are referring to I guess. git diff --stat For showing exactly the line numbers that has been changed you can use git blame -p <file> | grep "Not Committed Yet" And the line changed will be the last number before the ending parenthesis in the result. Not a clean solution though :( A: Here's a bash function to calculate the resulting line numbers from a diff: diff-lines() { local path= local line= while read; do esc=$'\033' if [[ $REPLY =~ ---\ (a/)?.* ]]; then continue elif [[ $REPLY =~ \+\+\+\ (b/)?([^[:blank:]$esc]+).* ]]; then path=${BASH_REMATCH[2]} elif [[ $REPLY =~ @@\ -[0-9]+(,[0-9]+)?\ \+([0-9]+)(,[0-9]+)?\ @@.* ]]; then line=${BASH_REMATCH[2]} elif [[ $REPLY =~ ^($esc\[[0-9;]+m)*([\ +-]) ]]; then echo "$path:$line:$REPLY" if [[ ${BASH_REMATCH[2]} != - ]]; then ((line++)) fi fi done } It can produce output such as: $ git diff | diff-lines http-fetch.c:1: #include "cache.h" http-fetch.c:2: #include "walker.h" http-fetch.c:3: http-fetch.c:4:-int cmd_http_fetch(int argc, const char **argv, const char *prefix) http-fetch.c:4:+int main(int argc, const char **argv) http-fetch.c:5: { http-fetch.c:6:+ const char *prefix; http-fetch.c:7: struct walker *walker; http-fetch.c:8: int commits_on_stdin = 0; http-fetch.c:9: int commits; http-fetch.c:19: int get_verbosely = 0; http-fetch.c:20: int get_recover = 0; http-fetch.c:21: http-fetch.c:22:+ prefix = setup_git_directory(); http-fetch.c:23:+ http-fetch.c:24: git_config(git_default_config, NULL); http-fetch.c:25: http-fetch.c:26: while (arg < argc && argv[arg][0] == '-') { fetch.h:1: #include "config.h" fetch.h:2: #include "http.h" fetch.h:3: fetch.h:4:-int cmd_http_fetch(int argc, const char **argv, const char *prefix); fetch.h:4:+int main(int argc, const char **argv); fetch.h:5: fetch.h:6: void start_fetch(const char* uri); fetch.h:7: bool fetch_succeeded(int status_code); from a diff like this: $ git diff diff --git a/builtin-http-fetch.c b/http-fetch.c similarity index 95% rename from builtin-http-fetch.c rename to http-fetch.c index f3e63d7..e8f44ba 100644 --- a/builtin-http-fetch.c +++ b/http-fetch.c @@ -1,8 +1,9 @@ #include "cache.h" #include "walker.h" -int cmd_http_fetch(int argc, const char **argv, const char *prefix) +int main(int argc, const char **argv) { + const char *prefix; struct walker *walker; int commits_on_stdin = 0; int commits; @@ -18,6 +19,8 @@ int cmd_http_fetch(int argc, const char **argv, const char *prefix) int get_verbosely = 0; int get_recover = 0; + prefix = setup_git_directory(); + git_config(git_default_config, NULL); while (arg < argc && argv[arg][0] == '-') { diff --git a/fetch.h b/fetch.h index 5fd3e65..d43e0ca 100644 --- a/fetch.h +++ b/fetch.h @@ -1,7 +1,7 @@ #include "config.h" #include "http.h" -int cmd_http_fetch(int argc, const char **argv, const char *prefix); +int main(int argc, const char **argv); void start_fetch(const char* uri); bool fetch_succeeded(int status_code); If you only want to show added/removed/modified lines, and not the surrounding context, you can pass -U0 to git diff: $ git diff -U0 | diff-lines http-fetch.c:4:-int cmd_http_fetch(int argc, const char **argv, const char *prefix) http-fetch.c:4:+int main(int argc, const char **argv) http-fetch.c:6:+ const char *prefix; http-fetch.c:22:+ prefix = setup_git_directory(); http-fetch.c:23:+ fetch.h:4:-int cmd_http_fetch(int argc, const char **argv, const char *prefix); fetch.h:4:+int main(int argc, const char **argv); It's robust against ANSI color codes, so you can pass --color=always to git diff to get the usual color coding for added/removed lines. The output can be easily grepped: $ git diff -U0 | diff-lines | grep 'main' http-fetch.c:4:+int main(int argc, const char **argv) fetch.h:4:+int main(int argc, const char **argv); In your case git diff -U0 would give: $ git diff -U0 | diff-lines test.txt:2:+new line here test.txt:3:+another new line test.txt:6:-will be removed test.txt:6:-git repo test.txt:6:+git If you just want the line numbers, change the echo "$path:$line:$REPLY" to just echo "$line" and pipe the output through uniq. A: I use the --unified=0 option of git diff. For example, git diff --unified=0 commit1 commit2 outputs the diff: Because of the --unified=0 option, the diff output shows 0 context lines; in other words, it shows exactly the changed lines. Now, you can identify the lines that start with '@@', and parse it based on the pattern: @@ -startline1,count1 +startline2,count2 @@ Back to the above example, for the file WildcardBinding.java, start from line 910, 0 lines are deleted. Start from line 911, 4 lines are added.
{ "pile_set_name": "StackExchange" }
Q: the different between join condition and where condition Somebody tell me what's the difference between two queries: Version A select p.LastName, o.OrderNo from Persons p, Orders o where p.P_Id = o.P_Id ...and... Version B select p.LastName, o.OrderNo from Persons p join Orders o on p.P_Id = o.P_Id A: Both use an INNER JOIN to combine records between the PERSONS and ORDERS tables. Version A is ANSI-89 syntax, and Version B is ANSI-92 syntax. There's no performance difference between them, but the ANSI-92 syntax supports OUTER JOINs (LEFT, RIGHT, and FULL depending on the database) while the ANSI-89 does not.
{ "pile_set_name": "StackExchange" }
Q: Send List to Controller using interface? I have my Product class, which is pretty straight forward, Then I want to use an Interface to send a List of Product objects over the to Controller. I think Im good to go with my Product class and IProduct interface ? my problems: In MYcontext class, I am trying to make the list, but IM not really sure how to proceed. and MyRepository class should send the List to the Controller eventually. My purpose of using the interface is just really for practice.. and I will do some Testing later too. using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Uppgift_1.Models { public class Product { public int ProductId { get; set; } public string ProductName { get; set; } public double PriceBuy { get; set; } public double PriceSell { get; set; } public double Moms { get; set; } public Product() { } public Product(int productId, string productName, double priceBuy, double priceSell, double moms) { ProductId = productId; ProductName = productName; PriceBuy = priceBuy; PriceSell = priceSell; Moms = moms; } // TODO: add calculation method } } using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Uppgift_1.Models { public interface IProduct { IQueryable<Product> Products { get; } } } using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Uppgift_1.Models { public class MYcontext : Product { IQueryable<Product> Products = new List<Product>(); Product p1 = new Product(21, "RollerSkates", 82.5, 164, 1.25); Product p2 = new Product(22, "Fridge", 88, 844, 1.25); Product p3 = new Product(23, "TV", 182.5, 364, 1.25); Product p4 = new Product(24, "Boat", 325, 64, 1.25); Product p5 = new Product(25, "Car", 22.5, 74, 1.25); Product p6 = new Product(26, "Magasine", 84.3, 44, 1.25); Product p7 = new Product(27, "Garage", 182.7, 843, 1.25); Product p8 = new Product(28, "House", 182.8, 542, 1.25); Product p9 = new Product(29, "Beach", 814.9, 62, 1.25); Product p10 = new Product(30, "Ball", 69.3, 16, 1.25); } } using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Uppgift_1.Models { public class MyRepository : IProduct { public IQueryable<Product> Products { get { return MYcontext.pList; } } } } A: You need to add getData logic to your repository like this(check Context Products, im not sure about it) : public class MyRepository : IProduct { public IQueryable<Product> Products { get { return MYcontext.pList; } } public IQueryable<Product> GetProducts() { return (from obj in Products select obj).FirstOrDefault(); } } And your interface namespace Uppgift_1.Models { public interface IProduct { IQueryable<Product> GetProducts(); } } And in Controller you could use it like this: public MyController:Controller { IProduct<Product> service = new MyRepository(); public ActionResult Index() { var prods = service.GetProducts(); return View(prods) ; } }
{ "pile_set_name": "StackExchange" }
Q: Change IVT of 8086 / 88 as you know when interrupt happened ,8086 get code type of interrupt and multiple it in 4,then Check it in IVT. know I wanna change IVT in 8086,I'm using emu8086. What should I do for it? A: You probably already know this: IVT is in address: 0000:0000 As you say, offset of each vector is calculated by multilying interrupt number by 4. If you want to change a value of single vector, then: disable interrupts (cli) Store old value of the vector if needed. write offset and segment of your interrupt handler to the vector. enable interrupts (sti)
{ "pile_set_name": "StackExchange" }
Q: Is it possible to write the same permutation as a collection of disjoint cycles in two different ways? The answer is apparently no. I just don't get it. $(1, 2, 3)(4, 5)$ and $(2, 3, 1)(5, 4)$ are the same permutation. Aren't those $2$ different ways of writing the same permutation? A: You are right that they are the same permutation. This is not a contradiction; you simply wrote the same cycles in two different ways. $(231)=(123)$ and $(54)=(45)$. This is because $231$ is a cyclic permutation of 123 and 45 is a cyclic permutation of 54. You get 231 from 123 by shifting everything to the left by one place (then the 1 ends up at the end). "Rearrangement" here refers to rearranging the order of the cycles themselves, not the elements within the cycles.
{ "pile_set_name": "StackExchange" }
Q: In Chrome Native messaging: how long is the native app instance object lifetime? Does a native application that talks to a Chrome extension is alive for ever? I mean should it be present e.g. before a postback happens? I could not find any configuration for that to add in the manifest file. I have a page, there are some objects on the page. After clicking an object and sending/receving one message with the Native app, then it no longer works for the rest of objects. My exact question: How long is the native app instance object lifetime? Should that object response e.g. forever? Or do I need a loop e.g. to read messages from stdin if this is a continuous communication? Here is my background script: var host_name = "files.mffta.java.nativeapp"; var port = null; initPort(); function initPort() { console.log( 'Connecting to native host: ' + host_name ); port = chrome.runtime.connectNative( host_name ); port.onMessage.addListener( onNativeMessage ); port.onDisconnect.addListener( onDisconnected ); } // Listen for messages that come from the content script. chrome.runtime.onMessage.addListener( function( messageData, sender, sendResponse ) { if( messageData ) { sendNativeMessage(messageData); sendResponse( { res: 'done!' } ); } } ); // Sending a message to the port. function sendNativeMessage(messageData) { if( port == null ) initPort(); console.log( 'Sending message to native app: ' + JSON.stringify( messageData ) ); port.postMessage( messageData ); console.log( 'Sent message to native app.' ); } // Receiving a message back from the Native Client API. function onNativeMessage( message ) { console.log( 'recieved message from native app: ' + JSON.stringify( message ) ); alert( "messaged received from Native: " + JSON.stringify( message ) ); //sending a message to Content Script to call a function if( message.methodName && message.methodName != "" ) { chrome.tabs.query( { active: true, currentWindow: true }, function( tabs ) { chrome.tabs.sendMessage( tabs[0].id, message, function( response ) { // Call native again to return JavaScript callback function results alert ("calc res received by extension : " + response); sendNativeMessage({ type: "JSCallbackRes", callbackRes: response }); } ); } ); } } // Disconnecting the port. function onDisconnected() { console.log( "ERROR: " + JSON.stringify( chrome.runtime.lastError ) ); console.log( 'disconnected from native app.' ); port = null; } My extension manifest: { "name": "Files.ChromeExt.Operarations", "version": "1.0", "manifest_version": 2, "description": "This extension calls a Native API which that API calls some x-Files related operations.", "icons": { "128": "x-files_icon.png" }, "permissions": [ "nativeMessaging", "activeTab" ], "background": { "persistent": true, "scripts": ["main.js"] }, "content_scripts" : [{"matches": ["http://localhost/*","https://localhost/*"], "js": ["contentscripts/page.js"]}] } Java program: [as has been asked in the comments] import java.io.IOException; import javax.swing.JOptionPane; public class Applet { public Applet(){} public static void main(String[] args) { try { readMessage(); sendMessage("{\"msg\" : \"hello\"}"); } catch (Exception ex) { JOptionPane.showMessageDialog(null, ex.getMessage()); } } public static String readMessage() { String msg = ""; try { int c, t = 0; for (int i = 0; i <= 3; i++) { t += Math.pow(256.0f, i) * System.in.read(); } for (int i = 0; i < t; i++) { c = System.in.read(); msg += (char) c; } } catch (Exception e) { JOptionPane.showMessageDialog(null, "error in reading message from JS"); } return msg; } public static void sendMessage(String msgdata) { try { int dataLength = msgdata.length(); System.out.write((byte) (dataLength & 0xFF)); System.out.write((byte) ((dataLength >> 8) & 0xFF)); System.out.write((byte) ((dataLength >> 16) & 0xFF)); System.out.write((byte) ((dataLength >> 24) & 0xFF)); // Writing the message itself System.out.write(msgdata.getBytes()); System.out.flush(); } catch (IOException e) { JOptionPane.showMessageDialog(null, "error in sending message to JS"); } } } By inspecting the chrome log I can see these messages: Native Messaging host tried sending a message that is 1936028240 bytes long. {"message":"Error when communicating with the native messaging host."}", source: chrome-extension://XXX I am testing these on a Win 8.0 machine 64 bit. Update: I am now convinced that the host is alive forever if connectNative is called and the port is not stopped by an error. So, the root cause of the error messages above must be something else than port lifetime. I mean some error in my communication is forcibly stopping the port. I highly appreciate any comments you can give. A: If using chrome.runtime.sendNativeMessage, the native app will be around right after receiving and before sending the message. Since reception of the message is asynchronous, you cannot assume that the app is still alive when the callback of sendNativeMessage is called. If you want to ensure that the native app stays around longer, use chrome.runtime.connectNative. This creates a port, and the native app will be alive until it exits or until the extension calls disconnect() on the port. If your app unexpectedly terminates early, then you have most likely made an error in the implementation of the native messaging protocol. For the exact format of the native messaging protocol, take a look at the documentation: https://developer.chrome.com/extensions/nativeMessaging#native-messaging-host-protocol As for your edit, the error message is quite clear: The length is invalid. The length is supposed to be in the system's native byte order (which could be little endian or big endian). When you get the following arror message with an excessive offset difference, then there are two possibilities: The byte order of the integer is incorrect, or Your output contains some unexpected characters, which causes the bytes to be shifted and resulted in bytes being at the incorrect location. To know which case you're in, view the number as a hexadecimal number. If there are many trailing zeroes, then that shows that the byte order is incorrect. For example, if your message has a length of 59, then the hexadecimal value is 3b. If the endianness is incorrect, then the following message is displayed: Native Messaging host tried sending a message that is 989855744 bytes long. 1493172224 is 3b 00 00 00 in hexadecimal notation, and you can observe that the 3b is there, but at the wrong end (in other words, the byte order is reversed). The solution to this problem for your system is to edit your code to print the bytes in the reverse order. If the hexadecimal view of the number does not look remotely close to your number, then odds are that the message length is incorrect. Recall that stdio is used for communication, so if you output anything else (e.g. errors) to stdout (System.out) instead of stderr (System.err), then the protocol is violated and your app will be terminated. System.err.println(ex.getStackTrace()); // <-- OK System.out.println("[ error -> " + ex.getMessage() + " ]"); // <-- BAD On Windows, also check whether you've set the mode for stdout (and stdin) to O_BINARY. Otherwise Windows will insert an extra byte before 0A (0D 0A), which causes all bytes to shift and the number to be incorrect. The Java Runtime already enables binary mode, so for your case it's not relevant.
{ "pile_set_name": "StackExchange" }
Q: Does one have to know Razor Pages to use scaffolded identity? I'm developing an ASP.NET Core MVC application. I am using Razor Views and MVC as my preferred approach. I am also using individual user accounts. I have run scaffolding to create code connected with Identity management (Login, Register pages, etc.). That scaffolding results with creating Razor Pages, which seems to be a MVVM approach. Is there a way I could scaffold those features using Razor Views, what in turn would support MVC pattern? I feel like I am mixing approaches due to that scaffolding. Now, when I want to add some feature connected with user profile, I have to write MVVM code, and I would like to use one approach instead. A: Yes indeed, Microsoft changed the Identity stuff when creating a new project a while ago, from classic Razor views to new Razor Pages. But luckily, you can grab all this old stuff from Github, for example here.
{ "pile_set_name": "StackExchange" }
Q: НС получаСтся ΡΠΏΠ°Ρ€ΡΠΈΡ‚ΡŒ сайт dns-shop.ru Π₯ΠΎΡ‚Π΅Π» ΠΏΠΎΠΏΡ‹Ρ‚Π°Ρ‚ΡŒΡΡ ΠΏΠΎΠ»ΡƒΡ‡ΠΈΡ‚ΡŒ послСднюю страницу сайта ΠΈ Π½Π°Π·Π²Π°Π½ΠΈΠ΅ Ρ‚ΠΎΠ²Π°Ρ€Π°, Π½ΠΎ ΠΏΠΎΠ»ΡƒΡ‡Π°ΡŽ Π² ΠΎΡ‚Π²Π΅Ρ‚ пустоту. НС ΠΌΠΎΠ³Ρƒ ΠΏΠΎΠ½ΡΡ‚ΡŒ, Ρ‡Ρ‚ΠΎ я Π½Π΅ Ρ‚Π°ΠΊ дСлаю. import requests from bs4 import BeautifulSoup page_num = 1 url = 'https://www.dns-shop.ru/catalog/17a8a01d16404e77/smartfony/?p=%s&i=1&mode=list&brand=brand-apple' % page_num page = requests.get(url).text soup = BeautifulSoup(page , 'html.parser') max_page = soup.find('span' ," item edge mobile end").get_text() print(max_page) for txt in soup.findAll('h3').text: print (txt) A: Администраторы www.dns-shop.ru Ρ€Π΅ΡˆΠΈΠ»ΠΈ Π·Π°Ρ‰ΠΈΡ‚ΠΈΡ‚ΡŒΡΡ ΠΎΡ‚ "парсСров" ΠΈ сдСлали сайт динамичСским. Π’Π°ΠΊΠΈΠΌ ΠΎΠ±Ρ€Π°Π·ΠΎΠΌ requests.get(url).text Π²Π΅Ρ€Π½Ρ‘Ρ‚ Π΅Ρ‰Π΅ Π½Π΅ Π²Ρ‹ΠΏΠΎΠ»Π½Π΅Π½Π½Ρ‹ΠΉ скрипт: <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta http-equiv="refresh" content="10;URL=/ciez2a"> </head> <body> <script type="text/javascript"> var JSEncryptExports={}; (function(w){function e(a,b,c){null!=a&&("number"==typeof a?this.fromNumber(a,b,c):null==b&&"string"!=typeof a?this.fromString(a,256):this.fromString(a,b))}function m(){return new e(null)}function D(a,b,c,d,f,g){for(;0<=--g;){var h=b*this[a++]+c[d]+f;f=Math.floor(h/67108864);c[d++]=h&67108863}return f}function Y(a,b,c,d,f,g){var h=b&32767;for(b>>=15;0<=--g;){var k=this[a]&32767,e=this[a++]>>15,z=b*k+e*h,k=h*k+((z&32767)<<15)+c[d]+(f&1073741823);f=(k>>>30)+(z>>>15)+b*e+(f>>>30);c[d++]=k&1073741823}return f} function Z(a,b,c,d,f,g){var h=b&16383;for(b>>=14;0<=--g;){var k=this[a]&16383,e=this[a++]>>14,z=b*k+e*h,k=h*k+((z&16383)<<14)+c[d]+f;f=(k>>28)+(z>>14)+b*e;c[d++]=k&268435455}return f}function T(a,b){var c=J[a.charCodeAt(b)];return null==c?-1:c}function A(a){var b=m();b.fromInt(a);return b}function K(a){var b=1,c;0!=(c=a>>>16)&&(a=c,b+=16);0!=(c=a>>8)&&(a=c,b+=8);0!=(c=a>>4)&&(a=c,b+=4);0!=(c=a>>2)&&(a=c,b+=2);0!=a>>1&&(b+=1);return b}function E(a){this.m=a}function F(a){this.m=a;this.mp=a.invDigit(); this.mpl=this.mp&32767;this.mph=this.mp>>15;this.um=(1<<a.DB-15)-1;this.mt2=2*a.t}function aa(a,b){return a&b}function L(a,b){return a|b}function U(a,b){return a^b}function V(a,b){return a&~b}function H(){}function W(a){return a}function G(a){this.r2=m();this.q3=m();e.ONE.dlShiftTo(2*a.t,this.r2);this.mu=this.r2.divide(a);this.m=a}function P(){this.j=this.i=0;this.S=[]}function M(){}function n(a,b){return new e(a,b)}function p(){this.n=null;this.e=0;this.coeff=this.dmq1=this.dmp1=this.q=this.p=this.d= null}function Q(a){var b,c,d="";for(b=0;b+3<=a.length;b+=3)c=parseInt(a.substring(b,b+3),16),d+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(c>>6)+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(c&63);b+1==a.length?(c=parseInt(a.substring(b,b+1),16),d+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(c<<2)):b+2==a.length&&(c=parseInt(a.substring(b,b+2),16),d+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(c>> 2)+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt((c&3)<<4));for(;0<(d.length&3);)d+="=";return d}function ba(a){var b="",c,d=0,f;for(c=0;c<a.length&&"="!=a.charAt(c);++c)v="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".indexOf(a.charAt(c)),0>v||(0==d?(b+="0123456789abcdefghijklmnopqrstuvwxyz".charAt(v>>2),f=v&3,d=1):1==d?(b+="0123456789abcdefghijklmnopqrstuvwxyz".charAt(f<<2|v>>4),f=v&15,d=2):2==d?(b+="0123456789abcdefghijklmnopqrstuvwxyz".charAt(f), b+="0123456789abcdefghijklmnopqrstuvwxyz".charAt(v>>2),f=v&3,d=3):(b+="0123456789abcdefghijklmnopqrstuvwxyz".charAt(f<<2|v>>4),b+="0123456789abcdefghijklmnopqrstuvwxyz".charAt(v&15),d=0));1==d&&(b+="0123456789abcdefghijklmnopqrstuvwxyz".charAt(f<<2));return b}var q;"Microsoft Internet Explorer"==navigator.appName?(e.prototype.am=Y,q=30):"Netscape"!=navigator.appName?(e.prototype.am=D,q=26):(e.prototype.am=Z,q=28);e.prototype.DB=q;e.prototype.DM=(1<<q)-1;e.prototype.DV=1<<q;e.prototype.FV=Math.pow(2, 52);e.prototype.F1=52-q;e.prototype.F2=2*q-52;var J=[],r;q=48;for(r=0;9>=r;++r)J[q++]=r;q=97;for(r=10;36>r;++r)J[q++]=r;q=65;for(r=10;36>r;++r)J[q++]=r;E.prototype.convert=function(a){return 0>a.s||0<=a.compareTo(this.m)?a.mod(this.m):a};E.prototype.revert=function(a){return a};E.prototype.reduce=function(a){a.divRemTo(this.m,null,a)};E.prototype.mulTo=function(a,b,c){a.multiplyTo(b,c);this.reduce(c)};E.prototype.sqrTo=function(a,b){a.squareTo(b);this.reduce(b)};F.prototype.convert=function(a){var b= m();a.abs().dlShiftTo(this.m.t,b);b.divRemTo(this.m,null,b);0>a.s&&0<b.compareTo(e.ZERO)&&this.m.subTo(b,b);return b};F.prototype.revert=function(a){var b=m();a.copyTo(b);this.reduce(b);return b};F.prototype.reduce=function(a){for(;a.t<=this.mt2;)a[a.t++]=0;for(var b=0;b<this.m.t;++b){var c=a[b]&32767,d=c*this.mpl+((c*this.mph+(a[b]>>15)*this.mpl&this.um)<<15)&a.DM,c=b+this.m.t;for(a[c]+=this.m.am(0,d,a,b,0,this.m.t);a[c]>=a.DV;)a[c]-=a.DV,a[++c]++}a.clamp();a.drShiftTo(this.m.t,a);0<=a.compareTo(this.m)&& a.subTo(this.m,a)};F.prototype.mulTo=function(a,b,c){a.multiplyTo(b,c);this.reduce(c)};F.prototype.sqrTo=function(a,b){a.squareTo(b);this.reduce(b)};e.prototype.copyTo=function(a){for(var b=this.t-1;0<=b;--b)a[b]=this[b];a.t=this.t;a.s=this.s};e.prototype.fromInt=function(a){this.t=1;this.s=0>a?-1:0;0<a?this[0]=a:-1>a?this[0]=a+DV:this.t=0};e.prototype.fromString=function(a,b){var c;if(16==b)c=4;else if(8==b)c=3;else if(256==b)c=8;else if(2==b)c=1;else if(32==b)c=5;else if(4==b)c=2;else{this.fromRadix(a, b);return}this.s=this.t=0;for(var d=a.length,f=!1,g=0;0<=--d;){var h=8==c?a[d]&255:T(a,d);0>h?"-"==a.charAt(d)&&(f=!0):(f=!1,0==g?this[this.t++]=h:g+c>this.DB?(this[this.t-1]|=(h&(1<<this.DB-g)-1)<<g,this[this.t++]=h>>this.DB-g):this[this.t-1]|=h<<g,g+=c,g>=this.DB&&(g-=this.DB))}8==c&&0!=(a[0]&128)&&(this.s=-1,0<g&&(this[this.t-1]|=(1<<this.DB-g)-1<<g));this.clamp();f&&e.ZERO.subTo(this,this)};e.prototype.clamp=function(){for(var a=this.s&this.DM;0<this.t&&this[this.t-1]==a;)--this.t};e.prototype.dlShiftTo= function(a,b){var c;for(c=this.t-1;0<=c;--c)b[c+a]=this[c];for(c=a-1;0<=c;--c)b[c]=0;b.t=this.t+a;b.s=this.s};e.prototype.drShiftTo=function(a,b){for(var c=a;c<this.t;++c)b[c-a]=this[c];b.t=Math.max(this.t-a,0);b.s=this.s};e.prototype.lShiftTo=function(a,b){var c=a%this.DB,d=this.DB-c,f=(1<<d)-1,g=Math.floor(a/this.DB),h=this.s<<c&this.DM,k;for(k=this.t-1;0<=k;--k)b[k+g+1]=this[k]>>d|h,h=(this[k]&f)<<c;for(k=g-1;0<=k;--k)b[k]=0;b[g]=h;b.t=this.t+g+1;b.s=this.s;b.clamp()};e.prototype.rShiftTo=function(a, b){b.s=this.s;var c=Math.floor(a/this.DB);if(c>=this.t)b.t=0;else{var d=a%this.DB,f=this.DB-d,g=(1<<d)-1;b[0]=this[c]>>d;for(var h=c+1;h<this.t;++h)b[h-c-1]|=(this[h]&g)<<f,b[h-c]=this[h]>>d;0<d&&(b[this.t-c-1]|=(this.s&g)<<f);b.t=this.t-c;b.clamp()}};e.prototype.subTo=function(a,b){for(var c=0,d=0,f=Math.min(a.t,this.t);c<f;)d+=this[c]-a[c],b[c++]=d&this.DM,d>>=this.DB;if(a.t<this.t){for(d-=a.s;c<this.t;)d+=this[c],b[c++]=d&this.DM,d>>=this.DB;d+=this.s}else{for(d+=this.s;c<a.t;)d-=a[c],b[c++]=d& this.DM,d>>=this.DB;d-=a.s}b.s=0>d?-1:0;-1>d?b[c++]=this.DV+d:0<d&&(b[c++]=d);b.t=c;b.clamp()};e.prototype.multiplyTo=function(a,b){var c=this.abs(),d=a.abs(),f=c.t;for(b.t=f+d.t;0<=--f;)b[f]=0;for(f=0;f<d.t;++f)b[f+c.t]=c.am(0,d[f],b,f,0,c.t);b.s=0;b.clamp();this.s!=a.s&&e.ZERO.subTo(b,b)};e.prototype.squareTo=function(a){for(var b=this.abs(),c=a.t=2*b.t;0<=--c;)a[c]=0;for(c=0;c<b.t-1;++c){var d=b.am(c,b[c],a,2*c,0,1);(a[c+b.t]+=b.am(c+1,2*b[c],a,2*c+1,d,b.t-c-1))>=b.DV&&(a[c+b.t]-=b.DV,a[c+b.t+ 1]=1)}0<a.t&&(a[a.t-1]+=b.am(c,b[c],a,2*c,0,1));a.s=0;a.clamp()};e.prototype.divRemTo=function(a,b,c){var d=a.abs();if(!(0>=d.t)){var f=this.abs();if(f.t<d.t)null!=b&&b.fromInt(0),null!=c&&this.copyTo(c);else{null==c&&(c=m());var g=m(),h=this.s;a=a.s;var k=this.DB-K(d[d.t-1]);0<k?(d.lShiftTo(k,g),f.lShiftTo(k,c)):(d.copyTo(g),f.copyTo(c));d=g.t;f=g[d-1];if(0!=f){var x=f*(1<<this.F1)+(1<d?g[d-2]>>this.F2:0),z=this.FV/x,x=(1<<this.F1)/x,l=1<<this.F2,t=c.t,p=t-d,B=null==b?m():b;g.dlShiftTo(p,B);0<=c.compareTo(B)&& (c[c.t++]=1,c.subTo(B,c)); /* ΠΎΠ±Ρ€Π΅Π·Π°Π½ΠΎ ... */ </script> </body> </html> Π§Ρ‚ΠΎΠ±Ρ‹ ΠΎΠ±ΠΎΠΉΡ‚ΠΈ это ΠΌΠΎΠΆΠ½ΠΎ Π²ΠΎΡΠΏΠΎΠ»ΡŒΠ·ΠΎΠ²Π°Ρ‚ΡŒΡΡ ΠΌΠΎΠ΄ΡƒΠ»Π΅ΠΌ Selenium, ΠΊΠΎΡ‚ΠΎΡ€Ρ‹ΠΉ ΠΎΡ‚ΠΊΡ€ΠΎΠ΅Ρ‚ ΠΎΠΊΠ½ΠΎ настоящСго Π±Ρ€Π°ΡƒΠ·Π΅Ρ€Π° для парсинга страницы: from selenium import webdriver from lxml import html page_num = 1 url = 'https://www.dns-shop.ru/catalog/17a8a01d16404e77/smartfony/?p={}&i=1&mode=list&brand=brand-apple'.format(page_num) driver = webdriver.Firefox() driver.get(url) content = driver.page_source tree = html.fromstring(content) print(tree.xpath('//span[@class=" item edge"]')[0].attrib) last_page = tree.xpath('//span[@class=" item edge"]')[0].attrib.get('data-page-number') print(last_page) Ρ€Π΅Π·ΡƒΠ»ΡŒΡ‚Π°Ρ‚: {'class': ' item edge', 'data-role': 'page-handler', 'data-page-number': '6'} 6
{ "pile_set_name": "StackExchange" }
Q: numpy covariance between each column of a matrix and a vector Based on this post, I can get covariance between two vectors using np.cov((x,y), rowvar=0). I have a matrix MxN and a vector Mx1. I want to find the covariance between each column of the matrix and the given vector. I know that I can use for loop to write. I was wondering if I can somehow use np.cov() to get the result directly. A: As Warren Weckesser said, the numpy.cov(X, Y) is a poor fit for the job because it will simply join the arrays in one M by (N+1) array and find the huge (N+1) by (N+1) covariance matrix. But we'll always have the definition of covariance and it's easy to use: A = np.sqrt(np.arange(12).reshape(3, 4)) # some 3 by 4 array b = np.array([[2], [4], [5]]) # some 3 by 1 vector cov = np.dot(b.T - b.mean(), A - A.mean(axis=0)) / (b.shape[0]-1) This returns the covariances of each column of A with b. array([[ 2.21895142, 1.53934466, 1.3379221 , 1.20866607]]) The formula I used is for sample covariance (which is what numpy.cov computes, too), hence the division by (b.shape[0] - 1). If you divide by b.shape[0] you get the unadjusted population covariance. For comparison, the same computation using np.cov: import numpy as np A = np.sqrt(np.arange(12).reshape(3, 4)) b = np.array([[2], [4], [5]]) np.cov(A, b, rowvar=False)[-1, :-1] Same output, but it takes about twice this long (and for large matrices, the difference will be much larger). The slicing at the end is because np.cov computes a 5 by 5 matrix, in which only the first 4 entries of the last row are what you wanted. The rest is covariance of A with itself, or of b with itself. Correlation coefficient The correlation coefficientis obtained by dividing by square roots of variances. Watch out for that -1 adjustment mentioned earlier: numpy.var does not make it by default, to make it happen you need ddof=1 parameter. corr = cov / np.sqrt(np.var(b, ddof=1) * np.var(A, axis=0, ddof=1)) Check that the output is the same as the less efficient version np.corrcoef(A, b, rowvar=False)[-1, :-1]
{ "pile_set_name": "StackExchange" }
Q: ExecuteScript ProcessLog What is the best way to utlize the ProcessorLog within an ExecuteScript processor? I was planning on adding some logging to my groovy ExecuteScript, if an error is encountered in the processing. However, trying to add the log has been unsuccessful. Probably overlooking something obvious. Code Snippet: import org.apache.commons.io.IOUtils import java.nio.charset.* import com.google.gson.JsonObject import com.google.gson.JsonParser import java.time.Instant import java.time.LocalDateTime import java.time.ZoneId import org.apache.nifi.logging.ProcessorLog; def flowFile = session.get() if(!flowFile) return def logger = getLogger(); Error 016-04-07 17:13:51,146 ERROR [Timer-Driven Process Thread-6] o.a.nifi.processors.script.ExecuteScript org.apache.nifi.processor.exception.ProcessException: javax.script.ScriptException: javax.script.ScriptException: groovy.lang.MissingMethodException: No signature of method: org.codehaus.groovy.jsr223.GroovyScriptEngineImpl.getLogger() is applicable for argument types: () values: [] Possible solutions: getContext() at org.apache.nifi.processors.script.ExecuteScript.onTrigger(ExecuteScript.java:205) ~[nifi-scripting-processors-0.5.1.jar:0.5.1] at org.apache.nifi.controller.StandardProcessorNode.onTrigger(StandardProcessorNode.java:1139) [nifi-framework-core-0.5.1.jar:0.5.1] at org.apache.nifi.controller.tasks.ContinuallyRunProcessorTask.call(ContinuallyRunProcessorTask.java:139) [nifi-framework-core-0.5.1.jar:0.5.1] at org.apache.nifi.controller.tasks.ContinuallyRunProcessorTask.call(ContinuallyRunProcessorTask.java:49) [nifi-framework-core-0.5.1.jar:0.5.1] at org.apache.nifi.controller.scheduling.TimerDrivenSchedulingAgent$1.run(TimerDrivenSchedulingAgent.java:124) [nifi-framework-core-0.5.1.jar:0.5.1] at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) [na:1.8.0_05] at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:308) [na:1.8.0_05] at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(ScheduledThreadPoolExecutor.java:180) [na:1.8.0_05] at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:294) [na:1.8.0_05] at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_05] at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_05] at java.lang.Thread.run(Thread.java:745) [na:1.8.0_05] Caused by: javax.script.ScriptException: javax.script.ScriptException: groovy.lang.MissingMethodException: No signature of method: org.codehaus.groovy.jsr223.GroovyScriptEngineImpl.getLogger() is applicable for argument types: () values: [] A: I believe ExecuteScript makes three objects available: session context log So I think you should be able to just do: log.error("my message")
{ "pile_set_name": "StackExchange" }
Q: Difficulty simulating events for unit testing in Jest/Enzyme/ReactTS with third party controls I am using BlueprintJS controls in my React controls, and one of them is a Blueprint Select control. What I need to be able to do is simulate changing the value in the dropdown, just like I would be able to with a standard html select, however because this is a separate 3rd party control, I do not know how to simulate this event. I've pasted the output template for the blueprint control below, but if I try and simulate itemselected or changed, it says cannot simulate these events. Any idea how I can simulate this using Enzyme/Jest? <Blueprint2.Select disabled={false} filterable={false} itemRenderer={[Function]} items={ Array [ "JK", "User1", "User2", ] } onItemSelect={[MockFunction]} > <Blueprint2.QueryList disabled={false} itemRenderer={[Function]} items={ Array [ "JK", "User1", "User2", ] } onActiveItemChange={[Function]} onItemSelect={[Function]} query="" renderer={[Function]} > <Blueprint2.Popover autoFocus={false} className="" defaultIsOpen={false} disabled={false} enforceFocus={false} hasBackdrop={false} hoverCloseDelay={300} hoverOpenDelay={150} inheritDarkTheme={true} interactionKind="click" isOpen={false} minimal={false} modifiers={Object {}} onInteraction={[Function]} openOnTargetFocus={true} popoverClassName="pt-select-popover" popoverDidOpen={[Function]} popoverWillClose={[Function]} popoverWillOpen={[Function]} position="bottom-left" rootElementTag="span" targetElementTag="div" transitionDuration={300} usePortal={true} > <Manager className="pt-popover-wrapper" tag="span" > <span className="pt-popover-wrapper" > <Target className="pt-popover-target" component="div" innerRef={[Function]} onClick={[Function]} > <div className="pt-popover-target" onClick={[Function]} > <div className="" key=".0" onKeyDown={[Function]} > JK </div> </div> </Target> <Blueprint2.Overlay autoFocus={false} backdropClassName="pt-popover-backdrop" backdropProps={Object {}} canEscapeKeyClose={true} canOutsideClickClose={true} didOpen={[Function]} enforceFocus={false} hasBackdrop={false} isOpen={false} lazy={true} onClose={[Function]} transitionDuration={300} transitionName="pt-popover" usePortal={true} /> </span> </Manager> </Blueprint2.Popover> </Blueprint2.QueryList> </Blueprint2.Select> A: For anyone trying to do something similar In the end I used the props on the blueprint Select component to access the onItemSelect() function. Code below const pb = wrapper.find("Select").first(); expect(pb.exists()).toBeTruthy(); const props = pb.props() as any; props.onItemSelect("User2");
{ "pile_set_name": "StackExchange" }
Q: why do I get "index is not defined" error using easy:search I'm just trying to set up a basic search tool in Meteor to find articles in my MongoDB collection, but I'm struggling to get off the ground (if anyone has a good tutorial for an alternative search tool I'm open to suggestions). I've settled on easy:search because it seemed like a simple search tool to get running, however one paragraph into their getting started instructions and I'm already getting an error: ReferenceError: Index is not defined although correct me if I'm wrong, but isn't that what the import { Index, MinimongoEngine } from 'meteor/easy:search' line is for? EDIT: I have tried using the import line on both the client and the server side and I get the same error either way A: this problem was fixed when I included the "import" line in the "lib" folder along with the other code (specified here) to be run on both server and client disclaimer: I uninstalled and reinstalled meteor and may have changed something else along the way which may have been the true solution, but this appears to be the triggering change
{ "pile_set_name": "StackExchange" }
Q: Looking for Simple Python Formula to Combine Two Text Files Beginner Python user here. I'm trying to write a formula that will merge two text files. As in, the first file should have the text of the second simply added to it, not replacing anything in either file. Here's what I have so far: def merge(file1,file2): infile = open(file2,'r') infile.readline() with open('file1','a') as myfile: myfile.write('infile') myfile.close() Any help would be greatly appreciated. A: You seem to have the right idea, a way it could be simplified and easier to read would be the following code I found on google, fit to your method. def merge(file1,file2): fin = open(file2, "r") data2 = fin.read() fin.close() fout = open(file1., "a") fout.write(data2) fout.close()
{ "pile_set_name": "StackExchange" }
Q: How to find all rows with a NULL value in any column using PostgreSQL There are many slightly similar questions, but none solve precisely this problem. "Find All Rows With Null Value(s) in Any Column" is the closest one I could find and offers an answer for SQL Server, but I'm looking for a way to do this in PostgreSQL. How can I select only the rows that have NULL values in any column? I can get all the column names easily enough: select column_name from information_schema.columns where table_name = 'A'; but it's unclear how to check multiple column names for NULL values. Obviously this won't work: select* from A where ( select column_name from information_schema.columns where table_name = 'A'; ) IS NULL; And searching has not turned up anything useful. A: You can use NOT(<table> IS NOT NULL). From the documentation : If the expression is row-valued, then IS NULL is true when the row expression itself is null or when all the row's fields are null, while IS NOT NULL is true when the row expression itself is non-null and all the row's fields are non-null. So : SELECT * FROM t; β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ f1 β”‚ f2 β”‚ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€ β”‚ (null) β”‚ 1 β”‚ β”‚ 2 β”‚ (null) β”‚ β”‚ (null) β”‚ (null) β”‚ β”‚ 3 β”‚ 4 β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”˜ (4 rows) SELECT * FROM t WHERE NOT (t IS NOT NULL); β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ f1 β”‚ f2 β”‚ β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€ β”‚ (null) β”‚ 1 β”‚ β”‚ 2 β”‚ (null) β”‚ β”‚ (null) β”‚ (null) β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”˜ (3 rows)
{ "pile_set_name": "StackExchange" }
Q: Can anyone tell what kind or even which airplane this is? As stated in this post on the Dutch Police website (Google Translate English version) this morning (12th june 2018), they are looking for all available information concerning the image below. All help is appreciated! [Update] Additional information: the picture was presumably made on the 16th of January 2018 at 20:57 local time. They are looking for any information about airplane type, carrier or maybe even flight number. A: It may be an A318 with cabine plan like this one for Avianca: My guesses are: the emergency light line stops around row 6, with the (red?) curtains around row 4. the seats arrangement is approximately 3 rows of business class then economy class. best guess would be 2x3 seats per row, with central screen every three row. cockpit door is slightly not centered to the left So it can fit with this type of plane. Sorry, I can't guess the company. The curtains seems red, but the cabine does not fit with AirFrance (and Hop) neither British Airways. EDIT According to the video posted by @Florian in comments, Avianca is a good guess for the company. Following the comment of @jean, and considering the shadows on the seats, it may be taken during daylight (in flight or on the ground) but for sure not during night.
{ "pile_set_name": "StackExchange" }
Q: Second derivative of an inverse function By the inverse function theorem, we know that $G'(x)=1/F'(G(x))$, where $G=F^{-1}$. I want to obtain $G''(x)$, but I don't know how to get the derivative of $F'(G(x))$. Any hints? A: Just apply the chain rule: $$ \frac{d}{dx} (F'\circ G)(x) = F''(G(x))G'(x), $$ and insert the value for $G'$ that you have obtained before.
{ "pile_set_name": "StackExchange" }
Q: How to show the legend of a trend line? Problem It seems that I'm having difficulty showing the trend line that generated using stat_smooth(). Before I used argument show.legend = T, I have a graph looks like this: After adding the argument, I got something like this: But you see, I want to show the trendline legend separately, like this: How do I achieve this? My source codes are here if you need them (I appreciate it if you can help me truncate the codes to make it more concise): library(ggplot2) library(ggrepel) library(ggthemes) library(scales) library(plotly) library(grid) library(extrafont) # read data econ <- read.csv("https://raw.githubusercontent.com/altaf-ali/ggplot_tutorial/master/data/economist.csv") target_countries <- c("Russia", "Venezuela", "Iraq", "Myanmar", "Sudan", "Afghanistan", "Congo", "Greece", "Argentina", "Brazil", "India", "Italy", "China", "South Africa", "Spane", "Botswana", "Cape Verde", "Bhutan", "Rwanda", "France", "United States", "Germany", "Britain", "Barbados", "Norway", "Japan", "New Zealand", "Singapore") econ$Country <- as.character(econ$Country) labeled_countries <- subset(econ, Country %in% target_countries) vector <- as.numeric(rownames(labeled_countries)) econ$CountryLabel <- econ$Country econ$CountryLabel[1:173] <- '' econ$CountryLabel[c(labeled_countries$X)] <- labeled_countries$Country # Data Visualisation g <- ggplot(data = econ, aes(CPI, HDI)) + geom_smooth(se = FALSE, method = 'lm', colour = 'red', fullrange = T, formula = y ~ log(x), show.legend = T) + geom_point(stroke = 0, color = 'white', size = 3, show.legend = T) g <- g + geom_point(aes(color = Region), size = 3, pch = 1, stroke = 1.2) g <- g + theme_economist_white() g <- g + scale_x_continuous(limits = c(1,10), breaks = 1:10) + scale_y_continuous(limits = c(0.2, 1.0), breaks = seq(0.2, 1.0, 0.1)) + labs(title = 'Corruption and human development', caption='Source: Transparency International; UN Human Development Report') g <- g + xlab('Corruption Perceptions Index, 2011 (10=least corrupt)') + ylab('Human Development Index, 2011 (1=best)') g <- g + theme(plot.title = element_text(family = 'Arial Narrow', size = 14, margin = margin(5, 0, 12, 0)), plot.caption = element_text(family = 'Arial Narrow', hjust = 0, margin=margin(10,0,0,0)), axis.title.x = element_text(family = 'Arial Narrow', face = 'italic', size = 8, margin = margin(10, 0, 10, 0)), axis.title.y = element_text(family = 'Arial Narrow', face = 'italic', size = 8, margin = margin(0, 10, 0, 10)), plot.background = element_rect(fill = 'white'), legend.title = element_blank() ) + theme(legend.background = element_blank(), legend.key = element_blank(), legend.text = element_text(family = 'Arial Narrow', size = 10)) + guides(colour = guide_legend(nrow = 1)) g <- g + geom_text_repel(data = econ, aes(CPI, HDI, label = CountryLabel), family = 'Arial Narrow', colour = 'grey10', force = 8, point.padding = 0.5, box.padding = 0.3, segment.colour = 'grey10' ) g grid.rect(x = 1, y = 0.996, hjust = 1, vjust = 0, gp = gpar(fill = '#e5001c', lwd = 0)) grid.rect(x = 0.025, y = 0.91, hjust = 1, vjust = 0, gp = gpar(fill = '#e5001c', lwd = 0)) Bonus Request As a man of high aesthetic standard, I would like to know: How to make country-label segments not straight? Refer to the third image, notice the segment line for 'China' is not straight. How do I arrange my country labels so that they don't overlap on scatter points and the trendline? (I consulted this Stack Overflow post, and as you can see from my codes, I created empty strings for countries I don't need. However, the overlapping persists) How to convert the whole plot into an interactive plot that can be embedded on a website? EDIT: Thanks @aosmith for helpful suggestions. I followed this post and tried to override.aes my trend line. This is what I added to the #Data Visualisation session: g <- ggplot(data=econ, aes(CPI,HDI))+ geom_smooth(se = FALSE, method = 'lm', aes(group = 1, colour = "Trendline"),fullrange=T, linetype=1,formula=y~log(x))+ scale_colour_manual(values = c("purple", "green", "blue", "yellow", "magenta","orange", "red"), guides (colour = guide_legend (override.aes = list(linetype = 1))) )+ geom_point(...) ... Thankfully it shows the trendline legend. But still not ideal: How do I improve the codes? A: The problem is in the guides statement. Here is the data visualization part of your code, somewhat fixed up: # Data Visualisation g <- ggplot(data = econ, aes(CPI, HDI)) + geom_smooth(se = FALSE, method = 'lm', aes(group = 1, colour = "Trendline"), fullrange=T, linetype=1, formula=y~log(x)) + geom_point(stroke = 0, color = 'white', size = 3, show.legend = T) + scale_colour_manual(values = c("purple", "green", "blue", "yellow", "magenta", "orange", "red")) g <- g + geom_point(aes(color = Region), size = 3, pch = 1, stroke = 1.2) g <- g + theme_economist_white() g <- g + scale_x_continuous(limits = c(1,10), breaks = 1:10) + scale_y_continuous(limits = c(0.2, 1.0), breaks = seq(0.2, 1.0, 0.1)) + labs(title = 'Corruption and human development', caption='Source: Transparency International; UN Human Development Report') g <- g + xlab('Corruption Perceptions Index, 2011 (10=least corrupt)') + ylab('Human Development Index, 2011 (1=best)') g <- g + theme(plot.title = element_text(family = 'Arial Narrow', size = 14, margin = margin(5, 0, 12, 0)), plot.caption = element_text(family = 'Arial Narrow', hjust = 0, margin=margin(10,0,0,0)), axis.title.x = element_text(family = 'Arial Narrow', face = 'italic', size = 8, margin = margin(10, 0, 10, 0)), axis.title.y = element_text(family = 'Arial Narrow', face = 'italic', size = 8, margin = margin(0, 10, 0, 10)), plot.background = element_rect(fill = 'white'), legend.title = element_blank() ) + theme(legend.background = element_blank(), legend.key = element_blank(), legend.text = element_text(family = 'Arial Narrow', size = 10)) g <- g + geom_text_repel(data = econ, aes(CPI, HDI, label = CountryLabel), family = 'Arial Narrow', colour = 'grey10', force = 8, point.padding = 0.5, box.padding = 0.3, segment.colour = 'grey10' ) g + guides(colour = guide_legend(nrow = 1, override.aes = list(linetype = c(rep("blank", 6), "solid"), shape = c(rep(1, 6), NA) ) ) )
{ "pile_set_name": "StackExchange" }
Q: How to create a grouped TableView without using a TableViewController I have a UITableView and I would like it to have 2 sections. I now know that you can only have grouped sections if you're using a UITableViewController and if you're using static cells, neither of which I am. Is that I want to do possible? If so where can I turn for help on setting this up. It seems like every tutorial I have found is for the example of using a UITableViewController. A: Setting the tableView's style property to .Grouped and return 2 from numberOfSections...-method should yield a good result. Where does this standard approach fail?
{ "pile_set_name": "StackExchange" }
Q: Did God change from a wrathful God to a loving God between Old Testament and New Testament? This question is mainly to the evangelical Christians and Bible believing Christians, who believe that God doesn't change and His nature is Love. The Old Testament is filled with accounts that describe how God poured out His wrath on people, including His chosen people, the Israelites. However, when we read the New Testament particularly the life, teachings and message of the Lord Jesus Christ we don't see the outpouring of God's wrath on people. Instead, we read about God's grace, mercy, and love. How do we square these two seemingly opposite manifestations of God's nature? A: There was a gap of about 400 years between the two Testaments, with the OT covering a vast time span, from creation till then. Taking the time from after the Flood, that alone has been variously calculated as 2,454 years to 2,518 years. This means that the OT deals with about two and a half thousand years of history after the Flood, whereas the NT only covers less than seventy-five years of history! The NT does not detail the horrific destruction of Jerusalem and its temple in A.D. 70 as all but its last book was completed before then. (The last book named Revelation may have used coded language to infer that event but it deals a lot with future events where the wrath of God will be poured out on the nations.) It is unbalanced to compare the historical dealings of God with his people and the nations over thousands of years, with a mere 75 years history in the NT. This is especially so when the NT does not hold back from warnings about the coming wrath of God, both on individuals who continue in rebellion against him, and the various β€œbowls of wrath” coming on the whole world before Christ returns in judgment. The idea that God must have changed in nature between the two testaments may indicate some ignorance of what those two testaments state, on the matter of God’s nature and his dealings with mankind. In both testaments, the immense patience and love of God is demonstrated, yet without holding back from clear evidence of God’s holiness, righteousness and sovereign judgements. There may be a bit of β€˜cherry-picking’ going on, selecting gruesome events in the OT (which tells things the way they were) while only citing nice sentiments expressed in the NT. Finally, you addressed your question to evangelical, Bible believing Christians, β€œwho believe that God doesn't change and His nature is Love.” As one such Christian I would point out that the Bible does not limit God’s nature to love, but that his love is perfectly balanced with his holiness, his righteousness and his justice. It’s imbalanced to focus only on God’s love, as if a loving God would sweep sin under the carpet without judging sin and sinners. In his love, God has done everything we could never do to spare repentant sinners the punishment due their sin, by pouring it out on the sinless Son of God instead. But if people disregard what God has lovingly done, they will have to bear that punishment. Then they will know the righteous wrath of God. That was the pattern in the OT because forgiveness and time to repent was always available to those seeking to please God, and that continues in the NT. No change there, God be praised! A: If you read the whole Bible from Genesis to Revelation, you'll notice: God's consistent character, who is compassionate and merciful to those who love and fear Him but who pours out His wrath to those who are rebellious, unthankful, unfaithful, and disobey His commandments. In the OT He revealed his character to Abraham, Moses, David, the prophets, etc; in the NT He revealed his SAME character to Jesus, Paul, the Apostles, etc. His commandments (both in OT and NT) were meant to protect us from harm and to enable us to flourish. In the OT He revealed the famous 10 commandments; in the NT Jesus recapitulates them into the great 2 commandments. God kept renewing His covenant starting with His chosen people Israel and later with the whole world (the Gentiles), exemplifying his faithfulness toward all his creation, and ask us to also be faithful to the covenant. In the OT it was the Mosaic covenant; in the NT it was the covenant with Jesus. In both the OT and the NT the covenant has the same structure: God blesses those who are faithful and obey, and God punishes, judges, and curses those who do not (see Deuteronomy for OT and Revelation for NT). God is especially angry at those who are not only proud (meaning pursuing their own standard instead of God's standard) but also persecute the weak (the poor, the widows, and the orphans). In the OT the Kings and the Jerusalem elite were some of the ones that God was angry with; in the NT it was the Jerusalem leaders and the Pharisees. But to those who were faithful but oppressed and cried out to God, in both the OT and the NT God promised vindication, deliverance, and reward, which we can read in many places such as the Psalms (OT) and in Revelation (NT). I hope from the above you see how God's nature doesn't change between OT and NT: loving to the righteous but wrathful to the wicked. Jesus came to save the sinners who WANT to be righteous (because it is impossible to be righteous without God's help). But on the Day of Judgment when Jesus come again, He comes as a judge who will cast the wicked to hell. In between the 2 comings, the door is still open for us to take the offer of salvation. A: Wrath is an important part of God's nature. I think a good way into answering this question is to ask the question, 'What did Jesus save us from?' They tell how you turned to God from idols to serve the living and true God, and to wait for his Son from heaven, whom he raised from the dead – Jesus, who rescues us from the coming wrath. (1 Thessalonians 1:9-10) There are many passages in the NT which talk about God's wrath. The Father loves the Son and has placed everything in his hands. Whoever believes in the Son has eternal life, but whoever rejects the Son will not see life, for God’s wrath remains on them. (John 3:35-36) For of this you can be sure: no immoral, impure or greedy person – such a person is an idolater – has any inheritance in the kingdom of Christ and of God. Let no one deceive you with empty words, for because of such things God’s wrath comes on those who are disobedient. (Ephesians 5:5-6) And one more, this wonderful description of Jesus coming again: I saw heaven standing open and there before me was a white horse, whose rider is called Faithful and True. With justice he judges and wages war. ... Coming out of his mouth is a sharp sword with which to strike down the nations. β€˜He will rule them with an iron sceptre.’ He treads the winepress of the fury of the wrath of God Almighty. (Revelation 19:11-16) In other words, God's nature has not changed between the Old Testament and the New Testament. Sin still provokes God's wrath and one day it will be punished. Jesus came to save us from sin, to save us from God's wrath. As he said: "God did not send his Son into the world to condemn the world, but to save the world through him. Whoever believes in him is not condemned, but whoever does not believe stands condemned already because they have not believed in the name of God’s one and only Son." (John 3:17-18) There are many other ways in which God's consistency and character are displayed through the Old and New Testaments and I think the other answers do a good job picking up some of those too. I'd just like to mention - as suggested in a comment - one thing extra, which is that the OT does display God as loving and merciful. This aspect of his character also has not changed. For example, God's self-description in Exodus 34, one of the most famous descriptions of him: Then the Lord came down in the cloud and stood there with him and proclaimed his name, the Lord. And he passed in front of Moses, proclaiming, β€˜The Lord, the Lord, the compassionate and gracious God, slow to anger, abounding in love and faithfulness, maintaining love to thousands, and forgiving wickedness, rebellion and sin. Yet he does not leave the guilty unpunished; he punishes the children and their children for the sin of the parents to the third and fourth generation.’ (Exodus 34:5-7) So here in the OT we have a description of God as loving and compassionate, slow to anger, yet not leaving sin unpunished. This is the same God of the New Testament: the God who is so loving that he refuses to let us to our sins, and yet the God who also is so just that he cannot leave sin unpunished - so Christ is punished in our place. His character does not change.
{ "pile_set_name": "StackExchange" }
Q: Setting tabBarController.selectedIndex/selectedViewController when it's a UINavigationController I've got 5 views in my tabBarController and all of them are embedded in a separate navigationcontroller, i.e. every view has it's own navigationcontroller. I did this to make it easier to push segues, I know it's probably not the best solution but it works fine. Now to my question: I'm trying to set the initial view with the following code: - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { tabBarController.selectedIndex = 2; return YES; } However it's not working at all, the app simply starts and index 0 (the left most view). I've searched through thorough threads like this and tried many different ways to solve this without any success... Closest I got was when I in MainStoryboard_iPhone.storyboard checked the box "Is initial view controller" in the viewcontroller I want to start with. This way the I got the correct starting viewcontroller but the tabbar wasn't showing. A: Since you're using storyboard, do this : 1) Give your tabBarController a storyboard identifier (say tbc); 2) In your appDelegate DidFinishLaunching, do this :: UITabBarController *tbc = [[UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil] instantiateViewControllerWithIdentifier:@"tbc"]; [tbc setSelectedIndex:1]; [self.window setRootViewController:tbc]; [self.window makeKeyAndVisible]; return YES; PS : This is just one of many ways to make it work
{ "pile_set_name": "StackExchange" }
Q: To implement registration page with Vaadin or not? This is a tactical implementation question about usage of Vaadin or in some part of my application. Vaadin is a great framework to login users and implement sophisticated web applications with many pages. However, I think it is not very well suited to desgin pages to register new users for my application. Am I right? Am I am wrong? It seems to me that a simple HTML/CSS/Javascript login + email registration + confirmation email with confirmation link cannot be implemented easily with Vaadin. It seems like Vaadin would be overkill. Do you agree? Or am I missing something? I am looking for feedback from experienced Vaadin users. A: Login/registration can be implemented with Vaadin, but there are good arguments to implement login page as a JSP too. It is often question on if you have a traditional web site too and how you want to integrate to that. A: I had to make the same decision and went for a simple HTML login using plain servlets and templates. The rationale was: 1) We're using OpenID and I experienced some difficulty catching redirects from providers in a Vaadin app. 2) By managing security at the servlet level there is a reduced surface area for attack. You can just override getNewApplication in AbstractApplicationServlet to control access to the app. This approach is recommended in this article: Creating Secure Vaadin Applications using JEE6
{ "pile_set_name": "StackExchange" }
Q: edit contact information in iphone I am developing an app in which I have to allow user to edit the contact programatically. I googled about it I found that ABPersonViewController will be used. I am not able to find it how to implament it. Address Book Programming Guide for iPhone OS also didnt work for me. Can you suggest me the way to do it. Thnx in advance A: Ok at last i have to find the solution myself here is it -(IBAction)showPicker:(id) sender{ ABAddressBookRef addressBook = ABAddressBookCreate(); CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeople(addressBook); ABRecordRef person = CFArrayGetValueAtIndex(allPeople,0); ABPersonViewController *personController = [[ABPersonViewController alloc] init]; personController.displayedPerson = person; personController.addressBook = addressBook; personController.allowsEditing = YES; personController.personViewDelegate = self; UINavigationController *contactNavController = [[UINavigationController alloc] initWithRootViewController:personController]; [personController release]; CFRelease(allPeople); CFRelease(person); [self presentModalViewController:contactNavController animated:YES]; } -(void)personViewControllerDidCancel:(ABPersonViewController *)peoplePicker { [self dismissModalViewControllerAnimated:YES]; } -(BOOL)personViewController:(ABPersonViewController *)peoplePicker shouldPerformDefaultActionForPerson:(ABRecordRef)person property:(ABPropertyID) property identifier:(ABMultiValueIdentifier) identifier { return YES; }
{ "pile_set_name": "StackExchange" }
Q: Regular expressions to segregate between good words and bad ones I have a blacklist of bad words that are blocked if they are used on any web search engine. Examples of those words are: anal, ass, bum bra, butt, cum, dick, lust, tit. Normal words that contain any of these previous words as part of their structures are accordingly blocked. Examples of those good words are: analog, canal, analysis, asset, compass, album, brand, button, circumstance, dickson, illustrate, repetition. My question: is there a regular expression (or bash shell script) that enables me to use the normal words without being blocked because of their blacklisted parts? Appreciating your interest to help. Thank you. A: You can use \b, which means "word boundary": \bbutt\b would match butt but not button.
{ "pile_set_name": "StackExchange" }
Q: Can i use nested queries for database entities in LINQ? I'm working on an ASP.Net application which uses a SQL-Server DB and database entities. Further i got three database entities which are dependend on each other. This is the dependency hierarchy: Instance (Key: InstanceID) CustomField (Key: CustomFieldID, InstanceID) CustomFieldData (Keys: CustomFieldDataID, CustomFieldID) CustomFieldData_Person (Keys: CustomFieldData_PersonID, CustomFieldDataID) I can find out the entries from the entity CustomField by this with the InstanceID: var customFieldEntries = DB_Instance_Singleton.getInstance.CustomField.Where(x => x.InstanceID == instanceId); Now i want to find out all entries from CustomFieldData_Person which belong to the hierarchy with the InstanceID as key. In SQL i would write something like this: SELECT * FROM CustomFieldData_Person WHERE CustomFieldDataID in ( SELECT * FROM CustomFieldData WHERE CustomFieldID in ( SELECT * FROM CustomField WHERE InstanceID = instanceId)) Unfortunately i'm absolutely new to LINQ. So my question is, how can i write such a nested query in LINQ (aacording to the first code example above)? Thanks in advance! A: Firstly if you create your ER model correctly you will have most of that logic already set up for you Person would have a property Person.CustomData which would have Properties for Field and Value so you can just navigate the object structure however if you dont have that then you can just convert the in statements to Contains CustomFieldData_Person.Where(cfdp=>CustomFieldData.Where(nested query for CustomFieldData).Contains(cfdp.CustomFieldDataID )
{ "pile_set_name": "StackExchange" }
Q: Adding 3rd condition to ngClass is not working I am trying to add a 3rd condition to my ngClass. At first, I got the following two class to work in my ngClass to alternate the color of the rows [ngClass]="{ totalrow:i%2 != 0, odd:i%2 == 0}" I am trying to add a 3rd class and condition where the mat-list will show a border line for the top of the mat-list-item. However when I add the 3rd condition, it gives me an error [ngClass]="{ totalrow:i%2 != 0, odd:i%2 == 0, borderTopClass : operator === 'fas fa-equals'}" I get the following error which is confusing to me Parser Error: Missing expected : at column 47 in [{ totalrow:i%2 != 0, odd:i%2 == 0, borderTopClass : operator === 'fas fa-equals'}] in Here is the code with the ngFor <div class="ng-container" *ngFor="let operator of operatorList; let i = index"> <mat-list-item fxLayoutAlign="start" style="padding-left: 0px; padding-right: 0px;" [ngClass]="{ totalrow:i%2 != 0, odd:i%2 == 0, borderTopClass : operator === 'fas fa-equals'}"> <i class="{{operator}}"></i> </mat-list-item> </div> Any help is appreciated. A: I guess a commenter needs a deeper explanation of how this works. <div [ngClass]="{ 'is-active': condition, 'is-inactive': !condition, 'multiple': condition && anotherCondition, }"> multiple class will apply when two conditions are both met. Not just one but both. You could add a third like this: 'multiple': condition && anotherCondition && thirdCondition Here's a StackBlitz of the OP's code working as he expected and without error. If I can help more pleas let me know.
{ "pile_set_name": "StackExchange" }
Q: Why do my components appear next to each other? I'm currently trying to create a program that moves a rectangle over a background Image with keyboard keys. The problem I'm facing is that when I draw the components they are simply placed next to each other, instead of the square overlaying the background image. Here's the code to display both the components; JLayeredPane panel = new JLayeredPane(); panel.setLayout(new FlowLayout()); add(panel); paintBackground pb = new paintBackground(bimg); panel.add(pb, 1, 0); paintPlayer cc = new paintPlayer(startX, startY); panel.add(cc, 2, 0); pack(); setVisible(true); I believe the problem is that the paintPlayer component is set to full size, and there seems to be a background. The paintPlayer component code looks like this: public Dimension getMinimumSize() { return new Dimension(800,600); } @Override public Dimension getPreferredSize() { return new Dimension(800,600); } @Override public Dimension getMaximumSize() { return new Dimension(800,600); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(Color.red); System.out.println(startX + startY ); g.fillRect(startX, startY, 30, 30); } I've had a go at setting the component size to just the size of the rectangle, but that way I can't move the rectangle by using the first two values in fillRect. The background for the rest of the space filled by the component (800x600) seems to be opaque. When added, the components just display next to each other, like this: https://gyazo.com/57245c518e02778c36ffc89ba75d5a81. How do I go about adding the paintPlayer ontop of the paintBackground, so that it only covers the rectangle on the background Image. I've done a fair bit of searching but I can't seem to work it out. Perhaps something to do with the layout? One other thing I've noticed is that by doing this, neither the frame or the pane benefit from a setBackground, as it's not visible. Cheers for any help. A: This is the default Constructor of JLayerdPane. public JLayeredPane() { setLayout(null); } You see it uses normaly AbsolutLayout. And if you read here: Note: that these layers are simply a logical construct and LayoutManagers will affect all child components of this container without regard for layer settings. You should understand what is wrong. Check OverlapLayout.
{ "pile_set_name": "StackExchange" }
Q: How to run an action when clicking on an appindicator I'm looking at writing a simple app indicator and I need it to update it's information whenever it's clicked on to open the menu. Is there any kind of on_click action thing? Let me rephrase it then: How to perform an action (any action) when the user clicks on the appindicator to open its menu? A: An app indicator can only open its menu. It can't perform any other action and your program doesn't get notified when the menu is displayed. You could either include some kind of "Update" menu item or find other events that trigger the update.
{ "pile_set_name": "StackExchange" }
Q: KeyError generated when editing site setting with foreign key set Django Version: 2.1.5 Python Version: 3.6.8 Wagtail Version: 2.4 I have a template with four columns of links in the footer. I have set up the following models which consist of a BaseSetting object and footer link objects for each column of links. The footer link objects each ForeignKey to the TemplateItems object. @register_setting class TemplateItems(BaseSetting): page_banner = models.OneToOneField('wagtailimages.Image', null=True, blank=True, on_delete=models.SET_NULL, related_name='+', help_text='Banner image that shows below menu on pages other than home page') footer_link_col1_header = models.CharField(max_length=25, default='', verbose_name='Footer Link Column 1 Header') footer_link_col2_header = models.CharField(max_length=25, blank=True, default='', verbose_name='Footer Link Column 2 Header') footer_link_col3_header = models.CharField(max_length=25, blank=True, default='', verbose_name='Footer Link Column 3 Header') footer_link_col4_header = models.CharField(max_length=25, blank=True, default='', verbose_name='Footer Link Column 4 Header') panels = [ ImageChooserPanel('page_banner'), MultiFieldPanel([ FieldPanel('footer_link_col1_header'), InlinePanel('footer_links_col_1', label='Column 1 Links'), FieldPanel('footer_link_col2_header'), InlinePanel('footer_links_col_2', label='Column 2 Links'), FieldPanel('footer_link_col3_header'), InlinePanel('footer_links_col_3', label='Column 3 Links'), FieldPanel('footer_link_col4_header'), InlinePanel('footer_links_col_4', label='Column 4 Links'), ], heading='Footer Links'), InlinePanel('social_media_links', label="Social Media Links"), ] class FooterLink(Orderable): name = models.CharField(max_length=60, default='') url = models.CharField(max_length=200, default='') panels = [ FieldRowPanel([ FieldPanel('name'), FieldPanel('url'), ]) ] class Meta: abstract = True def __str__(self): return f'{self.name}' class FooterLinkCol1(FooterLink): template_items = ForeignKey('TemplateItems', related_name='footer_links_col_1', null=True, on_delete=models.SET_NULL) class FooterLinkCol2(FooterLink): template_items = ForeignKey('TemplateItems', related_name='footer_links_col_2', null=True, on_delete=models.SET_NULL) class FooterLinkCol3(FooterLink): template_items = ForeignKey('TemplateItems', related_name='footer_links_col_3', null=True, on_delete=models.SET_NULL) class FooterLinkCol4(FooterLink): template_items = ForeignKey('TemplateItems', related_name='footer_links_col_4', null=True, on_delete=models.SET_NULL) Migrations are created and migrated successfully, but when I go to the TemplateItems settings object in the Wagtail admin in order to add footer links, I receive the following error: KeyError at /admin/settings/main/templateitems/2/ 'footer_links_col_1' If I comment out any of the footer_links_col_X items, then I receive the error for the first one that is not commented out. There are no existing footer links in the database for any of the columns. I wondered if the problem was coming because the ForeignKey is to a BaseSetting object, but when I declare these models in the Django admin (including the inlines for each of the column links), it displays and allows me to add links just fine. Traceback: File "/opt/virtualenvs/MY_SITE-a0hNfZxl/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/opt/virtualenvs/MY_SITE-a0hNfZxl/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 126. response = self.process_exception_by_middleware(e, request) File "/opt/virtualenvs/MY_SITE-a0hNfZxl/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 124. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/opt/virtualenvs/MY_SITE-a0hNfZxl/lib/python3.6/site-packages/django/views/decorators/cache.py" in _wrapped_view_func 44. response = view_func(request, *args, **kwargs) File "/opt/virtualenvs/MY_SITE-a0hNfZxl/lib/python3.6/site-packages/wagtail/admin/urls/init.py" in wrapper 102. return view_func(request, *args, **kwargs) File "/opt/virtualenvs/MY_SITE-a0hNfZxl/lib/python3.6/site-packages/wagtail/admin/decorators.py" in decorated_view 34. return view_func(request, *args, **kwargs) File "/opt/virtualenvs/MY_SITE-a0hNfZxl/lib/python3.6/site-packages/wagtail/contrib/settings/views.py" in edit 83. instance=instance, form=form, request=request) File "/opt/virtualenvs/MY_SITE-a0hNfZxl/lib/python3.6/site-packages/wagtail/admin/edit_handlers.py" in bind_to_instance 153. new.on_instance_bound() File "/opt/virtualenvs/MY_SITE-a0hNfZxl/lib/python3.6/site-packages/wagtail/admin/edit_handlers.py" in on_instance_bound 295. request=self.request)) File "/opt/virtualenvs/MY_SITE-a0hNfZxl/lib/python3.6/site-packages/wagtail/admin/edit_handlers.py" in bind_to_instance 153. new.on_instance_bound() File "/opt/virtualenvs/MY_SITE-a0hNfZxl/lib/python3.6/site-packages/wagtail/admin/edit_handlers.py" in on_instance_bound 295. request=self.request)) File "/opt/virtualenvs/MY_SITE-a0hNfZxl/lib/python3.6/site-packages/wagtail/admin/edit_handlers.py" in bind_to_instance 153. new.on_instance_bound() File "/opt/virtualenvs/MY_SITE-a0hNfZxl/lib/python3.6/site-packages/wagtail/admin/edit_handlers.py" in on_instance_bound 692. self.formset = self.form.formsets[self.relation_name] Exception Type: KeyError at /admin/settings/main/templateitems/2/ Exception Value: 'footer_links_col_1' A: InlinePanel requires the corresponding foreign key to be a ParentalKey: from modelcluster.fields import ParentalKey class FooterLinkCol1(FooterLink): template_items = ParentalKey('TemplateItems', related_name='footer_links_col_1', null=True, on_delete=models.SET_NULL) In turn, ParentalKey requires the parent model to inherit from ClusterableModel (which is automatically true for Wagtail Page models): from modelcluster.models import ClusterableModel class TemplateItems(BaseSetting, ClusterableModel): (There's some explanation of the motivation for ClusterableModel / ParentalKey in the readme for django-modelcluster.)
{ "pile_set_name": "StackExchange" }
Q: How to navigate divs in a custom built single page app? I'm not sure how JS frameworks work as far as single page app functionality. I've got a pseudo single page app, with no framework. I have 3 tabs that will toggle visibility for 3 different hidden div's on the same page. So far I've been able to hide two and display one on click to allow the page to "navigate" without changing pages. I'm running into some complications, however, because I'd like to run some ajax calls to keep the data on my div's updated when visible. I'd also like to be able to pass which page I want visible in the URL for links, etc. Basically I'm wondering what the best way is to identify what "screen" is visible, so I know what ajax calls to make, but I'd prefer if I didn't have to check the css on the element for visibility for these types of things. Can this be done with anchor href's in the url? I could use URL variables, but again I don't want to reload the page, and I could probably make a JS variable to look at and change as I click my tabs, but I wouldn't really be able to pass this in the url. Here is some code. The app is for a dice game, to add some context. The three tabs are simple empty divs with background images that sit on the left hand side of my screen for nav. $('#chatTab').click(animateChat); $('#timelineTab').click(animateTimeline); $('#rollTab').click(animateTheTable); //opens and closes chat box function animateChat () { $('#stats').fadeOut('slow', function(){$('#chat').delay(800).fadeIn('slow');}); $('#theTable').fadeOut('slow', function(){$('#chat').delay(800).fadeIn('slow');}); } //opens and closes timeline box function animateTimeline () { $('#chat').fadeOut('slow', function(){$('#stats').delay(800).fadeIn('slow');}); $('#theTable').fadeOut('slow', function(){$('#stats').delay(800).fadeIn('slow');}); } //opens and closes the roll table function animateTheTable(){ $('#stats').fadeOut('slow', function(){$('#theTable').delay(800).fadeIn('slow');}); $('#chat').fadeOut('slow', function(){$('#theTable').delay(800).fadeIn('slow');}); } A: This is a very open ended question so the answer depends on how far you want the app to go. If your page will only ever have a few UI elements and only one layer of navigation, you are probably better off doing it with straight Jquery and avoiding extra complication. Jquery can handle URL tracking by getting window.location on page load and performing your animations above. Read about handling URLs with JavaScript here: https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history But keep in mind that this only works in modern browsers. Old versions will not handle dynamic URL changes well. To save having to set up all the logic to check the URL you could use a location framework like history.js or Jquery Address. If you intend the game to become very complex with multiple screens and some kind of database, go with Angular Back or another JS framework. This will handle all your routing and animations, including URL tracking plus heaps of other features you may or may not need down the track. The learning curve is steep but once you are there you can make ANYTHING. Be careful though, it's easy to jump in headfirst and use the whizz-bang frameworks and ending up spending weeks doing something you could have barreled out in a few days with straight JS, CSS and HTML. Complexity kills completion.
{ "pile_set_name": "StackExchange" }